Skip to content

Instantly share code, notes, and snippets.

View jamesr2323's full-sized avatar

James Rees jamesr2323

  • ChangeLab
  • London
View GitHub Profile
const express = require('express');
const fs = require('fs-extra');
const path = require('path');
const app = express();
const port = 3000;
app.use(express.static('./'));
app.get('/', async (req, res) => {
@jamesr2323
jamesr2323 / get_git_stats
Created December 22, 2020 08:55
Get git stats by contributing user, in time period
# This is mostly just copied from this awesome SO answer: https://stackoverflow.com/a/20414465/4094427
# get_stats '*' - get stats for repo lifetime
# get_stats 'scss' get stats just for *.scss files
get_stats_all() {
echo "*.$1"
git log --shortstat --pretty="%cE" -- "*.$1" | sed 's/\(.*\)@.*/\1/' | grep -v "^$" | awk 'BEGIN { line=""; } !/^ / { if (line=="" || !match(line, $0)) {line = $0 "," line }} /^ / { print line " # " $0; line=""}' | sort | sed -E 's/# //;s/ files? changed,//;s/([0-9]+) ([0-9]+ deletion)/\1 0 insertions\(+\), \2/;s/\(\+\)$/\(\+\), 0 deletions\(-\)/;s/insertions?\(\+\), //;s/ deletions?\(-\)//' | awk 'BEGIN {name=""; files=0; insertions=0; deletions=0;} {if ($1 != name && name != "") { print name ": " files " files changed, " insertions " insertions(+), " deletions " deletions(-), " insertions-deletions " net"; files=0; insertions=0; deletions=0; name=$1; } name=$1; files+=$2; insertions+=$3; deletions+=$4} END {print name ": " files " files changed, " insertions " insertions(+),
@jamesr2323
jamesr2323 / nested_liquid.rb
Created July 10, 2020 17:43
Proof of concept: Nested liquid templates
require 'liquid'
class Button < Liquid::Tag
def initialize(tag_name, args, tokens)
super
@color = args.split(' ')[0]
@url = args.split(' ')[1]
@text = args.split(' ')[2..-1].join(' ')
end
@jamesr2323
jamesr2323 / assets_controller.rb
Created May 12, 2020 15:30
Dynamically change SASS in a multi-tenant Rails application
# This works by injecting SASS variables before the main template. As long as they are not
# redefined without !default later on you're good to go.
# Includes some local in-memory caching to not recompile SASS on every request.
# I've implemented it at the client (tenant) level, but it could equally be more granular, at
# level of some other entity in your application.
class AssetsController < ApplicationController
def styles
$stylesheets ||= {}
@jamesr2323
jamesr2323 / slack_post.py
Last active August 8, 2019 20:32
Post experiment results, images etc. to Slack in an updating message
## Usage
## sp = SlackPost(token=app_token, channel='#random')
## await sp.post_update("Look at this cool graph", ['img1.png', 'img2.png'])
## await sp.post_update("The data has changed!", ['img3.png', 'img4.png'])
class SlackPost():
def __init__(self, token, channel):
self.channel = channel
self.client = client = slack.WebClient(
token=token,
network_check = driver.execute_script("""
return performance.getEntries()
.filter(e => e.entryType==='navigation' || e.entryType==='resource')
.map(e=> ([e.name, e.transferSize]));
""")
params = {
cmd: 'Page.addScriptToEvaluateOnNewDocument',
params: {
source: %Q{
(function(XHR) {
"use strict";
window.xhrLog = '';
var open = XHR.prototype.open;
require 'selenium-webdriver'
require 'json'
require 'csv'
require 'active_support/all'
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--headless') # Remove this to watch the browser in testing
options.add_argument(%Q{--user-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"})
options.add_argument("--blink-settings=imagesEnabled=false")
driver = Selenium::WebDriver.for(:chrome, options: options)
@jamesr2323
jamesr2323 / rmse_loss.py
Created May 9, 2018 02:40
How to use RMSE loss function in PyTorch
# Thanks https://discuss.pytorch.org/t/rmse-loss-function/16540
class RMSELoss(torch.nn.Module):
def __init__(self):
super(RMSELoss,self).__init__()
def forward(self,x,y):
criterion = nn.MSELoss()
loss = torch.sqrt(criterion(x, y))
return loss
@jamesr2323
jamesr2323 / index.js
Last active March 28, 2022 12:32
Simple AWS Lambda Function to store a simple feed of text data in Redis
/*
This was written to provide a simple serverless backend for a widget which displays live updating comments on a signup page.
The frontend can simple call $.post to add a comment, and $.get to retrieve the latest comments.
You need a Redis instance somewhere, you can get a free 30MB one from Redis Labs.
You'll also need to configure a AWS API Gateway endpoint which invokes this function for GET and POST requests
*/
'use strict';
const redis = require('redis'); // You'll need to upload Redis in node_modules. Easiest way to do this is do npm install redis --save in a blank directory, zip it and then upload to Lambda