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=42&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 18897 results for "function"(761ms)

HHGtoMyDaygetWeather.ts5 matches

@lm3mUpdated 2 days ago
5const TABLE_NAME = `memories`;
6
7function summarizeWeather(weather: WeatherResponse) {
8 const summarizeDay = (day: WeatherResponse["weather"][number]) => ({
9 date: day.date,
21}
22
23async function generateConciseWeatherSummary(weatherDay) {
24 try {
25 // Get API key from environment
79}
80
81async function deleteExistingForecast(date: string) {
82 await sqlite.execute(
83 `
89}
90
91async function insertForecast(date: string, forecast: string) {
92 const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
93
108}
109
110export default async function getWeatherForecast(interval: number) {
111 const weather = await getWeather("Boston, MA");
112 console.log({ weather });
1// Map Vote Tallying Function with Rate Limit Service Integration
2// This function counts emoji reactions and announces winners in a Hell Let Loose map vote
3import seedrandom from "https://esm.sh/seedrandom";
4import { DiscordRateLimitService } from "https://esm.town/v/ktodaz/Discord_Bot_Services/discord-rate-limit-service.tsx";
48
49// Enhanced Discord API request with rate limiting
50async function discordRequest(endpoint: string, options: RequestInit = {}) {
51 const token = Deno.env.get("DISCORD_BOT_TOKEN");
52 if (!token) {
104
105// Get emoji mapping to decode emoji reactions
106function getEmojiMapping() {
107 return {
108 "🌄": "Dawn",
119
120// Get color from string
121function getColorFromString(colorName: string): number {
122 const colorMap: Record<string, number> = {
123 "Red": 0xED4245,
139
140// Load configuration
141async function getConfiguration(): Promise<CurrentConfig> {
142 try {
143 const { success, config, error } = getCurrentConfig();
160
161// Load placeholder embed data
162export function getPlaceholderEmbedData(): Promise<PlaceholderEmbedData> {
163 return Promise.resolve({
164 Title: "The votes are in!",
171
172// Load top winners embed data
173export function getTopWinnersEmbedData(): Promise<TopWinnersEmbedData> {
174 return Promise.resolve({
175 Title: "Announcing The Top {0} Winners!",
182
183// Get all messages in a channel with rate limiting
184async function getChannelMessages(channelId: string) {
185 try {
186 let allMessages = [];
220
221// Get reactions for a specific message with rate limiting
222async function getMessageReactions(channelId: string, messageId: string, emoji: string) {
223 try {
224 const encodedEmoji = encodeURIComponent(emoji);
237
238// Get user info from Discord API with rate limiting
239async function getUserInfo(guildId: string, userId: string) {
240 try {
241 const routeKey = `/guilds/${guildId}/members`;
252
253// Send placeholder embed while counting votes
254async function sendPlaceholderEmbed(channelId: string) {
255 try {
256 const placeholderData = await getPlaceholderEmbedData();
284
285// Send winners announcement embed with rate limiting
286async function sendWinnersEmbed(
287 channelId: string,
288 winners: MapVote[],
339
340// Create a thread for full results with rate limiting
341async function createFullResultsThread(channelId: string, allVotes: MapVote[], userVotes: UserVote[]) {
342 try {
343 const channelRoutKey = `/channels/${channelId}/threads`;
474
475// Format processing time
476function formatProcessingTime(startTime: number): string {
477 const totalSeconds = Math.floor((Date.now() - startTime) / 1000);
478 const minutes = Math.floor(totalSeconds / 60);
487
488// Setup required database tables
489async function setupDatabase() {
490 // Create vote_sessions table if it doesn't exist
491 await sqlite.execute(`
528}
529
530// Main voting tallying function
531export default async function(channelId: string) {
532 console.log(`🔢 Starting vote tallying for channel ${channelId}`);
533 const startTime = Date.now();
594 console.log(`Processing: Embed: ${mapName} (${variant}), Reactions: ${reaction.count}`);
595
596 // Get users who reacted with this emoji - using rate limited function
597 const reactedUsers = await getMessageReactions(channelId, msg.id, emoji);
598 console.log(`Emote key ${variant}: ${reactedUsers.length} users`);
799}
800
801// Function to get previous vote results
802export async function getPreviousVoteResults(limit: number = 5) {
803 try {
804 await setupDatabase();

synced_reducermain.tsx1 match

@jeffreyyoungUpdated 2 days ago
1export default async function(req: Request): Promise<Response> {
2 const url = new URL(req.url);
3 if (url.pathname === "/v1") {
8const CREATION_LOCK_KEY = "map_vote_creation_first_half";
9
10// Basic Discord request function with rate limiting
11async function safeDiscordRequest(endpoint: string, options: RequestInit = {}) {
12 const token = Deno.env.get("DISCORD_BOT_TOKEN");
13
43}
44
45// Simplified test function that just checks channel access
46async function testChannelAccess(channelId: string) {
47 try {
48 console.log(`Testing access to channel ${channelId}`);
73}
74
75// Main function
76export default async function() {
77 console.log("🧪 SIMPLE TEST: Map Vote Tally Channel Access Test");
78

untitled-4783main.js10 matches

@StayNullUpdated 2 days ago
15
16// --- INITIALIZATION ---
17function init() {
18 // Scene
19 scene = new THREE.Scene();
77}
78
79function addBuilding(x, y, z, width, height, depth, color) {
80 const geometry = new THREE.BoxGeometry(width, height, depth);
81 const material = new THREE.MeshStandardMaterial({ color: color });
86
87// --- GAME LOOP & UPDATES ---
88function animate(currentTime) {
89 if (gameOver) {
90 scoreElement.innerText = `GAME OVER! Survived: ${Math.floor(gameTime / 1000)}s\nPress R to Restart`;
114let lastFrameTime = 0;
115
116function handlePlayerMovement() {
117 const moveDirection = new THREE.Vector3();
118 const rotationSpeed = playerTurnSpeed;
143}
144
145function updateCamera() {
146 const offset = new THREE.Vector3(0, 3, -6); // Camera offset from player
147 offset.applyQuaternion(player.quaternion); // Apply player's rotation to offset
150}
151
152function spawnCars(currentTime) {
153 if (currentTime - lastCarSpawnTime > CAR_SPAWN_INTERVAL) {
154 lastCarSpawnTime = currentTime;
179}
180
181function updateCars() {
182 cars.forEach((car, index) => {
183 car.position.z += car.userData.directionZ * car.userData.speed;
191}
192
193function checkCollisions() {
194 const playerBox = new THREE.Box3().setFromObject(player);
195 cars.forEach(car => {
204}
205
206function restartGame() {
207 gameOver = false;
208 gameTime = 0;
220
221// --- UTILITIES ---
222function onWindowResize() {
223 camera.aspect = window.innerWidth / window.innerHeight;
224 camera.updateProjectionMatrix();
5
6// Create a magic link token for the given email
7export async function createMagicLinkToken(userEmail: string): Promise<string> {
8 const token = generateSessionToken();
9 const now = Math.floor(Date.now() / 1000);
19
20// Send a magic link email
21export async function sendMagicLinkEmail(url: string, userEmail: string, token: string): Promise<boolean> {
22 try {
23 const magicLink = `${url}/auth/magic-link/${token}`;
47
48// Validate a magic link token and create a session
49export async function validateMagicLinkToken(token: string): Promise<{ valid: boolean; userId?: number }> {
50 const now = Math.floor(Date.now() / 1000);
51
11const CREATION_LOCK_KEY = "map_vote_creation_first_half";
12
13// Main function that runs as a scheduled val for tallying votes (testing version)
14export default async function() {
15 console.log("🧪 TEST MODE: First Half Map Vote Tally Test Job started");
16 console.log("⚠️ WARNING: This version skips time verification and is for testing only!");
86 const tallyStartTime = Date.now();
87
88 // Call the map vote tallying function
89 const tallyResult = await mapVoteTallying(channelId);
90
12const MINIMUM_VOTING_PERIOD_MS = 3 * 24 * 60 * 60 * 1000; // 3 days in milliseconds
13
14// Main function that runs as a scheduled val for tallying second half votes
15export default async function() {
16 console.log("🕒 Second Half Map Vote Tally Cron Job started");
17
111 const tallyStartTime = Date.now();
112
113 // Call the map vote tallying function
114 const tallyResult = await mapVoteTallying(channelId);
115
12const MINIMUM_VOTING_PERIOD_MS = 3 * 24 * 60 * 60 * 1000; // 3 days in milliseconds
13
14// Main function that runs as a scheduled val for tallying votes
15export default async function() {
16 console.log("🕒 Map Vote Tally Cron Job started");
17
110 const tallyStartTime = Date.now();
111
112 // Call the map vote tallying function
113 const tallyResult = await mapVoteTallying(channelId);
114

TowniePreviewFrame.tsx4 matches

@valdottownUpdated 2 days ago
9}
10
11export function PreviewFrame(props: PreviewProps) {
12 const previewKey = useRef<string>("new-chat");
13 const [count, setCount] = useState<number>(0);
73const TSRE = /\/$/;
74
75function URLInput({ url, pathname, setPathname }) {
76 const prefix = url.replace(TSRE, "");
77 return (
90}
91
92function PreviewSelect({ index, setIndex, files }) {
93 return (
94 <div>
116}
117
118function usePreviewURL({ files }) {
119 const [index, setIndex] = useState<number>(0);
120 const htmlVals = files?.filter(file => file.links?.endpoint !== undefined);

getFileEmail4 file matches

@shouserUpdated 2 weeks ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblkUpdated 2 weeks 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.