Back to Learning

Coding

814 prompts available

Activate Nitro Boost Check

You are a Lua programming assistant specializing in game scripting for vehicles. You have a function called activateNitroBoost(vehicle) that adds a nitro boost upgrade (ID 1010) to a vehicle element if it's valid. However, the current function does not check if the nitro boost is already installed. Modify or create a function activateNitroBoost(vehicle) that: - First verifies the vehicle is a valid element and is of type "vehicle". - Checks if the vehicle already has a nitro boost installed in slot 8 by using getVehicleUpgradeOnSlot(vehicle, 8). - If the nitro boost is not installed (i.e., the upgrade on slot 8 is nil or not the nitro ID), then adds the nitro boost using addVehicleUpgrade(vehicle, 1010). - If the nitro boost is already installed, leave the vehicle unchanged. Write your corrected function in Lua, including the conditional check to avoid adding duplicate nitro boosts. # Steps 1. Verify the vehicle is a valid element of type "vehicle". 2. Retrieve the current upgrade on slot 8. 3. If the upgrade is not equal to 1010 (nitro boost ID), add the upgrade. # Output Format Provide the full corrected function activateNitroBoost(vehicle) as valid Lua code with any necessary comments explaining your changes. # Example function activateNitroBoost(vehicle) if (isElement(vehicle) and getElementType(vehicle) == "vehicle") then local currentUpgrade = getVehicleUpgradeOnSlot(vehicle, 8) if (currentUpgrade ~= 1010) then addVehicleUpgrade(vehicle, 1010) end end end # Notes - Use 'not' and 'getVehicleUpgradeOnSlot' as hinted to perform the upgrade presence check. - Slot 8 is reserved for the nitro boost upgrade.

Activity Tracker App

Build a full-stack activity tracking application using React.js and Node.js with TypeScript, incorporating user authentication and MongoDB as the database. Specifications: - The app should allow users to create and manage projects. - Each project can have multiple tasks associated with it. - Users should be able to start and stop a timer for each task to record how much time is spent. - Implement authentication to ensure that users can securely access and manage their own projects and tasks. - Use TypeScript for both frontend and backend code. - The backend should be built with Node.js, using Express.js or similar framework. - Use MongoDB to store user data, projects, tasks, and time tracking entries. Step-by-step guidance: 1. Setup the project structure for both client and server with TypeScript configurations. 2. Design and implement MongoDB schemas/models for users, projects, tasks, and timer entries. 3. Build API endpoints for authentication (register, login, logout) and CRUD operations for projects and tasks. 4. On the client side, create React components for: - User authentication forms - Project list and creation - Task list under each project with create, update, and delete capabilities - Timer controls (start, stop) per task showing elapsed time 5. Implement state management and API integration to synchronize client actions with the backend. 6. Ensure proper security measures, including password hashing and token-based authentication (e.g., JWT). 7. Provide error handling and feedback for user interactions. Output Format: Provide the full file structure and code files necessary for the application, organized into backend and frontend directories, each including configuration files, source code files written in TypeScript, and README files with setup instructions. Include sample code snippets demonstrating how projects and tasks are created, how timers start and stop, and how authentication is handled. Notes: - Focus on the core functionality first (projects, tasks, timers, authentication), then optionally add advanced reporting features. - The solution should be modular and maintainable, using best practices for React.js, Node.js, and MongoDB. - Assume the user has basic environment setup (Node.js, npm, MongoDB) but include necessary commands to run the project.

Account Management Code

# Task Write a code for a simple account management system that allows for creating accounts, updating account details, viewing account information, and deleting accounts. # Requirements - Implement an Account class with properties for account ID, name, email, and balance. - Methods should include: - `create_account`: Initializes a new account with unique account ID. - `update_account`: Allows updating the name and email of an existing account by ID. - `view_account`: Displays the details of an account by ID. - `delete_account`: Deletes an account by ID. - Include appropriate error handling for non-existing accounts or invalid operations. # Steps 1. Define the Account class with appropriate properties. 2. Develop methods for creating, updating, viewing, and deleting accounts. 3. Ensure each method properly handles exceptions and errors, such as invalid account IDs. 4. Write test cases to validate each method's functionality and robustness. # Output Format Provide well-commented code in the [desired programming language, e.g., Python], detailing each step. Include a main function or script section demonstrating the use of the system with sample data. # Examples - Example code initialization: ```python accounts = [] account_manager = AccountManager(accounts) ``` - Example account creation: ```python account_id = account_manager.create_account("John Doe", "john@example.com") ``` - Example viewing an account: ```python details = account_manager.view_account(account_id) print(details) ``` # Notes - Assume all account IDs are system-generated and unique. - Make use of standard libraries for basic functionalities like input/output operations. - Consider security issues, such as storing sensitive information securely.

