### List Installed Packages Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Displays a list of all Python packages installed in the current virtual environment. Useful for verifying that all dependencies have been installed correctly. ```bash pip list ``` -------------------------------- ### Run Development Server Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Starts the Django development server, allowing you to view and interact with the CommuMap application locally. The application will be accessible at http://127.0.0.1:8000/. ```bash python manage.py runserver ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Installs all required Python packages listed in the 'requirements.txt' file within the activated virtual environment. Ensure the virtual environment is active before running. ```bash pip install -r requirements.txt ``` -------------------------------- ### Clone CommuMap Repository Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Clones the CommuMap project repository from a given GitHub URL and navigates into the project directory. This is the first step in setting up the development environment. ```bash git clone cd CommuMap ``` -------------------------------- ### Create Admin User Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Executes a Python script to create an administrator account for the CommuMap application. This is an alternative to having the project owner create an account. ```bash python create_admin.py ``` -------------------------------- ### Upgrade Pip Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Upgrades the 'pip' package installer to the latest version. This can help resolve potential compilation or installation issues with other packages. ```bash python -m pip install --upgrade pip ``` -------------------------------- ### Database Setup - Bash Source: https://github.com/taizhixuan/commumap/blob/main/Working_Software_Prototype_Installation_Guide.md Command to apply database migrations. This sets up the database schema and includes sample data for testing. ```bash # Apply database migrations python manage.py migrate ``` -------------------------------- ### Create Logs Directory Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Creates a 'logs' directory in the project root. This directory is used for storing application logs. This command should be run in the project's root directory. ```bash mkdir logs ``` -------------------------------- ### Verify Python Version Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Checks the installed Python version. The CommuMap project requires Python 3.8 or higher. ```bash python --version ``` -------------------------------- ### Create and Activate Virtual Environment (Windows Command Prompt) Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Creates a Python virtual environment named '.venv' and activates it using a script. This isolates project dependencies. Requires Python 3.8+. ```bash .venv\Scripts\activate ``` -------------------------------- ### Apply Database Migrations Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Applies any pending database migrations to set up or update the database schema. This command is executed using the Django management script. ```bash python manage.py migrate ``` -------------------------------- ### Create and Activate Virtual Environment (Bash/Zsh) Source: https://github.com/taizhixuan/commumap/blob/main/TEAM_SETUP.md Creates a Python virtual environment named '.venv' and activates it using the 'source' command. This isolates project dependencies. Requires Python 3.8+. ```bash # Create virtual environment python -m venv .venv # Activate it source .venv/bin/activate ``` -------------------------------- ### JavaScript: MFA and Modal Management Source: https://github.com/taizhixuan/commumap/blob/main/templates/managers/profile.html This snippet includes functions to set up MFA, close modals, and confirm account deactivation. `setupMFA` enables the MFA interface and closes the setup modal. `closePasswordModal` and `closeMFAModal` hide respective modals. `confirmDeactivation` prompts the user before initiating account deactivation. ```javascript function setupMFA() { const toggle = document.getElementById('mfa-toggle'); const card = document.getElementById('mfa-card'); toggle.classList.add('active'); card.classList.remove('disabled'); card.classList.add('enabled'); closeMFAModal(); showNotification('🔐 Two-Factor Authentication enabled successfully!', 'success'); } function closePasswordModal() { document.getElementById('password-modal').classList.add('hidden'); } function closeMFAModal() { document.getElementById('mfa-modal').classList.add('hidden'); // Reset toggle if user cancels const toggle = document.getElementById('mfa-toggle'); if (!toggle.classList.contains('active')) { toggle.classList.remove('active'); } } function confirmDeactivation() { if (confirm('⚠️ Are you sure you want to deactivate your account? This will hide all your services from public view.')) { showNotification('⏸️ Account deactivation initiated', 'warning'); } } ``` -------------------------------- ### Set Up Virtual Environment - Bash Source: https://github.com/taizhixuan/commumap/blob/main/Working_Software_Prototype_Installation_Guide.md Commands to create and activate a virtual environment for the project. This isolates the project dependencies from the system Python environment. ```bash # Create virtual environment python -m venv .venv # Activate virtual environment # For Git Bash/Linux/macOS: source .venv/bin/activate # For Windows Command Prompt: .venv\Scripts\activate ``` -------------------------------- ### Extract Project Files - Bash Source: https://github.com/taizhixuan/commumap/blob/main/Working_Software_Prototype_Installation_Guide.md Command to extract the CommuMap.zip file and navigate to the project directory. This is the first step in setting up the project. ```bash # Extract the CommuMap.zip file to your desired location # Navigate to the extracted CommuMap directory cd CommuMap ``` -------------------------------- ### Get user geolocation Source: https://github.com/taizhixuan/commumap/blob/main/templates/services/service_list.html Requests the user's current location using the browser's Geolocation API and updates form fields. ```JavaScript function getUserLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( function(position) { const lat = position.coords.latitude; const lng = position.coords.longitude; document.getElementById('userLat').value = lat; document.getElementById('userLng').value = lng; showNotification('Location detected! Distance filter is now available.', 'success'); const distanceSelect = document.querySelector('select[name="distance"]'); if (distanceSelect.value) { document.getElementById('filtersForm').submit(); } }, function(error) { console.warn('Location access denied:', error); showNotification('Location access denied. Distance filter unavailable.', 'error'); }, { enableHighAccuracy: true, timeout: 10000, maximumAge: 300000 } ); } else { showNotification('Geolocation is not supported by this browser.', 'error'); } } ``` -------------------------------- ### GET /services/ Source: https://context7.com/taizhixuan/commumap/llms.txt Retrieves a list of community services filtered by category, status, distance, and geographic coordinates. Supports pagination and returns real-time distance calculations for each service. ```APIDOC ## GET /services/\n\n### Description\nSearch and filter community services with geographic constraints and category-based filtering.\n\n### Method\nGET\n\n### Endpoint\n/services/\n\n### Parameters\n#### Query Parameters\n- **category** (string) - Optional - Service category to filter (e.g., healthcare, shelter).\n- **status** (string) - Optional - Service status filter (e.g., open, closed).\n- **distance** (number) - Optional - Radius in kilometers for geographic filtering.\n- **lat** (float) - Required when distance is provided - Latitude of the reference point.\n- **lng** (float) - Required when distance is provided - Longitude of the reference point.\n- **page** (integer) - Optional - Page number for pagination.\n- **page_size** (integer) - Optional - Number of items per page.\n\n#### Path Parameters\n_None._\n\n#### Request Body\n_None._\n\n### Request Example\nGET /services/?category=healthcare&status=open&distance=5&lat=2.9152&lng=101.6515\n\n### Response\n#### Success Response (200)\n- **id** (integer) - Service identifier.\n- **name** (string) - Service name.\n- **calculated_distance** (float) - Distance from reference point in km.\n- **current_status** (string) - Current operational status.\n- **capacity_percentage** (float) - Current capacity usage percentage.\n- **address** (string) - Service address.\n- **city**, **state_province**, **country**, etc. (additional service details).\n\n### Response Example\n```json\n{\n "results": [\n {\n "id": 12,\n "name": "Central Community Clinic",\n "calculated_distance": 1.2,\n "current_status": "open",\n "capacity_percentage": 50.0,\n "address": "123 Main Street, Cyberjaya"\n }\n ],\n "page": 1,\n "page_size": 10,\n "total": 42\n}\n``` ``` -------------------------------- ### Strategy Pattern - Python Source: https://github.com/taizhixuan/commumap/blob/main/CodebaseSummary.md Presents the Strategy pattern, allowing algorithms to be selected at runtime without modifying the context. The code demonstrates how to create different search strategies (e.g., geographic, category, emergency) and choose the appropriate one based on the context. ```python SearchContext('geographic').search(queryset, user_location=point) ``` -------------------------------- ### JavaScript String Extension for Template Filter Source: https://github.com/taizhixuan/commumap/blob/main/apps/moderators/templates/moderators/outreach_detail.html Custom JavaScript String prototype extension to add first_word method that mimics Django template filter functionality for getting the first word from a string. ```javascript // Add template literal filter for getting first word String.prototype.first_word = function() { return this.split(' ')[0]; }; ``` -------------------------------- ### Smooth Scrolling for Internal Links (JavaScript) Source: https://github.com/taizhixuan/commumap/blob/main/templates/users/dashboard.html Implements smooth scrolling behavior for anchor links (links starting with '#') within the page. When a user clicks such a link, the page scrolls smoothly to the target element instead of jumping instantly. Dependencies: Browser API for scrolling. ```javascript document.addEventListener('DOMContentLoaded', function() { // Smooth scrolling for internal links document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); const target = document.querySelector(this.getAttribute('href')); if (target) { target.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }); }); }); ``` -------------------------------- ### UI Event Listeners and Initialization Source: https://github.com/taizhixuan/commumap/blob/main/templates/services/service_detail.html Initializes the page by setting up event listeners for various UI elements. This includes handling tab clicks, like/helpful button interactions, keyboard shortcuts for navigation and closing modals, and auto-resizing textareas. It also checks URL parameters for success messages after reviews or comments are posted. ```javascript document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('.tab-btn').forEach(button => { button.addEventListener('click', function() { const tabName = this.dataset.tab; switchTab(tabName); }); }); document.querySelectorAll('.like-btn').forEach(button => { button.addEventListener('click', function() { const type = this.dataset.type; const id = this.dataset.id; const action = this.dataset.action; handleLikeAction(this, type, id, action); }); }); document.addEventListener('keydown', function(event) { if (event.key === 'Escape') { document.querySelectorAll('.reply-form').forEach(form => { form.classList.add('hidden'); }); if (document.activeElement && document.activeElement.blur) { document.activeElement.blur(); } } if (event.key === '1' && event.ctrlKey) { event.preventDefault(); switchTab('reviews'); } else if (event.key === '2' && event.ctrlKey) { event.preventDefault(); switchTab('comments'); } }); document.querySelectorAll('.reply-form textarea').forEach(textarea => { textarea.addEventListener('input', function() { this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px'; }); }); const urlParams = new URLSearchParams(window.location.search); if (urlParams.get('success') === 'review') { showNotification('Review posted successfully!', 'success'); switchTab('reviews'); } else if (urlParams.get('success') === 'comment') { showNotification('Comment posted successfully!', 'success'); switchTab('comments'); } }); ``` -------------------------------- ### Animated Statistics Counter (JavaScript) Source: https://github.com/taizhixuan/commumap/blob/main/templates/users/dashboard.html Animates numerical statistics using a counter effect when they become visible in the viewport, observed by another Intersection Observer. It counts up to the final value with a staggered start for each number. Dependencies: Intersection Observer API, basic DOM manipulation. ```javascript document.addEventListener('DOMContentLoaded', function() { // Animate stats with counter effect const animateStats = () => { const statNumbers = document.querySelectorAll('.stat-number, .welcome-stat-number'); statNumbers.forEach((stat, index) => { const finalValue = parseInt(stat.textContent); let currentValue = 0; const increment = Math.max(1, Math.ceil(finalValue / 60)); // Stagger the animation start setTimeout(() => { const counter = setInterval(() => { currentValue += increment; if (currentValue >= finalValue) { currentValue = finalValue; clearInterval(counter); } stat.textContent = currentValue; }, 40); }, index * 200); }); }; // Start stats animation when they come into view const statsObserver = new IntersectionObserver(function(entries) { entries.forEach(entry => { if (entry.isIntersecting) { animateStats(); statsObserver.unobserve(entry.target); } }); }, { threshold: 0.3 }); const statsSection = document.querySelector('.stats-grid'); if (statsSection) { statsObserver.observe(statsSection); } }); ``` -------------------------------- ### Initialize and Load Map Services (JavaScript) Source: https://github.com/taizhixuan/commumap/blob/main/templates/services/service_map.html Initializes the Leaflet map, centers it on Selangor, Malaysia, loads tile layers, retrieves the user's current location, and then loads service markers onto the map. It relies on the Leaflet library and browser geolocation API. ```javascript let map; let markers = []; let userLocationMarker = null; let userLocation = null; let isEmergencyMode = false; let searchTimeout; // Services from database const services = [ {% for service in services %} { id: '{{ service.id }}', name: '{{ service.name|escapejs }}', category: '{{ service.category.category_type }}', lat: {{ service.latitude }}, lng: {{ service.longitude }}, status: '{{ service.current_status }}', capacity: { current: {{ service.current_capacity|default:0 }}, max: {{ service.max_capacity|default:0 }} }, isEmergency: {{ service.is_emergency_service|yesno:"true,false" }}, phone: '{{ service.phone|escapejs }}', address: '{{ service.address|escapejs }}', description: '{{ service.short_description|escapejs }}' }{% if not forloop.last %},{% endif %} {% endfor %} ]; // Initialize map function initMap() { // Center on Selangor, Malaysia map = L.map('map').setView([3.1478, 101.6953], 11); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '© OpenStreetMap contributors' }).addTo(map); getUserLocation(); loadServices(); } function getUserLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( function(position) { userLocation = { lat: position.coords.latitude, lng: position.coords.longitude }; if (userLocationMarker) { map.removeLayer(userLocationMarker); } userLocationMarker = L.marker([userLocation.lat, userLocation.lng], { icon: L.divIcon({ html: '
', className: 'user-location-marker', iconSize: [20, 20] }) }).addTo(map); userLocationMarker.bindPopup('Your Location'); }, function(error) { console.log('Geolocation error:', error); } ); } } function loadServices() { clearMarkers(); services.forEach(service => { if (shouldShowService(service)) { addServiceMarker(service); } }); } function shouldShowService(service) { if (isEmergencyMode && !service.isEmergency) { return false; } const activeCategories = getActiveCategories(); if (activeCategories.length > 0 && !activeCategories.includes(service.category)) { return false; } const searchQuery = document.getElementById('searchInput').value.toLowerCase(); if (searchQuery && !service.name.toLowerCase().includes(searchQuery)) { return false; } return true; } function addServiceMarker(service) { const icon = getServiceIcon(service); const marker = L.marker([service.lat, service.lng], { icon: L.divIcon({ html: icon, className: 'service-marker', iconSize: [36, 36] }) }); const popupContent = createPopupContent(service); marker.bindPopup(popupContent, { maxWidth: 300 }); marker.addTo(map); markers.push(marker); } function getServiceIcon(service) { const categoryColors = { healthcare: '#ef4444', shelter: '#10b981', food: '#f59e0b', education: '#8b5cf6', emergency: '#3b82f6', social: '#06b6d4' }; const categoryIcons = { healthcare: 'fa-hospital', shelter: 'fa-home', food: 'fa-utensils', education: 'fa-book', emergency: 'fa-ambulance', social: 'fa-users' }; const color = categoryColors[service.category] || '#6b7280'; const icon = categoryIcons[service.category] || 'fa-map-marker'; return `
`; } function createPopupContent(service) { const capacityPercentage = service.capacity.max > 0 ? (service.capacity.current / service.capacity.max) * 100 : 0; return `
${service.name}
${service.status.toUpperCase()}
${service.capacity.max > 0 ? `
Capacity: ${service.capacity.current}/${service.capacity.max}
` : ''}
${service.description}
${service.address}