query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a thread-safe storage preference system using Rust's atomic operations. The `AtomicStoragePreference` struct represents a storage preference value that can be updated atomically. The `StoragePreference` enum represents different storage preferences, and the `upgrade` method allows upgra... | ```rust
use std::sync::atomic::{AtomicU8, Ordering};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StoragePreference {
Low,
Medium,
High,
}
pub struct AtomicStoragePreference(AtomicU8);
impl AtomicStoragePreference {
pub fn new(preference: StoragePreference) -> Self {
let value = matc... | magicoder | rust |
You are tasked with creating a Python function that processes file paths and generates the appropriate command to open the file in the correct application. The function should take in the following parameters:
- `server`: An object representing a server connection.
- `secret`: A string representing a secret key for aut... | ```python
import os
def generate_open_command(server, secret, gid, alfred):
dir_path = server.tellStatus(secret, gid, ['dir'])['dir']
file_path = server.getFiles(secret, gid)[0]['path'].encode('utf-8')
if os.path.exists(file_path):
if alfred:
alfred_2_cmd = 'if application "Alfred 2" i... | magicoder | python |
You are tasked with creating a PHP class that interacts with a database table using the CodeIgniter framework. Your goal is to extend the provided `MejaModel` class to include a method that retrieves specific data from the database table.
Your task is to extend the `MejaModel` class with a method called `getMejaByStat... | ```php
namespace App\Models;
use CodeIgniter\Model;
class MejaModel extends Model {
public function getMeja()
{
$query = $this->db->table('tbl_meja');
return $query->get();
}
public function getMejaByStatus($status)
{
$query = $this->db->table('tbl_meja')->where('status',... | magicoder | php |
You are tasked with creating a Python package that converts Jinja2 templates to HTML and PDF files. To achieve this, you need to implement a function that takes a Jinja2 template file, processes it with provided context data, and generates both an HTML file and a PDF file from the rendered template.
Your task is to cr... | ```python
from jinja2 import Environment, FileSystemLoader
import weasyprint
def convert_to_pdf(template_file, context_data):
# Create a Jinja2 environment
env = Environment(loader=FileSystemLoader('/path/to/templates/directory'))
# Load the template
template = env.get_template(template_file)
# R... | magicoder | python |
You are tasked with implementing a function to perform cubic interpolation for a given set of control points. Cubic interpolation is a method of constructing a smooth curve that passes through a set of given points. The function should take in four control points and a parameter `t` within the range [0, 1], and return ... | ```rust
fn cubic_interpolation(p0: f32, p1: f32, p2: f32, p3: f32, t: f32) -> f32 {
let t2 = t * t;
let a0 = p3 - p2 - p0 + p1;
let a1 = p0 - p1 - a0;
let a2 = p2 - p0;
let a3 = p1;
a0 * t * t2 + a1 * t2 + a2 * t + a3
}
```
In the solution, the `cubic_interpolation` function calculates the coe... | magicoder | rust |
You are tasked with implementing a function to calculate the average waiting time for a set of processes in an operating system. The function should take in a list of processes, each represented by their arrival time and burst time, and return the average waiting time for these processes. The waiting time for a process... | ```cpp
#include <iostream>
#include <vector>
// Function to calculate the average waiting time for a set of processes
float calculateAverageWaitingTime(const std::vector<std::pair<int, int>>& processes) {
int n = processes.size();
int totalWaitingTime = 0;
int currentTime = 0;
for (const auto& process... | magicoder | cpp |
You are tasked with implementing a function that simulates the behavior of a tokenizer for a pre-trained transformer model. The tokenizer takes a sentence as input and tokenizes it according to the rules of the model. The provided code snippet shows a test case for the tokenizer using the "bert-base-cased" model. The s... | ```python
from transformers import PretrainedTransformerTokenizer
from typing import List
def tokenize_sentence(sentence: str) -> List[str]:
tokenizer = PretrainedTransformerTokenizer("bert-base-cased")
tokens = tokenizer.tokenize(sentence)
return tokens
```
The `tokenize_sentence` function initializes a ... | magicoder | python |
You are tasked with implementing a Python class to calculate the weighted average of a set of indicators. The class should be able to accept a list of indicators, each with a key, factor, and name, and calculate the weighted average based on a group factor. The weighted average for each indicator is calculated by multi... | ```python
class Indicator:
def __init__(self, key, factor, name):
self.key = key
self.factor = factor
self.name = name
class WeightedAverageCalculator:
def __init__(self, grp_factor):
self.grp_factor = grp_factor
self.indicators = []
def add_indicator(self, indicato... | magicoder | python |
You are working on a data processing project and need to write a Python program to perform some data analysis and output the results to a CSV file. The program should read data from a nested dictionary `content`, perform calculations, and write the results to a CSV file using the `csv` module.
The `content` dictionary... | ```python
import csv
import numpy as np
# Sample data
content = {
'family1': {
1: {
'file1': {
'coeff1': [1, 2, 3],
'coeff2': [4, 5, 6]
},
'file2': {
'coeff1': [7, 8, 9],
'coeff2': [10, 11, 12]
}... | magicoder | python |
You are tasked with implementing a custom PyTorch module for matching and shifting image features. The provided code snippet is a partial implementation of the `matchshifted` module, which takes two input tensors `left` and `right`, and a shift value, and produces a concatenated tensor of shifted left and right feature... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class matchshifted(nn.Module):
def __init__(self):
super(matchshifted, self).__init__()
def forward(self, left, right, shift):
batch, filters, height, width = left.size()
# ... | magicoder | python |
You are tasked with implementing a custom file output format class in Java for a data processing application. The class, `PythonOutputFormat`, extends the `FileOutputFormat` class and is responsible for managing a `PythonStreamer` object and handling multiple tasks.
The `PythonOutputFormat` class has the following att... | ```java
public class PythonOutputFormat extends FileOutputFormat {
private PythonStreamer streamer;
private boolean streamerOpen;
private int taskNumber, numTasks;
public void open(int taskNumber, int numTasks) {
this.taskNumber = taskNumber;
this.numTasks = numTasks;
this.stre... | magicoder | java |
You are working on a Django web application that manages university courses. The application has a module for registering different course modules, and the admin interface is used to manage these modules. The code snippet provided is from the admin.py file of the uicCourse app within the UICHCC repository.
Your task i... | ```python
from typing import List
from github import Github
def get_registered_models(repo_name: str, app_name: str) -> List[str]:
# Authenticate with GitHub using a personal access token
g = Github("YOUR_PERSONAL_ACCESS_TOKEN")
# Get the repository
repo = g.get_repo(f"{repo_name}/{app_name}")
# ... | magicoder | python |
You are tasked with implementing a custom attribute macro in Rust that validates the length of a string input. The macro should be used to annotate a struct field and enforce a specific length constraint on the string value assigned to that field.
Your task is to create a macro `at_arg` that takes two arguments: `posi... | ```rust
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, AttributeArgs, ItemStruct, Meta, NestedMeta};
#[proc_macro_attribute]
pub fn at_arg(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as AttributeArgs);
let input = parse_macro_input!(in... | magicoder | rust |
You are tasked with implementing a C++ class that manages texture atlas data for the SFML library. The provided code snippet is the beginning of the implementation of the `SFMLTextureAtlasData` class. Your task is to complete the implementation of this class by adding necessary member variables and methods to manage te... | ```cpp
#include "SFMLTextureData.h"
DRAGONBONES_NAMESPACE_BEGIN
class SFMLTextureAtlasData
{
private:
// Member variables to store texture atlas data
std::map<std::string, sf::Texture> textures; // Map to store textures with their paths
std::map<std::string, sf::IntRect> textureRegions; // Map to store te... | magicoder | cpp |
You are working as a DevOps engineer for a company that utilizes Docker for containerization and PostgreSQL for its database management system. As part of your responsibilities, you need to create a script to automate the backup process for the PostgreSQL database running in a Docker container. The provided code snippe... | ```bash
#!/bin/bash
# Define the base directory for storing the backup file
BASEDIR="/path/to/backup/directory"
# Execute the database dump and compression within the PostgreSQL Docker container
docker exec -t rdx_postgres_1 pg_dump -U postgres | gzip > "$BASEDIR"/db-backup-"`date +%d-%m-%Y_%H:%M:%S`".sql.gz
```
In ... | magicoder | shell |
You are given a function `double_it` that takes an integer as input and returns double the input value. However, the function seems to be producing unexpected results. Your task is to identify the issue with the given function and fix it to ensure that it correctly doubles the input value.
You need to modify the `doub... | ```python
def double_it(n: int) -> int:
return 2 * n
```
The issue with the original `double_it` function is that it was not correctly doubling the input value. By modifying the function to return `2 * n`, the function now correctly doubles the input value and passes the given assertion. | magicoder | python |
You are tasked with implementing a color utility class in a Swift application. The class should provide predefined color values for various shades of green, each represented as a hexadecimal color code and its corresponding RGB values.
Your task is to create a Swift structure or enumeration to represent the predefined... | ```swift
struct GreenColors {
static let green200 = (red: 166, green: 215, blue: 167)
static let green300 = (red: 129, green: 199, blue: 132)
static let green400 = (red: 102, green: 187, blue: 106)
static let green500 = (red: 76, green: 175, blue: 80)
static let green600 = (red: 67, green: 160, blue... | magicoder | swift |
You are tasked with creating a program to manage product data in a warehouse. The program should be able to read and process a CSV file containing product information and perform various operations on the data. Each row in the CSV file represents a product and contains the following columns: "Producto", "Precio", "Obse... | ```python
import csv
from collections import defaultdict
# Function to read product data from CSV file and store it in a dictionary
def read_product_data(file_path):
product_data = defaultdict(list)
with open(file_path, 'r', newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
... | magicoder | python |
You are tasked with implementing a function to parse and extract information from a given JSON object. The JSON object represents a command packet with various fields. The fields include "command", "devId", "uid", and "t". The "command" field contains a sub-object with "devId", "uid", and "t" fields. The "prefix" field... | ```python
def parse_command_packet(command_packet: dict) -> dict:
extracted_info = {
"devId": command_packet["command"]["devId"],
"uid": command_packet["command"]["uid"],
"t": command_packet["command"]["t"],
"hexByte": command_packet["DP_QUERY_NEW"]["hexByte"],
"prefix": comm... | magicoder | python |
You are tasked with creating a Swift function that processes incoming messages from a WebSocket connection. The function should parse the incoming message, extract specific data, and perform a series of operations based on the extracted information.
You are given a code snippet that represents the beginning of the mes... | ```swift
func processWebSocketMessage(_ message: Any) -> String {
if let text = message as? String,
let data = text.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let operation = json["operation"] as? String,
let operands = js... | magicoder | swift |
You are tasked with implementing a dropout function for a neural network library in Rust, utilizing the `wasm_bindgen` library for WebAssembly integration. The `handle_dropout` function is intended to take a `Tensor` as input and return a modified `Tensor` after applying the dropout operation. The `Tensor` type represe... | ```rust
use wasm_bindgen::prelude::*;
use rand::prelude::*;
use crate::Tensor;
#[wasm_bindgen(js_name = handleDropout)]
pub fn handle_dropout(input: &Tensor, dropout_rate: f64) -> Tensor {
let mut rng = thread_rng();
let mut output = input.clone();
for element in output.iter_mut() {
if rng.gen::<... | magicoder | rust |
You are tasked with implementing a program that simulates a simple banking system. The program should support the following operations: creating a new bank account, depositing funds into an account, withdrawing funds from an account, and checking the balance of an account. Each account should have a unique account numb... | ```python
class BankAccount:
account_number_counter = 1000
def __init__(self, account_holder_name, account_type):
BankAccount.account_number_counter += 1
self.account_number = BankAccount.account_number_counter
self.account_holder_name = account_holder_name
self.account_type = a... | magicoder | python |
You are tasked with implementing a session management system for an online MBA (Master of Business Administration) program. The system should allow users to log in, view their course information, and log out. The user's session should be maintained throughout their interaction with the system.
You are provided with a ... | ```php
// Start the session
session_start();
class MBAController extends Controller
{
// MBA Code
public function mba(){
// Check if the user is logged in
if(isset($_SESSION['user_id'])){
// User is logged in, retrieve and display course information
$courseInfo = $this-... | magicoder | php |
You are tasked with implementing a simple dependency injection container in Swift. The container should be able to register dependencies and resolve them when requested.
Your task is to create a DependencyContainer class with the following requirements:
1. The container should be able to register dependencies using a ... | ```swift
class DependencyContainer {
private var dependencies: [String: () -> Any] = [:]
func register<T>(_ type: T.Type, _ dependency: @escaping () -> T) {
let key = String(describing: type)
dependencies[key] = dependency
}
func resolve<T>(_ type: T.Type) throws -> T {
let key... | magicoder | swift |
You are working on a computer graphics project and need to implement a function to render orthographic projections of 3D objects. The function `render_prt_ortho` takes several parameters and is responsible for rendering the orthographic projections of a 3D object onto a 2D plane. Your task is to complete the implementa... | ```python
from pathlib import Path
import os
def render_prt_ortho(out_path, obj_uv_filespath, prep_filespath, shs, rndr, rndr_uv, im_size, angl_step=4, n_light=1, pitch=[0]):
geo_path = Path(os.path.join(out_path, 'GEO', 'OBJ', obj_uv_filespath.split('/')[-1]))
param_path = Path(os.path.join(out_path, 'PARAM',... | magicoder | python |
You are tasked with implementing a Python function that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The player's position in the grid is represented by (x, y) coordinates, where (0, 0) is the top-left corner. The gri... | ```python
def play_game(n, obstacles, treasures):
grid = [[0] * n for _ in range(n)]
for x, y in obstacles:
grid[y][x] = -1 # Mark obstacle positions as -1
for x, y in treasures:
grid[y][x] = 1 # Mark treasure positions as 1
def is_valid_move(x, y):
return 0 <= x < n and 0 <= ... | magicoder | python |
You are tasked with implementing a queue naming strategy interface for a messaging system. The interface, `IQueueNamingStrategy`, defines two methods for generating queue names based on the message type or the message itself. The `GetName` method takes either a `Message` object or a `Type` object as input and returns t... | ```csharp
using System;
public class Message
{
public string Id { get; set; }
public Type MessageType { get; set; }
}
public class CustomQueueNamingStrategy : IQueueNamingStrategy
{
public string GetName(Message message)
{
if (message == null)
{
throw new ArgumentNullExcept... | magicoder | csharp |
You are tasked with implementing a program that converts a given logical expression from an OR formulation to an AND formulation. The logical expression is represented as a string containing variables, logical operators (AND, OR), and parentheses. The program should take the input logical expression in OR formulation a... | ```python
def convert_to_and_formulation(logical_expression: str) -> str:
# Stack to keep track of opening parentheses
stack = []
# List to store the converted expression
converted_expression = []
for char in logical_expression:
if char == '(':
stack.append(len(converted_express... | magicoder | python |
You are working as a DevOps engineer for a company that is deploying a new application using Docker containers. As part of the deployment process, you need to automate the setup of a MySQL database within a Docker container. The company has provided you with a bash script that pulls the latest version of the MySQL serv... | To achieve the required tasks, you can use the following bash command to connect to the running MySQL container and execute the SQL script:
```bash
docker exec -i fume mysql -uroot -ppassword < FUME-DB-Create.sql
```
Explanation:
- `docker exec -i fume`: This command executes a command within the running "fume" conta... | magicoder | shell |
You are tasked with creating a RESTful API for managing consume types in a financial application. The consume types are represented by the `ConsumeTypeEntity` class, and you need to implement the necessary endpoints using Spring Boot and the Spring Web framework.
Your task is to create a Spring Boot controller that ha... | ```java
import org.springframework.web.bind.annotation.*;
import com.alyer.modules.consume_type.entity.ConsumeTypeEntity;
@RestController
@RequestMapping("/consume-types")
public class ConsumeTypeController {
// Assuming consumeTypeService is a service class handling the business logic
@GetMapping
publi... | magicoder | java |
You are tasked with implementing a function to transpose a given matrix. Transposing a matrix involves converting its rows into columns and vice versa. Your task is to write a function `transpose_matrix(matrix)` that takes a 2D matrix as input and returns its transposed form.
For example, given the input matrix:
```
m... | ```python
def transpose_matrix(matrix):
transposed_matrix = []
for i in range(len(matrix[0])):
transposed_matrix.append([row[i] for row in matrix])
return transposed_matrix
# Test the function with the given example
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed_matrix = transp... | magicoder | python |
You are given a code snippet written in C++ that is intended to output either "YES" or "NO" based on certain conditions. However, the code is incomplete and contains a syntax error. Your task is to identify the error and fix the code to ensure that it behaves as intended.
The original code snippet is as follows:
```cp... | The issue with the given code is that there are extra closing braces `}` at the beginning, which causes a syntax error. The corrected code should be as follows:
```cpp
#include <iostream>
int main() {
std::cout << "YES";
return 0;
}
```
The corrected code snippet includes the necessary `#include <iostream>` ... | magicoder | cpp |
You are tasked with creating a Vue component that manages user accounts. The component should render the account information and provide functionality to update and delete user accounts. You are provided with a code snippet that sets up a Vue component test using Jest and Vuex. Your task is to implement the Vue compone... | ```javascript
// Vue component 'Account'
<template>
<div>
<div v-if="user">
<h2>Account Information</h2>
<p>Name: {{ user.name }}</p>
<p>Email: {{ user.email }}</p>
<!-- Other account details -->
<button @click="updateAccount">Update Account</button>
<button @click="deleteAccou... | magicoder | javascript |
You are tasked with implementing a class that represents a generator in a custom data processing library. The class should support multiplication operations with other generators. The provided code snippet shows two methods, `mul_generators` and `rmul_generators`, which are used to multiply two generators together. The... | ```python
class Generator:
def __init__(self):
# Initialize the generator
def mul_generators(self, other):
# Multiply the current generator with the other generator
return Apply(mul, self, as_tohu_generator(other))
def rmul_generators(self, other):
# Multiply the other gene... | magicoder | python |
You are tasked with creating a program that analyzes the frequency of words in a given text. Your program should take a string of text as input and output the frequency of each word in the text. For the purpose of this problem, a word is defined as a sequence of alphanumeric characters (letters and digits) separated by... | ```python
import re
def word_frequency(text):
# Convert the entire text to lowercase
text = text.lower()
# Use regular expression to find all words in the text
words = re.findall(r'\w+', text)
# Create a dictionary to store word frequencies
frequency = {}
# Count the frequenc... | magicoder | python |
You are given a set of coordinates representing atoms in a molecular structure. Each line of the input represents an atom and consists of the atom's symbol (one or two characters) followed by its x, y, and z coordinates. Your task is to write a program to calculate the distance between two specified atoms in the molecu... | def calculate_distance(coordinates, atom1, atom2):
atom_coords = {}
for coord in coordinates:
atom, x, y, z = coord.split()
atom_coords[atom] = (float(x), float(y), float(z))
if atom1 not in atom_coords or atom2 not in atom_coords:
return "Invalid atom symbol"
x1, y1, z1 = ... | magicoder | python |
You are tasked with implementing a custom hashing algorithm for a class in C#. The class has a method that returns a boolean value and an overridden `GetHashCode` method. Your goal is to create a custom hashing algorithm that generates a unique hash code for each instance of the class based on its properties and behavi... | ```csharp
public class CustomClass
{
public bool CustomMethod()
{
// Your implementation here
// Example: Consider a property or behavior that influences the hash code
// For instance, a property named "Value" affecting the hash code
// You can use the value of "Value" to influen... | magicoder | csharp |
You are given a 2D grid representing a map of a forest. The grid is composed of open squares (.) and trees (#). You are also provided with a toboggan rule engine that specifies the slope or pattern for toboggan movement. The toboggan can move through the grid in a specific pattern, and you need to calculate the number ... | ```java
public long calculateEncounteredTrees(char[][] grid, ITobogganRuleEngine tobogganRuleEngine) {
int width = grid[0].length;
int height = grid.length;
int x = 0;
int y = 0;
long treesEncountered = 0;
while (y < height) {
if (grid[y][x % width] == '#') {
treesEncountere... | magicoder | java |
You are tasked with creating a Python function to analyze the distribution of a specific feature within a dataset's metadata. The metadata is stored in a dictionary format, and each key-value pair represents a feature and its corresponding data. Your function should take the metadata dictionary and a feature name as in... | ```python
import matplotlib.pyplot as plt
def visualize_feature_distribution(metadata: dict, feature_name: str) -> None:
if feature_name in metadata:
data = metadata[feature_name]
plt.hist(data, bins=10, color='skyblue', edgecolor='black')
plt.title(f"Distribution of {feature_name}")
... | magicoder | python |
You are tasked with developing a build configuration system for a software project. The build configuration system is responsible for setting various options that control the build process. Each option can be either enabled or disabled, and the final build configuration is determined by the combination of these options... | ```python
def parse_build_configuration(config_code):
config_options = {}
lines = config_code.strip().split('\n')
for line in lines:
option, value = line.split('=')
config_options[option.strip()] = value.strip() == 'true'
return config_options
``` | magicoder | python |
You are given a binary tree in the form of a string representing its level order traversal. Each node in the tree has an integer value. You need to write a program to find the number of paths in the tree that sum up to a given target value.
The input string represents the level order traversal of the binary tree, wher... | ```python
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def deserialize(data):
if data == "[]":
return None
nodes = [None if val == "null" else TreeNode(int(val)) for val in data.strip("[]").split(",")]
children = nodes[::-1]
... | magicoder | python |
You are tasked with implementing a custom modifier system for a SwiftUI-like framework. The provided code snippet defines an extension for the `View` protocol, allowing the creation of custom modifiers. The `modifier` function takes a modifier as input and returns a `ModifiedContent` instance, which combines the origin... | ```swift
// Define a generic Modifier protocol
protocol Modifier {
associatedtype Body
func body(content: Self.Content) -> Self.Body
}
// Implement a custom modifier to change the background color of a view
struct BackgroundColorModifier: Modifier {
let color: Color
func body(content: ModifiedCont... | magicoder | swift |
You are tasked with implementing a function that can parse a Django migration file and extract the names of all the models being created. A Django migration file is a Python file that contains a series of operations to apply to the database schema, including creating, altering, or deleting models. Each model creation o... | ```python
import ast
def extract_model_names(migration_file_path):
with open(migration_file_path, 'r') as file:
content = file.read()
tree = ast.parse(content)
model_names = []
for node in ast.walk(tree):
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attri... | magicoder | python |
You are tasked with creating a Python class that represents a user in a web application. The user class should have attributes for the user's name, email, password, and registration date. Additionally, the class should include a method to hash the user's password using the SHA-256 algorithm. You are provided with a cod... | ```python
# -*- coding: future_fstrings -*-
from app.database import Model, Column, SurrogatePK, db, relationship
import datetime as dt
import hashlib
class User(Model):
__tablename__ = 'users'
id = Column(SurrogatePK, primary_key=True)
name = Column(db.String(80), nullable=False)
email = Column(db.Str... | magicoder | python |
You are tasked with implementing a memory management system for a custom data structure called `IntBlockPool`. The `IntBlockPool` is used to manage a pool of integer buffers and is responsible for allocating and resetting memory blocks. Your task is to implement the `reset` method for the `IntBlockPool` struct, which r... | ```rust
impl IntBlockPool {
/// Resets the pool to its initial state reusing the first buffer.
pub fn reset(&mut self, zero_fill_buffers: bool, reuse_first: bool) {
if self.buffer_upto > -1 {
if zero_fill_buffers {
for buffer in &mut self.buffers {
for val... | magicoder | rust |
You are tasked with implementing a Python class for training machine learning models. The class includes functionality for distributed training across multiple GPUs using PyTorch's DistributedDataParallel (DDP) module. Additionally, the class provides an option for verbose output during training.
The provided code sni... | ```python
def train(self):
if self.args.multiGPU and self.args.distributed:
# Distributed training with DDP
self.model = DDP(self.model, device_ids=[self.args.gpu], find_unused_parameters=True)
# Training logic using the initialized model
# Example:
for epoch in range(self.num_epochs):
... | magicoder | python |
You are tasked with implementing a custom layout for a collection view in an iOS app. The layout, called WaterfallLayout, is designed to display items in a waterfall-like arrangement, where each column contains items of varying heights. The provided code snippet is a part of the prepare() method within the WaterfallLay... | ```swift
extension WaterfallLayout {
override func prepare() {
super.prepare()
let itemCount = collectionView!.numberOfItems(inSection: 0)
let cols = dataSource?.numberOfColsInWaterfallLayout?(self) ?? 2
let itemWidth = (collectionView!.bounds.width - self.sectionInset.... | magicoder | swift |
You are tasked with implementing a constrained conjugate gradient algorithm for solving a specific optimization problem in the context of a fluid dynamics simulation. The problem involves finding the optimal pressure distribution in a fluid system subject to certain constraints. The given code snippet demonstrates the ... | ```python
import numpy as np
import ccg_with_restart # Assuming the constrained conjugate gradient library is available
# Define the objective function and its gradient
def dual_objective(pressure, gradient=False):
# Implementation of the dual objective function
# If gradient=True, return the gradient of the ... | magicoder | python |
You are tasked with simulating a granular synthesis process using Python. Granular synthesis is a technique used in electronic music production to create complex sounds by playing back small, overlapping snippets of audio called grains. Your goal is to implement a Python class that models a granular synthesis engine.
... | ```python
import random
class GranularSynthesis:
def __init__(self):
self.parameters = {}
def set_value(self, key, value):
self.parameters[key] = value
def calculate_density(self):
if "/density" in self.parameters:
density = self.parameters["/density"]
dens... | magicoder | python |
You are working on a project that involves creating a game environment with traversable nodes. Each node has a coordinate, vector, movement cost, slope status, and a list of adjacent cardinal nodes. Your task is to implement a method that constructs a new traversable node with modified coordinates and the same vector, ... | ```swift
func createAdjacentNode(coordinate: Coordinate) -> TraversableNode {
var cardinals: [TraversableNode] = []
for cardinal in self.cardinals {
cardinals.append(cardinal)
}
return TraversableNode(coordinate: Coordinate(x: coordinate.x, y: self.coordinate.y, z: coordinate.z), vector: self.ve... | magicoder | swift |
You are tasked with creating a Swift function that processes attributed text to identify and extract URLs. Your function should take an attributed string as input and return an array of URLs found within the attributed text.
Your function signature should be:
```swift
func extractURLs(from attributedText: NSAttributed... | ```swift
import Foundation
func extractURLs(from attributedText: NSAttributedString) -> [URL] {
var urls: [URL] = []
attributedText.enumerateAttribute(.link, in: NSRange(location: 0, length: attributedText.length), options: []) { value, range, _ in
if let url = value as? URL {
urls.app... | magicoder | swift |
You are tasked with creating a Python function that retrieves information about a GitHub repository using the GitHub API. The function should take the repository owner's username and the repository name as input and return the number of stars the repository has received. You are provided with a code snippet that initia... | ```python
import requests
API_TOKEN = 'PUT_TOKEN_HERE'
URL_BASE = 'https://api.github.com/repos/'
def get_repo_stars(owner: str, repo_name: str) -> int:
url = URL_BASE + owner + '/' + repo_name
headers = {'Authorization': 'token ' + API_TOKEN}
response = requests.get(url, headers=headers)
if response.... | magicoder | python |
You are tasked with implementing a caching mechanism for storing statistics related to champion performance in a video game. The provided code snippet is a part of a method that stores the statistics in the cache. The `key` is generated by formatting the class name, patch, and elo, and then the statistics item is store... | ```python
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key: str) -> Any:
if key in self.cache:
# Move the accessed key to the end to mark it as most recently used
... | magicoder | python |
You are tasked with implementing a thread tracking system in Rust. The given code snippet is a part of a struct definition that includes fields for thread tracking. The `#[cfg(feature = "track_threads")]` attribute indicates that this code is conditionally compiled based on the presence of a feature named "track_thread... | ```rust
use std::sync::{Arc, Mutex};
use std::cell::Cell;
use std::sync::atomic::{AtomicUsize, AtomicU32, Ordering};
use std::marker::PhantomData;
const LOCAL_PRESENT: u32 = 0;
thread_local! {
static THREAD_ID: (usize) = {
// Generate a unique thread ID
// For example, using a counter or a random ... | magicoder | rust |
You are tasked with implementing a file monitoring system in Python. Your task is to create a class that monitors a directory for file changes and updates. The class should have a method to continuously loop and check for file updates at a specified interval. Additionally, it should provide an option for asynchronous p... | ```python
import os
import time
import threading
class FileMonitor:
def __init__(self, directory):
self.directory = directory
self.files_map = {}
def update_files(self):
self.files_map = {fid: file for fid, file in enumerate(os.listdir(self.directory))}
def readfile(self, file):
... | magicoder | python |
You are tasked with creating a Python programming problem related to database migrations in Django.
Your task is to create a function that simulates the process of applying database migrations to a Django project. In Django, database migrations are used to manage changes to the database schema over time. Each migratio... | ```python
from typing import List, Tuple, Dict
def apply_migrations(operations: List[Tuple[str, str, str, str]]) -> Dict[str, List[Tuple[str, str]]]:
schema = {}
for operation in operations:
operation_type, model_name, field_name, field_type = operation
if operation_type == 'AddField':
... | magicoder | python |
You are tasked with creating a Python function that simulates a simplified version of a message queue system using asyncio. The function should establish a connection to the message queue server, publish a message to a specified topic, and then subscribe to the same topic to receive the published message. You are provi... | ```python
import asyncio
from stan.aio.client import Client as Stan
from nats.aio.client import Client as Nats
async def simulate_message_queue(stan_server: str, client_id: str, topic: str, message: str) -> str:
nc = Nats()
await nc.connect(io_loop=asyncio.get_event_loop(), servers=[stan_server])
sc = Sta... | magicoder | python |
You are tasked with creating a script that securely retrieves a GitHub token from a specified file path and uses it to perform a specific action. The GitHub token is stored in a file, and the script needs to read the token from the file and utilize it for authentication purposes. Your task is to write a bash script tha... | ```bash
#!/bin/bash
# Check if the file path for the GitHub token is provided as an argument
if [ -z "$1" ]; then
echo "Error: File path for GitHub token not provided"
exit 1
fi
# Check if the file exists and is readable
if [ ! -f "$1" ] || [ ! -r "$1" ]; then
echo "Error: Unable to read the GitHub token file"
... | magicoder | shell |
You are given a series of sets, each containing distinct integers. Your task is to write a function that takes these sets as input and returns the intersection of all the sets. The intersection of sets is the set of elements that are common to all the sets.
For example, given the following sets:
```
{2, 3}
{4}
{3, 4}
... | ```python
from typing import List, Set
def findIntersection(sets: List[Set[int]]) -> Set[int]:
if not sets:
return set()
intersection = sets[0]
for s in sets[1:]:
intersection = intersection.intersection(s)
return intersection
``` | magicoder | python |
You are tasked with creating a Python function that extracts the version number from a given package's `__init__.py` file and appends a version identifier based on the commit count if the version ends with 'a', 'b', or 'rc'. The function should handle various scenarios and provide the final version number.
Write a Pyt... | ```python
import re
import subprocess
def process_version(package_name: str, init_file_path: str) -> str:
with open(init_file_path) as f:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1)
if version.endswith(('a', 'b', 'rc')):
try:
comm... | magicoder | python |
You are tasked with implementing a custom test framework for a C++ project. The framework should be able to handle test cases and provide a clear output of the test results. Your task is to create a class `TestFramework` with the following functionalities:
1. The class should have a method `addTest` that takes a test ... | ```cpp
// TestFramework.cpp
#include "TestFramework.h"
#include <iostream>
void TestFramework::addTest(std::function<void()> testFunction) {
testCases.push_back(testFunction);
}
void TestFramework::runTests() {
for (const auto& test : testCases) {
TestResult result;
try {
test();
... | magicoder | cpp |
You are working on a project that involves querying a graph database using the Gremlin query language. The code snippet provided is part of a C# library that interfaces with the graph database. The library contains methods for building and executing Gremlin queries.
Your task is to implement a method that filters node... | ```csharp
public static IGremlinNodeQuery<TNode> BothV<TNode>(this IGremlinQuery query, IEnumerable<Filter> filters, StringComparison comparison = StringComparison.OrdinalIgnoreCase)
{
var newQuery = query.AddFilterBlock(bothV, filters, comparison);
return new GremlinNodeEnumerable<TNode>(newQuery);
}
```
In t... | magicoder | csharp |
You are tasked with implementing a Python class that filters and organizes images based on their associated labels. The class, named `ImageDataset`, has the following attributes and methods:
Attributes:
- `imgs_all`: A list of tuples, where each tuple contains an image and its corresponding label.
- `n_class`: An inte... | ```python
class ImageDataset:
def __init__(self, imgs_all, n_class, num_perclass):
self.imgs_all = imgs_all
self.n_class = n_class
self.num_perclass = num_perclass
self.imgs_all.reverse() # Reverse the order of imgs_all
cnt = [0 for _ in range(self.n_class)] # Initialize c... | magicoder | python |
You are working for a typography company that is developing a font correction tool. The tool is designed to apply specific fixes to fonts for web usage. Your task is to implement a function that applies these fixes to a given font.
You are provided with a Python code snippet that demonstrates the usage of the font cor... | ```python
def correct_font_for_web(font, unhinted, family_name):
apply_web_specific_fixes(font, unhinted, family_name)
temporary_touchups.apply_temporary_fixes(font, is_for_web=True)
temporary_touchups.update_version_and_revision(font)
font.save(target_font_name)
return font
```
In the solution, the... | magicoder | python |
You are tasked with creating a Python function that processes a configuration dictionary based on a given module and request configuration. The function should handle different modules and their specific requirements. The configuration dictionary contains various parameters, and the function should modify it based on t... | ```python
import os
def process_configuration(module: str, request_config: dict) -> str:
if module == "upload":
detect_utils.check_config(request_config, required_arguments=['file', 'param1', 'param2'])
if not os.path.isabs(request_config['file']):
request_config["file"] = os.path.join(... | magicoder | python |
You are tasked with implementing a class that manages resource bundle information for a refactoring tool. The class should handle the setting of an accessor package and the determination of a resource bundle name based on a given class reference.
You are provided with a code snippet that demonstrates part of the funct... | ```java
import org.eclipse.jdt.core.Signature;
public class RefactoringResourceManager {
private String fAccessorPackage;
private String fResourceBundleName;
private static final String PROPERTY_FILE_EXT = ".properties";
public void setAccessorPackage(String accessorPack) {
if (accessorPack !=... | magicoder | java |
You are working on a program to manage a library's collection of books. The program has a list of authors' names, and you need to sort them alphabetically by their last names. Each author's name is in the format "First Name Last Name". You are required to write a function that takes a list of author names and returns t... | ```python
def sort_authors_by_last_name(authors):
sorted_authors = sorted(authors, key=lambda x: x.split()[-1])
return sorted_authors
# Test the function
author_names = ["John Smith", "Alice Johnson", "David Brown", "Emily Davis"]
sorted_authors_by_last_name = sort_authors_by_last_name(author_names)
print(sort... | magicoder | python |
You are tasked with creating a program to manage the delivery details for a logistics company. The program should allow users to input and store information about various deliveries, such as the delivery ID, recipient's name, delivery address, and delivery status. Additionally, the program should provide functionality ... | ```python
class DeliveryDetails:
def __init__(self, deliveryID, recipientName, deliveryAddress, deliveryStatus):
self.deliveryID = deliveryID
self.recipientName = recipientName
self.deliveryAddress = deliveryAddress
self.deliveryStatus = deliveryStatus
def update_status(self, ne... | magicoder | python |
You are tasked with implementing a function that will parse a given HTML form and extract all the input fields along with their attributes. The function should take the HTML form as input and return a dictionary where the keys are the input field names and the values are dictionaries containing the attributes of each i... | ```python
import re
def parse_html_form(html_form: str) -> dict:
input_fields = re.findall(r'<input.*?>', html_form)
parsed_fields = {}
for field in input_fields:
attributes = re.findall(r'(\w+)="([^"]*)"', field)
field_dict = {attr[0]: attr[1] for attr in attributes}
field_type = f... | magicoder | python |
You are tasked with creating a Python class that extends the functionality of a basic word counter. The class should be named `AdvancedWORC` and should inherit from the `BasicWORC` class provided in the `basicworc` module. The `BasicWORC` class has a method `count_words` that takes a string as input and returns the cou... | ```python
from collections import Counter
from .basicworc import BasicWORC
class AdvancedWORC(BasicWORC):
def top_words(self, n):
word_counts = self.count_words(self.input_string)
sorted_word_counts = sorted(word_counts.items(), key=lambda x: (-x[1], x[0]))
return [word for word, _ in sorte... | magicoder | python |
You are tasked with implementing a method to create an issue using a REST client in a Java application. The provided code snippet demonstrates the setup for this task. The `IssueLoader` class is responsible for creating issues using the `Client` instance, which is initialized with a server and an API key. However, the ... | ```java
public void create(String issueDetails) {
// Assuming the issue creation endpoint is "/create/issue" and the server supports POST requests
String endpoint = "/create/issue";
String requestBody = issueDetails; // Assuming issueDetails is the JSON payload for creating an issue
// Construct the re... | magicoder | java |
You are tasked with implementing a function to validate and process coupon data for a coupon management system. The system receives coupon data in the form of an object with various properties. Your task is to create a function that takes this coupon data as input and performs the following tasks:
1. Validates the inpu... | ```javascript
function processCouponData(couponData) {
// Validate input data
if (
!couponData.coupon_name ||
!couponData.price ||
!couponData.old_price ||
!couponData.new_price ||
!couponData.description ||
!couponData.category ||
!couponData.coupon_type
) {
return null;
}
//... | magicoder | javascript |
You are working at a company where employees greet each other by performing "salutes". The company's office layout is represented by a one-dimensional hallway, where each position can be occupied by an employee facing either left ("<") or right (">"). When two employees meet, they perform a salute by raising their hand... | ```python
def calculate_salutes(hallway):
crosses = 0
for i, char in enumerate(hallway):
if char == ">":
crosses += hallway[i:].count("<")
salutes = crosses * 2
return salutes
# Test the function with the provided example
hallway = ">----<---->"
print(calculate_salutes(hallway)) # ... | magicoder | python |
You are tasked with creating a program to simulate a traffic light system. The traffic light should cycle through the following states: green, yellow, and red, with specific durations for each state. Your program should use a loop to iterate through the states and simulate the appropriate time delays for each state.
Y... | ```python
import time
# Define the durations for each state
green_duration = 10
yellow_duration = 3
red_duration = 8
# Define the total number of iterations
total_iterations = green_duration + yellow_duration + red_duration
# Simulate the traffic light using the given code snippet
for _ in range(total_iterations):
... | magicoder | python |
You are tasked with implementing a task runner utility that can execute a series of tasks in a specific order. Each task is represented by an object with properties `id`, `title`, `genFunc`, and `deployFunc`. The `id` is a unique identifier for the task, `title` is a descriptive title for the task, `genFunc` is a funct... | ```javascript
function executeTasks(tasks) {
return tasks.reduce((prevTask, currentTask) => {
return prevTask.then(() => {
console.log(`Executing task: ${currentTask.title}`);
return currentTask.genFunc().then(() => {
console.log(`Generated documentation for task: ${currentTask.title}`);
... | magicoder | javascript |
You are given a string `s`. Write a function `longestPalindrome` to find the longest palindromic substring in `s`. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. For example, "level" and "radar" are palindromes.
The function signature is:
```python
def... | ```python
def longestPalindrome(s: str) -> str:
if len(s) < 2 or s == s[::-1]:
return s
start, max_len = 0, 0
for i in range(len(s)):
odd_len = s[i - max_len - 1:i + 1]
even_len = s[i - max_len:i + 1]
if i - max_len - 1 >= 0 and odd_len == odd_len[::-1]:
start ... | magicoder | python |
You are tasked with implementing a Python class that represents a worksheet and provides methods for accessing its data. The class should have the following functionalities:
1. A method `worksheets` that returns a list containing the worksheet itself.
2. A method `get_all_values` that returns the data contained within... | ```python
# Create a Worksheet object with sample data
worksheet_data = [
['Name', 'Age', 'Gender'],
['Alice', 25, 'Female'],
['Bob', 30, 'Male'],
['Eve', 28, 'Female']
]
worksheet = Worksheet(worksheet_data)
# Test the worksheets method
worksheets_list = worksheet.worksheets()
print(worksheets_list) ... | magicoder | python |
You are tasked with creating a command-line utility that processes template files based on user-defined variables. The utility should accept command-line arguments to specify the source directory, filename prefix, and template variable. Additionally, it should support a debug mode to enable additional logging and debug... | ```python
import os
import argparse
def process_template_files(srcdir, prefix, var, debug):
if debug:
print("Debug: Processing started")
for filename in os.listdir(srcdir):
if filename.endswith(".template"): # Assuming template files have .template extension
with open(os.path.join... | magicoder | python |
You are tasked with creating a Python function that processes a list of file paths and extracts specific information from each path. The function should take in a list of file paths and return a dictionary containing the index of each path, the folder name, and the file extension.
The file paths are generated using th... | ```python
import os
def process_file_paths(file_paths):
result = {}
for idx, path in enumerate(file_paths):
folder_name = os.path.basename(path).split('.')[0]
extension = os.path.basename(path).split('.')[1]
result[idx] = {'folder': folder_name, 'extension': extension}
return result... | magicoder | python |
You are tasked with implementing a class that represents a collection of observable names. An observable name is a name that can be monitored for changes. Your task is to create a class `ObservableNames` that extends the `collections.namedtuple` class and adds the functionality to monitor changes to the names in the co... | ```python
import collections
class ObservableNames(collections.namedtuple('ObservableNames', [])):
def __new__(cls, *args, **kwargs):
return super().__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
super().__init__()
self.observers = []
def add_observer(self, ob... | magicoder | python |
You are working on a project that involves low-level memory manipulation in Swift. You need to understand and utilize pointer conversions to achieve the desired functionality. In Swift, pointers are used to interact with C APIs or perform low-level memory operations. The code snippet provided demonstrates the usage of ... | Pointer conversion is a crucial aspect of low-level memory manipulation in Swift. It involves converting one type of pointer to another, allowing for interoperability with C APIs and enabling direct memory access.
In the given code snippet, the `takesMutableRawPointer` and `takesConstPointer` functions are called with... | magicoder | c |
You are working on a machine learning project and need to implement a log probability calculation function for a statistical model. The function `log_probability` takes two parameters: `input`, which is a tensor representing input data, and `target`, which is a tensor representing target values. The function is a metho... | ```python
import math
class LogProbabilityCalculator:
def __init__(self, log_noise):
self.log_noise = log_noise
def log_probability(self, input, target):
res = -0.5 * ((target - input.mean()) ** 2 + input.var()) / self.log_noise.exp()
res += -0.5 * self.log_noise - 0.5 * math.log(2 * m... | magicoder | python |
You are tasked with implementing a function to shuffle an array using the Fisher-Yates shuffle algorithm. The Fisher-Yates shuffle is an algorithm for generating a random permutation of a finite sequence. The algorithm produces an unbiased permutation: every permutation is equally likely. The algorithm effectively puts... | ```rust
fn fisher_yates_shuffle<T>(arr: &mut [T]) {
use fastrand; // Assuming the use of a random number generator library like `fastrand`
for i in (1..arr.len()).rev() {
let j = fastrand::usize(0..=i);
arr.swap(i, j);
}
}
```
The `fisher_yates_shuffle` function iterates through the input ... | magicoder | rust |
You are tasked with creating a Discord bot that can perform various tasks based on user input. The bot should be able to count the number of messages sent by a specific user within the last 100 messages in a channel, execute a sleep command for a specified duration, and search for a URL based on user input.
Your task ... | ```python
# Import necessary libraries
import discord
import asyncio
# Initialize the Discord client
client = discord.Client()
# Event handler for bot's on_message event
@client.event
async def on_message(message):
if message.content.startswith('~test'):
counter = 0
tmp = await client.send_message... | magicoder | python |
You are tasked with creating a web application that displays different pages based on the URL path. The application uses the Blade templating engine, and the code snippet provided is from a file named `life.blade.php` located in the `resources/views/pages` directory. The content of the file includes an HTML `<h2>` tag ... | ```php
function getBladeTemplate($urlPath) {
switch ($urlPath) {
case "/":
return "home.blade.php";
case "/about":
return "about.blade.php";
case "/contact":
return "contact.blade.php";
case "/life":
return "life.blade.php";
def... | magicoder | php |
You are tasked with implementing a class method for a Django model that handles bulk actions on a queryset of instances. The method should delete the queryset instances from the database and then perform a specific action on each individual instance.
You are given the following code snippet as a starting point:
```py... | ```python
@classmethod
def bulk_action(cls, info, queryset):
instances = list(queryset)
errors = []
for instance in instances:
if instance.requestor is not None:
# Perform action to send notification to requestor
try:
send_notification(instance.requestor, f"In... | magicoder | python |
You are tasked with creating a Python program that reads data from a file, performs Fast Fourier Transform (FFT) on the data, and then plots the FFT results. The input data is stored in a file named "fft-O0-sample.txt" and is formatted as follows:
```
0.0 1.0
0.1 2.0
0.2 3.0
...
```
Each line contains two space-separat... | ```python
import numpy as np
import matplotlib.pyplot as plt
# Load Data
with open('../data/fft-O0-sample.txt', 'r') as f:
data = np.loadtxt(f)
time = data[:, 0] # Extract time values
amplitude = data[:, 1] # Extract amplitude values
# Perform FFT
sampling_rate = 1 / (time[1] - time[0]) # Calculate the sampli... | magicoder | python |
You are tasked with implementing a simple state machine for a traffic signal system. The system should have three states: "Signal light off", "Red signal", and "Green signal". The traffic signal should transition from "Signal light off" to "Red signal" when a car is detected, and from "Red signal" to "Green signal" aft... | ```cpp
#include <iostream>
#include <string>
class Event {
public:
Event(const std::string& name) : name_(name) {}
std::string name() const { return name_; }
private:
std::string name_;
};
class State {
public:
State(const std::string& name) : name_(name) {}
std::string name() const { return name_... | magicoder | cpp |
You are tasked with simulating a predator-prey model using the Lotka-Volterra equations. The Lotka-Volterra model describes the dynamics of biological systems in which two species interact, one as a predator and the other as prey. The model is governed by the following differential equations:
\[ \frac{dP}{dt} = aP - b... | ```python
# Define the Lotka-Volterra equations
def lotka_volterra(prey, predator, a, b, c, d):
dP_dt = a * prey - b * prey * predator
dC_dt = -c * predator + d * prey * predator
return dP_dt, dC_dt
# Get user input for initial values and number of generations
A = float(input("Enter the value of A: ")) # ... | magicoder | python |
You are tasked with creating a Rust library for interfacing with a DHT22 temperature and humidity sensor. The provided code snippet is a part of the library implementation and shows the function `attach` being defined. Your task is to complete the implementation of the `attach` function to enable the library to work wi... | ```rust
mod dht22_pt;
use dht22_pt::DHT22;
use std::rc::Rc;
pub fn attach(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) {
// Initialize the DHT22 sensor
let dht22 = DHT22::new();
// Attempt to establish communication with the sensor
match dht22.init() {
Ok(_) => {
... | magicoder | rust |
You are tasked with implementing a custom comparison function for a class called `FullscreenQuad`. The `FullscreenQuad` class has a member function `bool operator<(const FullscreenQuad& other) const` which is used to compare two `FullscreenQuad` objects. The comparison function should be implemented in such a way that ... | ```cpp
class FullscreenQuad {
public:
// Member variables and other member functions are not shown for brevity
bool operator<(const FullscreenQuad& other) const {
// Assuming a specific comparison criterion based on member variables x and y
if (this->x < other.x) {
return true;
... | magicoder | cpp |
You are working on a build optimization tool for a web development project. The provided code snippet is a part of the build process and includes the `preprocess` function, which is responsible for preprocessing the project's source files before the actual build. The function imports and utilizes various modules such a... | ```typescript
import { optimization } from './optimization';
import { deepLinking, deepLinkingUpdate } from './deep-linking';
import { bundleCoreComponents } from './core/bundle-components';
// New function for image optimization
function optimizeImages(context: BuildContext): Promise<void> {
return new Promise((res... | magicoder | typescript |
You are tasked with creating a Python class for managing podcasts. The class should have methods for adding new podcasts, updating existing podcasts, and retrieving a list of podcasts based on certain criteria. Your task is to implement the `PodcastManager` class with the specified methods.
The `PodcastManager` class ... | ```python
class PodcastManager:
def __init__(self, json_file):
self._json_file = json_file
self.data = []
def add_podcast(self, name, feed_url, position):
new_podcast = {
"name": name,
"feed_url": feed_url,
"position": position,
}
self... | magicoder | python |
You are tasked with creating a Django migration to add a new field to an existing model. The model in question is `User` from the app `email_verification`. The new field to be added is `is_verified`, which will be a boolean field indicating whether the user's email has been verified.
Your task is to write the migratio... | ```python
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('email_verification', '0002_auto_20190415_1718'),
]
operations = [
migrations.AddField(
model_name='user',
name='is_verified',
field=models.Bool... | magicoder | python |
You are tasked with implementing a randomizer for two-handed voicings in a music application. Two-handed voicings are a technique used in piano playing where both hands are used to play chords in a harmonically rich and balanced manner. The randomizer should be designed as a module in the application and should be acce... | ```rust
// Define the TwoHandedVoicingRandomizer module
mod two_handed_voicing_randomizer {
use rand::prelude::*;
// Define the TwoHandedVoicingRandomizer struct
pub struct TwoHandedVoicingRandomizer;
impl TwoHandedVoicingRandomizer {
// Method to generate random two-handed voicings for a give... | magicoder | rust |
You are tasked with creating a Rust macro that generates code for creating a contract reference. Contract references are used to dynamically depend on a smart contract. Your task is to implement a macro that takes in the contract name and generates the necessary code for creating a reference to that contract.
Your mac... | ```rust
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
/// Generates code for creating a contract reference.
///
/// # Arguments
///
/// * `contract_name` - A string representing the name of the smart contract.
///
/// # Returns
///
/// A TokenStream2 containing the generated code for creating a refer... | magicoder | rust |
You are tasked with implementing a custom error handling system for a web application. The system should include a base error class and a specific error class for handling invalid field errors.
Your task is to create the `AppError` base class and the `InvalidFieldError` class, ensuring that they handle error messages ... | ```python
from flask import jsonify
class AppError:
def __init__(self, status_code, error_code, message):
self.status_code = status_code
self.error_code = error_code
self.message = message
def to_json(self):
response = jsonify({"errorCode": self.error_code, "errorMessage": self... | magicoder | python |
You are tasked with implementing a Depth-First Search (DFS) algorithm for a graph traversal. The graph is represented using an adjacency list and the DFS algorithm should be implemented as a method within a Python class.
You are given a code snippet that initializes some instance variables and calls the `__dfs` method... | ```python
class GraphTraversal:
def __init__(self, graph, orgin):
self.__orgin = orgin
self.__visited = [False] * graph.get_node_nums()
self.__from = [-1] * graph.get_node_nums()
self.__dfs(graph, orgin)
def __dfs(self, graph, node):
self.__visited[node] = True
... | magicoder | python |
You are tasked with implementing a class that interacts with Amazon DynamoDB using the provided `AmazonDynamoDbService` module. Your goal is to create a class called `DynamoDBManager` that encapsulates the functionality to perform basic operations such as adding an item, getting an item, updating an item, and deleting ... | ```javascript
import { AmazonDynamoDbService } from "./amazonDynamoDbService";
class DynamoDBManager {
constructor() {
this.dynamoDbService = new AmazonDynamoDbService();
}
addItem(tableName, item) {
try {
this.dynamoDbService.putItem(tableName, item);
} catch (error) {
console.error("Er... | magicoder | javascript |
You are tasked with creating a script to automate the generation of a configuration file for a bouncer service. The script should replace a placeholder in a template file with the actual path to the alert pipe and then save the modified content to a new file.
You are given a template file named `bouncer_config_templat... | ```bash
#!/bin/bash
# Read the template file and replace the placeholder with the actual path
sed "s@TEMPLATE_ALERT_PIPE_PATH@$ALERT_PIPE_PATH@g" bouncer_config_template.json > $DIR/bouncer_config.json
```
In the solution, the `sed` command is used to replace the placeholder `TEMPLATE_ALERT_PIPE_PATH` with the actual... | magicoder | shell |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.