query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a custom data structure called `InsertableOrderedDict` that combines the features of an ordered dictionary and a list. The `InsertableOrderedDict` should maintain the order of insertion for its key-value pairs and support efficient insertion, deletion, and retrieval operations.
Your ta... | ```python
class InsertableOrderedDict:
def __init__(self):
self._dict = {}
self._keys = []
def insert(self, key, value):
if key in self._dict:
self._dict[key] = value
else:
self._dict[key] = value
self._keys.append(key)
def delete(self, k... | magicoder | python |
You are tasked with implementing a simple stack data structure in Swift. A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. It has two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack.
Your task is to creat... | ```swift
class Stack<T> {
private var elements: [T] = []
func push(_ element: T) {
if elements.count < 100 {
elements.append(element)
} else {
print("Stack overflow")
}
}
func pop() -> T? {
if elements.isEmpty {
print("Stack u... | magicoder | swift |
You are tasked with implementing a build system for an Android application using the SCons build tool. The given code snippet is a part of the SConstruct file, which is used to configure the build settings for the application. The snippet shows the configuration of compiler and linker flags for the Android NDK (Native ... | ```python
from distutils.version import LooseVersion
def configure_ndk_flags(ndk_version: str, architecture: str) -> dict:
flags = {'CPPFLAGS': [], 'LINKFLAGS': []}
if ndk_version is not None and LooseVersion(ndk_version) >= LooseVersion("15.0.4075724"):
flags['CPPFLAGS'].extend(['-target', target_opt... | magicoder | python |
You are tasked with implementing a function to calculate the face reflection distance and height for a character in a video game. The function should take into account the current camera state and tweakable GUI settings.
You are given the following code snippet as a reference for the function:
```cpp
void CSamusFaceR... | ```cpp
void CalculateFaceReflection(const CStateManager& mgr, float& reflectionDistance, float& reflectionHeight) {
if (TCastToConstPtr<CFirstPersonCamera> fpCam = (mgr.GetCameraManager()->GetCurrentCamera(mgr))) {
zeus::CQuaternion camRot(fpCam->GetTransform().basis);
reflectionDistance = ITweakGui::FaceRefl... | magicoder | cpp |
You are tasked with implementing a thread-safe message sender for a Syslog server. The Syslog server is responsible for receiving and processing log messages from various sources. Your implementation should ensure that messages can be sent to the Syslog server from multiple threads without causing any data corruption o... | ```java
import com.cloudbees.syslog.SyslogMessage;
import com.cloudbees.syslog.sender.UdpSyslogMessageSender;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class SyslogMessageSender {
private final UdpSyslogMessageSender messageSender;
public SyslogMessageSender(String serverAddres... | magicoder | java |
You are tasked with implementing a class that manages a collection of strings and provides functionality to set a minimum length for the strings in the collection. Your task is to complete the implementation of the `setMinStringLength` method in the given class.
You are provided with the following class definition:
`... | ```java
public void setMinStringLength(Integer minStringLength) {
if (minStringLength != null) {
strings.removeIf(str -> str.length() < minStringLength);
}
}
```
The `setMinStringLength` method first checks if the input `minStringLength` is not null. If it's not null, it uses the `removeIf` method to r... | magicoder | java |
You are tasked with implementing a custom parser for a specific file format using Java. The file format consists of key-value pairs, where each key-value pair is separated by a delimiter. The parser should be able to read the file and extract the key-value pairs into a data structure for further processing.
You need t... | ```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CustomParser {
private String delimiter;
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
public Map<String, Str... | magicoder | java |
You are tasked with creating a Python function that simulates the behavior of a URL reverse lookup and deletion process in a Django web application. The function should take in the institution ID and user email as input parameters and perform the following steps:
1. Use the Django `reverse` function to generate a URL f... | ```python
from django.urls import reverse
class HttpClient:
def delete(self, url):
# Simulated HTTP DELETE request
pass
def assertEqual(self, expected, actual):
# Simulated assertion
pass
class Institution:
def __init__(self, id):
self.id = id
def delete(self)... | magicoder | python |
You are working on a data processing application that involves filtering and processing data based on certain conditions. In this scenario, you need to implement a function that filters out elements from a given list based on a specific condition. The condition is defined by a constant `IGNORE_OC_COUNT` and a condition... | ```python
from typing import List, Any
def filter_elements(elements: List[Any]) -> List[Any]:
IGNORE_OC_COUNT = 2
IGNORE_OC_CONDITION = lambda x: x % 2 == 0
count_map = {}
result = []
for element in elements:
if element not in count_map:
count_map[element] = 1
resu... | magicoder | python |
You are tasked with creating a program that simulates a simplified version of a popular game called "Rock, Paper, Scissors" using Python. The game should allow a user to play against the computer, which will randomly select one of the three options. The program should display the user's choice, the computer's choice, a... | ```python
import random
def get_user_choice():
while True:
user_choice = input("Enter your choice (rock, paper, or scissors): ").lower()
if user_choice in ["rock", "paper", "scissors"]:
return user_choice
else:
print("Invalid choice! Please enter rock, paper, or scis... | magicoder | python |
You are tasked with creating a Rust function that utilizes the `tokio` library to asynchronously spawn a blocking task. Your function should take a closure `f` as an argument, which returns a value of type `R`. The closure `f` should not take any arguments. The function should return a `tokio::task::JoinHandle` that re... | ```rust
use tokio::task;
fn spawn_blocking_task<F, R>(f: F) -> task::JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
task::spawn_blocking(f)
}
```
The `spawn_blocking_task` function uses the `tokio::task::spawn_blocking` method to asynchronously spawn a blocking task. It takes ... | magicoder | rust |
You are tasked with implementing a function to calculate the rotation matrix between two given matrices and then determining the indices of non-zero elements in the resulting rotation matrix.
You are given the following code snippet as a starting point:
```python
R = utils.rotation_matrix(A_prime, A)
# Check order.
... | ```python
import numpy as np
def find_nonzero_indices(A_prime, A):
def rotation_matrix(A_prime, A):
# Implementation of rotation_matrix function
# Calculate the rotation matrix R using A_prime and A
# ...
return R # Return the rotation matrix R
R = rotation_matrix(A_prime, A)
... | magicoder | python |
You are tasked with implementing a Python function that processes a JSON file containing information about students' exam results. The function should read the JSON file, calculate the average score for each student, and then write the student names along with their average scores to a new JSON file.
The JSON file con... | ```python
import json
def process_results(input_file, output_file):
with open(input_file, 'r') as f:
data = json.load(f)
results = data['results']
for result in results:
average_score = round(sum(result['scores']) / len(result['scores']), 1)
result['average_score'] = average_score
... | magicoder | python |
You are given a text file named `filename` containing a series of lines. Your task is to write a Python function that reads the file and counts the occurrences of the character '8' in the entire file. The function should return the total count of occurrences of '8' in the file.
Function Signature: `def count_eights(fi... | ```python
def count_eights(filename: str) -> int:
count = 0
with open(filename, 'r') as file:
for line in file:
for char in line:
if char == '8':
count += 1
return count
```
The `count_eights` function opens the file specified by `filename` and iterate... | magicoder | python |
You are tasked with creating a program that determines the movie rating restrictions based on the age of the viewer. The program should prompt the user to input their age and then provide the appropriate movie rating restrictions based on the following rules:
- If the age is less than 13, the viewer may only see G and ... | ```python
# Prompt the user to input their age
user_age = int(input("Enter your age: "))
# Determine the movie rating restrictions based on the user's age
if user_age < 13:
print("You may only see G and PG movies")
elif user_age >= 13 and user_age < 17:
print("You can see any movies except for R movies")
else:... | magicoder | python |
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. The program should read the text file, tokenize the words, and then count the occurrences of each word. Additionally, the program should ignore common stop words (e.g., "the", "is", "and") and should be ca... | ```python
import re
from collections import Counter
# Define common stop words
stop_words = {"the", "is", "and", "it", "of", "for", "in", "to", "a"}
# Read the text file
with open("sample_text.txt", "r") as file:
text = file.read()
# Tokenize the words and count occurrences
words = re.findall(r'\b\w+\b', text.lo... | magicoder | python |
You are tasked with creating a script to automate the setup of a PostgreSQL database for a new application. The script should perform the following tasks:
1. Drop the database "pushkin" if it already exists.
2. Drop the user "pushkin" if it already exists.
3. Create a new database named "pushkin".
4. Create a new user... | ```bash
#!/bin/bash
# Define the password for the pushkin user
PASSWORD="your_password_here"
# Drop the database if it exists
psql -U postgres -c "drop database if exists pushkin"
# Drop the user if it exists
psql -U postgres -c "drop user if exists pushkin"
# Create the pushkin database
psql -U postgres -c "create... | magicoder | shell |
You are tasked with implementing a custom data structure that supports dynamic memory allocation. Your goal is to create a `ResizableBuffer` struct that allows users to reserve additional memory space to avoid frequent reallocations. The `ResizableBuffer` should have a method `reserve` that takes an additional amount o... | ```rust
struct ResizableBuffer {
buf: Vec<u8>,
}
impl ResizableBuffer {
pub fn new() -> Self {
ResizableBuffer { buf: Vec::new() }
}
pub fn reserve(&mut self, additional: usize) {
self.buf.reserve(additional);
}
}
fn main() {
let mut buffer = ResizableBuffer::new();
buffer... | magicoder | rust |
You are tasked with creating a Python script to automate the deployment of an EMR (Elastic MapReduce) cluster on AWS using the Boto3 library. The script should take input parameters such as virtual cluster ID, job name, execution role ARN, S3 bucket details, EMR release label, and job driver configuration. The job driv... | ```python
def create_emr_cluster_script(VIRTUAL_CLUSTER_ID, JOB_NAME, EMR_ROLE_ARN, S3_BUCKET, EMR_RELEASE_LABEL, EMR_MASTER_DNS_NAME):
script = f"--virtual-cluster-id {VIRTUAL_CLUSTER_ID} \\\n"
script += f"--name {JOB_NAME} \\\n"
script += f"--execution-role-arn {EMR_ROLE_ARN} \\\n"
script += f"--relea... | magicoder | python |
You are tasked with implementing a Python function to calculate the Fibonacci sequence up to a given limit. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The function should take an integer `limit` as input and return a list of Fi... | ```python
from typing import List
def calculate_fibonacci(limit: int) -> List[int]:
if limit <= 0:
return []
fibonacci_sequence = [0, 1]
while True:
next_fib = fibonacci_sequence[-1] + fibonacci_sequence[-2]
if next_fib > limit:
break
fibonacci_sequence.append(ne... | magicoder | python |
You are tasked with implementing a class for managing asymmetric cycles. An asymmetric cycle is a sequence of integers where each element points to the next element in the sequence, and the last element points to null. The class should support cloning an asymmetric cycle.
You are provided with a partial code snippet f... | ```csharp
public class AsymmetricCycles
{
private int[] _nextArray;
public AsymmetricCycles(int[] nextArray)
{
_nextArray = nextArray;
}
/// <summary>
/// Clones this asymmetric cycles.
/// </summary>
/// <returns></returns>
public AsymmetricCycles Clone()
{
int... | magicoder | csharp |
You are tasked with implementing a checkpoint management system for a machine learning model training process. The system should save checkpoints at specific intervals and keep track of the best validation error encountered so far. You are given a partial code snippet that demonstrates the usage of a `save_checkpoint` ... | ```python
def save_checkpoint(checkpoint_path, extra_vars, step, best_dev_error):
if step % 1000 == 0: # Save checkpoint at every 1000 training steps
checkpoint_data = {
'step': step,
'best_dev_error': best_dev_error
}
for var in extra_vars:
checkpoint_da... | magicoder | python |
You are tasked with implementing a function that simulates a simple key-value store and performs computations based on the stored values. The store contains various items, each identified by a unique name. The provided code snippet is a part of a larger program that interacts with the store and performs computations ba... | ```javascript
function performComputation(name, arg_ids, arg_names, compute_counter, store, ir_instance, diff) {
let result = {};
// Retrieve the old value from the store
let old_value = store.get_{{name}}(...arg_ids);
result.old_value = old_value;
// Compute the counter if required
if (compute_counter) {... | magicoder | javascript |
You are tasked with creating a login system for a school management application. The given code snippet is a part of a PHP script that handles the login process. The script sets the session data upon successful login and redirects the user to the dashboard. Your task is to implement the login validation logic and sessi... | ```php
// Assuming the login form submits the username and password for validation
$username = $_POST['username'];
$password = $_POST['password'];
// Perform login validation (e.g., check against database)
if (/* validation logic */) {
// If login is successful
$login['username'] = $username;
$login['schoo... | magicoder | php |
You are tasked with implementing a custom sorting algorithm for an array of objects. Each object has a property called `age`, and the sorting algorithm should arrange the objects in such a way that the older objects come before the younger ones. However, there is a special case where objects with an `ExclusiveOlderFirs... | ```javascript
function customSort(people) {
const exclusiveFirst = people.filter(person => person.ExclusiveOlderFirst);
const nonExclusive = people.filter(person => !person.ExclusiveOlderFirst);
exclusiveFirst.sort((a, b) => a.age - b.age);
nonExclusive.sort((a, b) => a.age - b.age);
return exclusiveFirst.c... | magicoder | javascript |
You are tasked with implementing a custom model in a Django application for managing events. The provided code snippet is the beginning of the `Event` model class, which inherits from the `GeneralModel` class in the `eventup.utils.models` module. Your task is to complete the implementation of the `Event` model by addin... | ```python
''' Events Model '''
import uuid
from django.db import models
# Utils Model
from eventup.utils.models import GeneralModel
class Event(GeneralModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100)
description = models.TextFiel... | magicoder | python |
You are tasked with implementing a custom error handling system for a cryptocurrency trading application. The application interacts with the BitMEX exchange and needs to handle various error scenarios that may arise during API calls and WebSocket communication.
Your task is to create a custom error type called `BitMEX... | ```rust
use failure::{Fail, Serialize, Deserialize};
use serde::{Serialize, Deserialize};
use std::fmt;
#[derive(Debug, Fail, Serialize, Deserialize, Clone)]
pub enum BitMEXError {
#[fail(display = "No Api key set for private api")]
NoApiKeySet,
#[fail(display = "{} error message from BitMEX server: {}", n... | magicoder | rust |
You are tasked with creating a method to retrieve data from a database using Hibernate Query Language (HQL). Your goal is to implement a method that takes an HQL query as input and returns a list of results from the database.
You are given a Java class with a method signature as follows:
```java
public List findByHql... | ```java
import org.hibernate.Session;
import org.hibernate.query.Query;
public List findByHql(String hql) {
List results = null;
try (Session session = sessionFactory.openSession()) {
Query query = session.createQuery(hql);
results = query.list();
} catch (Exception e) {
// Handle a... | magicoder | java |
You are tasked with implementing a tokenizer function that takes a string as input and returns a list of integers based on certain rules. The rules for tokenizing the input string are as follows:
1. Each character in the input string is assigned a unique integer value based on its position in the string, starting from ... | ```python
import numpy as np
def tokenizer(s):
res = []
for char in s:
if char.isdigit():
res.append(int(char))
elif char.isalpha():
char_val = ord(char.lower()) - ord('a')
res.append(char_val)
else:
res.append(20)
return np.array(res)... | magicoder | python |
You are tasked with implementing a method that makes an asynchronous HTTP request using the `HttpClient` class in C#. Your method should handle potential exceptions and cancellation scenarios.
Write a method with the following signature:
```csharp
public async Task<HttpResponseMessage> MakeHttpRequestAsync(HttpClient ... | ```csharp
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class HttpRequestHandler
{
public async Task<HttpResponseMessage> MakeHttpRequestAsync(HttpClient client, HttpRequestMessage request, Func<HttpResponseMessage, Task> responseHandler, CancellationToken cancel... | magicoder | csharp |
You are tasked with implementing a simplified version of a dynamic DNS (DDNS) service. Dynamic DNS is a system that automatically updates the DNS records in real-time when the IP address of a device changes. In this problem, you are required to create a class `DynamicDNS` that manages the mapping of domain names to IP ... | ```python
class DynamicDNS:
def __init__(self):
self.domain_to_ip = {}
def start(self, options):
# Initialize the DDNS service with the provided configuration
initial_mappings = options.get('initial_mappings', {})
for domain, ip in initial_mappings.items():
self.doma... | magicoder | python |
You are tasked with implementing a custom security policy validation system in Python. The `validate` method serves as the interface for the security policy and takes in several parameters. Your goal is to create a robust implementation of the `validate` method that enforces security policies based on the provided para... | ```python
class CustomSecurityPolicy:
def validate(self, accessed=None, container=None, name=None, value=None, context=None, roles=None, *args, **kw):
# Custom security policy implementation
if accessed == "sensitive_resource" and "admin" not in roles:
return 0 # Deny access to sensitiv... | magicoder | python |
You are tasked with implementing a Python class that evaluates mathematical expressions using a custom syntax. Your task is to create a class `Pow` that represents the exponentiation operation. The `Pow` class should take two arguments, `left` and `right`, representing the base and exponent, respectively. The `eval` me... | ```python
class Number:
def __init__(self, value):
self.value = value
def type(self):
return Number
def eval(self):
return self.value
class Pow(Number):
def __init__(self, left, right):
self.left = left
self.right = right
def type(self):
return Po... | magicoder | python |
You are given a list of mathematical expressions, each containing the symbol '^' to represent exponentiation. Your task is to replace the '^' symbol with '**' and evaluate each expression to find the result. If the expression is not valid or cannot be evaluated, you should output "Invalid expression". Otherwise, output... | ```python
def evaluate_expressions(n, expressions):
results = []
for exp in expressions:
try:
exp = exp.replace('^', '**')
result = eval(exp)
results.append(str(result))
except:
results.append("Invalid expression")
return results
# Test the fu... | magicoder | python |
You are given the definition of a binary tree node and a function `findMode` that takes the root of a binary search tree as its input. The function is intended to return an array containing the mode(s) of the given binary search tree. The mode of a BST is defined as the value(s) that appear most frequently. If multiple... | ```python
from collections import defaultdict
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
def inorder(node):
if node:
inorder(node.left)
counts[node.val] += 1
inorder(node.right)
counts = defaultdict(int)
inor... | magicoder | python |
You are tasked with implementing a class for managing a grid of cells in a game. The class should ensure that either a view factory or a set of cells is provided, and that the number of cells matches the specified number of rows and columns.
Your task is to create a `GridManager` class with the following requirements:... | ```swift
class GridManager {
var viewFactory: (() -> UIView)?
var cells: [Cell]?
var rows: Int
var cols: Int
init(viewFactory: (() -> UIView)?, cells: [Cell]?, rows: Int, cols: Int) {
self.viewFactory = viewFactory
self.cells = cells
self.rows = rows
self.cols = cols... | magicoder | swift |
You are tasked with implementing a function that calculates the y-coordinate for a new shape to be added to a canvas. The function takes in the position and height of the current shape, as well as the position and height of the last child shape added to the canvas. The goal is to determine the y-coordinate for the new ... | ```javascript
function calculateNewShapeY(positionY, height, lastChildY, lastChildHeight) {
return positionY + height + lastChildY + lastChildHeight;
}
``` | magicoder | javascript |
You are tasked with implementing a role-based access control system for an e-commerce platform. The system should allow for the creation of different roles and the assignment of these roles to users. The code snippet provided demonstrates the addition of a user role and the creation of a new role for sellers.
Your tas... | ```php
class RoleManager {
private $roles = [];
public function addRole($roleName) {
if (!in_array($roleName, $this->roles)) {
$this->roles[] = $roleName;
}
}
public function assignRole($userId, $roleName) {
// Implement user role assignment logic here
}
}
// U... | magicoder | php |
You are tasked with implementing a class that represents a structured data object and provides methods for manipulating its fields. The class should support adding, updating, and retrieving fields, as well as converting the data object to a string representation.
You are given the following code snippet as a reference... | ```java
import java.util.HashMap;
import java.util.Map;
public class DataObject {
private Map<String, Object> fields;
public DataObject() {
this.fields = new HashMap<>();
}
public void field(String key, Object value) {
fields.put(key, value);
}
public void updateField(String ... | magicoder | java |
You are tasked with creating a method to update the count of a session in a web application. The method should be implemented in C# using ASP.NET Core and should handle the HTTP POST request. The method should accept a JSON object representing the session operation view model and update the session count in the reposit... | ```csharp
[HttpPost]
public async Task<IActionResult> UpdateCount([FromBody] SessionOperationViewModel sessionOperationViewModel)
{
try
{
// Assuming _sessionsRepository is an instance of ISessionsRepository injected via dependency injection
var session = await _sessionsRepository.UpdateSessionC... | magicoder | csharp |
You are tasked with implementing a TypeScript type definition for a configuration library called StyleDictionary. StyleDictionary is a tool that allows for the transformation and export of design tokens into various platforms such as web, iOS, Android, etc. The provided code snippet contains a series of type assertions... | ```typescript
// Define the StyleDictionary namespace and its core types
declare namespace StyleDictionary {
// Define the Core type representing the core functionality of StyleDictionary
export interface Core {
// Define the methods available on the Core type
buildPlatform(platform: string): Core;
clea... | magicoder | typescript |
You are tasked with implementing a Java class for representing and managing beer products. The class should encapsulate various attributes of a beer, such as name, price, alcohol content, brewery, type, and code. Additionally, you need to implement a method for persisting the beer object to a database.
Your task is to... | ```java
import java.math.BigDecimal;
// Enum for beer type
enum Type {
LAGER, ALE, STOUT, PORTER, VIENNA
}
// Enum for country
enum Country {
SWITZERLAND, GERMANY, BELGIUM, USA
}
// Brewery class
class Brewery {
private String name;
private Country country;
public Brewery(String name, Country co... | magicoder | java |
You are tasked with creating a script to manage the server mode for a database. The script will take a server mode as an argument and update the server mode in the database. Additionally, it should fetch and display the current server mode after the update.
You are provided with a code snippet that demonstrates the ba... | ```python
import sys
import subprocess
def update_server_mode(server_mode):
try:
print(f"Updating server status to {server_mode}")
update_command = f"mongo polymorph --eval \"db.servermodes.update({}, {{'server_mode': '{server_mode}'}},{{upsert:true}})\""
print(f"Calling: {update_c... | magicoder | python |
You are tasked with creating a Python function that parses configuration options from a given configuration file and returns a dictionary containing the parsed options. The configuration file is in the INI format and may contain various sections and options. Each option may have a specific data type, such as string, in... | ```python
from oslo_config import cfg
import configparser
def parse_config_file(file_path: str) -> dict:
# Define a dictionary to store the parsed options
parsed_options = {}
# Create a ConfigParser object to read the configuration file
config_parser = configparser.ConfigParser()
config_parser.rea... | magicoder | python |
You are tasked with creating a script to validate a configuration file for a Kubernetes operator. The script should check for specific configurations and report any errors found. The script should also handle the case where the Kubernetes configuration is set via environment variables.
Write a Bash script that accomp... | ```bash
#!/bin/bash
# Check if Kubernetes configuration is set in the plugin config and overrides the flag
if echo "$commandoutput3" | grep -q '^.*"name": "Environment",[[:space:]]"description": "Test plugin with kubeconfig set via env var",[[:space:]]"earnedPoints": 2,[[:space:]]"maximumPoints": 5,.*$'; then
echo... | magicoder | shell |
You are tasked with implementing a function that checks the validity of HTML tags in a given string. The function should return true if all the HTML tags are properly formatted and nested correctly, and false otherwise.
The function should take a single string as input, which may contain HTML tags such as `<div>`, `</... | ```java
import java.util.Stack;
public class HTMLValidator {
public static boolean isValidHTML(String html) {
Stack<String> stack = new Stack<>();
for (int i = 0; i < html.length(); i++) {
if (html.charAt(i) == '<') {
if (html.charAt(i + 1) == '/') {
... | magicoder | java |
You are given an array of integers. Your task is to find the length of the longest contiguous subarray with an equal number of 0s and 1s.
Write a function `findMaxLength` that takes in an array of integers and returns the length of the longest contiguous subarray with an equal number of 0s and 1s.
For example, given ... | ```python
from typing import List
def findMaxLength(nums: List[int]) -> int:
max_len = 0
rolling_sum = 0
seen_sums = {0: -1}
for i, num in enumerate(nums):
if num == 0:
rolling_sum -= 1
else:
rolling_sum += 1
if rolling_sum in seen_sums:
max... | magicoder | python |
You are tasked with implementing a Python decorator for tenant isolation in a DynamoDB environment. The decorator should ensure that each tenant's requests are isolated and use their own set of credentials when interacting with DynamoDB.
You are provided with a code snippet that partially implements the decorator `dyn... | ```python
import functools
# Assume these functions and variables are defined elsewhere
def copy_context():
# Implementation of copy_context
pass
def generate_credentials(event):
# Implementation of generate_credentials
pass
dynamodb_session_keys = {} # Assume this is a global variable representing ... | magicoder | python |
You are tasked with creating a custom exception hierarchy for a Python library. The library is used for interacting with the Discord API, and you need to define custom exceptions for specific error cases. The provided code snippet shows a part of the exception hierarchy for the library, with two custom exception classe... | ```python
class CommandPermissionError(PincerError, PermissionError):
"""
Exception raised when a user attempts to execute a command without
having the necessary permissions.
"""
```
In the solution, we define the `CommandPermissionError` class as a subclass of both `PincerError` and `PermissionError`, ... | magicoder | python |
You are tasked with implementing a custom categorical processor for encoding categorical variables in a dataset. The categorical processor should be able to transform categorical variables into numerical representations using a specific encoding scheme.
You are given a code snippet that initializes a list `X_train` c... | ```python
class CategoricalProcessor:
def __init__(self):
self.mapping = {} # Initialize an empty dictionary to store the mapping of categories to integers
def fit_transform(self, categories):
"""
Fit the categorical processor to the given categories and transform them into numerical r... | magicoder | python |
You are working on a machine learning project and need to implement a coordinate descent algorithm for a sparse optimization problem. The algorithm involves updating the weights iteratively based on certain conditions and constraints.
You are given a Python code snippet that represents part of the coordinate descent a... | ```python
import numpy as np
class CoordinateDescentAlgorithm:
def __init__(self, dim, bound):
self.dim = dim
self.bound = bound
self.last_weight = None
self.new_ind = None
def forwardOp(self, array):
# Implement the forward operation method based on the requirements of... | magicoder | python |
You are tasked with implementing a custom activity indicator for a console-based application. The activity indicator will be based on the `ActivityIndicatorType` protocol, which requires the implementation of a method to draw/render the indicator to the console for a given state.
The `ActivityIndicatorType` protocol h... | ```swift
// Define the ActivityIndicatorState enum to represent different states of the activity indicator
public enum ActivityIndicatorState {
case loading
case completed
case error
}
// Create a concrete type conforming to the ActivityIndicatorType protocol
public struct CustomActivityIndicator: Activity... | magicoder | swift |
You are tasked with implementing a credit management system for a company's customers. The system should allow for the creation of customer profiles with credit limits and track credit reservations made by customers. You need to create a class to represent a customer and implement methods to manage their credit.
Creat... | ```csharp
public class Money
{
public decimal Amount { get; set; }
public string Currency { get; set; }
public Money(decimal amount, string currency)
{
Amount = amount;
Currency = currency;
}
public static Money operator +(Money money1, Money money2)
{
if (money1.Cu... | magicoder | csharp |
You are tasked with implementing a generic checksum calculation system in Swift. Your goal is to create a generic function that can calculate a checksum for any type of data using a provided checksum algorithm.
You are given a code snippet that includes a generic function `calculate` and a protocol `Checksum`. The `ca... | ```swift
// Define the Checksum protocol
protocol Checksum {
associatedtype ChecksumType
func obtainChecksum() throws -> ChecksumType
}
// Define the BaseChecksumHolder class
class BaseChecksumHolder<ChecksumType: Checksum> {
private let data: Any
init(data: Any) {
self.data = data
}
... | magicoder | swift |
You are tasked with creating a unit test for a Python class that sends emails. The class, `EmailSender`, has a method `send_email` which sends an email using an external service. Your goal is to write a unit test using the `unittest` framework to ensure that the `send_email` method behaves as expected.
The `EmailSende... | ```python
import unittest
from unittest.mock import Mock
from email_sender import EmailSender # Import the EmailSender class from the email_sender module
class TestEmailSender(unittest.TestCase):
def test_send_email_called_and_message_content(self):
# Create a mock object to simulate the EmailSender class... | magicoder | python |
You are tasked with implementing a logging system for a software engine and its client applications. The logging system should be able to handle different types of log messages and direct them to appropriate sinks for output. The code snippet provided is the beginning of a logging system implementation using the Hazel ... | ```cpp
#include <iostream>
#include <memory>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
enum class LogLevel {
Info,
Warning,
Error
};
class Logger {
public:
Logger(const std::string& name, const std::string& pattern) {
logg... | magicoder | cpp |
You are tasked with creating a helper function to validate a given email address. The function should take an email address as input and return True if the email address is valid, and False otherwise. An email address is considered valid if it meets the following criteria:
- It contains a single "@" symbol.
- The "@" s... | ```python
# project/tests/helpers.py
def validate_email(email):
if email.count('@') != 1: # Check for a single "@" symbol
return False
username, domain = email.split('@') # Split the email address into username and domain
if not username or not domain: # Check if username or domain is empty
... | magicoder | python |
You are tasked with implementing a simple dependency injection container in TypeScript using the `tsyringe` library. The `tsyringe` library provides a decorator-based API for managing dependencies and performing dependency injection in TypeScript applications.
Your goal is to create a simple container that can registe... | ```typescript
import { container, injectable, inject } from 'tsyringe';
// Define the DependencyContainer class
class DependencyContainer {
// Register a dependency with the container
register<T>(token: string, dependency: new () => T | T): void {
if (typeof dependency === 'function') {
container.registe... | magicoder | typescript |
You are given a Python code snippet that processes a graph definition. The code iterates through the nodes of the graph and performs certain operations based on the node names and their relationships. Your task is to create a programming problem based on this scenario.
Write a function called `process_graph` that take... | ```python
def process_graph(input_graph_def, fuse_op_name, input_node_map):
skip_list = []
skip_node_name = []
for index, node in enumerate(input_graph_def):
if node.name in fuse_op_name:
skip_list.append(index + 1)
original_node = input_node_map[node.name]
mul_n... | magicoder | python |
You are tasked with creating a Bash script that automates the process of launching an EC2 instance in the AWS cloud. The script should utilize environment variables to set the AWS region and the SSH key pair to be used for accessing the instance. Your script should also handle error cases such as missing environment va... | ```bash
#!/bin/bash
# Check if the required environment variables are set
if [ -z "$REGION" ] || [ -z "$SSHKEY" ]; then
echo "Error: Required environment variables REGION and SSHKEY are not set."
exit 1
fi
# Launch an EC2 instance using the AWS CLI
instance_info=$(aws ec2 run-instances --image-id <your-ami-id> --... | magicoder | shell |
You are tasked with implementing a C++ program that performs serialization and deserialization of complex numbers using the Boost C++ library. The program should utilize the Boost Serialization library to serialize a pair of complex numbers (one of type float and the other of type double) and then deserialize them back... | ```cpp
#include <iostream>
#include <fstream>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/complex.hpp>
int main() {
std::complex<float> a(3.14f, 2.71f);
std::complex<double> b(6.28, 5.42);
// Seria... | magicoder | cpp |
You are tasked with implementing a simple text classification system using Python. Your goal is to create a base class for classifiers that can be extended to support different classification algorithms. The base class should provide common functionality for training and predicting, and it should be flexible enough to ... | ```python
from abc import ABC, abstractmethod
import numpy as np
class Classifier(ABC):
@abstractmethod
def train(self, X, y):
pass
@abstractmethod
def predict(self, X):
pass
class NaiveBayesClassifier(Classifier):
def __init__(self):
self.class_probs = {}
self.fea... | magicoder | python |
You are tasked with implementing a service that retrieves branch information for a company. The provided code snippet shows the beginning of a Java class `BranchInfoServiceImpl` that is annotated with `@Service` and implements the interface `IBranchInfoService`. Your task is to complete the implementation of this servi... | ```java
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BranchInfoServiceImpl implements IBranchInfoService {
// Assuming the existence of a Branch class representing branch information
// Method to retrieve branch information by ID
public Branch getBranchById(... | magicoder | java |
You are tasked with implementing a settings cluster enable controller for a web application. The controller is responsible for handling requests related to enabling or disabling settings clusters. The provided code snippet is a simplified version of the controller class.
Your task is to complete the implementation of ... | ```php
class SettingsClusterEnableController extends AbstractController
{
public function anyIndex($clusterName = null, $isEnable = 1)
{
$this->toggleCluster($clusterName, $isEnable);
}
public function toggleCluster($clusterName = null, $isEnable = 1)
{
if ($isEnable == 1) {
... | magicoder | php |
You are tasked with creating a Python context manager that asynchronously handles the reading and writing of data using the `tablib` library. The `tablib` library is a powerful tool for managing tabular data in Python. Your task is to implement an asynchronous context manager that can be used to read data from a file a... | ```python
from contextlib import asynccontextmanager
import tablib
@asynccontextmanager
async def async_tablib_context_manager(file_path, mode):
dataset = tablib.Dataset()
try:
if mode == 'r':
async with aiofiles.open(file_path, mode='r') as file:
data = await file.read()
... | magicoder | python |
You are tasked with implementing a function that will parse a given HTML code and extract all the attributes and their corresponding values from the opening tags of the input HTML elements. The function should return a dictionary where the keys are the HTML element names and the values are dictionaries containing the a... | ```python
import re
def parse_html_attributes(html: str) -> dict:
tag_pattern = r'<(\w+)([^>]*)>'
attribute_pattern = r'(\w+)="([^"]*)"'
result = {}
for match in re.finditer(tag_pattern, html):
tag_name = match.group(1)
attributes_str = match.group(2)
attributes = dict(re.f... | magicoder | python |
You are tasked with creating a Python function that processes data from a space exploration project. The function should handle the retrieval of exoplanet data and provide information about the success of the retrieval, the type of the result, and the length of the result if it is iterable. Your task is to implement th... | ```python
def process_exoplanet_data(name: str, result, iterable: bool) -> str:
try:
if iterable:
result_length = len(result)
else:
result_length = None
return f"exoplanet.{name} success\n\t {type(result)}\n\t {result_length}"
except Exception as e:
retur... | magicoder | python |
You are tasked with implementing a font selection algorithm for a text rendering system. The system has access to a collection of fonts, each with a unique identifier, a reference to the font data, and a relative scale factor. The goal is to find the appropriate font and scale factor for rendering a given character.
Y... | ```rust
fn select_font<'a>(
fonts: &'a [(usize, Font<'static>, f32)],
chr: char,
) -> (usize, &'a Font<'static>, rusttype::Glyph<'static>, f32) {
for &(id, ref font, relative_scale) in fonts {
let glyph = font.glyph(chr);
if glyph.id().0 != 0 {
return (id, font, glyph, relative_s... | magicoder | rust |
You are tasked with creating a Python function to control the speed of a fan using PWM (Pulse Width Modulation) on a Raspberry Pi. The function should take two parameters: `fan_speed` and `control_interval`. The `fan_speed` parameter represents the desired speed of the fan, ranging from 0 to 100, where 0 indicates the ... | ```python
from RPi import GPIO
from time import sleep
def control_fan_speed(fan_speed: int, control_interval: int) -> None:
port = 18 # Example GPIO pin number, replace with the actual pin number
GPIO.setmode(GPIO.BCM)
GPIO.setup(port, GPIO.OUT)
pwm = GPIO.PWM(port, 50)
pwm.start(0)
try:
... | magicoder | python |
You are tasked with implementing a function that converts a given string from snake_case to CamelCase. Snake case is a naming convention where spaces are replaced with underscores and each word begins with a lowercase letter, while Camel case is a naming convention where the first letter of each word is capitalized and... | ```python
def snake_case2camelcase(word):
return "".join(x.capitalize() for x in word.split("_"))
```
The `snake_case2camelcase` function takes a string in snake_case as input and returns the string in CamelCase. It achieves this by splitting the input string at each underscore, capitalizing the first letter of ea... | magicoder | python |
You are tasked with creating a Django model for a student management system. The model should include fields for a student's user information, study program, current study year, professional skills, technical skills, and soft skills. Additionally, the model should include related models for study programs, projects, an... | ```python
from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
class StudyProgramme(models.Model):
name = models.CharField(max_length=100)
# Add other relevant fields
class Project(models.Model):
name = models.CharField(max_length=100)
# Add other r... | magicoder | python |
You are tasked with creating a program that generates a crossword puzzle grid based on a given set of words. The program should take a list of words as input and output a crossword grid that accommodates all the words in a valid crossword puzzle format. The crossword grid should have black squares to separate words and... | ```swift
func generateCrosswordGrid(words: [String]) -> [[Character]] {
let maxLength = words.map { $0.count }.max() ?? 0
var grid = Array(repeating: Array(repeating: ".", count: maxLength * 2 + 3), count: maxLength * 2 + 3)
for i in 0..<grid.count {
grid[i][0] = "#"
grid[i][grid[i].count -... | magicoder | swift |
You are given a code snippet that is part of a server-client communication program. The code snippet is responsible for handling a client request and sending a response back to the client. Your task is to understand the code snippet and implement a function that simulates the behavior of the server's response.
The cod... | ```python
def server_response(tr, c, cnt):
try:
chk = int(tr)
c.close()
return None
except ValueError:
chk = int(tr)
chk -= 1
c.send(str(chk).encode())
c.close()
return chk
```
The `server_response` function first attempts to convert the input `tr... | magicoder | python |
You are working on a weather bot that retrieves and stores weather data in a database. The bot uses SQLAlchemy to interact with the database and fetches weather information from an external API using a key stored in its configuration. Your task is to implement a method in the `WeatherPlugin` class that retrieves the cu... | ```python
import requests
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from .models import Weather
class WeatherPlugin(Plugin, CommandMixin, DatabaseMixin):
def __init__(self, bot):
super().__init__(bot)
self.key = bot.config["FORECAST_KEY"]
self.engine = cre... | magicoder | python |
You are tasked with implementing a policy response system for a network management application. The system should handle associate and disassociate policy requests based on the IFA 013 v3.2.1 specifications. The code snippet provided is the beginning of a Java class `AssociatePolicyResponse` that is expected to handle ... | ```java
public class AssociatePolicyResponse implements InterfaceMessage {
// Method to handle associate policy request
public void handleAssociatePolicyRequest(PolicyRequest request) {
// Implement logic to process associate policy request
// Validate request parameters, apply policy rules, an... | magicoder | java |
You are tasked with solving the problem of finding the lowest house number that receives a certain number of presents during the holiday season. Santa Claus has a special delivery system that involves visiting houses and leaving presents. The number of presents delivered to each house is determined by a specific algori... | ```rust
fn find_lowest_house_number(target_presents: u64) -> u64 {
let mut house_number = 1;
let mut presents_delivered = 0;
let mut presents_to_deliver = 10;
while presents_delivered < target_presents {
presents_delivered += presents_to_deliver;
presents_to_deliver += 10;
house... | magicoder | rust |
You are tasked with implementing a performance logging system for a software application. The system should measure the time taken by various processes and log the performance metrics. You are given a code snippet that logs the total time taken by a specific process called "doPullTranslation". Your task is to create a ... | ```java
import java.util.HashMap;
import java.util.Map;
public class PerformanceLogger {
private Map<String, Long> processStartTimeMap;
public PerformanceLogger() {
processStartTimeMap = new HashMap<>();
}
public void startProcess(String processName) {
processStartTimeMap.put(processN... | magicoder | java |
You are tasked with implementing a game of Tetris. In Tetris, different shapes, known as tetrominoes, fall from the top of the game board and the player must rotate and position them to create solid horizontal lines without any gaps. When a line is completed, it disappears, and any blocks above it fall down to fill the... | ```swift
import UIKit
class ZShape: Shape {
override var blockRowColumnPositions: [Orientation: Array<(columnDiff: Int, rowDiff: Int)>] {
return [
Orientation.zero: [(-1, 0), (0, 0), (0, 1), (1, 1)],
Orientation.ninetyDegrees: [(1, -1), (1, 0), (0, 0), (0, 1)]
]
}
}
```
... | magicoder | swift |
You are given a code snippet containing annotations for different fields in a software system. Each annotation consists of a description and a numerical identifier. Your task is to write a program that parses these annotations and organizes them into a dictionary where the description is the key and the numerical ident... | ```python
import re
def parse_annotations(code_snippet):
annotations = {}
pattern = r'\[Elo\("(.*?)"\s*,\s*(\d+)\)\]'
matches = re.findall(pattern, code_snippet)
for match in matches:
description, identifier = match
annotations[description] = int(identifier)
return annotations
code... | magicoder | python |
You are given a list of tuples representing the bounding boxes of detected objects in an image. Each tuple contains four integers: x-coordinate, y-coordinate, width, and height of the bounding box. Additionally, there is a list of weights corresponding to the detected objects. The goal is to find the weighted sum of th... | ```python
from typing import List, Tuple
def calculate_weighted_sum(stars: List[Tuple[int, int, int, int]], levelWeights: List[int], sf: float) -> float:
big_w = 0
weighted = 0
if len(stars) > 0:
for (x, y, w, h) in stars:
if w > big_w:
big_w = w
index =... | magicoder | python |
You are tasked with implementing a validation system for a web application. The system should be able to validate various types of input data based on predefined rules. Each rule is represented as a key-value pair in a dictionary, where the key is the name of the rule and the value is the error message associated with ... | ```python
def validateInput(data, rules):
errors = {}
for field, value in data.items():
if field in rules:
rule_message = rules[field]
if 'string' in rule_message and not isinstance(value, str):
errors[field] = rule_message.replace(':field:', field)
el... | magicoder | python |
You are tasked with creating a Python package version checker. Your program should read the version number from the `__init__.py` file of a given package and compare it with a specified version number. If the package version is greater than or equal to the specified version, the program should return "Up to date"; othe... | ```python
import re
def check_package_version(package_name, specified_version):
try:
with open(f"{package_name}/__init__.py", 'r') as file:
content = file.read()
version_match = re.search(r"__version__ = '(\d+\.\d+\.\d+)'", content)
if version_match:
pack... | magicoder | python |
You are tasked with implementing a deferred execution mechanism in Rust. Deferred execution allows certain actions to be postponed until a later time, typically when a specific condition is met or when a particular scope is exited. In this problem, you will create a `DeferStack` data structure that enables deferred exe... | ```rust
use std::ptr;
struct DeferStack<'a> {
inner: std::cell::Cell<*mut Vec<Box<dyn FnOnce() + 'a>>>,
}
impl<'a> DeferStack<'a> {
fn new() -> DeferStack<'a> {
DeferStack {
inner: std::cell::Cell::new(Box::into_raw(Box::new(Vec::new()))),
}
}
fn defer<F: FnOnce() + 'a>(&s... | magicoder | rust |
You are tasked with creating a Python class that interacts with a web API to update user profiles. The class should handle authentication, making HTTP requests, and handling potential errors. Your task is to complete the implementation of the `update_profile` method in the given Python class.
You are provided with a p... | ```python
import requests
class AuthenticationError(Exception):
pass
class UnauthorizedError(Exception):
pass
class NotFoundError(Exception):
pass
class ServerError(Exception):
pass
class ServiceUnavailableError(Exception):
pass
class RequestTimeoutError(Exception):
pass
class ForbiddenEr... | magicoder | python |
You are tasked with implementing a class for a universal constraint in a physics engine. The universal constraint restricts the relative movement between two rigid bodies to rotation around two specified axes. Your task is to complete the implementation of the `UniversalConstraint` class by defining the constructor and... | ```cpp
UniversalConstraint::UniversalConstraint(RigidBody^ rigidBodyA, RigidBody^ rigidBodyB,
Vector3 anchor, Vector3 axis1, Vector3 axis2)
: Generic6DofConstraint(0) // Call base class constructor with 0 as the index
{
// Initialize the universal constraint using the provided parameters
btTransform fra... | magicoder | cpp |
You are tasked with creating a Python function that simulates a simple user authentication system. Your function should register a user with the provided details and then attempt to log in using the same credentials. You will need to handle the registration and login process using HTTP requests to a specified service U... | ```python
import requests
def simulate_user_authentication(first_name, last_name, email, password, service_url):
user = {'first_name': first_name, 'last_name': last_name, 'email': email, 'password': password}
register_response = requests.put(f'{service_url}/user/register', json=user)
if register_respo... | magicoder | python |
You are tasked with creating a Python program that utilizes the Ray library for distributed computing to optimize a reinforcement learning agent using the LOLA (Learning with Opponent-Learning Awareness) algorithm. The LOLA algorithm is a type of policy gradient method that incorporates opponent modeling to improve the... | ```python
import os
import ray
from ray import tune
from ray.rllib.agents.ppo import PPOTrainer
from ray.rllib.examples.env.multi_agent import MultiAgentCartPole
from ray.tune.registry import register_env
# Define the grid world environment and the agents' behavior within it
def env_creator(env_config):
return Mul... | magicoder | python |
You are tasked with implementing a C++ class that manages a clipboard for various types of objects. The clipboard should be able to store and retrieve objects of different types, such as bitmaps, colors, and strings. Your task is to design and implement the `Clipboard` class with the following requirements:
1. The `Cl... | ```cpp
#include <vector>
#include <unordered_map>
#include "util/objects.hh"
#include "util/template-fwd.hh"
namespace faint {
class Clipboard {
public:
void addBitmap(const Bitmap& bitmap) {
bitmaps.push_back(bitmap);
}
void addColor(const ColRGB& color) {
colors.push_back(color);
}
... | magicoder | cpp |
You are tasked with implementing a class that utilizes the `AbortHandler` interface to manage a list of tasks. The `AbortHandler` interface contains a single method `isAbort()` that returns a boolean value indicating whether the task should be aborted. Your task is to implement the `TaskManager` class with the followin... | ```java
import java.util.List;
public class TaskManager {
public boolean executeTasks(List<Runnable> tasks, AbortHandler abortHandler) {
for (Runnable task : tasks) {
if (abortHandler.isAbort()) {
return false;
}
task.run();
}
return true;... | magicoder | java |
You are tasked with implementing a function that extracts specific information from a JSON-like data structure and formats it according to a given template. The data structure represents a user profile and a dynamic ID, and the template specifies how the extracted information should be formatted.
You are given the fol... | ```python
def format_user_info(content, template):
try:
formatted_string = template.format(
username=content["desc"]["user_profile"]["info"]["uname"],
id=content["desc"]["dynamic_id_str"]
)
return formatted_string
except KeyError:
return ""
```
The `forma... | magicoder | python |
You are tasked with implementing a caching mechanism for a Python program that defines circuits using the `Magma` hardware description language. The `@cache_definition` decorator is used to cache the results of circuit definition functions, preventing redundant computation when the same circuit is defined multiple time... | ```python
from collections import OrderedDict
from functools import wraps
def custom_cache(max_size):
cache = OrderedDict()
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
key = (args, frozenset(kwargs.items()))
if key in cache:
# Move th... | magicoder | python |
You are tasked with implementing a function that calculates the average score of students in a class based on the given data. The data is represented in a table format, and your function should parse the table and compute the average score. Each row of the table represents a student, and the last column of each row con... | ```python
from bs4 import BeautifulSoup
def calculate_average_score(html_table: str) -> float:
soup = BeautifulSoup(html_table, 'html.parser')
scores = []
for row in soup.find_all('tr'):
data = [td.get_text() for td in row.find_all('td')]
if data and data[-1].isdigit():
scores.a... | magicoder | python |
You are tasked with creating a Python class that simulates a simple moving average crossover trading algorithm. The algorithm will use historical stock price data to generate buy and sell signals based on the crossover of short-term and long-term moving averages. Your task is to implement the `SMACrossover` class with ... | ```python
import pandas as pd
class SMACrossover:
def __init__(self, short, long):
self.short = short
self.long = long
self.initial_capital = 0.0
self.mq_ip = ''
self.hook_ip = ''
self.hook_name = ''
self.trading_environment = ''
self.trading_universe... | magicoder | python |
You are tasked with creating a function that decodes a string encoded using the RFC 2047 standard. The RFC 2047 standard defines a method for encoding non-ASCII text in email headers, such as subject lines and addresses. The encoded string begins with "=?charset?encoding?encoded-text?=". For example, an encoded string ... | ```rust
extern crate rfc2047_decoder;
fn rfc2047_decoder(encoded_str: &[u8]) -> Result<String, rfc2047_decoder::DecodeError> {
let decoded = rfc2047_decoder::decode(encoded_str)?;
Ok(decoded)
}
fn main() {
let encoded_str = "=?UTF-8?Q?Hello_World?=";
let decoded_str = "Hello World";
assert_eq!(
... | magicoder | rust |
You are tasked with implementing a class that simulates an agent moving through an environment and collecting resources. The environment is represented as a 2D grid, and the agent can move up, down, left, or right within the grid. The agent has a "store" where it can collect resources from the environment. The agent ca... | ```python
class Agent:
def __init__(self, environment, x, y):
self.environment = environment
self._x = x
self._y = y
self.store = 0
def collect_resource(self):
if self.environment[self._y][self._x] > 10:
self.environment[self._y][self._x] -= 10
se... | magicoder | python |
You are tasked with creating a Python function that can load and run test cases from a given directory. The function should be able to identify and execute all the test cases present in the directory using the `unittest` framework.
Write a function `load_and_run_tests` that takes in a directory path as input and retur... | ```python
import os
import unittest
def load_and_run_tests(test_dir: str) -> str:
loader = unittest.defaultTestLoader
suite = unittest.TestSuite()
# Load all test cases from the specified directory
for file in os.listdir(test_dir):
if file.startswith("test_") and file.endswith(".py"):
... | magicoder | python |
You are tasked with implementing a custom request dispatcher for a web application framework. The request dispatcher is responsible for creating and managing the dispatching of requests to the appropriate resource methods. The framework uses the `wrappedProvider` to obtain the necessary resources for request handling.
... | ```java
public class CustomRequestDispatcher implements RequestDispatcher {
private final WrappedProvider wrappedProvider;
public CustomRequestDispatcher(WrappedProvider wrappedProvider) {
this.wrappedProvider = wrappedProvider;
}
@Override
public RequestDispatcher create(AbstractResourceM... | magicoder | java |
You are tasked with implementing a class for handling dipole data and performing operations on dipole objects. A dipole is a pair of equal and opposite point charges separated by a distance. The code snippet provided demonstrates the usage of the `Dipole` class and some related functions.
Your task is to create a Pyth... | ```python
import numpy as np
from numpy.testing import assert_allclose
class Dipole:
def __init__(self, times, data):
self.times = times
self.data = {'agg': data}
def write(self, filename):
np.savetxt(filename, self.data['agg'])
def read_dipole(filename):
data = np.loadtxt(filenam... | magicoder | python |
You are tasked with implementing a context manager in Python that handles exceptions and logs critical information. Your task is to create a class `ExceptionHandler` that acts as a context manager and logs critical information using the `caplog` fixture provided by the `pytest` testing framework. The `ExceptionHandler`... | ```python
import logging
import pytest
class ExceptionHandler:
def __enter__(self):
return self # Enter the context and return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
logging.critical(f"Exception occurred: {exc_value}") # Log the exceptio... | magicoder | python |
You are tasked with creating a script to automate the process of sending HTTP POST requests to an API endpoint and processing the responses. The API endpoint expects a JSON payload with specific parameters and returns a response that needs to be further processed.
Your script should iterate through a range of numbers ... | ```bash
for i in {1..100};
do
TEXT_INDEXED=$(curl --request POST -d '{"top_k": 10, "data": ["text:hey, dude message '$(echo $i)'"]}' -H 'Content-Type: application/json' '0.0.0.0:45678/api/index' | jq '.response_field') # Assuming jq is used for JSON parsing
# Process the TEXT_INDEXED data further as per the ... | magicoder | shell |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.