### Format Utilities for Numbers, Dates, and Strings (JavaScript) Source: https://context7.com/beatleader/beatleader-website/llms.txt Provides utilities for formatting numbers with locale support, rounding numbers, padding numbers with leading zeros, and performing URL template substitutions. It also includes a function to get the current locale for internationalization. ```javascript import {formatNumber, round, substituteVarsUrl, padNumber} from './utils/format'; import {getCurrentLocale} from './stores/config'; // Format numbers with locale const pp = formatNumber(15234.567, 2); // "15,234.57" (US locale) const acc = formatNumber(98.765, 2); // "98.77" const signed = formatNumber(123.4, 1, true); // "+123.4" const invalid = formatNumber(NaN, 2, false, 'N/A'); // "N/A" // Round numbers const rounded = round(98.76543, 2); // 98.77 const roundedPrecision = roundToPrecision(97.85, 0.5); // 97.5 // Pad numbers const day = padNumber(5, 2); // "05" const month = padNumber(12, 2); // "12" // URL template substitution with encoding const url = substituteVarsUrl( 'https://api.beatleader.xyz/player/${playerId}/scores?page=${page}&country=${country}', { playerId: '76561198059961776', page: 1, country: 'US' }, false, // clearUnused true // clearEmptyQuery (remove empty params) ); // Result: "https://api.beatleader.xyz/player/76561198059961776/scores?page=1&country=US" // With empty value removal const cleanUrl = substituteVarsUrl( '/ranking?page=${page}&country=${country}', {page: 1, country: ''}, false, true // Remove empty country param ); // Result: "/ranking?page=1" // Get current locale const locale = getCurrentLocale(); // 'en-US', 'de-DE', etc. ``` -------------------------------- ### Application Initialization and Bootstrapping (JavaScript) Source: https://context7.com/beatleader/beatleader-website/llms.txt This script serves as the entry point for the application, handling database setup, service initialization, and global state management. It configures Immer for state management, initializes singleton stores and services, and mounts the main Svelte application component. Error handling for common issues like browser private mode or storage quota exceeded is also included. ```javascript // main.js - Application entry point import {mount} from 'svelte'; import App from './App.svelte'; import initDb from './db/db'; import initializeRepositories from './db/repositories-init'; import createConfigStore from './stores/config'; import createAccountStore from './stores/beatleader/account'; import createPlayerService from './services/beatleader/player'; import {enablePatches, setAutoFreeze} from 'immer'; let app = null; (async () => { try { // Initialize IndexedDB await initDb(); await initializeRepositories(); // Configure Immer for state management enablePatches(); setAutoFreeze(false); // Initialize singleton stores and services await createConfigStore(); createAccountStore(); createPlayerService(); // Mount Svelte app app = mount(App, { target: document.body, props: {} }); } catch (error) { console.error(error); // Handle specific errors if (error instanceof DOMException) { if (error.toString().includes('InvalidStateError')) { error = new Error('Firefox in private mode is not supported. Please run the site in normal mode.'); } if (error.toString().includes('QuotaExceededError')) { error = new Error('Your device probably lacks free space for the website to operate.'); } } // Show error component app = mount(ErrorComponent, { target: document.body, props: {error, withTrace: true} }); } })(); export default app; ``` -------------------------------- ### Generic Repository for IndexedDB Management Source: https://context7.com/beatleader/beatleader-website/llms.txt Implements a generic repository pattern for managing data in IndexedDB. Features automatic caching, support for custom keys and secondary indexes, and methods for setting, getting (with cache or forced refresh), querying by index, and deleting data. Includes cache manipulation utilities. ```javascript import createRepository from './db/repository/generic'; // Create repository for player data with inline key and indexes const playerRepository = createRepository( 'players', // store name 'playerId', // inline key field { 'by-name': 'name', 'by-country': 'country' } ); // Set player data const player = { playerId: '76561198059961776', name: 'PlayerName', country: 'US', pp: 15000, rank: 100 }; await playerRepository.set(player); // Get player by key (uses cache if available) const cachedPlayer = await playerRepository.get('76561198059961776'); console.log(cachedPlayer.name); // Force refresh from database const freshPlayer = await playerRepository.get('76561198059961776', true); // Query by index const usPlayers = await playerRepository.getAllFromIndex('by-country', 'US'); console.log(`Found ${usPlayers.length} US players`); // Get single item from index const player = await playerRepository.getFromIndex('by-name', 'PlayerName'); // Get all players (with caching) const allPlayers = await playerRepository.getAll(); // Delete player await playerRepository.delete('76561198059961776'); // Flush all cached data playerRepository.flushCache(); // Manual cache operations playerRepository.setCache(player, player.playerId); playerRepository.addToCache([player1, player2, player3]); ``` -------------------------------- ### Generic API Client for Data Fetching and Processing (JavaScript) Source: https://context7.com/beatleader/beatleader-website/llms.txt A reusable API client that automates data fetching, response caching detection, and request handling. It allows defining custom data fetchers and processors to tailor API interactions. This client supports retrieving raw or processed data and inspecting response metadata like cache status and rate limits. ```javascript import createClient from './network/clients/generic'; import queue from './network/queues/queues'; // Define data fetcher const fetchPlayerData = async ({playerId, priority = queue.PRIORITY.FG_HIGH, ...options}) => { return queue.BEATLEADER_API.player(playerId, priority, options); }; // Define data processor const processPlayerData = (rawData) => { return { ...rawData, displayName: rawData.name, ppFormatted: Math.round(rawData.pp), countryRank: rawData.countryRank || null, processed: true }; }; // Create client const playerClient = createClient(fetchPlayerData, processPlayerData); // Use client with raw data const rawPlayer = await playerClient.get({ playerId: '76561198059961776', priority: queue.PRIORITY.FG_HIGH, fullResponse: false }); console.log(rawPlayer.name, rawPlayer.pp); // Use client with processed data const processedPlayer = await playerClient.getProcessed({ playerId: '76561198059961776', priority: queue.PRIORITY.FG_LOW, fullResponse: false }); console.log(processedPlayer.displayName, processedPlayer.ppFormatted); console.log('Processed:', processedPlayer.processed); // true // Get full response with metadata const fullResponse = await playerClient.getProcessed({ playerId: '76561198059961776', fullResponse: true }); console.log('Cached:', playerClient.isResponseCached(fullResponse)); console.log('Data:', playerClient.getDataFromResponse(fullResponse)); console.log('Rate limit:', fullResponse.rateLimit); // Access processor directly const manuallyProcessed = playerClient.process(rawPlayer); ``` -------------------------------- ### Analyze Top Users by Reaction Source: https://github.com/beatleader/beatleader-website/blob/master/src/pages/process.ipynb This snippet identifies and prints the top 5 users who have reacted to threads, based on reaction counts. It iterates through thread reactions and aggregates users from a dictionary mapping thread names to reactions and their authors. ```python for thread_name in thread_reactions: if reaction in thread_reaction_authors[thread_name]: reaction_users.update(thread_reaction_authors[thread_name][reaction]) print(" Top users:") for user, user_count in reaction_users.most_common(5): print(f" {user}: {user_count} times") print() ``` -------------------------------- ### Fetch Player Data from BeatLeader API Source: https://context7.com/beatleader/beatleader-website/llms.txt Retrieves player statistics and profile information from the BeatLeader API. Supports configurable caching durations (cacheTtl) and data freshness (maxAge), with options for full response including cache metadata. Utilizes a priority queue for request management. ```javascript import createPlayerService from './services/beatleader/player'; const playerService = createPlayerService(); // Fetch player with default caching (20 minutes for regular players, 3 minutes for main player) const player = await playerService.fetchPlayer('76561198059961776', queue.PRIORITY.FG_HIGH, { fullResponse: false, cacheTtl: 60000, // 1 minute cache maxAge: 120000 // Accept cached data up to 2 minutes old }); console.log(player.name, player.pp, player.rank); // Fetch with full response including cache metadata const response = await playerService.fetchPlayer('76561198059961776', queue.PRIORITY.FG_LOW, { fullResponse: true }); if (response.cached) { console.log('Data from cache'); } else { console.log('Fresh data from API'); } console.log('Player data:', response.body); // Force refresh ignoring cache const freshPlayer = await playerService.fetchPlayerOrGetFromCache( '76561198059961776', 0, // maxAge = 0 forces fresh fetch queue.PRIORITY.FG_HIGH, null, true // force = true ); ``` -------------------------------- ### Load and Analyze Discord Data (Python) Source: https://github.com/beatleader/beatleader-website/blob/master/src/pages/process.ipynb Loads Discord data from a JSON file and initiates an analysis of the loaded data. This snippet requires the 'json' library and a function named 'analyze_discord_data' to be defined elsewhere. It takes a file path as input and returns the analyzed data. ```python import json # Assume analyze_discord_data is defined elsewhere # def analyze_discord_data(data): # ... with open('C:\\Users\\vikto\\Desktop\\ForumExport_5.json', 'r', encoding='utf-8') as f: discord_data = json.load(f) analyze_discord_data(discord_data) ``` -------------------------------- ### Fetch Leaderboard Scores from BeatLeader API Source: https://context7.com/beatleader/beatleader-website/llms.txt Retrieves leaderboard scores for a given map ID with support for pagination, filtering (countries, search, friends), and automatic score data processing. Allows fetching raw API responses to access rate limit information. Uses a priority queue and optional AbortSignal for cancellation. ```javascript import leaderboardClient from './network/clients/beatleader/leaderboard/api-leaderboard'; import queue from './network/queues/queues'; // Fetch first page of leaderboard const leaderboard = await leaderboardClient.getProcessed({ leaderboardId: 'x12345', page: 1, filters: { search: '', countries: 'US,CA', friends: false }, priority: queue.PRIORITY.FG_HIGH, cacheTtl: 60000, signal: null // AbortSignal for cancellation }); console.log('Total scores:', leaderboard.scores.length); leaderboard.scores.forEach(score => { console.log(`${score.rank}. ${score.player.name}: ${score.modifiedScore} (${score.accuracy}%)`); }); // Fetch with raw response const rawLeaderboard = await leaderboardClient.get({ leaderboardId: 'x12345', page: 2, filters: {}, priority: queue.PRIORITY.BG_NORMAL, fullResponse: true }); if (!rawLeaderboard.cached) { console.log('Rate limit remaining:', rawLeaderboard.rateLimit.remaining); } ``` -------------------------------- ### Analyze Discord Data with Python Source: https://github.com/beatleader/beatleader-website/blob/master/src/pages/process.ipynb This Python function analyzes Discord data, calculating message counts, word counts, emoji usage, and reaction statistics per author and per thread. It uses the 're' module for text processing and 'collections.Counter' for efficient counting. The function takes a dictionary 'data' representing the Discord threads and messages as input and prints a summary of the analysis. ```python import emoji import re from collections import Counter missing_users_map = { 339903300994596884: "edgii", 596340515947937793: "3psilon9" } def analyze_discord_data(data): # Initialize counters and storage author_message_counts = Counter() author_word_counts = Counter() word_counts = Counter() emoji_counts = Counter() thread_message_counts = Counter() thread_author_messages = {} thread_reaction_counts = Counter() thread_reactions = {} # Store reactions per thread thread_reaction_authors = {} # Store reaction authors per thread author_reaction_counts = Counter() # Track reactions given by each author total_messages = 0 threads = {} # Process each thread for thread in data: thread_name = thread.get("Title", "Unnamed Thread") messages = thread["Messages"] total_messages += len(messages) thread_message_counts[thread_name] = len(messages) thread_author_messages[thread_name] = Counter() threads[thread_name] = thread # Count thread reactions and store per-thread reactions with authors thread_reactions[thread_name] = Counter() thread_reaction_authors[thread_name] = {} if "Reactions" in thread: for reaction in thread["Reactions"]: reaction_name = reaction["Value"] reaction_users = [user["AuthorName"] if user["AuthorName"] else missing_users_map[user["AuthorId"]] if user["AuthorId"] in missing_users_map else str(user["AuthorId"]) for user in reaction["Users"]] reaction_count = len(reaction_users) thread_reaction_counts[reaction_name] += reaction_count thread_reactions[thread_name][reaction_name] = reaction_count thread_reaction_authors[thread_name][reaction_name] = reaction_users # Count reactions per author for user in reaction_users: author_reaction_counts[user] += 1 # Process each message for msg in messages: author_id = msg["AuthorId"] author_name = msg["AuthorName"] if author_id == 1003326182261014568: continue if author_id in missing_users_map: author_name = missing_users_map[author_id] # Count messages per author in this thread author_key = author_name if author_name is not None else str(author_id) thread_author_messages[thread_name][author_key] += 1 # Count messages per author overall author_message_counts[author_name if author_name is not None else author_id] += 1 # Count words if msg["Content"]: # Split into words and convert to lowercase words = re.findall(r'\b\w+\b', msg["Content"].lower()) word_counts.update(words) # Count words per author author_word_counts[author_name if author_name is not None else author_id] += len(words) # Find emojis (both Unicode and Discord custom) # emojis = emoji.emoji_list(msg["Content"]) # emoji_counts.update(e["emoji"] for e in emojis) # Discord custom emojis like <:votePepeYes:970735414325432480> custom_emojis = re.findall(r'<:\w+:\d+>', msg["Content"]) emoji_counts.update(custom_emojis) # Print results print("=== Discord Thread Analysis ===\n") print(f"Total Messages: {total_messages}\n") print("Top 10 Most Active Users by Message Count:") for author_id, count in author_message_counts.most_common(10): print(f"{author_id}: {count} messages") print() print("Top 10 Most Active Users by Word Count:") for author_id, count in author_word_counts.most_common(10): print(f"{author_id}: {count} words") print() print("Top 10 Most Active Users by Reactions Given:") for author_id, count in author_reaction_counts.most_common(10): print(f"{author_id}: {count} reactions") print() print("Top 10 Biggest Threads:") for thread_name, count in thread_message_counts.most_common(10): print(f"{thread_name}: {count} messages; reactions: {', '.join(f'{reaction}: {thread_reaction_authors[thread_name][reaction]}' for reaction in thread_reactions[thread_name])}") for author, msg_count in thread_author_messages[thread_name].most_common(3): print(f" {author}: {msg_count} messages") print() print("Overall Thread Reactions:") for reaction, count in thread_reaction_counts.most_common(): print(f"{reaction}: {count} total reactions") # Print top 5 users who used this reaction reaction_users = Counter() ``` -------------------------------- ### Analyze Top Words with Stop Word Filtering Source: https://github.com/beatleader/beatleader-website/blob/master/src/pages/process.ipynb This code snippet identifies and displays the top 20 most frequently used words from a given word count. It filters out common English stop words and words with a length of 1 or less before counting. It depends on a pre-existing `word_counts` dictionary and the `Counter` class from the `collections` module. ```python # Filter out common words/characters stop_words = {'the', 'is', 'and', 'to', 'a', 'in', 'that', 'it', 'of', 'i', 'you', 'me', 'my', 'have', 'has', 'had', 'will', 'would', 'was', 'now', 'do', 'should', 'can', 'could', 'may', 'might', 'must', 'should', 'would', 'no', 'but', 'for', 'not', 'on', 'if', 'so', 'as', 'at', 'are', 'can', 'one', 'this', 'be', 'https', 'arcviewer'} filtered_words = {word: count for word, count in word_counts.items() if word not in stop_words and len(word) > 1} print("Top 20 Most Used Words:") for word, count in Counter(filtered_words).most_common(20): print(f"'{word}': {count} times") print() ``` -------------------------------- ### Analyze Top Emojis Source: https://github.com/beatleader/beatleader-website/blob/master/src/pages/process.ipynb This snippet displays the top 10 most frequently used emojis based on pre-calculated emoji counts. It assumes an existing `emoji_counts` object, likely a `collections.Counter` or similar structure. ```python print("Top 10 Most Used Emojis:") for emoji_code, count in emoji_counts.most_common(10): print(f"{emoji_code}: {count} times") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.