Skip to content

Instantly share code, notes, and snippets.

@duncansmart
duncansmart / dynamicInit.js
Created November 19, 2023 12:06
Call initFunc on elements in selector that are in DOM now and also on dynamically-added elements later on
View dynamicInit.js
// Call initFunc on elements in selector that are in DOM now and also on dynamically-added elements later on
function dynamicInit(selector, initFunc) {
//console.log('dynamicInit', selector)
window._dynamicInitData ??= [];
window._dynamicInitData.push({ selector, initFunc });
if (!window._dynamicInitObserver) {
window._dynamicInitObserver = new MutationObserver(function (mutations) {
// avoid infinite loop when we add new elements below
window._dynamicInitObserver.disconnect()
@duncansmart
duncansmart / TupleComparer.cs
Created November 3, 2023 23:01
TupleComparer that takes a IEqualityComparer (e.g. StringComparer.OrdinalIgnoreCase)
View TupleComparer.cs
/// <summary>
/// Compares tuples of 2 items of the same type, using the specified comparer.
/// </summary>
class TupleComparer<T> : IEqualityComparer<(T, T)>
{
IEqualityComparer<T> _comparer;
public TupleComparer(IEqualityComparer<T> comparer) => _comparer = comparer;
public bool Equals((T, T) x, (T, T) y) => _comparer.Equals(x.Item1, y.Item1) && _comparer.Equals(x.Item2, y.Item2);
public int GetHashCode((T, T) obj) => HashCode.Combine(_comparer.GetHashCode(obj.Item1), _comparer.GetHashCode(obj.Item2));
}
@duncansmart
duncansmart / Get-Powerwall-Data.ps1
Last active April 12, 2023 14:35
Powershell script to download Tesla Powerwall data to a CSV file
View Get-Powerwall-Data.ps1
###############################################################################
# Get a refresh token using something like https://chrome.google.com/webstore/detail/tesla-access-token-genera/kokkedfblmfbngojkeaepekpidghjgag
$REFRESH_TOKEN = 'your.token.here'
# Set as appropriate:
$startDate = [DateTime]::Parse('2023-04-01')
$csvFile = 'C:\temp\my powerwall data.csv'
###############################################################################
# Auth
$token = Invoke-RestMethod -Uri "https://auth.tesla.com/oauth2/v3/token" -Method Post -Body @{
@duncansmart
duncansmart / Secure environment variables on windows.md
Created October 11, 2022 17:54
Secure environment variables on windows
View Secure environment variables on windows.md

To create a DPAPI-encrypted environment variable run the following PowerShell:

[Environment]::SetEnvironmentVariable((Read-Host "Enter name"), (Read-Host "Enter value" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString), [EnvironmentVariableTarget]::User)

(You may need to restart any apps that wish to use this value now)

The value can be decrypted using the following PowerShell line (replace MY_ENV_VAR with your variable name):

[Net.NetworkCredential]::new('', (ConvertTo-SecureString $env:MY_ENV_VAR)).Password
@duncansmart
duncansmart / SmartStream.cs
Created August 31, 2022 14:06
Stream that starts off backed by MemoryStream but after threshold will switch to file-backed temp-file stream
View SmartStream.cs
using System;
using System.IO;
class SmartStream : Stream
{
int _maxMemorySize;
Stream _stream = new MemoryStream();
public SmartStream(int maxMemorySize)
{
@duncansmart
duncansmart / web.config
Last active April 20, 2021 08:50
IIS reverse proxy to local UniFi Controller
View web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<httpRuntime requestPathInvalidCharacters="&lt;,>,%,&amp;,\,?" /> <!-- some requests contains mac address thus ":" should be allowed -->
</system.web>
<system.webServer>
<httpErrors errorMode="Detailed" />
<rewrite>
<rules>
<clear />
@duncansmart
duncansmart / edgemax-dump-traffic-stats.js
Last active April 16, 2023 05:00
Continuously grabs the traffic stats from an EdgeRouter-X router and dumps them in CSV format to stdout.
View edgemax-dump-traffic-stats.js
const url = require('url');
const axios = require('axios');
const qs = require('querystring')
const WebSocket = require('ws');
// disable certificate verification
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const baseUrl = 'https://192.168.1.1';
const username = 'ubnt';
View EE APN IPv4.mobileconfig
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PayloadContent</key>
<array>
<dict>
<key>APNs</key>
<array>
<dict>
@duncansmart
duncansmart / MailEventLogs.ps1
Created July 13, 2017 08:25
Emails filtered eventlogs from previous 24 hours
View MailEventLogs.ps1
# powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Unrestricted -Command "& { .\MailEventLogs.ps1 }"
$mailTo = "foo@example.com"
$mailFrom = "$env:COMPUTERNAME@example.com"
$smtpServer = "aspmx.l.google.com"
Set-StrictMode -Version Latest
$startDate = (Get-Date).AddDays(-1).AddMinutes(-5)
View csc_net46.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;