query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Python function that processes and visualizes data from a CSV file containing information about monthly sales of a company. The function should read the CSV file, calculate the total sales for each month, and then generate a bar plot to visualize the monthly sales data. The code snippet p...
```python import pandas as pd import matplotlib.pyplot as plt def visualize_monthly_sales(csv_file): # Read the CSV file into a pandas DataFrame sales_data = pd.read_csv(csv_file) # Calculate total sales for each month monthly_sales = sales_data.groupby('Month')['Sales'].sum() # Generate a bar pl...
magicoder
python
You are tasked with creating a Python function that manages virtual environments using the `conda` package manager. Your goal is to implement a function that creates a new virtual environment and another function that removes an existing virtual environment. The `conda` package manager is used to manage software packag...
```python import subprocess def create_env(name, version): """Create virtual environment using conda package manager. Args: name (str): Name of the virtual environment. version (str): Python version to be used in the virtual environment. Returns: str: Message indicating the status of ...
magicoder
python
You are working on a data analysis project and need to implement a function to calculate estimates and areas based on given data. The provided code snippet is part of a larger data processing pipeline and contains operations related to matrix manipulation and data aggregation. Your task is to implement a function that ...
```python import numpy as np import pandas as pd def calculate_estimates_and_area(source_df, variable, weights, UT, SU): def _nan_check(df, var): # Implementation of NaN check function pass def _inf_check(df, var): # Implementation of infinity check function pass vals = _n...
magicoder
python
You are tasked with implementing a custom hash map in Java. Your hash map should support the basic operations of putting a key-value pair, getting the value associated with a given key, and removing a key-value pair. Additionally, your hash map should handle collisions using separate chaining. Your custom hash map sho...
```java import java.util.LinkedList; class MyHashMap { private static final int SIZE = 1000; private LinkedList<Entry>[] buckets; public MyHashMap() { buckets = new LinkedList[SIZE]; for (int i = 0; i < SIZE; i++) { buckets[i] = new LinkedList<>(); } } public v...
magicoder
java
You are tasked with creating a Python function that validates whether a given string matches a specific pattern using regular expressions. Your function should take a pattern string as input and return a compiled regular expression object that matches the given pattern. Additionally, you need to implement a test case t...
```python import re from unittest import TestCase class TestRegex(TestCase): def pattern_equal_rex(self, pattern): try: # Remove trailing "$" characters from the pattern modified_pattern = pattern.rstrip("$") # Compile the modified pattern into a regular expression objec...
magicoder
python
You are tasked with creating a Python script to exploit a potential vulnerability in an FTP server. The given code snippet is part of an exploit script that attempts to connect to an FTP server at IP address 192.168.129.128 on port 21 and send a crafted "USER" command. The variable `junk` is used in the script to poten...
```python import socket # Craft the payload for the 'USER' command to potentially exploit a buffer overflow junk = b'A' * 1000 # Replace with the appropriate payload to potentially exploit the buffer overflow # Create a socket and connect to the FTP server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.conn...
magicoder
python
You are tasked with creating a Python function that validates a MongoDB connection string. The connection string is a URI-like string used to connect to a MongoDB database. It contains various parameters and their values, separated by commas. Your function should check if the connection string is valid by ensuring that...
```python def validate_mongodb_connection_string(connection_string: str) -> bool: required_params = {'username', 'password', 'authSource'} # Split the connection string to extract parameters params = connection_string.split('//')[-1].split('@')[-1].split('/')[0].split('?')[0].split('&') # Crea...
magicoder
python
You are tasked with creating a Python function that prepares a DataFrame for visualization using a radar chart. The radar chart will display the frequency of occurrences for different categories within the DataFrame. Your task is to implement the function `prepare_df` that takes a DataFrame and a grouping column as inp...
```python import pandas as pd def prepare_df(df, grouping): """ Prepares the DataFrame for visualization using a radar chart. Parameters ---------- df : pandas.DataFrame The input DataFrame containing the data to be prepared for visualization. grouping : str The column name bas...
magicoder
python
You are tasked with implementing a custom `throwing::unique_ptr` class, which is a simplified version of the standard `std::unique_ptr` in C++. The `throwing::unique_ptr` class is designed to manage dynamic memory allocation and deallocation for a single object or an array of objects. However, it differs from `std::uni...
```cpp #include <iostream> class ThrowingUniquePtrException : public std::exception { public: const char* what() const noexcept override { return "Assignment from throwing::unique_ptr to another is not allowed"; } }; template <typename T> class throwing::unique_ptr { private: T* ptr; public: ...
magicoder
cpp
You are tasked with implementing a simple command-line application for managing a list of tasks. The application should allow users to add tasks, mark tasks as completed, view all tasks, and delete tasks. The tasks should be stored in memory and should persist for the duration of the application's execution. Your task...
```javascript class TaskManager { constructor() { this.tasks = []; } addTask(task) { this.tasks.push({ task, completed: false }); } completeTask(index) { if (index >= 0 && index < this.tasks.length) { this.tasks[index].completed = true; } else { console.log("Invalid task index");...
magicoder
javascript
You are tasked with implementing a function that processes a list of import statements in a programming language. Each import statement follows the format `pub use self::error::{Error, PortalError};`, where `pub` denotes the visibility, `self::error` is the module path, and `Error` and `PortalError` are the specific it...
```python from typing import List, Dict def process_imports(imports: List[str]) -> Dict[str, List[str]]: import_map = {} for imp in imports: parts = imp.split("::") module_path = parts[1].split("{")[0].strip() items = parts[1].split("{")[1].split("}")[0].split(",") items = [item...
magicoder
python
You are tasked with creating a Python function that interacts with a database using asynchronous operations. Your goal is to implement a function that initializes a database by dropping existing tables and creating new ones using the provided asynchronous engine. You are given the following code snippet as a reference...
```python from sqlalchemy.ext.asyncio import AsyncEngine from sqlalchemy import create_engine, MetaData async def init_db(engine: AsyncEngine): async with engine.begin() as conn: metadata = MetaData() metadata.bind = engine await conn.run_sync(metadata.drop_all) await conn.run_sync(...
magicoder
python
You are tasked with implementing a word attribute system for a text processing application. The system should allow the user to set various attributes for words in a text. Each word can have multiple attributes associated with it, and these attributes can be of different types. The attributes can be set using the `set_...
```cpp #include <iostream> #include <unordered_map> #include <vector> #include <string> enum class word_attribute { place, compound }; enum class place_attribute { grab, release, none }; enum class compound_attribute { grab, release, none }; class WordAttributes { private: std::u...
magicoder
cpp
You are working on a project that involves parsing and validating YANG data models. YANG is a data modeling language used to model configuration and state data manipulated by the Network Configuration Protocol (NETCONF), NETCONF Remote Procedure Call (RPC), and NETCONF Notifications. Your task is to implement a Python ...
```python class YANGDataClass: def __init__(self, yang_name, base_type, restriction_dict, int_size, is_leaf, yang_type, is_config, namespace, defining_module): self.yang_name = yang_name self.base_type = base_type self.restriction_dict = restriction_dict self.int_size = int_size ...
magicoder
python
You are tasked with creating a program that manages a file explorer interface. The program should be able to display a file tree, a log list, a homepage, and code icons. To achieve this, you need to implement the necessary functionality for each component and ensure they work together seamlessly. Your task is to creat...
```rust // Import necessary modules use makepad_widget::*; use crate::filetree::*; use crate::loglist::*; use crate::homepage::*; use crate::codeicon::*; // Define the main application struct struct FileExplorerApp { file_tree: FileTree, log_list: LogList, home_page: HomePage, code_icons: CodeIcons, } ...
magicoder
rust
You are tasked with implementing a function to process a given post and extract the largest image and video dimensions from it. The post is represented as an associative array `$post`, containing the keys 'format' and 'embed_html'. The 'format' key holds an array of images, each represented as an associative array with...
```php function extractLargestDimensions($post) { $largestImage = ['width' => 0, 'height' => 0]; foreach ($post['format'] as $image) { if ($image['width'] > $largestImage['width']) { $largestImage = $image; } } preg_match('/width="(\d+?)".+?height="(\d+?)"/', $post['embed_ht...
magicoder
php
You are tasked with implementing a custom loss function for a neural network training process. The loss function is a combination of Negative Log-Likelihood (NLL) loss and Kullback-Leibler (KL) divergence loss, with an additional weighting factor for the KL loss. The loss is then normalized by the batch size and moved ...
```python def custom_loss(NLL_loss, KL_loss, KL_weight, batch_size, device): combined_loss = (NLL_loss + KL_weight * KL_loss) / batch_size normalized_loss = combined_loss.to(device) return normalized_loss ``` The provided solution defines a function `custom_loss` that takes the NLL loss, KL loss, KL weight...
magicoder
python
You are tasked with creating a Python function that simulates the behavior of a package manager's load command. The load command is responsible for loading a package and its dependencies. The function should take a parser and arguments as input and return the specifications of the package and its dependencies based on ...
```python def load(parser, args): env = ev.get_env(args, 'load') # Assuming ev.get_env is a function to retrieve the environment specs = [spack.cmd.disambiguate_spec(spec, env, first=args.load_first) for spec in args.packages] return specs ``` In the solution, the `load` function retrieves the environment...
magicoder
python
You are tasked with implementing a Python package for parsing and handling HTTP requests and responses. The package structure is as follows: ``` multi_parser/ ├── shared/ │ ├── __init__.py │ ├── request.py │ └── response.py ``` The `__init__.py` file serves as the entry point for the `shared` mo...
```python # shared/request.py class HTTPRequest: def parse_request(self, request_data): # Implement request parsing logic here pass # shared/response.py class HTTPResponse: def construct_response(self, status_code, headers, body): # Implement response construction logic here pas...
magicoder
python
You are tasked with creating a class hierarchy for a medical practice management system. The system should be able to categorize different types of medical practices and provide a way to manage and organize them. Your task is to design and implement the class hierarchy for this system. You are provided with a code sni...
```csharp ///<summary>Interface for medical practice details.</summary> public interface IMedicalPractice { string GetPracticeDetails(); } ///<summary>Represents a hospital in the medical practice system.</summary> public class Hospital : MedicineSystem, IMedicalPractice { public string Name { get; set; } ...
magicoder
csharp
You are tasked with implementing a class for managing HTML elements' class attributes in a web development project. The class should provide methods for adding, removing, toggling, and checking the presence of classes within the class attribute of an HTML element. Your task is to create a JavaScript class called `Clas...
```javascript class ClassManager { constructor(element) { this.element = element; } addClass(className) { if (!this.element.classList.contains(className)) { this.element.classList.add(className); } } removeClass(className) { if (this.element.classList.contains(className)) { this....
magicoder
javascript
You are tasked with creating a Python class that can generate memes by adding captions to images. Your class should have a method `make_meme` that takes in the path of the original image, the text for the caption, the author of the meme, and an optional width for the meme. The method should return the path of the saved...
```python from PIL import Image, ImageDraw, ImageFont import os class MemeGenerator: def make_meme(self, img_path: str, text: str, author: str, width: int = 500) -> str: # Open the original image original_image = Image.open(img_path) # Set up the drawing context draw = ImageDraw.Dr...
magicoder
python
You are tasked with implementing a function to verify the correctness of a cryptographic operation using the given code snippet as a reference. The code snippet is part of a cryptographic verification process using the OpenSSL library in C++. Your task is to implement a function `verifyCryptographicOperation` that tak...
```cpp #include <openssl/bn.h> #include <iostream> bool verifyCryptographicOperation(BIGNUM* XT, BIGNUM* salt, BIGNUM* d, BIGNUM* e2, BIGNUM* add, BIGNUM* t4, BIGNUM* e, BIGNUM* n, BIGNUM* m, BIGNUM* T, BN_CTX* ctx) { BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t4, t4, e...
magicoder
cpp
You are tasked with implementing a timer class for a network simulation project. The timer class, named TdTimer, is a subclass of the Timer class and is used in the context of a network simulation framework. The TdTimer class is responsible for handling timed events in the simulation. Your task is to complete the imple...
```java package projects.GAF.nodes.timers; import projects.GAF.nodes.messages.DiscoveryMessage; import projects.GAF.nodes.nodeImplementations.GAF; import projects.GAF.nodes.nodeImplementations.GAF.States; import sinalgo.nodes.timers.Timer; public class TdTimer extends Timer { // Other methods and attributes ...
magicoder
java
You are tasked with creating a Python program to analyze the results of a Monte Carlo simulation for photon intensity and K-ratios. The simulation results are stored in the `pymontecarlo` package, which provides modules for handling photon intensity and K-ratio data. Your program should read the simulation results and ...
```python # Import necessary modules from the pymontecarlo package from pymontecarlo.results.photonintensity import PhotonIntensityResult from pymontecarlo.results.kratio import KRatioResult # Read the simulation results from a file or data source # Assuming the simulation results are stored in 'photon_intensity_resul...
magicoder
python
You are tasked with creating a Python function that reads data from a TFRecord file and returns a specified number of records as a list of dictionaries. TFRecord is a binary file format used in TensorFlow for storing large amounts of data efficiently. The function should take the file path of the TFRecord file and the ...
```python from tfrecord_handler._io import * import tensorflow as tf from typing import List, Dict, Any def read_tfrecord(file_path: str, num_records: int) -> List[Dict[str, Any]]: records = [] record_iterator = tf.python_io.tf_record_iterator(file_path) for _ in range(num_records): try: ...
magicoder
python
You are tasked with implementing a custom API specification framework in Python. The framework should allow users to register definition helpers and path helpers for generating API documentation. Definition helpers are responsible for defining data models, while path helpers are used for defining API paths. Your task ...
```python import smore.apispec.core class APISpec: def __init__(self): self._definition_helpers = [] self._path_helpers = [] def register_definition_helper(self, func): """ Register a new definition helper. The helper **must** meet the following conditions: - Include ``...
magicoder
python
You are tasked with implementing a method to remove old games from a game repository based on their age. The method should take the maximum age of games in hours as a parameter and remove all games older than this threshold. The method should return the number of games removed as a response. You are provided with the ...
```java import com.google.common.collect.ImmutableMap; import javax.ws.rs.core.Response; public class GameRepository { private List<Game> games; // Assume games is a list of Game objects public Response removeOldGames(int maxAgeInHours) { int gamesRemoved = 0; Iterator<Game> iterator = games.i...
magicoder
java
You are tasked with implementing a simplified version of a stream deletion function in a hypothetical streaming service. The function takes in the stream name and a set of options and attempts to delete the specified stream. If successful, it prints a message indicating the deletion. If an error occurs during the delet...
```cpp #include <iostream> #include <string> enum class ErrorType { NoError, StreamNotFound, PermissionDenied, InternalError }; struct DeleteStreamOptions { bool forceDelete; bool recursiveDelete; }; ErrorType DeleteStream(const std::string& streamName, const DeleteStreamOptions& options) { ...
magicoder
cpp
You are tasked with implementing a neural network model using the given code snippet. The model consists of two populations of neurons: excitatory (E) and inhibitory (I). The code snippet contains a function that computes the derivatives of the membrane potentials for the E and I populations based on a set of different...
```python import numpy as np import matplotlib.pyplot as plt def F(x, a, theta): return 1 / (1 + np.exp(-a * (x - theta))) def simulate_network(pars, duration, dt): wEE, wEI = pars['wEE'], pars['wEI'] wIE, wII = pars['wIE'], pars['wII'] I_ext_E, I_ext_I = pars['I_ext_E'], pars['I_ext_I'] a_E, a_I ...
magicoder
python
You are tasked with creating a PHP function that can extract and decode a hidden message from a given string. The message is encoded using ionCube Loader, and it is embedded within a long string of seemingly random characters. Your task is to write a function that can extract and decode this hidden message. Write a PH...
```php function decodeIonCubeMessage($encodedMessage) { $decodedMessage = ''; $encodedMessage = base64_decode($encodedMessage); // Decode the base64 encoded message $decodedMessage = ioncube_read_file($encodedMessage); // Use ionCube Loader to decode the message return $decodedMessage; } // Test the fu...
magicoder
php
You are tasked with implementing a resource management system for a game engine. The system should handle the loading and unloading of game levels and the associated resources. Each level has a queue of tasks that need to be executed when the level is loaded. Additionally, when a level change is finished, an event shou...
```cpp // Resource Management System Implementation // Define a class to manage the resource loading and unloading class ResourceManager { public: // Method to load a level and trigger the LevelLoaded event void LoadLevel(const std::string& levelName) { // Load the level and associated resources ...
magicoder
cpp
You are tasked with implementing a Python class that manages background tasks using a task queue. The class should have a method to add a new task to the queue and a method to retrieve the next task to be executed. Additionally, the class should have a property to access the delay time for the next task in the queue. ...
```python class BackgroundTaskManager: def __init__(self): self.__task_queue__ = [] def add_task(self, task): # Add the task to the task queue self.__task_queue__.append(task) def get_next_task(self): # Retrieve and remove the next task from the task queue i...
magicoder
python
You are given an array `sizes` containing the sizes of different datasets and an empty 2D array `inputs`. Your task is to generate random input data for each dataset size and populate the `inputs` array with the generated data. The input data for each dataset size should be an array of random numbers. The length of th...
```typescript function generateInputData(sizes: number[], inputs: number[][]): void { for (let size of sizes) { const data: number[] = []; for (let i = 0; i < size; i++) { data.push(Math.floor(Math.random() * 1000) + 1); } inputs.push(data); } } ```
magicoder
typescript
You are tasked with creating a program that processes a list of annotations and extracts the keys associated with them. Annotations are special labels applied to program elements, such as classes, methods, or properties, to convey additional information. In this problem, you will focus on extracting keys from annotatio...
```csharp using System; using System.Collections.Generic; using System.Text.RegularExpressions; public class AnnotationKeyExtractor { public List<string> ExtractKeysFromAnnotations(string codeSnippet) { List<string> keys = new List<string>(); // Define the pattern to match the annotati...
magicoder
csharp
You are tasked with creating a function to decode ERC20 token contract information from RPC responses. The function should handle potential errors and return a structured token object upon successful decoding. You are given a code snippet that attempts to decode the name and symbol of an ERC20 token contract. The `rea...
```rust struct Token { name: String, symbol: String, // Other fields can be added if necessary } fn decode_erc20_token(rpc_responses_unmarshalled: &UnmarshalledResponses, pair_token_address: &str) -> Result<Token, String> { let decoded_name = read_string(rpc_responses_unmarshalled.responses[1].raw.as_r...
magicoder
rust
You are tasked with creating a Python class that simulates a simple forum thread management system. The class should allow users to create new threads, reply to existing threads, and retrieve statistics about the threads. Your task is to implement the `ThreadManager` class with the following methods: 1. `create_threa...
```python class ThreadManager: def __init__(self): self.threads = {} self.next_thread_id = 1 self.total_replies = 0 def create_thread(self, title: str, content: str) -> int: thread_id = self.next_thread_id self.threads[thread_id] = {'title': title, 'content': content, 'r...
magicoder
python
You are tasked with implementing a method to perform a left view traversal of a binary tree. The left view of a binary tree is the set of nodes visible when the tree is viewed from the left side. In other words, it is the nodes that are visible at the first level of each depth in the tree. You are given a partially im...
```csharp using System; using System.Collections.Generic; public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } } public class BinaryTreeLeftView { public IList<int> LeftView(TreeNode root) { IList<int...
magicoder
csharp
You are tasked with implementing a dynamic array data structure in C#. A dynamic array is a resizable array that allows for efficient insertion and deletion of elements at the end of the array. Your task is to implement the `DynamicArray` class with the following specifications: - The class should have a private field...
```csharp public class DynamicArray { private int length; private dynamic[] values; public bool IsStatic { get; private set; } public DynamicArray(bool isStatic, int initialCapacity) { length = 0; values = new dynamic[initialCapacity]; IsStatic = isStatic; } public...
magicoder
csharp
You are tasked with testing a Python function that updates the status of nodes in a distributed system. The function takes in a batch size, a flag indicating whether the update should be all-or-nothing, and a mock Boto3 response. It then updates the nodes based on the response and returns the number of failed nodes, th...
```python import unittest def test_update_node_status(): # Your test case implementation using the provided variables # Mock the Boto3 calls and response with mocker: boto3_stubber.add_response('update_node_status', mock_boto3_response) # Call the function to update node status fai...
magicoder
python
You are tasked with implementing a function that encodes a given unsigned 64-bit integer into a variable-length byte sequence using a specific encoding scheme. The encoding scheme uses a 7-bit encoding with the most significant bit (MSB) of each byte serving as a continuation flag. If the MSB is set, it indicates that ...
```rust use std::io::{Result, Write}; #[derive(Debug)] pub struct UnsignedVarLong(pub u64); impl UnsignedVarLong { pub fn encode_varlong<W: Write>(&self, writer: &mut W) -> Result<()> { let mut value = self.0; if value == 0 { writer.write(&[0])?; } else { while valu...
magicoder
rust
You are tasked with implementing a custom FNV-1a hashing algorithm for hashing sequences of elements. The FNV-1a algorithm is a non-cryptographic hash function that produces a 64-bit hash value. Your goal is to create a generic FNV1aHasher class that can hash sequences of any type of elements. The FNV1aHasher class sho...
```swift // Define a generic FNV1aHasher class for hashing sequences class FNV1aHasher<T> { private var hashValue: UInt64 = 14695981039346656037 // FNV offset basis private let fnvPrime: UInt64 = 1099511628211 // FNV prime // Add an element to the sequence being hashed func add(_ element: T?) { ...
magicoder
swift
You are tasked with creating a script to automate the setup of a MySQL server on a Linux system. The script should perform the following tasks: 1. Set the ownership of the MySQL data directory to the user and group "mysql". 2. Start the MySQL server using the `mysqld_safe` command with the specified data directory. 3....
```bash #!/bin/bash # Set ownership of the MySQL data directory chown -R mysql:mysql /var/lib/mysql # Start the MySQL server cd '/usr' && /usr/bin/mysqld_safe --datadir='/var/lib/mysql' & # Wait for 5 seconds sleep 5 # Execute MySQL command to delete specific user entries mysql -uroot -e "DELETE FROM mysql.user WHE...
magicoder
shell
You are tasked with implementing a module dependency resolver for a programming language. The given code snippet represents a collection of module names within a Rust project. Your goal is to create a function that takes this collection of module names and returns a valid order in which the modules can be compiled, con...
```rust use std::collections::{HashMap, HashSet}; fn resolve_module_dependencies(modules: &[&str]) -> Option<Vec<&str>> { let mut graph: HashMap<&str, HashSet<&str>> = HashMap::new(); let mut in_degree: HashMap<&str, usize> = HashMap::new(); // Build the dependency graph and calculate in-degrees for m...
magicoder
rust
You are tasked with implementing a resource manager class in Swift that handles the registration of projects and encoding of the root configuration. The root configuration is a dictionary that maps project handles to their respective directory URLs. Your goal is to extend the resource manager class with the ability to ...
```swift class ResourceManager { var rootConfig: [String: URL] = [:] func addProject(projectHandle: String, currentDirURL: URL) { rootConfig[projectHandle] = currentDirURL encodeRootConfig(config: rootConfig) successMessage(msg: "Project \(projectHandle) has been registered and is locat...
magicoder
swift
You are tasked with implementing a Python class that simulates a logging configuration system. The system should support the creation of configurable loggers and the ability to inherit logging configurations from parent loggers. Your task is to create a `LoggingConfigurable` class that fulfills these requirements. The...
```python import logging class LoggingConfigurable: _root_logger = logging.getLogger() def __init__(self, log=None, parent=None): if log is not None: self._logger = log elif parent is not None: self._logger = parent._logger.getChild(self.__class__.__name__) else...
magicoder
python
You are tasked with implementing a test case for a message handling system. The system has a method `test_qgetdata` which takes several parameters and performs a series of checks. The method `wait_for_qgetdata` is also mentioned, which is used to wait for a response from the system. Your task is to create a test case t...
```python def test_qgetdata(self, qgetdata, expected_error=0, len_vvec=0, len_contributions=0, response_expected=True): # Send the qgetdata message to the system for processing self.send_message(qgetdata) # Wait for a response from the system, if response_expected is True if response_expected: ...
magicoder
python
You are tasked with creating a Python function that processes a list of metadata for a software package and extracts specific information from it. The metadata is represented as a list of strings, where each string contains information about the package, such as its intended audience, license, natural language, program...
```python from typing import List, Tuple def extract_metadata(metadata: List[str]) -> Tuple[str, List[str]]: programming_language = next((data.split('::')[1].strip() for data in metadata if data.startswith('Programming Language ::')), None) keywords = next((eval(data.split('=')[1].strip()) for data in metadata...
magicoder
python
You are tasked with creating a Rust program that manages a storage directory. The program needs to handle the scenario where the storage directory already exists and the scenario where it needs to create the directory. Your task is to implement the logic for handling these scenarios. Your program should have the follo...
```rust use log::{info, debug}; use std::fs; fn create_storage_directory(storage_dir_path: &str) { if !fs::metadata(storage_dir_path).is_ok() { fs::create_dir_all(storage_dir_path).expect("Failed to create storage directory"); let abs_path = fs::canonicalize(storage_dir_path).expect("Failed to get ...
magicoder
rust
You are tasked with creating a Python class that manages a library of books. The class should support adding books, removing books, and listing all the books in the library. Additionally, the class should have a method to check if a specific book is available in the library. You need to implement the `Library` class w...
```python class BookNotInLibraryError(Exception): pass class Library: def __init__(self): self.books = [] def add_book(self, book_title): self.books.append(book_title) def remove_book(self, book_title): if book_title in self.books: self.books.remove(book_title) ...
magicoder
python
You are tasked with implementing a function that constructs a SQL query based on a given set of filter conditions. The function should take in a list of filter conditions and generate a SQL query string that includes the appropriate WHERE clause and handles the logical operators between the conditions. You are given t...
```java public String generateSQLQuery(List<FilterCondition> conditions) { StringBuilder sql = new StringBuilder("SELECT * FROM table_name"); boolean firstCondition = true; for (FilterCondition condition : conditions) { if (firstCondition) { sql.append(" WHERE "); firstCondit...
magicoder
java
You are tasked with implementing a Python class that extends another class and overrides its methods. The base class `_2dCSCG_S0F_VIS_Matplot` is provided, and you need to create a subclass `_2dCSCG_S2F_VIS_Matplot` that inherits from the base class and adds its own functionality. Your task is to implement the `_2dCSC...
```python import matplotlib.pyplot as plt class _2dCSCG_S2F_VIS_Matplot(_2dCSCG_S0F_VIS_Matplot): def plot_data(self, data_points): # Call the base class method if needed super().plot_data(data_points) # Plot the data using Matplotlib x_values = [point[0] for point in data_points] ...
magicoder
python
You are tasked with creating a Python function to clean and parse contact names from a given dataset. The dataset contains records with contact information, and the goal is to extract and standardize the contact names. The provided code snippet is a unit test using the `pytest` framework to validate the functionality o...
```python import numpy as np def parse_contact_name(record: dict, contact_columns: list, strict: bool) -> tuple: contact_info = [record.get(col, np.nan) for col in contact_columns] if strict and any(pd.isnull(info) for info in contact_info): raise ValueError("Incomplete contact name information") ...
magicoder
python
You are tasked with implementing a function to solve the optimization problem for finding the minimum rank of a matrix factorization. The problem is defined as follows: Given matrices Y and X, the objective is to find matrix D that minimizes the following function: \[ \min_{D} 0.5 \lVert Y - DX \rVert_F^2 + \lambda \l...
```python import numpy as np from scipy.optimize import minimize from scipy.linalg import svd def min_rank_dict(Y, X, lambdaD, Dinit, iterations=100, tol=1e-8): def objective_function(D): return 0.5 * np.linalg.norm(Y - np.dot(D, X)) ** 2 + lambdaD * np.linalg.norm(svd(D)[1], 1) def constraint_functio...
magicoder
python
You are tasked with implementing a function that calculates the hash value of a given input string using the SHA-256 algorithm. The provided code snippet demonstrates the final steps of the hash calculation process, where the hash value is formatted and returned as a string. Your task is to complete the implementation ...
```swift import CommonCrypto func calculateSHA256Hash(_ input: String) -> String { if let data = input.data(using: .utf8) { var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in _ = CC_SHA256(buffer.baseAddress, ...
magicoder
swift
You are tasked with creating a function that parses a given HTML code snippet and extracts the attributes and their corresponding values from the input elements. The input elements are represented by the `<input>` tag within the provided HTML code snippet. The attributes to be extracted include `type`, `name`, `id`, an...
```javascript function parseHTMLInputAttributes(htmlCode) { const inputRegex = /<input\s+([^>]*)>/g; const attributeRegex = /(\w+)="([^"]*)"/g; const inputs = htmlCode.match(inputRegex); const result = {}; if (inputs) { inputs.forEach((input, index) => { const attributes = {}; let match; ...
magicoder
javascript
You are tasked with creating a program that analyzes a given text file to determine the frequency of each word in the file. Your program should read the text file, tokenize the words, and then count the occurrences of each word. The program should then output the list of unique words along with their frequencies in des...
```python import re from collections import Counter def word_frequency_counter(file_path): with open(file_path, 'r') as file: text = file.read().lower() # Read the file and convert text to lowercase words = re.findall(r'\b\w+\b', text) # Tokenize the words using regular expression word_co...
magicoder
python
You are working on a script that retrieves secrets from an S3 bucket and sets environment variables based on the retrieved secrets. The script uses the AWS CLI to copy the secrets file from the S3 bucket to the local environment. It then extracts the `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` from the secrets file a...
```bash set_github_secrets() { local secrets_uri="$1" local secrets_file="$2" # Use AWS CLI to copy secrets file from S3 bucket to local file path aws s3 cp "${secrets_uri}" "${secrets_file}" 1>&2 # Extract GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET from the secrets file GITHUB_CLIENT_ID="${GITHUB_CLIENT_I...
magicoder
shell
You are tasked with creating a Python function that processes package information and generates compiler flags for C and C++ programs. The function should take in several parameters and perform specific operations based on the input. Your task is to implement the function according to the given requirements. Function ...
```python def generate_compiler_flags(hdrs: list, shlibs: list, v: int, cflags: list) -> list: if not hdrs: raise ValueError("failed to locate headers") if not shlibs: raise ValueError("failed to locate any shared libs") if v > 0: print(f"Package headers: {' '.join(hdrs)}") ...
magicoder
python
You are tasked with implementing a class for managing a linked list of integers. The class, named `LinkedList`, should support various operations on the linked list, including insertion, deletion, and searching for elements. Your task is to implement the `LinkedList` class with the following specifications: 1. The cl...
```cpp #include <iostream> class LinkedList { private: struct Node { int value; Node* next; Node(int val) : value(val), next(nullptr) {} }; Node* ensemble; public: LinkedList() : ensemble(nullptr) {} void insert(int value) { Node* newNode = new Node(value); ...
magicoder
cpp
You are tasked with creating a Python program that interacts with a Bluetooth Low Energy (BLE) device. The program should connect to a specific BLE peripheral device, subscribe to a characteristic, and then print the received data. The UUID of the characteristic to subscribe to is provided as `YOUR_CHAR_UUID`. You are ...
```python from bluepy.btle import Peripheral, DefaultDelegate class CharDelegate(DefaultDelegate): def __init__(self): DefaultDelegate.__init__(self) def handleNotification(self, cHandle, data): print("Received data:", data.decode('utf-8')) YOUR_ADDRESS = "00:00:00:00:00:00" # Replace with t...
magicoder
python
You are tasked with creating a program to manage a database of employees in a company. The program should allow for the creation, retrieval, updating, and deletion of employee records. To achieve this, you need to implement a class called `EmployeeDatabase` with the following functionalities: 1. `addEmployee(name: str...
```javascript class EmployeeDatabase { constructor() { this.employees = new Map(); } addEmployee(name, id, position) { this.employees.set(id, { name, position }); } getEmployee(id) { const employee = this.employees.get(id); if (employee) { return { name: employee.name, position: employ...
magicoder
javascript
You are tasked with implementing a method to sort a list of integers in descending order using a custom comparator. The custom comparator should be based on the absolute values of the integers. You need to write a Java method that takes an unsorted list of integers and returns a new list containing the same integers so...
```java import java.util.Collections; import java.util.Comparator; import java.util.List; public class IntegerSorter { public List<Integer> sortDescendingByAbsoluteValue(List<Integer> list) { // Create a custom comparator based on absolute values Comparator<Integer> absComparator = (a, b) -> Intege...
magicoder
java
You are working on a script to concatenate and minify JavaScript files for a web application. The script uses an array of file paths and a final file path to create the concatenated and minified output. Your task is to implement a function that takes in the array of file paths and the final file path, and returns the c...
```bash function concatMinify(files, appends, final_file) { # Concatenate files cat "${files[@]}" > temp.js # Append additional files cat "${appends[@]}" >> temp.js # Minify the concatenated file minify temp.js > "${final_file}" # Return the concatenated and minified output as a string cat "${final_f...
magicoder
shell
You are tasked with implementing an `Interner` trait in Rust, which is used to intern (or internify) values, meaning to ensure that only a single instance of a value exists in memory. The trait extends the `index` trait and has four functions: `intern`, `gensym`, `get`, and `len`. The `Interner` trait has the followin...
```rust use std::collections::HashMap; trait Interner<T: Eq + std::hash::Hash + Copy> { fn intern(&mut self, value: T) -> u32; fn gensym(&mut self, value: T) -> u32; fn get(&self, key: u32) -> Option<&T>; fn len(&self) -> u32; } struct MyInterner<T: Eq + std::hash::Hash + Copy> { values: HashMap<T...
magicoder
rust
You are tasked with creating a custom permission class for a Django REST Framework (DRF) viewset. The custom permission class should restrict access to a specific viewset action based on the user's role and a specific condition. You are given the following code snippet as a starting point: ```python from rest_framewo...
```python from rest_framework import viewsets, permissions class CustomPermission(permissions.BasePermission): def has_permission(self, request, view): if view.action == 'create': user = request.user if user.is_authenticated: if user.role == 'admin': ...
magicoder
python
You are tasked with creating a Python function that handles errors related to establishing a connection to an I2C device. The function should catch the specific error and print a custom error message. Write a function called `connect_to_i2c` that takes no arguments. Inside the function, attempt to create a connection...
```python class I2CConnectionError(Exception): pass def create_connection(): # Simulated function to create I2C connection # Raises I2CConnectionError if connection cannot be established pass def connect_to_i2c(): try: e = create_connection() print(e) except I2CConnectionError:...
magicoder
python
You are tasked with creating a program that parses a given HTML menu structure and generates a hierarchical representation of the menu items. Each menu item is represented by an `<li>` tag with an `<a>` tag inside it, containing the link and the text of the menu item. Your task is to write a function that takes a stri...
```python from bs4 import BeautifulSoup def parse_menu_structure(html_menu): menu_dict = {} soup = BeautifulSoup(html_menu, 'html.parser') ul_tags = soup.find_all('ul') for ul in ul_tags: menu_items = ul.find_all('a') for item in menu_items: menu_text = item.get_text() ...
magicoder
python
You are tasked with implementing a simple command-line interface for a text-based game. The game involves a character navigating through a grid-based world. The character can move in four directions: up, down, left, and right. The grid is represented by a 2D array, where each cell can be either empty or contain an obst...
```java int currentRow = 0; // Current row of the character int currentCol = 0; // Current column of the character switch (command) { case "up": if (currentRow > 0 && grid[currentRow - 1][currentCol] == 0) { currentRow--; } else { System.out.println("Obstacle encountered, ca...
magicoder
java
You are tasked with implementing a test case for a network management system. The system is responsible for tracking the MAC addresses observed on various network devices. The provided code snippet is a part of a Python unit test for this system. The test case is designed to verify the functionality of searching for ob...
```python def testmac(self): command = ["search_observed_mac", "--mac=02:02:04:02:06:cb"] out = self.commandtest(command) # Verify that the correct device and port are associated with the observed MAC address self.matchoutput(out, "ut01ga2s01.aqd-unittest.ms.com,1,02:02:04:02:06:cb,", command) # Ver...
magicoder
python
You are tasked with creating a custom annotation processor for a Java application. The annotation, `@Table`, is used to specify the name of a data table in a database. The annotation can be applied only to classes and has a single attribute, `name`, which defaults to the class name if not explicitly specified. Your goa...
```java import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; impor...
magicoder
java
You are tasked with implementing a simple shape visitor pattern in Rust. The provided code snippet includes the implementation of the `Shape` trait for a `Rectangle` struct and the `Display` trait for the `Rectangle` struct. Your task is to extend this implementation by creating a `Circle` struct and implementing the `...
```rust use std::error::Error; use std::fmt; struct Point { x: f64, y: f64, } struct Circle { center: Point, radius: f64, outline_color: String, fill_color: String, } impl Circle { fn new(center: Point, radius: f64, outline_color: String, fill_color: String) -> Circle { Circle { ...
magicoder
rust
You are tasked with implementing a function that converts a 1D waveform signal into a 2D image representation. The function `Wav_2_Im(im, wn)` takes two parameters: `im`, a 1D array representing the waveform signal, and `wn`, an integer specifying the width of the output image. The function should convert the 1D wavefo...
```python import numpy as np def Wav_2_Im(im: np.ndarray, wn: int) -> np.ndarray: # Normalize the input waveform signal to the range [0, 1] im_normalized = (im - np.min(im)) / (np.max(im) - np.min(im)) # Reshape the normalized signal into a 2D array with the specified width wn hn = int(np.ceil(len...
magicoder
python
You are tasked with creating a program to analyze a list of binary numbers and determine the number of leading zeros in each binary number. The program should utilize the `tqdm` library to display a progress bar with a custom message while iterating through the list of binary numbers. Your task is to implement a funct...
```python from typing import List from tqdm import tqdm def count_leading_zeros(binary_numbers: List[str], pbar_msg: str) -> List[int]: leading_zeros_count = [] for binary_num in tqdm(binary_numbers, desc=pbar_msg): leading_zeros = 0 for bit in binary_num: if bit == '0': ...
magicoder
python
You are tasked with implementing a function that processes a given string to extract specific information. The input string represents a code snippet from a Swift program, and the goal is to extract the names of all the functions defined within the code. A function in Swift is defined using the `func` keyword followed ...
```swift func extractFunctionNames(_ codeSnippet: String) -> [String] { var functionNames: [String] = [] let pattern = "func\\s+([a-zA-Z0-9_]+)\\s*\\(" do { let regex = try NSRegularExpression(pattern: pattern, options: []) let matches = regex.matches(in: codeSnippet, options: [], range...
magicoder
swift
You are working on a bioinformatics project and need to process protein data from UniProt and PDB databases. Your task is to write a Python function that reads protein data from UniProt and PDB, performs some operations, and writes the output to a file. You are given a code snippet that contains part of the logic for ...
```python def process_protein_data(organism, extra_file=None): if organism == 'yeast_ecoli': d = read_in('uniprot', 'pdb', organism=organism) if extra_file: d_old = read_in('uniprot', 'pdb', filename=extra_file) flag = 'EXTRA' else: d_old = read_in('unipro...
magicoder
python
You are tasked with implementing a Python decorator that logs the execution of a function. The decorator should log the function name, its arguments, and the return value. Additionally, the decorator should allow the user to specify the logging level for the messages. Your task is to complete the implementation of the...
```python import logging import click import functools class LazyLog(object): def __init__(self, level): self.level = level def __call__(self, func): @functools.wraps(func) def wrapper(*args, **kwargs): logger = logging.getLogger(func.__module__) logger.setLevel...
magicoder
python
You are tasked with creating a function that processes a given HTML template and extracts specific attributes from it. The HTML template contains a `<div>` element with a class attribute of "btn-group action-btn" and two child elements, each representing a button. The buttons have attributes for their IDs and associate...
```python import re def extract_button_attributes(html_template: str) -> dict: button_attributes = {} pattern = r'(\w+-\w+)", "(\w+\.\w+)' # Regular expression pattern to match button attributes matches = re.findall(pattern, html_template) for match in matches: button_id, action = match ...
magicoder
python
You are tasked with implementing a secure authentication system for a web application. The provided code snippet is a part of a PHP Laravel application and contains a method for logging out a user. The `logout` method is responsible for clearing the user's session and redirecting them to the login page if the session u...
```php public function login($username, $password) { // Predefined set of credentials (replace with actual credentials) $validUsername = 'user123'; $validPassword = 'password123'; // Check if the provided credentials match the predefined set if ($username === $validUsername && $password === $validPassword) {...
magicoder
php
You are tasked with implementing a Python class that simulates a Splitter Grid, which allows users to interact with touch events to resize and rearrange grid elements. The provided code snippet is a method within the SplitterGrid class, which is responsible for handling touch events when the user moves their finger on ...
```python class SplitterGrid: def __init__(self, internal_width): self.internal_width = internal_width # Add any other necessary attributes and initialization code def on_touch_move(self, touch): if touch.grab_current is not self: return super(SplitterGrid, self).on_touch_mo...
magicoder
python
You are given an integer `numRows`, representing the number of rows to generate in Pascal's triangle. Pascal's triangle is a triangular array of binomial coefficients. Each number in the triangle is the sum of the two numbers directly above it. The first row is always 1, and the subsequent rows are constructed by addin...
```python def generate_pascals_triangle(numRows): if numRows == 0: return [] triangle = [[1]] for i in range(1, numRows): prev_row = triangle[i - 1] new_row = [1] # First element of each row is always 1 for j in range(1, i): new_row.append(prev_row[j - 1] + prev_...
magicoder
python
You are tasked with creating a Python function to download files from URLs that match a specific pattern. The function should take into account the URL pattern, file extensions, output directory, optional parameters, and a download limit. You need to implement the `download_by_pattern` function, which takes the follow...
```python import re import os import requests def make_pattern(url_regex: str, extentions: list) -> re.Pattern: if extentions: ext_regex = '({})'.format('|'.join(extentions)) else: ext_regex = '()' return re.compile(url_regex.format(extentions=ext_regex)) def download_by_pattern(url_regex:...
magicoder
python
You are tasked with implementing a protocol-oriented design in Swift to manage view controller interactions. The goal is to create a protocol that defines a property for an interaction controller, which will be implemented by a view controller. The interaction controller will be used to handle user interactions within ...
```swift // Protocol definition protocol AbstractViewController { var interactionController: BaseInteractionController? { get } } // BaseInteractionController protocol protocol BaseInteractionController { // Define required methods or properties for interaction controller // ... } // Conforming class clas...
magicoder
swift
You are tasked with implementing a closure generator in Python. A closure is a function object that has access to variables in its lexical scope, even when the function is called outside that scope. Your task is to create a function `closure_generator` that takes an object as input and returns a closure that can access...
```python def closure_generator(obj): def closure(new_obj=None): nonlocal obj if new_obj is not None: obj = new_obj return obj return closure ``` The `closure_generator` function creates and returns a closure that can access and modify the `obj` provided as an argument. The ...
magicoder
python
You are tasked with implementing a Python function that retrieves version information for software packages from different sources. The function should handle various parameters and return the correct version based on the specified source and options. You are given the following code snippet as a reference: ```python...
```python import aiohttp async def get_version(package_name: str, options: dict) -> str: source = options.get("source") if source == "debianpkg": version = await retrieve_debianpkg_version(package_name) if options.get("strip_release") == 1: version = strip_release_info(version) ...
magicoder
python
You are given a JSON object representing a company's organizational structure. The object contains employees and their respective managers. Each employee has an `id`, `name`, and `managerId`. The `managerId` refers to the `id` of the employee's manager. The object is represented as a nested structure, where each manage...
```javascript function flattenOrganizationalStructure(orgStructure) { const result = []; function flatten(employee, managerName) { result.push({ employeeName: employee.name, managerName: managerName || "None" }); if (employee.directReports) { for (const report of employee.directReports) { fla...
magicoder
javascript
You are tasked with implementing a queue data structure using a linked list. A queue is a linear data structure that follows the First In First Out (FIFO) principle, where elements are added at the rear (enqueue) and removed from the front (dequeue). You need to create a Swift class `Queue` that supports the following ...
```swift class Node<E> { var value: E var next: Node? init(_ value: E) { self.value = value } } class Queue<E> { private var head: Node<E>? private var tail: Node<E>? func enqueue(_ key: E) { let newNode = Node(key) if tail == nil { head = newNo...
magicoder
swift
You are tasked with implementing a custom random number generator using the ChaCha algorithm. The ChaCha algorithm is a stream cipher designed to generate high-quality random numbers. Your goal is to create a ChaCha random number generator in Rust that can be used to produce random numbers. Your task is to implement t...
```rust // Define the ChaChaRng struct pub struct ChaChaRng { // Define the internal state of the ChaChaRng state: [u32; 16], } impl ChaChaRng { // Create a new ChaCha random number generator using the default fixed key of 8 zero words pub fn new_unseeded() -> ChaChaRng { let mut rng = ChaChaRn...
magicoder
rust
You are tasked with designing a trading simulation system that involves data collection and multiple types of traders. The system is designed to work with asynchronous programming and utilizes locks to manage concurrent access to shared resources. Your goal is to implement a simplified version of the trading system by ...
```python from asyncio import Lock, sleep, create_task, run class DataCollector: def __init__(self, api_key, secret_key, symbol, db_lock): self.api_key = api_key self.secret_key = secret_key self.symbol = symbol self.db_lock = db_lock async def fetch_data(self): # Simul...
magicoder
python
You are tasked with creating a Python class to represent weather data readings. The class should have methods to calculate the dew point and the heat index based on temperature, humidity, and pressure readings. The formulas for calculating the dew point and heat index are as follows: Dew Point (in Celsius): \[ Td = T ...
```python class WeatherData: def __init__(self, temperature, humidity, pressure): self.temperature = temperature self.humidity = humidity self.pressure = pressure def calculate_dew_point(self): dew_point = self.temperature - ((100 - self.humidity) / 5) return dew_point ...
magicoder
python
You are tasked with implementing a custom data structure called `BitSet` in Swift. A `BitSet` is a collection of bits, where each bit can be either 0 or 1. The `BitSet` should support the following operations: 1. `init(withWords words: Word...)`: A constructor that initializes the `BitSet` with an array of `Word` value...
```swift struct BitSet { private var bits: UInt64 = 0 init(withWords words: UInt64...) { for word in words { bits |= word } } func setBit(atIndex index: Int) { bits |= (1 << index) } func clearBit(atIndex index: Int) { bits &= ~(1 << ind...
magicoder
swift
You are tasked with creating a Python program that processes a given input file and performs specific operations based on the content. The input file contains a series of lines, each representing a Python code snippet. Your program needs to read each line and determine if it contains a specific format. If a line matche...
```python import sys def process_input_file(input_file): with open(input_file, 'r') as file: for line in file: line = line.strip() if line.startswith("DORIAN_REQUIRED_PYTHON"): versions = line.split()[1:] version_sum = sum(float(version) for version i...
magicoder
python
You are tasked with creating a program to manage a car rental system. The program should allow users to add new cars to the system, update car information, and display the details of all available cars. Each car should have attributes such as make, model, year, and rental price. Additionally, the program should be able...
```python import tkinter as tk from PIL import Image, ImageTk class Car: def __init__(self, make, model, year, rental_price): self._make = make self._model = model self._year = year self._rental_price = rental_price self._logo_image = None def set_make(self, make): ...
magicoder
python
You are tasked with creating a Python program to parse Legends of Runeterra (LoR) deck codes and extract specific information from them. LoR deck codes are used to represent decks of cards in the game Legends of Runeterra. Each card in the deck is represented by a code, along with the quantity of that card in the deck....
```python from lor_deckcodes.models import LoRDeck, CardCodeAndCount def extract_deck_info(deck_code): deck = LoRDeck.from_deckcode(deck_code) total_cards = sum(card.count for card in deck.cards) unique_cards = {card.card_code: card.count for card in deck.cards} print(f"Total number of cards: {total_c...
magicoder
python
You are tasked with implementing a program that processes data and generates CSV output based on certain conditions. The program should support an extended format with specific fields and options. You are given a code snippet that sets the `extendedFormat` variable to `False` and initializes a list of fields `csvField...
```python from typing import List, Dict, Any import csv def generate_csv_output(data: List[Dict[str, Any]], extended: bool) -> str: if extended: csvFields = ['RESOLVED_ENTITY_ID', 'RELATED_ENTITY_ID', 'MATCH_LEVEL', 'MATCH_KEY', 'DATA_SOURCE', 'RECORD_ID', 'LENS_CODE', 'REF_SCORE', 'ENTITY_TYPE', 'ERRULE_C...
magicoder
python
You are tasked with implementing a simplified version of an address space management system. The address space is a range of valid addresses that can be used to store data. Your goal is to create a class that manages the allocation and deallocation of memory within this address space. You are provided with the followi...
```cpp #include <vector> #include <algorithm> class AddressSpaceManager { private: int size; std::vector<bool> memoryMap; // Represents the availability of each address in the address space public: AddressSpaceManager(int size) : size(size), memoryMap(size, false) {} int allocate(int blockSize) { ...
magicoder
cpp
You are tasked with creating a Python function that processes a model queryset to return the latest version of each record along with the corresponding primary key. The function should take a model queryset as input and return a dictionary where the keys are the primary keys of the latest versions and the values are th...
```python from django.db.models import Max, OuterRef def annotated_model_queryset(self, using=None): """Returns a model queryset annotated with latest_pk, the primary key corresponding to the latest version """ versioning_extension = get_versioning_extension() versionable = versioning_extension.ver...
magicoder
python
You are tasked with creating a simple 3D graphics rendering system. The system uses a camera to define the viewpoint and allows the creation of 3D models. The code snippet provided is a part of the test suite for this system. The `DrawRedBox` test case is responsible for drawing a red box using the system. The `Camera....
```csharp public class Camera { public static void Use<T>() where T : Camera, new() { // Implementation to set the camera to use the specified camera type } } public class Model { public Model(ModelData modelData, Vector3D position) { // Implementation to create a new model using th...
magicoder
csharp
You are given a 2D array `energies` representing the energy levels at different positions in a grid. The task is to find the minimum cost path from the top row to the bottom row, where the cost of each step is the energy level at that position. You can only move to the adjacent positions directly below, directly below ...
```python from typing import List def min_cost_path(energies: List[List[int]]) -> int: rows, cols = len(energies), len(energies[0]) cost = [[0 for _ in range(cols)] for _ in range(rows)] # Initialize the cost for the top row for i in range(cols): cost[0][i] = energies[0][i] # Calculate th...
magicoder
python
You are tasked with implementing a Python function that reads a binary file containing temperature data and returns the average temperature in Celsius. The binary file contains 4-byte floating-point numbers representing temperatures in Fahrenheit. Your task is to convert these temperatures to Celsius and calculate thei...
```python import struct def average_temperature_from_binary_file(file_path: str) -> float: with open(file_path, 'rb') as file: data = file.read() temperatures = struct.unpack('f' * (len(data) // 4), data) # Unpack 4-byte floating-point numbers celsius_temperatures = [(f - 32) * 5/9 for f i...
magicoder
python