query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a generic data structure called `TypedVector` in Rust. The `TypedVector` should be able to store elements of any type and provide methods for adding elements, getting the length of the vector, and accessing elements by index.
Your task is to complete the implementation of the `TypedVec... | ```rust
// Define the TypedVector struct
struct TypedVector<T> {
type_id: String,
vec: Vec<T>,
}
impl<T> TypedVector<T> {
// Constructor method to create a new TypedVector instance
fn new(type_id: String) -> TypedVector<T> {
TypedVector {
type_id,
vec: Vec::new(),
... | magicoder | rust |
You are working for a software company that develops a virtual switch (vswitch) module for networking purposes. The company uses Python for packaging and distributing its vswitch module. The code snippet provided is a simplified version of the setup script used to package and install the vswitch module. The `setup` fun... | ```python
def simulate_setup(install_params):
print(f"Simulating setup for {install_params['name']} module:")
print(f"- Package name: {install_params['name']}")
print(f"- Version: {install_params['version']}")
print(f"- Author: {install_params['author']}")
print(f"- Author email: {install_params['au... | magicoder | python |
You are tasked with implementing a multi-threaded file processing system. The given code snippet is a part of a Python program that uses the `queue.Queue` class to process and write data from multiple threads to an output file. The `q` object is an instance of `queue.Queue` and is used to store partitions of data to be... | ```python
import queue
import threading
# Define the EOF constant
EOF = None
# Define a function to populate the queue with data partitions
def populate_queue(queue, data_partitions):
for partition in data_partitions:
queue.put(partition)
# Signal the end of input data
queue.put(EOF)
# Define a f... | magicoder | python |
You are tasked with implementing a union data structure in C++ to represent a set of different types. The union should allow for the inspection of the name of the active member without checking the value of the discriminator. The discriminator is a variable that indicates which member of the union is currently active. ... | ```cpp
#include <iostream>
#include <string>
union DataUnion {
int intValue;
double doubleValue;
char stringValue[20];
int discriminator;
std::string getActiveMemberName() {
switch (discriminator) {
case 1:
return "int";
case 2:
retur... | magicoder | cpp |
You are tasked with implementing a method to convert a given object to a string with each line indented by 4 spaces, except for the first line. The method signature is as follows:
```java
public String convertObjectToString(Object obj) {
// Your implementation here
}
```
The method should take an `Object` as inpu... | ```java
public String convertObjectToString(Object obj) {
return formatObjectToString(obj, 0);
}
private String formatObjectToString(Object obj, int indentLevel) {
if (obj == null) {
return "null";
}
if (obj instanceof Map) {
return formatMapToString((Map<?, ?>) obj, indentLevel);
}... | magicoder | java |
You are tasked with implementing a data writing and flushing algorithm for a file system. The algorithm takes into account the delay between writes, the number of writes between flushes and chunk size, and the total number of elements to write. The goal is to efficiently write data to a file while minimizing the number... | ```python
import time
def write_and_flush(D: int, F: int, N: int, outputfile: str) -> None:
with open(outputfile, 'w') as file:
for i in range(1, N + 1):
file.write(f"Element {i}\n")
if i % F == 0 or i == N:
file.flush()
time.sleep(D / 1000000) # Con... | magicoder | python |
You are tasked with implementing a data processing module for a computer vision application. The module is responsible for processing training and validation data pairs using various transformations and parameters. Your goal is to create a class or function that performs the necessary data processing based on the given... | ```python
class DataProcessing:
def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, mode, proposal_params, transform, joint_transform=None):
self.search_area_factor = search_area_factor
self.output_sz = output_sz
self.center_jitter_factor = center_jit... | magicoder | python |
You are tasked with creating a Python function that generates a filename for a TV show scene file based on a given pattern and scene file metadata. The function should take into account the show name, season number, episode number, and whether to include leading zeroes for the season and episode numbers.
You are provi... | ```python
import os
class SceneFileMetadata:
def __init__(self, show, season, episode):
self.show = show
self.season = season
self.episode = episode
def generateFilename(sceneFile, pattern, zeroesSeason=False, zeroesEpisodes=False):
meta = sceneFile.meta
# Keep the extension of the... | magicoder | python |
You are tasked with implementing a logging system for a software application. The system should log data from various functions and classes within the application. The provided code snippet is a simplified representation of a logging function for a specific class.
You are given a `func3Class` class with a member funct... | ```cpp
#include <iostream>
// Define the LOG_MESSAGE macro for logging
#define LOG_MESSAGE(funcName, data) \
std::cout << "Logging " << funcName << " - Data: " << data << std::endl;
// Define a generic logging function template
template <typename T>
void logData(const std::string& funcName, const T& data) {
L... | magicoder | cpp |
You are given a list of 2D points represented as tuples of (x, y) coordinates. Your task is to write a function that calculates the angle (in degrees) between each point and a main reference point. The angle should be measured in the counter-clockwise direction from the positive x-axis to the line connecting the main r... | ```python
import math
def calculate_angles(list_of_points, main_point):
relative_points = []
for point in list_of_points:
relative_points.append([point[0] - main_point[0], point[1] - main_point[1]])
angles = []
for point in relative_points:
angle_rad = math.atan2(point[1], point[0])
... | magicoder | python |
You are tasked with implementing a migration script for a Judo club's member database. The club has decided to upgrade its database schema, and your task is to write a migration script to handle this upgrade. The existing code snippet provides the starting point for the migration script.
Your task is to complete the `... | ```php
class ClubMigration extends AbstractMigration
{
public function up()
{
// Add the belt_color column to the members table
$this->addSql('ALTER TABLE members ADD COLUMN belt_color VARCHAR(50)');
// Create the belt_colors table
$this->addSql('CREATE TABLE belt_colors (
... | magicoder | php |
You are tasked with creating a Django web application that includes user authentication and media file serving. Your goal is to set up the necessary URL configurations and views to enable user login, logout, and media file serving.
Given the provided code snippet, you need to complete the following tasks:
1. Define th... | ```python
# Import necessary modules
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.urls import include
# Define URL patterns
urlpatterns = [
# Login URL
url(r'^login/$', auth_views.Log... | magicoder | python |
You are tasked with creating a Python decorator that measures the execution time of a given function. Your decorator should be able to wrap any function and print the time taken for its execution. The decorator should be implemented using the provided code snippet as a starting point.
Your task is to implement the `ti... | ```python
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
rv = func(*args, **kwargs)
total = time.time() - start
print("Time:", total)
return rv
return wrapper
@timer
def example_function():
print("Executing example function...")
exam... | magicoder | python |
You are tasked with creating a program that simulates a parallel job execution system. The program should take a list of jobs and execute them in parallel, with a specified maximum number of concurrent jobs. The input will consist of a list of job files, each containing a set of commands to be executed. The program sho... | ```python
import subprocess
from concurrent.futures import ThreadPoolExecutor
import os
def execute_job(job_file):
with open(job_file, 'r') as file:
commands = file.readlines()
for command in commands:
subprocess.run(command, shell=True)
def execute_jobs_in_parallel(job_files, max_conc... | magicoder | python |
You are tasked with optimizing the initialization process for a Python class by efficiently transferring the contents of a dictionary into the class attributes. Your goal is to implement a method that achieves this transfer in the fastest way possible.
You are given a Python class `FastInit` with the following initia... | To optimize the initialization process for the `FastInit` class, we can use the `update` method of the `self.__dict__` attribute to efficiently transfer the contents of the `kw` dictionary into the class attributes. This approach minimizes unnecessary dictionary lookups and provides a fast way to update the class attri... | magicoder | python |
You are tasked with understanding and analyzing Swift Intermediate Language (SIL) code. SIL is an intermediate representation used by the Swift compiler during optimization and code generation. Your goal is to interpret and understand the SIL code snippet provided and explain its functionality.
Given SIL code snippet:... | The SIL code snippet provided represents a Swift function in its intermediate representation. Let's break down the components:
1. `// SIL-LABEL`: This is a SIL comment marker that indicates the beginning of a SIL function declaration.
2. `sil public_external [transparent] [serialized] [canonical]`: These are SIL func... | magicoder | swift |
You are tasked with implementing a function to sort a list of features by priority based on their importance computation. The function should handle scenarios where feature importance computation comes from a mix of current and previous fit models, and some features are unevaluated.
You are given a code snippet that c... | ```python
import pandas as pd
def sort_features_by_priority(features, prev_importance_df, using_prev_fit_fi):
# Create a DataFrame for the current features
curr_importance_df = prev_importance_df[~prev_importance_df.index.isin(using_prev_fit_fi)]
# Sort the features by importance
sorted_prev_fit_f... | magicoder | python |
You are tasked with creating a script that validates the protocol used in a URL. The script should check if the protocol is either "http" or "https" and display an appropriate message based on the validation result.
Write a Bash script that takes a URL as input and performs the following steps:
1. Extract the protocol... | ```bash
#!/bin/bash
# Input URL
read -p "Enter the URL: " URL
# Extract protocol from URL
PROTOCOL=$(echo "$URL" | grep -o "^\w\+://")
# Convert protocol to lowercase
PROTOCOL=$(echo "$PROTOCOL" | tr '[:upper:]' '[:lower:]')
# Check if the protocol is valid
if [[ "$PROTOCOL" == "http://" ]] || [[ "$PROTOCOL" == "ht... | magicoder | shell |
You are tasked with implementing a custom attribute-based sorting mechanism for a collection of objects in C#. The given code snippet provides an enumeration of sorting options, each associated with a query parameter value. Your task is to create a custom attribute and a sorting method that can sort a collection of obj... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
// Define a custom attribute to specify the query parameter value
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class QueryParameterValueAttribute : Attribute
{
public string QueryParam... | magicoder | csharp |
You are tasked with implementing a function to initialize the weights of a neural network model and load pretrained weights if specified. The function should follow the given code snippet's logic and handle different cases for loading pretrained weights.
You are given the following code snippet as a reference:
```pyth... | ```python
import torch
def initialize_model_weights(model, pretrained_weights):
def weights_init_normal(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
torch.nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm2d') != -1:
tor... | magicoder | python |
You are tasked with creating a Python function that calculates the average of the best-performing scheme based on a given set of results. The function should take a dictionary `results` as input, where the keys are scheme names and the values are dictionaries containing the scheme's results. Each scheme's results dicti... | ```python
import numpy as np
def average_of_the_best(results: dict, reward_key: str) -> float:
avg_best = -1000000000000
abr_best = ''
for scheme in results.keys():
avg_tmp = np.mean(results[scheme][reward_key])
if avg_best < avg_tmp:
avg_best = avg_tmp
abr_best = sc... | magicoder | python |
You are tasked with implementing a function to serialize a given `Log` struct into the Recursive Length Prefix (RLP) encoding format. The `Log` struct represents a log entry in Ethereum's blockchain and contains the address of the contract, log data, and topics.
The `Log` struct is defined as follows:
```rust
use bigi... | ```rust
use bigint::{Address, H256, U256};
use rlp::{Encodable, RlpStream};
#[derive(Debug)]
pub struct Log {
pub address: Address,
pub data: U256,
pub topics: Vec<H256>,
}
impl Encodable for Log {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(3); // Begin RLP list with 3 items
... | magicoder | rust |
You are tasked with implementing a custom view class in Swift that includes a title label. The provided code snippet is a part of the class implementation and shows the private method `initTitleLabel()` being used to initialize and configure the title label within the custom view. Your task is to complete the implement... | ```swift
import UIKit
class CustomTitleView: UIView {
private var titleLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
initTitleLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initTitleLabel()
}
private f... | magicoder | swift |
You are given a directed graph represented as a list of vertices and their corresponding outgoing edges. Each vertex is represented by a list of outgoing edges. Your task is to implement a function that modifies the graph based on certain conditions.
You need to implement a function `modify_graph(graph: List[List[int]... | ```python
from typing import List
def modify_graph(graph: List[List[int]]) -> List[List[int]]:
changed_graph = [[0, 0] for _ in range(len(graph))]
for j in range(len(graph)):
min_edge = min(graph[j][1:])
changed_graph[j][0] = min_edge
for j in range(len(graph)):
for i in r... | magicoder | python |
You are tasked with creating a Rust library for managing various types of Uninterruptible Power Supplies (UPS). The library should provide a unified interface for interacting with different UPS devices through their respective communication protocols. To achieve this, you need to implement the necessary modules and str... | ```rust
// Define a module for managing HID devices
pub mod hid_device {
pub trait HidDevice {
fn connect(&self);
fn disconnect(&self);
fn send_data(&self, data: &[u8]);
fn receive_data(&self) -> Vec<u8>;
}
}
// Implement the specific functionality for Megatec HID UPS devices
pu... | magicoder | rust |
You are tasked with implementing a custom iterator in Rust for a scheduling algorithm. The `ComputeSchedule` struct represents the schedule, and it contains a vector of `ComputeUnit` items and an index to keep track of the current position in the schedule. The `ComputeUnit` type is not explicitly defined in the given c... | ```rust
// Define the ComputeUnit type (assuming it as a relevant data type)
struct ComputeUnit;
// Define the ComputeSchedule struct
struct ComputeSchedule {
_compute_units: Vec<ComputeUnit>,
_index: usize,
}
// Implement the Iterator trait for ComputeSchedule
impl Iterator for ComputeSchedule {
type Ite... | magicoder | rust |
You are tasked with implementing a Python function that simulates the behavior of an asynchronous form validation process. The function should take in two parameters: `hass`, an object representing the Home Assistant system, and `interface_data`, a dictionary containing data for the interface. The function should use a... | ```python
import asyncio
IF_HMIP_RF_NAME = "IF_HMIP_RF_NAME"
async def async_check_form(hass, interface_data):
# Simulate asynchronous form validation process
await asyncio.sleep(1) # Simulating asynchronous operation
# Perform form validation logic
# Assuming interface_data contains form data to be... | magicoder | python |
You are tasked with implementing a function to find the area of the largest rectangle formed by a histogram. Given an array of non-negative integers representing the histogram's bar height where the width of each bar is 1, the function should calculate the area of the largest rectangle that can be formed within the his... | ```csharp
public static int CalculateLargestRectangleArea(int[] heights)
{
if (heights == null || heights.Length == 0)
{
return 0;
}
Stack<int> stack = new Stack<int>();
int maxArea = 0;
int i = 0;
while (i < heights.Length)
{
if (stack.Count == 0 || heights[i] >= heigh... | magicoder | csharp |
You are tasked with implementing a function to fetch and process news articles from a given source. The function should use the `requests` library to retrieve XML data from a specified URL, parse the XML using the `ElementTree` module, and then extract relevant information from the XML tree.
You are provided with a co... | ```python
import requests
import xml.etree.ElementTree as ET
from unittest.mock import MagicMock
ARTICLES_LINK = "https://example.com/articles.xml"
def fetch_stories():
# Fetch XML data from the specified URL
tree = ET.fromstring(requests.get(ARTICLES_LINK).text)
all_articles = []
nyc_articles = []
... | magicoder | python |
You are tasked with implementing a Python function that calculates the total light intensity at a specific point in a 3D space. The function will take into account the contributions from multiple light sources positioned at different offsets along the x-axis. Each light source is modeled as a positional light with a sp... | ```python
import math
def calculate_total_light_intensity(x, y, z):
offsets = [0, 1.5, 3]
exponents = [1, 2, 5]
cone_angle = 80 # in degrees
total_intensity = 0
for offset, exponent in zip(offsets, exponents):
distance_squared = (x - offset) ** 2 + y ** 2 + z ** 2
distance = math.... | magicoder | python |
You are tasked with implementing a configuration parser that can read and process configuration files in a specific format. The configuration files contain key-value pairs, where each key is a string and each value can be a string, integer, or boolean. The configuration file format is as follows:
```
# This is a commen... | ```cpp
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <sstream>
#include <string>
#include <cctype>
class ConfigurationParser {
private:
std::unordered_map<std::string, std::string> configMap;
void trim(std::string& str) {
str.erase(0, str.find_first_not_of(" \t\r\n"));
... | magicoder | cpp |
You are given a 2D board represented as a 2D array of integers, where each cell contains a non-negative integer value. The board represents a game where a player can move from cell to cell. The player can only move to adjacent cells (up, down, left, or right) and cannot visit the same cell twice in a single path. The g... | ```javascript
function maxPathSum(board, startCell, endCell) {
const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
const rows = board.length;
const cols = board[0].length;
const visited = Array(rows).fill().map(() => Array(cols).fill(false));
function isValidCell(row, col) {
return row >= 0 && row < r... | magicoder | javascript |
You are tasked with creating a C# wrapper for a native library that provides image processing functionalities. The native library exposes a function `filament_Image_KtxBundle_GetSphericalHarmonics` through the `libfilament-dotnet` dynamic link library (DLL). Your goal is to create a C# method that can invoke this nativ... | ```csharp
public static class ImageProcessing
{
[StructLayout(LayoutKind.Sequential)]
public struct SphericalHarmonics
{
// Define the structure fields to match the native representation
// For example:
// public float r, g, b;
}
[DllImport("libfilament-dotnet", EntryPoint =... | magicoder | csharp |
You are tasked with writing a script to automate the configuration process for installing a software package called "R." The script needs to handle different configurations based on the value of the environment variable `MACOSX_DEPLOYMENT_TARGET` and another variable `RFLAG`.
The script should execute the following st... | ```bash
#!/bin/bash
if [[ $MACOSX_DEPLOYMENT_TARGET == "10.6" || $MACOSX_DEPLOYMENT_TARGET == "10.7" || $MACOSX_DEPLOYMENT_TARGET == "10.8" ]]; then
./configure FFLAGS="-m64" CFLAGS="-std=gnu99 -g -O2" CXXFLAGS="-std=gnu99 -g -O2" --without-jpeglib --disable-R-framework --enable-R-shlib --disable-openmp --without-... | magicoder | shell |
You are tasked with implementing a custom string class in Objective-C that supports the creation of strings from various sources. Your task is to create a method `createString` that takes a source and encoding type and returns a new string object. The source can be a C string or another NSString object, and the encodin... | ```objective-c
+ (instancetype)createStringWithSource:(id)source encoding:(NSStringEncoding)enc {
if ([source isKindOfClass:[NSString class]]) {
return [self stringWithString:source];
} else if ([source isKindOfClass:[NSString class]]) {
return [self stringWithCString:[source UTF8String] encodin... | magicoder | c |
You are tasked with creating a Python decorator that logs the execution time of a test method in a test suite. You will need to implement the decorator and apply it to a sample test method. The decorator should log the start and end time of the test method execution, along with the total time taken. You should also ens... | ```python
from tempest.lib import decorators
from tempest import test
from tempest import config
import time
CONF = config.CONF
LOG = log.getLogger(__name__)
def log_test_execution_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time =... | magicoder | python |
You are given a code snippet representing a decision tree structure. Each block of code represents a decision node in the tree, and the conditions within each block determine the path to take based on the input object `obj` and its corresponding indices. The conditions are based on comparisons between elements of the `... | ```python
def decision_tree_outcome(obj):
if obj[1] <= 2:
if obj[0] > 2:
return 'True'
elif obj[0] <= 2:
if obj[8] > 0:
return 'True'
elif obj[8] <= 0:
if obj[9] > 2:
return 'True'
elif obj[9] <= ... | magicoder | python |
You are tasked with implementing a simplified version of a protocol runner in Rust. The protocol runner is responsible for managing the state transitions of a blockchain protocol. The code snippet provided is a part of the match arm for handling a specific message in the protocol runner.
Your task is to implement the ... | ```rust
fn handle_action(action: Action, state: &mut ProtocolRunnerState) {
match action {
Action::ProtocolRunnerInitCheckGenesisApplied(_) => {
*state = ProtocolRunnerState::CheckGenesisApplied;
}
// Handle other action variants and update the state accordingly
}
}
```
In t... | magicoder | rust |
You are tasked with creating a program that extracts and processes information from HTML code to generate a summary of social media links and locations. The HTML code snippet provided represents a portion of a webpage's footer.
Your task is to write a function that takes the HTML code as input and returns a dictionary... | ```python
from bs4 import BeautifulSoup
def extract_social_media_and_locations(html_code):
soup = BeautifulSoup(html_code, 'html.parser')
social_media_links = [img['src'] for img in soup.find_all('img', class_='social-media')]
locations = []
city_elements = soup.find_all('p', class_='city')
... | magicoder | python |
You are tasked with creating a Python function that processes a given string to extract specific substrings based on predefined patterns using regular expressions.
You need to implement a function `extract_substrings` that takes in a string `input_string` and a list of patterns `pattern_list`. The function should use ... | ```python
import re
from typing import List, Optional
def extract_substrings(input_string: str, pattern_list: List[str]) -> List[Optional[str]]:
matched_substrings = []
for pattern in pattern_list:
match = re.match(pattern, input_string)
if match:
matched_substrings.append(match.gro... | magicoder | python |
You are working on a game development project that involves a grid-based game board with various panels. Each panel can be moved in four directions: up, down, left, and right. The game provides a function `panelMove` that takes a string representing the movement commands for a panel. The commands are represented by the... | ```python
class MagicPanels:
@staticmethod
def panelMove(commands):
# Define the initial position of the panel
initial_position = (0, 0) # Example initial position
# Define the grid boundaries
grid_width = 5 # Example grid width
grid_height = 5 # Example grid ... | magicoder | python |
You are tasked with implementing a Python function that performs a matrix projection operation. A matrix projection involves transforming a given matrix using a projection matrix. The projection matrix is a square matrix that, when multiplied with the input matrix, projects the input matrix onto a subspace defined by t... | ```python
def matrix_projection(input_matrix, projection_matrix):
import numpy as np # Importing numpy for matrix operations
input_matrix = np.array(input_matrix) # Convert input_matrix to numpy array
projection_matrix = np.array(projection_matrix) # Convert projection_matrix to numpy array
projected... | magicoder | python |
You are tasked with creating a simple web-based game where a user must click on a moving object to score points. The game will involve a plane (represented by an image) moving across the screen, and the user must click on the plane to score points. If the user misses the plane, an "X" mark will appear at the location o... | ```javascript
// Define variables
let score = 0;
let rounds = 0;
// Function to move the plane
function movePlane() {
let dot = document.getElementById('dot');
let xmark = document.getElementById('xmark');
let plane = document.getElementById('plane');
let xmk = document.getElementById('xmk');
// Set initial posi... | magicoder | javascript |
You are working on a messaging bot application that processes different types of messages. The bot is designed to handle various types of data, such as passport data and poll data, and perform specific actions based on the message type. The bot uses the `telepot` library to handle incoming messages and extract relevant... | ```python
import telepot
import some_module as st # Assuming the token is stored in some_module
class AdminBot:
def __init__(self, token):
self.bot = telepot.Bot(token)
def on_passport_data(self, msg):
chat_id, passport_data = telepot.glance(msg, flavor='all_passport_data')
output = c... | magicoder | python |
You are tasked with implementing a secure token management system for an API data manager class in Swift. The `APIDataManager` class is responsible for handling API requests, and it needs to securely store and manage an app token. Your task is to create a secure mechanism to set and get the app token, ensuring that it ... | ```swift
class APIDataManager {
private static var appToken : String?
static func setAppToken(_ token: String) {
appToken = token
}
static func getAppToken() -> String? {
return appToken
}
}
```
In the solution, the `appToken` is declared as a private static variable within... | magicoder | swift |
You are tasked with creating a Python function that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The player can move up, down, left, or right within the grid. The grid is represented as a 2D list, where each cell cont... | ```python
from typing import List
def collect_treasures(grid: List[List[str]], start_row: int, start_col: int, moves: int) -> int:
def is_valid_move(row, col):
return 0 <= row < len(grid) and 0 <= col < len(grid[0]) and grid[row][col] != 'X'
def collect_treasures_helper(row, col, moves_left):
... | magicoder | python |
You are tasked with creating a Python script that retrieves data from a given URL, parses it as XML, and writes the parsed data to a YAML file. Your script should take a URL as a command-line argument and perform the following steps:
1. Import necessary libraries: `requests`, `sys`, `datetime`, and `BeautifulSoup` fro... | ```python
# Import the necessary libraries
import requests
import sys
import datetime
from bs4 import BeautifulSoup
import yaml
# Get the URL from the command-line argument
url = sys.argv[1]
# Retrieve the content from the URL
response = requests.get(url)
# Parse the XML content
tree = BeautifulSoup(response.content... | magicoder | python |
You are tasked with creating a program that utilizes the QGrain library to analyze and visualize grain size distribution data. The QGrain library provides functionality for processing and interpreting grain size distribution data, which is commonly used in geology, soil science, and material science.
Your program shou... | ```python
# Import necessary modules
from QGrain.main import *
import matplotlib.pyplot as plt
# Load grain size distribution data from a file
data_file = "grain_size_data.txt"
grain_data = GrainSizeData.from_csv(data_file)
# Process the data to obtain statistical parameters
statistics = grain_data.statistics()
# Vi... | magicoder | python |
You are tasked with creating a program to control a robotic arm using the OpenJigWare library. The robotic arm has multiple joints and can perform various movements. The OpenJigWare library provides functions to control the robotic arm's movements, such as rotating joints and gripping objects. Your task is to implement... | ```cpp
#include "OpenJigWare.h"
#include <iostream>
int main() {
// Initialize the OpenJigWare library
if (!JWInitialize()) {
std::cerr << "Failed to initialize OpenJigWare library" << std::endl;
return 1;
}
// Connect to the robotic arm
if (!JWConnect()) {
std::cerr << "Fa... | magicoder | cpp |
You are tasked with implementing a custom HTTP adapter for a Python application. The adapter will be responsible for handling HTTP requests and responses in a specialized manner. Your goal is to create a class that can be used as an adapter for the `requests` library's `Session` object. The adapter should intercept and... | ```python
import requests
class CustomHTTPAdapter(requests.adapters.HTTPAdapter):
def __init__(self, custom_header_value):
self.custom_header_value = custom_header_value
super().__init__()
def send(self, request, **kwargs):
request.headers['Custom-Header'] = self.custom_header_value
... | magicoder | python |
You are tasked with creating a web scraping tool using Python and Selenium. Your goal is to scrape data from a website within a specified range of IDs. The website requires user authentication, and the scraping process should be initiated only after the user is logged in.
You are provided with a Django view function `... | ```python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from djang... | magicoder | python |
You are tasked with implementing a Python function that processes a list of values and returns a modified list based on the following requirements:
1. If the input list contains strings that represent boolean values ("yes", "true", "1", "no", "false", "0"), convert these strings to their corresponding boolean values.
... | ```python
from typing import List, Union
import datetime
def process_list(input_list: List[Union[str, Any]]) -> List[Union[bool, datetime, int, Any]]:
output_list = []
for val in input_list:
if isinstance(val, str):
if val.lower() in ("yes", "true", "1"):
output_list.append(... | magicoder | python |
You are tasked with implementing a custom data serialization and deserialization mechanism for a web browser application using C++. The application uses the WebKit framework, and the serialization process involves encoding and decoding data references and string arguments.
Your task is to create a class that provides ... | ```cpp
#include "DataReference.h"
#include "WebCoreArgumentCoders.h"
#include <wtf/text/WTFString.h>
namespace WebKit {
class CustomDataSerializer {
public:
// Serialize data reference
static EncodedData serializeDataReference(const DataReference& dataRef) {
// Implementation to enc... | magicoder | cpp |
You are tasked with implementing a custom aggregation function for a graph neural network model. The model uses metapath convolution and PyTorch's GATConv for message passing. Your goal is to create a new aggregation function and integrate it into the model.
You are given a Python class `MetapathConv` that represents ... | ```python
class MetapathConv:
def __init__(self, meta_paths, conv_layers):
self.meta_paths = meta_paths
self.conv_layers = conv_layers
# Other initialization code
def Aggr_custom(self, tensors):
# Implement the custom aggregation function here
# For example, you can use ... | magicoder | python |
You are tasked with creating a Python function that processes a list of dependencies and generates a dependency graph. The dependency graph should represent the relationships between different dependencies, where each dependency is a node and the edges represent the dependencies between them. The input list contains tu... | ```python
def generate_dependency_graph(dependencies):
dependency_graph = {}
for dependency, dependent in dependencies:
if dependent not in dependency_graph:
dependency_graph[dependent] = [dependency]
else:
dependency_graph[dependent].append(dependency)
... | magicoder | python |
You are tasked with designing a Python class that manages job schemas for a job processing system. The job schemas are used to define the structure of different types of jobs that can be submitted to the system. Each job schema is represented as a Python class with specific attributes and methods.
Your task is to crea... | ```python
class JobSchema:
def __init__(self, schema_name, schema_fields):
self.schema_name = schema_name
self.schema_fields = schema_fields
def validate(self, data):
return all(field in data for field in self.schema_fields)
class ExpectationSweepJobContextSchema(JobSchema):
def _... | magicoder | python |
You are tasked with creating a program that analyzes a given HTML file to identify and extract any JavaScript code enclosed within `<script>` tags. Your program should be able to handle multiple occurrences of `<script>` tags and extract the JavaScript code within them.
Write a function `extractJavaScript` that takes ... | ```python
import re
def extractJavaScript(html):
script_tags = re.findall(r'<script>(.*?)</script>', html, re.DOTALL)
filtered_scripts = [script for script in script_tags if '@push' not in script]
return filtered_scripts
# Test the function with the given example
html_content = """
<!DOCTYPE html>
<html>
... | magicoder | python |
You are tasked with implementing a queue using two stacks. You are given the following code snippet as a starting point:
```csharp
public class QueueWithStacks
{
private Stack<int> _stack = new Stack<int>();
private Stack<int> _tmpStack = new Stack<int>();
public void Enqueue(int value)
{
_sta... | ```csharp
public class QueueWithStacks
{
private Stack<int> _stack = new Stack<int>();
private Stack<int> _tmpStack = new Stack<int>();
public void Enqueue(int value)
{
_stack.Push(value);
}
public int Dequeue()
{
if (_tmpStack.Count == 0)
{
if (_stack.C... | magicoder | csharp |
You are tasked with creating a Python program that interacts with a MySQL database using the `mysql.connector` module. Your program should connect to the database, retrieve data from a specific table, perform a calculation on the retrieved data, and then update another table with the calculated result.
Your program sh... | ```python
import mysql.connector
# Connect to the MySQL database
try:
cnx = mysql.connector.connect(user='root', password='your_password', database='your_database')
cursor = cnx.cursor()
# Retrieve data from the sales_data table
query = "SELECT product_id, quantity_sold FROM sales_data"
cursor.exe... | magicoder | python |
You are tasked with implementing a function to calculate the conversion error when converting an integer to a floating-point number. The function should take an integer representing the number of bits used to represent the integer and return the conversion error as a floating-point number.
You are given the following ... | ```cpp
#include <iostream>
#include <cmath>
// Function to calculate the conversion error when converting an integer to a floating-point number
static float calculateFloatConversionError(int srcBits) {
if (srcBits > 0) {
// Clamp the number of bits to a valid range (0 to 32)
const int clampedBits =... | magicoder | cpp |
You are tasked with implementing a custom smart pointer in Rust. Smart pointers are data structures that act like pointers but also have additional metadata and capabilities. In this case, you need to implement the `DerefMut` trait for a custom smart pointer type.
The `DerefMut` trait in Rust is used to overload the d... | ```rust
impl<T> std::ops::DerefMut for CustomSmartPointer<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self._value
}
}
fn main() {
let mut data = CustomSmartPointer::new(42);
*data = 10; // This modifies the inner value of the smart pointer
println!("{}", *data); // This prints 10
}
```
I... | magicoder | rust |
You are tasked with implementing a function that parses restaurant data from a website using Python and the Beautiful Soup library. The function should extract specific information from the HTML of a restaurant page and return it in a structured format.
You are given the following code snippet as a starting point:
``... | ```python
import requests
from bs4 import BeautifulSoup
def parse_restaurant(name, url):
data = {
'name': None,
'address': None,
'phone': None,
'hours': None,
'menu': None
}
# Send a GET request to the restaurant's webpage
response = requests.get(url)
if re... | magicoder | python |
You are tasked with implementing a logging system in Swift. The provided code snippet is a part of a logging framework and defines a static method `warning` within a class. The `warning` method takes a message as input and logs it with a prefix "[WARNING]" using another method `log` with the log level `LogLevel.Warning... | ```swift
// Define the LogLevel enum
enum LogLevel {
case Info
case Warning
case Error
}
// Complete the logging framework
class Logger {
public static func log(_ msg: String, _ level: LogLevel) {
switch level {
case .Info:
print("[INFO] \(msg)")
case .Wa... | magicoder | swift |
You are tasked with implementing a callback timer class in C++ that allows users to register callback functions and execute them after a specified time interval. The timer should support starting, stopping, and resetting, and it should be able to handle multiple concurrent timers.
Your task is to design and implement ... | ```cpp
#include <iostream>
#include <functional>
#include <chrono>
#include <thread>
class CCallbackTimer {
public:
using CallbackFunction = std::function<void()>;
void RegisterCallback(CallbackFunction callback, std::chrono::milliseconds delay) {
m_callback = std::move(callback);
m_delay = de... | magicoder | cpp |
You are tasked with creating a Python script that simulates a simple server-client interaction. The server script (`ta3ta2.server`) and the client test script (`ta3ta2.test_server`) are provided. Your goal is to write a Python script that automates the process of starting the server, waiting for it to initialize, and t... | ```python
import subprocess
import time
import os
# Terminate any existing Python processes
subprocess.run(["pkill", "-9", "python"])
# Start the server script in the background and redirect output
server_process = subprocess.Popen(["python", "-m", "ta3ta2.server"], stdout=open("/tmp/server_out", "w"), stderr=subproc... | magicoder | python |
You are tasked with creating a Python function that processes medical imaging data and organizes it into appropriate directories based on certain conditions. The function should take in a folder path containing DICOM series data and a case ID, and then convert the DICOM series to NIfTI format. Depending on the folder s... | ```python
from pathlib import Path
import dicom2nifti
def process_medical_data(folder_path: str, case_id: str, output_dir: str) -> str:
folder = Path(folder_path)
output_dir = Path(output_dir)
if folder.parts[-3] == 'VIP_CUP18_TestData':
output_path = output_dir / 'testing' / f"{case_id}.nii.gz"
... | magicoder | python |
You are tasked with creating a Python function that sends emails using the SendGrid API. Your function should take in the recipient's email address, the email subject, the email template, and any additional keyword arguments for the template. The function should use the SendGrid API to send the email asynchronously.
C... | ```python
import sendgrid
from flask import current_app
def send_email_async(to, subject, template, **kwargs):
app = current_app._get_current_object()
sg = sendgrid.SendGridAPIClient(apikey=app.config['SENDGRID_API_KEY'])
mail = {
"personalizations": [
{
"to": [
... | magicoder | python |
You are tasked with creating a word grid game using HTML, CSS, and JavaScript. The game will present the player with a grid of letters and the player's objective is to find as many words as possible by connecting adjacent letters in the grid. The game will have a timer and a score counter to track the player's performa... | ```javascript
// Define the grid of letters
const grid = [
['A', 'B', 'C', 'D'],
['E', 'F', 'G', 'H'],
['I', 'J', 'K', 'L'],
['M', 'N', 'O', 'P']
];
// Define the list of acceptable words
const acceptableWords = ['DOG', 'CAT', 'FISH', 'BIRD', 'LION', 'BEAR'];
// Initialize game variables
let selectedLetters =... | magicoder | javascript |
You are tasked with implementing a data structure to store key-value pairs and a function to retrieve the value associated with a given key. The data structure should support adding new key-value pairs, updating existing values, and retrieving values by their keys. Additionally, you need to write a function to perform ... | ```rust
fn double_numeric_values(data_structure: &mut DataStructure) {
for pair in &mut data_structure.values {
if let Ok(key) = pair.key.parse::<i32>() {
pair.value = (2 * key).to_string();
}
}
}
fn main() {
let mut target = DataStructure::new();
target.add("1", "one");
... | magicoder | rust |
You are tasked with implementing a simulation program that generates maps based on certain parameters. The code snippet provided is a part of this simulation program and involves generating simulated maps using a random draw function. The simulation can be configured to use either a logarithmic scale for the parameter ... | ```python
import numpy as np
from typing import List, Callable
def generate_simulated_maps(a: List[float], t_masked_compressed: np.ndarray, n_sim_per_chunk: int, poisson_a_is_log: bool, random_draw_fn: Callable) -> np.ndarray:
sim_maps = np.empty((n_sim_per_chunk, *t_masked_compressed.shape), dtype=t_masked_compre... | magicoder | python |
You are tasked with implementing a function to validate user input for a registration form. The function should ensure that the provided user data meets certain criteria before allowing the user to be added to the system. The user data includes the user's name, email, and password. Your task is to create a function tha... | ```php
function validateUserData(array $userData): bool {
// Validate name
if (empty($userData['name']) || !ctype_alpha(str_replace(' ', '', $userData['name']))) {
return false;
}
// Validate email
if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) {
return false;
}... | magicoder | php |
You are tasked with creating a Python class that implements a file filtering mechanism. The class should be able to filter files based on certain criteria, such as file extension, size, or creation date. Your task is to design and implement the `FileFilter` class with the following requirements:
- The `FileFilter` cla... | ```python
from abc import ABC, abstractmethod
import os
class FileFilter(ABC):
@abstractmethod
def filter_files(self, file_list):
pass
def __init__(self):
if type(self) is FileFilter:
raise TypeError("Can't instantiate abstract class FileFilter")
class ExtensionFilter(FileFilt... | magicoder | python |
You are tasked with implementing a simple web application authentication system using PHP. The provided code snippet is a simplified representation of the authentication logic. Your goal is to expand upon this code to create a complete authentication system.
Your task is to create a PHP class that manages user authent... | ```php
<?php
class Authentication {
public function login($username, $password) {
// Perform user authentication logic, e.g., check credentials against a database
if ($this->validateUser($username, $password)) {
$_SESSION["admin_id"] = $username; // Set the user's session
View::load("index"); // R... | magicoder | php |
You are tasked with implementing a Python class that represents a simple tree structure. The tree will consist of nodes, each of which can have an arbitrary number of child nodes. Your task is to implement the `Root` class, which will serve as the root node of the tree.
The `Root` class should have the following prope... | ```python
class Root:
def __init__(self, value):
self.value = value
self.children = []
def add_child(self, child):
self.children.append(child)
def get_children(self):
return self.children
def get_value(self):
return self.value
```
The `Root` class is implemente... | magicoder | python |
You are tasked with implementing a function that determines whether a given symbol has any nested types. A symbol in this context refers to a construct in a programming language, such as a class, interface, or struct. The function should take the symbol as input and return a boolean value indicating whether the symbol ... | ```python
def has_nested_types(symbol):
# Check if the symbol has nested types
# Replace this logic with language-specific code to retrieve nested types
nested_types = get_nested_types(symbol)
# Check if the retrieved nested types are empty or null
if nested_types is None or len(nested_types) == 0:... | magicoder | python |
You are tasked with implementing a custom property wrapper in Swift that enforces a specific behavior for a property. Your property wrapper should ensure that the property it wraps always has a non-nil value when accessed, and it should provide a default value if the property is accessed before being explicitly set.
Y... | ```swift
// Define the NonNilDefault property wrapper
@propertyWrapper
struct NonNilDefault {
private var value: String?
var wrappedValue: String {
get {
return value ?? "Default Value"
}
set {
if let newValue = newValue {
value = newValue
... | magicoder | swift |
You are tasked with creating a program to decrypt a message encrypted using a specific algorithm. The encrypted message is in the form of a string, and the decryption process involves reversing the encryption algorithm. The encryption algorithm works by shifting each letter in the message by a certain number of positio... | ```python
def decrypt_message(encrypted_message, shift):
decrypted_message = ""
for char in encrypted_message:
if char.isalpha():
shifted_char = chr(((ord(char) - shift - 65) % 26) + 65) if char.isupper() else chr(((ord(char) - shift - 97) % 26) + 97)
decrypted_message += shifted... | magicoder | python |
You are given a Python code snippet that includes a call to a function `main()`. Your task is to implement the `main()` function to generate two distinct numbers and print them as the solutions.
The `main()` function should generate the numbers according to the following rules:
1. The first number should be the smalle... | ```python
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def main():
# Find the smallest ... | magicoder | python |
You are given a list of integers representing the scores of a game. Your task is to write a function that calculates the average score of the game, excluding the highest and lowest scores.
Write a function `calculateAverageScore(scores)` that takes in a list of integers `scores` and returns the average score, rounded ... | ```python
def calculateAverageScore(scores):
scores.sort() # Sort the scores in ascending order
scores = scores[1:-1] # Exclude the highest and lowest scores
average_score = round(sum(scores) / len(scores)) # Calculate the average score and round to the nearest whole number
return average_score
```
T... | magicoder | python |
You are tasked with creating a program to manage and organize image files based on specific criteria. The program should take a directory path as input and perform the following operations on the image files within the directory:
1. If an image file with the suffix "_Z-axis.png" exists, it should be removed.
2. If an ... | ```python
import os
def manage_image_files(directory_path: str, tcp_client_socket) -> None:
for file_suffix in ["_Z-axis.png", "_X-axis.png", "_combined.png"]:
file_path = os.path.join(directory_path, "*" + file_suffix)
matching_files = glob.glob(file_path)
if matching_files:
fo... | magicoder | python |
You are tasked with implementing a circular queue data structure in Python. A circular queue is a data structure that follows the FIFO (First In, First Out) principle and has a fixed size. When the queue is full and a new element is enqueued, the oldest element in the queue is dequeued to make space for the new element... | ```python
class CircularQueue:
def __init__(self, k):
self.size = k
self.queue = [None] * k
self.front = self.rear = -1
def enQueue(self, value):
if self.isFull():
self.deQueue()
if self.isEmpty():
self.front = 0
self.rear = (self.rear + 1... | magicoder | python |
You are tasked with implementing a function `crop_classes(train_geo)` that takes a list of geographical coordinates representing train stations and returns a dictionary containing the count of train stations in each class of service. Each geographical coordinate is represented as a tuple of latitude and longitude. The ... | ```python
def crop_classes(train_geo):
class_counts = {1: 0, 2: 0, 3: 0}
for station in train_geo:
latitude, longitude = station
if latitude > 45 and longitude < -100:
class_counts[1] += 1
elif latitude < 45 and longitude > -100:
class_counts[2] += 1
... | magicoder | python |
You are tasked with implementing a function to calculate the cumulative probability within a given range for a normal distribution. The function `cumulative2` takes four parameters: `mean` (the mean of the normal distribution), `std` (the standard deviation of the normal distribution), `lower_range` (the lower bound of... | ```python
from scipy.stats import norm
def cumulative2(mean, std, lower_range, upper_range):
# Calculate the cumulative probability using the cumulative distribution function (CDF) of the normal distribution
cumulative_prob = norm.cdf(upper_range, loc=mean, scale=std) - norm.cdf(lower_range, loc=mean, scale=st... | magicoder | python |
You are tasked with creating a Python class that simulates a simple state machine. The state machine should have the ability to transition between different states based on input events. Your task is to implement the `StateMachine` class with the following specifications:
- The `StateMachine` class should have the fol... | ```python
class StateMachine:
def __init__(self, initial_state):
self._state = initial_state
self._transitions = {}
def add_transition(self, event, from_state, to_state):
if from_state not in self._transitions:
self._transitions[from_state] = {}
self._transitions[fro... | magicoder | python |
You are tasked with implementing a Rust function that processes a given `typ` and returns the corresponding `fe::TypeDesc` based on the pattern matching of the input. The `typ` is of type `FixedSize` and the function should handle the pattern matching for different cases of `FixedSize` and `Base` enums.
Write a functi... | ```rust
enum FixedSize {
Base(Base),
// other variants
}
enum Base {
Unit,
Int,
Float,
String,
// other variants
}
enum fe::TypeDesc {
Unit,
Int,
Float,
String,
// other variants
}
fn process_type(typ: FixedSize) -> fe::TypeDesc {
match typ {
FixedSize::Bas... | magicoder | rust |
You are tasked with implementing a custom documentation system for a software library. The system should support the concept of "documentation extensions," which allow developers to annotate their code with additional metadata for documentation generation.
Each documentation extension is represented by a class with th... | ```java
public class DocumentationExtension {
private String extensionName;
private MergeBehavior mergeBehavior;
public DocumentationExtension(String extensionName, MergeBehavior mergeBehavior) {
this.extensionName = extensionName;
this.mergeBehavior = mergeBehavior;
}
public Docum... | magicoder | java |
You are tasked with implementing a search functionality for a ratings system in a PHP application. The `search` method is responsible for retrieving ratings associated with a specific model and its related user information. The method takes a modelMorph object and an optional array of parameters as input. The `setParam... | ```php
/**
* search
*
* @param $modelMorph
* @param array $params
* @return mixed
*/
public function search($modelMorph, $params = [])
{
$params = $this->setParams($params);
$query = $modelMorph->ratings();
// Apply filtering based on the input parameters to the $query object
if (isset($params['m... | magicoder | php |
You are tasked with creating a program to manage the levels of service at a healthcare establishment. The establishment has a database with tables to store information about the levels of service and characterizations of the establishment. The snippet provided is a part of the SQL code used to create the table for the ... | ```python
import re
def parseSQLCreateTable(sql_code: str) -> dict:
pattern = r'CREATE TABLE IF NOT EXISTS (\w+)\.(\w+)\((.+)\);'
match = re.match(pattern, sql_code)
if match:
database_name = match.group(1)
table_name = match.group(2)
columns_info = match.group(3)
columns = ... | magicoder | python |
You are tasked with implementing a Python class that handles input and output operations for a specific data format. The class, named `DataHandler`, has several attributes and methods that need to be implemented. The provided code snippet is a part of the `DataHandler` class and shows the initialization and a method de... | ```python
class DataHandler:
def __init__(self, format, length, text=None, data=None):
if format.startswith("Fortran"):
self.format = FortranFormat(format)
else:
self.format = format
self.length = length
if text is None:
self._output()
if d... | magicoder | python |
You are tasked with creating a secure encryption oracle for a client's application. The encryption oracle takes a string as input and returns the encrypted version of the input. The encryption algorithm uses a custom XOR-based encryption method. However, the current implementation is vulnerable to a specific type of at... | The vulnerability in the current implementation lies in the fact that the encryption oracle does not authenticate the input before encryption, making it susceptible to bit-flipping attacks. An attacker can manipulate the encrypted data by flipping specific bits in the ciphertext, leading to potentially malicious behavi... | magicoder | python |
You are tasked with implementing a simplified version of a FIFO (First In, First Out) queue using Python. The FIFO queue should support the following operations:
1. `enqueue(item)`: Add an item to the end of the queue.
2. `dequeue()`: Remove and return the item at the front of the queue.
3. `is_empty()`: Return True if... | ```python
import os
class FifoQueue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, item):
new_node = Node(item)
if self.rear is None:
self.front = new_node
self.rear = new_node
else:
self.rear.next = new_nod... | magicoder | python |
You are working for a data science company that specializes in building machine learning models for various applications. Your task is to create a Python function that loads a pre-trained machine learning model and returns it. The model is saved using the joblib library, and it is expected to be a RandomForestClassifie... | ```python
from sklearn.ensemble import RandomForestClassifier
import joblib
def load_model(MODEL_NAME: str) -> RandomForestClassifier:
"""
Load a pre-trained RandomForestClassifier model from the given file path.
Args:
MODEL_NAME (str): The file path of the pre-trained model.
Returns:
RandomF... | magicoder | python |
You are tasked with implementing a Python class that can generate human-readable descriptions of cron expressions. A cron expression is a string representing a schedule, typically used to set the time at which a job should run. The expression consists of five space-separated fields: minute, hour, day of the month, mont... | ```python
class CronDescriptor:
def get_description(self, cron_expression):
parts = cron_expression.split()
minute = self.parse_field(parts[0], "minute")
hour = self.parse_field(parts[1], "hour")
day_of_month = self.parse_field(parts[2], "day of the month")
month = self.parse... | magicoder | python |
You are tasked with implementing a method to process and display member authorities in an Android application. The application uses AndroidAnnotations and RxJava for asynchronous operations.
You are given a class `SetEnterpriseAuthorityActivity` that extends `BackActivity` and is annotated with `@EActivity(R.layout.ac... | ```java
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
@EActivity(R.layout.activity_set_enterprise_authority)
public class SetEnter... | magicoder | java |
You are tasked with implementing a class for handling the impact of an instant kill ability in a game. The class should support serialization and deserialization of its data. The provided code snippet shows part of the implementation for the `InstantKillImpact` class, including methods for serialization and deserializa... | ```csharp
using System;
using System.Runtime.Serialization;
[Serializable]
public class InstantKillImpact : ISerializable
{
public double Chance { get; private set; }
public InstantKillImpact(double chance)
{
Chance = chance;
}
// Serialization constructor
protected InstantKillImpact(... | magicoder | csharp |
You are tasked with implementing a parallel processing algorithm for a genetic analysis tool. The provided code snippet is a part of a Python class that manages the parallel processing of genetic data using the Expasy database. The `run` method is responsible for dividing the genetic data into multiple processes and in... | ```python
def run(self, num_process):
self.num_process = num_process
num_total = len(self.gene_ls)
processes = []
for i in range(self.num_process):
start_point = i * (num_total // self.num_process)
end_point = (i + 1) * (num_total // self.num_process) if i < ... | magicoder | python |
You are tasked with implementing a Swift protocol for a cryptocurrency token swap feature. The protocol should provide a method for generating a URL to initiate the token swap and should also support registering additional token action services.
Your task is to create a Swift protocol called `TokenSwapURLProviderType`... | ```swift
// Define the protocol for token swap URL provider
protocol TokenSwapURLProviderType {
var action: String { get }
var rpcServer: RPCServer? { get }
var analyticsName: String { get }
func url(token: TokenObject) -> URL?
}
// Define the protocol for token actions service
protocol TokenActionsSer... | magicoder | swift |
You are tasked with implementing a simplified version of the `ssprintf` function in C. The `ssprintf` function is similar to the standard `sprintf` function, but it dynamically allocates memory for the resulting string. Your task is to create a function `my_ssprintf` that takes a format string and a variable number of ... | ```c
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
char* my_ssprintf(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
char buf[4097];
int len = vsnprintf(buf, 4096, fmt, ap);
va_end(ap);
if (len < 0) {
return NULL; // Error in formatting
}
char* result = (char*)malloc((len + 1... | magicoder | c |
You are tasked with creating a Python program to scrape statistics from a website using Selenium. The program should utilize a web browser to navigate to a webpage, find a list of stations, and then scrape statistics for each station using a function called `find_station`. The program should display the progress of the... | ```python
from selenium import webdriver
from tqdm import tqdm
class Station:
def __init__(self, name, url):
self.name = name
self.url = url
def find_stations(browser):
# Implement logic to find and return a list of Station objects using the provided browser
# Example:
# stations = [St... | magicoder | python |
You are tasked with implementing a Java class that represents a search query for a data search application. The search query should support filtering by multiple criteria and sorting the results based on specific fields. The class should also provide methods for adding filter criteria and sorting options.
Your task is... | ```java
package org.flockdata.search;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.Collection;
public class SearchQuery {
private Collection<String> filterCriteria;
private Collection<String> sortingOptions;
public SearchQuery() {
this.filterC... | magicoder | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.