import numpy as np
from sklearn.cluster import SpectralClustering
def estimate_speakers(embeddings: np.ndarray, max_k: int = 8):
# L2-normalize so the dot product is cosine similarity.
x = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
sim = x @ x.T
# CLAMP negatives to 0. Do NOT rescale [-1, 1] to [0, 1]:
# rescaling maps near-orthogonal (different-speaker) pairs at ~0
# up to 0.5, inflating cross-speaker edges and washing out the
# eigengap. Clamping leaves different-speaker pairs near 0.
affinity = np.clip(sim, 0.0, 1.0)
np.fill_diagonal(affinity, 1.0)
# Normalized (symmetric) graph Laplacian: L = I - D^-1/2 A D^-1/2.
deg = affinity.sum(axis=1)
d_inv_sqrt = 1.0 / np.sqrt(np.maximum(deg, 1e-12))
lap = np.eye(affinity.shape[0]) - (
affinity * d_inv_sqrt[:, None] * d_inv_sqrt[None, :]
)
eigvals = np.sort(np.linalg.eigvalsh(lap))
upper = min(max_k, len(eigvals) - 1)
gaps = np.diff(eigvals[: upper + 1])
k = int(np.argmax(gaps)) + 1
if k < 2:
return 1, np.zeros(affinity.shape[0], dtype=int)
labels = SpectralClustering(
n_clusters=k, affinity="precomputed", random_state=0
).fit_predict(affinity)
return k, labelsSnippets
Atomic, copy-paste code. Filter by language.
python
bash
# CHECKS
# wait this many seconds before the first attempt
WAIT=5
# seconds between attempts
TIMEOUT=10
# number of attempts before the deploy is failed
ATTEMPTS=6
# path expected-substring-in-the-body
/healthz okts
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const run = promisify(execFile);
interface SshTarget {
keyPath: string;
user: string;
host: string;
}
export async function dokku(t: SshTarget, args: string[]): Promise<string> {
const { stdout } = await run(
"ssh",
[
"-i",
t.keyPath,
"-o",
"StrictHostKeyChecking=accept-new",
`${t.user}@${t.host}`,
"dokku",
...args,
],
{ maxBuffer: 5 * 1024 * 1024, timeout: 60_000 },
);
return stdout;
}
// Want structured data out of a REPL? Make the REPL emit JSON.
export async function mongoJson(uri: string, expr: string): Promise<unknown> {
const { stdout } = await run(
"mongosh",
[uri, "--quiet", "--eval", `JSON.stringify(${expr})`],
{ maxBuffer: 5 * 1024 * 1024, timeout: 60_000 },
);
return JSON.parse(stdout);
}ts
import sodium from "libsodium-wrappers";
interface PublicKey {
key: string; // base64
key_id: string;
}
export async function setSecret(opts: {
owner: string;
repo: string;
name: string;
value: string;
token: string;
}): Promise<void> {
const api = `https://api.github.com/repos/${opts.owner}/${opts.repo}/actions/secrets`;
const headers = {
Authorization: `Bearer ${opts.token}`,
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
};
const keyRes = await fetch(`${api}/public-key`, { headers });
if (!keyRes.ok) throw new Error(`public-key: ${keyRes.status}`);
const pk = (await keyRes.json()) as PublicKey;
await sodium.ready;
const sealed = sodium.crypto_box_seal(
sodium.from_string(opts.value),
sodium.from_base64(pk.key, sodium.base64_variants.ORIGINAL),
);
const encrypted_value = sodium.to_base64(
sealed,
sodium.base64_variants.ORIGINAL,
);
const putRes = await fetch(`${api}/${opts.name}`, {
method: "PUT",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify({ encrypted_value, key_id: pk.key_id }),
});
if (!putRes.ok && putRes.status !== 201 && putRes.status !== 204) {
throw new Error(`put secret: ${putRes.status}`);
}
}python
import collections
import wave
import webrtcvad
def read_pcm(path):
with wave.open(path, "rb") as wf:
assert wf.getnchannels() == 1, "mono only"
assert wf.getsampwidth() == 2, "16-bit only"
rate = wf.getframerate()
assert rate in (8000, 16000, 32000, 48000)
return wf.readframes(wf.getnframes()), rate
def frames(pcm, rate, ms=30):
n = int(rate * (ms / 1000.0) * 2) # bytes per frame
for i in range(0, len(pcm) - n + 1, n):
yield pcm[i : i + n]
def voiced_segments(path, aggressiveness=2, ms=30, pad=300):
vad = webrtcvad.Vad(aggressiveness)
pcm, rate = read_pcm(path)
num_padding = pad // ms
ring = collections.deque(maxlen=num_padding)
triggered, voiced = False, []
for frame in frames(pcm, rate, ms):
speech = vad.is_speech(frame, rate)
if not triggered:
ring.append((frame, speech))
if sum(s for _, s in ring) > 0.9 * ring.maxlen:
triggered = True
voiced.extend(f for f, _ in ring)
ring.clear()
else:
voiced.append(frame)
ring.append((frame, speech))
if sum(not s for _, s in ring) > 0.9 * ring.maxlen:
triggered = False
yield b"".join(voiced)
voiced, ring = [], collections.deque(maxlen=num_padding)
if voiced:
yield b"".join(voiced)
for i, chunk in enumerate(voiced_segments("call.wav")):
print(f"segment {i}: {len(chunk)} bytes")
# hand chunk to your transcriber herets
import { createHmac, randomBytes } from "node:crypto";
// Stricter than encodeURIComponent: OAuth also escapes ! * ' ( )
function pctEncode(value: string): string {
return encodeURIComponent(value).replace(
/[!*'()]/g,
(c) => "%" + c.charCodeAt(0).toString(16).toUpperCase(),
);
}
interface Creds {
consumerKey: string;
consumerSecret: string;
token: string;
tokenSecret: string;
}
export function authHeader(
method: string,
baseUrl: string,
creds: Creds,
): string {
const oauth: Record<string, string> = {
oauth_consumer_key: creds.consumerKey,
oauth_nonce: randomBytes(16).toString("hex"),
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: Math.floor(Date.now() / 1000).toString(),
oauth_token: creds.token,
oauth_version: "1.0",
};
// Sort by encoded key, then join as k=v with &.
const sortedEncodedParams = Object.keys(oauth)
.map((k) => [pctEncode(k), pctEncode(oauth[k])])
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([k, v]) => `${k}=${v}`)
.join("&");
const baseString =
method.toUpperCase() +
"&" +
pctEncode(baseUrl) +
"&" +
pctEncode(sortedEncodedParams);
const signingKey =
pctEncode(creds.consumerSecret) + "&" + pctEncode(creds.tokenSecret);
oauth.oauth_signature = createHmac("sha1", signingKey)
.update(baseString)
.digest("base64");
return (
"OAuth " +
Object.keys(oauth)
.sort()
.map((k) => `${pctEncode(k)}="${pctEncode(oauth[k])}"`)
.join(", ")
);
}ts
import { Cloud } from "parse-server";
Parse.Cloud.beforeSave("Order", async (request) => {
const order = request.object;
if (!request.user) {
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, "login required");
}
const qty = order.get("quantity");
if (typeof qty !== "number" || !Number.isInteger(qty) || qty < 1) {
throw new Parse.Error(
Parse.Error.VALIDATION_ERROR,
"quantity must be a positive integer",
);
}
const status = order.get("status");
const allowed = ["pending", "paid", "shipped"];
if (!allowed.includes(status)) {
throw new Parse.Error(
Parse.Error.VALIDATION_ERROR,
`status must be one of ${allowed.join(", ")}`,
);
}
// Server owns these fields. Ignore whatever the client sent.
if (order.isNew()) {
order.set("owner", request.user);
order.set("createdVia", "api");
}
});ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
type Content = { content: { type: "text"; text: string }[]; isError?: boolean };
const textResult = (text: string): Content => ({ content: [{ type: "text", text }] });
const jsonResult = (data: unknown): Content => textResult(JSON.stringify(data));
const errorResult = (text: string): Content => ({ ...textResult(text), isError: true });
const appName = z
.string()
.min(1)
.max(63)
.regex(/^[a-z0-9-]+$/, "lowercase letters, digits, hyphens only");
const server = new McpServer({ name: "ops", version: "1.0.0" });
// Read-only: safe to call any time.
server.tool(
"get_app_status",
"Read the deploy status of one app. Read-only; never changes anything.",
{ app: appName },
async ({ app }) => {
const res = await fetch(`https://ops.internal/apps/${app}/status`);
if (!res.ok) return errorResult(`lookup failed: ${res.status}`);
return jsonResult(await res.json());
},
);
// Destructive: guarded by a literal the model must supply on purpose.
server.tool(
"restart_app",
"Restart one app. Destructive; requires confirm:\"yes\".",
{ app: appName, confirm: z.literal("yes") },
async ({ app }) => {
const res = await fetch(`https://ops.internal/apps/${app}/restart`, {
method: "POST",
});
if (!res.ok) return errorResult(`restart failed: ${res.status}`);
return textResult(`restarted ${app}`);
},
);
await server.connect(new StdioServerTransport());