query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with writing a shell script to automate the installation of specific software versions. The script should utilize the environment variables provided and install the corresponding software versions using the appropriate package manager. Given the following environment variables: ``` export gdsVersion="1....
```bash #!/bin/bash # Check if gdsVersion is set if [ -z "$gdsVersion" ]; then echo "Error: gdsVersion environment variable is not set." exit 1 fi # Check if zuluVersion is set if [ -z "$zuluVersion" ]; then echo "Error: zuluVersion environment variable is not set." exit 1 fi # Check if jreVersion is set if ...
magicoder
shell
You are tasked with implementing a Python function that takes a string as input and converts all special characters and Unicode characters into their respective hex-escaped representations. The function should follow the steps outlined in the given code snippet to achieve this conversion. Your task is to complete the ...
```python def convert_to_hex_escaped(input_string): # Step 1: Break up large Unicode characters into multiple UTF-8 hex characters s_1 = input_string.encode("utf-8").decode("latin-1") # Step 2: Escape all special characters return s_1.encode("unicode-escape").decode("latin-1") ``` The provided solutio...
magicoder
python
You are tasked with creating a Python class that manages permissions for a Django web application. The class should allow for the registration and management of different types of permissions within the application. Your task is to implement a `PermissionManager` class with the following requirements: - The class shou...
The `PermissionManager` class is implemented with a constructor to initialize an empty dictionary to store permissions. It has methods to register a permission, check the status of a permission, grant a permission, and revoke a permission. The methods ensure that permissions are managed effectively within the Django we...
magicoder
python
You are tasked with implementing a custom exception class in PHP that extends the built-in `Exception` class. Your custom exception class should have a constructor that accepts a message and an optional previous exception. Your task is to create a PHP class called `CustomException` that extends the `Exception` class a...
```php class CustomException extends Exception { public function __construct($message = "", Exception $previous = null) { parent::__construct($message, 0, $previous); if ($previous !== null) { $this->setPrevious($previous); } } } ``` In the solution, we define a class `Custo...
magicoder
php
You are working on a software testing system for a city's infrastructure management. The system maintains a queue of items to be tested, and each item can be in one of several states. You need to implement a class to manage the testing queue and its items. You are given a partial code snippet for a Python class that r...
```python class ItemToTest: def __init__(self): self.state = 'Not_tested' def add_to_TestingQueue(self, PrivateTest=False): if PrivateTest: self.City.PrivateTestingQueue.append(self) else: self.City.TestingQueue.append(self) def remove_from_testing_l...
magicoder
python
You are tasked with creating a Python script that processes a collection of blog entries and generates a static website using the `staticjinja` library. Each blog entry is stored in a separate JSON file and contains metadata such as title, author, date, and content. Your script should read these JSON files, process the...
```python import os import json from staticjinja import make_site # Step 1: Read all the JSON files from the blog_entries directory blog_entries_dir = 'blog_entries' json_files = [f for f in os.listdir(blog_entries_dir) if f.endswith('.json')] # Step 2 and 3: Parse the content of each JSON file and create a dictionar...
magicoder
python
You are tasked with implementing a course management system that allows users to update specific fields of a course. The system provides a function `_get_course_field` to obtain the field to be updated for a given course. Additionally, there is a function that checks if a course name matches the provided name and retur...
```python def _update_course_field(courses, course_name, field_name, new_field_value): for course in courses: if course['name'] == course_name: if field_name in course: course[field_name] = new_field_value return course else: return f"F...
magicoder
python
You are tasked with writing a script to extract information from a build configuration file and generate a JSON file based on certain conditions. The script should extract the version, device, ROM type, and variant from the build configuration file and create a JSON file with specific naming conventions. Given the fol...
```bash #!/bin/bash zip=$(get_build_var XTENDED_VERSION).zip device=$(echo $TARGET_PRODUCT | cut -d '_' -f2) buildprop=$OUT/system/build.prop linen=$(grep -n "ro.xtended.build.type" $buildprop | cut -d ':' -f1) romtype=$(sed -n $linen'p' < $buildprop | cut -d '=' -f2) variant=$(echo $zip | cut -d '-' -f4) name=$device...
magicoder
shell
You are tasked with implementing a Python decorator that validates the configuration keys for a task class. The code snippet provided showcases the usage of the `@with_config_key` decorator to validate configuration keys for a `WriterTask` class. Your goal is to create a decorator that ensures the presence of specific ...
```python class WriterTaskConfigInvalid(Exception): pass def with_config_key(key, raise_exc): def decorator(cls): def wrapper(*args, **kwargs): if key not in kwargs.get('config', {}): raise raise_exc return cls(*args, **kwargs) return wrapper return d...
magicoder
python
You are tasked with implementing a class that represents an HTML tag. The class should have the ability to create an HTML tag with a specified tag type and tag name. Your task is to complete the implementation of the `HtmlTag` class by adding a method that generates the opening tag based on the tag type and name provid...
```csharp using System; public enum HtmlTagType { Normal, SelfClosing } public class HtmlTag { public HtmlTagType TagType { get; } public string TagName { get; } public HtmlTag(HtmlTagType tagType, string tag) { TagType = tagType; TagName = SanitizeTagName(tag); } pub...
magicoder
csharp
You are tasked with implementing a TypeScript function that simulates the behavior of the `ReflectDefineMetadata` function. The `ReflectDefineMetadata` function is used to define metadata on a target object or property. The metadata can be any arbitrary value associated with a specific key. You are provided with the f...
```typescript function reflectDefineMetadata(target: Object, key: string, value: any): void { if (typeof target !== 'object' || target === null) { throw new TypeError("Invalid target"); } if (typeof key !== 'string' || key === '') { throw new TypeError("Invalid key"); } Object.define...
magicoder
typescript
You are tasked with implementing a function to perform random image augmentation for a given input image. The function should apply random shifts to the input image based on specified ranges for height and width shifts. The shifts are to be applied using the following logic: 1. If the `height_shift_range` is non-zero,...
```python import numpy as np def random_image_augmentation(x, height_shift_range, width_shift_range): h, w = x.shape[0], x.shape[1] if height_shift_range: tx = np.random.uniform(-height_shift_range, height_shift_range) * h else: tx = 0 if width_shift_range: ty = np.random.unifor...
magicoder
python
You are tasked with creating a function that processes a given object containing asynchronous import functions and returns a modified object with the imported raw data. The input object has the following structure: ```javascript { readme: async () => import("!!raw-loader!./readme.md"), files: () => [ { name: "2...
```javascript async function processImports(inputObject) { const processedObject = {}; // Process readme import processedObject.readme = await inputObject.readme(); // Process files import processedObject.files = await Promise.all( inputObject.files().map(async (file) => { const importedData = awa...
magicoder
javascript
You are tasked with implementing a custom data structure that simulates a circular buffer. A circular buffer is a fixed-size buffer that wraps around when it reaches its capacity, effectively overwriting the oldest elements with the newest ones. Your task is to implement the `CircularBuffer` class with the following me...
```cpp #include <vector> #include <string> class CircularBuffer { public: CircularBuffer(int capacity) : capacity(capacity), size(0), head(0) { buffer.resize(capacity); } void push_back(const std::string& value) { buffer[head] = value; head = (head + 1) % capacity; if (size...
magicoder
cpp
You are given a Rust code snippet that contains assertions using the `assert_eq!` macro. The assertions compare the result of a range lookup with a color value. The `range` is a collection of colors, and the lookup is performed using the `min` function with different parameters. Your task is to implement the `min` func...
```rust #[derive(Debug, PartialEq)] struct ColorU8([u8; 4]); fn min(a: usize, b: u8) -> usize { if a < b as usize { a } else { b as usize } } fn main() { let white = ColorU8([255, 255, 255, 255]); let range = [ ColorU8([255, 255, 255, 255]), ColorU8([200, 200, 200, ...
magicoder
rust
You are tasked with implementing a logging module for a .NET application using the ABP (ASP.NET Boilerplate) framework. The module should integrate with the Castle Windsor dependency injection container and utilize the Log4Net logging library for logging messages. Your task is to create a class that configures and ini...
```csharp using Castle.Facilities.Logging; using Castle.MicroKernel.Registration; using Castle.Windsor; using Castle.Windsor.Installer; using log4net; using log4net.Config; public class Log4NetModuleConfig { public static void InitializeLog4Net(IWindsorContainer container) { // Step 1: Configure Log4Ne...
magicoder
csharp
You are tasked with creating a Python class that represents a factory part and its associated attributes. The factory part can be of different types, such as a table or a node, and it interacts with other components in the factory. Your task is to implement the `FactoryPart` class and its subclasses, and ensure that th...
```python import unittest from unittest import mock class FactoryPart: def __init__(self, name, index, source, sink): self.name = name self.index = index self.source = source self.sink = sink class Table(FactoryPart): def __init__(self, name, index, source, sink): super...
magicoder
python
You are tasked with creating a Rust module that manages sprite sheets for a 2D game. The module should provide functionality to load sprite sheet configurations and manage the corresponding textures. You are given a code snippet that imports two items from external modules: `SpriteSheetConfig` from the `fortress_bake::...
```rust // sprite_sheet_manager.rs use fortress_bake::render::SpriteSheetConfig; use self::sprite_sheet_texture_manager::SpriteSheetTextureManager; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub struct SpriteSheetManager { texture_manager: SpriteSheetTextureManager, } impl SpriteSheetManage...
magicoder
rust
You are tasked with implementing a simple behavior-based robot control system using Python. The robot has three behaviors: move to a specific point, catch an object, and move back to a specific point. The robot's behaviors are triggered by messages received from a ROS (Robot Operating System) topic. The provided code ...
```python import rospy from std_msgs.msg import Int32 move2point = 14 catchobj = 15 back2point = 16 is_start = False def start_callback(msg): global is_start if not is_start: is_start = msg.data def next_pub(msg): pub = rospy.Publisher('scan_black/strategy_behavior', Int32, queue_size=10) # I...
magicoder
python
You are working on a project that involves evaluating the performance of a model that predicts certain outcomes. As part of this evaluation, you need to implement a function that calculates a specific loss metric based on the predicted and ground truth values. The code snippet provided is a part of the loss calculation...
```python def calculate_loss(pred_perm, gt_perm, pred_ns, gt_ns): # Calculate the loss metric using pred_perm, gt_perm, pred_ns, and gt_ns loss = torch.nn.functional.cross_entropy( input=pred_perm[:, :pred_ns.max(), :gt_ns.max()], target=gt_perm[:, :pred_ns.max(), :gt_ns.max()], reductio...
magicoder
python
You are tasked with implementing a Python module that interacts with various event handling functions. The module should provide both synchronous and asynchronous versions of the functions for retrieving and posting events. You are given the following code snippet as a starting point: ```python from .wrappers import g...
```python import asyncio from .wrappers import get_event_by_user_id_handler, get_event_by_user_id_handler_async, post_event_handler, post_event_handler_async def get_event_by_user_id(user_id: int) -> dict: try: return get_event_by_user_id_handler(user_id) except Exception as e: # Handle excepti...
magicoder
python
You are tasked with implementing a parser for a subset of the C++ programming language. The given code snippet is a part of a C++ parser implemented using the GLR Parser (glrp) framework. The parser is responsible for handling abstract declarators and pointer abstract declarators in C++. An abstract declarator in C++ ...
To implement the parsing rules for abstract declarators and pointer abstract declarators in C++, you can use the GLR Parser framework and define the rules as Python functions. The parsing rules should handle the different components of abstract declarators and pointer abstract declarators, such as pointers, references,...
magicoder
python
You are tasked with implementing a class to represent an edge pair in a graph. The class should provide functionality to store and retrieve information about the two vertices connected by the edge, as well as any associated weight. Additionally, the class should support comparison operations to determine equality betwe...
```java public class EdgePair { private int vertex1; private int vertex2; private double weight; public EdgePair(int v1, int v2, double w) { this.vertex1 = v1; this.vertex2 = v2; this.weight = w; } public int getVertex1() { return vertex1; } public int ...
magicoder
java
You are tasked with implementing a collectible system for a game using Unity and C#. The game features different types of collectible items, each with its own unique properties. Your goal is to create a system that allows the player to collect these items and keep track of the collected items in a data structure. You ...
```csharp using System.Collections.Generic; using UnityEngine; public class Collectable : MonoBehaviour { public enum CollectibleType { CABIN, ENGINE, CHASSIS, SWHEEL, TIRES }; private HashSet<CollectibleType> collectedItems = new HashSet<CollectibleType>(); public void CollectItem(CollectibleType item) ...
magicoder
csharp
You are given an array of integers representing the weights of items and a maximum weight capacity. Your task is to find the maximum total weight that can be carried by selecting a subset of the items, such that the total weight does not exceed the maximum weight capacity. You need to implement a function `maxTotalWei...
```cpp #include <iostream> using namespace std; int maxTotalWeight(int weights[], int n, int w) { bool dp[n + 1][w + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= w; j++) { if (i == 0 || j == 0) dp[i][j] = false; else if (weights[i - 1] <= j) ...
magicoder
cpp
You are tasked with implementing a Python class that manages software packages. The class should have the ability to track whether a package needs a specific operation, such as "lipo," to be performed on it. Your task is to implement the `Package` class with the following specifications: - The class should have an att...
```python class Package: def __init__(self): self.needs_lipo = False def perform_lipo(self): self.needs_lipo = True def reset_lipo(self): self.needs_lipo = False def status(self): return self.needs_lipo ```
magicoder
python
You are tasked with creating a Python decorator that logs the execution time of a function. The decorator should print the name of the function, its execution time, and the arguments passed to the function. Your task is to implement the `@log_execution_time` decorator and apply it to a sample function. Your decorator ...
```python import time import functools def log_execution_time(func): @functools.wraps(func) def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() execution_time = end_time - start_time print(f"Function '{func.__name_...
magicoder
python
You are working on a natural language processing (NLP) project and have been tasked with implementing a text classification pipeline using a machine learning model. The pipeline consists of a series of preprocessing, feature extraction, and model training steps. You are provided with a code snippet that includes a pred...
```python from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import make_pipeline from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.externals import joblib from pathlib import Path imp...
magicoder
python
You are working on a Python package for a graphical user interface (GUI) application. The package contains several modules, including `palette.py`, `theme.py`, and `template.py`. Each of these modules is responsible for a specific aspect of the GUI design and functionality. Your task is to create a function that will ...
```python def import_and_get_attribute(module_name: str, attribute_name: str, default_value: any): try: imported_module = __import__(module_name, fromlist=[attribute_name]) attribute = getattr(imported_module, attribute_name, default_value) return attribute except (ImportError, Attribute...
magicoder
python
You are tasked with implementing a parser for a simple programming language that supports positional and named arguments in function calls. The given code snippet represents part of the data structures used in the parser. The `Argument` enum has two variants: 1. `Positional(Expression)`: Represents a positional argume...
```rust use super::Expression; use crate::{DeclId, Span, Spanned}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum Argument { Positional(Expression), Named((Spanned<String>, Option<Spanned<String>>, Option<Expression>)), } fn parse_arguments(tokens: Vec<Token>) -> Result<Vec<Argument>, Str...
magicoder
rust
You are tasked with implementing a shell script function that sorts a list of numbers in ascending order. The function should take a list of numbers as input and return the sorted list. The sorting algorithm to be used is the bubble sort algorithm. You are provided with a partial code snippet for the shell script func...
```bash #!/bin/bash sort_numbers() { local __sort="$1" local __len=${#__sort} local __sorted='0' while [ "$__sorted" -eq '0' ]; do __sorted='1' for (( i=0; i<__len-1; i++ )); do if [ "${__sort[$i]}" -gt "${__sort[$((i+1))]}" ]; then local __temp="${__sort[$i...
magicoder
shell
You are tasked with implementing a custom tag handler for a configuration management system. The tag handler, called `GlobHandler`, is responsible for processing glob patterns within configuration files and expanding them into a list of file paths. The `GlobHandler` should support basic glob patterns such as `*`, `?`, ...
```python from typing import List from pathlib import Path class GlobHandler: @staticmethod def expand_glob_pattern(pattern: str) -> List[str]: try: path = Path('.') matched_files = list(path.glob(pattern)) if not matched_files: raise ValueError("No m...
magicoder
python
You are tasked with implementing a custom paging view in Swift. The provided code snippet includes a protocol `PageContentViewDelegate` and a class `PageContentView` that will be used to create the paging view. Your task is to complete the implementation of the `PageContentView` class by adding the necessary propertie...
```swift class PageContentView: UIView, UIScrollViewDelegate { weak var delegate: PageContentViewDelegate? private var childViewControllers: [UIViewController] private var scrollView: UIScrollView! init(frame: CGRect, childViewControllers: [UIViewController]) { self.childViewControllers = child...
magicoder
swift
You are tasked with creating a program that manages a legacy mode flag and performs operations based on its value. The legacy mode flag is initially set to `false`. Your program should provide functionality to toggle the legacy mode flag and execute different operations based on its state. Your task is to implement a ...
```java public class LegacyManager { private boolean legacyMode = false; public void toggleLegacyMode() { legacyMode = !legacyMode; } public String performOperation(int value) { if (legacyMode) { return "Legacy operation performed with value: " + value; } else { ...
magicoder
java
You are tasked with creating a Python class that interacts with Google's mobility report data. The class should have a method to load the report from Google, with the option to filter by a country region code and to cache the report. Additionally, the class should have a default report URL and the ability to show progr...
```python import pandas as pd from typing import Optional class GoogleMobility: DEFAULT_REPORT_URL = "https://example.com/mobility_report.csv" def __init__(self, report_url: Optional[str] = None): self.report_url = report_url or GoogleMobility.DEFAULT_REPORT_URL def load_report(self, country_regi...
magicoder
python
You are tasked with implementing a function to perform non-IID (non-identically distributed) data partitioning for a given dataset. Non-IID data partitioning is a technique commonly used in federated learning, where data is distributed among multiple clients in a non-uniform manner to simulate real-world scenarios wher...
```python import numpy as np def noniid_data_partitioning(dataset, num_users, alpha): # Perform non-IID label distribution def noniid_label_distribution(data, num_users, alpha): num_classes = len(np.unique(data['labels'])) num_classes_per_user = int(num_classes / num_users) user_data = ...
magicoder
python
You are given a string `T` consisting of lowercase English letters. Your task is to write a function that returns the longest substring of `T` that contains at most two distinct characters. If there are multiple such substrings with the same length, return the first occurring substring. For example, given the input st...
```java public String longestSubstringWithTwoDistinct(String T) { if (T == null || T.length() == 0) { return ""; } int[] poses = new int[128]; Map<Character, Integer> maxPos = new HashMap<>(); int start = 0, end = 0, maxLen = 0, maxStart = 0; for (int i = 0; i < T.length(); i++) { ...
magicoder
java
You are tasked with creating a program that monitors the CPU usage of a given process on a Windows system. The program should retrieve the CPU usage as a percentage and display it to the user. To achieve this, you will need to utilize the Windows API functions for retrieving system and process times, and then calculate...
```cpp #include <windows.h> #include <iostream> double GetProcessCpuUsage(DWORD processId) { FILETIME ftSysIdle, ftSysKernel, ftSysUser; FILETIME ftProcCreation, ftProcExit, ftProcKernel, ftProcUser; if (!GetSystemTimes(&ftSysIdle, &ftSysKernel, &ftSysUser) || !GetProcessTimes(OpenProcess(PROCESS_...
magicoder
cpp
You are working on a task management system that involves importing tasks from various sources. The given code snippet is a function `task_imports` that returns a list of task modules to be imported. Each module contains task definitions that need to be integrated into the system. Your task is to implement a function ...
```python import importlib def import_tasks(modules: list) -> dict: imported_tasks = {} for module in modules: tasks = [] try: imported_module = importlib.import_module(module) for task_name in dir(imported_module): if task_name.startswith('task'): ...
magicoder
python
You are tasked with implementing a BookManager class that manages a collection of books. The class should have the following functionalities: 1. Add a book to the collection. 2. Remove a book from the collection based on its title. 3. List all the books in the collection. You are provided with a partial implementatio...
```python class Book: def __init__(self, title): self.title = title class BookManager: def __init__(self): self.books = [] def add_book(self, book): self.books.append(book) def remove_book(self, title): for b in self.books: if b.title == title: ...
magicoder
python
You are tasked with implementing a Python function that generates a banner of a specified width and height, with a given message centered within the banner. The banner will be composed of horizontal and vertical characters, and the message will be surrounded by these characters to form a border. Your task is to write a...
```python def generate_banner(message: str, width: int, height: int, horizontal: str, vertical: str) -> str: if len(message) > width - 2: raise ValueError("Message length exceeds the specified width") horizontal_border = horizontal * width vertical_space = f"{vertical}" + " " * (width - 2) + f"{ver...
magicoder
python
You are tasked with implementing a class called `Selection` that monitors the system clipboard for changes and retrieves the new content at regular intervals. Your task is to complete the `Selection` class by implementing the `get_str` method to achieve this functionality. The `Selection` class has the following attri...
```python import subprocess import time class Selection: def __init__(self, intvl): self.content = "" self.intvl = intvl def get_str(self): while True: cur = subprocess.check_output(["xsel"]).decode('utf-8').strip() if cur != self.content: self....
magicoder
python
You are tasked with creating a program that can analyze the structure of an HTML file and determine if all the opening tags have corresponding closing tags. For the purpose of this problem, an HTML tag is defined as a string enclosed in angle brackets, such as `<html>`, `<body>`, or `<div>`. Opening tags are denoted by...
```python def htmlTagChecker(html_string): stack = [] i = 0 while i < len(html_string): if html_string[i] == '<': if html_string[i:i+2] == '</': # Closing tag tag_end = html_string.find('>', i) if tag_end == -1: return False # No corr...
magicoder
python
You are tasked with implementing a custom cost function for detecting abrupt changes in time series data. The `ruptures` library provides a `BaseCost` class that serves as the foundation for creating custom cost functions. Your goal is to create a new cost function by subclassing `BaseCost` and implementing the require...
```python from ruptures.base import BaseCost class CustomCost(BaseCost): def __init__(self): super().__init__() def fit(self, data): # Implement fitting logic for the cost function pass def cost(self, start, end): # Calculate and return the cost of the segment defined by s...
magicoder
python
You are tasked with creating a serverless application using AWS CDK (Cloud Development Kit) in Python. Your goal is to set up a serverless stack that includes AWS X-Ray for tracing and monitoring the application's performance. The provided code snippet initializes the serverless stack and synthesizes the application. ...
```python from aws_cdk import core from aws_cdk.aws_xray import CfnGroup, CfnSamplingRule from aws_cdk.aws_lambda import Function, Code, Runtime from aws_cdk.aws_apigateway import LambdaRestApi class FagateServerlessStack(core.Stack): def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: su...
magicoder
python
You are tasked with implementing a data synchronization mechanism for a sensor fusion system. The system receives data from two sensors: an accelerometer and a gyroscope. The provided code snippet is a part of the synchronization logic, which checks if the data from the accelerometer and gyroscope has been updated. Th...
```cpp void sensorDataSynchronization(int _accel_sub, int _gyro_sub) { bool accel_updated = false; bool gyro_updated = false; orb_check(_accel_sub, &accel_updated); // Check for updated data from the accelerometer orb_check(_gyro_sub, &gyro_updated); // Check for updated data from the gyroscope ...
magicoder
cpp
You are tasked with implementing a Python function that performs deconvolution on a given input signal using the Richardson-Lucy algorithm. Deconvolution is a process used to reverse the effects of convolution, which is a mathematical operation commonly used in signal processing and image processing. The Richardson-Luc...
```python from typing import List def richardson_lucy_deconvolution(input_signal: List[float], psf: List[float], num_iterations: int) -> List[float]: def convolve(signal, kernel): return [sum(signal[i] * kernel[j - i] for i in range(j + 1) if i >= 0 and i < len(signal)) for j in range(len(signal) + len(ker...
magicoder
python
You are tasked with creating a Python script that analyzes a given `setup.py` file and extracts specific information from it. The `setup.py` file is used to describe the metadata about the Python package, including its dependencies, license, and description. Your task is to write a function `extract_package_info` that...
```python import ast def extract_package_info(setup_content): setup_dict = ast.literal_eval(setup_content.split('setup(')[1].split(')')[0]) return { 'dependencies': setup_dict.get('install_requires', []), 'license': setup_dict.get('license', ''), 'description': setup_dict.get('descripti...
magicoder
python
You are tasked with implementing a class that simulates a creature's combat cooldown mechanism. The creature has a combat cooldown value that needs to be decremented until it reaches 0. The provided code snippet shows the `onUpdate` method of the creature's class, which is called periodically to update the creature's s...
```java public class Creature { private int combatCooldown; public Creature(int initialCombatCooldown) { this.combatCooldown = initialCombatCooldown; } public int getCombatCooldown() { return combatCooldown; } public void decrementCombatCooldown() { if (combatCooldown ...
magicoder
java
You are tasked with creating a Python script to automate the process of generating and publishing content for a website. The script should load data, generate works and a timeline, build the HTML files, and then publish the output to a remote server using rsync over SSH. Your task is to implement the Python script to ...
```python import os import subprocess def main(): try: tpuser = os.environ['TPUSER'] tphost = os.environ['TPHOST'] works_cats, years = gen.load_data() gen.gen_works(works_cats) gen.gen_timeline(years) # Build HTML files subprocess.run(['make', 'html'], chec...
magicoder
python
You are tasked with implementing a Python class that creates a proxy object to delegate method calls to a wrapped object. The proxy object should have an attribute named `_wrapped` that holds the wrapped object. When a method is called on the proxy object, it should delegate the call to the corresponding method of the ...
```python from functools import wraps class Proxy: def __init__(self, wrapped): self._wrapped = wrapped def _wrapper(self, func): @wraps(func) def wrapper(*args, **kwargs): return getattr(self._wrapped, func.__name__)(*args, **kwargs) return wrapper # No additi...
magicoder
python
You are tasked with implementing a Python function that manipulates date and time information using the `pyepoch` library. The `pyepoch` library provides functionality for working with dates and times in various timezones. Your task is to complete the implementation of the `timezone()` function, which takes a date and ...
```python import pyepoch from pytz import timezone as tz def timezone(date_time, new_timezone): # Convert the input date_time to UTC timezone utc_date_time = date_time.astimezone(tz('UTC')) # Convert the UTC date_time to the new timezone new_date_time = utc_date_time.astimezone(tz(new_timezone)) ...
magicoder
python
You are tasked with implementing a function that processes a list of tuples representing field configurations for a user interface. Each tuple consists of a string representing the field group name and a dictionary containing the field names. The function should return a dictionary where the keys are the field group na...
```python from typing import List, Tuple, Dict, Union, Any def process_field_configurations(field_configurations: List[Tuple[str, Dict[str, Union[str, Any]]]]) -> Dict[str, List[str]]: result = {} for group, fields_dict in field_configurations: result[group] = list(fields_dict.values())[0] return r...
magicoder
python
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. The program should read the text file, identify the specified words, and output the count of each word. You are given a text file named "sample_text.txt" containing the following content: ``` Lorem ipsum ...
```python # Read the content of the text file with open("sample_text.txt", "r") as file: text = file.read() # Define the list of specific words to count specific_words = ["dolor", "ut", "in", "aliqua"] # Create a dictionary to store the word counts word_counts = {word: text.lower().count(word) for word in specifi...
magicoder
python
You are tasked with creating a unit test for a class that manages the configuration of a package manager. The class has a method `getComposerBinDirectory` which should return the path to the vendor's binary directory. To facilitate testing, the code uses vfsStream, a virtual file system for testing purposes. The provid...
```php use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; class ConfigurationTest extends TestCase { protected $configuration; protected $root; protected function setUp(): void { $this->root = vfsStream::setup(); mkdir(vfsStream::url('root/vendor/bin'), 0777, true); ...
magicoder
php
You are tasked with implementing a Python function that performs a specific operation on a given list of integers. The function should take a list of integers as input and return a new list containing the cumulative sum of the input list. The cumulative sum at each index in the output list should be the sum of all the ...
```python from typing import List def cumulative_sum(nums: List[int]) -> List[int]: cumulative = [] total = 0 for num in nums: total += num cumulative.append(total) return cumulative ``` The `cumulative_sum` function iterates through the input list of integers, maintaining a running to...
magicoder
python
You are tasked with implementing a rendering system for a 3D graphics application. The given code snippet is part of the rendering process and involves setting up the rendering encoder to draw indexed primitives for a mesh using a color map texture. Your task is to write a function that takes in the necessary paramete...
```swift func setupRendering(renderEncoder: RenderEncoder, mesh: Mesh, colorMap: Texture) { renderEncoder.setFragmentTexture(colorMap, index: TextureIndex.color.rawValue) for submesh in mesh.submeshes { renderEncoder.drawIndexedPrimitives(type: submesh.primitiveType, ...
magicoder
swift
You are tasked with creating a Python class to represent a chess game and implementing a method to determine all possible moves for a given piece on the board. The chess board is represented as an 8x8 grid, and the pieces are represented by their respective characters ('K' for king, 'Q' for queen, 'R' for rook, 'B' for...
```python class ChessGame: def __init__(self): self.board = [['' for _ in range(8)] for _ in range(8)] def possible_moves(self, piece, position): # Implement logic to determine possible moves for the given piece at the specified position # Return a list of strings representing valid mov...
magicoder
python
You are tasked with implementing a Python class that represents a beacon block for a blockchain system. The beacon block consists of a beacon block body and has a generic type parameter. Your goal is to create the class and implement a method that returns a string representation of the beacon block. You are provided w...
```python from typing import TypeVar class BeaconBlockBody: @staticmethod def create() -> "BeaconBlockBody": # Implementation for creating a default beacon block body pass class BeaconBlock: TBaseBeaconBlock = TypeVar("TBaseBeaconBlock", bound="BaseBeaconBlock") def __init__(self, bod...
magicoder
python
You are tasked with implementing a command-line argument parser for a PHP application. The parser should extract and validate command-line arguments based on the provided route and controller action information. You are given a code snippet that retrieves information about the controller action using the Reflection AP...
```php /** * Parses and validates command-line arguments based on the provided route and controller action information. * * @param string $path The command-line input string. * @param Route $route The route object containing controller information. * @return array An associative array of parsed arguments. * @thro...
magicoder
php
You are tasked with implementing a Swift enumeration and its associated properties to represent different box dimensions. The enumeration should have cases for box height, box rotate angle, box slant angle, and box width. Each case should have an associated value of a custom type `SDAI` which has properties `realValue`...
```swift // Define the custom type SDAI with realValue and integerValue properties struct SDAI { var realValue: Double var integerValue: Int? } // Define the enumeration BoxDimension with associated values of type SDAI enum BoxDimension { case _BOX_HEIGHT(SDAI) case _BOX_ROTATE_ANGLE(SDAI) case _BO...
magicoder
swift
You are tasked with creating a script that automates the setup process for a developer's environment. The script should execute a series of sub-scripts to install and configure various tools and settings. Each sub-script is responsible for a specific task, such as setting up Visual Studio Code, installing npm packages,...
```bash #!/bin/bash # Function to execute sub-scripts execute_script() { if [ -f "./scripts/$1" ]; then echo "Executing $1..." if ./scripts/"$1"; then echo "$1 executed successfully." else echo "Error executing $1. Exiting..." exit 1 fi else echo "Script $1 not found. Exiting....
magicoder
shell
You are tasked with creating a custom authentication strategy for a Node.js application using the NestJS framework. The application uses JSON Web Tokens (JWT) for authentication and authorization. Your goal is to implement a JwtStrategy class that extends the PassportStrategy class and uses the passport-jwt library to ...
```typescript import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy, ExtractJwt } from 'passport-jwt'; import { PropietarioService } from './propietario.service'; @Injectable() export class JwtStrategy extends PassportStrategy(Strateg...
magicoder
typescript
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the balance. Additionally, the class should have a method for applying interest to the account balance. The interest should be calculated based on a giv...
```python class BankAccount: def __init__(self, initial_balance): self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount <= self.balance: self.balance -= amount else: print("Insufficient...
magicoder
python
You are tasked with implementing a message encoder for a schema registry system. The schema registry system is responsible for encoding and decoding messages based on predefined schemas. Your goal is to create a class that can encode messages according to the schema rules. You are provided with an interface `ISchemaRe...
```typescript import ISchemaRegistryEncoding from './ISchemaRegistryEncoding'; class SchemaRegistryEncoder implements ISchemaRegistryEncoding { // Implement the encode method to encode messages based on the predefined schema rules encode(message: string): string { // Add encoding logic based on the predefined ...
magicoder
typescript
You are tasked with implementing a simple result-keeping system for a sports tournament. The provided code snippet includes the import of a `ResultKeeper` module and its associated types and functions. The `ResultKeeper` module is responsible for managing and displaying the results and standings of players in the tourn...
```rust // player.rs pub struct Player { id: u32, // Add any other relevant player information here } // result_keeper.rs use crate::player::Player; pub struct PlayerStanding { player_id: u32, wins: u32, losses: u32, draws: u32, } pub struct ResultKeeper { players: Vec<Player>, standi...
magicoder
rust
You are tasked with creating a custom error handling mechanism for a file processing application. The application needs to handle errors related to file operations and provide detailed error messages for debugging purposes. Your task is to implement a custom error type and a function to handle errors related to file op...
Custom Error Type and Error Handling Function: ```rust use std::fmt; // Define a custom error type for file-related errors #[derive(Debug)] enum FileError { PathNotFound, PermissionDenied, } // Implement the Display trait for custom error type to format error messages impl fmt::Display for FileError { fn...
magicoder
rust
You are given a code snippet from a C header file that defines various constants for different peripherals in a microcontroller. Your task is to write a program that parses this code snippet and extracts the peripheral names and their corresponding values. Write a function `parsePeripheralConstants` that takes a strin...
```python import re def parsePeripheralConstants(code_snippet): peripheral_constants = {} pattern = r'#if defined\((.*?)\)\s+([\w]+)\s+=\s+(.*?),' matches = re.findall(pattern, code_snippet) for match in matches: peripheral_constants[match[1]] = match[2] return peripheral_constants # Test ...
magicoder
python
You are given a Python script that reads integers from a file and processes them in a sliding window. Your task is to complete the script by implementing the sliding window logic and counting the number of times a specific condition is met. The script reads integers from a file named "input.txt" and initializes a slid...
```python SLIDE_WINDOWS = 3 THRESHOLD = 10 f = open("input.txt", "r") window = [] for i in range(SLIDE_WINDOWS): window.append(int(f.readline())) count = 0 for cur in f: window_sum = sum(window) if window_sum >= THRESHOLD: count += 1 window.pop(0) window.append(int(cur)) print(count) ``` ...
magicoder
python
You are tasked with implementing a Python class that manages a collection of neural network layers for a reinforcement learning system. The class should provide methods for adding different types of layers, such as DenseEmbeddingNet, QNet, CNNEmbeddingNet, PolicyNet, and ValueNet, and for retrieving specific layers bas...
```python from Layers.layers import DenseEmbeddingNet, QNet, CNNEmbeddingNet, PolicyNet, ValueNet class NeuralNetworkManager: def __init__(self): self.layers = [] def add_layer(self, layer_type, *args, **kwargs): if layer_type == 'DenseEmbeddingNet': layer = DenseEmbeddingNet(*args...
magicoder
python
You are tasked with implementing a Python class that represents a user's profile. The class should have attributes for the user's name, age, email, and access token. Additionally, you need to implement a method that returns a string representation of the user's profile, excluding any attributes that start with an under...
```python class UserProfile: def __init__(self, name, age, email, access_token): self.name = name self.age = age self.email = email self._internal_data = "some internal data" self.ACCESS_TOKEN = access_token def __str__(self): return ", ".join("{}={}".format(key,...
magicoder
python
You are working as a DevOps engineer for a software company that develops Python packages. As part of the continuous integration and deployment process, you need to automate the deployment of a Python package to the Python Package Index (PyPI) using the `devpi` tool. The deployment process involves pushing the package ...
```python import getpass import subprocess # Prompt the user to input the PyPI username and password securely pypi_username = input("Enter your PyPI username: ") pypi_password = getpass.getpass("Enter your PyPI password: ") # Construct the package name and version using the Travis CI tag travis_tag = "1.0.0" # Repla...
magicoder
python
You are tasked with creating a program that interacts with a web API to retrieve data. Your program should send an HTTP request with specific content and handle the response appropriately. You are given a code snippet that demonstrates how to send the request and handle the response using C# and the HttpClient class. ...
```csharp public async Task<string> SendHttpRequest(HttpClient httpClient, HttpRequestMessage request, HttpContent requestContent) { try { request.Content = requestContent; using (var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { ...
magicoder
csharp
You are tasked with creating a Python script to automate the process of creating an AWS CloudFormation stack for a VPC (Virtual Private Cloud) using the AWS CLI. Your script should handle the execution of the CloudFormation command and provide appropriate feedback based on the success or failure of the stack creation. ...
```python import subprocess # Define the stack name stack_name = "my-vpc-stack" # Execute AWS CLI command to create CloudFormation stack create_stack_command = f"aws cloudformation create-stack --stack-name {stack_name} --template-body file://../cloudformation/csye6225-cf-networking.json --capabilities=CAPABILITY_NAM...
magicoder
python
You are tasked with creating a Python program that processes metadata from a software development project. The metadata is provided as a list of strings, where each string represents a line of metadata. Each line contains a key-value pair separated by a double colon (::). Your program needs to extract specific informat...
```python from typing import List, Dict, Union def process_metadata(metadata: List[str]) -> Dict[str, Union[str, List[str]]]: extracted_info = { "Development Status": "", "Intended Audience": "", "Topic": [] } for line in metadata: key_value = line.split("::") if le...
magicoder
python
You are tasked with implementing a function to generate big rules from frequent itemsets. Given a list of frequent itemsets `L`, a dictionary `support_data` containing the support for each itemset, and a minimal confidence `min_conf`, you need to generate all big rules. Each big rule is represented as a 3-tuple contain...
```python def generate_big_rules(L, support_data, min_conf): big_rule_list = [] for itemset in L: if len(itemset) > 1: for i in range(1, len(itemset)): for antecedent in combinations(itemset, i): antecedent = tuple(sorted(antecedent)) c...
magicoder
python
You are tasked with creating a program that can extract and display information from HTML tags. Specifically, you need to write a function that can extract the text content from an HTML `<h6>` tag with specific attributes and display it. Write a function `extractH6Text` that takes in a string of HTML content and retur...
```python import re def extractH6Text(html_content): pattern = r'<h6 class="m-0 font-weight-bold text-primary">(.*?)</h6>' match = re.search(pattern, html_content) if match: return match.group(1) else: return "Tag not found" # Test cases print(extractH6Text("<h6 class=\"m-0 font-weight...
magicoder
python
You are tasked with implementing a function to determine whether two given arrays of strings are isomorphic. Two arrays of strings are considered isomorphic if they have the same length and there exists a one-to-one mapping of the elements from one array to the other, such that the order is preserved. In other words, e...
```java public static boolean isIsomorphic(String[] arr1, String[] arr2) { if (arr1.length != arr2.length) { return false; // If the arrays have different lengths, they cannot be isomorphic } Map<String, String> mapping = new HashMap<>(); Set<String> mappedValues = new HashSet<>(); for (in...
magicoder
java
You are tasked with implementing a Python class that provides serialization and JSON conversion functionality for its instances. The provided code snippet outlines a basic structure for this class, but it is incomplete. Your task is to complete the class definition and implement the required methods to achieve the desi...
```python import json from abc import ABC, abstractmethod class Serializable(ABC): __abstract__ = True @abstractmethod def serialize(self, includes=None): return {c: getattr(self, c) for c in self.__dict__ if includes is None or c in includes} def to_json(self, includes=None): return ...
magicoder
python
You are tasked with implementing a scoring system for a web application. The system should allow users to submit scores for specific categories and then publish those scores. You are provided with a code snippet from a Node.js application that handles the publishing of scores. Your task is to complete the implementatio...
```javascript // Function to calculate the overall score based on individual category scores function calculateOverallScore(score) { // Calculate the sum of scores for all categories const overallScore = Object.values(score).reduce((total, categoryScore) => total + categoryScore, 0); return overallScore; } // In...
magicoder
javascript
You are tasked with creating a Python program that handles custom exceptions related to test functions and test class names in an exam management system. The program should define two custom exception classes, `TestFuncNameError` and `TestClassNameError`, to handle errors when the test function name is wrong and when t...
```python class ExamException(Exception): """ Base exception class for exam-related errors """ class TestFuncNameError(ExamException): """ Error for when test function name is wrong """ class TestClassNameError(ExamException): """ Error for when test class name is wrong """ def va...
magicoder
python
You are tasked with simulating a simplified trading system using object-oriented programming concepts. Your goal is to create a Trade class that models a trade in a financial market. The Trade class should have methods to open and close trades, as well as to create market orders. Additionally, you need to implement a T...
```python class Trade: def __init__(self): self.trade_id = 0 def open_trade(self, symbol, is_buy, is_in_pips, amount, time_in_force, stop, trailing_step, order_type, limit): # Simulate opening a trade and return a unique trade ID self.trade_id += 1 return self.trade_id def ...
magicoder
python
You are given a code snippet that involves signal processing using the Discrete Fourier Transform (DFT) and visualization using Python's matplotlib library. Your task is to write a Python function that calculates the negative frequency magnitude spectrum and plots it alongside the positive frequency magnitude spectrum....
```python import numpy as np import matplotlib.pyplot as plt def plot_positive_negative_spectrum(mX, N): # Calculate the negative frequency magnitude spectrum mX_neg = np.flip(mX[1:]) # Exclude the DC component and flip the array # Plot the positive and negative frequency magnitude spectra plt.figure...
magicoder
python
You are given a list of lists containing integers. Each inner list represents a row of a 2D grid. The integers in each row are sorted in ascending order. However, the integers in each row are not necessarily in ascending order relative to the integers in other rows. Your task is to write a function that efficiently fin...
```python def find_median(grid): flat_list = [num for row in grid for num in row] flat_list.sort() length = len(flat_list) if length % 2 == 0: return (flat_list[length // 2 - 1] + flat_list[length // 2]) / 2 else: return flat_list[length // 2] ``` The `find_median` function first fla...
magicoder
python
You are tasked with creating a script to simulate a simple dice game using the Bash scripting language. The game involves rolling a six-sided die multiple times and keeping track of the outcomes. Your script should generate random numbers to simulate the dice rolls and then display the frequency of each outcome. Your ...
```bash #!/bin/bash # Function to simulate rolling a six-sided die roll_die() { dieharder -d 209 -g 5 -S $1 | awk 'NR==2{print $3%6+1}' } # Main script declare -A frequencies num_rolls=1000 # Specify the number of times to roll the die for ((i=1; i<=$num_rolls; i++)); do result=$(roll_die $i) ((frequencies[$r...
magicoder
shell
You are tasked with implementing a temperature scheduler for a smart home system. The `run_temp_scheduler()` function is responsible for controlling the temperature settings based on the time of day and the current temperature. The function takes no parameters and returns no value. It operates by querying the current t...
```python import datetime def run_temp_scheduler(): current_time = datetime.datetime.now().time() current_temperature = get_current_temperature() # Assume a function to retrieve the current temperature if datetime.time(6, 0) <= current_time < datetime.time(9, 0) and current_temperature < 70: set_...
magicoder
python
You are tasked with creating a Swift function that retrieves a list of knowledge articles related to a specific case from a Salesforce Service Cloud instance. You will be utilizing the Salesforce Mobile SDK for iOS to achieve this. Your function should take in the case ID as a parameter and return an array of knowledg...
```swift import UIKit import ServiceCore import ServiceChat import ServiceCases import ServiceKnowledge func getKnowledgeArticlesForCase(caseID: String) -> [KnowledgeArticle] { // Authenticate with Salesforce Mobile SDK let authManager = SCAuthenticationManager.shared() authManager.login { (authStatus) in ...
magicoder
swift
You are tasked with creating a program to simulate a simple game of "Whack-a-Mole". In this game, the player must tap on randomly appearing moles to earn points. The moles will appear at random positions on a grid, and the player must tap on them before they disappear to earn points. If the player taps on a mole, they ...
```swift import UIKit class WhackAMoleGame { var score = 0 var rounds = 0 let maxRounds = 10 let gridPositions = [(x: 100, y: 100), (x: 200, y: 100), (x: 300, y: 100), (x: 100, y: 200), (x: 200, y: 200), (x: 300, y: 200), (x: 100, y: 300), (x: 200, y: 300), (x: 300, y: 300)] var moles = [Mole]() ...
magicoder
swift
You are tasked with creating a Python function that parses a time interval string and returns the total number of seconds it represents. The time interval string can have the following format: "X days, HH:MM:SS" or "HH:MM:SS" where X is the number of days, HH is the number of hours, MM is the number of minutes, and SS ...
```python import re def parse_time_interval(time_str): time_str = time_str.strip() if not time_str: raise ValueError(f'{time_str!r} is not a valid time interval') match = re.match( r'^((?P<days>[-+]?\d+) days?,? )?(?P<sign>[-+]?)(?P<hours>\d+):' r'(?P<minutes>\d+)(:(?P<seconds>\d+(...
magicoder
python
You are tasked with creating a script to automate the process of sparsifying a neural network model using a given code snippet as inspiration. The script should iterate through different sparsity levels and perform the necessary operations to create sparse model files and weight files. The script should perform the f...
```bash #!/bin/bash model_file="path_to_model_file.prototxt" net="network_name" weight_file="path_to_weight_file.caffemodel" for sparsity in $(seq 0.10 0.10 0.90) do set_sparse ${model_file} ${sparsity} out_sparse_model_file=${net}_float16_dense_1batch-${sparsity}.prototxt.sparse mv ${net}_float16_dense_...
magicoder
shell
You are tasked with implementing a throttle controller for an autonomous vehicle. The vehicle's throttle control system is represented by a Proportional-Integral-Derivative (PID) controller. The PID controller takes in the vehicle's mass, fuel capacity, brake deadband, deceleration limit, acceleration limit, wheel radi...
```python class ThrottleController: def __init__(self, vehicle_mass, fuel_capacity, brake_deadband, decel_limit, accel_limit, wheel_radius, wheel_base, steer_ratio, max_lat_accel, max_steer_angle): self.yaw_controller = YawController(wheel_base, steer_ratio, 0.1, max_lat_accel, max_steer_an...
magicoder
python
You are tasked with implementing a simple geometric application in Rust. You are given a code snippet defining a trait and a function signature. Your goal is to create a struct and implement the trait for the struct to calculate the distance of the point from the origin. The code snippet provided is as follows: ```rus...
```rust // Define a struct JsPoint representing a point in 2D space struct JsPoint { x: f64, y: f64, } // Implement the trait for JsPoint to calculate the distance of the point from the origin trait DistanceFromOrigin { fn distance_from_origin(&self) -> f64; } impl DistanceFromOrigin for JsPoint { fn ...
magicoder
rust
You are given a list of integers representing the frequency of characters in a string. Your task is to rearrange the characters in the string such that no two adjacent characters are the same. If it is not possible to rearrange the characters, return an empty string. You need to implement the function `rearrangeString...
```python def rearrangeString(freq): max_freq = max(freq) max_freq_char = chr(freq.index(max_freq) + ord('a')) freq[freq.index(max_freq)] -= 1 result = max_freq_char while sum(freq) > 0: prev_char = result[-1] max_freq = max(freq) max_freq_char = chr(freq.index(max_freq) + o...
magicoder
python
You are tasked with implementing a Python class that represents an undirected graph and provides procedures for its manipulation. The graph class should support adding and removing edges, as well as performing depth-first search (DFS), breadth-first search (BFS), and finding connected components. Your task is to compl...
```python class DepthFirstSearch: def __init__(self, graph): self.graph = graph self.visited = set() self.traversal_order = [] def search(self, vertex): self._dfs(vertex) return self.traversal_order def _dfs(self, vertex): if vertex not in self.visited: ...
magicoder
python
You are tasked with creating a program that can extract and display information from a 3D scene file in a specific format. The scene file is provided in the Wavefront .obj format, which is a simple text-based file format that represents 3D geometry. The file contains information about vertices, texture coordinates, nor...
```python import re # Function to extract information from the .obj file def extract_obj_info(file_path): vertices = [] faces = [] with open(file_path, 'r') as file: for line in file: if line.startswith('v '): vertex = list(map(float, re.findall(r"[-+]?\d*\.\d+|\d+"...
magicoder
python
You are working on a project that involves manipulating and tuning mathematical expressions using a specialized library called IR (Expression Manipulation Library). The library provides functions for creating, modifying, and tuning mathematical expressions. In the given code snippet, the variable `rel` is initialized w...
```python def tune_expression(initial_expression: str) -> str: # Split the initial expression into components components = initial_expression.split('(') operator, constants, placeholders = components[1].split(',') constant_value = constants.strip() placeholder1, placeholder2 = placeholders.strip(')'...
magicoder
python
You are tasked with implementing a function that calculates the molecular weight of a chemical compound based on its constituent elements. The molecular weight of a compound is the sum of the atomic weights of all the atoms in the compound. The atomic weights of the elements are provided in a dictionary. Each element i...
```python def calculate_molecular_weight(compound: str, atomic_weights: dict) -> float: weight = 0.0 current_element = "" current_count = 0 for char in compound: if char.isalpha(): if current_element: weight += atomic_weights.get(current_element, 0) * max(current_cou...
magicoder
python
You are tasked with creating a Python program to generate an Excel file containing student information. The program should prompt the user to input the student details, including name, age, and grade. The program should then save this information to an Excel file named "students.xls" with the following format: - The s...
```python import xlwt # Create a new workbook and add a worksheet workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Students') # Prompt user for student details name = input("Enter student's name: ") age = input("Enter student's age: ") grade = input("Enter student's grade: ") # Write headers to the Excel f...
magicoder
python
You are tasked with creating a bash script to monitor the login attempts of a web application and terminate the application if the login attempts exceed a specified timeout. The script should increment a counter for each login attempt and check if the counter exceeds the login timeout value. If the timeout is exceeded,...
```bash #!/bin/bash # Initialize the counter COUNTER=0 # Set the login timeout value LOGIN_TIMEOUT=3 # Example value, can be adjusted as needed # Function to check login attempts and terminate if timeout is exceeded check_login_timeout() { COUNTER=$((COUNTER+1)) if [[ $COUNTER -gt $LOGIN_TIMEOUT ]]; then ...
magicoder
shell
You are tasked with implementing a function to calculate the best blend of enriched air for scuba diving based on the depth and the desired fraction of oxygen. The function should handle error cases where the depth is negative or the fraction of oxygen is outside the valid range. The enriched air calculator class provi...
```swift class EnrichedAirCalculator { func bestBlend(for depth: Int, fractionOxygen: Double) throws -> String { guard depth >= 0 else { throw EnrichedAirCalculationError.invalidDepth } guard fractionOxygen >= 0 && fractionOxygen <= 1 else { throw EnrichedAir...
magicoder
swift