Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
NickStrupat / OnceThenOther.cs
Created July 9, 2024 20:49
A thread-safe utility class that returns the `once` value once ever, and then the `other` value from then on.
public sealed class OnceThenOther<T>(T once, T other)
{
private Int32 flag = 0;
// Checking the flag value normally before exchanging it atomically is an optimization with two parts:
// A) Contentious first access will all synchronize on the atomic exchange
// B) Subsequent accesses will see the local cached value of `1`, so they won't have to perform the heavier atomic exchange
public T Value => flag == 0 && Interlocked.Exchange(ref flag, 1) == 0 ? once : other;
}
@NickStrupat
NickStrupat / ChatBot.csproj
Last active July 8, 2024 14:13
C# Chat bot powered by Llama 3 through Ollama
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<WarningsAsErrors>Nullable</WarningsAsErrors>
</PropertyGroup>
@NickStrupat
NickStrupat / InterfaceImplementor.cs
Created August 28, 2021 21:26
Pass an interface type and receive an instance of a run-time-emitted class which implements the interface.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
public static class InterfaceImplementor
@NickStrupat
NickStrupat / ExpandoObjectExtensions.cs
Last active October 13, 2020 19:16
Extend ExpandoObject to control assignment by hooking INotifyPropertyChanged
public static class Extensions
{
public static ExpandoObject WithAutoCorrect(this ExpandoObject eo)
{
(eo as INotifyPropertyChanged).PropertyChanged += Handler;
return eo;
static void Handler(object sender, PropertyChangedEventArgs e)
{
var dict = (IDictionary<String, Object>)sender;
@NickStrupat
NickStrupat / DictionaryObjectExtensions.cs
Last active October 9, 2020 16:51
Dictionary to object
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
public static class DictionaryObjectExtensions
{
@NickStrupat
NickStrupat / StrupHash.cs
Created October 15, 2019 21:56
pinning byte[] before page alignment calculation
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace StrupHash
{
class Program
{
static unsafe void Main(string[] args)
class MapWrapper implements Map<string, any> {
constructor(readonly object: any) {}
clear(): void {
for (let key of this.keys())
delete this.object[key];
}
delete(key: string): boolean {
if (!this.has(key))
return false;
@NickStrupat
NickStrupat / crypto.ts
Created September 17, 2019 19:30
Small class for generating public-private key pairs, signing, and verifying signatures
import { sign } from "tweetnacl"
import { decodeUTF8 } from "tweetnacl-util";
export class Crypto {
private constructor() {}
static generateKeys(): CryptoKeyPair {
const naclKeyPair = sign.keyPair();
return new CryptoKeyPair(naclKeyPair.publicKey, naclKeyPair.secretKey);
}
@NickStrupat
NickStrupat / get-all-key-value-pairs.ts
Created September 17, 2019 18:37
Get an object as iterable pairs of eval-able keys and values
function * getAllKeyValuePairs(o: any, key: string): IterableIterator<[string, string]> {
if (o instanceof Map) {
for (let element of o.entries())
yield * getAllKeyValuePairs(element[1], `${key}.get("${element[0]}")`);
}
else if (o instanceof Date) {
for (let languageCode of ['en', 'fr'])
yield * getAllKeyValuePairs(o.toLocaleString(languageCode), `${key}.toLocaleString("${languageCode}")`);
}
else if (o instanceof Array) {
public static class Extensions
{
public static Rune[] ToArray(this SpanUtf8BytesRuneEnumerator enumerator)
{
Span<Rune> runes = stackalloc Rune[enumerator.remaining.Length];
var i = 0;
foreach (var utf8BytesRune in enumerator)
runes[i++] = utf8BytesRune;
var result = new Rune[i];
runes.Slice(0, i).CopyTo(result);