Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/?q=function&page=1382&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=function

Returns an array of strings in format "username" or "username/projectName"

Found 18948 results for "function"(1710ms)

claude_newmain.tsx1 match

@adagradschool•Updated 5 months ago
1
2 export default function handler(req) {
3 return new Response(`"\n <!DOCTYPE html>\n <html>\n <head>\n <title>Claude Chat Conversation</title>\n <meta charset=\"UTF-8\">\n <style>\n body {\n font-family: system-ui, -apple-system, sans-serif;\n line-height: 1.5;\n max-width: 800px;\n margin: 0 auto;\n padding: 20px;\n background: #f9fafb;\n }\n .message {\n margin: 20px 0;\n padding: 15px;\n border-radius: 8px;\n }\n .human {\n background: #e5e7eb;\n }\n .assistant {\n background: #dbeafe;\n }\n .role {\n font-weight: bold;\n margin-bottom: 8px;\n }\n </style>\n </head>\n <body>\n \n </body>\n </html>\n"`, {
4 headers: {

memorySampleSummarymain.tsx6 matches

@toowired•Updated 5 months ago
9
10// Initialize the database
11async function initDB() {
12 await sqlite.execute(`
13 CREATE TABLE IF NOT EXISTS ${TABLE_NAME}_${SCHEMA_VERSION} (
21
22// Generate embedding for a given text
23async function generateEmbedding(text: string): Promise<number[]> {
24 const response = await openai.embeddings.create({
25 model: "text-embedding-ada-002",
30
31// Add a new memory to the bank
32export async function addMemory(content: string): Promise<void> {
33 await initDB();
34 const embedding = await generateEmbedding(content);
40
41// Retrieve similar memories
42export async function getSimilarMemories(query: string, limit: number = 5): Promise<string[]> {
43 await initDB();
44 const queryEmbedding = await generateEmbedding(query);
59
60// Cosine similarity calculation
61function cosineSimilarity(vecA: number[], vecB: number[]): number {
62 const dotProduct = vecA.reduce((sum, a, i) => sum + a * vecB[i], 0);
63 const magnitudeA = Math.sqrt(vecA.reduce((sum, a) => sum + a * a, 0));
67
68// Example usage
69export async function memoryBankDemo() {
70 // Add some memories
71 await addMemory("Create a RESTful API using Express.js and PostgreSQL");

sqlitemain.tsx7 matches

@toowired•Updated 5 months ago
31
32// ------------
33// Functions
34// ------------
35
36async function execute(statement: InStatement, args?: InArgs): Promise<ResultSet> {
37 const res = await fetch(`${API_URL}/v1/sqlite/execute`, {
38 method: "POST",
49}
50
51async function batch(statements: InStatement[], mode?: TransactionMode): Promise<ResultSet[]> {
52 const res = await fetch(`${API_URL}/v1/sqlite/batch`, {
53 method: "POST",
64}
65
66function createResError(body: string) {
67 try {
68 const e = zLibsqlError.parse(JSON.parse(body));
85}
86
87function normalizeStatement(statement: InStatement, args?: InArgs) {
88 if (Array.isArray(statement)) {
89 // for the case of an array of arrays
107}
108
109function upgradeResultSet(results: ImpoverishedResultSet): ResultSet {
110 return {
111 ...results,
116// adapted from
117// https://github.com/tursodatabase/libsql-client-ts/blob/17dd996b840c950dd22b871adfe4ba0eb4a5ead3/packages/libsql-client/src/sqlite3.ts#L314C1-L337C2
118function rowFromSql(
119 sqlRow: Array<unknown>,
120 columns: Array<string>,

radiodbmain.tsx4 matches

@temptemp•Updated 5 months ago
8 )
9 `);
10export async function schedulePush(id: Date, file: string, index: number) {
11 // console.log(id.toISOString(), file);
12 await sqlite.execute(
14 );
15}
16export async function schedulePurge(id: Date) {
17 await sqlite.execute(
18 `DELETE FROM SCHEDULE WHERE id < '${id.toISOString()}'`,
19 );
20}
21export async function scheduleRead() {
22 const current = new Date();
23 const normalized = new Date();
26 return result.rows;
27}
28export async function pushRandomData(index: number) {
29 await schedulePurge(new Date()); // Clear previous entries
30

redditSearchmain.tsx4 matches

@cofsana•Updated 5 months ago
15
16// Use Browserbase (with proxy) to search and scrape Reddit results
17export async function redditSearch({
18 query,
19 apiKey = Deno.env.get("BROWSERBASE_API_KEY"),
46}
47
48function constructSearchUrl(query: string): string {
49 const encodedQuery = encodeURIComponent(query).replace(/%20/g, "+");
50 return `https://www.reddit.com/search/?q=${encodedQuery}&type=link&t=week`;
51}
52
53async function extractPostData(page: any): Promise<Partial<ThreadResult>[]> {
54 return page.evaluate(() => {
55 const posts = document.querySelectorAll("div[data-testid=\"search-post-unit\"]");
67}
68
69async function processPostData(postData: Partial<ThreadResult>[]): Promise<ThreadResult[]> {
70 const processedData: ThreadResult[] = [];
71

scraper_templateREADME.md1 match

@cofsana•Updated 5 months ago
133. Adjust the if statement to detect changes and update your blob
14
154. Craft a message to be sent with `sendNotification()` function

aqimain.tsx1 match

@daabin•Updated 5 months ago
2import { easyAQI } from "https://esm.town/v/stevekrouse/easyAQI?v=5";
3
4export async function aqi(interval: Interval) {
5 const location = "guangzhou"; // <-- change to place, city, or zip code
6 const data = await easyAQI({ location });
1
2 export default function handler(req) {
3 return new Response(`"\n <!DOCTYPE html>\n <html>\n <head>\n <title>Claude Chat Conversation</title>\n <meta charset=\"UTF-8\">\n <style>\n body {\n font-family: system-ui, -apple-system, sans-serif;\n line-height: 1.5;\n max-width: 800px;\n margin: 0 auto;\n padding: 20px;\n background: #f9fafb;\n }\n .message {\n margin: 20px 0;\n padding: 15px;\n border-radius: 8px;\n }\n .human {\n background: #e5e7eb;\n }\n .assistant {\n background: #dbeafe;\n }\n .role {\n font-weight: bold;\n margin-bottom: 8px;\n }\n </style>\n </head>\n <body>\n \n <div class=\"message human\">\n <div class=\"role\">Human</div>\n <div class=\"content\">This is an engineering proposal. Convert that into a tech talk about 10 minutes long</div>\n </div>\n \n <div class=\"message assistant\">\n <div class=\"role\">Claude</div>\n <div class=\"content\">Tech Talk: Optimizing Data Storage with Symbol TablesClick to open document\nThis tech talk covers the key aspects of your data optimization project in a format suitable for a 10-minute presentation. Would you like me to adjust any specific section or add more technical details to any part?</div>\n </div>\n \n <div class=\"message human\">\n <div class=\"role\">Human</div>\n <div class=\"content\">Write the script for it</div>\n </div>\n \n <div class=\"message assistant\">\n <div class=\"role\">Claude</div>\n <div class=\"content\">Tech Talk Script: Optimizing Data Storage with Symbol TablesClick to open document\nThis script should take about 10 minutes to deliver at a comfortable speaking pace. It maintains technical depth while remaining accessible and includes natural transitions between sections. Would you like me to adjust any particular section or add more technical details anywhere?\nKey features of the script:\n\nConversational tone while maintaining technical accuracy\nClear narrative arc from problem to solution to results\nTechnical details balanced with practical implications\nSpecific examples and metrics to support key points\nNatural breaking points for slides/demos if needed</div>\n </div>\n \n <div class=\"message human\">\n <div class=\"role\">Human</div>\n <div class=\"content\">Draw a mermaid diagram to show data flows in a decision flow</div>\n </div>\n \n <div class=\"message assistant\">\n <div class=\"role\">Claude</div>\n <div class=\"content\">I'll create a Mermaid diagram showing how data flows through the system, including the new symbol table optimization.\nDecision Flow System ArchitectureClick to open diagram\nThe diagram shows the complete flow of data through our system:\n\nClient sends input data to Router\nRouter directs request to Runner\nRunner:\n\nExecutes the decision flow\nCollects node results\nApplies symbol table deduplication\n\n\nDecision message sent via EventBridge\nArchiver:\n\nProcesses the message\nStores data across three tables:\n\nSymbol Table (new)\nDecision Table\nData Table\n\n\n\n\nExporter retrieves data via Decision History API\n\nThe color coding helps distinguish:\n\nPink: Services\nBlue: Databases\nYellow: Message bus\n\nWould you like me to modify any part of the diagram or add more detail to any specific component?</div>\n </div>\n \n <div class=\"message human\">\n <div class=\"role\">Human</div>\n <div class=\"content\">I meant in the decision flow, as the data flow through the nodes, how it accumulates node results</div>\n </div>\n \n <div class=\"message assistant\">\n <div class=\"role\">Claude</div>\n <div class=\"content\">Ah, I'll create a Mermaid diagram showing how data flows through nodes in a decision flow and how node results accumulate, both in the original format and with symbol table optimization.\nDecision Flow Node Results AccumulationClick to open diagram\nThis diagram contrasts the two approaches:\n\nOriginal Storage (top):\n\nEach node stores complete copies of all data\nData accumulates and duplicates as it flows through nodes\nNode 3 ends up storing three copies of the same values\n\n\nSymbol Table Storage (bottom):\n\nUnique key-value pairs stored once in symbol table\nNodes only store indexes to the symbol table\nNo data duplication\nEasy to reconstruct full state at any node using indexes\n\n\n\nColor coding:\n\nPink: Flow nodes\nLight blue: Original node results\nYellow: Symbol table entries\nBlue: Node result indexes\n\nThe optimization becomes more apparent as data flows through the nodes - while the original storage duplicates values at each step, the symbol table approach maintains a single copy of each unique value and uses lightweight indexes to reference them.\nWould you like me to adjust any part of the diagram or add more detail to better illustrate the data flow?</div>\n </div>\n \n <div class=\"message human\">\n <div class=\"role\">Human</div>\n <div class=\"content\">It will be with a technical member on the team, please come prepared to talk through a technical project that you've worked on previously. Be ready to walk through the specific pieces of the project you owned, the architecture of the system, and the impact of the decisions made. You should be prepared to describe the project for at least ~20 minutes, going into significant technical detail about key components, also feel free to prepare diagrams and slides if that will help you describe the project.</div>\n </div>\n \n <div class=\"message assistant\">\n <div class=\"role\">Claude</div>\n <div class=\"content\">I'll help you prepare for a technical deep dive interview by creating a comprehensive walkthrough of PEP 186 based on the document. Let's structure this with both a narrative outline and supporting diagrams.\nSystem ArchitectureClick to open diagram\nNode Result CompressionClick to open diagram\nHere's the technical deep dive outline for a 20-minute discussion:\n\nProject Overview (2 minutes)\n\nProblem: Rapidly growing Aurora storage costs\nGoals: 80% data reduction, 50% cost reduction for key customers\nPerformance constraints: <5ms latency impact\nKey customer impact: Isaac, Branch, and Zilch use cases\n\n\nTechnical Analysis (3 minutes)\n\nRoot cause: Data duplication in node results\nInitial compression analysis showing ~20.6% with basic approach\nTheoretical limits study using lz4 compression\nDecision to use symbol tables based on append-only nature of data\n\n\nCore Technical Solution (5 minutes)\n\nSymbolTableV2 class design:\npythonCopyclass SymbolTableV2(BaseModel):\n version: t.Literal[\"v2\"]\n tbl: list[orjson.Fragment] = []\n tix: list[SymbolTableRef] = []\n\nKey optimizations:\n\nKey-value pair deduplication vs value-only\nIndex-based references vs 64-bit hashes\nZSTD compression for serialized data\n\n\nStorage schema decisions and rationale for separate table\n\n\nSystem Architecture (4 minutes)\n\nPipeline components:\n\nRunner: Symbol table creation and compression\nEventBridge: Message transport\nArchiver: Persistence and version handling\nExporter: Decision history API integration\n\n\nDatabase schema evolution\nBackward compatibility handling\n\n\nEdge Cases & Challenges (3 minutes)\n\nAsync resumptions and out-of-order messages\nFlow of flows and nested decision handling\nLoop handling\nProvenance data preservation\nVersion compatibility during rollout\n\n\nResults & Impact (3 minutes)\n\nCompression improvement: 20.6% → 86%\nMessage size reduction: 65KB → 25KB\nCost impact for key customers\nPerformance metrics showing <5ms latency impact\nStorage growth rate flattening\n\n\n\nKey technical points to emphasize:\n\nWhy we chose a separate symbol table vs using the existing data table\nTrade-offs in moving deduplication upstream to Runner\nCompression algorithm selection and performance implications\nSchema design decisions and indexing strategy\nBackward compatibility approach\n\nQuestions to be prepared for:\n\nWhy not use database-level compression (TOAST)?\nAlternative approaches considered\nScalability implications\nRecovery and error handling\nPerformance monitoring and alerts\nFuture optimization opportunities\n\nWould you like me to expand on any of these sections or create additional diagrams to illustrate specific components?</div>\n </div>\n \n </body>\n </html>\n"`, {
4 headers: {

sqliteExplorerAppREADME.md1 match

@thesolarmonk•Updated 5 months ago
33- [x] fix wonky sidebar separator height problem (thanks to @stevekrouse)
34- [x] make result tables scrollable
35- [x] add export to CSV, and JSON (CSV and JSON helper functions written in [this val](https://www.val.town/v/nbbaier/sqliteExportHelpers). Thanks to @pomdtr for merging the initial version!)
36- [x] add listener for cmd+enter to submit query

TaylorSwiftMomentsmain.tsx7 matches

@vawogbemi•Updated 5 months ago
84];
85
86function Header({ logoUrl, themeColor1, themeColor2 }) {
87 return (
88 <div className="py-4" style={{ backgroundColor: themeColor1, color: themeColor2 }}>
96}
97
98function EraSelector({ activeEra, onSelectEra }) {
99 return (
100 <div className="flex justify-center items-stretch w-full h-[40vh] overflow-hidden">
125}
126
127function truncatePrompt(prompt, maxLength = 50) {
128 if (prompt.length <= maxLength) return prompt;
129 return prompt.substring(0, maxLength - 3) + "...";
130}
131
132function ImageGallery({ images, activeEra, onLike, onDelete }) {
133 const downloadImage = async (url, filename) => {
134 try {
193}
194
195function App() {
196 const [prompt, setPrompt] = useState("");
197 const [imageUrl, setImageUrl] = useState("");
384}
385
386function client() {
387 createRoot(document.getElementById("root")).render(<App />);
388}
389if (typeof document !== "undefined") { client(); }
390
391export default async function server(req: Request): Promise<Response> {
392 const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
393 const { falProxyRequest } = await import("https://esm.town/v/stevekrouse/falProxyRequest");

getFileEmail4 file matches

@shouser•Updated 2 weeks ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblk•Updated 2 weeks ago
Simple functional CSS library for Val Town
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",