query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a DNS message parser in Rust. The DNS message format is defined in RFC 1035, and the parser should be able to extract specific fields from a DNS message. Your task is to implement a function `parse_dns_message` that takes a byte array representing a DNS message and returns a tuple cont...
```rust fn parse_dns_message(message: &[u8]) -> Option<(String, String)> { // Extract domain name from question section let domain_start = 12; // Start of question section let mut domain_end = domain_start; while message[domain_end] != 0 { domain_end += 1; } let domain_bytes = &message[d...
magicoder
rust
You are working on a text processing tool that involves several methods and classes. One of the methods, `fixUniCode`, is responsible for fixing any Unicode issues in the input text. Another method, `clean`, is used to clean the input text. Additionally, there is a class `req` with a method `run` that processes the inp...
```python class MainClass: def __init__(self, view, edit, t): self.view = view self.edit = edit self.t = t def fixUniCode(self, text): # Implement the fixUniCode method to fix any Unicode issues in the input text # Example implementation: # return text.encode('la...
magicoder
python
You are tasked with implementing a Python class that simulates a simple network connection. The class, named `NetworkConnection`, should have the following functionality: 1. A method `log_info(info)` that takes a string `info` as input and logs it to the console. 2. An attribute `_conectado` (misspelled intentionally)...
```python class NetworkConnection: def __init__(self): self._conectado = False def log_info(self, info): print(info) def get_conectado(self): return self._conectado def set_conectado(self, value): self._conectado = value # Usage connection = NetworkConnection() connec...
magicoder
python
You are given an array of integers `arr`. Your task is to implement a function that sorts the array in non-decreasing order using a specific sorting algorithm. The sorting algorithm works as follows: 1. Find the minimum value in the array. 2. Swap the minimum value with the first element of the array. 3. Repeat the abo...
```python from typing import List def custom_sort(arr: List[int]) -> List[int]: n = len(arr) for i in range(n): min_index = i for j in range(i+1, n): if arr[j] < arr[min_index]: min_index = j arr[i], arr[min_index] = arr[min_index], arr[i] return arr ```
magicoder
python
You are tasked with implementing a class that manages exam properties for a school management system. The class, `ExamManager`, should have the following functionalities: 1. A method `setPropNames` that takes a string `propNames` as input and sets it as the property names for the exam. 2. A method `getProp` that retur...
```java import java.util.ArrayList; import java.util.List; class ExamProp { private String name; private String value; public ExamProp(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public String getVa...
magicoder
java
You are tasked with implementing a Python class that represents a mathematical concept called a "Vector Field." A vector field is a function that assigns a vector to each point in a subset of space. Your task is to complete the implementation of the VectorField class by adding a method that calculates the magnitude of ...
```python class VectorField: def __init__(self, phi): self._phi = phi def magnitude_at_point(self, point): if len(point) != len(self._phi): raise ValueError("Point dimension does not match vector field dimension") magnitude_squared = sum(component ** 2 for component...
magicoder
python
You are tasked with creating a program that processes the output of the `samtools stats` command, which is used to generate statistics for a SAM (Sequence Alignment/Map) file. The `samtools stats` command produces a detailed report containing various statistics related to the alignment and mapping of sequences. Your pr...
```python import re def parse_samtools_stats(stats_report): stats_dict = {} pattern = r"SN\s+(.+):\s+(\d+|\d+\.\d+)%?" matches = re.findall(pattern, stats_report) for match in matches: key = match[0].strip().replace(" ", "_") value = float(match[1]) if '.' in match[1] else int(matc...
magicoder
python
You are tasked with implementing a function that calculates the time elapsed between two given dates in a human-readable format. The function should take two date objects as input and return a string representing the time elapsed in a human-friendly manner, such as "3 days ago" or "1 year ago". You are provided with a...
```swift import Foundation func timeAgoSinceDate(_ date: Date, currentDate: Date) -> String { let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date, to: currentDate) if let years = components.year, years > 0 { return yea...
magicoder
swift
You are working on a machine learning project using PyTorch and distributed computing. Your task is to implement a custom loss function for a specific scenario. The code snippet provided initializes predicted and ground truth tensors on a specific GPU device. You need to create a custom loss function that calculates th...
```python import torch import torch.distributed as dist def custom_loss_function(y_pred, y): if dist.get_rank() == 1: criterion = torch.nn.MSELoss() loss = criterion(y_pred, y) return loss else: return None # Return None for processes other than rank 1 ``` In the solution, we ...
magicoder
python
You are tasked with creating a program that simulates a simple CSS parser. Given a string representing a set of CSS rules, your program should extract and display the selectors and their corresponding properties. Write a function `parseCSS` that takes a string `cssString` as input and returns an object representing th...
```javascript function parseCSS(cssString) { const rules = cssString.split('\n').filter(rule => rule.trim() !== ''); // Split the string into individual rules const parsedCSS = {}; // Object to store parsed CSS rules rules.forEach(rule => { const [selector, properties] = rule.split('{').map(part =>...
magicoder
javascript
You are tasked with creating a Python class that simulates a simple vending machine. The vending machine should be able to stock items, display available items, accept coins, and dispense items based on the user's selection and the amount of money inserted. Your task is to implement the VendingMachine class with the f...
```python class VendingMachine: def __init__(self): self.stock = {} self.balance = 0 def stock_item(self, item_name, price, quantity): if item_name in self.stock: self.stock[item_name]['quantity'] += quantity else: self.stock[item_name] = {'price': price,...
magicoder
python
You are tasked with implementing a Python class that represents a deck of playing cards. The class should have methods for shuffling the deck, dealing a single card, and dealing a hand of cards. Each card in the deck should be represented as a string in the format "RANKSUIT", where RANK is a single character representi...
```python import random class Deck: def __init__(self): ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] suits = ['H', 'D', 'C', 'S'] self.cards = [rank + suit for suit in suits for rank in ranks] def shuffle(self): random.shuffle(self.cards) def ...
magicoder
python
You are tasked with creating a program to detect faces in an image using the dlib library in Python. The `detect_faces_from_image` function takes an image in RGB format as input and returns a list of coordinates representing the detected faces. The coordinates are in the format `[left, top, right, bottom]`, where `left...
```python import dlib class FaceDetector: def __init__(self, model_path): self.detector = dlib.get_frontal_face_detector() self.sp = dlib.shape_predictor(model_path) def detect_faces_from_image(self, image_RGB): # Detect faces using dlib library dlib_rectangles = self.detector(...
magicoder
python
You are given a positive integer `n`. Your task is to determine whether `n` can be expressed as a perfect power of a certain number. A perfect power is a positive integer that can be expressed as an integer raised to some positive integer power greater than 1. For example, 16 is a perfect power because it can be expres...
```python def isPerfectPower(n): if n == 1: return (1, 1) for base in range(2, int(n ** 0.5) + 1): exponent = 2 while base ** exponent <= n: if base ** exponent == n: return (base, exponent) exponent += 1 if n < 0: for base in range(2...
magicoder
python
You are given a DNA sequence as a string `seq` and an integer `w`. Your task is to write a function that finds the starting positions of all the occurrences of a specific pattern within the DNA sequence. The pattern is defined as a substring of length `w`. The function should return a list of starting positions (0-inde...
```python from typing import List def find_pattern_positions(seq: str, w: int, pattern: str) -> List[int]: positions = [] for i in range(len(seq) - w + 1): if seq[i:i+w] == pattern: positions.append(i) return positions ``` The `find_pattern_positions` function iterates through the DNA ...
magicoder
python
You are working on a data processing module for a social media analytics platform. The module is responsible for analyzing user engagement with posts and determining whether a post has received positive engagement based on certain criteria. You are given a snippet of code from the module, which processes the data and a...
```python import numpy as np import pandas as pd class DataProcessor: def __init__(self, df, window_size, react_size, positive_range, target): self.df = df self.window_size = window_size self.react_size = react_size self.positive_range = positive_range self.target = target ...
magicoder
python
You are tasked with creating a web application that allows users to upload an image and then uses facial recognition to detect and recognize faces in the image. You need to implement the backend logic for this application using Python and Flask. Your task is to complete the function `recognise_faces_in_image(file)` wh...
```python # Import necessary libraries from flask import Flask, request import face_recognition import numpy as np from PIL import Image, ImageDraw app = Flask(__name__) def allowed_file(filename): # Function to check if the file type is allowed ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} return '....
magicoder
python
You are tasked with implementing a simplified event dispatcher for a UDP (User Datagram Protocol) transport layer in Rust. The event dispatcher will be responsible for managing and dispatching events received over UDP. Your task is to implement the `UdpEventDispatcher` struct and its associated methods. The `UdpEventD...
```rust use std::net::{UdpSocket, SocketAddr}; use std::thread; // Define the Event enum enum Event { PacketReceived(Vec<u8>), Error(String), } // Define the UdpEventDispatcher struct struct UdpEventDispatcher { socket: UdpSocket, } impl UdpEventDispatcher { // Create a new instance of UdpEventDispat...
magicoder
rust
You are given a string `str` containing digits. Your task is to determine if the string contains the substring "21" or if the integer value represented by the string is divisible by 21. If either condition is met, print "The streak is broken!". Write a function or method that takes a string as input and performs the r...
```java public static void checkStreak(String str) { if (str.contains("21") || (Integer.parseInt(str) % 21 == 0)) { System.out.println("The streak is broken!"); } } ```
magicoder
java
You are given a code snippet that appears to be part of a program for handling localization keys and comments. The code snippet includes a conditional statement that checks for the presence of non-empty comments and performs certain actions based on the conditions. Your task is to understand the logic and requirements ...
```swift struct LineKey { let locKey: String let env: String let filename: String let index: Int let comment: String let userInfo: [String: Any] let userReadableGroupComment: String } func mergeComments(_ key1: LineKey, _ key2: LineKey, _ useNonEmptyCommentIfOneEmptyTheOtherNot: Bool) -> Li...
magicoder
swift
You are tasked with implementing a simple Observable pattern in Swift. An Observable is an object that allows other objects, called Observers, to subscribe to changes in its state. When the state of the Observable changes, it notifies all subscribed Observers. Your task is to implement the `Observable` class with the ...
```swift // Observable.swift class Observable<T> { typealias Observer = (T) -> Void var value: T? { didSet { notifyObservers() } } private var observers: [Observer] = [] func subscribe(_ observer: @escaping Observer) { observers.append(observer) ...
magicoder
swift
You are tasked with creating a Python class that implements a custom logging system. The class should have the ability to log messages at different levels and direct the log output to different handlers. Your task is to implement the `CustomLogger` class with the following specifications: - The class should have a con...
```python from logging import getLogger, StreamHandler, DEBUG class CustomLogger: def __init__(self, name): self.logger = getLogger(name) def add_stream_handler(self): stream_handler = StreamHandler() self.logger.addHandler(stream_handler) def set_log_level(self, level): s...
magicoder
python
You are tasked with creating a program that simulates a simple calculator. The program should prompt the user to input an operation and two values to be operated on. The operations supported are addition, subtraction, multiplication, and division. The user can input the operation as a word or symbol (e.g., "plus" or "+...
```cpp #include <iostream> #include <string> using namespace std; int main() { cout << "Provide an operation and two values you'd like operated on:\n"; string operatus; double val1; double val2; cin >> operatus >> val1 >> val2; double result = 0; if (operatus == "+" || operatus == "plus") ...
magicoder
cpp
You are working on a system monitoring application that collects and logs inventory snapshots from various hosts. The application uses an underlying implementation (`impl`) to perform these operations. The `inventory_collect` function is used to collect inventory snapshots, and the `snmp_inventory_log` function is used...
```cpp #include <iostream> #include <cstring> // Assume the definition of opal_buffer_t and ORTE_ERROR_LOG function // Define the error code #define ORCM_ERR_NOT_AVAILABLE 1 class InventoryManager { private: // Assume the definition of impl and its methods public: InventoryManager() { // Initialize ...
magicoder
cpp
You are tasked with implementing a function to calculate the view matrix for a virtual camera in a 3D scene. The view matrix is used to transform world coordinates into camera coordinates and is a crucial component in 3D graphics rendering. The view matrix is typically created using the "lookAt" function, which takes ...
```cpp #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> glm::mat4 calculateViewMatrix(glm::vec3 pos, glm::vec3 target, glm::vec3 up) { return glm::lookAt(pos, target, up); } ``` The `calculateViewMatrix` function simply uses the `glm::lookAt` function to create the view matrix based on the provided c...
magicoder
cpp
You are tasked with implementing a function that parses an HTML table and extracts the column headers. The HTML table is represented as a string, and the column headers are enclosed within `<th>` tags. Each `<th>` tag may contain attributes such as `bgcolor` and `style`. Your task is to extract the text content of the ...
```python from bs4 import BeautifulSoup from typing import List def extract_column_headers(html_table: str) -> List[str]: soup = BeautifulSoup(html_table, 'html.parser') headers = soup.find('tr').find_all('th') column_headers = [header.get_text() for header in headers] return column_headers ``` The `e...
magicoder
python
You are tasked with implementing a program to format and display a table of student names and their corresponding scores. The program should utilize the `std::setw` and `std::left` manipulators from the C++ iostream library to align the output in a visually appealing manner. Your task is to write a C++ program that t...
```cpp #include <iostream> #include <iomanip> #include <vector> #include <string> struct Student { std::string name; int score; }; void displayStudentTable(const std::vector<Student>& students) { std::cout << std::setw(15) << std::left << "Student" << "Score" << std::endl; for (const auto& student : s...
magicoder
cpp
You are tasked with implementing a Python decorator that logs the execution time of a function. The decorator should use the `logging` module to log the execution time in milliseconds. You should also create a sample function and apply the decorator to it to demonstrate its functionality. Your task is to create a deco...
```python import logging import time from functools import wraps LOGGER = logging.getLogger(__name__) def log_execution_time(func): @wraps(func) def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() execution_time_ms = (end...
magicoder
python
You are tasked with implementing a function that calculates the gradient with respect to the inputs of a convolutional neural network (CNN) during the backward pass. The function takes in a cache of values from the forward pass and returns the gradient with respect to the inputs. You are given the following informatio...
```python def calculate_input_gradient(cache): # Retrieve necessary values from the cache x, w, dout, stride, pad = cache # Get dimensions of input and weights N, C, H, W = x.shape F, _, HH, WW = w.shape # Initialize the gradient with respect to the input dx = np.zeros_like(x) # Pad t...
magicoder
python
You are tasked with creating a parallel computing program to evaluate a costly mathematical function using the Message Passing Interface (MPI) in Python. The given code snippet is a part of the worker process in the parallel computing program. Your task is to complete the implementation of the worker process and write ...
```python from mpi4py import MPI from learning_objective.hidden_function import evaluate, get_settings import numpy as np comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() def worker_process(rank): lim_domain = get_settings(lim_domain_only=True) domain_size = lim_domain[1] - lim_domain[0] ...
magicoder
python
You are working on a project that involves implementing a convolutional neural network (CNN) for image classification. As part of this project, you need to understand and implement the concept of convolutional layers and pooling operations. Given the following code snippet from a CNN implementation using a deep learn...
In the given code snippet, the operations being performed are typical operations found in a convolutional neural network (CNN). Let's break down each line of code and explain its significance in the context of a CNN: 1. `h = F.relu(self.conv3_2(h))`: - Here, `self.conv3_2` represents a convolutional layer in the n...
magicoder
python
You are working on a project that involves managing dependencies and operations for database migrations. In this scenario, you are given a list of dependencies and a series of migration operations. Your task is to write a function that processes these dependencies and operations to determine the order in which the migr...
```python from collections import defaultdict def resolve_migration_order(dependencies, operations): # Create a dictionary to store the dependencies for each app dependency_map = defaultdict(list) for app, version in dependencies: dependency_map[app].append(version) # Create a dictionary to st...
magicoder
python
You are given a directed graph represented as a collection of nodes and edges. Each edge has an associated weight, and the graph may contain cycles. Your task is to implement a function to find the shortest path from a given source node to a target node using Dijkstra's algorithm. The Dijkstra's algorithm is an algori...
```python import heapq def dijkstra_shortest_path(graph, source, target): # Initialize distances with infinity for all nodes except the source distances = {node: float('inf') for node in graph} distances[source] = 0 # Initialize the priority queue with the source node queue = [(0, source, [])] ...
magicoder
python
You are given a binary tree represented by a structure `TreeNode` with pointers to its left and right children. Your task is to write a function `convert` that takes the root of the binary tree as input and converts the tree into a modified form. The function should return a pair of pointers, where the first pointer po...
```cpp #include <utility> struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; pair<TreeNode*, TreeNode*> convert(TreeNode* root) { if (root == nullptr) { return {nullptr, nullptr}; } if (root->left != nullptr) {...
magicoder
cpp
You are tasked with implementing a cross-platform file save dialog feature for a desktop application. The provided code snippet outlines the initial structure for this feature, including the use of asynchronous communication and platform-specific code. Your task is to design a system that allows the application to dis...
To solve this problem, you can start by implementing the platform-specific code for opening the save panel. Below is a sample solution that demonstrates the implementation for macOS and Windows: ```rust use oneshot::{Receiver, RecvError}; use std::path::{PathBuf, Path}; use std::sync::mpsc::channel; use std::thread; ...
magicoder
rust
You are tasked with creating a Python module that manages different machine learning algorithms for a recommendation system. The module should include classes for a cost model, grid search, collaborative filtering, and logistic regression. Each class should have specific functionalities and attributes to handle differe...
```python # recommendation_system.py class CostModel: def __init__(self): # Initialize cost model attributes pass def calculate_cost(self, data): # Calculate the cost function based on the input data pass def optimize_cost(self, parameters): # Optimize the cost fun...
magicoder
python
You are tasked with creating a C++ function that processes a list of strings and returns the count of strings that contain a specific substring. Your function should be able to handle cases where the substring appears multiple times within a single string. Write a function `countSubstringOccurrences` that takes in the...
```cpp #include <iostream> #include <vector> #include <string> int countSubstringOccurrences(const std::vector<std::string>& inputStrings, const std::string& substring) { int count = 0; for (const std::string& str : inputStrings) { size_t pos = 0; while ((pos = str.find(substring, pos)) != std:...
magicoder
cpp
You are tasked with creating a Python function that simulates the behavior of the `subprocess.run` function for executing shell commands. Your function should take a list of command-line arguments and return a dictionary containing the command's output, error, and return code. Your function should be named `simulate_s...
```python import subprocess def simulate_subprocess_run(command): result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return { 'stdout': result.stdout.decode('utf-8'), 'stderr': result.stderr.decode('utf-8'), 'returncode': result.returncode } ``` In this...
magicoder
python
You are tasked with simulating the behavior of a GSM module's method for obtaining an IP address. The GSM module has a method `gprs_getIPAddress` that takes a `FeedbackInterface` object as a parameter. The `FeedbackInterface` object contains a timer, a boolean flag `blocked`, and a function `ResponseListener` that retu...
```cpp #include <iostream> #include <string> enum class Reply { OK_ }; class FeedbackInterface { public: unsigned long timerStart; bool blocked; bool ResponseListener(const std::string& reply, FeedbackInterface& fi) { // Simulated ResponseListener logic return (reply == "OK") ? true : fals...
magicoder
cpp
You are given a snippet of PHP code that manipulates the value of the variable `$start`. Your task is to implement a function that simulates the behavior of the given code snippet. The function should take three parameters: `$start`, `$n`, and `$step`, and return the updated value of `$start` based on the conditions sp...
```php function updateStart($start, $n, $step) { if ($step > 0) { $start += $step; } elseif ($start < 0) { $start = $n - min(abs($start), $n); } else { $start = $n - abs($start); } return $start; } ```
magicoder
php
You are tasked with creating a program that simulates the execution of a test suite for a build tool. The build tool uses a custom DSL (Domain Specific Language) to define and execute tests. The DSL consists of commands enclosed in quotes, where each command represents a specific action to be performed during the test ...
```python def simulate_test_suite(commands): for command in commands: if command.startswith("start test"): test_name = command.split('"')[1] print(f"Starting test: {test_name}") elif command.startswith("runSbt"): project_path = command.split('"')[1] pr...
magicoder
python
You are tasked with implementing a simple file system navigation tool. Given a sequence of commands, each representing a file system operation, your program should determine the final directory that the user would be in after executing all the commands. The commands are as follows: - `cd <directory>`: Move into the spe...
```python from typing import List def final_directory(initial_directory: str, commands: List[str]) -> str: current_directory = initial_directory.split('/') for command in commands: if command == "fi": current_directory = current_directory[:-1] # Move up one level else: ...
magicoder
python
You are tasked with creating a Python program that analyzes the dependencies of a given Python package. The program should take a package name as input and then determine all the direct and transitive dependencies of that package. A package's dependencies are defined in a dictionary where the keys are package names and...
```python def find_dependencies(dependencies, package): direct_dependencies = dependencies.get(package, []) transitive_dependencies = [] def get_transitive_deps(pkg): nonlocal transitive_dependencies for dep in dependencies.get(pkg, []): if dep not in transitive_dependencies...
magicoder
python
You are tasked with implementing a function to validate the workload for L2 normalization in the ArmNN library. The function `ClL2NormalizationWorkloadValidate` takes in the input tensor information and validates it for the L2 normalization workload on the Arm Compute Library for OpenCL. The function signature is as f...
```cpp arm_compute::Status ClL2NormalizationWorkloadValidate(const TensorInfo& input, { // Check if the input tensor is valid if (!input.is_resizable() || input.data_layout() != DataLayout::NHWC) { return arm_compute::Status(arm_compute::ErrorCode::RUNTIME_ERROR, "Invalid input tensor"); } ...
magicoder
cpp
You are tasked with simulating a simplified CPU instruction for a hypothetical opcode. The opcode in question is Opcode::SHL { vx }, which is part of a larger CPU instruction set. When this opcode is executed, it performs a left shift operation on the value stored in a specific register (vx) of the CPU. Additionally, i...
```rust struct CPU { regs: [u8; 16], // Array of 16 general-purpose registers } impl CPU { fn execute_shl(&mut self, vx: usize) { // Perform left shift operation on the value in register vx self.regs[0xF] = (self.regs[vx] & 0b10000000) >> 7; // Store the value of the shifted bit in the carry fl...
magicoder
rust
You are tasked with implementing a function to handle the deserialization of a WebSocket object within a larger system. The function receives a JSON value representing the WebSocket object and is expected to return an outcome indicating success or failure. The outcome includes an error message if the deserialization fa...
```cpp #include <iostream> #include <string> #include <json/json.h> class CoreInternalOutcome { public: CoreInternalOutcome() {} CoreInternalOutcome(const Core::Error& error) : m_error(error) {} bool IsSuccess() const { return !m_error.IsValid(); } Core::Error GetError() const { r...
magicoder
cpp
You are given a list of integers and a target sum. Your task is to write a function that finds all unique combinations in the list that sum up to the target. Each number in the list may only be used once in the combination. The same number may be chosen from the list an unlimited number of times. For example, given th...
```cpp #include <vector> #include <algorithm> void backtrack(std::vector<std::vector<int>>& res, std::vector<int>& combination, std::vector<int>& candidates, int target, int start) { if (target < 0) return; if (target == 0) { res.push_back(combination); return; } for (int i = start; i <...
magicoder
cpp
You are tasked with implementing a Python class method that constructs a full URL from a given relative URL and an optional base URL. The method should handle cases where the base URL is not provided and should correctly handle the construction of the full URL based on the scheme and other components. You are given th...
```python @staticmethod def s_get_full_url(url, base=None): if not base: return url # If base URL is not provided, return the relative URL as the full URL # Parse the base URL and relative URL base_parsed = urlparse(base) url_parsed = urlparse(url) # Construct the full URL based on the co...
magicoder
python
You are tasked with creating a web page that displays a bar chart using Open Flash Chart library. The web page should retrieve data from a database and dynamically generate the bar chart based on the data. Your task is to write a C# method that retrieves the data from the database and generates the necessary JSON forma...
```csharp protected string GenerateBarChartData() { string jsonData = "{\"elements\":[{\"type\":\"bar\",\"colour\":\"#4372A0\",\"values\":["; // Assuming the database connection is established and the SQL query is provided string connectionString = "YourConnectionString"; string query = "SELECT categor...
magicoder
csharp
You are tasked with creating a Python script to automate the generation of private keys and certificates for a test certificate authority and a cluster. The script should utilize the `openssl` command-line tool to perform the necessary operations. Your task is to write a Python function that generates the private keys ...
```python import subprocess def generate_certificates(certs_dir): # Generate a private key and a certificate for a test certificate authority ca_key_cmd = f"openssl genrsa -out {certs_dir}/ca.key 4096" ca_cert_cmd = f"openssl req -new -x509 -key {certs_dir}/ca.key -sha256 -subj \"/C=US/ST=WA/O=Test CA, Inc...
magicoder
python
You are tasked with implementing a factory class for creating exception handling trees in a web API middleware. The factory class should adhere to the given interface and be capable of creating exception handling trees based on specific requirements. Your task is to implement the `IExceptionHandlingTreeFactory` interf...
```csharp using QuantumLogic.WebApi.Middleware.ExceptionHandling.Trees; using QuantumLogic.WebApi.Middleware.ExceptionHandling.Handlers; namespace QuantumLogic.WebApi.Middleware.ExceptionHandling.Factories { public class CustomExceptionHandlingTreeFactory : IExceptionHandlingTreeFactory { public IExcep...
magicoder
csharp
You are tasked with implementing a StringTableDataModel class that will be used as the data model for a StringTableViewModel in a GUI framework. The StringTableDataModel class should support storing and retrieving string data in a tabular format. Your task is to design and implement the StringTableDataModel class with ...
```cpp #include <string> #include <vector> class StringTableDataModel { private: std::vector<std::vector<std::string>> tableData; public: // Adds a new row of string data to the table void addRow(const std::vector<std::string>& rowData) { tableData.push_back(rowData); } // Removes the row...
magicoder
cpp
You are given a C++ class `PointCollection` that represents a collection of 2D points. The class has a member variable `pointsArray` which is a vector of `Point` objects. The `Point` class has two integer member variables `x` and `y` representing the coordinates of the point. Your task is to implement a method `averag...
```cpp int averageDistance() { if (pointsArray.size() == 0) { return 0; // Return 0 if the collection is empty } double totalDistance = 0; int numPairs = 0; for (size_t i = 0; i < pointsArray.size(); ++i) { for (size_t j = i + 1; j < pointsArray.size(); ++j) { // Calcul...
magicoder
cpp
You are tasked with creating a Python program to scrape and display weather information and forum statistics from specific web pages. The program should use the `requests` library to fetch the HTML content of the web pages and the `BeautifulSoup` library to parse the HTML and extract the required information. Your pro...
```python import requests from bs4 import BeautifulSoup # Function to scrape and display weather information def get_weather(): headers = {'User-Agent': 'Mozilla/5.0'} try: html = requests.get("http://www.weather.com.cn/weather/101280601.shtml", headers=headers) html.encoding = "utf-8" ...
magicoder
python
You are tasked with creating a custom error handling system for a cloud storage service. The system should include a class that manages various error types related to the service's operations. Each error type should be represented as a subclass of the main error class, and should have specific attributes and methods to...
```python class CloudStorageError(Exception): def __init__(self, message): super().__init__(message) self.message = message def handle_error(self): print(f"Error: {self.message}") class InvalidBucketState(CloudStorageError): def __init__(self, bucket_name): super().__init_...
magicoder
python
You are given a code snippet that includes a macro `FR(i, n)` which is used to iterate `i` from 0 to `n-1`. Your task is to implement a similar macro `FRL(i, l, r)` that iterates `i` from `l` to `r` (inclusive). You should write a macro that can be used in a C++ program to achieve this functionality. Your task is to d...
```cpp // Define the FRL macro to iterate i from l to r (inclusive) #define FRL(i, l, r) for (int i = (l); i <= (r); ++i) // Sample program demonstrating the usage of FRL macro #include <iostream> int main() { int sum = 0; FRL(i, 3, 7) { sum += i; } std::cout << "Sum of numbers from 3 to 7: " ...
magicoder
cpp
You are tasked with implementing a configuration management system for a software application. The `Config` class is responsible for loading and providing access to configuration settings. The `loadConfig` method is used to load the configuration settings from a resource file named "config". The `Config` class follows ...
```java import java.util.concurrent.locks.ReentrantLock; public class Config { private static Config instance; private ResourceBundle resourceBundle; private static ReentrantLock lock = new ReentrantLock(); public static Config getInstance() { if (instance == null) { lock.lock(); ...
magicoder
java
You are tasked with implementing a custom convolutional layer in PyTorch for a neural network. The layer has two main components: k1 and k2, which are derived from the input kernel 'k'. The layer also has attributes for CUDA compatibility, padding, and parameter gradients. Additionally, a forward method is defined to p...
```python import torch class CustomConvLayer(torch.nn.Module): def __init__(self, size, factor, cuda=False, padding=0): super(CustomConvLayer, self).__init__() k = torch.randn(size, size) k1 = torch.reshape(k, shape=(1, 1, size, 1)) self.k1 = torch.cat([k1, k1, k1], dim=0) k...
magicoder
python
You are tasked with implementing a function to calculate the Class Activation Map (CAM) for a given image and a pre-trained convolutional neural network (CNN). CAM is a visualization technique that highlights the important regions of the input image that contribute to the CNN's classification decision. You are provide...
```python import numpy as np import tensorflow as tf from tensorflow.keras import backend as K def generate_CAM(model, image, weights): # Activation before the last global pooling for layer in reversed(model.layers): if len(layer.output_shape) > 2: break function = K.function([model.lay...
magicoder
python
You are tasked with creating a program that processes a multi-line string and performs specific operations on each line. Your program should take a multi-line string `input_str` as input and perform the following operations on each line: 1. Count the number of words in the line. 2. Determine the longest word in the lin...
```python def process_lines(input_str): result = [] for line in input_str.splitlines(): words = line.split() word_count = len(words) longest_word = max(words, key=len) capitalized_line = ' '.join(word.capitalize() for word in words) result.append({ 'line': lin...
magicoder
python
You are tasked with implementing a template engine that supports autoescaping, block trimming, and block stripping. The template engine should take a template string as input and apply the specified settings to the template rendering process. You need to write a function `render_template(template, settings)` where: - ...
```python def render_template(template, settings): autoescape = settings.get("autoescape", False) trim_blocks = settings.get("trim_blocks", False) lstrip_blocks = settings.get("lstrip_blocks", False) if autoescape: # Implement autoescaping logic here pass if trim_blocks: te...
magicoder
python
You are tasked with implementing a function to compare two sets of database schemas and identify any differences between them. Each schema is represented as a list of tables, where each table is a dictionary containing the table name and its corresponding columns. You need to write a function that takes in two lists o...
```python def compare_schemas(schemas1, schemas2): differences = [] # Check for added or removed tables table_names1 = {schema['table_name'] for schema in schemas1} table_names2 = {schema['table_name'] for schema in schemas2} added_tables = table_names2 - table_names1 removed_tables = table_nam...
magicoder
python
You are given a Python code snippet that initializes a list of prime numbers and defines a function `is_truncatable` to check if a given number is truncatable. A truncatable prime is a prime number that remains prime when digits are successively removed from either end. For example, 3797 is a truncatable prime because ...
```python import lib def is_truncatable(n, primes_set): num_str = str(n) for i in range(len(num_str)): if int(num_str[i:]) not in primes_set or int(num_str[:i+1]) not in primes_set: return False return True def find_truncatable_primes(limit): sieve = lib.get_prime_sieve(limit) ...
magicoder
python
You are given a list of positive integers representing the elements of a vector. Your task is to write a function to determine if the vector can be partitioned into two subsets such that the sum of elements in both subsets is equal. If such a partition exists, return the subsets; otherwise, return "Vector can not be pa...
```python def partitionProblem(num): total_sum = sum(num) if total_sum % 2 != 0: return "\nVector can not be partitioned" target_sum = total_sum // 2 size = len(num) dp = [[False for _ in range(target_sum + 1)] for _ in range(size + 1)] for i in range(size + 1): dp[i][0] = True...
magicoder
python
You are tasked with creating a Swift function that retrieves data from a Parse server using the AFNetworking library and displays it in a table view. You are given a Parse class named "Product" with the following structure: - "name" (String): The name of the product. - "price" (Number): The price of the product. Your...
```swift func fetchProducts(completion: @escaping ([[String: Any]]) -> Void) { let query = PFQuery(className: "Product") query.findObjectsInBackground { (objects, error) in if let error = error { print("Error fetching products: \(error.localizedDescription)") completion([]) ...
magicoder
swift
You are tasked with implementing a web service endpoint that calculates the histogram of a given list of values and returns the result in JSON format. The endpoint should be accessible via a POST request to the '/api/gauge_histogram' route. The input to the endpoint will be a JSON object with a key "values" containing ...
```python from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/api/gauge_histogram', methods=['POST']) def gauge_histogram(): data = request.get_json() values = data.get('values', []) # Calculate the histogram histogram = {} bin_size = (max(values) - min(values)) / 10 f...
magicoder
python
You are tasked with implementing a simplified version of a Stochastic Variational Inference (SVI) algorithm for training a Variational Autoencoder (VAE). The provided code snippet is a part of the training process for the VAE and includes the initialization of training parameters and the execution of the SVI algorithm....
```python def run_svi(svi, model, train_dataloader, val_dataloader, epochs, scheduler, device, output_particles, writer): train_losses = [] val_losses = [] for epoch in range(epochs): model.train() train_loss = 0.0 for batch_idx, (data, _) in enumerate(train_dataloader): ...
magicoder
python
You are tasked with creating a Python function that processes text data using AllenNLP, a popular natural language processing library. Your function will take a list of sentences as input and perform text embedding using AllenNLP's TextFieldEmbedder. Additionally, it will calculate the text field mask for each sentence...
```python from typing import List from allennlp.data import TextFieldTensors, Vocabulary from allennlp.modules.text_field_embedders import TextFieldEmbedder from allennlp.nn.util import get_text_field_mask from allennlp.training.metrics import Average def process_text_data(sentences: List[str], text_field_embedder: Te...
magicoder
python
You are tasked with implementing a function to generate a text table from given data, row and column dimensions, and a function to calculate cell values. The function should be able to handle multi-character separators for both rows and columns. You are given the following function signature: ```python def text_table(...
```python from typing import List, Dict, Any, Callable def text_table(data: List[Dict[str, Any]], dim_rows: List[str], dim_cols: List[str], value_func: Callable[[List[Dict[str, Any]]], Any], d_cols: str = " ", d_rows: str = "\n") -> str: table = [] # Create the header row header = d_cols.join(dim_cols) ...
magicoder
python
You are tasked with creating a logging system for a software application. The given code snippet demonstrates the setup of a logging system using the Python `logging` module. The code snippet initializes two handlers for the logger: a stream handler that logs messages with a level of INFO to the console, and a file han...
```python import logging import sys def configure_logging(logfile): log = logging.getLogger() log.setLevel(logging.DEBUG) cons_h = logging.StreamHandler(sys.stdout) cons_h.setLevel(logging.INFO) log.addHandler(cons_h) file_h = logging.FileHandler(logfile) file_h.setLevel(logging.DEBUG) ...
magicoder
python
You are tasked with implementing a custom migration operation in a Django project. Your task is to create a new migration operation that will add a new field to a specific model in the project's schema. The model is named 'schema', and the new field to be added is called 'published'. Your custom migration operation sho...
```python from django.db import migrations, models class AddPublishedField(migrations.Migration): dependencies = [ ('daiquiri_metadata', '0024_django2'), ] operations = [ migrations.AddField( model_name='schema', name='published', field=models.BooleanFi...
magicoder
python
You are tasked with implementing a function that replaces specific characters in a given string based on a predefined mapping. The function should take two parameters: a string representing the input and an object containing the character mapping. The character mapping object will have keys representing the characters ...
```javascript function replaceCharacters(input, trChars) { for (const key of Object.keys(trChars)) { input = input.replace(new RegExp('[' + key + ']', 'g'), trChars[key]); } return input.toString(); } ``` In the solution, the function `replaceCharacters` takes two parameters: `input` representing the input st...
magicoder
javascript
You are tasked with creating a Python script to automate the process of brute-forcing the login credentials of a WordPress website using the XML-RPC interface. The XML-RPC interface in WordPress allows for remote procedure calls, including the ability to authenticate users. The provided code snippet is a Bash script th...
```python import sys import xmlrpc.client import requests def brute_force_login(url, password_file, username): try: with open(password_file, 'r') as file: passwords = file.read().splitlines() server = xmlrpc.client.ServerProxy(url) for password in passwords: ...
magicoder
python
You are tasked with implementing a Gramian Angular Field (GAF) generator, a technique used in time series analysis to transform a time series into an image representation. The GAF is created by computing the pairwise angles between all pairs of points in the time series and then mapping these angles to a color represen...
```python import numpy as np def generate_gaf(time_series: np.ndarray) -> np.ndarray: # Normalize the time series to have values between -1 and 1 normalized_series = (time_series - np.mean(time_series)) / np.std(time_series) # Compute the outer product of the normalized time series with itself out...
magicoder
python
You are working on a scientific computing project and need to implement a function to perform a specific type of data manipulation. The function takes in an object `ctx` which has various attributes and methods related to the project. The provided code snippet is a part of the function and shows a while loop that itera...
```python import numpy as np def perform_data_manipulation(ctx): dJ = 1 # Initialize dJ to a value greater than 1e-5 while dJ > 1e-5: dJ = ctx.formal_sol_gamma_matrices() ctx.depthData.fill = False J = np.copy(ctx.spect.J) sourceData = {'chi': np.copy(ctx.depthData.chi), ...
magicoder
python
You are tasked with implementing a custom deep copy function for a specific data structure. The data structure is a nested dictionary containing various data types such as integers, strings, lists, and other dictionaries. Your custom deep copy function should create a new copy of the original data structure, ensuring t...
```python def custom_deep_copy(data): if isinstance(data, dict): copied_dict = {} for key, value in data.items(): copied_dict[key] = custom_deep_copy(value) return copied_dict elif isinstance(data, list): copied_list = [] for item in data: copied_l...
magicoder
python
You are given a Python function that takes in a list of integers and returns the sum of all the even numbers in the list. Your task is to implement the missing function `sum_even_numbers` to achieve this. ```python def sum_even_numbers(nums): # Your implementation here pass # Test cases print(sum_even_numbers...
```python def sum_even_numbers(nums): return sum(num for num in nums if num % 2 == 0) ```
magicoder
python
You are tasked with creating a function that processes grading instructions for exercises in an educational platform. The function should take in an array of grading criteria and return a modified array with the usage count of each grading instruction incremented by 1. Each grading criterion contains a title and an arr...
```typescript function incrementUsageCount(gradingCriteria: GradingCriterion[]): GradingCriterion[] { return gradingCriteria.map((criterion) => { const updatedInstructions = criterion.structuredGradingInstructions.map((instruction) => { return { ...instruction, usageCount: instruction.usageCount...
magicoder
typescript
You are tasked with implementing a validation system for a game engine. The system should iterate through a list of checks and fields to determine if all the checks pass for a given game object. Each check is a function that takes in a namespace, behavior, field, and game object, and returns a boolean indicating whethe...
```csharp public class ValidationSystem { public bool Validate(List<Check> checks, List<Field> fields, string @namespace, string behaviour, GameObject gameObject) { bool allPassed = true; foreach (var check in checks) { foreach (var field in fields) { ...
magicoder
csharp
You are given a Python function that takes in a list of integers and returns the maximum sum of a contiguous subarray within the input list. Your task is to implement the function `max_subarray_sum` to achieve this. The function signature is: ```python def max_subarray_sum(nums: List[int]) -> int: pass ``` You ne...
```python from typing import List def max_subarray_sum(nums: List[int]) -> int: max_sum = float('-inf') current_sum = 0 for num in nums: current_sum = max(num, current_sum + num) max_sum = max(max_sum, current_sum) return max_sum ``` The `max_subarray_sum` function uses Kadan...
magicoder
python
You are tasked with implementing a class that represents a subset of a dataset and provides a method to retrieve an element by its index. The class should handle out-of-bounds index access gracefully. You are given a code snippet that includes an assertion and a return statement. The `subdataset` is assumed to be a co...
```cpp #include <iostream> #include <vector> #include <cassert> template <typename T> class SubsetDataset { private: std::vector<T> subdataset; public: SubsetDataset(const std::vector<T>& data) : subdataset(data) {} T getElement(size_t id) { if (id < subdataset.size()) { return subdat...
magicoder
cpp
You are tasked with implementing a function that constructs a binary tree from a given list of integers and then prints the tree in a textual format. The textual representation of the tree should display the structure of the binary tree in a human-readable format. You are provided with a code snippet that prints the t...
```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def construct_binary_tree(nums): if not nums: return None nodes = [None if val is None else TreeNode(val) for val in nums] root = nodes[0] ...
magicoder
python
You are tasked with simulating the behavior of a Finch robot in a maze. The Finch robot has an accelerometer that measures the acceleration in the z-direction (up and down). The robot is programmed to move forward until it detects an obstacle on either the left or right side. When an obstacle is detected, it stops and ...
```python from typing import List def simulate_maze(z_accel_values: List[float]) -> List[str]: movements = [] for zAccel in z_accel_values: if zAccel > -0.7: movements.append("Move Forward") else: movements.append("Stop and Check") # Assuming tweety.obstacle(...
magicoder
python
You are tasked with implementing a function that can extract the namespace hierarchy from a given C++ code snippet. The namespace hierarchy is a sequence of nested namespaces, represented by the `namespace` keyword in C++. Each namespace is identified by its name, and the hierarchy is denoted by the indentation level o...
```python from typing import List def extractNamespaceHierarchy(code: str) -> List[str]: namespaces = [] current_namespace = "" indent_level = 0 for line in code.split('\n'): if "namespace" in line: indent_level = line.count('{') - line.count('}') namespace_name = line....
magicoder
python
You are tasked with implementing a C++ class that represents a factory production line system. The class should manage the state of the production line and provide functionality to interact with it. The provided code snippet gives a glimpse of the class members that need to be implemented. Your task is to create a cl...
```cpp #include <memory> // Define the Line and FactoryState classes if not already defined class Line {}; class FactoryState {}; class ProductionLine { private: const int _startY; const Line& _line; std::shared_ptr<const FactoryState> _factoryState; public: ProductionLine(int startY, const Line& lin...
magicoder
cpp
You are tasked with implementing a class that processes DICOM (Digital Imaging and Communications in Medicine) data. The DICOM standard defines a Field of View Sequence Item, which contains information about the field of view for a medical imaging study. Your task is to create a method that extracts and processes the f...
```csharp public class FieldOfViewSequenceItem : SequenceIodBase { // Other class members and methods /// <summary> /// Extracts and processes the field of view information from the DICOM dataset. /// </summary> /// <param name="dicomAttribute">The DICOM attribute containing the field of view infor...
magicoder
csharp
You are tasked with creating a program to generate personalized warning messages for individuals entering the #dogpark based on their usernames and specific conditions. The warning messages should be constructed based on a set of predefined templates and should include the username of the individual. The program should...
```python def generateWarningMessage(username, condition): if condition == 1: return "@%s beware - flesh entering the #dogpark without correct papers will actually turn into a liquid." % username elif condition == 2: return "Only truely evil spirits may enter the #dogpark. Are you one of us, @%s...
magicoder
python
You are tasked with implementing a function to process a YAML file and identify any duplicate keys within a mapping node. A mapping node is a collection of key-value pairs in YAML. Your function should take a YAML file as input and return a dictionary containing the duplicate keys along with the line numbers where they...
```python def construct_mapping(node, deep=False): mapping = dict() errors = dict() for key_node, value_node in node.value: key = key_node.value if key in mapping: if key in errors: errors[key].append(key_node.__line__) else: errors[key...
magicoder
python
You are tasked with implementing a custom iterator class in Python. The class should iterate over a collection of commands and their corresponding arguments. The code snippet provided is a partial implementation of the iterator class, and your task is to complete the implementation. You are given the following code sn...
```python class CommandIterator: def __init__(self, command_dict): self.command_dict = command_dict self.commands = iter(command_dict.keys()) def __getitem__(self, command): return {command: self.command_dict[command]} def __iter__(self): return self def __next__(self)...
magicoder
python
You are tasked with creating a Python function that processes a configuration file for a software project. The configuration file is in a custom format and contains sections and entries. Each section has a name, and each entry within a section has a key and a value. The function needs to perform the following tasks: 1...
```python def process_config_file(config_file, crate_name, CRATES_VERSION): with open(config_file, 'r') as file: lines = file.readlines() updated_lines = [] in_dependency_section = False for line in lines: if line.startswith('['): section_name = line.strip('[]\n') ...
magicoder
python
You are tasked with implementing a Redux reducer function that manages the state of selected mages in a fantasy-themed application. The state is represented as an object with a `mageIds` array, and the reducer should handle actions to toggle the selection of mages. Additionally, the reducer should return a model and a ...
```javascript // Redux reducer function to manage the state of selected mages function selectedMagesReducer(state = { mageIds: [] }, action) { switch (action.type) { case 'TOGGLE_MAGE': const mageIndex = state.mageIds.indexOf(action.mageId); const updatedMageIds = [...state.mageIds]; if (mageInd...
magicoder
javascript
You are given a code snippet that defines a custom comparison function and a function to create a priority queue using this comparison function. Your task is to implement a function that uses this priority queue to find the minimum spanning tree (MST) of a given graph. You are provided with the following structures: `...
```cpp #include <vector> #include <queue> #include <algorithm> struct Edge { int src, dest, weight; }; struct Graph { int V, E; std::vector<Edge> edges; }; auto get_heap() noexcept { const auto compare = [](const Edge& lhs, const Edge& rhs) noexcept { return lhs.weight > rhs.weight; }; ...
magicoder
cpp
You are tasked with creating a Python class that interacts with a SOAP web service to manage projects. Your class should handle the retrieval of project data and the creation of new projects using the suds library. The suds library provides a lightweight SOAP client for consuming SOAP-based web services. Your task is ...
```python from suds.client import Client from model.project import Project class SoapHelper: def __init__(self, app, wsdl_url): self.app = app self.client = Client(wsdl_url) def get_project_data(self, project_id): try: project_data = self.client.service.getProjectData(proj...
magicoder
python
You are working on an image processing application that converts a color image into a grayscale image. The given code snippet is a part of the image processing algorithm. The algorithm takes an input image in the form of an array of pixels, where each pixel is represented as a 32-bit integer in ARGB format. The algorit...
```java public int[] convertToGrayscale(int[] pixels, int width, int height) { int[] grayscalePixels = new int[width * height]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int pixel = pixels[width * i + j]; int alpha = (pixel & 0xFF000000); i...
magicoder
java
You are tasked with implementing a function that calculates the average of an array of numbers, excluding the minimum and maximum values. Your function should take an array of numbers as input and return the average of the remaining values. Write a function `calculateAverage` that takes an array of numbers as input an...
```javascript const calculateAverage = (numbers) => { if (numbers.length < 3) { return null; } const sortedNumbers = numbers.slice().sort((a, b) => a - b); const sum = sortedNumbers.slice(1, -1).reduce((acc, val) => acc + val, 0); const average = sum / (sortedNumbers.length - 2); return average; }; //...
magicoder
javascript
You are tasked with creating a Python function that computes the flow duration curve (FDC) for a given set of flow data. The FDC is a graphical representation of the distribution of streamflow over a specific time period. The function should take in an array of flow values, the number of steps for the FDC, a boolean fl...
```python import numpy as np import pandas as pd def compute_fdc(flows: np.array, steps: int = 500, exceed: bool = True, col_name: str = 'flow') -> pd.DataFrame: # Sort the flow values in descending order sorted_flows = np.sort(flows)[::-1] # Calculate exceedance probabilities if exceed: excee...
magicoder
python
You are tasked with creating a Python class that manages a list of tasks. The class should have the ability to add, remove, and retrieve tasks, as well as provide a method to return the number of tasks currently in the list. Additionally, the class should have a method to generate a URL for accessing the list of tasks....
```python class TaskManager: def __init__(self): self.tasks = [] def add_task(self, task): self.tasks.append(task) def remove_task(self, task): if task in self.tasks: self.tasks.remove(task) def get_tasks(self): return self.tasks def num_tasks(self): ...
magicoder
python
You are tasked with implementing a function to update a branch in a version control system. The function should take in the current branch name, the new branch name, and a list of commits to be included in the new branch. The function should then create the new branch with the specified commits and return a success mes...
```python from typing import List def update_branch(current_branch: str, new_branch: str, commits: List[str]) -> str: # Assuming the existence of a version control system with appropriate methods for branch manipulation # Pseudocode for updating the branch if new_branch_exists(new_branch): update_e...
magicoder
python
You are given a list of items, each with a corresponding profit and weight. Your task is to implement a function that selects a combination of items to maximize the total profit while ensuring that the total weight does not exceed a given capacity. You are provided with the following code snippet as a starting point: ...
```python def knapsack(data, bag): data.sort(key=lambda x: x[1]/x[2], reverse=True) # Sort items by profit-weight ratio in descending order total_profit = 0 remaining_capacity = bag for item in data: index, profit, weight = item if remaining_capacity >= weight: total_profit...
magicoder
python
You are tasked with implementing a Python function to parse URLs for different web services and extract relevant information. The function should take a URL as input and return the service name, API method, and API arguments in a structured format. You are provided with a code snippet that contains test cases for pars...
```python from typing import Tuple, Dict, List import urllib.parse def parse_url(url: str) -> Tuple[str, str, Dict[str, List[str]]]: parsed_url = urllib.parse.urlparse(url) service = parsed_url.netloc.split('.')[1] # Extract service name from the URL path_segments = parsed_url.path.split('/') api_meth...
magicoder
python