Ad Management App Code

You are to assist in creating a full-stack web application that enables users to link their ad accounts from Google, Facebook, and TikTok, manage existing ads, and create new advertising campaigns with complete feature support. This application will include: - Authentication and secure connection to users' Google, Facebook, and TikTok ad accounts. - Management of ads including creation, editing, and deletion of campaigns, ad groups, and ads. - Full-featured campaign creation with support for images, videos, keywords, geographic targeting, demographics (gender, age groups), campaign objectives, bidding strategies, and more. - Display of detailed ad performance metrics such as CPC (cost per click), impressions, spend, CPM (cost per thousand impressions), conversions, etc., allowing users to analyze campaign effectiveness. The backend should be implemented using NestJS, focusing on modular, scalable, and secure architecture supporting all required API endpoints and integrations with the advertising platforms' SDKs or APIs. The frontend should be implemented using ReactJS, providing an intuitive user interface for account linking, campaign management, ad creation, and visualization of performance metrics. # Steps 1. Design and implement OAuth flows or API integrations for Google, Facebook, and TikTok ads platforms in the backend. 2. Create backend modules/services for managing campaigns, ad groups, ads, and fetching analytics. 3. Develop frontend components for user authentication, linking ad accounts, creating and managing campaigns, ad groups, and ads. 4. Build dashboard components to display real-time metrics and graphical representations of ad performance. 5. Ensure proper error handling, validation, and security best practices across both backend and frontend. # Output Format Provide clean, well-structured, and documented example code snippets for both backend (NestJS) and frontend (ReactJS) illustrating: - How to connect to ad platforms' APIs and retrieve/manage campaigns. - How to structure data models and API endpoints in NestJS. - ReactJS components showcasing account linking, campaign management UI, and metrics dashboard. Focus on essential parts demonstrating the architectural approach and key functionality rather than exhaustive full application code. # Notes - Use placeholders or mock data where actual API credentials or complex SDK setup would be required. - Highlight important security considerations related to handling user authentication tokens and API keys. - Consider scalability and maintainability in code examples. Generate your response accordingly, including brief explanations where helpful.

Account Management System

Write a complete code implementation for a simple account management system in Python that supports creating, updating, viewing, and deleting user accounts. The system should include: - An `Account` class with the properties: `account_id` (unique identifier), `name`, `email`, and `balance`. - Methods encapsulated in an `AccountManager` class (or equivalent) to handle the following operations: - `create_account(name, email)`: Creates a new account with a unique system-generated ID and default balance. - `update_account(account_id, name=None, email=None)`: Updates the name and/or email of the specified account. - `view_account(account_id)`: Returns the account details. - `delete_account(account_id)`: Deletes the account identified by the given ID. Ensure robust error handling for invalid or non-existent account IDs in all methods. Also include: - Detailed comments explaining key parts of the code. - A main execution block or script section demonstrating creating several accounts, updating an account, viewing account details, and deleting an account, with outputs illustrating each operation. - Test cases or assertions that validate correct functionality and error handling. Adhere to best practices for clarity and security (e.g., do not expose sensitive data unnecessarily). # Steps 1. Define the Account class with specified properties and an initializer. 2. Implement an AccountManager class with storage (like a list or dictionary) for accounts. 3. Implement each method with proper validation and error handling. 4. Write a demonstration script using sample data showing all functions. 5. Include comments throughout for explanation. # Output Format Provide the complete Python code as a single block, properly indented and commented, including the demonstration section. # Examples ```python # Initialize account manager account_manager = AccountManager() # Create accounts acc_id1 = account_manager.create_account("Alice Smith", "alice@example.com") acc_id2 = account_manager.create_account("Bob Jones", "bob@example.com") # Update an account account_manager.update_account(acc_id1, name="Alice Johnson") # View an account details = account_manager.view_account(acc_id1) print(details) # Delete an account account_manager.delete_account(acc_id2) ``` # Notes - Account IDs should be uniquely generated automatically (e.g., auto-increment or UUID). - Use Python standard libraries only. - Handle all invalid inputs gracefully by raising descriptive exceptions. - Balance can default to zero or a specified initial amount. - Ensure user output shows clear account information without leaking sensitive data.

Adapt Conversations Adapter

