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/image-url.jpg%20%22Image%20title%22?q=function&page=2136&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 24101 results for "function"(3796ms)

dateHelpersmain.tsx2 matches

@iamseeley•Updated 12 months ago
1export function formatDateRange(startDateString, endDateString, format) {
2 const startDate = new Date(startDateString);
3 const endDate = new Date(endDateString);
17}
18
19function formatSingleDate(date, format) {
20 const options = {};
21

freeformServerREADME.md1 match

@pomdtr•Updated 12 months ago
5This val was adapted from @tmcw [obsidian plugin](https://github.com/tmcw/obsidian-freeform).
6
7Instead of using the `display` function, this port use `export default`.
8
9```

embeddingsSearchExamplemain.tsx10 matches

@yawnxyz•Updated 12 months ago
4
5// Step 1: Get Embeddings
6// Function to get a single embedding
7async function getEmbedding(text) {
8 console.log(`Getting embedding for: ${text}`);
9 const { embedding } = await embed({
15}
16
17// Function to get embeddings for multiple texts
18async function getEmbeddings(texts) {
19 console.log(`Getting embeddings for texts: ${texts}`);
20 const { embeddings } = await embedMany({
34];
35
36async function prepareDocumentsWithEmbeddings() {
37 const contents = documents.map(doc => doc.content);
38 const embeddings = await getEmbeddings(contents);
47
48// Step 3: Nearest Neighbor Search
49function cosineSimilarity(a, b) {
50 const dotProduct = a.reduce((sum, val, idx) => sum + val * b[idx], 0);
51 const magnitudeA = Math.sqrt(a.reduce((sum, val) => sum + val * val, 0));
54}
55
56function findNearestNeighbors(embedding, k = 1) {
57 const neighbors = documents
58 .map(doc => ({ doc, similarity: cosineSimilarity(doc.embedding, embedding) }))
65
66// Step 4: Use Lunr.js for Full-Text Search
67const idx = lunr(function () {
68 this.ref('id');
69 this.field('content');
73});
74
75// Combined Search Function
76async function search(query, similarityThreshold = 0.2) {
77 console.log(`Searching for query: ${query}`);
78 const queryEmbedding = await getEmbedding(query);

semanticSearchREADME.md1 match

@yawnxyz•Updated 12 months ago
13];
14
15async function runExample() {
16 // Add documents to the semantic search instance
17 await semanticSearch.addDocuments(documents);

github_change_user_statusmain.tsx1 match

@arrudaricardo•Updated 12 months ago
29}`;
30
31export default async function changeUserStatus(
32 input: Input,
33 token: string,

ocaps_inkmain.tsx12 matches

@zarutian•Updated 12 months ago
176 const duration = 300 + ((300 * dist) / 100);
177 var startTime = null;
178 function step(time) {
179 if (startTime == null) {
180 startTime = time;
206 }
207 // Create HTML choices from ink choices
208 _inkStory.currentChoices.forEach(function (choice) {
209 // Create paragraph with anchor element
210 var choiceParagraphElement = document.createElement("p");
219 var choiceAnchorEl =
220 choiceParagraphElement.querySelectorAll("a")[0];
221 const eventListener = function (event) {
222 // Do not follow <a> link
223 event.preventDefault();
270 };
271 temp1(t1);
272 _inkStory.BindExternalFunction("str_concat", (a, b) => {
273 return a.toString().concat(b.toString());
274 });
275 _inkStory.BindExternalFunction("urlfetch", (url) => {
276 throw new Error("Not yet implemented!");
277 });
278 _inkStory.BindExternalFunction("json_subscript", (json_data, sub) => {
279 return JSON.stringify(JSON.parse(json_data)[sub]);
280 });
281 _inkStory.BindExternalFunction(
282 "json_set_subscript",
283 (json_data, sub, item) => {
287 },
288 );
289 _inkStory.BindExternalFunction("json_array_length", (json_data) => {
290 return JSON.parse(json_data).length;
291 });
292 _inkStory.BindExternalFunction("query", (message, defaultValue) => {
293 return prompt(message, defaultValue);
294 });
295 _inkStory.BindExternalFunction("urlpost", (url, payload) => {
296 const response_p = fetch(url, {
297 method: "POST",
309 });
310 });
311 _inkStory.BindExternalFunction("parseInt", (str) => {
312 return parseInt(str, 10);
313 });
314 _inkStory.allowExternalFunctionFallbacks = true;
315 _inkStory.onError = (msg, type) => {
316 errorHandlerForAll("Ink story error: ".concat(type, " ", msg));

tahirsTilmain.tsx1 match

@tfayyaz•Updated 12 months ago
2import { renderToString } from "npm:react-dom/server";
3
4export default async function(req: Request) {
5 return new Response(
6 renderToString(

remindersmain.tsx2 matches

@koch•Updated 12 months ago
2import { fetch } from "https://esm.town/v/std/fetch";
3
4export async function reminders(interval: Interval) {
5 function* walk(node, path = []) {
6 yield node;
7 if (node && Array.isArray(node.value)) {

cachemain.tsx13 matches

@xkonti•Updated 12 months ago
25 * Make sure to set the `CACHE_TABLE_NAME` environment variable first.
26 */
27export async function setup() {
28 await sqlite.execute(`
29 CREATE TABLE IF NOT EXISTS ${tableName} (
42 * @returns The value indicating whether the key is present in cache.
43 */
44export async function exists(key): Promise<Boolean> {
45 const result = await sqlite.execute({
46 sql: `SELECT 1 FROM ${tableName} WHERE key = :key AND (expires_at IS NULL OR expires_at > datetime('now'))`,
55 * @returns The value for the key, or `null` if the key does not exist or has expired
56 */
57export async function get<T = unknown>(key): Promise<T | null> {
58 const result = await sqlite.execute({
59 sql: `SELECT content FROM ${tableName} WHERE key = :key AND (expires_at IS NULL OR expires_at > datetime('now'))`,
72 * @returns The number of keys set (1 if the key was inserted/updated, 0 if the ttl was 0)
73 */
74export async function set(key, value, ttl: number = defaultTTL): Promise<number> {
75 if (ttl <= 0) return 0;
76 const expires_at = ttl ? `datetime('now', '+${ttl} seconds')` : null;
90 * @returns The number of keys set (1 if the key was inserted/updated, 0 if the expiresAt was in the past)
91 */
92export async function setUntil(key: string, value: unknown, expiresAt: string): Promise<number> {
93 const currentDateTime = new Date().toISOString();
94 if (expiresAt <= currentDateTime) return 0;
108 * @returns The number of keys updated (1 if updated, 0 if not found or ttl was 0).
109 */
110export async function setExpiration(key: string, ttl: number = defaultTTL): Promise<number> {
111 if (ttl <= 0) return 0;
112 const expires_at = `datetime('now', '+${ttl} seconds')`;
127 * @returns The number of keys updated (1 if updated, 0 if not found or expiresAt was in the past).
128 */
129export async function setExpirationUntil(key: string, expiresAt: string): Promise<number> {
130 const currentDateTime = new Date().toISOString();
131 if (expiresAt <= currentDateTime) return 0;
146 * @returns A list of keys. Can be an empty list (array) if no keys match.
147 */
148export async function listKeys(
149 prefix: string | undefined = undefined,
150): Promise<string[]> {
164 * @returns An array of key-value pairs. Each pair is an object with 'key' and 'value' properties.
165 */
166export async function getMany<T = unknown>(
167 prefix: string | undefined = undefined,
168 limit: number = 0,
201 * @returns The number of keys deleted (1 if the key was deleted, 0 if the key did not exist)
202 */
203export async function deleteKey(key): Promise<number> {
204 const result = await sqlite.execute({
205 sql: `DELETE FROM ${tableName} WHERE key = :key`,
215 * @returns The number of keys deleted
216 */
217export async function deleteKeys(
218 prefix: string | undefined = undefined,
219): Promise<number> {
231 * Perfect for running on a schedule to keep the cache small and fast.
232 */
233export async function deleteExpired(): Promise<number> {
234 const result = await sqlite.execute({
235 sql: `DELETE FROM ${tableName} WHERE expires_at IS NOT NULL AND expires_at <= datetime('now')`,
239}
240
241// Export all functions as a single object to allow for easy importing
242export const cache = {
243 setup,

nighthawksChatmain.tsx4 matches

@yawnxyz•Updated 12 months ago
10const kv = new KV();
11
12async function generateText(prompt, charId) {
13 if (charId) {
14 await nighthawks.loadCharacter(charId);
23}
24
25async function createCharacter(obj) {
26 console.log('Creating character with:', obj)
27 await nighthawks.createCharacter(obj);
31}
32
33async function saveCharacter(char) {
34 console.log('Saving character:', char)
35 await nighthawks.saveCharacter(char);
38
39
40async function getStoredCharacter(charId) {
41 await nighthawks.loadCharacter(charId);
42 if (nighthawks.characters.length > 0) {

getFileEmail4 file matches

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

tuna8 file matches

@jxnblk•Updated 1 month ago
Simple functional CSS library for Val Town
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": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.