query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a custom memory allocator in C++ that inherits from a base `Allocator` class. The `Allocator` class has two pure virtual functions that need to be implemented in the derived class. The goal is to create a custom allocator that wraps a system allocator and allows the use of other allocat...
```cpp #include <iostream> #include <cstdlib> // Base Allocator class with pure virtual functions class Allocator { public: virtual void* allocate(size_t size) = 0; virtual void deallocate(void* ptr) = 0; }; // Custom allocator inheriting from the base Allocator class class MySystemAllocator : public Allocato...
magicoder
cpp
You are given two arrays A and B of sizes N and M respectively. You are also given an integer X. Your task is to find the maximum number of elements from array A and array B such that the sum of the selected elements is less than or equal to X. You need to write a function `maxElementsSumLessThanX` that takes in the f...
```cpp int maxElementsSumLessThanX(int N, int M, int X, int A[], int B[]) { sort(A, A + N, greater<int>()); // Sort array A in descending order sort(B, B + M, greater<int>()); // Sort array B in descending order int maxElements = 0; int sum = 0; int i = 0, j = 0; while (i < N && j < M)...
magicoder
cpp
You are tasked with implementing a notification manager for a mobile application. The application receives local notifications, and the notification manager is responsible for handling these notifications. The provided code snippet shows a function that is called when the application receives a local notification. Insi...
```swift class APNSManager { static let shared = APNSManager() private init() {} func application(_ application: UIApplication, didReceive notification: UILocalNotification) { // Handle the received local notification // Example: Print the notification's message if let message = no...
magicoder
swift
You are tasked with implementing a language model using the log-linear model with a softmax function. The model will assign probabilities to sequences of words in a given vocabulary. To facilitate this, you need to define a function that calculates the log probability of a given sequence of words. You are provided wit...
```python from typing import List, Dict def calculate_log_prob(words: List[str], vocab_log_probs: Dict[str, List[float]]) -> float: vocab_size = len(next(iter(vocab_log_probs.values()))) log_prob = 0.0 for i, word in enumerate(words): if word in vocab_log_probs: log_prob += vocab_log_pr...
magicoder
python
You are given the coordinates of two points on a 2D plane, (c1, c2) and (c3, c4). Your task is to write a program to determine the minimum number of moves required to transform one point to the other. The moves are allowed only if the points are on the same line or same diagonal. If the points are already at the same p...
```cpp #include <iostream> #include <cmath> bool sameLine(int c1, int c2, int c3, int c4) { return (c1 == c3) || (c2 == c4); } bool sameDiagonal(int c1, int c2, int c3, int c4) { return (abs(c1 - c3) == abs(c2 - c4)); } int main() { int c1, c2, c3, c4; std::cin >> c1 >> c2 >> c3 >> c4; if (c1 ==...
magicoder
cpp
You are tasked with creating a script that compares two files and removes a temporary file if it exists. Your script should take two file paths as input and perform the following steps: 1. Check if a temporary file named "tmp.tmp" exists in the current directory. 2. If the temporary file exists, remove it. 3. Compare t...
```bash #!/bin/bash # Check if the temporary file exists and remove it if it does if [ -f "tmp.tmp" ]; then rm -f tmp.tmp fi # Check if both input files exist if [ ! -f "$1" ]; then echo "Error: File '$1' does not exist." exit 1 fi if [ ! -f "$2" ]; then echo "Error: File '$2' does not exist." ex...
magicoder
shell
You are tasked with implementing a function that processes a list of integers and returns a new list containing only the unique elements from the original list. Additionally, the function should maintain the order of the unique elements as they appeared in the original list. You are given the following code snippet as...
```rust fn extract_unique_elements(input: Vec<i32>) -> Vec<i32> { let mut unique_elements = Vec::new(); let mut seen = std::collections::HashSet::new(); for num in input { if seen.insert(num) { unique_elements.push(num); } } unique_elements } ``` The `extract_unique_el...
magicoder
rust
You are tasked with implementing a method to apply a set of changes to a list of elements. The list is represented as an immutable copy of the data present in the underlying list at a specific instant, and the changes are provided as a sequence of operations to be applied to the list. You need to create a method `appl...
```swift public struct Update<T> { public var list: LazyCollection<[T]> public var changes: [Change] init(list: [T], changes: [Change]) { self.list = list.lazy self.changes = changes } public func applyChanges() -> [T] { var updatedList = Array(list) // Create a mut...
magicoder
swift
You are tasked with creating a simple class hierarchy for a settings management system in a C# application. The system should allow for the creation of different types of settings, such as text, numeric, and boolean settings, and provide a way to retrieve and update these settings. Create a base class called `Setting`...
```csharp public class Setting { public string Name { get; set; } public string Type { get; set; } public virtual object GetValue() { return null; } public virtual void SetValue(object value) { } } public class TextSetting : Setting { public int MaxLength { get; set; } public override object Ge...
magicoder
csharp
You are tasked with optimizing the performance of a Java program that populates a HashMap with a large number of entries. The provided code snippet demonstrates the current implementation, which measures the time taken to populate the HashMap with 1,000,000,000 entries and then prints the elapsed time. Your task is to...
To optimize the performance of populating the HashMap, we can utilize parallel processing to distribute the workload across multiple threads. This approach can significantly reduce the time taken to populate the HashMap with a large number of entries. Here's a sample solution using Java's parallel streams to populate ...
magicoder
java
You are tasked with implementing a Python function that simulates a simplified version of a command execution system within a container. The function, `exec_command`, takes several parameters including a client, a container, a command to execute, and optional parameters for interactive mode, standard output, standard e...
```python def exec_command( client, container, command, interactive=True, stdout=None, stderr=None, stdin=None): """ Run provided command via exec API in provided container. :param client: Docker client object :param container: Container in which the command will be executed :param command:...
magicoder
python
You are tasked with creating a Python function to manage the conversion of mesh files from one format to another for finite element simulations. The function should handle the conversion of mesh files using external software tools and ensure that the converted files are up to date. You are given the following code sni...
```python import os import sys import time import subprocess def run_command(command): try: subprocess.run(command, shell=True, check=True) return True except subprocess.CalledProcessError: return False def convert_mesh(mesh_file_root): gmsh_app = "gmsh" # Assuming the Gmsh applic...
magicoder
python
You are tasked with implementing a program that manages a collection of classes from different libraries. Each class has a specific name and is associated with a particular library. Your goal is to create a data structure to efficiently store and retrieve these classes, as well as perform operations on them. You are g...
```cpp #include <iostream> #include <unordered_map> #include <vector> #include <string> // Define a structure to represent a class struct ClassInfo { std::string library; // Add any other relevant information about the class }; class ClassManager { private: std::unordered_map<std::string, ClassInfo> class...
magicoder
cpp
You are working on a project to develop a probabilistic programming model for analyzing data. As part of this project, you need to implement a function that samples latent variables from the model. The model is represented as a graph structure, where nodes correspond to random variables and edges represent dependencies...
```python from collections import defaultdict import torch import pyro import pyro.poutine as poutine def sample_latent_variables(model_graph, aux_samples=None, save_params=None): """ Samples latent variables from the probabilistic programming model. :param model_graph: A graph structure representing the ...
magicoder
python
You are tasked with implementing a digital signal processing (DSP) algorithm for creating an audio effect using all-pass filters. All-pass filters are commonly used in audio processing to create phase shifts without affecting the magnitude of the signal. In this problem, you will be working with a TypeScript class that...
```typescript /** * Solution for connecting all-pass filter banks and implementing signal processing logic */ class AudioEffectProcessor { private _bank0: AllPassFilterBank; private _bank1: AllPassFilterBank; private _oneSampleDelay: IIRFilterNode; constructor(options?: Partial<ToneAudioNodeOptions>) { ...
magicoder
typescript
You are tasked with implementing a function to calculate the dates of the vernal equinox day for a given year. The vernal equinox day is the day in spring when the length of day and night are approximately equal. The function should return the date of the vernal equinox day for the given year. The vernal equinox day c...
```python import datetime def _vernal_equinox_day(year): """ Calculate the vernal equinox day for the given year based on the Japanese tradition. Returns the date of the vernal equinox day. """ if 1879 <= year <= 1947: # Calculate vernal equinox day based on the historical method "春季皇霊祭" ...
magicoder
python
You are tasked with creating a module loader for a web application. The module loader should be able to resolve and load modules based on their import statements. Each module is represented by a file with a specific name, and the import statements specify the modules to be loaded. The import statements follow the forma...
```typescript function loadModules(importStatements: string[]): string[] { const modules: string[] = []; const graph: { [key: string]: string[] } = {}; // Parse the import statements and build the dependency graph for (const statement of importStatements) { const moduleName = statement.split('"')[1]; ...
magicoder
typescript
You are tasked with implementing a robot control system for a simulated robot in a robotics competition. The system is responsible for managing the reloading of the robot and handling the driver practice mode. The provided code snippet contains two variables that are crucial for the robot control system: 1. `reloadRob...
```csharp using System; using System.Threading; public class RobotControlSystem { private volatile int reloadRobotInFrames; private bool driverPracticeOn; public void SetReloadDelay(int frames) { reloadRobotInFrames = frames; } public void InitiateReloading() { Thread relo...
magicoder
csharp
You are tasked with implementing a class that manages hooks for player run commands and user messages in a game engine. The provided code snippet is from a method within the `EyeAnglesTester` class, responsible for unloading the hooks associated with this class. The `Unload` method removes the `EyeAnglesTester` instanc...
```cpp #include <vector> class Listener { public: virtual ~Listener() {} }; class HookManager { private: std::vector<Listener*> playerRunCommandListeners; std::vector<Listener*> userMessageListeners; public: void AddPlayerRunCommandListener(Listener* listener) { playerRunCommandListeners.push...
magicoder
cpp
You are working on a Python project that involves file input and output operations. You have come across a code snippet that imports two functions, `objopen` and `gopen`, from a module named `io`. Your task is to create a class that simulates the behavior of these functions for file handling. You need to implement a c...
```python class FileHandler: def __init__(self, file_path): self.file_path = file_path def read_file(self): with open(self.file_path, 'r') as file: content = file.read() return content def write_file(self, content): with open(self.file_path, 'w') as file: ...
magicoder
python
You are tasked with creating a Python function to convert PDF files into images. Your function should take in the directory of the PDF files, the output directory for the images, the DPI (dots per inch) for the images, and an optional parameter for monochrome conversion. The function should utilize the `pdftoppm` execu...
```python import os import subprocess def get_images(pdf_dir: str, output_dir: str, dpi: int, mono: bool = True) -> None: if which("pdftoppm") is None: raise ValueError("Requires executable pdftopmm to be on the PATH") pdf_files = [f for f in os.listdir(pdf_dir) if f.endswith(".pdf")] for pdf_fil...
magicoder
python
You are tasked with creating a Python program to interact with the Cloud Manager API. The Cloud Manager API allows access to programs, pipelines, and environments by an authorized technical account created through the Adobe I/O Console. The base URL for this API is https://cloudmanager.adobe.io. To access the API, you ...
```python import requests def fetch_programs(api_key, organization_id): base_url = "https://cloudmanager.adobe.io" programs_url = f"{base_url}/api/programs" headers = { "x-api-key": api_key, "Authorization": f"Bearer {organization_id}" } try: response = requests.get(program...
magicoder
python
You are tasked with creating a Python script that checks whether the current user has root privileges before executing a specific command. The script should also prompt the user to specify the JDK (Java Development Kit) to be used for a particular operation. The script should handle both the privilege check and JDK spe...
```python import os import getpass def check_and_execute_command(): if os.geteuid() != 0: raise PermissionError("Root or sudo permissions required to execute this command.") jdk_version = input("Specify the JDK version: ") print(f"Executing command with JDK {jdk_version}") # Example usag...
magicoder
python
You are tasked with implementing a custom stack data structure in C#. The stack should support the standard push, pop, and peek operations, as well as a method to retrieve the minimum element in the stack in constant time. You need to design the stack to have O(1) time complexity for all operations. Your task is to im...
```csharp public class MinStack { private Stack<int> stack; private Stack<int> minStack; public MinStack() { stack = new Stack<int>(); minStack = new Stack<int>(); } public void Push(int x) { stack.Push(x); if (minStack.Count == 0 || x <= minStack.Peek()) ...
magicoder
csharp
You are tasked with creating a program that reads a text file and counts the occurrences of each unique word in the file. The program should then output the word and its corresponding count in descending order based on the count. Additionally, the program should exclude common stop words such as "the", "and", "of", etc...
```python import re from collections import Counter # Define the list of stop words stop_words = {"the", "and", "of", "it", "is", "for", "in", "on", "to", "a"} # Read the content of the text file with open("sample.txt", "r") as file: text = file.read() # Remove non-alphabetic characters and convert text to lower...
magicoder
python
You are tasked with creating a program that simulates a simple file management system. The program should be able to handle basic file operations such as creating, deleting, and listing files. Additionally, it should support the concept of directories to organize files. Your task is to implement a function `handleComm...
```python class FileManagementSystem: def __init__(self): self.current_directory = "root" self.directory_structure = {"root": []} def handleCommand(self, command): command_parts = command.split() operation = command_parts[0] if operation == "CREATE": file_na...
magicoder
python
You are tasked with implementing a function that calculates the total cost of a shopping cart, taking into account any applicable discounts. The function should take a list of items in the cart and a dictionary of discount codes, and return the total cost after applying any relevant discounts. Each item in the cart is ...
```python from typing import List, Tuple, Dict def calculate_total_cost(cart: List[Tuple[str, float]], discount_codes: Dict[str, float]) -> float: total_cost = sum(item[1] for item in cart) # Calculate the total cost without any discounts discount = 0.0 # Initialize discount as 0 for code, percentage in...
magicoder
python
You are tasked with creating a Python class to manage video capture devices using the OpenCV library. Your class should support the ability to add and remove video capture devices dynamically. The class should also provide a method to capture frames from all connected devices simultaneously. Your task is to implement ...
```python import cv2 class VideoCaptureManager: def __init__(self): self.devices = [] def add_device(self, device_id): self.devices.append(cv2.VideoCapture(device_id)) def remove_device(self, device_id): for device in self.devices: if device.get(cv2.CAP_PROP_POS_MSEC) ...
magicoder
python
You are tasked with creating a Python function that processes a dynamic state of infrastructure nodes to identify failed nodes and nodes to be removed. The dynamic state is represented as a nested dictionary, and the function should extract information from it to determine the failed and remove nodes. The dynamic stat...
```python def process_nodes(self, infra_id, infobroker): dynamic_state = infobroker.get('infrastructure.state', infra_id, True) datalog.debug('%r', dynamic_state) log.debug('Processing failed nodes in %r', infra_id) nodes = [node for instances in dynamic_state.values() for nod...
magicoder
python
You are tasked with implementing a status tracking system for a software application. The status can be one of the following: `kStatusIdx`, `kStatusLoaded`, or `kStatusResolving`. Each status has an associated integer value: 1 for `kStatusIdx`, 2 for `kStatusLoaded`, and 3 for `kStatusResolving`. Your goal is to create...
```python class StatusTracker: def __init__(self): self.current_status = 1 # Default status is kStatusIdx def set_status(self, status): if status in [1, 2, 3]: self.current_status = status else: raise ValueError("Invalid status value") def get_status(self):...
magicoder
python
You are tasked with implementing a Python decorator that logs the execution time of a function. The decorator should print the name of the function and the time taken for execution in milliseconds. You are given a code snippet that uses the decorator `method_decorator` to apply the logging functionality to a function c...
```python import time def log_execution_time(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() execution_time = (end_time - start_time) * 1000 # Convert to milliseconds print(f"Function '{func.__name__}' exec...
magicoder
python
You are tasked with implementing a file-saving mechanism for a 3D mapping process in a robotics application. The provided code snippet is part of a larger program responsible for mapping and logging the robot's pose estimation and 3D scene view. The code snippet shows a conditional block that saves the pose log informa...
```cpp #include <iostream> #include <string> #include "mapBuilder.h" // Assuming the mapBuilder object is defined in a separate header file void saveMappingData(bool SAVE_POSE_LOG, const std::string& OUT_DIR, int LOG_FREQUENCY, bool SAVE_3D_SCENE, int step, MapBuilder& mapBuilder) { if (SAVE_POSE_LOG) { s...
magicoder
cpp
You are tasked with creating a Python program to retrieve transaction data from a REST API and perform analysis on the obtained JSON response. The API endpoint and query parameters are provided in the code snippet below. Your program should make a GET request to the specified URL with the given query parameters, extrac...
```python import requests url = "http://api-gateway-dbs-techtrek.ap-southeast-1.elasticbeanstalk.com/transactions/10" querystring = {"from": "01-01-2019", "to": "01-31-2019"} headers = { 'identity': "Group11", 'token': "<PASSWORD>", 'cache-control': "no-cache", 'Postman-Token': "<PASSWORD>" } try: ...
magicoder
python
You are working on a linear programming problem solver and need to implement a function to handle the pivot operation in the simplex method. The pivot operation involves selecting a pivot element in the tableau and performing row operations to update the tableau to its next iteration. The tableau is represented as a ma...
```cpp void pivotOperation(double** tableau, int enteringVar, int leavingVar, int numRows, int numCols) { // Perform row operations to update the tableau double pivotElement = tableau[leavingVar][enteringVar]; // Make the pivot element 1 for (int j = 0; j < numCols; j++) { tableau[leavingVa...
magicoder
cpp
You are tasked with implementing a function that selects prize winners for a conference based on a list of tickets. Each ticket contains information about the attendee, including their name, email, and a unique identifier (slug). The function should iterate through the list of tickets and select prize winners based on ...
```python from typing import List, Dict, Union class Conference: def __init__(self, name): self.name = name class PrizeWinner: def __init__(self, name, email): self.name = name self.email = email def select_prize_winners(tickets: List[Dict[str, Union[str, int]]], conf: Conference) -> ...
magicoder
python
You are tasked with creating a function that processes scene configurations for a multi-scene iOS application. The function should take in a list of scene configurations and return the names of the configurations that have a specific session role. Write a function `filterSceneConfigurations` that takes in two paramete...
```swift func filterSceneConfigurations(_ configurations: [(name: String, sessionRole: String)], sessionRole: String) -> [String] { return configurations.filter { $0.sessionRole == sessionRole }.map { $0.name } } ```
magicoder
swift
You are tasked with implementing a hyperparameter tuning algorithm for a machine learning model. The algorithm uses grid search to find the optimal learning rate and L2 regularization parameter for the model. The learning rate (lr) is a hyperparameter that controls the step size during the model's training, and the L2 ...
```python learning_rates = [0.001, 0.01, 0.1] # Define the learning rates to be evaluated lambda_l2_values = [0.00001, 0.0001, 0.001] # Define the L2 regularization parameter values to be evaluated # Perform grid search over learning rates and L2 regularization parameters for lr in learning_rates: for lambda_l2 ...
magicoder
python
You are tasked with creating a Python class for managing image classification experiments. Your class should be able to set up a model, train it, save the trained model, and load the saved model for further use. You will need to implement the necessary methods to achieve these functionalities. Your class should have t...
```python import os import json from pathlib import Path class ImageClassifier: def __init__(self): self.model = None def set_up_model(self, param_file_path, data_directory): # Implement model setup logic using the experiment configuration and data directory # Example: Read experiment ...
magicoder
python
You are tasked with creating a program that simulates a simplified version of a Docker container initialization process. In this scenario, you are given a list of tasks that need to be executed in a specific order. Each task has a name and a list of its dependencies. Your goal is to implement a function that determines...
```python def initialize_tasks(tasks): task_map = {task.name: task for task in tasks} visited = set() result = [] def dfs(task_name): if task_name in visited: return visited.add(task_name) for dependency in task_map[task_name].dependencies: dfs(dependency...
magicoder
python
You are tasked with implementing a function that simulates a race between two asynchronous tasks. The function should return the result of the first task to complete, while canceling the other task. You are given the following code snippet as a reference: ```swift import PromiseKit6 class RaceTests: XCTestCase { ...
```swift import PromiseKit func raceTasks<T>(_ task1: @escaping () -> Promise<T>, _ task2: @escaping () -> Promise<T>) -> Promise<T> { return Promise<T> { seal in var task1Completed = false var task2Completed = false let task1Promise = task1().done { result in if !task2...
magicoder
swift
You are tasked with implementing a function to handle email notifications for a city-based service. The function should handle different scenarios based on the city's settings and the user's email address. The function should also utilize a deferred task queue for sending emails. You are given the following code snipp...
```python from google.appengine.ext import deferred def handle_email_notifications(cirklo_city, data, language): if cirklo_city.get_signup_accepted_mail(language) is None: raise HttpBadRequestException('City settings aren\'t fully setup yet.') else: whitelist_merchant(cirklo_city.city_id, data[...
magicoder
python
You are tasked with implementing a custom layer in a neural network model using the Keras library in Python. The provided code snippet is a part of a larger neural network architecture and demonstrates the addition of a batch normalization layer, activation function, and dropout layer to the model. Your task is to cre...
```python import tensorflow as tf from tensorflow.keras import layers, models class CustomLayer(layers.Layer): def __init__(self, emb_num, dropout_rate): super(CustomLayer, self).__init__() self.emb_num = emb_num self.dropout_rate = dropout_rate self.batch_norm = layers.BatchNormal...
magicoder
python
You are tasked with creating a Python program that simulates a simple student management system. The program should be able to perform various operations such as adding new courses, displaying the current working directory, and printing today's date. Additionally, the program should be able to generate a random number ...
```python import random as r import math import datetime import os def generate_random_number(start, end): random_num = r.randint(start, end) print(f"Random number between {start} and {end}: {random_num}") def calculate_square_root(number): square_root = math.sqrt(number) print(f"Square root of {numbe...
magicoder
python
You are tasked with creating a JavaScript function that makes an asynchronous request to a server using jQuery's `$.get` method and updates the content of a specified HTML element with the received data. Write a function `updatePageContent` that takes in two parameters: 1. `url` (string): The URL to send the GET reque...
```javascript function updatePageContent(url, pageId) { $("#page_builder").html(""); // Clear the content of the HTML element $.get(url, { name: 'rows', page: pageId }, function (data) { $("#page_builder").html(data); // Update the content with the received data }); } ```
magicoder
javascript
You are tasked with creating a web form that allows users to input a date and then submit the form to perform a search. The provided code snippet is a part of the HTML form and includes an input field for the date and a submit button. Your task is to write the JavaScript code that will handle the form submission and p...
```javascript document.getElementById('submit_busca_simples').addEventListener('click', function() { var inputDate = document.getElementById('ds_nome_razao_social').value; // Perform input validation if necessary // Send an asynchronous request to the server var xhr = new XMLHttpRequest(); xhr.ope...
magicoder
javascript
You are tasked with creating a Python program to visualize data using the Plotly library. The code snippet provided initializes a new figure using the Plotly library. Your task is to extend this code to create a program that generates a line plot with multiple traces. Your program should perform the following steps: 1...
```python import plotly.graph_objects as go import numpy as np # Create x-values ranging from 0 to 10 with a step size of 0.1 x_values = np.arange(0, 10.1, 0.1) # Define the three functions def curve1(x): return x ** 2 def curve2(x): return 2 * x + 5 def curve3(x): return 10 * np.sin(x) # Create the fi...
magicoder
python
You are tasked with implementing a custom useContextFile hook in a React application. The useContextFile hook is responsible for managing the state of a file context and providing methods to interact with it. The hook should allow setting the current file using a provided key and handle any errors that may occur during...
```javascript import { useState } from 'react'; const useContextFile = () => { const [response, setResponse] = useState(null); const [error, setError] = useState(null); const setCurrent = (key) => { try { // Perform the logic to set the current file based on the provided key // Example: const fi...
magicoder
javascript
You are tasked with implementing a simple iOS app that manages a list of objects. The provided code snippet is from the `MasterViewController` of the app, which is responsible for displaying the list of objects and allowing users to add new objects. Your task is to complete the implementation by adding the `insertNewO...
```swift @objc func insertNewObject(_ sender: Any) { let newObject = // create a new object, e.g., a custom data model or a simple string objects.insert(newObject, at: 0) let indexPath = IndexPath(row: 0, section: 0) tableView.insertRows(at: [indexPath], with: .automatic) if let detailViewController...
magicoder
swift
You are tasked with creating a script to automate the installation of PhantomJS, a headless web browser, on a Linux system. PhantomJS is often used for tasks such as automated testing, screen capturing, page automation, and network monitoring. The provided code snippet is a part of a script that aims to install Phantom...
```bash # Update RubyGems system and install Bundler before_install: - gem update --system - gem install bundler # Install necessary dependencies for PhantomJS addons: apt: packages: - libcurl4-openssl-dev - libfontconfig # Install PhantomJS install: - rm -rf $PWD/travis_phantomjs; mkdir -p $P...
magicoder
shell
You are tasked with creating a Python program that validates the presence of a specific entry point in a `pyproject.toml` file. The `pyproject.toml` file is a configuration file commonly used in Python projects, and it contains various project metadata and settings. Your program should read the `pyproject.toml` file, p...
```python import toml from pathlib import Path # Constants PROJECT_ROOT = Path("/path/to/project/root") # Replace with actual project root path PYPROJECT_TOML_FILENAME = "pyproject.toml" ENTRY_POINT = "my_script" class PyprojectToml: def __init__(self, **kwargs): for key, value in kwargs.items(): ...
magicoder
python
You are tasked with implementing a gRPC client for the Google Ads API in Python. The provided code snippet is a part of the client setup for making a unary unary call to the `MutateCampaignBidModifiers` method of the `CampaignBidModifierService`. Your task is to complete the implementation of the gRPC client by writin...
```python import grpc import google.ads.googleads.v4.services.campaign_bid_modifier_service_pb2 as campaign_bid_modifier_service_pb2 import google.ads.googleads.v4.services.campaign_bid_modifier_service_pb2_grpc as campaign_bid_modifier_service_pb2_grpc def make_campaign_bid_modifiers_request(): # Create a gRPC ch...
magicoder
python
You are tasked with implementing a program to perform quaternion arithmetic operations. Quaternions are an extension of complex numbers and are represented as a 4-tuple (w, x, y, z), where w, x, y, and z are real numbers. Quaternion arithmetic involves addition, subtraction, multiplication, and conjugation operations. ...
```python from typing import List def performQuaternionOperation(q1: List[float], q2: List[float], operation: str) -> List[float]: if operation == "add": return [q1[0] + q2[0], q1[1] + q2[1], q1[2] + q2[2], q1[3] + q2[3]] elif operation == "subtract": return [q1[0] - q2[0], q1[1] - q2[1], q1[2]...
magicoder
python
You are tasked with implementing a class to track the performance of a trading strategy. The class, named `TradingPerformance`, should have the following functionalities: 1. Track the total number of wins and losses. 2. Calculate the total profit from winning trades in euros. 3. Calculate the total loss from losing tr...
```python class TradingPerformance: def __init__(self): self.winCount = 0 self.lossCount = 0 self.sumWinEuro = 0 self.sumLoss = 0 self.maxLoss = float('-inf') def record_trade(self, result, resultEuro): if result > 0: self.winCount += 1 se...
magicoder
python
You are tasked with creating a Rust module that interacts with a hardware device. The module should handle errors and provide a clean interface for interacting with the device. Your task is to implement the missing parts of the module to ensure it meets the requirements. You are provided with the following code snippe...
```rust // device.rs use crate::error::DeviceError; pub struct Device { // Define the necessary fields to interact with the hardware device } impl Device { pub fn new() -> Result<Device, DeviceError> { // Implement the initialization logic for the device, handle any potential errors } pub fn ...
magicoder
rust
You are given the definition of a singly linked list node in C++: ```cpp #include <iostream> struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; ``` Your task is to implement a function `reverseList` that takes the head of a singly linked list as input and ret...
```cpp ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; ListNode* next = nullptr; while (curr != nullptr) { next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev; } ``` The `reverseList` function i...
magicoder
cpp
You are tasked with implementing a TypeScript class that manages anonymous consents for a web application. The class should provide methods for handling anonymous consents, and it should enforce access control by using TypeScript's access modifiers. You are given a code snippet that shows the constructor of the class,...
```typescript import { AnonymousConsentsService } from 'path-to-anonymous-consents-service'; class AnonymousConsentsManager { protected anonymousConsentsService: AnonymousConsentsService; constructor(anonymousConsentsService: AnonymousConsentsService) { this.anonymousConsentsService = anonymousConsentsService...
magicoder
typescript
You are tasked with implementing a function that takes a string as input and returns the count of unique characters in the string. For the purpose of this problem, consider uppercase and lowercase letters as distinct characters. You should ignore any non-alphabetic characters and count only the unique alphabetic charac...
```python def countUniqueCharacters(s): unique_chars = set() for char in s: if char.isalpha(): unique_chars.add(char.lower()) return len(unique_chars) # Test the function input_str = "Hello, World!" print(countUniqueCharacters(input_str)) # Output: 7 ```
magicoder
python
You are tasked with implementing a function that processes a hierarchical category tree and generates an HTML unordered list (ul) with list items (li) for each category. Each list item should include the category's ID, title, and action links for editing and deleting the category. The function should handle nested cate...
```php public function update_category() { return $this->tree_ul; } ``` The `update_category` method simply returns the concatenated HTML string stored in the class variable `$this->tree_ul`. This variable holds the entire HTML structure of the category tree, including the unordered list and its list items with ca...
magicoder
php
You are tasked with creating a TypeScript function that merges multiple objects into a single object. The function should take an arbitrary number of objects as arguments and return a new object containing all the key-value pairs from the input objects. If there are duplicate keys, the value from the last object in the...
```typescript function mergeObjects(...objects: object[]): object { return Object.assign({}, ...objects); } // Test the function const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const obj3 = { c: 5, d: 6 }; const mergedObj = mergeObjects(obj1, obj2, obj3); console.log(mergedObj); // Output: { a: 1, b: 3, c...
magicoder
typescript
You are working on a Python web application project that follows the modular design pattern. The project structure includes several modules, each containing related functionality. The code snippet provided is from the main application file, where modules are being imported using relative imports. Your task is to creat...
```python import importlib def execute_module_function(module_name, function_name): try: module = importlib.import_module('.' + module_name, package=__package__) if hasattr(module, function_name): function = getattr(module, function_name) return function() else: ...
magicoder
python
You are tasked with implementing a Python function to generate an ISO 0 TDES PIN block with Visa PVV encryption. The PIN block is to be created using the provided PIN and account number, and then encrypted using a specified key. You are given the following code snippet as a reference: ```python pb3 = pinblock.Iso0TDE...
```python from typing import Tuple from cryptography.hazmat.primitives import padding from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend def generate_iso0_tdes_pin_block(pin: str, accoun...
magicoder
python
You are tasked with creating a custom template tag in a Django web application that retrieves and displays the web path for a given URL. The web paths are stored in the `WebPath` model, and each web path is associated with a specific `WebSite`. The custom template tag should take a URL as input and return the correspon...
```python # Import necessary modules from django import template from cms.contexts.models import WebPath, WebSite # Register the template library register = template.Library() # Define the custom template tag @register.simple_tag def get_web_path(url): # Get the current website's domain current_domain = "exam...
magicoder
python
You are tasked with implementing a JSON schema validator for a specific subset of JSON schemas. The schemas in this subset define fixed-size arrays and simple key-value pairs. The fixed-size arrays are defined using a special syntax, where the first element is the word "vector" followed by a colon and then the type of ...
```rust use regex::Regex; fn validate_json_schema(schema: &str) -> bool { let fixed_array_regex = Regex::new(r#""fixed"\s*:\s*\[\s*"vector",\s*"\d+:\w+"\s*(,\s*"\d+:\w+"\s*)*\]"#).unwrap(); let key_value_regex = Regex::new(r#""\w+"\s*:\s*"\d+:\w+""#).unwrap(); fixed_array_regex.is_match(schema) && key_val...
magicoder
rust
You are working on a machine learning project and need to preprocess a dataset for training. One of the preprocessing steps involves loading a subset of the dataset into a TensorFlow tensor. The provided code snippet demonstrates the loading process using the `load_from_tf_tensor` method. The method takes a TensorFlow ...
```python import tensorflow as tf def generate_random_tensor(batch_size, feature_num): return tf.random.normal(shape=[batch_size, feature_num + 1]) ``` The `generate_random_tensor` function uses TensorFlow's `tf.random.normal` method to create a tensor with random normal values of the specified shape `[batch_size,...
magicoder
python
You are tasked with creating a program that processes a contact list and performs various operations on it. Each contact in the list is represented by a dictionary with the following keys: "name", "email", and "phone". The program should provide functionality to add a new contact, remove an existing contact, search for...
```python import re class Contact: def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone class ContactList: def __init__(self): self.contacts = [] def add_contact(self, name, email, phone): contact = Contact(name, email, pho...
magicoder
python
You are tasked with creating a Python class that facilitates secure file transfer using the paramiko library. The class should include a method `connect_by_key` that establishes an SFTP connection to a remote host using a private key for authentication. The `connect_by_key` method should take the following parameters:...
```python import paramiko class SecureFileTransfer: def __init__(self): self.__sftp = None def connect_by_key(self, host, port, uname, key_path, key_pass=''): try: key = paramiko.RSAKey.from_private_key_file(key_path, key_pass) transport = paramiko.Transport((host, port...
magicoder
python
You are tasked with creating a Python script to process geospatial data using the GDAL library. The script should take an input VRT (Virtual Raster) file and generate a set of map tiles suitable for use in a web mapping application. The specific requirements for the script are as follows: - Input: The script should ta...
```python import sys from osgeo import gdal def generate_map_tiles(input_vrt, output_dir): gdal.UseExceptions() options = [ '-p', 'raster', '-s', 'simple', '-w', 'leaflet', '--xyz', input_vrt, output_dir ] gdal.SetConfigOption('GDAL_PAM_ENABLED'...
magicoder
python
You are tasked with implementing a custom data structure to store font information for a text editor. The font information includes the typeface (font) and size. You need to create a Swift structure to represent this font information and provide a method to encode it into a JSON format using the `Codable` protocol. Yo...
```swift // MARK: - FontInfo Structure struct FontInfo: Codable { let font: String let size: Int // MARK: - Private CodingKeys Enumeration private enum CodingKeys: String, CodingKey { case font = "typeface" case size = "size" } } // Example Usage let fontInfo = FontInfo(f...
magicoder
swift
You are tasked with implementing a function that generates a grid layout for displaying items based on a given list and schema. The function should take in two optional parameters: `list`, which represents the items to be displayed, and `schema`, which defines the layout structure of the grid. The `list` parameter is ...
```javascript function generateGridLayout({ list = [], schema = [] }) { return ( <div className="grid grid-cols-3 gap-5"> {list.map((item, index) => ( <div key={item.id} className={`col-span-1 w-${schema[index].width} text-center`} > <h3>{item.name}</h3> ...
magicoder
javascript
You are tasked with creating a program that parses a given license identifier and determines whether it complies with a set of acceptable licenses. The license identifier is a string that may contain one or more license names separated by "OR" or "AND" operators. Each license name may be followed by a version number. T...
```python import re def validate_license(license_identifier, acceptable_licenses): # Extracting license names from the identifier licenses = re.findall(r'\b[\w-]+(?:\.\d+)?\b', license_identifier) # Checking if any of the acceptable licenses is present in the extracted licenses for operator in ["O...
magicoder
python
You are tasked with creating a program that processes a series of input numbers and outputs them in a specific format. The program should take four integer inputs and format them as a space-separated string of four-digit numbers, with leading zeros added as necessary. Write a program that takes four integer inputs and...
```java import java.util.Scanner; public class NumberFormatter { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int firstNum = Integer.parseInt(scanner.nextLine()); int secondNum = Integer.parseInt(scanner.nextLine()); int thirdNum = Integer.pars...
magicoder
java
You are tasked with implementing a method to extract the parent name from a given file path. The parent name is defined as the substring following the last occurrence of the dot ('.') character in the path. For example, given the path "com.example.utils.FileUtil", the parent name would be "FileUtil". Write a Java meth...
```java public class PathUtil { /** * Returns the last node in the path. * * @param path the input path * @return the last node in the path. */ public static String getParentName(final String path) { return path.substring(path.lastIndexOf('.') + 1); } } ``` The `getParentNa...
magicoder
java
You are tasked with creating a Python script to automate the installation of specific Python packages on a Databricks cluster. The script should read a list of Python package names and versions from a file and install them on the specified Databricks cluster using the Databricks CLI commands. Your task is to write a P...
```python import subprocess def install_packages_on_cluster(cluster_id, package_file_path): with open(package_file_path, 'r') as file: package_list = file.readlines() for package in package_list: package = package.strip() subprocess.run(['databricks', 'libraries', 'install', '--cluster...
magicoder
python
You are tasked with creating a Python class for building a neural network model using the Keras library. Your class should include methods for initializing the model, compiling it, and training it on a given dataset. The class should also have the ability to make predictions using the trained model. Your task is to im...
```python from keras.models import Sequential from keras.layers import Dense class NeuralNetwork: def __init__(self, layer_sizes, activation): self.layer_sizes = layer_sizes self.activation = activation self.model = None def build_model(self, input_dim): self.model = Sequential...
magicoder
python
You are tasked with writing a script to automate the configuration of a server's network settings. The script should check for the presence of an IP address and a fully qualified domain name (FQDN), and if either is missing, it should provide guidance for resolving the issue. Your script should perform the following t...
```bash #!/bin/bash # Check if IP variable is empty if [ -z "$IP" ] ; then # Obtain IP address of the default gateway interface IP=$(ip addr show dev $(route -n | awk '/^0\.0\.0\.0/{print $NF}') | awk '/inet / {print $2}' | head -1 | sed "s;/.*;;") fi # Check if FQDN is empty if [[ "$(hostname -f 2>/dev/null)" ==...
magicoder
shell
You are tasked with creating a Rust program that simulates a distributed key generation (DKG) process for a group of clients. The DKG process involves a set of clients collaborating to generate a shared public key without any single client being able to determine the private key on its own. Your task is to implement t...
```rust // Define the DKGWorker struct struct DKGWorker { id: u32, threshold: u32, num_clients: u32, shares: Vec<Option<u64>>, } impl DKGWorker { // Constructor method for DKGWorker fn new(id: u32, threshold: u32, num_clients: u32) -> DKGWorker { DKGWorker { id, ...
magicoder
rust
You are tasked with implementing a function that simulates the behavior of a simple text-based game. The game involves a player navigating through a series of positions represented by an array of strings. The player's position is tracked by an index within the array. The player can move left or right within the array, ...
```javascript function movePlayer(positions, steps) { const numPositions = positions.length; let newPositionIndex = (positions.findIndex((pos) => pos === "A") + steps) % numPositions; if (newPositionIndex < 0) { newPositionIndex += numPositions; } return positions[newPositionIndex]; } ``` The `movePlayer...
magicoder
javascript
You are working on a cheminformatics project and need to implement a Tanimoto similarity score calculation for molecular structures represented as SMILES strings. The Tanimoto similarity score is a measure of similarity between two sets, often used in cheminformatics to compare molecular fingerprints. In this problem, ...
```python from rdkit import Chem from rdkit.Chem import AllChem def get_ECFP4(mol): return AllChem.GetMorganFingerprint(mol, 2) def TanimotoSimilarity(fp1, fp2): return DataStructs.TanimotoSimilarity(fp1, fp2) def decoder(selfie): # Implementation of the decoder function to convert selfie to SMILES p...
magicoder
python
You are working on a distributed computing project using PyTorch and need to create a distributed subset of indices for a dataset. To achieve this, you decide to use the `create_distributed_subset_indices` function from the `pytorch_pfn_extras.distributed._dataset_util` module. However, you encounter an issue with the ...
The unexpected behavior of the `create_distributed_subset_indices` function could be due to various reasons. Here are some potential causes and solutions to address the issue: 1. Incorrect Input Parameters: - Check if the input parameters provided to the `create_distributed_subset_indices` function are correct. Ens...
magicoder
python
You are tasked with implementing a class for handling binary input and output streams in a programming language. The class should provide methods for creating input/output binary streams from file names and existing input binary streams. You need to implement the `SubLInOutBinaryStream` class with the following method...
```java import java.io.File; import java.io.IOException; public class SubLInOutBinaryStream { private String fileName; private SubLInputBinaryStream inStream; public SubLInOutBinaryStream(String fileName, SubLSymbol ifExists, SubLSymbol ifNotExists) { this.fileName = fileName; try { ...
magicoder
java
You are tasked with implementing a production system for a strategy game. The system should handle the production of buildings and units. The provided code snippet is a simplified representation of the production system's constructor and a method to retrieve the currently producing entity. Your task is to extend the p...
```java public class Building implements Producible { // Implementation of the Building class } public class Unit implements Producible { // Implementation of the Unit class } public class Main { public static void main(String[] args) { ProductionSystem productionSystem = new ProductionSystem(new ...
magicoder
java
You are given a nested list containing integers and strings. Your task is to write a function that recursively flattens the nested list into a single list, preserving the order of elements. For example, given the input: ``` input_list = [[[1, 2]], [[1, 2]], [[['Goodbye'], {'Great': 'Job'}], [['Goodbye']]]] ``` The exp...
```python def flatten_nested_list(input_list): result = [] for item in input_list: if isinstance(item, list): result.extend(flatten_nested_list(item)) else: result.append(item) return result ``` The `flatten_nested_list` function recursively processes each element of...
magicoder
python
You are tasked with implementing a function that checks whether a given string is a valid C++ preprocessor directive. A valid preprocessor directive in C++ starts with a `#` symbol followed by a keyword, such as `ifdef`, `ifndef`, `define`, `include`, etc. The keyword is case-insensitive and may be followed by optional...
```cpp #include <iostream> #include <string> #include <cctype> bool isValidPreprocessorDirective(const std::string& directive) { if (directive.empty() || directive[0] != '#') { return false; } size_t pos = 1; while (pos < directive.size() && std::isspace(directive[pos])) { pos++; }...
magicoder
cpp
You are working on a network protocol analyzer tool that processes Server Message Block version 1 (SMB1) packets. The tool uses Rust programming language and the `smb1_trans_response_record` function to handle SMB1 transaction response records. Your task is to implement a function that parses the SMB1 transaction respo...
```rust #[derive(Debug)] struct SMBTransResponseData { total_parameter_count: u16, total_data_count: u16, parameter_offset: u16, parameter_displacement: u16, data_count: u16, data_offset: u16, } #[derive(Debug)] enum ParseError { IncompleteData, InvalidData, } fn parse_smb_trans_respon...
magicoder
rust
You are tasked with creating a program to process and display sales data from a database. The given code snippet is a part of a PHP script that generates a table to display sales information. The script retrieves data from a database and populates the table with details such as the date of sale, invoice number, item na...
```php <?php // Assuming database connection and query execution // Replace the database connection details and query with actual values // Database connection details $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "sales_db"; // Create connection $conn = new mysqli($servername, ...
magicoder
php
You are tasked with optimizing the given code snippet, which processes a catalog of images in parallel using multiprocessing. The current implementation divides the catalog into subunits based on the number of processes and then processes each subunit independently. However, the current implementation does not efficien...
```python import cv2 from multiprocessing import Pool from functools import partial def process_image(image_info): img = cv2.imread(image_info['path']) vec = get_gist_C_implementation(img) return image_info['path'], vec def getfeat(start, end, use_tqdm=False): with Pool() as pool: image_infos ...
magicoder
python
You are given an array `A` of integers. Write a function that rearranges the array such that all the odd elements appear at even indices (0-based indexing) in the array. The function should return the modified array. If there are multiple possible rearrangements, return any one of them. The function signature is: ```p...
```python from typing import List def rearrange_odd_elements(A: List[int]) -> List[int]: res = [0] * len(A) i = 0 for x in A: if x % 2 == 1: res[i] = x i += 2 return res ``` The solution initializes a result array `res` with the same length as the input array `A`. It the...
magicoder
python
You are tasked with implementing a gadget factory system for a fictional company that produces various electronic components. The company has a requirement to declare and manage different types of gadgets using a standardized format. The provided code snippet is a part of this system and demonstrates the declaration of...
```python class GadgetFactory: def __init__(self): self.registered_gadgets = {} def register_gadget(self, gadget_name, gadget_class): self.registered_gadgets[gadget_name] = gadget_class def create_gadget(self, gadget_name, *args, **kwargs): if gadget_name in self.registered_gadgets...
magicoder
python
You are tasked with creating a Python function to strip white space from various data structures. The function should handle notebooks, files, and text content. The function should be able to strip white space from code cells in a notebook, text content in a file, and general text content. Create a function `strip_whi...
```python def strip_white_space(data, content_type): def strip_text(text): return text.strip() if content_type == 'notebook': for cell in data['content']['cells']: if cell['cell_type'] == 'code': cell['source'] = strip_text(cell['source']) elif content_type == 'f...
magicoder
python
You are tasked with simulating the motion of a sphere falling through a fluid under the influence of gravity. The sphere's velocity and position will be updated at each time step using the Euler method. The relevant physical parameters are as follows: - V: Volume of the sphere (in cubic meters) - rho_f: Density of the ...
```python import math def simulate_motion(initial_velocity, initial_position, time_step, total_time): # Physical parameters V = 0.1 # Volume of the sphere in cubic meters rho_f = 1000 # Density of the fluid in kg/m^3 g = 9.81 # Acceleration due to gravity in m/s^2 rho_s = 500 # Density of the s...
magicoder
python
You are tasked with creating a serverless function that takes a JSON payload containing a person's name and returns a greeting message. The function will be triggered by an HTTP request and should write the greeting message to a designated response file. You are provided with a code snippet that partially implements t...
```python import json import os def handler(req, res): try: postreqdata = json.loads(req) name = postreqdata['name'] greeting_message = "hello world from " + name with open(os.environ['res'], 'w') as response_file: response_file.write(greeting_message) return "Gr...
magicoder
python
You are tasked with implementing a performance monitoring system for a computational software framework. The given code snippet is a part of the monitoring system and is responsible for printing out the function evaluations, derivative evaluations, and errors after running a computational problem. Your task is to crea...
```python class ComputationalComponent: def __init__(self, name): self.name = name self.exec_count = 0 self.derivative_exec_count = 0 def run(self): # Simulate running the computational component self.exec_count += 1 self.derivative_exec_count += 1 class Perform...
magicoder
python
You are tasked with implementing a function that processes input events related to mouse actions. The function takes an enum `mev` representing different mouse events and returns a formatted string based on the event type and associated parameters. The enum `mev` has three variants: `Press`, `Release`, and `Hold`. The ...
```rust // Define the enum representing mouse events enum MouseEvent { Press(u8, i32, i32), Release(i32, i32), Hold(i32, i32), } // Function to obtain the representation of a mouse button fn repr_mouse_button(b: u8) -> Option<String> { // Implementation of repr_mouse_button function is not provided ...
magicoder
rust
You are given a Python class `Solution` with a method `XXX` that takes an integer `num` as input. The method initializes a list `values` containing integer values representing Roman numeral symbols. Your task is to implement the logic inside the `XXX` method to convert the given integer `num` into its corresponding Rom...
```python class Solution: def XXX(self, num: int) -> str: values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] symbols = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'] result = '' for i in range(len(values)): while num >= values[i]: ...
magicoder
python
You are tasked with implementing a class for managing network base stations in a wireless communication system. The class should handle various quality of service (QoS) parameters and be capable of creating a conceptual graph representing the network slice. You are given a code snippet that sets up a test case for the...
```python class SliceConceptualGraph: def __init__(self, name, midhaul_qos, backhaul_qos, parameters): self.name = name self.midhaul_qos = midhaul_qos self.backhaul_qos = backhaul_qos self.best_qos = parameters['best_qos'] self.worst_qos = parameters['worst_qos'] self...
magicoder
python
You are tasked with implementing a Python function that takes a list of integers as input and returns the count of unique elements in the list. A unique element is defined as an element that appears only once in the list. You should not use any built-in Python libraries or functions that directly solve this problem. T...
```python from typing import List def count_unique_elements(arr: List[int]) -> int: unique_elements = set() repeated_elements = set() for num in arr: if num in unique_elements: unique_elements.remove(num) repeated_elements.add(num) elif num not in repeated_eleme...
magicoder
python
You are given a sequence of integers representing the positions of holes on a road. The goal is to determine the minimum number of patches required to cover all the holes using patches of length L. A patch can cover a range from position x to position x+L. If a hole cannot be covered by any existing patch, a new patch ...
```cpp #include <iostream> #include <vector> using namespace std; int minPatches(int N, int L, vector<int>& holes) { int patches = 0; long long ini = 0, actual; int i = 0; while (ini < N) { if (i < N && holes[i] <= ini + L) { actual = holes[i]; i++; } else { ...
magicoder
cpp
You are given a list of integers representing the scores of a game. The game has a special rule for scoring where the score of each player is the sum of their scores in the current round and the previous two rounds. If there are not enough previous rounds to calculate the score, the player's score for that round is the...
```python from typing import List def calculate_total_scores(scores: List[int]) -> List[int]: total_scores = [] for i in range(len(scores)): if i == 0: total_scores.append(scores[i]) elif i == 1: total_scores.append(scores[i-1] + scores[i]) else: tota...
magicoder
python
You are given a positive integer `n`. Your task is to write a function `max_digit_removal(n)` that finds the maximum possible integer that can be obtained by removing exactly one digit from `n`. The function should return the maximum integer that can be obtained by removing any one digit from `n`. For example, given ...
```python def max_digit_removal(n): s = str(n) # Convert the integer to a string # Generate all possible integers by removing one digit at a time and find the maximum return max(int('{}{}'.format(s[:i], s[i+1:])) for i in range(len(s))) ``` The `max_digit_removal` function first converts the input integer...
magicoder
python
You are tasked with implementing a secure token generation system for a client management application. The system should generate a unique token for each new client added to the database. The token should be a random string of 20 characters, consisting of uppercase letters, lowercase letters, and digits. You are provi...
```python import random import string def generate_token(): tmp = "" characters = string.ascii_letters + string.digits for _ in range(20): tmp += random.choice(characters) return tmp def add_client(): log.info('Controller add_clients starts') if request.method == 'POST': # Proc...
magicoder
python