query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a simple RPC (Remote Procedure Call) framework in Java. The RPC framework should allow a client to remotely invoke methods on a server and receive the results. To achieve this, you need to create a proxy-based RPC client and a corresponding server that can handle the remote method invoc...
```java import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.Socket; public class RpcClientProxy { private String host; private int port; public RpcClientProxy(Strin...
magicoder
java
You are tasked with implementing a Python script that handles tab completion for a custom command-line interface (CLI). The script should be able to provide completions for commands and arguments based on the user's input. Your task is to complete the `handle_tab_complete` function, which is called when the user press...
```python import sys # Define the list of available commands and arguments available_commands = ['command1', 'command2', 'command3'] available_arguments = ['arg1', 'arg2', 'arg3'] def handle_tab_complete(): if "--get_completions" in sys.argv: exit() # Exit if --get_completions flag is set user_input...
magicoder
python
You are tasked with creating a Python program that processes a list of integers and performs specific operations on it. Your program should define a function `process_numbers` that takes a list of integers as input and returns a modified list based on the following rules: 1. If the number is even, add 10 to it. 2. If ...
```python def process_numbers(numbers): modified_list = [] for num in numbers: if num % 2 == 0: modified_list.append(num + 10) elif num % 2 != 0: modified_list.append(num - 5) if num % 5 == 0: modified_list[-1] *= 2 return modified_list def main()...
magicoder
python
You are tasked with creating a Python program to read and process data from an Omron 2JCIE-BU01 environmental sensor. The sensor provides various environmental data such as temperature, humidity, light intensity, UV index, noise level, and acceleration. Your program should perform the following tasks: 1. Connect to th...
```python # Import necessary libraries import sys sys.path.insert(0, "../lib-ext") sys.path.insert(0, "..") from omron_2jcie_bu01 import Omron2JCIE_BU01 from datetime import datetime, timedelta # Connect to the Omron 2JCIE-BU01 sensor sensor = Omron2JCIE_BU01("XX:XX:XX:XX:XX:XX") # Replace "XX:XX:XX:XX:XX:XX" with th...
magicoder
python
You are tasked with implementing a simple chat server using the `untwisted` library in Python. The `untwisted` library provides tools for asynchronous programming and event-driven networking. Your task is to complete the implementation of the `ChatServer` class, which will handle incoming client connections and manage...
```python from untwisted.tools import coroutine from untwisted import core, ACCEPT, READ, WRITE class ChatServer: def __init__(self, server): server.add_map(ACCEPT, self.handle_accept) self.pool = [] @coroutine def handle_accept(self, server, client): self.pool.append(client) ...
magicoder
python
You are tasked with implementing a custom data structure that combines the functionality of a stack and a queue. This data structure, named "StackQueue," should support the following operations: 1. `push(item)`: Add an item to the data structure. 2. `pop()`: Remove and return the most recently added item. 3. `peek()`: ...
```python from collections import deque class StackQueue: def __init__(self): self.stack = [] self.queue = deque() def push(self, item): self.stack.append(item) def pop(self): if not self.stack: while self.queue: self.stack.append(self.queue.pop...
magicoder
python
You are tasked with implementing a data structure that combines the functionality of a heap and a hash table. The data structure should support the following operations: 1. `insert(key, value)`: Insert a key-value pair into the data structure. 2. `remove(key)`: Remove the key-value pair with the specified key from the...
```rust impl<K: Ord + Hash + Clone, V: Clone> HeapHashMap<K, V> { fn insert(&mut self, key: K, value: V) { self.heap.push((key.clone(), value.clone())); self.map.insert(key, value); } fn remove(&mut self, key: &K) { if let Some(value) = self.map.remove(key) { self.heap.r...
magicoder
rust
You are tasked with implementing a configuration management system for a Windows Forms application. The system should allow the application to set various properties of the form, such as whether it can be maximized, minimized, resized, or displayed as a tool window. Additionally, the system should provide a way to set ...
```csharp using System; public class FormPropertiesManager { private readonly Form _form; public FormPropertiesManager(Form form) { _form = form; } public void SetBool(string propertyName, bool value) { switch (propertyName) { case "MaximizeBox": ...
magicoder
csharp
You are tasked with implementing a function that processes a complex data structure and returns a specific value based on certain conditions. The data structure consists of nested optional fields and requires careful unwrapping and manipulation to obtain the desired result. You are given a Rust code snippet that demon...
```rust use std::ptr::{null_mut,NonNull}; struct RpuDataNlq { // Define the fields and methods of RpuDataNlq } struct Rpu { rpu_data_nlq: Option<RpuDataNlq>, // Define other fields of Rpu } struct Opaque { rpu: Option<Rpu>, // Define other fields of Opaque } fn process_data_structure(ptr: *const...
magicoder
rust
You are tasked with implementing a function that calculates the area of a polygon given its vertices. The vertices are represented as a list of (x, y) coordinates in the 2D plane. The area of a polygon can be calculated using the shoelace formula, which states that the area is half the absolute value of the difference ...
```swift func calculatePolygonArea(vertices: [(Double, Double)]) -> Double { var area = 0.0 let n = vertices.count for i in 0..<n { let j = (i + 1) % n area += (vertices[i].0 * vertices[j].1) - (vertices[j].0 * vertices[i].1) } return abs(area) / 2.0 } // Test the function...
magicoder
swift
You are tasked with simulating a simplified version of a producer-consumer problem using Python. The producer will continuously generate data and push it into a shared buffer, while the consumer will retrieve and process the data from the buffer. Your task is to implement the producer and consumer classes, ensuring tha...
```python import threading import queue import time # Shared buffer using a queue shared_buffer = queue.Queue(maxsize=10) class ProducerThread(threading.Thread): def run(self): while True: data = generate_data() # Function to generate data shared_buffer.put(data) time....
magicoder
python
You are tasked with implementing a simplified version control system for a software project. The system will track dependencies between different components and manage the operations required to update these components. You are given a Python code snippet representing a simplified version of a migration file in a Djan...
```python class CircularDependencyError(Exception): pass def resolve_dependencies(dependencies, operations): graph = {} for dep in dependencies: if dep[0] not in graph: graph[dep[0]] = set() graph[dep[0]].add(dep[1]) visited = set() result = [] def dfs(node): ...
magicoder
python
You are tasked with implementing a file system data structure in Rust. The file system is represented using a struct `FileSystem` with various fields and methods. One of the methods in the `FileSystem` struct is shown below: ```rust impl FileSystem { fn read_file(&self, ino: u64) -> Result<Vec<u8>, Error> { ...
```rust impl FileSystem { fn read_file(&self, ino: u64) -> Result<Vec<u8>, Error> { let mut file_reader = BufReader::new(&self.device).by_ref(); let superblock = &self.sb; let root_ino = if ino == FUSE_ROOT_ID { self.sb.sb_rootino } else { ino }; ...
magicoder
rust
You are tasked with implementing a program to solve the "Ticket Translation" problem. In this problem, you are given a set of rules for valid fields on a ticket, as well as a list of nearby tickets with their field values. Your goal is to determine the correct order of fields on the ticket. The rules are represented a...
```python def is_valid_value(value, rule): for r in rule: if r[0] <= value <= r[1]: return True return False def sort_fields(rules, nearby_tickets): valid_tickets = [ticket for ticket in nearby_tickets if all(any(is_valid_value(value, rule) for rule in rules) for value in ticket)] p...
magicoder
python
You are tasked with implementing a simplified version of a library for handling system processes. The library, named `slib`, provides a function `spx()` that is used to execute a system process and return its exit status. Additionally, the library provides an `exit()` function to terminate the current process with a gi...
```c #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/wait.h> int spx() { pid_t pid = fork(); if (pid < 0) { perror("Fork failed"); exit(EXIT_FAILURE); } else if (pid == 0) { // Child process execl("/bin/ls", "ls", "-l", NULL); // Replace with the d...
magicoder
c
You are tasked with implementing a function that converts a given OpenGL pixel format to its corresponding size in bytes. The pixel format is represented by a pair of values: the first value is an OpenGL constant representing the pixel format, and the second value is a custom `PixelType` object representing the number ...
```cpp #include <iostream> #include <unordered_map> class PixelType { public: int components; PixelType(int components) : components(components) {} }; int getPixelFormatSize(int pixelFormat, PixelType pixelType) { std::unordered_map<int, int> formatSizeMap = { { GL_UNSIGNED_INT_24_8, pixelType.co...
magicoder
cpp
You are tasked with creating a React component that displays a forum. The forum component should be designed to render the forum interface and handle user interactions. Your task is to implement the `Forum` component with the following requirements: 1. The `Forum` component should render a list of discussion threads. ...
```jsx import React from 'react'; import { Link } from 'react-router-dom'; const Forum = () => { const discussionThreads = [ { id: 1, title: 'React Hooks', author: 'JohnDoe', comments: 15 }, { id: 2, title: 'Redux State Management', author: 'JaneSmith', comments: 10 }, { id: 3, title: 'Component Lifecycl...
magicoder
jsx
You are tasked with creating a script to manage the startup of a local emulator for Google Cloud Datastore. The script should handle the configuration of the emulator based on certain conditions. You are given a code snippet from an existing script that starts the emulator. The script checks the value of the `FULL_MEM...
```bash #!/bin/bash FULL_MEMORY="true" # Example value for demonstration DATA_DIR="/path/to/data/dir" HOST_PORT="8080" # Example port for demonstration DATAFLAG="" if [ "$FULL_MEMORY" = "true" ]; then DATAFLAG="--no-store-on-disk" fi echo "Starting emulator..." /root/google-cloud-sdk/bin/gcloud beta emulators ...
magicoder
shell
You are tasked with creating a Python class that generates and manages job configurations for different data processing tasks. The class should allow users to specify command arguments, SQL scripts, and properties for the job. Additionally, the class should provide a method to assert the equality of two job configurati...
```python class JobConfig: def __init__(self): self.command_args = None self.sql_script = None self.properties = {} def command_arguments(self, args): self.command_args = args return self def script(self, sql_script): self.sql_script = sql_script ret...
magicoder
python
You are tasked with simulating a temperature sensor and a modem for sending temperature data to a server. The provided code snippet is a simplified version of a program that attempts to join a modem network and then continuously sends temperature data to a server using the modem. Your task is to implement the simulatio...
```python import random import time class TemperatureSensor: @staticmethod def get_temp_celsius(): # Simulate temperature readings between 0 and 100 degrees Celsius with two decimal places return round(random.uniform(0, 100), 2) @staticmethod def hex_int_from_2dp_celsius(temp): ...
magicoder
python
You are tasked with creating a role-based access control system for a web application. Your goal is to implement a middleware function that will handle incoming requests and ensure that the user making the request has the necessary roles and permissions to access the requested resource. You are provided with a code sn...
```php public function handle($request, Closure $next, $roles = null, $permission = null) { $user = $request->user(); if ($user != null) { if ($roles !== null && !$user->hasRole($roles)) { $error = [ 'message' => 'Unauthorized. User does not have the required role.', ...
magicoder
php
You are given a snippet of code that appears to be incomplete. Your task is to complete the code by implementing a specific functionality. The code snippet is part of a Java program that aims to create a class representing a geometric shape. The class should have methods to calculate the area and perimeter of the shape...
```java public class Rectangle extends GeometricShape { private double length; private double width; public Rectangle(double length, double width) { this.length = length; this.width = width; } @Override public double calculateArea() { return length * width; } @...
magicoder
java
You are tasked with creating a script for a 2D game where clouds are dynamically resized based on their position and a size multiplier. The clouds are represented as GameObjects with associated sprites. The initial size of the cloud is modified by the `sizemultiplier` and the cloud's position. Additionally, the clouds ...
```csharp void ResizeCloudAndCalculateDistance() { // Resize the cloud based on its initial size, position, and sizemultiplier Vector3 initialScale = self.transform.localScale; float newSizeX = initialScale.x * sizemultiplier * self.transform.position.y; float newSizeY = initialScale.y * sizemultiplier ...
magicoder
csharp
You are tasked with implementing a simple stack data structure in Python. A stack is a Last-In-First-Out (LIFO) data structure that supports two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack. Additionally, you need to implement a method to re...
```python class MinStack: def __init__(self): self.stack = [] self.min_stack = [] def push(self, x: int) -> None: self.stack.append(x) if not self.min_stack or x <= self.min_stack[-1]: self.min_stack.append(x) def pop(self) -> None: if self.stack[-1] == ...
magicoder
python
You are tasked with implementing a program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Each account should have a unique account number and be associated with the user's name. The program should also be able to display a...
```java import java.util.HashMap; public class BankingSystem { private HashMap<Integer, BankAccount> accounts; private int accountCounter; public BankingSystem() { accounts = new HashMap<>(); accountCounter = 1; } public void createAccount(String name, double initialBalance) { ...
magicoder
java
You are working on a secret message encryption program. The program takes a message as input and encrypts it using a simple algorithm. The algorithm iterates through each character in the message in reverse order, increments its ASCII value by 1, and then concatenates the resulting characters to form the encrypted mess...
```python def encrypt_message(message: str) -> str: secret = "" for character in reversed(message): secret = secret + str(chr(ord(character)+1)) return secret ```
magicoder
python
You are tasked with creating a custom class in PHP that extends the `Illuminate\Database\Eloquent\Collection` class and adds functionality to filter and manipulate a collection of `Carbon` objects. The `Carbon` class is a popular date and time manipulation library in PHP. Your task is to create a new class called `Cus...
```php namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Collection; class CustomDateCollection extends Collection { public function filterFutureDates(): CustomDateCollection { $filteredDates = $this->filter(function (Carbon $date) { return $date->isFuture(); ...
magicoder
php
You are tasked with implementing a custom test case class for a unit testing framework. The class should include a method to calculate the average of an array of integers and a corresponding test method to verify the correctness of the average calculation. Your task is to complete the implementation of the `CustomTest...
```swift // Solution for the testAverageCalculation method func testAverageCalculation() { let expectedAverage: Double = 15.0 let calculatedAverage = average(of: numbers) XCTAssertEqual(calculatedAverage, expectedAverage, "Average calculation is incorrect") } ``` In the `testAverageCalculation` method, the...
magicoder
swift
You are tasked with creating a custom management command in a Django application. The command should accept two optional arguments: `--database` to specify the name of the database and `--plan` as a flag to indicate a specific action. The `--database` argument should default to `DEFAULT_DB_ALIAS` if not provided. Your ...
```python from django.core.management import call_command from django.core.management.base import BaseCommand from django.db import connections class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( '--database', default=connections[DEFAULT_DB_ALIAS].settings_dict['NA...
magicoder
python
You are tasked with implementing a function to encrypt a given message using a custom cryptographic algorithm. The algorithm is provided through a `crypto_wrapper` library, and the necessary configurations are defined in the `configurations.h` file. Additionally, some external constants are included from the `extern_co...
```c #include "crypto/crypto_wrapper.h" #include "configurations.h" #include "extern_consts.h" #define _default_response "" char* encryptMessage(const char* message) { char* encryptedMessage = crypto_wrapper_encrypt(message, configurations, extern_consts); if (encryptedMessage == NULL) { return _defau...
magicoder
c
You are given a function `longestPalindrome` that takes a string `s` as input and returns the longest palindromic substring within the string. A palindromic string is one that reads the same backward as forward. The function is implemented using the following code snippet: ```python def longestPalindrome(s: str) -> st...
```python def longestPalindrome(s: str) -> str: if len(s) < 2 or s == s[::-1]: return s start, end = 0, 0 for i in range(len(s)): len1 = expand_around_center(s, i, i) len2 = expand_around_center(s, i, i + 1) max_len = max(len1, len2) if max_len > end - start: ...
magicoder
python
You are tasked with implementing a Python metaclass that enforces a specific naming convention for class attributes. The metaclass should ensure that any attribute name starting with "attr_" must be in all uppercase letters. Any attempt to define an attribute violating this convention should raise a custom exception. ...
```python class InvalidAttributeError(Exception): pass class Meta(type): def __new__(cls, name, bases, dct): for attr_name in dct: if attr_name.startswith('attr_') and not attr_name.isupper(): raise InvalidAttributeError(f"Invalid attribute name: {attr_name}. Attribute names...
magicoder
python
You are tasked with implementing a Python function that calculates the total number of unique paths to reach the bottom-right corner of a grid from the top-left corner. You can only move either down or to the right at any point in time. The grid is represented as a 2D list where 1 indicates an obstacle and 0 indicates ...
```python from typing import List def unique_paths_with_obstacles(obstacle_grid: List[List[int]]) -> int: m, n = len(obstacle_grid), len(obstacle_grid[0]) # If the starting cell has an obstacle, there is no path if obstacle_grid[0][0] == 1: return 0 # Initialize the first cell to 1 if...
magicoder
python
You are tasked with creating a script to automate the execution of smoketests for a software application. The script should iterate through a list of files, display their contents, and then indicate the completion of the smoketests. The script should also terminate immediately if any command within it fails. You are p...
```bash #!/bin/bash # List of files to be processed files=("file1.txt" "file2.txt" "file3.txt") # Iterate through the list of files for i in "${files[@]}" do echo "============================================================" echo $i cat $i done # Print completion timestamp echo $(date): Smoketests completed. ...
magicoder
shell
You are tasked with implementing a Python class that simulates a multicast data transmission system. The provided code snippet serves as a starting point for your implementation. Your task is to complete the implementation of the `Multicast_transceiver` class and the `detuple` function based on the given code snippet a...
```python class Multicast_transceiver: def __init__(self, local_address, local_port, multicast_group, multicast_port): self.local_address = local_address self.local_port = local_port self.multicast_group = multicast_group self.multicast_port = multicast_port def receive_data(sel...
magicoder
python
You are tasked with creating a program that processes a list of Git repository URLs and performs specific operations on them. Each repository URL is in the format `https://github.com/{owner}/{repository_name}.git`. Your program needs to extract the owner's login and the repository name from the URL and then clone the r...
```python from datetime import datetime from typing import List import os def process_repositories(repository_urls: List[str], start_time: datetime) -> None: for url in repository_urls: owner, repo_name = url.split("/")[-2], url.split("/")[-1].replace(".git", "") os.system(f"git clone {url} repos/{...
magicoder
python
You are given a series of assembly-like instructions that operate on different types of data. Each instruction is represented by a mnemonic followed by the source and destination operands. The operands are represented by their data type (e.g., r for register, a for array, f for float, etc.) and an index. The mnemonics...
The final values of the specified operands after executing the given instructions are as follows: - `r256[8] = 10` - `a256[1] = 20` - `f128[4] = 15.5` - `a1024[15] = 30` - `a8[5] = 0` - `f64[5] = 0` - `r160[5] = 0` - `a8[5] = 1` - `r160[5] = 0` - `f64[19] = 0` The instructions `ifn a32[32]` and `ifz r2048[17]` are con...
magicoder
r
You are tasked with implementing a program to simulate an actor's movement within a 2D grid. The actor should not be allowed to exit the boundaries of the grid. The grid is represented as a 2D array, and the actor's movement is controlled by a sequence of commands. Each command corresponds to a movement direction: "U" ...
```cpp #include <vector> #include <string> #include <utility> std::pair<int, int> simulateActorMovement(std::vector<std::vector<int>> grid, const std::string& commands) { int rows = grid.size(); int cols = grid[0].size(); int x = 0, y = 0; for (char command : commands) { if (command == 'U' && ...
magicoder
cpp
You are tasked with implementing a Python class to manage user profiles and their associated stories and favorite authors. The class should have methods to retrieve stories and favorite authors from a web page, as well as a method to generate a JSON dump of the user profile data. You are provided with a code snippet t...
```python from datetime import datetime import json from bs4 import BeautifulSoup _DATE_FORMAT = "%Y-%m-%d %H:%M:%S" class UserProfile: def __init__(self, user_id, timestamp, username): self.id = user_id self.timestamp = timestamp self.username = username self.stories = [] ...
magicoder
python
You are working on a blog application that uses Spring Data JPA for data access. The code snippet provided is a part of the application's data access layer. The `ArticleRepository` interface extends the `JpaRepository` interface, which provides CRUD (Create, Read, Update, Delete) operations for the `Article` entity. Ad...
```java package fr.gtm.blog.dao; import org.springframework.data.jpa.repository.JpaRepository; import fr.gtm.blog.domain.Article; import java.util.List; public interface ArticleRepository extends JpaRepository<Article, Integer> { List<Article> findByTitleContaining(String search); } ``` In the solution, the met...
magicoder
java
You are tasked with creating a custom validation system for a web application. The system should handle various validation rules and provide custom error messages for specific cases. Your task is to implement a class that can handle these validation rules and error messages. You are given a partial code snippet from a...
```php class Validator { private $rules = []; public function setRules($attribute, $rules) { $this->rules[$attribute] = $rules; } public function validate($data) { $errors = []; foreach ($this->rules as $attribute => $rules) { foreach ($rules as $rule => $m...
magicoder
php
You are tasked with implementing a Luhn algorithm validator for credit card numbers. The Luhn algorithm is used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers, and Canadian Social Insurance Numbers. The algorithm is designed to prevent ac...
```javascript const luhn = { validate: (number) => { const numStr = number.toString(); let sum = 0; let isSecondDigit = false; for (let i = numStr.length - 1; i >= 0; i--) { let digit = parseInt(numStr.charAt(i)); if (isSecondDigit) { digit *= 2; if (digit > 9) { ...
magicoder
javascript
You are tasked with creating a Swift function that calculates the area of a custom UIView shape and then applies a drop shadow effect to the view based on the calculated area. You are given the following code snippet as a starting point: ```swift extension UIView { func dropShadow(scale: Bool = true) { la...
```swift extension UIView { func calculateAreaAndApplyShadow(scale: Bool = true) { let area = bounds.width * bounds.height // Assuming the view's shape is a rectangle let shadowRadius = sqrt(area) / 10 // Adjust the divisor for desired shadow intensity layer.masksToBounds = false la...
magicoder
swift
You are tasked with implementing a machine learning model class that includes a prediction method. The given code snippet is a part of the `predict` method of this class. The method takes a feature matrix `X` as input and returns the predictions based on whether the model is trained and whether it is a one-class classi...
```python import numpy as np class CustomModel: def __init__(self, oneclass=False): self.trained = False self.oneclass = oneclass self.learner = None def fit(self, X, y): # Implementation of model training # Set self.trained to True after training pass def ...
magicoder
python
You are tasked with implementing a function to calculate the multi-class Area Under the Curve (AUC) for a given set of target labels and corresponding model output probabilities. The AUC is a widely used metric for evaluating the performance of classification models. In this problem, you will need to write a Python fun...
```python def multi_class_auc(all_target, all_output, num_c=None): from sklearn.preprocessing import label_binarize from sklearn.metrics import roc_auc_score import numpy as np if num_c is None: num_c = len(np.unique(all_target)) # Binarize the target labels binarized_target = label_bi...
magicoder
python
You are tasked with implementing a class hierarchy for a role-playing game character system. The system should support different character classes, each with its own unique abilities and attributes. Your task is to design and implement the necessary classes and interfaces to support this system. You are provided with ...
```csharp // Define the interface for character classes public interface ICharacterClass { string ClassName { get; } void UseAbility(); int GetAttribute(string attributeName); } // Implement specific character classes public class Warrior : ICharacterClass { public string ClassName => "Warrior"; p...
magicoder
csharp
You are tasked with implementing a function to parse a given `res_body` dictionary and extract specific information related to a job step. The `res_body` dictionary contains details about a job step, including its name, ID, type, action on failure, properties, and status. The properties further include information such...
```python def parse_job_step(res_body): properties = res_body.get('properties', {}) jar_path = properties.get('jarPath', '') job_type = properties.get('jobType', '') input_path, output_path = properties.get('inputOutputPaths', '').split(', ') parsed_info = { 'name': res_body.get('name', '')...
magicoder
python
You are tasked with creating a Python function that renames files with a specific extension. Your function should take in a directory path, the current file extension, and the new file extension as input. It should then rename all files in the directory with the current file extension to the new file extension. Your f...
```python import os def rename_files(directory_path, current_extension, new_extension): renamed_count = 0 for file in os.listdir(directory_path): if file.endswith(current_extension): new_name = file.replace(current_extension, new_extension) if new_name != file: # Check if the n...
magicoder
python
You are given a partial implementation of a graph data structure in C. The code snippet provided includes the definition of a graph vertex and some related data structures. Your task is to complete the implementation of a function that checks whether a given graph is cyclic or acyclic. You need to implement the follow...
```c #include <stdio.h> #include <stdlib.h> #define MAXVEX 100 typedef char VertexType[3]; /*定义VertexType为char数组类型*/ typedef struct vertex { int adjvex; /*顶点编号*/ struct vertex *next; /*指向下一个邻接点的指针*/ } VertexNode; typedef struct { VertexType vexs[MAXVEX]; /*顶点表*/ VertexNode *adjlist[MAXVEX]; /*邻接表*/...
magicoder
c
You are tasked with implementing a circular buffer class in C++. A circular buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. When the buffer is full and a new element is inserted, it overwrites the oldest element in the buffer. Your task is to complete the implementat...
```cpp #include <cstdint> #include <cstring> class CircularBuffer : public Reader, public Writer { static const uint32_t BUFFER_SIZE = 1024; uint32_t last_sender_id_; uint32_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[BUFFER_SIZE]; public: CircularBuffer() : last_s...
magicoder
cpp
You are tasked with creating a function that simulates a simple vending machine. The vending machine will have a set of available items with corresponding prices. Users can insert coins into the machine and make a selection. The machine should dispense the selected item if the user has inserted enough money. If the use...
```javascript function VendingMachine(items) { this.availableItems = items; this.insertedCoins = 0; this.selectedItem = null; } VendingMachine.prototype.insertCoin = function(coin) { this.insertedCoins += coin; } VendingMachine.prototype.selectItem = function(itemName) { if (this.availableItems[it...
magicoder
javascript
You are tasked with implementing a custom type checker in Swift that mimics the behavior of the `as!` type cast operator. The `as!` operator performs a forced type cast, which attempts to convert an instance of a class or a value of a non-class type to a specified type. If the cast fails, a runtime error occurs. Your t...
```swift enum CustomTypeCastError: Error { case typeCastFailed } func customAs<T>(_ value: Any, to type: T.Type) throws -> T { if let castedValue = value as? T { return castedValue } else { throw CustomTypeCastError.typeCastFailed } } // Example usage: do { let intValue: Int = try ...
magicoder
swift
You are tasked with creating a Python class that can parse and instantiate FHIR (Fast Healthcare Interoperability Resources) resources from JSON files. FHIR is a standard for exchanging healthcare information electronically. Your task is to implement a class that can read a JSON file containing a FHIR resource, validat...
```python import os import io import json class FHIRParser: def __init__(self, datadir): self.datadir = datadir def instantiate_from(self, filename): with io.open(os.path.join(self.datadir, filename), 'r', encoding='utf-8') as handle: js = json.load(handle) resource_typ...
magicoder
python
You are tasked with implementing a Python context manager that logs the start and end of an activity using the `absl.logging` module. The context manager should handle any exceptions raised within the activity and log them as exceptions. Your task is to complete the implementation of the `log_activity` context manager ...
```python import contextlib import absl.logging @contextlib.contextmanager def log_activity(activity_name): try: absl.logging.info(f"Starting activity: {activity_name}") yield absl.logging.info(f"Completed activity: {activity_name}") except Exception as e: absl.logging.exception...
magicoder
python
You are working on a project that involves processing data from multiple cameras. The code snippet provided is a part of a larger program that processes camera calibration data. The snippet contains a class method that processes camera calibration information and performs some calculations using NumPy. Your task is to...
```python import numpy as np class CameraCalibrationProcessor: def __init__(self, T_front_cam_to_ref): self.T_front_cam_to_ref = T_front_cam_to_ref def cart_to_homo(self, matrix): homo_matrix = np.vstack((matrix, [0, 0, 0, 1])) return homo_matrix def process_calibration_data(self,...
magicoder
python
You are tasked with creating a program to parse and extract specific information from an API response. The response is in JSON format and contains two main sections: "meta" and "headers". The "meta" section includes a key-value pair with the key "total" and an integer value. The "headers" section includes several key-v...
```python import json # Sample API response in JSON format api_response = ''' { "meta": { "total": 3 }, "headers": { "content-type": "application/json; charset=utf-8", "status": 200, "ratelimit-limit": 1200, "ratelimit-remaining": 1137, "ratelimit-reset": 1415984218 } } ''' # Parse the...
magicoder
python
You are tasked with implementing a function to convert a hexadecimal string to an array of unsigned 8-bit integers (u8). The function should take a hexadecimal string as input and return a vector of u8 values representing the hexadecimal bytes. You need to implement the following function: ```rust /// Converts a hexad...
```rust pub fn hex_to_vec(hex: &str) -> Vec<u8> { let mut vec = Vec::with_capacity((hex.len() + 1) / 2); // Capacity based on the number of bytes let mut iter = hex.chars().peekable(); // Create a peekable iterator over the characters while let Some(c) = iter.next() { let byte = match c.to_digit(16...
magicoder
rust
You are tasked with implementing a simple user management system using Python. The system should allow for the creation of user profiles and the association of contexts with each user. A context is a specific setting or environment that can be linked to a user profile. Your task is to create a class `UserManagementSyst...
```python from typing import List class UserManagementSystem: def __init__(self): self.users = {} self.contexts = {} def add_user(self, name: str): user_id = len(self.users) + 1 self.users[user_id] = name def add_context(self, user_id: int, context: str): if user_i...
magicoder
python
You are tasked with creating a simplified version of a threading manager for executing functions in separate threads. Your goal is to implement a function that can run a given function in a new thread. You should also create a class that represents a simplified version of a social media platform, VK (Vkontakte), and im...
```python import threading def runThread(func, args=(), name=None): thr = threading.Thread(target=func, args=args, name=name or func.__name__) try: thr.start() except threading.ThreadError: crashlog("runThread.%s" % name) class VK: def login(self, username, password): # Simulat...
magicoder
python
You are tasked with creating a function that parses a given HTML string and extracts the URLs of all the images present in the string. The HTML string will contain image tags in the format `<img src='url' ...>` where `url` is the URL of the image. The function should return a list of all the image URLs present in the H...
```python from typing import List import re def extractImageUrls(html: str) -> List[str]: img_urls = re.findall(r"<img[^>]*?src=['\"](.*?)['\"][^>]*?>", html) return img_urls ```
magicoder
python
You are working on a project that involves managing a database schema using Alembic, a database migration tool for SQLAlchemy. Your task is to create a new migration script that adds a new table to the existing database schema. The table should store information about different services and their associated quotas. Yo...
```python def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table( 'service', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('name', sa.String(), nullable=True), sa.Column('quota', sa.String(), nullable=True), ...
magicoder
python
You are tasked with implementing a custom serialization mechanism for a specific data structure. The data structure represents a binary tree node, where each node has a value and references to its left and right children. Your goal is to write a serialization and deserialization algorithm for this binary tree node stru...
```csharp public class BinaryTreeSerializer { private const char NullNodeMarker = '#'; private const char ValueDelimiter = ','; public string Serialize(BinaryTreeNode root) { StringBuilder sb = new StringBuilder(); SerializeHelper(root, sb); return sb.ToString(); } priv...
magicoder
csharp
You are tasked with creating a program to analyze Verilog files and extract specific information from them. Your program needs to read Verilog files, identify LFSR (Linear Feedback Shift Register) modules, and extract the size of each LFSR module found in the files. Your task is to implement a function that takes a li...
```python import re from typing import List, Dict def extract_lfsr_sizes(file_names: List[str]) -> Dict[str, int]: lfsr_sizes = {} lfsr_regex = re.compile(r'module\s+lfsr_(\d+)\s*\(') for file_name in file_names: with open(file_name, 'r') as file: content = file.read() matc...
magicoder
python
You are tasked with creating a Python function that processes a given CSV file and returns the average value of a specific column. The CSV file contains data related to the sales of various products. The function should take the file path and the column name as input and return the average value of the specified column...
```python import pandas as pd def calculate_average_sales(csv_file, column_name): try: data = pd.read_csv(csv_file) average = data[column_name].mean() return round(average, 2) except FileNotFoundError: return "File not found" except KeyError: return "Column not found...
magicoder
python
You are given a Python function `where(condition, x, y)` that takes in three arguments: - `condition`: a boolean array represented as a Chainer variable - `x`: an array of values - `y`: an array of values The function `where` chooses elements from `x` or `y` depending on the values of the `condition`. If the `conditio...
```python def custom_where(condition, x, y): result = [] for c, xi, yi in zip(condition, x, y): result.append(xi if c else yi) return result # Example usage condition = [True, False, True, False] x = [1, 2, 3, 4] y = [5, 6, 7, 8] print(custom_where(condition, x, y)) # Output: [1, 6, 3, 8] ``` The...
magicoder
python
You are tasked with implementing a constraint system for validating input data in a web application. The system should support constraints for minimum and maximum length, as well as minimum value for numerical inputs. You are provided with a code snippet that outlines the constants for these constraints, but it seems t...
```javascript const CS_MINLENGTH = 'minlength'; /** * constraint maximum length * @var string */ const CS_MAXLENGTH = 'maxlength'; // corrected typo in the constant name /** * constraint minimum value * @var string */ const CS_MINVALUE = 'minvalue'; // added missing constant for minimum value constraint functi...
magicoder
javascript
You are tasked with implementing a clustering algorithm to group data points into homogeneous clusters based on local connectivity. The given code snippet initializes data points and provides some context about creating a graph capturing local connectivity. Your task is to complete the implementation by writing a funct...
```python import numpy as np from sklearn.neighbors import kneighbors_graph from sklearn.cluster import DBSCAN def local_connectivity_clustering(X, n_neighbors): # Create a graph capturing local connectivity connectivity_graph = kneighbors_graph(X, n_neighbors, mode='connectivity', include_self=True) # Im...
magicoder
python
You are given a Python code snippet that uses a prime number sieve function to find a specific value based on prime numbers. Your task is to understand the code and implement a similar prime number sieve function to solve a related problem. Write a Python function `find_special_value(limit)` that takes an integer `lim...
```python import time def prime_sieve(limit): sieve = [True] * (limit + 1) sieve[0:2] = [False, False] for num in range(2, int(limit ** 0.5) + 1): if sieve[num]: for multiple in range(num * num, limit + 1, num): sieve[multiple] = False return [i for i in range(limit ...
magicoder
python
You are tasked with implementing a function that creates a subgraph based on a set of intrinsics, rules, and subject types. The function should take in the intrinsics, rules, subject types, and other relevant parameters, and construct a subgraph based on these inputs. Additionally, the function should include a specifi...
```python def create_subgraph_with_intrinsics(intrinsics, A, rules, SubA, _suba_root_subject_types): # Implementation of create_subgraph_with_intrinsics function subgraph = {} # Placeholder for subgraph construction # TODO: Mark intrinsics in the dot format # Further implementation to construct the s...
magicoder
python
You are tasked with implementing a simulation of a repeller object in a 2D grid. The repeller object is represented by the following code snippet: ```csharp public class Repeller { public Repeller(int repellerRadius, int repelPower) { this.RepellerRadius = repellerRadius; this.RepelPower = repe...
```csharp public static int[,] CalculateRepellerInfluence(int[,] grid, int repellerX, int repellerY, Repeller repeller) { int width = grid.GetLength(0); int height = grid.GetLength(1); int[,] influenceGrid = new int[width, height]; for (int x = 0; x < width; x++) { for (int y = 0; y < heigh...
magicoder
csharp
You are tasked with creating a Rust function that interacts with an HTTP API to retrieve air quality data for multiple cities. The function should utilize the `RParifClient` struct, which is designed for making multiple calls to the API. The function should take an API key and a list of INSEE city codes as input. The I...
```rust use std::collections::HashMap; struct RParifClient { // Implementation details of RParifClient } #[derive(Debug)] enum RParifError { RequestError(reqwest::Error), CallError(reqwest::StatusCode), } #[derive(Debug)] struct AirQualityData { // Implementation details of AirQualityData } impl RPa...
magicoder
rust
You are tasked with creating a Python program that reads a directory path from the user and then lists all the files and subdirectories within that directory. Additionally, the program should display the total size of all the files in the directory in bytes. Your program should prompt the user to input a directory pat...
```python import os def list_files_and_calculate_size(): directory_path = input("Enter the directory path: ") if os.path.exists(directory_path) and os.path.isdir(directory_path): total_size = 0 print(f"Listing files and subdirectories in {directory_path}:") for item in os.listdir(direc...
magicoder
python
You are tasked with creating a Python function to scrape and extract specific bio stats of a Dota 2 hero from the official Dota 2 website. The function should take the hero's name as input and return their bio stats. The bio stats are located within the HTML of the hero's page on the Dota 2 website. The function shoul...
```python import requests from bs4 import BeautifulSoup def getting_dota2com_bio_stats(hero: str) -> str: url = "http://www.dota2.com/hero/%s/?l=english" % hero response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.content, 'html.parser') bio_stats = sou...
magicoder
python
You are tasked with creating a program that can efficiently install a list of software packages on a Linux system. The program should be able to handle both individual package installations and bulk installations. Your task is to implement a function that takes a list of software packages as input and installs them us...
```python import subprocess def install_packages(package_list): if not package_list: print("No packages to install.") return try: # Construct the command to install packages using apt command = ['sudo', 'apt', 'install', '-y'] + package_list # Execute the command using...
magicoder
python
You are tasked with creating a script to automate the testing of Docker images using Bats (Bash Automated Testing System). Your script should include the necessary setup and testing steps to ensure the successful building of a standard Docker image. Given the provided code snippet as a starting point, you need to expa...
```bash #!/usr/bin/env bats DOCKER_IMAGE_NAME_TO_TEST="standard_image" setup() { if [ "${BATS_TEST_NUMBER}" = 1 ]; then echo "# Testing ${DOCKER_IMAGE_NAME_TO_TEST}" >&3 fi } @test "We can build successfully the standard Docker image" { docker build -t "${DOCKER_IMAGE_NAME_TO_TEST}" "${BATS_TEST_DIRNAME}/....
magicoder
shell
You are given a C++ code snippet that defines two template structs: `index_impl` and `contains_impl`. The `index_impl` struct is used to find the index of a given type `T` within a template sequence `seq`. The `contains_impl` struct is used to determine if a given type `T` is present within a template sequence `seq`. Y...
```cpp #include <type_traits> #include <limits> template<typename T, template <typename...> class seq, typename... Ts> struct Index; template<typename T, template <typename...> class seq, typename... Ts> struct Index<T, seq<Ts...>> : std::integral_constant<std::size_t, Index<T, seq<Ts...>, 0>::value> {}; template<ty...
magicoder
cpp
You are working on a project that involves running a series of commands to fit models and create trajectories. Each command in the `commands.txt` file consists of two parts: model fitting and trajectory creation. The commands need to be executed in sequence, but each command can be executed independently and in paralle...
```python import subprocess def execute_command(command): process = subprocess.Popen(command, shell=True) process.wait() def main(): with open('commands.txt', 'r') as file: commands = file.readlines() for i in range(0, len(commands), 2): fit_model_command = commands[i].strip() ...
magicoder
python
You are tasked with implementing a Python class that denies access based on the content of a specified key in the input arguments. Your task is to complete the implementation of the `args_key_is_empty_or_allowed` class by adding a method that checks if the specified key in the input arguments is either empty or contain...
```python class args_key_is_empty_or_allowed: """Denies if args key is non-empty and not allowed.""" def __init__(self, args_key, allowed_extractor_func): self.args_key = args_key self.allowed_extractor_func = allowed_extractor_func def deny_access(self, input_args): # Check if the...
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The system should be able to create bank accounts, deposit and withdraw funds, and provide the account balance. Additionally, the program should be able to transfer funds between two accounts. Create a class `BankAccount` with the following...
```csharp using System; public class BankAccount { private static int accountNumberCounter = 1001; private int accountNumber; private double balance; public BankAccount(double initialBalance) { accountNumber = accountNumberCounter++; balance = initialBalance; } public void...
magicoder
csharp
You are tasked with implementing a Python class that manages file content and related information in a GitHub repository. The class should have the following attributes and methods: Attributes: - `file_commit_sha`: A string representing the commit SHA of the file. - `content`: A string representing the content of the ...
```python class GitHubFileManager: def __init__(self, file_commit_sha, content, github_obj, repo_last_commit_sha, pull_num): self.file_commit_sha = file_commit_sha self.content = content self.github_obj = github_obj self.repo_last_commit_sha = repo_last_commit_sha self.pull_n...
magicoder
python
You are working on implementing a variant of the AdaGrad optimization algorithm for training a machine learning model. The given code snippet is a part of the update step in the algorithm. Your task is to complete the implementation of the AdaGrad optimizer by writing a function that takes in the current parameters, gr...
```python import numpy as np def adaGradUpdate(params, grad, g, g2, mem, fixedRate, bestIter, r) -> np.ndarray: g2 = (1-r)*g2 + r*grad**2 rate = g*g/(g2+1e-16) mem *= (1 - rate) learningRate = fixedRate/(max(bestIter, 7)) mem += 1 alpha = np.minimum(learningRate, rate)/(np.sqrt(g2)+1e-16) r...
magicoder
python
You are working on a machine learning project and need to implement a custom loss function for a neural network. The loss function involves calculating the Hessian matrix of the network's output with respect to its parameters. You decide to use PyTorch to efficiently compute the Hessian matrix. The code snippet provide...
```python import torch def compute_scaled_mean_hessian(net, X, h_scale, num_observations): # Compute the Hessian matrix using PyTorch operations # net: neural network # X: input data # h_scale: scalar for scaling the mean Hessian # num_observations: number of observations in the dataset # Init...
magicoder
python
You are tasked with implementing a C++ template metaprogramming problem to determine and print prime numbers. Your goal is to complete the implementation of the `PrimeNumberPrinter` class template, which will print all prime numbers up to a given number. The provided code snippet contains a partial implementation of t...
```cpp template <int number, int divisor> class IsPrime { public: enum { primeNumber = (number == 2 || number % divisor != 0) && divisor * divisor <= number && IsPrime<number, divisor + 1>::primeNumber }; }; template <int number> class IsPrime<number, 1> { public: enum { primeNumber = numbe...
magicoder
cpp
You are tasked with implementing a function that removes the last element from a singly linked list and returns the removed element. The linked list is represented using the following Node class: ```python class Node: def __init__(self, value): self.value = value self.next = None ``` You need to i...
```python from typing import Union class Node: def __init__(self, value): self.value = value self.next = None def remove_last_element(head: Node) -> Union[int, None]: if head is None: # If the linked list is empty return None if head.next is None: # If the linked list has only o...
magicoder
python
You are tasked with creating a Python program to simulate a network port scanning tool. The program should generate a specified number of random UDP port numbers within a given range and attempt to send a single UDP packet to each port using the `hping3` tool. The goal is to identify open ports by observing the respons...
```python import subprocess import random def test_udp_ports(portTests, portFrom, portToo, ip): for _ in range(portTests): port = random.randint(portFrom, portToo) print(f"Trying UDP port {port}") subprocess.run(["sudo", "hping3", "-A", ip, "--udp", "-p", str(port), "-c", "1"]) # Example u...
magicoder
python
You are tasked with creating a custom test case class for a PHP application using the Orchestra Testbench library. The Orchestra Testbench library is commonly used for testing Laravel packages, and it provides a TestCase class that can be extended to create custom test cases. Your goal is to create a custom test case c...
```php namespace Orchestra\Testbench\Tests; use Orchestra\Testbench\TestCase; class CustomTestCase extends TestCase { public function testCustomFeature() { // Your specific test logic goes here $this->assertTrue(true); // Example assertion, replace with your actual test condition } } ```
magicoder
php
You are tasked with implementing a class method that processes data from a file and updates compound objects with specific properties. The provided code snippet is a part of a larger program and demonstrates the processing of data entries to attach a property called "dG" to compound objects. The `data` variable is an i...
```python class DataProcessor: def __init__(self, data): self.data = data self._logger = Logger() # Assume Logger class is available def process_data(self, data): for entry in data: fields = entry.split() idx = fields[0] # Assuming the index is in the first fie...
magicoder
python
You are tasked with implementing a class for handling chat messages in a messaging application. The provided code snippet is a part of the CChat class, which contains member functions for initializing and converting chat messages to a string representation. Your task is to complete the implementation of the CChat class...
```cpp #include <string> #include <sstream> class CChat { private: int nVersion; int nTime; int nID; bool bPrivate; std::string sPayload; std::string sFromNickName; std::string sToNickName; std::string sDestination; public: void SetPayload(const std::string& payload) { sPay...
magicoder
cpp
You are tasked with creating a Python function that processes data from a music forum and generates a JSON file containing information about the forum topics and their corresponding responses. The function should take a list of topic dictionaries as input, where each dictionary represents a forum topic and contains the...
```python import json from typing import List, Dict, Any def generate_music_forum_json(topics: List[Dict[str, Any]]) -> None: forum_data = {"topics": []} for topic in topics: topic_data = { "topic_id": str(topic['_id']), "author": topic['author'], "title": topic['tit...
magicoder
python
You are tasked with creating a program that simulates a simple text-based adventure game. The game will involve navigating through different rooms, encountering obstacles, and making decisions that affect the outcome of the game. Your task is to implement the `parse_input_arguments` function, which takes user input an...
```rust fn main() { match parse_input_arguments() { Ok(command) => { match command { Command::Go(direction) => { // Handle movement logic based on the specified direction // Update the player's current room and provide feedback ...
magicoder
rust
You are tasked with creating a script to automate the preprocessing and optimization of language model data using the SRILM toolkit. The script should handle the preparation of data, including text processing and vocabulary creation, as well as the optimization of language model parameters. Your task is to write a Bas...
```bash #!/bin/bash # Check if the vocabulary size is provided as a command-line argument if [ $# -ne 1 ]; then echo "Usage: $0 <vocab_size>" exit 1 fi vocab_size=$1 # Step 1: Convert text data to integer format prepare_int_data.py data/text data/vocab_${vocab_size}.txt data/int_${vocab_size} # Step 2: Record p...
magicoder
shell
You are tasked with implementing a program to extract and count the occurrences of specific namespaces in a given C++ header file. The namespaces are defined using the `namespace` keyword in C++. Your program should read the header file and output the count of each unique namespace present in the file. For example, gi...
```cpp #include <iostream> #include <fstream> #include <string> #include <map> #include <regex> int main() { std::ifstream file("input_header_file.hpp"); std::string line; std::map<std::string, int> namespaceCount; while (std::getline(file, line)) { std::smatch match; std::regex nsRege...
magicoder
cpp
You are tasked with implementing a function that validates a given subnet mask and returns the length of the prefix if the mask is valid. A subnet mask is a 32-bit number that consists of a series of contiguous 1s followed by a series of contiguous 0s. For example, 255.255.255.0 can be represented as 11111111.11111111....
```rust #[derive(Debug, PartialEq)] enum CidrError { InvalidPrefixLength, } fn validate_subnet_mask(mask: u32) -> Result<usize, CidrError> { let length = (!mask).leading_zeros(); if mask.leading_zeros() == 0 && mask.trailing_zeros() == mask.count_zeros() { Ok(length as usize) } else { E...
magicoder
rust
You are tasked with creating a Swift function to handle authentication requests using OAuth 2.0. The function should construct an HTTP request, send it to the token endpoint, and handle the response. You are provided with a code snippet that sets up the request and initiates a data task to handle the response. Your ta...
```swift func authenticateUser(grantType: String, resourceId: String, clientId: String, username: String, password: String, tokenEndPoint: String, requestType: String, contentType: String, completion: @escaping (Result<String, Error>) -> Void) { let authRequest = NSMutableURLRequest() let bodyString = "grant_ty...
magicoder
swift
You are tasked with creating a TypeScript interface for a set of Material Design Icons (MDI) used in a web application. The MDI icons are represented as React components and are imported from a library. Your goal is to define an interface that enforces the correct usage of these icons throughout the application. Given...
```typescript // Define the MdiIcon interface interface MdiIcon { (): MdiReactIconComponentType; default: MdiReactIconComponentType; } // Usage of the MdiIcon interface for CommentIcon const CommentIcon: MdiIcon = () => { return null; // Placeholder return for the icon component }; CommentIcon.default = CommentI...
magicoder
typescript
You are tasked with creating a program that analyzes the license information of software packages. The license information is provided in the form of a multi-line string, and your program needs to extract and display the license details. The license information is structured as follows: - The license text is enclosed ...
```python import re def analyze_license(license_text: str) -> dict: result = {} # Extracting the type and version of the license using regular expressions match = re.search(r'Licensed under the (.+), (.+) \(the "License"\)', license_text) if match: result["type"] = match.group(1) r...
magicoder
python
You are tasked with implementing a binary search tree (BST) in Python. A binary search tree is a data structure that satisfies the binary search property: for each node `n`, all nodes in the left subtree of `n` have values less than `n`, and all nodes in the right subtree of `n` have values greater than `n`. Your task...
```python class Node: def __init__(self, data): self.data = data self.left = None self.right = None def insert(self, data): if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) ...
magicoder
python
You are given a function `strRev` that takes a string `str` as input and reverses the order of words in the string. The function should return a new string with the words in reverse order, while maintaining the order of characters within each word. The input string `str` will consist of alphabets, spaces, and punctuati...
```swift func strRev(_ str: String) -> String { guard let lastSpaceIndex = str.lastIndex(of: " ") else { return str } let lastWord = String(str[str.index(after: lastSpaceIndex)...]) let remainingStr = String(str[..<lastSpaceIndex]) return lastWord + " " + strRev(remainingStr) } func reverse...
magicoder
swift
You are tasked with creating a Python extension module that interfaces with the Festival speech synthesis system. Festival is a general multi-lingual speech synthesis system developed at the Centre for Speech Technology Research at the University of Edinburgh. The given code snippet is a part of a setup script for buil...
To solve this problem, you need to implement the C++ function for speech synthesis and ensure that it can be called from Python using the extension module. Here's a sample solution for the `_festival.cpp` file: ```cpp #include <Python.h> #include <festival.h> static PyObject* festival_speak(PyObject* self, PyObject* ...
magicoder
cpp
You are tasked with creating a Python function that takes a list of integers as input and returns a dictionary containing the frequency of each unique integer in the input list. The function should be named `calculate_frequency` and should take a single parameter: - `input_list`: a list of integers (1 <= length <= 10^...
```python def calculate_frequency(input_list): sequence_frequencies = {} for num in input_list: if num in sequence_frequencies: sequence_frequencies[num] += 1 else: sequence_frequencies[num] = 1 return sequence_frequencies ``` The `calculate_frequency` function itera...
magicoder
python