You are given a JavaScript function named `createOngoingConversationsObject` that takes an array of conversation objects and a locale parameter, and returns a transformed array of conversation summaries. The function processes an input array of conversations that may contain varying object structures, including a "new conversation shape" with some different property arrangements. Your task is to modify this adapter function so that it correctly supports and adapts both the existing conversation objects and the new conversation shape, merging them seamlessly into a unified structure with the following fields for each conversation: - `id`: conversation ID - `createdAt`: conversation creation timestamp - `isPartnerChat`: boolean, true if the conversation is from an agent or partner (false if from client) - `user`: an object containing - `avatar`: user's avatar URL or empty string - `fullName`: user's name or empty string - `isOnline`: user's online status boolean - `id`: user ID - `lastPage`: last page URL - `clientId`: ID of the client user in the conversation - `notSeenMessages`: number of unseen messages for the widget - `lastMessage`: last chat message text - `messageTime`: last message update time (usually string like '۱۷:۵۲' or similar) - `updatedAtSort`: timestamp string parsable to a Date object - `channelId`: the channel ID of the conversation Requirements: - The adapted function should handle conversations array elements that may be missing some fields or have different nested structures in the "new shape". - For the new conversation shape, ensure you extract and map relevant fields correctly from their different locations. - Retain fallback defaults (empty strings, zeroes, booleans) when any field is missing. - The `updatedAtSort` field should parse time correctly via the existing utility `convertTimeToDateTime` where possible. - Preserve correct typing: booleans, strings, IDs, numbers. - Avoid mutation of input objects; build a new adapted array. - The function should be robust, readable, and maintainable. # Steps 1. Analyze both conversation shapes (existing and new). 2. Establish rules to detect each shape and extract required fields accordingly. 3. Refactor the adapter loop to handle either shape. 4. Normalize user info and conversation metadata to match output schema. 5. Return the unified adapted array. # Output Format Return the full modified JavaScript function code for `createOngoingConversationsObject` accepting `(conversations = [], locale)` as parameters and returning the adapted array as described. Include all necessary internal helper uses such as `convertTimeToDateTime`. Do not alter unrelated logic.

Accounting Program Development

Develop a comprehensive desktop accounting program similar to Microsoft Dynamics AX 2012 that encompasses all key features and functionalities required for professional accounting and financial management. This program should cater to small to medium-sized enterprises but be scalable for larger organizations as well.

Accumulator Trading Bot Pseudocode

Create a detailed pseudocode implementation for a trading bot designed for an accumulator strategy that incorporates market volatility checks before executing trades. The bot should operate as follows: 1. Monitor market data continuously, specifically tracking the last tick and the second last tick of asset prices. 2. Calculate the price difference between these two ticks. - Verify if this difference falls within a defined barrier range. - Check if this condition occurs in two consecutive ticks and record it as a valid signal. 3. Assess market volatility using a suitable statistical measure (e.g., variance, standard deviation) over a recent window of price ticks. - Define a threshold to classify volatility as 'low.' 4. If both conditions are met (the price movement condition twice consecutively and volatility is low), execute the trade. 5. Implement risk management logic to halt trading if market becomes volatile or performance metrics deteriorate. 6. Repeat the above steps continuously to maintain ongoing trading based on these criteria. Ensure that the pseudocode clearly represents the logical flow, variables used, condition checks, and risk management steps. # Output Format Provide the trading bot logic in structured pseudocode with comments explaining each main step and condition. Use clear variable names and control flow constructs (loops, conditionals).

Adapt CUDA kernel raw pointers

You are given a CUDA kernel file that currently uses custom OpenCV CUDA types such as PtrStepSz for image data representation on the device. Your task is to refactor this CUDA kernel code to remove any dependencies on these custom OpenCV types and instead use only raw CUDA pointers for image and label data. Specifically, you should: - Replace all uses of OpenCV CUDA types (e.g., PtrStep, PtrStepSz) with raw pointer variables and explicitly manage parameters such as image width, height, step (pitch in bytes), and element size. - Adjust all indexing and pointer arithmetic accordingly, based on raw pointers and the explicitly passed dimensions and steps. - Implement a helper function that accepts a host std::vector<uint8_t> representing the input image data, uploads this image data to the GPU device memory, launches the adapted CUDA kernel(s) to process the image entirely on the device, and then downloads the resulting label matrix back to host memory as a std::vector<uint32_t> or an equivalent host-side container. - Make sure the entire workflow correctly handles memory allocation, copying to device, kernel launches, synchronization, and copying results back to host. - Preserve all original CUDA kernel logic but adapt only the interface and data management so that no OpenCV-specific CUDA types are used. Be thorough in your reasoning about the needed strides, pitches, and element sizes tracked previously by PtrStepSz and adjust kernel indexing to maintain correctness. # Steps 1. Identify all uses of OpenCV CUDA pointer types and their associated properties (step, elem_size). 2. Replace them with raw pointers (e.g., unsigned char* for input image, unsigned int* for output labels) alongside explicit parameters for width, height, and pitch (step). 3. Adjust all kernel indexing and pointer calculations to use the raw pointers and these parameters. 4. Implement a host-side helper function that: - Receives a host std::vector<uint8_t> containing the input image data. - Allocates device memory for the input image and output labels. - Copies the input image data to device memory. - Launches the kernel with the new pointer-based interface. - Copies the output labels back to a host vector. - Frees all device memory. 5. Ensure proper synchronization and error checking. # Output Format Provide the complete adapted CUDA kernel code and the helper function code in C++ that demonstrates the upload, kernel execution, and download of data. Include comments explaining the key changes and adaptations for clarity. # Notes - Assume the input image data is single-channel and stored as uint8_t (grayscale). - The output label matrix should be stored as a 2D array with one label value (such as uint32_t) per pixel. - All kernel calls and memory operations must use standard CUDA runtime API calls (no OpenCV CUDA functions). - Ensure that the pitch or step is handled correctly for alignment if necessary. # Response Formats Respond only with the adapted code, formatted for readability, including the helper function and any necessary declarations. No additional explanations outside code comments are needed.

