query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Swift function that handles the decoding of JSON data from an API response. Your function should take in the response data and a generic type `T` representing the expected type of the decoded object. The function should return a result type, either a success containing the decoded object ... | ```swift
enum BackendError: Error {
case parsing(reason: String)
}
func decodeResponse<T: Decodable>(_ response: Data?, _ type: T.Type) -> Result<T, Error> {
guard let responseData = response else {
print("didn't get any data from API")
return .failure(BackendError.parsing(reason: "Did not get ... | magicoder | swift |
You are tasked with implementing a simple command-line shell for a ternary computer system. The shell should support basic operations such as executing CPU instructions, assembling code, and converting between different number systems.
Your task is to implement the `Shell` class, which will serve as the core component... | ```cpp
#include <iostream>
#include "cpu.hpp"
#include "word.hpp"
#include "convert.hpp"
#include "assembler/assembler.hpp"
namespace ternary { namespace shell {
class Shell {
public:
void executeInstruction(const std::string& instruction) {
try {
// Assuming the existence o... | magicoder | cpp |
You are tasked with creating a Python function that dynamically registers modules for a web application. The web application uses a modular architecture, where different functionality is encapsulated within separate modules. Each module is represented as a Python module and is associated with a specific URL route.
You... | ```python
def register_modules(app, *modules):
for module in modules:
# Derive the URL route from the module name
route = '/' + module.__name__.split('.')[-1].replace('_', '-')
# Register the module with the web application using the derived route
app.register_module(module,... | magicoder | python |
You are tasked with creating a Python program to automate the process of generating a web page displaying movie information and trailers. The program should utilize the `youtube_search` library to search for the official trailer of each movie and update the `trailer_youtube_url` attribute of the movie object with the U... | ```python
import youtube_search
import webbrowser
import argparse
class Movie:
def __init__(self, title):
self.title = title
self.trailer_youtube_url = None
def youtube_search(movie_title):
search_result = youtube_search.search(movie_title + 'official trailer')
if search_result:
re... | magicoder | python |
You are tasked with implementing a user authentication system for a web application. The given code snippet is a part of a PHP class responsible for handling user authentication and rendering the login/logout links on the web page. The class contains a method `handleLogin` which is called when a user attempts to log in... | ```php
class UserAuthentication {
private $presenter;
private $logInTarget;
private $templateMain;
public function __construct($presenter, $logInTarget, $templateMain) {
$this->presenter = $presenter;
$this->logInTarget = $logInTarget;
$this->templateMain = $templateMain;
... | magicoder | php |
You are working on a deep learning project and are tasked with implementing a learning rate scheduler for training a neural network. The learning rate scheduler should gradually decrease the learning rate over a specified number of steps during training.
You are given the following code snippet as a starting point:
`... | ```python
import tensorflow as tf
def train_model(features, labels, learning_rate, num_epochs, batch_size):
# Define the neural network model using TensorFlow's high-level API
# Assuming model architecture is already defined
model = define_neural_network_model(features)
# Define the loss function usin... | magicoder | python |
You are tasked with implementing a simple virtual machine that executes instructions. The virtual machine has a `run` method that starts the execution and a `base` property that holds a base value. When the `run` method is called, it sets the `running` property to `true` and initializes the `cycles` property to 0. Howe... | ```rust
impl VirtualMachine {
fn run(&mut self, v: u8) {
if !self.running {
self.base = (v as u16) << 8;
self.running = true;
self.cycles = 0;
}
}
}
```
In the solution, the `run` method is implemented to check if the virtual machine is already running. If it'... | magicoder | rust |
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the account balance. Additionally, the class should keep track of the account holder's name and account number.
Create a class `BankAccount` with the f... | ```python
import random
class BankAccount:
def __init__(self, account_holder_name):
self.account_holder_name = account_holder_name
self.account_number = random.randint(100000, 999999)
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amo... | magicoder | python |
You are tasked with implementing a class that simulates a simple terminal using the SDL library. The provided code snippet is a constructor for the `SDLTerminal` class, which inherits from a `Terminal` class and takes a title as a parameter. The constructor sets the title and then conditionally sets the `dpiScale` and ... | ```cpp
#include <iostream>
#include <string>
#include <SDL2/SDL.h>
class Terminal {
// Define the Terminal class with necessary members and methods
};
class SDLTerminal : public Terminal {
private:
std::string title;
float dpiScale;
float fontScale;
public:
SDLTerminal(std::string title) : Termin... | magicoder | cpp |
You are tasked with implementing a custom error handling mechanism in Rust. Your goal is to create a custom error type and implement the necessary traits to enable error propagation and display.
Define a custom error type `TsError` that can represent different error cases. The error type should have an associated enum... | ```rust
use std::fmt;
use std::io;
// Define the TsErrorValue enum to represent different error cases
#[derive(Debug)]
pub enum TsErrorValue {
IOError(io::Error),
// Add more error variants as needed
}
// Define the TsError type to hold the error value
#[derive(Debug)]
pub struct TsError {
value: TsErrorV... | magicoder | rust |
You are working on a security application that involves encoding and decoding sensitive information. As part of this application, you need to implement a function to encode a given wallet ID and a code into a hexadecimal string using a specific encoding process. The encoding process involves concatenating the "open wal... | ```python
def encodeWallet(wallet, code):
concatenated_str = "open wallet " + wallet + code
encoded_hex = concatenated_str.encode('utf-8').hex()
return encoded_hex
# Test the function
wallet = "myWallet123"
code = "ABC456"
print(encodeWallet(wallet, code)) # Output: '6f70656e2077616c6c6574206d7957616c6c65... | magicoder | python |
You are working on a movie recommendation system that uses collaborative filtering techniques. The code snippet provided is a part of the backend logic for processing user input and generating movie recommendations. The system allows users to rate a list of movies and select a recommendation method, either user-user co... | ```python
import numpy as np
def user_user_cf(user_ratings, movies_list):
# Calculate user-user similarity matrix
user_similarity = np.dot(user_ratings, user_ratings.T) / (np.linalg.norm(user_ratings) * np.linalg.norm(user_ratings.T))
# Find the most similar user to the current user
most_similar_user ... | magicoder | python |
You are tasked with implementing a file export feature for a web application. The `export` method is part of a controller class and is responsible for exporting data associated with a specific ID. The method is expected to retrieve the data, format it, and then return a downloadable file to the user. However, the code ... | ```php
public function export($id)
{
try {
// Retrieve data associated with the given ID from the database
$data = YourModel::find($id);
if (!$data) {
return $this->errorResponse('Data not found for the given ID');
}
// Format the data into a suitable file forma... | magicoder | php |
You are given a class `PalindromeChecker` with a method `isPalindrome` that takes a string as input and returns `true` if the input string is a palindrome, and `false` otherwise. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuatio... | ```java
public class PalindromeChecker {
public boolean isPalindrome(String input) {
// Remove non-alphanumeric characters and convert to lowercase
String cleanInput = input.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
// Check if the clean input is a palindrome
int left = ... | magicoder | java |
You are tasked with creating a function that processes data from a Firestore database and returns a structured object representing a book. The function should take in a Firestore document snapshot and extract the necessary fields to construct the book object.
You are provided with a code snippet that shows the end of ... | ```swift
import FirebaseFirestore
func processFirestoreBookDocument(document: DocumentSnapshot) -> FirestoreGetBook? {
guard let data = document.data(),
let id = data["id"] as? String,
let title = data["title"] as? String,
let author = data["author"] as? String,
let imageURL... | magicoder | swift |
You are tasked with creating a validation rule for a new feature in a web application. The application allows users to create new pages with titles, categories, and content. The code snippet provided is a part of a Laravel controller that handles the creation of new pages. The `create` method is responsible for validat... | ```php
// Custom validation rule class
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\Page;
class UniquePageTitleInCategory implements Rule
{
protected $category_id;
public function __construct($category_id)
{
$this->category_id = $category_id;
}
public function p... | magicoder | php |
You are tasked with creating a command-line utility that simulates the behavior of the `rm` command in Unix-based systems. The utility should be able to handle the removal of multiple directories and their contents. Your task is to implement a function that takes a list of directory paths as input and simulates the rem... | ```python
import os
def simulate_rm_directories(directory_paths):
for directory_path in directory_paths:
if os.path.exists(directory_path):
for root, dirs, files in os.walk(directory_path, topdown=False):
for file in files:
os.remove(os.path.join(root, file))... | magicoder | python |
You are tasked with implementing a Markdown scanner that checks for the presence of valid emphasis sequences in a given document. An emphasis sequence in Markdown is denoted by either asterisks (*) or underscores (_) surrounding a word or phrase. For example, `*emphasis*` or `_emphasis_` are valid emphasis sequences.
... | ```python
import re
def has_valid_emphasis(document: str) -> bool:
emphasis_pattern = r'(\*{1,2}|_{1,2})\S+\1'
return bool(re.search(emphasis_pattern, document))
```
The `has_valid_emphasis` function uses a regular expression pattern to search for valid emphasis sequences in the input `document`. The pattern ... | magicoder | python |
You are given a code snippet that seems to be part of a program that deals with Fibonacci numbers and flower orders. Your task is to complete the program by implementing the missing part of the code.
You need to write a function that takes two integers `n` and `k` as input and returns a string representing the result ... | ```cpp
#include <iostream>
#include <vector>
using namespace std;
// Function to calculate the Fibonacci sequence up to a certain index
void calculateFibonacci(vector<long long>& fib, int n) {
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
}
// Funct... | magicoder | cpp |
You are tasked with creating a Python program to simulate a simple banking system. The system should have classes for Bank, Account, and Transaction. The Bank class should be responsible for managing accounts and processing transactions. The Account class should represent a bank account with attributes for the account ... | ```python
import uuid
from datetime import datetime
class Bank:
def __init__(self):
self.accounts = {}
def create_account(self, account_holder_name):
account_number = str(uuid.uuid4())[:8] # Generate a unique account number
new_account = Account(account_number, account_holder_name)
... | magicoder | python |
You are tasked with implementing a Python function that compares the configuration of a CTCBeamDecoder object with a protobuf configuration. The CTCBeamDecoder is a class that is used for performing beam search decoding for connectionist temporal classification (CTC) tasks, and the protobuf configuration is a serialize... | ```python
from tests.protos.test_ctc_beam_decoder import ctc_beam_decoders
from tests.protos import ctc_beam_decoder_pb2
class CTCBeamDecoder:
def __init__(self, blank_index):
self.blank_index = blank_index
def ctc_beam_decoder_module_match_cfg(
ctc: CTCBeamDecoder, ctc_cfg: ctc_beam_decoder_pb2.CTC... | magicoder | python |
You are given a string `name` containing a lowercase word. Your task is to write a function `reverse_vowels` that reverses the vowels in the given string. The vowels are 'a', 'e', 'i', 'o', and 'u'. The function should return the modified string with the reversed vowels while keeping the consonants in their original po... | ```python
def reverse_vowels(name: str) -> str:
vowels = set('aeiou')
name_list = list(name)
left, right = 0, len(name_list) - 1
while left < right:
while name_list[left] not in vowels and left < right:
left += 1
while name_list[right] not in vowels and left < right:
... | magicoder | python |
You are tasked with implementing a custom error message handling system for a web application. The `getErrorMessage` method is responsible for returning an appropriate error message based on the error code provided. The error codes and their corresponding messages are stored in a map. If the error code is not found in ... | ```java
public String getErrorMessage(int errorCode) {
return errorMessages.getOrDefault(errorCode, "An error occurred");
}
```
In the solution, the `getErrorMessage` method uses the `getOrDefault` method of the `Map` interface to retrieve the error message based on the provided error code. If the error code is fo... | magicoder | java |
You are tasked with creating a script to automate the backup of Juju environment configuration files. Juju is a cloud orchestration tool that uses configuration files to define and manage cloud environments. The provided code snippet is a part of a larger script that checks for the existence of specific configuration f... | ```python
import os
import shutil
juju_dir = os.path.expanduser("~/.juju")
# Check for environments.yaml in ~/.juju directory
environments_yaml_path = os.path.join(juju_dir, "environments.yaml")
if os.path.isfile(environments_yaml_path):
shutil.copy(environments_yaml_path, "environments.yaml")
# Check for deploy... | magicoder | python |
You are tasked with creating a Python function that calculates the memory consumption of the calling process in megabytes. The function should utilize the `resource` module to obtain memory usage information and return the result in megabytes.
Your task is to implement the `get_memory_usage` function, which takes no a... | ```python
import sys
import resource
def get_memory_usage():
"""
Get memory usage for the calling process.
Return:
memory consumption for calling process in MB's.
"""
rusage_denom = 1024.00
if sys.platform == "darwin":
denom = 1.0
else:
denom = rusage_denom
usa... | magicoder | python |
You are working on a software module that involves interpolation and data manipulation. The given code snippet is part of a larger program that uses an interpolation object `mInterp` to perform interpolation on some data `mData2`. The interpolated values are then used to update an array `mCoeff` with the calculated val... | ```cpp
void updateCoefficients(Interpolation* mInterp, Data* mData2, Point aPIm2, double* mCoeff, int NumAB) {
Pt3dr aNewVD2 = mInterp->GetValDer(mData2, aPIm2);
double aV2 = aNewVD2.z;
mCoeff[NumAB] = aV2;
}
``` | magicoder | cpp |
You are tasked with implementing a class that manages network configurations for a system. The class has a method `badrequesttest` that takes a list of commands and returns the output of executing those commands. The snippet provided is a part of the implementation of this class. The `net` variable is assigned the valu... | ```python
class NetworkManager:
def __init__(self, net):
self.net = net
def badrequesttest(self, command):
# Implement the logic to execute the commands and return the output
# This could involve interacting with the system's network configuration
# and handling any errors or ex... | magicoder | python |
You are given a list of lists representing a Denavit-Hartenberg (DH) parameter table for a robotic arm. Each inner list contains four elements representing the DH parameters (a, alpha, d, theta) for a specific joint of the robotic arm. The DH parameters are used to describe the geometry and kinematics of the robot's li... | ```python
import numpy as np
def calculate_transformation_matrix(dh):
transformation_matrix = np.identity(4)
for params in dh:
a, alpha, d, theta = params
cos_theta = np.cos(theta)
sin_theta = np.sin(theta)
cos_alpha = np.cos(alpha)
sin_alpha = np.sin(alpha)
tra... | magicoder | python |
You are tasked with implementing a simplified version of an asynchronous setup and unload mechanism for a home automation system. The system manages various devices and their associated entities, such as sensors. Your goal is to create a Python function that sets up a new sensor entry and another function that unloads ... | ```python
# Import necessary modules
import logging
# Define the logger
LOGGER = logging.getLogger(__name__)
# Define the async_setup_entry function
async def async_setup_entry(hass: object, config_entry: object, async_add_devices):
device_id = config_entry.data[CONF_DEVICE_ID]
device = hass.data[DOMAIN].devi... | magicoder | python |
You are tasked with creating a program that analyzes a given PHP file and counts the number of namespaces and traits used in the file. A namespace in PHP is used to organize code into a logical hierarchy, while a trait is a group of methods that can be included within a class. Your program should be able to read a PHP ... | ```python
import re
def count_namespaces_and_traits(file_path):
with open(file_path, 'r') as file:
content = file.read()
namespace_count = len(re.findall(r'namespace\s+[\w\\]+;', content))
trait_count = len(re.findall(r'use\s+[\w\\]+;', content))
print(f"Namespaces: {namespace_count}")
pr... | magicoder | python |
You are tasked with creating a Python function that dynamically imports a module and executes a specific function within that module. Your function should take the module name and the function name as input and return the result of executing the specified function from the module.
Write a Python function called `execu... | ```python
def execute_module_function(module_name, function_name):
import importlib
try:
module = importlib.import_module(module_name)
function = getattr(module, function_name)
result = function()
return result
except ModuleNotFoundError:
return f"Module '{module_nam... | magicoder | python |
You are tasked with creating a class that represents a model for internal identifiers related to vaccine tracing. The class should have specific attributes and functionality to manage these identifiers effectively.
Create a PHP class called `InternalIdentifier` that meets the following requirements:
- The class should... | ```php
<?php
namespace VaccineTracing;
class InternalIdentifier
{
protected $table = 'internal_identifiers';
protected $connection = 'tracing';
protected $fillable = ['identifier', 'name', 'unit', 'vaccine_count'];
protected $dates = [
'created_at',
'updated_at',
];
public fun... | magicoder | php |
You are tasked with implementing a method to retrieve information about Docker containers using the Docker CLI. The Docker CLI (Command Line Interface) is a command-line tool for interacting with Docker containers and images. Your goal is to complete the implementation of the `test_docker_cli_get_containers` method, wh... | ```python
def test_docker_cli_get_containers(self):
docker = DockerCli()
containers = docker.get_containers()
self.assertIsInstance(containers, list)
for container in containers:
self.assertIsInstance(container, dict)
self.assertIn('image', container)
self.assertIn('port', contai... | magicoder | python |
You are tasked with implementing a utility class for handling response callbacks in a TypeScript application. The utility class should provide methods for processing the result, executing a callback after receiving a response, and handling exceptions.
Your task is to create a TypeScript class called `ResponseHandler` ... | ```typescript
type RespCallbackOptions<T> = {
// Define the properties required for processing the result and executing the callback after response
}
type ProcessExCallbackOptions = {
// Define the properties required for handling exceptions
}
class ResponseHandler {
processResult = <T = unknown>(options: RespC... | magicoder | typescript |
You are tasked with implementing a Python class for managing JSON Web Key (JWK) operations. A JSON Web Key is a JSON data structure representing a cryptographic key. The class should support the following functionalities:
1. Define an enumeration class `JsonWebKeyCurveName` to represent the elliptic curve names used i... | ```python
from enum import Enum
import json
class JsonWebKeyCurveName(str, Enum):
p_256 = "P-256"
p_384 = "P-384"
p_521 = "P-521"
p_256_k = "P-256K"
class JsonWebKeyOperation(str, Enum):
sign = "sign"
verify = "verify"
encrypt = "encrypt"
decrypt = "decrypt"
class JsonWebKey:
def ... | magicoder | python |
You are tasked with implementing a custom test case handler for a testing framework. The `testcase` object has a method `handle` which takes a `proc` parameter. Additionally, there is a `TestExceptionHandler` class with a method `assert_exc_msg` that takes the `testcase` object and a tuple containing strings as paramet... | ```python
class CustomTestCaseHandler:
def __init__(self, testcase):
self.testcase = testcase
def handle_exception(self, exc_msg):
self.testcase.exception = f'Exception: {exc_msg} has failed!'
class TestExceptionHandler:
@staticmethod
def assert_exc_msg(testcase, exc_tuple):
ex... | magicoder | python |
You are tasked with implementing a custom random number generator class in C++. The class should have the ability to generate random numbers using the Mersenne Twister algorithm, and it should provide a method to seed the generator with a given value.
Your task is to complete the implementation of the `CustomRandomGen... | ```cpp
#include <iostream>
#include <random>
class CustomRandomGenerator {
private:
std::mt19937_64 randomGenerator;
public:
void Seed(unsigned long long seedValue) {
randomGenerator.seed(seedValue);
}
unsigned long long GenerateRandomNumber() {
return randomGenerator();
}
};
int... | magicoder | cpp |
You are tasked with creating a function that reverses the order of words in a given string. Your function should take a string as input and return a new string with the words in reverse order. A word is defined as a sequence of non-space characters.
For example, given the input string "Hello world, how are you?", the ... | ```java
public class ReverseWords {
public static String reverseWords(String input) {
String[] words = input.split("\\s+"); // Split the input string into an array of words
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversed.appen... | magicoder | java |
You are tasked with implementing a function that converts an epoch into a bit representation. An epoch is represented by a struct `Epoch` containing a vector of public keys. Each public key is a string of alphanumeric characters. The function should take an epoch as input and return a bit representation of the public k... | ```rust
struct Epoch {
public_keys: Vec<String>,
}
fn epoch_to_bits(epoch: &Epoch) -> Vec<u8> {
let mut result = Vec::new();
for key in &epoch.public_keys {
let key_length = key.len() as u8;
result.extend(&key_length.to_be_bytes()); // Convert key length to big-endian bytes
for ch i... | magicoder | rust |
You are given a DataFrame `dataTable` containing numerical and NaN (Not a Number) values. Your task is to implement a function `fillna_and_transform` that performs the following operations:
1. Fill all NaN values in the DataFrame with 0.
2. Unstack the DataFrame and add 1 to each value.
The function should take the Da... | ```python
import pandas as pd
import numpy as np
def fillna_and_transform(dataTable: pd.DataFrame) -> pd.DataFrame:
dataTable.fillna(0, inplace=True) # Fill NaN values with 0
transformed_data = (dataTable.stack() + 1).unstack() # Unstack the DataFrame and add 1 to each value
return transformed_data
``` | magicoder | python |
You are tasked with implementing a custom `asDriver` function for a reactive programming framework. The `asDriver` function should convert a stream of events into a `Driver`, which is a special kind of observable sequence that represents a value or error that never fails. The `asDriver` function should take into accoun... | ```swift
struct Driver<T> {
// Implementation details of Driver
}
extension Observable {
func asDriver() -> Driver<E> {
return self.asDriver(onErrorJustReturn: Void())
}
}
```
The `asDriver` function is implemented to return a `Driver` by using the `asDriver` method provided by the reactive progra... | magicoder | swift |
You are tasked with implementing a custom interceptor for a network request handling system. The interceptor is responsible for intercepting and modifying the request and response during the network call. Your task is to create a class that implements the interceptor interface and handles the interception logic.
Your ... | ```java
public class CustomInterceptor implements Interceptor {
private boolean proceedCalled = false;
@Override
public Response intercept(Request request) {
// Your interception logic goes here
// Ensure to call proceed() exactly once
// Return the modified response or null if need... | magicoder | java |
You are tasked with implementing a Python function that simulates a simple text-based adventure game. The game will involve navigating through different rooms, interacting with objects, and making decisions that affect the outcome of the game.
Your task is to implement the `adventure_game` function, which takes a list... | ```python
def adventure_game(rooms):
current_room = rooms[0]
end_room = rooms[-1]["name"]
while True:
direction = input("Choose a direction to move in: ").lower()
if direction in current_room["exits"]:
next_room_name = current_room["exits"][direction]
for room in... | magicoder | python |
You are tasked with implementing a string manipulation function that inserts a given substring into another string at a specified position. The function should take the original string, the substring to be inserted, the position at which to insert the substring, and return the modified string.
You are given the follow... | ```csharp
public static string InsertSubstring(string original, string substring, InsertPosition position)
{
if (position == InsertPosition.Start)
{
return substring + original;
}
else if (position == InsertPosition.End)
{
return original + substring;
}
else
{
thr... | magicoder | csharp |
You are tasked with implementing a function that calculates the total number of unique paths to reach the bottom-right corner of a grid from the top-left corner. You can only move either down or to the right at any point in time. The grid is represented by a 2D array where 1 indicates an obstacle and 0 indicates an emp... | ```python
from typing import List
def unique_paths_with_obstacles(obstacle_grid: List[List[int]]) -> int:
m, n = len(obstacle_grid), len(obstacle_grid[0])
# If the starting point or the ending point has an obstacle, return 0
if obstacle_grid[0][0] == 1 or obstacle_grid[m-1][n-1] == 1:
return 0... | magicoder | python |
You are tasked with implementing a class for managing categories and subcategories in a software application. The provided code snippet is a constructor for the `Category` class, which initializes the category name and a collection of subcategories.
Your task is to complete the implementation of the `Category` class b... | ```csharp
using System;
using System.Linq;
public class Category
{
private byte[] _name;
public BindableCollection<SubCategory> SubCategories { get; }
public Category()
{
_name = "NULL".ToBytes("Unicode", 128);
SubCategories = new BindableCollection<SubCategory>();
}
public vo... | magicoder | csharp |
You are given a 2D binary matrix of size N x N, where each cell contains either 0 or 1. The matrix represents a map of a region, where 1s represent land and 0s represent water. A group of connected 1s forms an island. Two 1s are considered connected if they are adjacent horizontally or vertically (not diagonally). Your... | ```python
from typing import List
def countDistinctIslands(grid: List[List[int]]) -> int:
def dfs(grid, i, j, path, direction):
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0:
return '0'
grid[i][j] = 0
path += direction
path = dfs(grid, i+1, ... | magicoder | python |
You are tasked with implementing a Python module that calculates the Fibonacci sequence. 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 module should provide a function called `fibonacci` that takes an integer `n` as input and ... | ```python
# fibonacci.py
def fibonacci(n):
if n == 0:
return 0
elif n == 1 or n == -1:
return 1
else:
a, b = 0, 1
if n < 0:
for _ in range(1, abs(n)):
a, b = b - a, a
return a
else:
for _ in range(n - 1):
... | magicoder | python |
You are given a Rust code snippet that contains a struct `S` with fields `x` and `y` of type `i32`, and a struct `T`. The code also includes two conditional statements using pattern matching and the `PartialEq` trait.
Your task is to understand the code and identify the issues in the conditional statements. Then, you ... | The issues in the given code are as follows:
1. In the first conditional statement, the pattern matching is incorrect. It's trying to match the value of `y` with `2` directly, which is not allowed. The correct pattern matching should be done using the `if let` statement with a tuple pattern.
2. In the second conditio... | magicoder | rust |
You are tasked with implementing a text checker class that can identify and validate plaintext content. The class should be able to check for errors in the provided text and generate a thumbnail representation if requested. Your task is to create a Python class that fulfills these requirements and write a method to che... | ```python
from pathlib import Path
class Request:
def __init__(self, realpath: Path, thumb: bool):
self.realpath = realpath
self.thumb = thumb
class Result:
def __init__(self, recognizer, errors, thumb):
self.recognizer = recognizer
self.errors = errors
self.thumb = thu... | magicoder | python |
You are tasked with implementing a function to compute the Histogram of Oriented Gradients (HOG) for an image. The HOG is a feature descriptor used in computer vision and image processing for object detection. Your goal is to create a Python function that takes an input image and computes its HOG representation. The HO... | ```python
import numpy as np
import cv2
def compute_hog(image):
if image.shape[0] <= 0 or image.shape[1] <= 0:
raise ValueError("negative dimensions are not allowed")
# Compute HOG using OpenCV
win_size = (image.shape[1] // 8 * 8, image.shape[0] // 8 * 8)
block_size = (16, 16)
block_stride... | magicoder | python |
You are tasked with implementing a Kafka Avro sink test for a data pipeline system. The `TestKafkaAvroSink` class contains a method `test_kafka_avro_sink` that needs to be completed. The method takes two parameters: `kafka` and `schema_registry`, which are instances of the Kafka client and Schema Registry client, respe... | ```python
from avro import schema, io
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter
import io
import requests
class TestKafkaAvroSink:
def test_kafka_avro_sink(self, kafka, schema_registry):
# Define Avro schema for the data
avro_schema = {
... | magicoder | python |
You are tasked with implementing a method to calculate the histogram of object sizes based on a given query in a Python class. The class contains a method `getObjectSizeHistogram` that takes in a query string `q` and the number of bins `nbins`. The method should return a list of lists, where each inner list contains th... | ```python
class ObjectAnalyzer:
def __init__(self, state):
self.state = state
def _countAll(self, counts, as_of_date):
# Implementation for counting all objects
pass
def _countSOLR(self, counts, col, fq, as_of_date):
# Implementation for counting objects using SOLR
... | magicoder | python |
You are tasked with creating a Python function to calculate the dN/dS ratio for a given set of DNA sequences. The dN/dS ratio, also known as the Ka/Ks ratio, is a measure of the relative rates of nonsynonymous (amino acid-changing) and synonymous (silent) substitutions in DNA sequences. This ratio is often used to infe... | ```python
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_dna
from Bio.Data import CodonTable
from collections import Counter
def calculate_dnds_ratio(vcf_file, genbank_file):
# Parse the GenBank file to extract the coding sequences
coding_sequ... | magicoder | python |
You are tasked with implementing a Java program that simulates a simple benchmarking tool for measuring the performance of different sorting algorithms. The program should allow the user to select a sorting algorithm, input an array of integers, and then measure the time taken to sort the array using the chosen algorit... | ```java
import java.util.Arrays;
public class BenchmarkTool {
private String selectedAlgorithm;
private int[] sortedArray;
private long sortingTime;
public void selectAlgorithm(String algorithm) {
this.selectedAlgorithm = algorithm;
}
public void sortArray(int[] arr) {
long st... | magicoder | java |
You are tasked with creating a Rust library that provides HTTP client functionality using the popular `reqwest` crate. Your library should support making GET and POST requests to specified URLs and handling the responses appropriately. Additionally, the library should allow users to set custom headers for the requests.... | ```rust
// Cargo.toml
// Ensure that the reqwest feature is enabled in the library's Cargo.toml file
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
// lib.rs
#[cfg(feature = "reqwest")]
pub mod reqwest {
use reqwest::blocking::Client;
use reqwest::header::HeaderMap;
pub struct HttpClie... | magicoder | rust |
You are given a string `nume2` representing the name of a computer graphics card. The string consists of alphanumeric characters and underscores. Your task is to write a function `extract_graphics_card_info` that takes `nume2` as input and returns a dictionary containing the extracted information about the graphics car... | ```python
def extract_graphics_card_info(nume2):
info = {}
parts = nume2.split('_')
if len(parts) >= 2:
info['brand'] = parts[0]
info['model'] = '_'.join(parts[1:])
return info
# Test the function
nume2 = "Geforce_RTX_2080TI"
print(extract_graphics_card_info(nume2)) # Output: {'brand':... | magicoder | python |
You are tasked with implementing a Python decorator that can be used to protect a Flask route with multiple authentication methods. The decorator should allow the route to be accessed only if at least one of the specified authentication methods is successful. The authentication methods are provided as arguments to the ... | ```python
from functools import wraps
from flask import request
from auth.oauth import validate_bearer_auth
from auth.cookie import validate_session_cookie
from auth.signedgrant import validate_signed_grant
from util.http import abort
def multi_auth_required(*auth_methods):
def decorator(func):
@wraps(func... | magicoder | python |
You are tasked with creating a program that simulates a simple banking system. The system should be able to create new bank accounts, perform deposits and withdrawals, and provide the account balance.
Create a class `BankAccount` with the following functionalities:
- A constructor that takes the initial balance as a p... | ```python
class BankAccount:
def __init__(self, initial_balance):
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
print("Insufficient... | magicoder | python |
You are tasked with implementing a reusable identifier generator for UICollectionView cells and supplementary views in Swift. The provided code snippet includes an extension for UICollectionReusableView that defines a method to generate a reusable identifier based on the class name.
Your task is to create a Swift prot... | ```swift
// Define the Reusable protocol
protocol Reusable {
static var reusableIdentifier: String { get }
}
// Extend Reusable protocol to provide default implementation for reusableIdentifier
extension Reusable {
static var reusableIdentifier: String {
return String(describing: self)
}
}
// Exam... | magicoder | swift |
You are tasked with creating a Python function to batch convert images from one format to another. The function should take in the input path, specific format, output path, and the desired format as parameters. The function should iterate through all the images in the input path with the specific format, convert them t... | ```python
import os
from PIL import Image
def batch_convert(input_path, specific_format, output_path, format):
failed = 0
succeeded = 0
images = utils.System.files_tree_list(input_path, extensions=[specific_format])
print("~ Total found images: {}".format(len(images)))
for image_path in images:
... | magicoder | python |
You are tasked with creating a program to manage employee records in a company. The program should be able to add new employees, retrieve employee information, and filter employees based on specific criteria.
You are given a Python class `Employee` with the following attributes:
- `name` (string): the name of the emp... | ```python
class Employee:
def __init__(self, name, department, full_time):
self.name = name
self.department = department
self.full_time = full_time
class EmployeeDatabase:
def __init__(self):
self.employees = []
def add_employee(self, name, department, full_time):
n... | magicoder | python |
You are tasked with implementing a class that represents a simplified version of a leaderboard for an online game. The class should have the ability to add new player scores, retrieve the top N players, and calculate the average score of all players.
You are provided with a partial code snippet for the leaderboard cla... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace GameLeaderboard
{
public class Leaderboard
{
private Dictionary<string, int> playerScores = new Dictionary<string, int>();
public void AddScore(string playerName, int score)
{
if (playerS... | magicoder | csharp |
You are tasked with implementing a function to handle errors in a cloud storage system. The function should catch a specific type of exception and then check if the HTTP status code associated with the exception is equal to 404 (Not Found). If the status code is 404, the function should perform a specific action. Your ... | ```python
class StorageException:
def __init__(self, request_information):
self.RequestInformation = request_information
def handleStorageException(e):
if e.RequestInformation.HttpStatusCode == 404:
return "Resource not found"
else:
return "Other storage exception"
# Test cases
e1 ... | magicoder | python |
You are tasked with creating a Python function that utilizes the given code snippet to implement a user authentication system. The code snippet includes imports from various modules such as `services.tasks`, `models.users`, and `services.auth`. The `TaskService` class from `services.tasks` is used to perform tasks, the... | ```python
from services.tasks import TaskService
from models.users import User
from services.auth import get_current_user
def authenticate_user(username, password):
task_service = TaskService()
user = task_service.find_user_by_username(username)
if user is None:
return "User not found"
eli... | magicoder | python |
You are tasked with creating a program that reads and analyzes a file containing license information for various software packages. The file contains license details for different software components, and your program needs to extract and process this information.
The file format is as follows:
- Each software compone... | ```python
import re
def extractLicenseInfo(file_path):
with open(file_path, 'r') as file:
content = file.read()
pattern = r'/\*(.*?)\*/'
matches = re.findall(pattern, content, re.DOTALL)
license_info_list = []
for match in matches:
info = {}
lines = match.split('\n')
... | magicoder | python |
You are tasked with implementing a simple tree data structure in Rust. The tree consists of nodes that can be of different kinds: `Root`, `Child`, or `Free`. Each node type has specific attributes and behaviors associated with it.
The `Kind` enum represents the different kinds of nodes in the tree. The `Root` variant ... | ```rust
use std::rc::Rc;
#[derive(Debug)]
struct TextSize;
struct GreenNode;
struct SyntaxNode;
struct NodeData;
enum Kind {
Root(GreenNode),
Child { parent: SyntaxNode, index: u32, offset: TextSize },
Free { next_free: Option<Rc<NodeData>> },
}
impl Kind {
fn as_child(&self) -> Option<(&SyntaxNod... | magicoder | rust |
You are tasked with implementing a stack data structure using a linked list. You need to create a class `Stack` with the following methods:
1. `push(value)`: Add a new element to the top of the stack.
2. `pop()`: Remove and return the element from the top of the stack.
3. `peek()`: Return the element at the top of the ... | ```java
class Node {
int data;
Node next;
Node(int value) {
data = value;
next = null;
}
}
public class Stack {
private Node top;
public Stack() {
top = null;
}
public void push(int value) {
Node newNode = new Node(value);
newNode.next = top;
... | magicoder | java |
You are tasked with implementing a simple network protocol for data transmission using the Vegas congestion control algorithm. Vegas is a delay-based congestion avoidance algorithm that aims to achieve high throughput while maintaining low network latency. The sender and receiver will communicate over a specified port ... | ```python
# Sender implementation using Vegas congestion control algorithm
class VegasSender:
def __init__(self, port):
self.port = port
# Initialize sender state variables
# ...
def send_data(self, data):
# Implement Vegas congestion control algorithm for data transmission
... | magicoder | python |
You are tasked with implementing a function that calculates the average value of elements in a specified rectangular region of a 2D array. The function should take in the 2D array and the coordinates of the rectangular region, and return the average value of the elements within that region.
You are given the following... | ```python
import numpy as np
def average_in_region(arr, top_left, bottom_right):
region = arr[top_left[0]:bottom_right[0]+1, top_left[1]:bottom_right[1]+1]
return np.mean(region)
# Example usage
arr = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])
top_left... | magicoder | python |
You are tasked with implementing a simplified version of a bytecode generator for an interpreter. The bytecode generator is responsible for converting high-level code into a lower-level representation that can be executed by a virtual machine. In this problem, you will focus on the initialization and destruction of the... | ```cpp
#include "src/scopes.h"
#include "src/token.h"
namespace v8 {
namespace internal {
namespace interpreter {
class BytecodeGenerator {
public:
// Constructor for the BytecodeGenerator class
BytecodeGenerator(Isolate* isolate, Zone* zone)
: builder_(isolate) {
InitializeAstVisitor(isolate, zone);
... | magicoder | cpp |
You are tasked with creating a Python program that performs linting on Python files within a specified directory. The program should use regular expressions to filter out only Python files and then apply a linting function to each file. The linting function should be dynamically created and added as a method to a class... | ```python
import os
import re
class TestLint:
pass # Placeholder for the TestLint class
def lint(self, path):
# Implement the linting process here
pass # Placeholder for the linting process
srcdir = os.path.join(os.path.dirname(__file__), '..') # Assuming this code is within a Python file
regex = re.c... | magicoder | python |
You are tasked with implementing a data structure and associated methods for managing digital-to-analog converter (DAC) points in a streaming application. The `DacPoint` struct represents a single point in the DAC stream and contains various properties related to the streaming process. Your goal is to create methods to... | ```python
from enum import Enum
class DacStatus(Enum):
SOURCE_NETWORK_STREAMING = 1
class DacPoint:
def __init__(self, source, light_engine_flags, playback_flags, source_flags, buffer_fullness, point_rate, point_count):
self.source = source
self.light_engine_flags = light_engine_flags
... | magicoder | python |
You are given two strings, `x` and `y`. Your task is to find the length of the longest common substring between `x` and `y`. A substring is a contiguous sequence of characters within a string.
Write a function `longest_common_substring(x, y)` that takes in two strings `x` and `y` and returns the length of the longest ... | ```python
def longest_common_substring(x, y):
m = len(x)
n = len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
max_length = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
max_length =... | magicoder | python |
You are tasked with creating a program that generates a random order of presentation for a list of participants in a competition. The program should take a list of participant names as input and then output the random order in which they will present.
Write a Python function called `generate_presentation_order` that t... | ```python
import random
def generate_presentation_order(participants):
random.shuffle(participants)
return participants
# Example usage
participants = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
presentation_order = generate_presentation_order(participants)
print('The order of presentation will be:')
print(pr... | magicoder | python |
You are tasked with creating a Python function that generates a migration script for a hypothetical database migration tool. The migration script should be able to handle the creation of new tables and the addition of new fields to existing tables.
Your function should take in a list of migration operations, where eac... | ```python
def generate_migration_script(operations):
script = "# -*- coding: utf-8 -*-\n"
script += "# Generated by CustomMigrationTool 1.0\n"
script += "from __future__ import unicode_literals\n\n"
script += "from django.db import migrations, models\n\n"
script += "class Migration(migrations.Migrat... | magicoder | python |
You are tasked with creating a Python function that extracts information from a given Python module and generates a summary of the module's contents. The module contains functions for converting data from one format to another, and the summary should include details about the functions and their dependencies.
Write a ... | ```python
import ast
import os
def generate_module_summary(module_path):
summary = {
"functions": [],
"imports": [],
"unused_functions": [],
"used_functions": []
}
with open(module_path, "r") as file:
module_content = file.read()
tree = ast.parse(module_content... | magicoder | python |
You are tasked with creating a function that processes and validates regular expressions against given strings. The function should take a regular expression pattern and a string as input and return a specific output based on the matching results.
You are given the following code snippet as a reference:
```cpp
REQUIR... | The `re_show` function can be implemented using the following C++ code:
```cpp
#include <regex>
#include <string>
#include <vector>
#include <sstream>
std::string re_show(const std::string& pattern, const std::string& input) {
std::regex re(pattern);
std::smatch match;
std::stringstream result;
while... | magicoder | cpp |
You are tasked with implementing a function that calculates a specific metric for a given dataset. The function takes in several parameters and returns the calculated metric. Your task is to understand the function's requirements and implement it according to the given specifications.
The function call is as follows:
... | ```python
def metric_calc(df, groupby, position, player_ids, work_columns):
# Perform the necessary data filtering based on position and player_ids
filtered_data = df[(df['position'] == position) & (df['player_id'].isin(player_ids))]
# Group the filtered data based on the specified groupby column(s)
... | magicoder | python |
You are tasked with creating a simplified version of a task scheduling system. The system should allow users to schedule tasks to be executed at a later time. Each task is represented by a `Task` object, which has a `run` method that performs the task's functionality. Additionally, the system should handle any runtime ... | ```java
import java.util.ArrayDeque;
import java.util.Queue;
public class Scheduler {
private static Scheduler instance = new Scheduler();
private Queue<Task> taskQueue;
private Scheduler() {
taskQueue = new ArrayDeque<>();
}
public static Scheduler get() {
return instance;
}
... | magicoder | java |
You are working on a system that tracks and stores trajectory data for various deployments. The code snippet provided is a part of a function that is responsible for writing the trajectory data to a JSON file. The function takes two parameters: `deployment`, a dictionary containing deployment information, and `geo_data... | ```python
import os
import json
def write_trajectory(deployment, geo_data):
trajectory_dir = app.config.get('TRAJECTORY_DIR')
username = deployment['username']
name = deployment['name']
dir_path = os.path.join(trajectory_dir, username)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
... | magicoder | python |
You are tasked with implementing a class that represents a slot entry in a game's item transformation system. The class should handle slot selection, sacrifice item setting, button events, pre-construction, and execution of the item transformation process.
Your task is to create a C++ class `ItemTransformSlotEntry` th... | ```cpp
#include "CommonButton.h"
#include "FortItem.h"
class UFortItem;
class ItemTransformSlotEntry
{
public:
void SetSlotSelection(bool Selected) {
// Implementation to set the selection state of the slot
}
void SetSacrificeItem(class UFortItem* SelectedSacrificeItem) {
// Implementatio... | magicoder | cpp |
You are tasked with creating a class that represents a television. The television class should have properties to store the current channel and a method to change the channel. Additionally, you need to implement a method to display the current channel on the television screen.
Create a `Television` class with the foll... | ```csharp
public class Television
{
public string Channel { get; set; }
public void ChangeChannel(string newChannel)
{
Channel = newChannel;
}
public void DisplayChannel()
{
Console.WriteLine("Current Channel: " + Channel);
}
}
``` | magicoder | csharp |
You are given two lists: `participant` and `completion`. The `participant` list contains the names of participants in a race, while the `completion` list contains the names of participants who have completed the race. Your task is to write a function `solution(participant, completion)` that returns the name of the part... | ```python
def solution(participant, completion):
participant.sort()
completion.sort()
for i in range(len(completion)):
if participant[i] != completion[i]:
return participant[i]
return participant[-1]
```
The solution first sorts both the `participant` and `completion` lists. Then, it... | magicoder | python |
You are working on a distributed caching system for an application running on multiple instances. The code snippet provided is a part of a Python class that represents a shared cache entity in Google App Engine. The class has a method called `invalidate` which is used to notify all instances to invalidate their caches.... | ```python
import datetime
def handle_cache_invalidation():
global last_processed_timestamp
last_processed_timestamp = datetime.datetime.now()
SharedInvalidateParent.invalidate()
```
In the solution, the `handle_cache_invalidation` function updates the `last_processed_timestamp` with the current timestamp u... | magicoder | python |
You are tasked with creating a Django REST Framework serializer for a model representing category information. The category model has a self-referential foreign key relationship, allowing categories to be nested within other categories. To achieve this, you will need to use the `rest_framework` and `rest_framework_recu... | ```python
from rest_framework import serializers
from ..models import CategoryInfo
from rest_framework_recursive.fields import RecursiveField
class CategoryInfoSerializer(serializers.ModelSerializer):
parent = RecursiveField(allow_null=True)
class Meta:
model = CategoryInfo
fields = ('id', 'na... | magicoder | python |
You are tasked with implementing a function that checks whether a given HTML snippet is properly formatted. The HTML snippet is represented as a string, and you need to ensure that all opening tags have corresponding closing tags in the correct order.
Write a function `isHTMLValid(html: string): boolean` that takes a ... | ```javascript
function isHTMLValid(html) {
const stack = [];
const openingTag = '<div>';
const closingTag = '</div>';
for (let i = 0; i < html.length; i++) {
if (html.substring(i, i + openingTag.length) === openingTag) {
stack.push(openingTag);
} else if (html.substring(i, i + closingTag.length) ... | magicoder | javascript |
You are tasked with implementing a validation function for a user registration system. The function should validate the input data and return an error message if the validation fails. You are given a partial code snippet for the validation function in PHP:
```php
class UserRegistration
{
public function validateIn... | ```php
class UserRegistration
{
public function validateInput($username, $email, $password)
{
if (strlen($username) < 3 || strlen($username) > 20) {
return "Username must be between 3 and 20 characters long.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
r... | magicoder | php |
You are tasked with implementing a k-means clustering algorithm for a given dataset. The algorithm involves finding the new centroids based on the current centroids and the data points. The `find_new_centroids` method takes in the current centroids and the data points and returns the new centroids.
You are given the f... | ```python
def find_new_centroids(centroids, data):
new_centroids = []
for centroid in centroids:
cluster_points = [point for point in data if point['cluster'] == centroid['cluster']]
if len(cluster_points) > 0:
new_centroid = {
'cluster': centroid['cluster'],
... | magicoder | python |
You are given an array of integers `u` and an integer `N`. Your task is to write a function `closest_product(u, N)` that finds the pair of elements in the array `u` whose product is closest to the integer `N`. If there are multiple pairs with the same absolute difference from `N`, return the pair with the smallest prod... | ```python
def closest_product(u, N):
u.sort()
closest_pair = []
min_diff = float('inf')
for i in range(len(u)):
for j in range(i + 1, len(u)):
product = u[i] * u[j]
diff = abs(product - N)
if diff < min_diff or (diff == min_diff and product < u[0] * u[1]):
... | magicoder | python |
You are tasked with implementing a rate limiter for an API service. The rate limiter should restrict the number of API calls a user can make within a certain time frame. Your task is to design and implement a RateLimiter class that enforces the following rules:
- Each user is allowed a maximum of `max_api_call_day` API... | ```python
class RateLimiter:
def __init__(self, max_api_call_day):
self.max_api_call_day = max_api_call_day
self.request_count = 0
def make_api_call(self):
if self.request_count < self.max_api_call_day:
self.request_count += 1
print("API call successful")
... | magicoder | python |
You are tasked with creating a RESTful API for a travel application that manages tourist attractions. The API should be built using PHP and the CodeIgniter framework. Your task is to implement the "Wisata" (tourist attraction) resource, which will handle CRUD operations for tourist attractions.
Your task is to complet... | ```php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') or exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
class Wisata extends REST_Controller
{
public function __construct()
{
parent::__construct();
... | magicoder | php |
You are tasked with creating a smart contract for a decentralized exchange (DEX) that facilitates the trading of ERC-20 tokens. The DEX requires a function to sign a trade message using the signer's private key and a function to deploy a test token contract.
You are provided with two code snippets. The first snippet c... | ```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract DecentralizedExchange is Ownable {
using SafeMath for uint256;
using Address for address;
address public signer; // Add... | magicoder | solidity |
You are tasked with creating a program that processes a collection of articles and extracts specific information from them. Each article is represented as a HTML snippet, and you need to extract the title and content of each article.
You are given a string `htmlContent` containing the HTML code for multiple articles. ... | ```python
import re
def extractArticles(htmlContent):
articles = re.findall(r'<a>.*?<h2>(.*?)</h2>.*?<p>(.*?)</p>.*?</a>', htmlContent, re.DOTALL)
extracted_articles = [{'title': title, 'content': content} for title, content in articles]
return extracted_articles
```
The `extractArticles` function uses re... | magicoder | python |
You are working on a machine learning project using the `scikit-learn` library in Python. Your task is to create a pipeline for training and evaluating a classification model using the famous Iris dataset. The dataset contains four features (sepal length, sepal width, petal length, and petal width) and three classes of... | ```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from tpot.builtins import StackingEstimator
import pandas as pd
import numpy as np
# Load the Iris dataset
iris = loa... | magicoder | python |
You are tasked with implementing a function store system in Rust. The function store is responsible for executing functions and indirect functions based on their indices. You need to create a struct `FunctionStore` and implement the trait `FunctionStore` for it. The trait contains two methods: `execute_function` and `e... | ```rust
pub trait DataStore {
// Define any required methods for the DataStore trait
}
pub struct Stack {
// Define the Stack struct and its methods
}
pub struct FunctionStore {
// Define the FunctionStore struct and its methods
}
impl FunctionStore for FunctionStore {
fn execute_function(
&s... | magicoder | rust |
You are tasked with implementing a Python class that represents a grid for tuning hyperparameters in a machine learning library. The grid will be used to define a set of values for a specific hyperparameter that will be tested during model training. Your task is to complete the implementation of the `Grid` class, ensur... | ```python
from abc import ABCMeta
from typing import Sequence
class TuneUnit(metaclass=ABCMeta):
def __init__(self):
pass
class Grid(TuneUnit):
def __init__(self, values: Sequence):
super().__init__()
self.values = values
def get_values(self) -> Sequence:
return self.val... | magicoder | python |
You are tasked with creating a program that analyzes a given text file to determine the frequency of occurrence of each word. The program should ignore punctuation, capitalization, and consider words with different cases as the same word. Additionally, the program should exclude common stop words such as "the," "and," ... | ```python
import re
from collections import Counter
# Read the content of the input file
with open('input.txt', 'r') as file:
text = file.read()
# Define the list of stop words
stop_words = {'the', 'and', 'of', 'in', 'on', 'any', 'or', 'if', 'is', 'it', 'to', 'this', 'even', 'such'}
# Remove punctuation and conv... | magicoder | python |
You are tasked with implementing a CRC (Cyclic Redundancy Check) algorithm to calculate the CRC value of a given buffer. The CRC algorithm is used for error detection in digital networks and storage devices. The provided code snippet contains a hexadecimal representation of a buffer and a function `calc_crc` that needs... | ```python
def calc_crc(crc_buff):
crc = 0xFFFFFFFF # Initialize CRC value to 0xFFFFFFFF
poly = 0xEDB88320 # CRC-32 polynomial
for byte in crc_buff:
crc = crc ^ byte # XOR the CRC value with the next byte
for _ in range(8):
if crc & 1: # If the least significant bit is 1
... | magicoder | python |
You are tasked with implementing a secure random number generator using TypeScript and the Chance library. The Chance library is a popular JavaScript library for generating random values, and in this problem, you will use its TypeScript typings to create a secure random number generator function.
Your task is to imple... | ```typescript
import Chance from 'chance';
async function secureChance(): Promise<InstanceType<typeof Chance>> {
return new Promise((resolve, reject) => {
try {
// Create a new instance of Chance with a secure source of randomness
const secureRandomChance = new Chance({ secure: true });
resolve... | magicoder | typescript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.