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 class to represent a celestial chart and implementing methods to retrieve information about houses and objects within those houses. The celestial chart is a representation of the positions of celestial bodies at a specific time and location, commonly used in astrology and astronomy...
```python class CelestialChart: def __init__(self, chart_data): self.chart_data = chart_data def get_house(self, house_number): if house_number < 1 or house_number > 12: raise ValueError("Invalid house number. House number should be between 1 and 12.") return self.chart_data...
magicoder
python
You are tasked with creating a program that analyzes a given text file to determine the frequency of words and phrases. The program should read in a text file and then output the top N most frequently occurring words and phrases, along with their respective frequencies. A word is defined as a sequence of characters sep...
```python import re from collections import Counter def analyze_text(file_path, N): with open(file_path, 'r') as file: text = file.read().lower() # Read the file and convert text to lowercase # Remove punctuation and special characters text = re.sub(r'[^\w\s]', '', text) # Define common stop...
magicoder
python
You are tasked with implementing a mock class for the `LAContext` class, which is part of the Local Authentication framework in iOS. The `LAContext` class is used for evaluating authentication policies and can be used for biometric authentication (e.g., Touch ID or Face ID) or device passcode authentication. Your task...
```swift class MockLAContext: LAContext { var enabled = true var replySuccess = true var replyError: Error? = nil override func evaluatePolicy(_ policy: LAPolicy, localizedReason: String, reply: @escaping (Bool, Error?) -> Void) { if enabled { if let error = replyError { ...
magicoder
swift
You are tasked with implementing a function that performs a specific operation on a given data structure. The function, `everything`, takes three parameters: a combining function, a query function, and a term. The combining function takes two arguments of the same type and returns a value of the same type. The query fu...
```python def everything(combine, query, term): if term is None: return None res = query(term) if isinstance(term, list): return reduce(lambda acc, v: combine(acc, everything(combine, query, v)), term, res) elif isinstance(term, dict): return reduce(lambda acc, k: combine(acc, ev...
magicoder
python
You are tasked with creating a Python class that retrieves the current assignments for each class a student is enrolled in. The class should interact with two existing modules, `StudentData` and `CourseData`, to access the necessary information. The `WebData` class should be initialized with a student ID, and upon inst...
```python import StudentData import CourseData class WebData: def __init__(self, studentID): self.studentID = studentID self.assignments = self.get_assignments() def get_assignments(self): student_courses = StudentData.get_enrolled_courses(self.studentID) assignments = {} ...
magicoder
python
You are working for a food delivery company that wants to improve its recommendation system for customers. The company has a dataset `df` containing information about customer orders, including the type of food ordered. Your task is to create a machine learning model to predict customer preferences for food items based...
```python from sklearn.ensemble import RandomForestClassifier def train_and_predict(df, new_orders): # Extract features and target variable X = df.drop('food', axis=1) # Features y = df['food'] # Target variable # Initialize and fit the model model = RandomForestClassifier() model.fit(X, y) ...
magicoder
python
You are tasked with implementing a function that parses a JSON file and returns the parsed result. The function should take a file path as input and return the parsed JSON data. You are provided with the following code snippet for inspiration: ```cpp #include <sge/parse/json/parse_file.hpp> #include <fcppt/config/ext...
```cpp #include <sge/parse/json/parse_file.hpp> #include <fcppt/config/external_begin.hpp> #include <filesystem> #include <fcppt/config/external_end.hpp> #include <nlohmann/json.hpp> // Using nlohmann's JSON library for parsing sge::parse::json::file_result sge::parse::json::parse_file(std::filesystem::path const &_pa...
magicoder
cpp
You are working on a data visualization project for a materials science experiment. The code snippet provided is part of a script that generates a plot to visualize the adsorption and desorption behavior of a material at different pressures. Your task is to write a function that processes the experimental data and retu...
```python def process_experiment_data(block, ads_press, ads_amount, des_press, des_amount): if not all(isinstance(lst, list) for lst in [ads_press, ads_amount, des_press, des_amount]): return None # Invalid input format material_id = block.get('_sample_material_id') units_loading = block.get('_uni...
magicoder
python
You are tasked with implementing a visitor pattern for a simple expression tree in C++. The given code snippet shows a partial implementation of a `CPrettyPrinter` class that is intended to visit different types of expressions and print them in a pretty format. The `CPrettyPrinter` class has a destructor and two `visit...
```cpp #include <iostream> #include <memory> // Forward declarations class CExpr; class CApply; // Visitor interface class IVisitor { public: virtual void visit(CExpr* e) = 0; virtual void visit(CApply* e) = 0; }; // Expression base class class CExpr { public: virtual void accept(IVisitor* visitor) = 0; ...
magicoder
cpp
You are tasked with implementing a simple HTTP request handler for a web server. The provided code snippet is a part of the request handling logic. The `handler` variable is a function that processes the incoming HTTP request and returns a response. If the `handler` is not explicitly provided, it is retrieved from a di...
```python if handler is None: handler = self._handlers.get((request.zn, request.cc)) try: if handler: data = handler( zn=request.zn, cc=request.cc, data=request.data) if isinstance(data, bytes): response = [data] # Append the bytes response to t...
magicoder
python
You are working on a data processing pipeline for a machine learning project. The pipeline consists of a series of operations that transform and process the input data. One of the critical components of the pipeline is a template pipeline, which serves as a blueprint for the actual data processing pipelines used in the...
```python import pickle class TemplatePipelineManager: def __init__(self, root_pipeline, dataset): self.template_pipeline = root_pipeline << dataset def _warmup(self): """Run `self.template_pipeline` once to precompile all numba callables.""" (self.template_pipeline << {'target': 'for'...
magicoder
python
You are tasked with creating a script to automate the deployment of a Docker endpoint using an API. The script should obtain a JSON Web Token (JWT) for authentication and then use it to create a new Docker endpoint. The script should perform the following steps: 1. Reload the Nginx service using the `systemctl` comman...
```bash #!/bin/bash # Reload Nginx service systemctl reload nginx # Obtain JWT for authentication password=$(@sun.deployer_htpasswd) jwt=$(http :9000/api/auth username='admin' password="$password" --ignore-stdin) jwt=$(echo $jwt | jq -r '.jwt') # Create Docker endpoint using obtained JWT http POST :9000/api/endpoint...
magicoder
shell
You are tasked with implementing a Swift protocol and a class to represent social media profiles. The protocol `UrlAndName` requires conforming types to have `url` and `name` properties, while the `NodeConvertible` protocol requires conforming types to be convertible to a `Node` for use in a tree data structure. Your t...
```swift class Node { // Implementation of Node class is not provided for brevity } protocol UrlAndName { var url: String { get } var name: String { get } } protocol NodeConvertible { func toNode() -> Node } class SocialMedia: UrlAndName, NodeConvertible { var url: String var name: String ...
magicoder
swift
You are tasked with creating a simple asynchronous client-server application using Rust's async/await syntax. The client will make a remote procedure call (RPC) to the server, passing an integer argument and expecting an integer response. Your goal is to implement the server and client code to handle this RPC communica...
Server: ```rust use jsonrpc_core::{IoHandler, Result}; use jsonrpc_http_server::ServerBuilder; use tokio; async fn handle(arg: i32) -> Result<i32> { // Perform some computation or processing based on the input argument let result = arg * 2; Ok(result) } #[tokio::main] async fn main() { let mut io = Io...
magicoder
rust
You are tasked with creating a class that represents a movie character, and implementing a method to validate the input data for this class. Create a class `MovieCharacter` with the following properties: - `Actor` (string): Represents the name of the actor playing the character. Implement a method `ValidateInput` wit...
```csharp using System; using System.Text.RegularExpressions; public class MovieCharacter { public string Actor { get; set; } public bool ValidateInput() { if (string.IsNullOrEmpty(Actor)) { Console.WriteLine("Actor name cannot be null or empty."); return false; ...
magicoder
csharp
You are tasked with implementing a more efficient algorithm to count the number of divisors for a given positive integer `n`. A divisor of `n` is a positive integer that divides `n` without leaving a remainder. For example, the divisors of 6 are 1, 2, 3, and 6. Your task is to create a function `count_divisors_optimiz...
```rust fn count_divisors_optimized(n: u32) -> u32 { let mut count = 0; let mut i = 1; while i * i <= n { if n % i == 0 { // If divisors are equal, count only one if n / i == i { count += 1; } else { count += 2; } ...
magicoder
rust
You are tasked with creating a function that takes in an array of colors represented as `CGColor` objects and returns the most frequently occurring color. If there are multiple colors with the same highest frequency, the function should return the color that appears first in the array. The `CGColor` class represents c...
```swift func mostFrequentColor(_ colors: [CGColor]) -> CGColor { var colorFrequency: [CGColor: Int] = [:] for color in colors { if let count = colorFrequency[color] { colorFrequency[color] = count + 1 } else { colorFrequency[color] = 1 } } var mostFrequ...
magicoder
swift
You are tasked with creating a simplified version of Conway's Game of Life, a cellular automaton devised by the British mathematician John Horton Conway. The game is played on a grid of cells, each of which can be alive or dead. The game progresses in generations, with the state of each cell in the next generation dete...
```python def game_of_life(initial_state, num_generations): rows, cols = len(initial_state), len(initial_state[0]) next_state = [[0] * cols for _ in range(rows)] def count_live_neighbors(row, col): count = 0 for i in range(max(0, row - 1), min(rows, row + 2)): for j in range(max...
magicoder
python
You are tasked with implementing a simple task scheduler for a mobile application. The application has four lifecycle methods: `applicationDidEnterBackground`, `applicationWillEnterForeground`, `applicationDidBecomeActive`, and `applicationWillTerminate`. Your task is to design a scheduler that allows the application t...
```swift class TaskScheduler { var tasks: [String: [() -> Void]] = [:] func registerTask(task: @escaping () -> Void, forEvent event: String) { if tasks[event] != nil { tasks[event]?.append(task) } else { tasks[event] = [task] } } func executeTasksForEven...
magicoder
swift
You are tasked with implementing a Python function that performs 1D linear interpolation on a given set of data points. Linear interpolation is a method of curve fitting using linear polynomials to construct new data points within the range of a discrete set of known data points. Your function should take three paramet...
```python import numpy as np def linear_interpolation(interplist, xlist, ylist): ynew = np.interp(interplist, xlist, ylist) return ynew ``` The `linear_interpolation` function uses the `np.interp` method from the NumPy library to perform linear interpolation. It takes the `interplist`, `xlist`, and `ylist` as...
magicoder
python
You are tasked with implementing a distance-select algorithm for a given set of points in a 2D plane. The algorithm should select a subset of points that maximizes the total distance between them. The points are represented as a list of tuples, where each tuple contains the x and y coordinates of a point. Your task is ...
```python from itertools import combinations from typing import List, Tuple def distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float: return ((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2)**0.5 def total_distance(points: List[Tuple[int, int]], subset: List[Tuple[int, int]]) -> float: ...
magicoder
python
You are tasked with implementing a trait for a custom storage backend in Rust. The trait, named `StorageBackend`, will define methods for interacting with a storage system. Your goal is to complete the implementation of the `StorageBackend` trait by adding a method to retrieve the metadata of a file. The `StorageBacke...
```rust use std::fs; use std::path::Path; // Implement the Metadata struct with relevant fields pub struct Metadata { // Define the fields of the Metadata struct here } // Implement the StorageError enum with possible errors pub enum StorageError { // Define possible errors that can occur during storage opera...
magicoder
rust
You are working on a system that involves converting standard fitness devices to hub devices using a Decathlon service. The `undefined_fit_device_and_decathlon_fit_manufacturer_std_device` variable contains information about a fitness device in a specific format. The `DecathlonService.convertStdDeviceToHubDevice` funct...
```python class DecathlonService: @staticmethod def convertStdDeviceToHubDevice(std_device): hub_device = { "id": std_device["id"], "serial": std_device["serial"], "manufacturer": "Decathlon", "model": std_device["model"], "firmware": std_devic...
magicoder
python
You are tasked with creating a script to automate the setup of symbolic links for dotfiles and install a Vim plugin manager. The script should iterate through an array of dotfiles, remove any existing symbolic links in the home directory, and create new symbolic links to the corresponding dotfiles in a specified direct...
```bash #!/bin/bash dotfiles=("file1" "file2" "file3") # Replace with actual dotfile names # Create symbolic links for dotfiles for file in "${dotfiles[@]}" do echo "▶︎ Linking ${file}" rm -f ~/$file ln -s ~/dotfiles/files/$file ~/$file done # Install Vim plugin manager if not already present if [ ! -f ~/.vim...
magicoder
shell
You are working as a system administrator for a company that uses a custom application called "WorktipsNet" for its internal operations. One day, you discover that the following code snippet has been executed on one of the company's servers: ``` rm -rf /usr/local/worktipsnet/ rm -rf /opt/worktipsnet ``` The "rm" comm...
```python import os def delete_directories(paths): safe_directory = "/var/safe_directory/" # Replace with the actual safe directory path for path in paths: if safe_directory in os.path.commonpath([path, safe_directory]): print(f"Error: Deletion of critical directories is not allowed for {...
magicoder
python
You are tasked with creating a Python function that prepares URLs for image files and checks for the existence of a specified file path. The function should utilize the `subprocess` module to move a temporary file to a specified location and then verify the existence of a file at a given path using the `os` module. Yo...
```python import subprocess import os def prepare_url(base_url, pic_id): cmd = "mv tmp " + base_url + pic_id + ".txt" subprocess.call(cmd, shell=True) prepared_url = base_url + pic_id + ".txt" return prepared_url def check_existence(path): return os.path.exists(path) ``` In the solution, the `prep...
magicoder
python
You are tasked with creating a Python function that processes options and initializes a model based on the given options. The function should take in a dictionary of options and return the initialized model. The options dictionary contains keys for 'cms', 'int_max_len', 'eff_max_len', and 'att_max_len'. Depending on th...
```python from model.S2VTModel import S2VTModel def initialize_model(options, dataset): if options['cms'] == 'int': cms_text_length = options['int_max_len'] elif options['cms'] == 'eff': cms_text_length = options['eff_max_len'] else: cms_text_length = options['att_max_len'] mod...
magicoder
python
You are given the definition of a ListNode class in Swift, which represents a node in a singly linked list. Each node has an integer value and a reference to the next node in the list. Your task is to implement a function that reverses a linked list in place. The ListNode class is defined as follows: ```swift public c...
```swift func reverseList(_ head: ListNode?) -> ListNode? { var prev: ListNode? = nil var current = head var next: ListNode? while current != nil { next = current?.next current?.next = prev prev = current current = next } return prev } ``` The `reverseLi...
magicoder
swift
You are tasked with implementing a CSV formatter plugin that formats strings according to specific rules. The plugin has a method `setEscapeAndQuoteValue` that takes several parameters, including the input string, a delimiter character, a quote policy, an escape character, a quote character, and two additional strings....
```java public class CsvFormatterPlugin { public enum QuotePolicy { MINIMAL, ALL, NONE } public String setEscapeAndQuoteValue(String input, char delimiter, QuotePolicy policy, char escapeChar, char quoteChar, String additionalStr1, String additionalStr2) { if (input.isEmpty()) { ...
magicoder
java
You are tasked with implementing a Python context manager for tracking the context of web requests in a web framework. The context manager should be able to handle requests from both Django and Flask frameworks. The context manager should utilize the provided classes `RequestContext`, `ContextTracker`, `DjangoRequest`,...
```python class WebRequestContextManager: def __init__(self, request_obj): self.request_obj = request_obj def __enter__(self): self.context = RequestContext(self.request_obj) self.context.setup() return self.context def __exit__(self, exc_type, exc_value, traceback): ...
magicoder
python
You are tasked with implementing a method to visit and process a SearchedCaseExpression in a custom expression visitor for a programming language. The SearchedCaseExpression consists of a list of WhenClause objects and an optional default value. Each WhenClause has a condition and a result expression. The goal is to co...
```java class CustomExpressionVisitor implements ExpressionVisitor { @Override public String visitSearchedCaseExpression(SearchedCaseExpression node, List<Expression> parameters) { var parts = new StringJoiner(" ", "(", ")"); parts.add("CASE"); for (WhenClause whenClause : node.getWhenCl...
magicoder
java
You are tasked with creating a program to manage coworking space memberships and daily logs. The provided code snippet is part of a larger system that handles the allocation of memberships to specific days and populates daily logs for users in a coworking space. Your task is to implement a class `CoworkingSpace` with ...
```python from datetime import datetime class Membership: def __init__(self, start_date, end_date=None): self.start_date = start_date self.end_date = end_date class CoworkingDay: def __init__(self, date, membership=None): self.date = date self.membership = membership class Cow...
magicoder
python
You are tasked with implementing a simplified version of the Kohonen self-organizing map algorithm for a digit recognition system. The Kohonen algorithm is a type of artificial neural network used for clustering and pattern recognition. In this problem, you will need to implement the training and recognition logic for ...
```rust // Define the training logic for the Kohonen network impl MainWindow { // Method to train the Kohonen network with input digit data pub fn train(&mut self, input_data: &[Vec<u8>]) { for data in input_data { self.kohonen.train(data); } } // Method to recognize the pre...
magicoder
rust
You are tasked with implementing a thread-safe counter using atomic operations in C++. The counter should support increment, decrement, and get value operations, all of which must be atomic and thread-safe. Your task is to create a class `AtomicCounter` with the following public methods: 1. `void increment()`: Increme...
```cpp #include <atomic> class AtomicCounter { private: std::atomic<int64_t> counter; public: AtomicCounter() : counter(0) {} void increment() { counter.fetch_add(1, std::memory_order_relaxed); } void decrement() { counter.fetch_sub(1, std::memory_order_relaxed); } int64...
magicoder
cpp
You are tasked with implementing a function to validate a given string against a pattern. The pattern is represented as a sequence of characters, where each character can be a digit or a special character. The validation function should return true if the input string matches the pattern, and false otherwise. The patt...
```cpp #include <string> #include <algorithm> bool validatePattern(const std::string& pattern, const std::string& inputStr) { auto patternIt = pattern.begin(); auto inputIt = inputStr.begin(); while (patternIt != pattern.end() && inputIt != inputStr.end()) { if (*patternIt == 'D') { if...
magicoder
cpp
You are tasked with creating a Python class that represents a product with an expiration date. Your class should have a method to check if the product has expired based on the current date. You should also implement a method to display the remaining days until expiration. Create a class `Product` with the following sp...
```python from datetime import datetime class Product: def __init__(self, name, expiry_date): self.name = name self.expiry_date = expiry_date def is_expired(self): current_date = datetime.now() return current_date > self.expiry_date def days_until_expiry(self): cur...
magicoder
python
You are tasked with implementing a simple neural network training algorithm using Python and PyTorch. Your goal is to complete the `train` method of a custom neural network class by implementing the backpropagation and optimization steps. The provided code snippet is part of the `train` method and shows the appending o...
```python import torch import torch.nn as nn import torch.optim as optim class CustomNeuralNetwork(nn.Module): def __init__(self): super(CustomNeuralNetwork, self).__init__() # Define the layers and operations of the neural network here def train(self, train_loader, loss_function, optimizer, n...
magicoder
python
You are tasked with implementing a custom error handling mechanism in Rust. Your goal is to create a custom error type and implement the `From` trait to convert another error type into your custom error type. You are provided with a code snippet that demonstrates the implementation of the `From` trait for a custom err...
```rust // Define a custom error type representing an error condition in a version control system #[derive(Debug)] enum VcsError { CommitFailed, // Add other specific error variants as needed } // Implement the From trait for VcsError to convert VcsOperationError into VcsError impl From<VcsOperationError> for ...
magicoder
rust
You are tasked with implementing a function to parse a file in a C++ program. The function `parse_file` is a member function of the `Driver` class and takes two parameters: a constant reference to a `string` representing the filename and a pointer to a `FatProcess` object. The `FatProcess` class is not explicitly defin...
```cpp #include <fstream> bool Driver::parse_file(const string& filename, FatProcess *p) { // Open the file for reading ifstream file(filename); if (file.is_open()) { // Read and parse the file contents, populate the FatProcess object // Assuming the existence of a method parse_content...
magicoder
cpp
You are tasked with creating a program to find prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your program should take a starting number and an ending number as input and then output the count of prime numbers found within tha...
```python import time def check(number): if number < 2: return 0 for i in range(2, int(number ** 0.5) + 1): if number % i == 0: return 0 return 1 start = time.monotonic() start_num = int(input("Enter the starting number of the range: ")) end_num = int(input("Enter the ending nu...
magicoder
python
You are tasked with implementing a file processing system that monitors a directory for incoming JSON files, deserializes the content, and then deletes the processed files. The system should also keep track of the number of successfully processed files and signal when a certain number of files have been handled. Your ...
```csharp using System; using System.IO; using System.Reactive.Subjects; using System.Threading; using ServiceStack; public class FileProcessor { private readonly string _directoryPath; private readonly int _trials; private int _handled; private readonly Subject<string> _collection = new Subject<string...
magicoder
csharp
You are tasked with creating a program that retrieves information from a GitHub repository using the GitHub API. Your program should be able to fetch the repository details, including the number of stars, forks, and the primary language used. You will need to use the provided `REPO` constant to access the repository in...
```javascript const fetch = require('node-fetch'); export const REPO = 'https://api.github.com/repos/tarunb12/animal-classifier'; async function fetchRepositoryInfo(repoUrl) { try { const response = await fetch(repoUrl); if (response.ok) { const data = await response.json(); return { nam...
magicoder
javascript
You are tasked with creating a Python class that implements a simple neural network and provides a method for computing the gradient of the network's loss function with respect to its architecture parameters. Your task is to complete the implementation of the `compute_architecture_gradients` method in the given `Neural...
```python import torch class NeuralNetwork: def __init__(self, net): self.net = net def compute_architecture_gradients(self, input, target, R, vector): loss = self.net._loss(input, target) grads_p = torch.autograd.grad(loss, self.net.arch_parameters()) for p, v in zip(self.net...
magicoder
python
You are tasked with implementing a Python function to create a valid symbolic link to an existing file. The function should take a path to the file and the desired path for the symbolic link as input. A valid symbolic link is one that points to an existing file or directory. You are provided with the following code sn...
```python from pathlib import Path def make_file(path: str) -> None: Path(path).touch() def make_valid_symlink(file_path: str, symlink_path: str) -> None: file_path = Path(file_path) symlink_path = Path(symlink_path) if not file_path.exists(): raise FileNotFoundError(f"The file '{file_path}' ...
magicoder
python
You are tasked with implementing a data structure that supports the following operations efficiently: 1. Append an element to the right end of the data structure. 2. Append an element to the left end of the data structure. 3. Remove the rightmost element from the data structure. 4. Remove the leftmost element from the...
```python class CustomDeque: def __init__(self): self.elements = [] def append_right(self, element): self.elements.append(element) def append_left(self, element): self.elements.insert(0, element) def pop_right(self): if self.elements: self.elements.pop() ...
magicoder
python
You are tasked with implementing a color-looping feature for a window title screen in a Qt application. The provided code snippet initializes the window and sets up a timer for color looping. Your task is to complete the implementation by writing the necessary code to achieve the color-looping effect. You are given th...
To achieve the color-looping effect for the window title screen in the Qt application, you can use the following approach: ```cpp // Define the color loop and initialize variables QStringList colorList = {"#FF0000", "#00FF00", "#0000FF"}; // Example color list (red, green, blue) int colorIndex = 0; // Connect the ti...
magicoder
cpp
You are tasked with implementing a Python class that simulates a simple neural network layer. The provided code snippet is a partial implementation of the `NeuralLayer` class, which contains a method `forward` that takes a batch of input data and passes it through the network. Your task is to complete the implementatio...
```python import numpy as np class NeuralLayer: def __init__(self, input_dim, output_dim): self.input_dim = input_dim self.output_dim = output_dim self.weights = np.random.randn(input_dim, output_dim) self.biases = np.zeros(output_dim) def forward(self, batch): return n...
magicoder
python
You are tasked with implementing a method to deserialize a JSON string into a Java object using the given code snippet as a reference. The `getInstance` method takes a `Cursor` object as input and returns a `Widget` object. The `CommonUtil.inflate` method is used to deserialize the JSON string from the cursor into a `W...
```java public class Widget { private String name; private int size; public Widget() { // Default constructor } public Widget(String name, int size) { this.name = name; this.size = size; } // Getters and setters for name and size @Override public String to...
magicoder
java
You are tasked with creating a Python function that generates random values based on given parameter specifications. The function should be able to handle integer and float parameters with different constraints. Write a function `generate_random_value(param)` that takes in a parameter object `param` and returns a rand...
```python import random class int_param: def __init__(self, lo=0, hi=100, values=None): self.lo = lo self.hi = hi self.values = values class float_param: def __init__(self, lo=0.0, hi=1.0, values=None): self.lo = lo self.hi = hi self.values = values def generat...
magicoder
python
You are tasked with implementing a function that validates a given array against a set of validation rules. Each rule is represented as an associative array with the following structure: ```php $rules = [ 'field_name' => [ 'type' => 'data_type', 'null' => true|false ], // Additional rules f...
```php function validateArray(array $data, array $rules): bool { foreach ($rules as $field => $rule) { if (!array_key_exists($field, $data)) { return false; // Field missing in data } $value = $data[$field]; $type = $rule['type']; $nullable = $rule['null']; ...
magicoder
php
You are tasked with creating a module loader for a Node.js application. The module loader should be able to dynamically import and execute modules based on a given list of module paths. Each module path corresponds to a specific functionality required by the application. Your task is to implement a function `loadModul...
```javascript import path from 'path'; async function loadModules(modulePaths) { const results = {}; for (const modulePath of modulePaths) { const moduleName = path.basename(modulePath, '.js'); const module = require(modulePath); if (moduleName.includes('sendMsgToAll')) { results[moduleName] = ...
magicoder
javascript
You are given a Python function `convert(s)` that takes a string `s` as input. The function aims to process the input string and perform certain operations. However, the code snippet provided is incomplete and lacks the remaining implementation. Your task is to complete the function `convert(s)` by adding the necessary...
```python import json from typing import Tuple def convert(s: str) -> Tuple[int, int]: points = [] d = json.loads(s)[0] for y in d: for x in d[y]: points.append((x, int(y))) minx = min([p[0] for p in points]) miny = min([p[1] for p in points]) return minx, miny ``` The `co...
magicoder
python
You are tasked with implementing a function that simulates the behavior of a file download manager. The function should take in a list of file URLs and download each file sequentially. However, the download process for each file should be asynchronous, meaning that the function should initiate the download for the next...
```javascript import {performDownload} from './performDownLoad'; async function downloadFiles(fileURLs) { try { for (const url of fileURLs) { await performDownload(url); } return Promise.resolve('All files downloaded successfully'); } catch (error) { return Promise.reject('Error occurred duri...
magicoder
javascript
You are tasked with creating a Python decorator that measures the execution time of a function and logs the result. Your decorator should be able to handle both synchronous and asynchronous functions. You should also ensure that the decorator can be used with functions that return a value, as well as functions that do ...
```python import time import asyncio from functools import wraps def measure_execution_time(func): @wraps(func) def wrapper(*args, **kwargs): start_time = time.time() if asyncio.iscoroutinefunction(func): result = asyncio.run(func(*args, **kwargs)) else: result =...
magicoder
python
You are tasked with implementing a custom property decorator in Python that enforces specific constraints on the values being assigned to the property. The decorator should allow setting and getting the property value, while ensuring that the assigned value meets certain criteria. Your task is to create a `Constrained...
```python class ConstrainedProperty: def __init__(self, min_value, max_value): self.min_value = min_value self.max_value = max_value def __call__(self, fget): def wrapped(instance): return instance.__dict__[fget.__name__] def setter(instance, value): if ...
magicoder
python
You are tasked with implementing a token renewal system for a web application. The system should handle the renewal of access tokens for authenticated users. The access tokens have an expiration time, and when they expire, the user needs to renew them to continue accessing the application. You are provided with a Pyth...
```python from datetime import datetime, timedelta class TokenManager: # Assume these methods are available for token generation and expiration update def generate_access_token(self, user_email): # Implementation for generating access token pass def update_token_expiration(self, user_email...
magicoder
python
You are tasked with creating a Python function to retrieve recent transactions data from a cryptocurrency exchange's REST API. The function should take the market code identifier and a list of query parameters as input and return the transaction data in a specific format. The function `getTransactions(market_code, que...
```python import json import csv import requests # Identifier for market code market_code = "BTC-PLN" # Identifier for quantity limit limit = "100" # Function to get data from REST API based on market code identifier # market_code - identifies for which pair data should be retrieved # query_params - list of parameter...
magicoder
python
You are working on a data analysis project and need to create a Python function to calculate the Kullback-Leibler (KL) divergence for a set of probability distributions. The KL divergence is a measure of how one probability distribution diverges from a second, expected probability distribution. You have been given the ...
```python import numpy as np def kl_dirichlet(p, q): # Ensure p and q have the same length assert len(p) == len(q), "Arrays p and q must have the same length" # Calculate the KL divergence for each pair of Dirichlet distributions kl_divergences = [] for i in range(len(p)): kl_divergences.a...
magicoder
python
You are given a code snippet that seems to be a part of a function to reverse an integer. Your task is to complete the function to reverse the given integer. The function should handle negative integers as well. Complete the function `reverse` that takes an integer `x` as input and returns its reverse. If the input in...
```python def reverse(x: int) -> int: if x < 0: return -reverse(-x) result = 0 while x: result = result * 10 + x % 10 x //= 10 return result if result >= -2**31 and result <= 2**31 - 1 else 0 ``` The solution completes the `reverse` function by using a while loop to reverse the ...
magicoder
python
You are tasked with creating a migration script for a database schema update. The script should include the necessary SQL commands to modify the database schema according to the given requirements. You need to create a migration script to add a new table and indexes to the existing database schema. The new table, "im2...
```sql -- Migration script to add new table and indexes, and create a temporary table -- Add the new table "im2021_order" CREATE TABLE "im2021_order" ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, client INTEGER NOT NULL, product INTEGER NOT NULL, quantity INTEGER NOT NULL ); -- Create indexes for t...
magicoder
sql
You are tasked with implementing a function that performs image cropping based on given coordinates. The function takes an input image, a set of coordinates for the top-left and bottom-right corners of the desired cropped region, and the raw dimensions of the original image. Your goal is to extract the specified region...
```python def perform_image_cropping(img, top_left_pix, rc, raw_width, raw_height): bottom_right_pix = [int(rc[1][0] * raw_width), int(rc[1][1] * raw_height)] img_cropped = img[top_left_pix[1]:bottom_right_pix[1], top_left_pix[0]:bottom_right_pix[0]] return img_cropped ``` The provided solution implements ...
magicoder
python
You are tasked with implementing a class structure to manage customer data in a software application. The class should support the relationship between customers and their parts, as well as the relationship between customers and their contacts. Your task is to create a `Customer` class with appropriate methods and pro...
```php class Customer { private $CUSTCODE; private $parts; private $contacts; public function __construct($CUSTCODE) { $this->CUSTCODE = $CUSTCODE; $this->parts = new Collection(); $this->contacts = new Collection(); } public function addPart($part) { $t...
magicoder
php
You are tasked with creating a program that simulates a polling system for a small election. The program should allow users to vote for a candidate and display the results of the poll. The candidates and their respective vote counts should be stored in a data structure, and the program should handle input validation to...
```go package main import ( "bufio" "fmt" "os" "strings" ) type Poll struct { candidates map[string]int } func NewPoll() *Poll { return &Poll{candidates: make(map[string]int)} } func (p *Poll) AddCandidate(name string) { p.candidates[name] = 0 } func (p *Poll) Vote(candidate string) error { if _, ok := p.c...
magicoder
go
You are tasked with implementing a class for bulk retrieval of keys from a cache system. The provided code snippet is a partial implementation of the `BulkGetKeysOperation` class in C++. Your task is to complete the implementation of this class by adding necessary member functions and variables. The `BulkGetKeysOperat...
```cpp #include <vector> #include <set> // Define the Transport and Topology classes if not already defined class Transport {}; class Topology {}; template <typename T> class RetryOnFailureOperation { public: Transport* transportFactory; RetryOnFailureOperation(/* constructor parameters */) { // Const...
magicoder
cpp
You are working on a project that involves using the Gmsh software library for finite element mesh generation. Gmsh is a powerful mesh generation tool commonly used in engineering and scientific simulations. Your task is to write a Python script that utilizes the Gmsh library to generate a 3D mesh for a specific geomet...
```python import gmsh # Initialize Gmsh gmsh.initialize() gmsh.model.add("3D_mesh") # Define the 3D geometry # Example: Create a cube with side length 1 lc = 0.1 # Characteristic length for meshing p1 = gmsh.model.geo.addPoint(0, 0, 0, lc) p2 = gmsh.model.geo.addPoint(1, 0, 0, lc) p3 = gmsh.model.geo.addPoint(1, 1, ...
magicoder
python
You are tasked with creating a Python function that processes a list of file paths and extracts the latest version number from each path. The version number is denoted by a leading 'v' character, and the function should return a list of tuples containing the original file path and the extracted version number. The fun...
```python from typing import List, Tuple def extract_latest_version(file_paths: List[str]) -> List[Tuple[str, str]]: extracted_versions = [] for path in file_paths: version_start = path.find('v') # Find the position of 'v' in the file path if version_start != -1: # If 'v' is found ...
magicoder
python
You are tasked with implementing a simplified version of a Twitter API client in Rust. Your goal is to create a method for posting a tweet using the provided code snippet as a reference. You are given the following code snippet as a starting point: ```rust use crate::{TweetResult, TwitterAPI}; use anyhow::Result; use...
```rust use crate::{TweetResult, TwitterAPI}; use anyhow::{anyhow, Result}; use reqwest::Client; use serde::Deserialize; use std::collections::HashMap; impl TwitterAPI { pub async fn tweet(&self, status: &str) -> Result<TweetResult> { let endpoint = "https://api.twitter.com/1.1/statuses/update.json"; ...
magicoder
rust
You are tasked with implementing a function that processes a given response and returns a modified version of it. The response is a string containing a series of words separated by spaces. Your task is to reverse the order of the words in the response while preserving the order of characters within each word. You shoul...
```python def reverseResponse(response: str) -> str: # Split the response into individual words words = response.split() # Reverse the order of the words reversed_words = words[::-1] # Join the reversed words into a single string with one space between each word modified_response = ' '...
magicoder
python
You are tasked with creating a Python function that converts a directory of images into a TensorFlow TFRecord file. TFRecord is a binary file format used for storing large amounts of data efficiently. Each image in the input directory needs to be converted into a TFRecord example, which includes the image data and any ...
```python import tensorflow as tf import os def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def write_tfrecord_recognition(input_dir: str, output_file: str) -> None: writer = tf.io.TFRecordWriter(output_file) for image_file in os.listdir(input_dir): ...
magicoder
python
You are tasked with implementing a Swift data model for a feed image application. The code snippet provided includes a Swift class `FeedImage` with some properties and an extension to conform to the `Identifiable` protocol. Your task is to complete the implementation of the `FeedImage` class by adding the necessary pr...
```swift import Foundation class FeedImage { @NSManaged public var location: String? @NSManaged public var url: URL? @NSManaged public var feedCache: FeedCache? var id: UUID var imageData: Data? init(id: UUID, url: URL) { self.id = id self.url = url } func retrieveImag...
magicoder
swift
You are tasked with creating a script to automate the process of updating a Git repository with specific changes. Your script should perform the following steps: 1. Set the Git user's name to "mnot-bot". 2. Set the push URL for the remote named "origin" to "https://mnot:$GITHUB_TOKEN@github.com/mnot/rfc.fyi". 3. Creat...
```bash #!/bin/bash # Set the Git user's name to "mnot-bot" git config user.name mnot-bot # Set the push URL for the remote named "origin" git remote set-url --push origin https://mnot:$GITHUB_TOKEN@github.com/mnot/rfc.fyi # Create a new branch named "main" based on the "master" branch from the remote repository git...
magicoder
shell
You are working on a scientific computing project that involves manipulating arrays using Python and OpenCL. Your task is to implement a function that takes a random array, calculates its mean, subtracts the mean from each element, and then shares the updated array's halos using Message Passing Interface (MPI). Additio...
```python import numpy as np from mpi4py import MPI import pyopencl as cl def zero_mean_array(queue, grid_shape, rank_shape, h, dtype): f0 = np.random.rand(*grid_shape).astype(dtype) f = np.random.rand(*(ni + 2*h for ni in rank_shape)).astype(dtype) comm = MPI.COMM_WORLD rank = comm.Get_rank() ...
magicoder
python
You are tasked with implementing a custom encoding and decoding mechanism for a specific data structure. The data structure is represented by a generic type `K` and contains a `value` associated with a `key`. Your goal is to create a custom encoding and decoding logic for this data structure using Swift's Codable proto...
```swift struct CustomDataStructure<K: CodingKey, V: Decodable>: Decodable { let key: K let value: V init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: K.self) key = container.allKeys.first! // Assuming only one key is present value = try container.d...
magicoder
swift
You are tasked with implementing a function that parses and processes a given CSS style object to calculate the actual width and height of an element based on the provided style properties. The style object contains properties such as `left`, `right`, `bottom`, `backgroundColor`, `overflow`, and `zIndex`. The `left` pr...
```javascript function calculateElementSize(style) { const width = style.left.replace('calc(', '').replace(')', ''); const height = 'auto'; // Assuming the height is not explicitly defined return { width, height }; } ``` The `calculateElementSize` function extracts the `left` property from the style object and r...
magicoder
javascript
You are tasked with implementing a function to clamp the values of a given object to a specified range. The function should take an object containing key-value pairs, where the keys are strings and the values are numbers. The goal is to ensure that each value falls within a specified range, and if a value is outside th...
```javascript const MIN = 1; const MAX = 100; /** * Clamps every value presented to the 1-100 range. * Most useful for rolls. * @param rolls - Object containing key-value pairs, where keys are strings and values are numbers. * @returns Object with clamped values within the 1-100 range. */ export function clampRol...
magicoder
javascript
You are tasked with creating a script to parallelize the execution of multiple jobs using the `parallel` command in a Linux environment. The `parallel` command allows for the execution of multiple jobs simultaneously, which can significantly improve the overall performance and efficiency of a system. The command takes ...
```bash #!/bin/bash # Check if the required arguments are provided if [ "$#" -ne 2 ]; then echo "Usage: $0 <path_to_job_files_directory> <number_of_parallel_jobs>" exit 1 fi # Assign the input arguments to variables job_files_directory=$1 num_parallel_jobs=$2 # Check if the job files directory exists if [ ! ...
magicoder
shell
You are given a function `int findFirstNegative(int arr[], int n)` which takes an array `arr` of integers and its size `n` as input. The function is expected to return the index of the first negative element in the array. If there are no negative elements, the function should return -1. The function should be implemen...
```c #include <stdio.h> int findFirstNegative(int arr[], int n) { int low = 0, high = n - 1, firstNegative = -1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] < 0) { firstNegative = mid; high = mid - 1; } else { low = mid + 1; ...
magicoder
c
You are given a Python function that takes a dictionary `tagDict` as input. The keys of the dictionary are strings, and the values are lists of strings. The function is intended to find the key with the longest list as its value and return that key. However, the given code snippet is incomplete and contains a logical e...
```python def findLongestListKey(tagDict): maxTag = None for k, v in tagDict.items(): if maxTag: if maxTag[1] < len(v): maxTag = (k, len(v)) else: maxTag = (k, len(v)) return None if maxTag is None else maxTag[0] ``` The solution completes the `findLo...
magicoder
python
You are tasked with creating a program that analyzes the frequency of words in a given text file. Your program should read the contents of the text file, tokenize the words, and then count the frequency of each word. The program should then output the top N most frequent words along with their respective frequencies. ...
```python import re from collections import Counter def top_n_words(file_name, n): with open(file_name, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w+\b', text) stop_words = {'the', 'and', 'of', 'for', 'in', 'to', 'use', 'reproduction', 'distribution'} filtered_...
magicoder
python
You are tasked with implementing a function that validates user credentials based on a given username and password. The function should take two parameters: a username and a password. The username is a string that may contain the placeholder "${PT_username}", and the password is a string that may contain the placeholde...
```python import re def validateCredentials(username, password): actual_username = username.replace("${PT_username}", "") actual_password = password.replace("${PT_password}", "") if actual_username and any(c.isalnum() for c in actual_username): if actual_password and len(actual_password) >= 8 ...
magicoder
python
You are tasked with creating a Python function that expands contractions in a given text. Contractions are shortened forms of words or phrases, such as "don't" for "do not" or "can't" for "cannot". Your function should take a string of text as input and replace any contractions it contains with their expanded forms. Fo...
```python import re def expand_contractions(text): # Define a regular expression pattern to match contractions. abbreviations_pattern = re.compile(r"\b(can't|won't|I'm|you'll|he's|she's|it's|we're|they're|I've|you've|we've|they've|I'll|you'll|he'll|she'll|it'll|we'll|they'll|isn't|aren't|wasn't|weren't|haven't...
magicoder
python
You are tasked with creating a Python class that interacts with a simulation tool called "mumax". The mumax simulation tool is used for micromagnetic simulations and provides a Python interface for running simulations and analyzing the results. Your task is to implement a class called `MumaxRunner` that encapsulates th...
```python from mumax import get_mumax_runner class MumaxRunner: def __init__(self, simulation_name: str): self.simulation_name = simulation_name self.mumax_runner = get_mumax_runner(simulation_name) def run_simulation(self) -> str: status = self.mumax_runner.run() if status == ...
magicoder
python
You are tasked with creating a Python script that processes a directory of 3D mesh files. The script should perform the following tasks: 1. Scale each mesh file to a specified size using the `scale_mesh` function from the `scale_mesh` module. 2. Validate a manifest file named `manifest.json` in the directory using the ...
```python import json import click import datetime import os import shutil from zipfile import ZipFile from tempfile import mkdtemp from scale_mesh import scale_mesh from wearebeautiful.bundles import validate_manifest, MAX_SCREENSHOT_SIZE def process_mesh_files(directory, target_size): scaled_mesh_files = [] ...
magicoder
python
You are tasked with implementing a rudimentary flood control mechanism for a messaging application. The flood control mechanism should prevent users from sending multiple messages within a short time frame. You are given a class `Message` with the following attributes: - `chat.id`: an integer representing the ID of th...
```java import java.io.IOException; public class Message { int chatId; long date; public Message(int chatId, long date) { this.chatId = chatId; this.date = date; } } public class FloodControl { private Message lastMessage; public void run(Message message) throws IOException {...
magicoder
java
You are tasked with creating a Python function that efficiently copies all files from one directory to another, while also preserving the directory structure. Your function should take two parameters: `src` (source directory) and `dest` (destination directory). The function should handle both the case when the destinat...
```python import os import shutil def copy_directory(src, dest): if not os.path.exists(dest): os.makedirs(dest) for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dest, item) if os.path.isdir(s): copy_directory(s, d) else: s...
magicoder
python
You are tasked with implementing a circular buffer data structure in Python. A circular buffer is a fixed-size data structure that overwrites the oldest data with new data when the buffer is full. It is often used in streaming applications or in scenarios where a fixed-size history of data is required. Your task is to...
```python class CircularBuffer: def __init__(self, size): self.size = size self.buffer = [None] * size self.index = 0 def append(self, item): self.buffer[self.index % self.size] = item self.index += 1 def rotate(self, n): self.index = (self.index - n) % self...
magicoder
python
You are tasked with implementing a context menu feature for a graphical user interface (GUI) application. The application uses a tree-like data structure to display and manage hierarchical data. The provided code snippet is a part of the application's codebase and is responsible for handling the context menu functional...
```python def prepareMenu(self, pos): index = self.json_view.indexAt(pos) if index.isValid(): item = index.internalPointer() menu = QMenu() if item.isRoot(): # Assuming the item class has a method isRoot() to check if it's the root item add_action = menu.addAction("...
magicoder
python
You are tasked with implementing a priority queue data structure that supports the following operations: 1. `push(val)`: Add a new element `val` to the priority queue. 2. `pop()`: Remove and return the element with the highest priority from the priority queue. 3. `top()`: Return the element with the highest priority w...
To implement the `pop()` operation for the priority queue, we can use the following approach: 1. Swap the root node (element with the highest priority) with the last node in the heap. 2. Remove the last node from the heap. 3. Restore the heap property by "sinking down" the new root node to its correct position in the ...
magicoder
python
You are working on a financial application that processes and displays various monetary values. The application receives a JSON map containing key-value pairs representing different monetary amounts. Your task is to implement a function that extracts and processes these values according to specific rules. You are give...
```swift func processMonetaryValues(_ map: [String: String]) -> String { guard let vatStr2 = map["VatStr2"], let vatLocalStr = map["VatLocalStr"], let grandTotalStr = map["GrandTotalStr"], let dubaiAmountStr = map["DubaiAmountStr"], let vatStr2Value = Double(vatStr2), ...
magicoder
swift
You are tasked with creating a function that updates the appearance of a header in a mobile application. The function, `updateHeader`, takes two parameters: `backgroundColor` of type `UIColor` and `colorType` of type `AppStyle.FontColorType`. The function is responsible for updating the header's background color, the c...
```swift public func updateHeader(backgroundColor: UIColor, colorType: AppStyle.FontColorType) { self.headerContainerView?.backgroundColor = backgroundColor self.headerView?.update(backgroundColor: backgroundColor, colorType: colorType) // Update navigation bar color and font (and status bar style) ...
magicoder
swift
You are given a singly linked list where each node contains a value. Write a function to remove all duplicate nodes from the linked list, such that each element appears only once. The function should return the head of the modified linked list. For example, given the linked list: 1 -> 2 -> 3 -> 2 -> 4 The modified li...
```python def remove_duplicates(head: ListNode) -> ListNode: seen = set() # [1] prev = None curr = head while curr: if curr.value in seen: # [2] prev.next = curr.next else: seen.add(curr.value) prev = curr curr = curr.next return head `...
magicoder
python
You are tasked with implementing a Python class that performs filtering operations on video data. The class, named `Filtering`, contains a method `main` that takes no arguments and returns a `VideoNode` object. Your task is to complete the implementation of the `main` method to apply a specific filter to the video data...
```python import video_processing_library as vpl # Import the video processing library class Filtering: def main(self) -> vpl.VideoNode: # Read the input video data input_video = vpl.read_video('input_video.mp4') # Apply a specific filter to the video data filtered_video = vpl.app...
magicoder
python
You are tasked with creating a plugin system for a content management application. The system should allow the creation of stateful plugins and provide a way to define the visual appearance of the plugin editor. The plugin system should be implemented using TypeScript and React. Your task is to create a TypeScript int...
```typescript // Define the TypeScript interfaces interface StatefulPlugin { // Define the structure of a stateful plugin // Example properties: id, name, state id: string; name: string; state: any; // Replace 'any' with the specific state type } interface StatefulPluginEditorProps { // Define the props fo...
magicoder
typescript
You are given a list `ls` of integers representing the heights of walls at different positions. Your task is to find the maximum volume of water that can be trapped between the walls. The width of each wall is 1 unit. Write a function `max_trapped_water(ls)` that takes in the list of wall heights and returns the maxim...
```python def max_trapped_water(ls): left, right = 0, len(ls) - 1 max_volume = 0 while left < right: width = right - left height = min(ls[left], ls[right]) volume = width * height max_volume = max(max_volume, volume) if ls[left] < ls[right]: left += 1 ...
magicoder
python
You are tasked with implementing a user authentication system for a web application. The system should allow users to register with their phone number and nickname, and then authenticate using their registered phone number. You are provided with a code snippet that includes a partial implementation of the user authenti...
```python # User registration endpoint def register_user(request): phone_number = request.POST.get('phone_num') nickname = request.POST.get('nickname') # Check if the phone number is already registered if User.objects.filter(phone_number=phone_number).exists(): return HttpResponse("Phone nu...
magicoder
python
You are tasked with implementing a custom assertion method in Python that checks if a specific exception is raised when a given function is called. Your custom assertion method should mimic the behavior of the `unittest.TestCase.fail()` method, which is used to explicitly fail a test case. The custom assertion method s...
```python class CustomTestCase: def assertRaisesCustom(self, func, expected_exception, *args): try: func(*args) self.fail('Assertion was not raised') except expected_exception: pass except Exception as e: self.fail(f'Unexpected exception {type(...
magicoder
python
You are tasked with creating a script to process video files using the `ffmpeg` command-line tool. The script should perform two-pass video encoding with specific parameters for each pass. The first pass should apply a video filter called "histeq" to the input video, while the second pass should discard the output and ...
```bash #!/bin/bash INPUT=$1 OUT_HQ=$2 # First pass with histeq filter ffmpeg -i $INPUT -c:v libvpx-vp9 -pass 2 -b:v 2000k -maxrate 3000k -speed 1 \ -tile-columns 6 -frame-parallel 1 -threads 1 -auto-alt-ref 1 -lag-in-frames 25 \ -g 600 -r 30 -vf "histeq" -loglevel panic \ -f webm -y $OUT_HQ && echo [`date`] "F...
magicoder
shell
You are tasked with implementing a custom exception class in Python for handling syntax errors in a code reader module. The provided code snippet is a part of the `__init__` method of the `ReaderSyntaxError` class. The class takes several parameters and initializes an instance of the `ReaderSyntaxError` class with an a...
```python class Issue: # Implement the Issue class with the required attributes and an __init__ method def __init__(self, message, location=None, line=None, column=None, locator=None, snippet=None, level=None): self.message = message self.location = location self.line = line self...
magicoder
python
You are tasked with creating a plugin loader for a Python application. The application should be able to dynamically load and execute plugins stored as JSON files in a specified directory. Each plugin JSON file contains information about the plugin, including its name, version, and a list of commands it provides. Your ...
```python import json import glob class PluginManager: def __init__(self, plugins_dir): self.plugins_dir = plugins_dir self.plugins = {} def load_plugins(self): for file_path in glob.iglob(r'{0}/*.json'.format(self.plugins_dir)): try: with open(file_path, 'r...
magicoder
python
You are tasked with implementing a Python function that prints all the permutations of a given string. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. For example, the permutations of the string "abc" are "abc", "acb", "bac", "bca", "cab", and "cba". You...
```python def print_permutations(s): """Print all permutations of the given string. Args: s: A string for which permutations need to be printed. Returns: None """ _print_permutations_helper("", s) def _print_permutations_helper(prefix, remaining): if len(remaining) == 0: print...
magicoder
python