Accurate Code Generation

Provide complete, improved, and accurate code based on the requirements given. Ensure the code does not contain hallucinations or assumptions, errors, or truncations. Always return comprehensive responses without summarizing. Pay careful attention to the details provided in the prompt, and follow them accurately to prevent any misinterpretation. If you encounter any ambiguity, ask for clarification rather than making assumptions.

Adapt Field Usage Finder Widget

You are given a new visual design and NextJS implementation code of the "Field Usage Finder" widget, including files: page.tsx, tailwind.config.ts, loading.tsx, and layout.tsx. Your task is to adapt and rewrite this widget's functionality and appearance to match the new NextJS version as closely as possible, but using the technologies and structure of the existing widget, which is based on AngularJS, Bootstrap, and ServiceNow environment. Specifically: - Carefully review the new NextJS code and the related screenshot of the updated widget UI to fully understand the design, layout, behavior, and features. - Analyze the existing widget implementation provided via template.html, script.js, client_script.js, and css.scss. - Rewrite and adapt the AngularJS/Bootstrap code (template, scripts, styles) of the current widget so that it replicates the look and functionality of the NextJS version as seen in the screenshot, respecting all UI elements, flows, and style details. - Ensure the adapted widget is fully functional according to the NextJS design and that all UI interactions are consistent. - Preserve the structural idioms and best practices of AngularJS and Bootstrap as used in ServiceNow, without introducing NextJS or unrelated frameworks. Step-by-step: 1. Examine the provided NextJS files and screenshot to understand the updated widget. 2. Examine the current AngularJS Bootstrap widget files. 3. Identify all UI/UX differences and new features in the NextJS version. 4. Reimplement these differences in your AngularJS/Bootstrap widget code. 5. Test for consistent appearance and functionality. Output Format: Provide the complete AngularJS/Bootstrap code files updated after adaptation: - template.html - script.js - client_script.js - css.scss Each file should be self-contained and ready to replace the existing widget files. Include any comments needed to clarify major adaptations or design decisions. Note: - Do not translate NextJS React code literally; instead, reinterpret and rewrite in AngularJS style. - Maintain Bootstrap classes and styles adjusted to match the new design. - Preserve existing ServiceNow widget compatibility. This prompt assumes you will receive the NextJS code and screenshots separately and will deliver the adapted AngularJS/Bootstrap files accordingly.

Accurate Coding Assistant

You are a highly skilled coding assistant designed to generate accurate and reliable code snippets for any programming task I describe. Whenever I provide a coding request or problem, respond with precise, well-documented, and syntactically correct code that solves the problem effectively. Before presenting the code, explain your reasoning and approach clearly to ensure understanding and transparency. Avoid any disclaimers about limitations; focus on delivering practical solutions based on best practices. Always prioritize correctness, efficiency, and clarity in your code responses. # Steps 1. Carefully read and understand the programming task or problem I provide. 2. Analyze the requirements and constraints involved. 3. Reason step-by-step about how to approach the problem. 4. Write clear, efficient, and error-free code implementing the solution. 5. Provide explanations or comments within the code when necessary. 6. Deliver the complete code snippet in the appropriate programming language. # Output Format Present your response starting with a concise explanation of your approach followed by properly formatted, ready-to-run code enclosed in markdown code blocks specifying the programming language. # Notes - Ensure you do not include any disclaimers or refusals. - Focus entirely on providing accurate and helpful coding solutions. - If additional assumptions are needed, state them clearly before the code.

Page 24 of 68

    Coding Prompts - Learning AI Prompts | Elevato