Skip to content

Instantly share code, notes, and snippets.

View pages_slash_404.js
import React from 'react';
import Html from '../components/html'; // wraps pages into <html> and some common layout
// you might want a webpack.config.js at least for styles
// typically we use a sass loader, and also @emotion/react in our components
// Html will take care to add <link> for built ./build/**/*.css
// and <script> for built ./build/**/*.js if any, you might even inline it <script>{content}</script> if short
// It's also possible to build css/js assets per page, we didn't do that
export async function getServerSideProps({ req }) {
caub / webpack.config.js
Last active Jun 6, 2021
react-scripts lite
View webpack.config.js
const fs = require('fs-extra');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
fs.emptyDirSync(__dirname + '/build');
fs.copySync(__dirname + '/public/', __dirname + '/build/', {
dereference: true,
View fetchJson.js
const API_URL = 'https://..';
// returns true for plain object literals, like {foo: 'bar'}, false for other cases, like instances of classes, like lodash.isPlainObject
const isPlainObject = obj => obj && Object.getPrototypeOf(obj) === Object.prototype || Object.getPrototypeOf(obj) === null;
export function fetchJson(url, { body, headers, ...o } = {}) {
const isJson = isPlainObject(body); // most of the time we send plain 'json' objects
return fetch(url[0] === '/' ? API_URL + url : url, {
headers: {
...isJson && {'Content-Type': 'application/json'},

Mongo script gotchas

  • no console.log, use print instead
  • no Object.entries, Object.values use Object.keys
  • Map, Set are not spec-compliant, Set values are stringified, Map are not iterable, don't use them
  • for (const foo of [1]) {} is also broken, it needs a let/var instead of const (warning: let might not be block-scoped as per spec, they probably just replace it by var)
  • Use doc._id + '' to get the objectId as hex string, don't rely on template strings also, they seem to incorrectly invoke doc._id.toString() which returns 'ObjectId(hexstring)'
  • Outdated RegExp, not supporting look-behinds
caub / Sux.js
Last active Jun 28, 2019
simple react state management
View Sux.js
import React from 'react';
const SuxContext = React.createContext();
export class SuxProvider extends React.Component {
state = {};
render() {
return (
<SuxContext.Provider value={{...this.state, dispatch: data => this.setState(data)}}>
View express.js
const fetch = require('node-fetch');
const http = require('http');
class Express {
notFoundHandler = (req, res) => {
res.statusCode = 404;
res.write('not found');
caub /
Last active Apr 15, 2021
VSCode's Format on save for SublimeText

requirement: TypeScript package should be installed

Step 1: Create a new plugin (Tools > Developer > new plugin) with the following, save it as for example:

import sublime
import sublime_plugin

class FormatTypescriptOnSave(sublime_plugin.EventListener):
  def on_pre_save(self, view): 
caub / zendesk-chat.js
Last active Aug 27, 2019
Zendesk Chat API issue
View zendesk-chat.js
const fetch = require('node-fetch');
const cp = require('child_process');
const http = require('http');
// const ZENDESK_KEY = process.env.ZENDESK_KEY || '..........';
const ZENDESK_USER = process.env.ZENDESK_KEY || '';
const ZENDESK_PASSWORD = process.env.ZENDESK_PASSWORD || '..........';
// const basicAuth = Buffer.from(`${ZENDESK_USER}/token:${ZENDESK_KEY}`).toString('base64');
const ZENDESK_SUBDOMAIN = process.env.ZENDESK_SUBDOMAIN || 'd3v-ultimateai';
const ZENDESK_OAUTH_CLIENT_ID = process.env.ZENDESK_OAUTH_CLIENT_ID || 'ultimate.ai_zendesk';
View 4.js
var formatDate = d=>`${d.getFullYear()}-${`${d.getMonth()+1}`.padStart(2,0)}-${`${d.getDate()}`.padStart(2,0)}`
var es=document.body.textContent.trim().split('\n').map(l => {let [,d,s]=l.split(/\[|\] /g); return {d: new Date(d), s}}).sort((a,b)=>a.d-b.d)
var{d,s}) => { let m=d.getMinutes(); if (d.getHours()===23){d.setDate(d.getDate()+1);m=0;} return {date: formatDate(d), m,d,s}} )
var days=xs.reduce((o,{date,m,s})=>{const slots=o[date]&&o[date].slots||Array.from({length:60},()=>0); let g=s.match(/#\d+/); if (s.startsWith('falls')){for(let i=m;i<slots.length;i++)slots[i]=1} if (s.startsWith('wakes')){for(let i=m;i<slots.length;i++)slots[i]=0} return {...o,[date]:{...o[date],slots,...g&&{guard:g[0]}}} }, {})
var guards=Object.values(days).reduce((o, {slots,guard}) => {let name=guard.slice(1); const sleeptime=o[name]||0; return {...o,[name]:sleeptime+slots.reduce((a,b)=>a+b)};}, {})
var ds = Object.entries(days).filter(([date, o]) => o.guard==='#2593').map(([date, {slots}]) => slots)
caub / server.js
Last active Oct 15, 2018
https with letsencrypt
View server.js
// d run -d --name=ok -p 443:6100 -p 80:6000 --workdir=/home/node -v /etc/letsencrypt/:/etc/letsencrypt/:ro -v $PWD/server.js:/home/node/server.js node node server
var https = require("https");
var http = require("http");
var fs = require("fs");
var p="/etc/letsencrypt/live/";
var hs=https.createServer({
key: fs.readFileSync(p+"privkey.pem")+"",