query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are given a C++ code snippet that manipulates a string `s`. Your task is to understand the code and implement a function that replicates the same string manipulation logic.
The given code snippet is as follows:
```cpp
void manipulateString(string s) {
char *p = &s[0];
char *q = &s[s.size() - 1];
while (p <... | ```cpp
#include <iostream>
#include <string>
void manipulateString(std::string s) {
char *p = &s[0];
char *q = &s[s.size() - 1];
while (p < q) {
char tmp = *p;
*p = *q;
*q = tmp;
p++, q--;
}
std::cout << s << '\n';
}
int main() {
std::string input = "Hello, World!";
manipulateString(i... | magicoder | cpp |
You are tasked with implementing a custom macro for performing checked division in Rust. The macro should take two input expressions and return a `Result` containing the result of the division if it does not result in overflow/underflow, or an `ArithmeticError` if the operation does result in overflow/underflow.
Your ... | ```rust
use std::fmt;
// Custom error type for arithmetic errors
#[derive(Debug)]
struct ArithmeticError(String);
impl fmt::Display for ArithmeticError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Arithmetic error: {}", self.0)
}
}
macro_rules! checked_div {
// Base case fo... | magicoder | rust |
You are given a Python class `Example` with a method `baz` that takes an integer argument `n`. The method `baz` is intended to perform a specific operation based on the value of `n`. Your task is to complete the implementation of the `baz` method to satisfy the following requirements:
- If `n` is a positive integer, t... | ```python
class Example:
def baz(self, n):
if n > 0:
even_numbers = [str(i) for i in range(2, 2*n+1, 2)]
print(" ".join(even_numbers))
else:
print("Invalid input")
```
In this solution, the `baz` method first checks if the input `n` is positive. If it is, it crea... | magicoder | python |
You are tasked with implementing a Swift extension for a custom type that can convert instances of the type to a dictionary. The extension should provide a method to convert the custom type to a dictionary representation. You need to write the code for the extension method that accomplishes this task.
The custom type ... | ```swift
extension CustomType {
func toDictionary() -> [String: Any] {
let mirror = Mirror(reflecting: self)
var dictionary = [String: Any]()
for case let (label?, value) in mirror.children {
dictionary[label] = value
}
return dictionary
}
}
... | magicoder | swift |
You are working on a Python script that interacts with SharePoint using the SharePoint REST API. Your task is to implement a class method for creating a new SharePoint Team site and another method for deleting an existing site. The provided code snippet is part of the existing class, and you need to complete the implem... | ```python
class SharePointManager:
def __init__(self, context):
self.context = context
def create(self, site_name, site_description):
"""
Creates a new SharePoint Team site
:param site_name: Name of the new site
:param site_description: Description of the new site
... | magicoder | python |
You are tasked with creating a Rust library that interfaces with a C library called `phper`. The `phper` library provides functionality for working with PHP extensions in Rust. Your goal is to create a Rust struct that wraps a C struct from the `phper` library and implements the `Deref` and `DerefMut` traits to provide... | ```rust
use phper_sys::*;
use std::{
mem::{forget, size_of},
ops::{Deref, DerefMut},
};
// Define the PhperWrapper struct
pub struct PhperWrapper {
inner: phper_sys::PhperStruct, // Replace with the actual C struct type from phper_sys
}
impl PhperWrapper {
// Create a new instance of PhperWrapper and ... | magicoder | rust |
You are tasked with creating a program to automate the testing of a web registration page. The program should be able to retrieve all the links present on the registration page and print them to the console. You are given a code snippet that initializes a `RegistrationPage` object and retrieves all the links from it.
... | ```java
import org.openqa.selenium.WebElement;
import java.util.List;
public class RegistrationPage {
private boolean isLoggedIn;
public RegistrationPage(boolean isLoggedIn) {
this.isLoggedIn = isLoggedIn;
// Additional initialization if needed
}
public List<WebElement> getAllLinks() ... | magicoder | java |
You are working with a system that manages different versions of cluster images. The provided code snippet is a part of a script that retrieves the latest version of cluster images for versions 4.3, 4.4, 4.5, and 4.6. The script uses the `oc` command-line tool to interact with the system.
Your task is to write a funct... | ```bash
#!/bin/bash
# Function to retrieve the latest version of cluster images and shuffle the output
clusterimageset_latest() {
latest43=$(oc get clusterimageset | grep 4.3 | sort -r | head -n 1 | awk '{print $2}')
latest44=$(oc get clusterimageset | grep 4.4 | sort -r | head -n 1 | awk '{print $2}')
lat... | magicoder | shell |
You are tasked with creating a Python class that represents a task. The task has a name and a status. The status can be one of the following: "Incomplete", "InProgress", or "Complete". You need to define the class with appropriate attributes and methods to manipulate the task status.
Create a class `Task` with the fol... | ```python
class Task:
def __init__(self, name: str):
self.name = name
self.valid_statuses = {"Incomplete", "InProgress", "Complete"}
self.status = "Incomplete"
def update_status(self, new_status: str):
if new_status not in self.valid_statuses:
raise ValueError("Inval... | magicoder | python |
You are tasked with implementing a simple expression tree in Python. An expression tree is a binary tree used to represent expressions. Each node in the tree represents an operator or operand. Operators can be addition (+), subtraction (-), multiplication (*), or division (/), while operands are numerical values. The t... | ```python
class Expression:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def evaluate(self):
if self.value.isdigit():
return int(self.value)
else:
left_val = self.left.evaluate()
... | magicoder | python |
You are tasked with implementing a Python function to perform L0 smoothing on an input image. L0 smoothing is a technique used in image processing to reduce noise and enhance edges by selectively smoothing regions of an image. The function should take several input parameters and apply the L0 smoothing algorithm to the... | ```python
import numpy as np
def L0_smooth(input_image, output_image, k, l, verbose):
# Load the input image
img = load_image(input_image)
# Perform L0 smoothing
smoothed_img = l0_smoothing(img, k, l, verbose)
# Save the smoothed image
save_image(output_image, smoothed_img)
def load_image(im... | magicoder | python |
You are tasked with creating a simple to-do list application in Swift using SwiftUI. Your task is to implement a `TodoItem` view that displays a single to-do item. The `TodoItem` view should take two parameters: `main` of type `Main` and `todoIndex` of type `Binding<Int>`. The `main` parameter represents the main data ... | ```swift
import SwiftUI
struct TodoItem: View {
@ObservedObject var main: Main
@Binding var todoIndex: Int
var body: some View {
VStack {
Text(main.todos[todoIndex].title) // Display the title of the to-do item
Text(main.todos[todoIndex].description) // Display the descript... | magicoder | swift |
You are given a list of integers `nums`. Your task is to implement a function `count_pairs(nums)` that counts the number of pairs of indices `(i, j)` such that `i < j` and `nums[i] + nums[j]` is a power of 2.
For example, given the input `nums = [1, 2, 3, 4, 5, 6, 7, 8]`, the function should return 6, as there are 6 p... | ```python
from collections import defaultdict
from typing import List
def count_pairs(nums: List[int]) -> int:
power_of_two = set(2 ** i for i in range(22)) # Pre-calculate powers of 2 up to 2^21
count_map = defaultdict(int)
pairs_count = 0
for num in nums:
for power in power_of_two:
... | magicoder | python |
You are tasked with implementing a method to encode a Swift struct to form URL-encoded data for use in a network request. The given code snippet is a part of a Swift struct method that should return the struct's data in a form suitable for network requests. The struct, `RefreshTokensRequest`, has properties `grantType`... | ```swift
struct RefreshTokensRequest {
var grantType: String
var refreshToken: String
func formURLEncoded() -> Data {
// Assuming the availability of a helper method `formURLEncoded()` to encode key-value pairs
guard let data = [
"grantType": grantType,
"refreshT... | magicoder | swift |
You are tasked with implementing a pruning algorithm for a neural network model. The pruning algorithm aims to create a mask that identifies the least important weights in the model, allowing them to be pruned (removed) to reduce model size and computational cost. The pruning process involves the following parameters a... | ```python
def create_pruning_mask(model, pruning_rate, saliency_fn, mask=None, compare_fn=None):
if not mask:
mask = {}
for layer in model.layers:
saliency_weights = saliency_fn(layer) # Calculate saliency weights for the layer
sorted_indices = sorted(range(len(saliency_weights)), ... | magicoder | python |
You are tasked with implementing a custom attribute system in C#. Custom attributes are a powerful feature in C# that allow you to add metadata to types and their members. In this problem, you will create a custom attribute called "UsageAttribute" and apply it to properties of a class. The attribute will have two named... | ```csharp
public class AttributeCalculator
{
public int CalculateTotalValue(MyClass obj)
{
int totalValue = 0;
var properties = typeof(MyClass).GetProperties();
foreach (var property in properties)
{
var attribute = (UsageAttribute)Attribute.GetCustomAttribute(proper... | magicoder | csharp |
You are tasked with implementing a device management system for a laboratory. The system should allow users to add, remove, and retrieve information about various devices used in the laboratory. Each device is uniquely identified by a name and has associated attributes such as type, status, and location.
You need to i... | ```python
class Device:
def __init__(self, name, type, status, location):
self.name = name
self.type = type
self.status = status
self.location = location
def __str__(self):
return f"{self.name}: {self.type}, {self.status}, {self.location}"
class DeviceManager:
def _... | magicoder | python |
You are tasked with implementing a finite state machine (FSM) in Python. The FSM should support the following operations:
1. Initializing the FSM with a set of states, a current state, a set of non-accepting states, and a set of transition functions.
2. Setting the number of states in the FSM.
3. Adding a transition f... | ```python
class FSM:
def __init__(self):
self.states = []
self.curState = 0
self.nonAccepting = []
self.pk = []
def set_statesNo(self, newNo):
self.statesNo = newNo
def add_transition_function(self, func):
self.pk.append(func)
def transition(self, input... | magicoder | python |
You are tasked with implementing a C++ program that processes a list of transactions and calculates the total amount of money spent by each user. Each transaction is represented by a tuple containing the user ID, transaction type, and transaction amount. The program should output the total amount spent by each user.
Y... | ```cpp
#include <iostream>
#include <vector>
#include <tuple>
#include <map>
std::map<std::string, double> calculateTotalSpentByUser(const std::vector<std::tuple<std::string, std::string, double>>& transactions) {
std::map<std::string, double> totalSpentByUser;
for (const auto& transaction : transactions) {
... | magicoder | cpp |
You are tasked with creating a Rust function that processes a given directory and its subdirectories to identify and list all files with a specific file extension. Your task is to implement the `find_files_with_extension` function, which takes two parameters: a reference to a `Path` representing the root directory and ... | ```rust
use std::path::Path;
use std::fs;
fn find_files_with_extension(root_dir: &Path, extension: &str) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
if let Ok(entries) = fs::read_dir(root_dir) {
for entry in entries {
if let Ok(entry) = entry {
let path = ent... | magicoder | rust |
You are tasked with creating a program that processes a list of authors and their corresponding contact information. The program should be able to parse the input data and generate a formatted output for each author. The input data will consist of the author's name, pseudonym, and email address. The output should displ... | To solve this problem, you can create a program in Java that reads the input data, processes it, and generates the formatted output for each author. Here's a sample solution:
```java
import java.util.Scanner;
public class AuthorInfoProcessor {
public static void main(String[] args) {
Scanner scanner = new... | magicoder | java |
You are tasked with creating a program that simulates a simple text-based game. The game involves a character navigating through a grid-based world, collecting treasures, and avoiding obstacles. The character's movements are controlled by a sequence of commands, and the game ends when all treasures are collected or the... | ```python
def simulateGame(grid, commands):
treasures = set(str(i) for i in range(1, 10))
position = None
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 'S':
position = (i, j)
break
for command in commands:
if comma... | magicoder | python |
You are tasked with implementing a function that processes a given Twemoji index and generates SVG elements for emojis. The function should take in the Twemoji index, along with other relevant parameters, and return the corresponding SVG element.
Write a function `generate_svg_element` that takes the following paramet... | ```python
def generate_svg_element(index, shortname, alias, uc, alt, title, category, options, md):
"""Return SVG element for the given emoji."""
emoji_data = index.get(shortname)
if emoji_data:
svg_options = " ".join([f'{key}="{value}"' for key, value in options.items()])
svg_element = f'<s... | magicoder | python |
You are tasked with implementing a custom error handling system in Swift for a fictional e-commerce platform called MiaoCai. The platform needs a robust error framework to handle various types of errors that can occur during its operation. Your task is to create a custom error type and implement a mechanism to throw an... | ```swift
// MCError.swift
// MiaoCai
enum MCError: Error {
case networkError(String)
case inputError(String)
case serverError(String)
}
func processOrder(orderRequest: String) throws -> String {
// Simulate network error
let isNetworkError = false
if isNetworkError {
throw MCError.netw... | magicoder | swift |
You are tasked with creating a Python class that simulates data for a fictional online marketplace. The class should generate simulated data for products, customers, and transactions. The data simulation should include various attributes for products (e.g., name, price, category), customers (e.g., name, age, location),... | ```python
from utils.datasimulation import DataSimulation
class MarketplaceDataSimulator:
def __init__(self):
self.products = []
self.customers = []
self.transactions = []
def generate_products(self, num_products):
self.products = DataSimulation.generate_products(num_products)
... | magicoder | python |
You are tasked with creating a Python class that manages configuration settings for a web application. The class should allow for the dynamic addition and retrieval of configuration settings, as well as the ability to check if a setting exists. Additionally, the class should provide a method to load configuration setti... | ```python
class Config:
def __init__(self):
self.settings = {}
def set_config(self, key, value):
self.settings[key] = value
def get_config(self, key):
return self.settings.get(key)
def has_config(self, key):
return key in self.settings
def load_from_file(self, fil... | magicoder | python |
You are tasked with implementing a custom logging macro in Rust. The macro should take a quoted expression as input and log the value of the expression. Your task is to create the macro `read_log!` that takes a quoted expression as input and logs the value of the expression.
The macro should be used as follows:
```ru... | ```rust
macro_rules! read_log {
($expr:tt) => {
println!("Value of expression: {}", $expr);
};
}
fn test_ident() {
let x = 1;
let output = read_log!(q!(x));
}
```
In the solution, the `read_log!` macro is implemented using the `macro_rules!` macro in Rust. It takes a quoted expression as input... | magicoder | rust |
You are given two arrays `x` and `w`, representing vectors in a mathematical space. The arrays have the following dimensions:
- `x` has the shape `[batch_size, vector_dimension]`
- `w` has the shape `[vector_dimension, out_planes]`
Your task is to write a function `calculate_similarity(x, w)` that calculates the cosin... | ```python
import numpy as np
def calculate_similarity(x, w):
x_modulus = np.sqrt(np.sum(np.power(x, 2), axis=1)) # Magnitude of each vector in x
w_modulus = np.sqrt(np.sum(np.power(w, 2), axis=0)) # Magnitude of each vector in w
dot_product = np.dot(x, w) # Dot product of x and w
cosine_sim = dot_p... | magicoder | python |
You are tasked with implementing a function that converts a given RFC 3339 timestamp to a `LocalDateTime` object. The RFC 3339 timestamp format is a profile of the ISO 8601 standard for date and time formats. It represents a date and time in Coordinated Universal Time (UTC), with the timezone offset specified as "Z" fo... | ```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class RFC3339Converter {
public static LocalDateTime convertRFC3339ToDateTime(String timestamp) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T... | magicoder | java |
You are tasked with implementing a simple cache system using object-oriented programming in TypeScript. The cache system should store key-value pairs and have the ability to retrieve, add, and remove entries. Additionally, the cache should have a maximum capacity, and when the capacity is reached, the least recently us... | ```typescript
class LRUCache {
private capacity: number;
private cache: Map<string, number>;
private accessOrder: string[];
constructor(capacity: number) {
this.capacity = capacity;
this.cache = new Map();
this.accessOrder = [];
}
get(key: string): number {
if (this.cache.has(key)) {
... | magicoder | typescript |
You are tasked with implementing a simple WebSocket server in C#. The server should be able to handle incoming HTTP connections with the "Upgrade: websocket" header data and establish WebSocket connections with clients.
Your task is to complete the implementation of the `UseWebSockets` extension method for the `IHorse... | ```csharp
using System;
using System.Net.WebSockets;
using System.Threading.Tasks;
public static class HorseServerExtensions
{
public static IHorseServer UseWebSockets(this IHorseServer server, WebSocketConnectedHandler connectedAction)
{
// Assume server implementation for handling HTTP connections
... | magicoder | csharp |
You are tasked with creating a command-line interface (CLI) tool for a software build system. The tool should support building different targets with various configurations and options. Your task is to implement a Python CLI using the `click` library to achieve this functionality.
Your CLI tool should have the followi... | ```python
import click
@click.group()
def cli():
pass
@cli.command()
@click.argument('target')
@click.option('--nogl', is_flag=True, help='Build without OpenGL support')
@click.option('--config', default='Release', help='Build configuration (default: Release)')
@click.option('--option', help='Additional build opt... | magicoder | python |
You are tasked with implementing a custom collection view layout and its delegate methods in Swift. The layout, `CollectionViewPagingLayout`, is designed to support a paging behavior for a collection view, and the delegate, `CollectionViewPagingLayoutDelegate`, provides methods for handling user interactions and tracki... | ```swift
// Define the CollectionViewPagingLayout protocol
protocol CollectionViewPagingLayout: AnyObject {
func collectionViewPagingLayout(_ layout: CollectionViewPagingLayout, didSelectItemAt indexPath: IndexPath)
}
// Define the CollectionViewPagingLayoutDelegate protocol
protocol CollectionViewPagingLayoutDele... | magicoder | swift |
You are tasked with creating a program that processes linguistic treebanks using the Stanford NLP library. A linguistic treebank is a collection of parsed sentences represented as trees, where each node corresponds to a word or phrase in the sentence. The Stanford NLP library provides tools for working with linguistic ... | ```java
import edu.stanford.nlp.trees.MemoryTreebank;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.international.french.FrenchTreebankLanguagePack;
import edu.stanford.nlp.trees.international.french.FrenchXMLTreeReaderFactory;
import edu.stanford.nlp.trees.tregex.TregexPattern;
import edu.stanford.... | magicoder | java |
You are tasked with creating a Python decorator that logs the input arguments and return value of a given function. The decorator should use the `logging` module to log the information and should be flexible enough to work with functions of varying argument types and return values.
Your task is to implement the `log_f... | ```python
import logging
from functools import wraps
def log_function(logger):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
arg_list = [f"{k}={v}" for k, v in kwargs.items()]
arg_list.extend(map(str, args))
arg_str = ', '.join(arg_list)
... | magicoder | python |
You are given a list of integers. Your task is to write a Python function that takes this list as input and returns two separate lists: one containing all the even numbers that are divisible by 2, and the other containing all the odd numbers that are divisible by 3.
The function signature is:
```python
def find_divisi... | ```python
from typing import List, Tuple
def find_divisible_numbers(input_list: List[int]) -> Tuple[List[int], List[int]]:
div_by_2 = [num for num in input_list if num % 2 == 0]
div_by_3 = [num for num in input_list if num % 2 != 0 and num % 3 == 0]
return div_by_2, div_by_3
```
The `find_divisible_number... | magicoder | python |
You are tasked with implementing a custom string class in C++ that supports various string operations. Your task is to create a class `CustomString` that encapsulates a string and provides methods for string manipulation.
The `CustomString` class should have the following public methods:
1. `CustomString()`: A default... | ```cpp
#include <cstring>
class CustomString {
private:
char* data;
public:
CustomString() : data(nullptr) {}
CustomString(const char* str) {
size_t len = strlen(str);
data = new char[len + 1];
strcpy(data, str);
}
CustomString(const CustomString& other) {
size_t ... | magicoder | cpp |
You are tasked with implementing a function that processes a list of labels and returns the unique labels in the order they first appear. However, the given code snippet contains an error that prevents the labels from being appended correctly. Your task is to identify and fix the error in the code snippet and then impl... | The error in the code snippet is that the `try-except` block is not necessary and does not serve any purpose. It is attempting to catch an exception that is not being raised during the appending of labels. Therefore, the `try-except` block can be removed.
Here's the corrected code snippet:
```python
labels = []
for la... | magicoder | python |
You are tasked with creating a Python script that automates the process of organizing files in a directory. Your script should categorize files based on their extensions and move them into separate subdirectories. For example, all ".txt" files should be moved to a "txt_files" subdirectory, all ".jpg" files to a "jpg_fi... | ```python
import os
import shutil
def organize_files(source_dir):
extensions = {} # Dictionary to store file extensions and their corresponding paths
for root, _, files in os.walk(source_dir):
for file in files:
file_path = os.path.join(root, file)
file_ext = os.path.splitext(f... | magicoder | python |
You are tasked with implementing a function that recombines candidate spots based on their IDs. The function takes in four parameters: `repeat_cand_spots`, `repeat_ids`, `original_cand_spots`, and `original_ids`. The `repeat_cand_spots` and `repeat_ids` represent the candidate spots and their corresponding IDs for a re... | ```python
def recombine_candidate_spots(repeat_cand_spots, repeat_ids, original_cand_spots, original_ids):
if len(repeat_cand_spots) != len(repeat_ids):
raise IndexError(f"Wrong length of repeat candidate spots")
if len(original_cand_spots) != len(original_ids):
raise IndexError(f"Wrong length o... | magicoder | python |
You are tasked with creating a Python module that manages user authentication and access control for a web application. The module should include functionality for user registration, login, and authorization checks for various resources within the application.
Your task is to implement the `auth.py` module, which will... | ```python
# auth.py
from ._utfiles import *
from ._utconfig import *
from ._uttime import *
# Placeholder for user credentials storage
user_credentials = {}
def register_user(username, password):
# Store user credentials securely (e.g., using hashing and salting)
hashed_password = hash_password(password)
... | magicoder | python |
You are tasked with implementing a function that checks whether a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, "racecar" and "A man a plan a canal Pan... | ```c
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
bool isPalindrome(const char *str) {
int left = 0;
int right = strlen(str) - 1;
while (left < right) {
while (!isalnum(str[left]) && left < right) {
left++;
}
while (!isalnum(str[right]) && left < right) {... | magicoder | c |
You are tasked with simulating a version control system's status update and handling process. The given code snippet is part of a version control system script and involves retrieving status information, handling file changes, and updating the repository and staging area. Your task is to implement the functions `get_st... | ```python
def get_status_info(head_id):
# Simulated implementation of status.get_status_info
# Replace with actual implementation based on the version control system used
# For example, using GitPython library:
# import git
# repo = git.Repo('.')
# status = repo.git.status()
# to_be_committe... | magicoder | python |
You are given a list of integers `nums`. Your task is to write a function `longestConsecutive` that finds the length of the longest consecutive elements sequence in the list. A consecutive sequence is a sequence of numbers where each number appears exactly once and the difference between consecutive numbers is 1.
Your... | ```python
def longestConsecutive(nums):
s = set(nums) # Convert the list to a set for O(1) lookup
longest_streak = 0
for num in s:
if num - 1 not in s: # Check if num-1 exists in the set
current_num = num
current_streak = 1
while current_num + 1 in s: # Find ... | magicoder | python |
You are tasked with creating a Telegram bot that facilitates the even distribution of participants into different rooms. The bot should be able to handle user requests to change rooms and provide them with the necessary information. You are provided with a code snippet that includes the Telegram token, relative chat ID... | ```python
import requests
TELEGRAM_TOKEN = "..." # Replace with actual token
RELATIVE_CHAT_IDS = ["...", "..."] # Replace with actual chat IDs
TEXT = {
"bot_info": ('Привет, я бот, который отвечает за равномерное распределение участников по комнатам.\n\n'
'Нажми кнопку, если готов сменить комна... | magicoder | python |
You are tasked with creating a Python function that processes an image and performs foreground and background color adjustments. The function should take an image file path, width, height, foreground color, and background color as input and return the processed image. The image processing involves resizing the image, n... | ```python
import numpy as np
from PIL import Image
def process_image(image_path: str, width: int, height: int, foregrounds: str, backgrounds: str) -> np.ndarray:
img = np.array(Image.open(image_path).resize((width, height)))
img = img / 255
foreground_color = tuple(map(int, foregrounds.split(',')))
ba... | magicoder | python |
You are working with a dataset containing information about entities and their attributes. The dataset is represented as a DataFrame in a Python environment using a library like PySpark. Your task is to write a function that filters and processes this DataFrame based on certain conditions and returns a limited set of r... | ```python
from pyspark.sql import functions as F
def process_entities(df1, e, targetType, minScore, maxCount):
if targetType == '':
df2 = df1.where(df1.EntityId != e)
else:
df2 = df1.where((df1.EntityId != e) & (df1.EntityType == targetType))
df3 = df2.select(df2.EntityId, df2.EntityType, ... | magicoder | python |
You are tasked with creating a Bash script that will recursively search for files with a specific extension within a given directory and its subdirectories. Your script should take two command-line arguments: the directory to search in and the file extension to look for. The script should then output the absolute paths... | ```bash
#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <directory> <file_extension>"
exit 1
fi
# Check if the provided directory exists
if [ ! -d "$1" ]; then
echo "Error: Directory $1 does not exist."
exit 1
fi
# Use find command to search ... | magicoder | shell |
You are tasked with implementing a program that can parse and extract information from a C/C++ header file. The header file contains function prototypes and may include comments and other miscellaneous content. Your program needs to extract the function prototypes and store them in a data structure for further processi... | ```python
from typing import List
import re
def extractFunctionPrototypes(headerContent: str) -> List[str]:
prototypes = re.findall(r'\b\w+\s+\w+\s*\([^;]*\);', headerContent)
return prototypes
```
The `extractFunctionPrototypes` function uses the `re.findall` method to search for function prototypes in the `... | magicoder | python |
You are tasked with creating a script that monitors the CPU usage of a Linux system and takes action based on the usage level. The script should continuously check the CPU usage and perform different actions depending on whether the usage is high or low.
Your script should include the following components:
1. A while ... | ```bash
#!/bin/bash
while true
do
# Get the current CPU usage
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
# Define the thresholds for high and low CPU usage
high_threshold=80
low_threshold=20
if (( $(echo "$cpu_usage > $high_threshold" | bc -l) )); then
echo "High CP... | magicoder | shell |
You are tasked with implementing a Python function that processes the results of a machine learning experiment stored in a pickle file. The pickle file contains dictionaries with results from different models and their predictions. Your goal is to extract specific information from the pickle file and perform some calcu... | ```python
import pickle
import numpy as np
def process_ml_results(pickle_file, dataset_name):
# Load the pickle file
with open(pickle_file, 'rb') as f:
results = pickle.load(f)
# Extract results for CLD (Cross Label Dependency) and Powerset models
cld_results = results['cld']
powerset_resu... | magicoder | python |
You are tasked with creating a Python class to represent an article in a warehouse management system. The class should have attributes to store the name, description, price, total quantity in shelf, and total quantity in vault of the article. Additionally, you need to implement methods to update the quantities and calc... | ```python
class Article:
def __init__(self, name: str, description: str, price: float, total_in_shelf: int, total_in_vault: int):
self.name = name
self.description = description
self.price = price
self.total_in_shelf = total_in_shelf
self.total_in_vault = total_in_vault
... | magicoder | python |
You are tasked with implementing a file encryption and decryption system using Java's cryptography libraries. The given code snippet is part of a class that handles the generation of encryption keys and the encryption of data using RSA and AES algorithms.
Your task is to complete the implementation of the `decrypt` me... | ```java
public byte[] decrypt(String encryptedData) throws IOException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
rsaCipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
byte[] decryptedAesKey = rsaCipher.doFinal(Base64.getDecoder().decode(encryptedData));
SecretKeySpec aesKeySpec =... | magicoder | java |
You are tasked with creating a Python class that encapsulates the functionality of a simple bank account. The class should support basic operations such as depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should have a method to calculate the interest accrued on the account... | ```python
class BankAccount:
def __init__(self, initial_balance, annual_interest_rate):
self.balance = initial_balance
self.annual_interest_rate = annual_interest_rate / 100 # Convert percentage to decimal
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount... | magicoder | python |
You are working on a geographic information system (GIS) project and need to write a Python function to calculate the total serviceable coverage when two facility layers are used. The function should merge polygons from the input layers and dissolve them to form one large area of total coverage.
You are given the foll... | ```python
def generate_serviceable_demand(dl, dl_demand_field, dl_id_field, *args):
"""
Finds to total serviceable coverage when 2 facility layers are used
Merges polygons & dissolves them to form one big area of total coverage
"""
# Import necessary modules
from qgis.analysis import QgsGeometry... | magicoder | python |
You are tasked with implementing a simple property setter class in Java. The class should have methods to set the opacity and visibility properties of an object, as well as a method to retrieve the visibility property.
You are provided with a code snippet that demonstrates the usage of the setter class. Your task is t... | ```java
public class Setter {
public static void setOpacityProp(Object obj, float val) {
// Implementation to set the opacity property of the object
// Example: ((SomeObject) obj).setOpacity(val);
}
public static void setVisibilityProp(Object obj, int val) {
// Implementation to set... | magicoder | java |
You are tasked with implementing a custom error handling mechanism in C++. The provided code snippet shows a private class with two member variables: `err_id` of type `int` and `err_string` of type `std::string`. Your goal is to create a public interface for this error handling mechanism, allowing users to set error in... | ```cpp
#include <iostream>
#include <string>
class CustomError {
private:
int err_id;
std::string err_string;
public:
void setError(int id, const std::string& message) {
err_id = id;
err_string = message;
}
int getErrorID() const {
return err_id;
}
const std::stri... | magicoder | cpp |
You are given a Rust macro that takes an expression as input and returns a new expression that doubles the input expression. Your task is to implement the macro to achieve this functionality.
You need to define a macro called `double_expr` that takes an expression as input and returns a new expression that doubles the... | ```rust
macro_rules! double_expr {
// Base case: for literal values
($val:literal) => {
$val * 2
};
// Case for binary operations
($left:expr + $right:expr) => {
double_expr!($left) + double_expr!($right)
};
($left:expr - $right:expr) => {
double_expr!($left) - double... | magicoder | rust |
You are tasked with implementing a RESTful API endpoint for a shopping cart system. The provided code snippet is a part of the backend implementation using Python and Flask. Your task is to create a function that handles the addition of items to the shopping cart and returns the distributor ID based on the user's provi... | ```python
def add_to_cart(zipcode: str, item: dict) -> (dict, int):
# Simulating database query for ZIP code existence
zip_code_exists = check_zip_code_existence_in_database(zipcode)
if not zip_code_exists:
return {}, 404 # ZIP code not found in the database
# Simulate storing user's ... | magicoder | python |
You are tasked with implementing a matrix struct in Swift that supports basic matrix operations. The matrix struct should have the following functionalities:
1. A method `get` that retrieves the value at a specific row and column in the matrix.
2. A mutating method `set` that updates the value at a specific row and co... | ```swift
struct Matrix {
let rows: Int
let columns: Int
var grid: [Float]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row ... | magicoder | swift |
You are tasked with creating a script to monitor the logs of a Kubernetes deployment and perform specific actions based on the log output. Your script should continuously monitor the logs of the deployment named "flagger" in the "istio-system" namespace and take action when a specific success message is detected. The s... | ```python
import subprocess
def monitor_deployment_logs():
process = subprocess.Popen(
["kubectl", "-n", "istio-system", "logs", "deployment/flagger"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
while True:
line = process.stdout.readline().decode("utf-8").strip()
... | magicoder | python |
You are tasked with creating a Python script that automates the process of building and uploading a Python package to the Python Package Index (PyPI) using the `twine` package. Your script should handle the creation of source distribution and wheel distribution files, and then upload them to PyPI using `twine`.
Your s... | ```python
import subprocess
import sys
def build_and_upload_package():
try:
# Step 1: Create source distribution and wheel distribution
subprocess.run([sys.executable, "setup.py", "sdist", "bdist_wheel"], check=True)
# Step 2: Upload distribution files to PyPI using twine
subproces... | magicoder | python |
You are tasked with creating a Python module for musical notation. The module should include classes for representing musical notes and chords.
1. Create a class `Note` with the following attributes:
- `pitch`: a string representing the pitch of the note (e.g., "C", "D", "E", "F", "G", "A", "B")
- `octave`: an ... | ```python
class Note:
def __init__(self, pitch, octave):
self.pitch = pitch
self.octave = octave
class Chord:
def __init__(self, notes, chord_type):
self.notes = notes
self.chord_type = chord_type
```
This solution provides the required classes `Note` and `Chord` with their resp... | magicoder | python |
You are working on a project that involves visualizing and analyzing heatmaps of various structures. The project utilizes a Python library called `bgheatmaps` to generate heatmaps, plan routes, and extract slice coordinates from structures. You are tasked with creating a program that uses the functionalities provided b... | ```python
from bgheatmaps.heatmaps import heatmap
from bgheatmaps.planner import plan
from bgheatmaps.slicer import get_structures_slice_coords
def visualize_heatmaps(structures):
for structure in structures:
slice_coords = get_structures_slice_coords(structure)
route = plan(slice_coords)
h... | magicoder | python |
You are tasked with creating a Python function that takes in a JSON database, a database schema, and an index property, and returns a blueprint dictionary for a dataframe with the specified orientation.
The function should have the following signature:
```python
def notion_db_blueprint_df(db_json: dict, db_schema: dic... | ```python
def notion_db_blueprint_df(db_json: dict, db_schema: dict, index_prop: str) -> dict:
# Extracting the data from the JSON database
data = db_json.get("data", [])
# Creating the blueprint dictionary based on the schema
blueprint = {prop: {"type": db_schema[prop]} for prop in db_schema}
... | magicoder | python |
You are tasked with creating a Python function that extracts the copyright year range from a given code snippet. The code snippet will be a string containing Python code, and the function should return the copyright year range as a tuple of two integers representing the start and end years.
The function signature is:
... | ```python
import re
def extract_copyright_year_range(code_snippet: str) -> tuple:
pattern = r'Copyright (\d{4})-(\d{4})'
match = re.search(pattern, code_snippet)
if match:
start_year = int(match.group(1))
end_year = int(match.group(2))
return (start_year, end_year)
else:
... | magicoder | python |
You are tasked with implementing a function that processes a response containing a list of articles and their metadata. The function should handle different scenarios based on the status of the response and the number of articles received.
You are given a code snippet that checks the status of the articles and returns... | ```python
from typing import List, Tuple
def process_articles(articles) -> Tuple[List, int]:
if articles['status'] != 'OK':
num_of_articles = len(articles['response']['docs'])
if num_of_articles > 5:
return articles['response']['docs'][:5], articles['response']['meta']['hits']
e... | magicoder | python |
You are tasked with implementing a function to retrieve a list of photo albums from the user's photo library on iOS. Each album should be represented as an instance of the `YPAlbum` struct, which contains the album's thumbnail image, title, and the number of items (photos or videos) it contains.
You are given the `YPA... | ```swift
import UIKit
import Photos
struct YPAlbum {
var thumbnail: UIImage?
var title: String = ""
var numberOfItems: Int = 0
}
func fetchPhotoAlbums() -> [YPAlbum] {
var albums: [YPAlbum] = []
let fetchOptions = PHFetchOptions()
let userAlbums = PHAssetCollection.fetchAssetCollections(w... | magicoder | swift |
You are tasked with implementing a simplified version of the A* search algorithm to find the shortest path between two points on a 2D grid. The grid is represented as a 2D array of integers, where each integer represents the cost of moving through that cell. The algorithm should consider four possible movements: up, do... | ```swift
func findShortestPath(grid: [[Int]], start: (Int, Int), end: (Int, Int)) -> [(Int, Int)] {
let numRows = grid.count
let numCols = grid[0].count
var visited = Array(repeating: Array(repeating: false, count: numCols), count: numRows)
let directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
... | magicoder | swift |
You are tasked with creating a web application component that utilizes the Yew framework, a modern Rust framework for creating web apps. The component, `KeyPathSelector`, is responsible for fetching and displaying data from a remote server. The component needs to make use of the `FetchService` provided by Yew to retrie... | ```rust
use yew::{
format::{Nothing, Text},
services::{
fetch::{FetchTask, Request, Response, FetchService},
ConsoleService,
},
web_sys::{HtmlSelectElement, HtmlOptionElement},
Callback, html, Component, ComponentLink, Html, ShouldRender,
};
pub struct KeyPathSelector {
fetch_se... | magicoder | rust |
You are tasked with implementing a function to resize an image based on a given target size and content mode. The function should handle different scaling modes and apply optional effects such as bleed, opacity, corner radius, border, and content scale. The function should return the resized image according to the spec... | ```swift
func resizeImage(_ image: UIImage, targetSize: CGSize, mode: ContentMode, bleed: CGFloat, opaque: Bool, cornerRadius: CGFloat, border: Border?, contentScale: CGFloat) -> UIImage {
guard !image.size.equalTo(.zero) else { return image }
guard !targetSize.equalTo(.zero) else { return image }
var ... | magicoder | swift |
You are tasked with creating a Python script that reads a binary file and generates C++ header and source files containing the file's contents in a specific format. The script should take the file path, variable name, and output file paths as input and produce the required C++ files.
The Python script should perform t... | ```python
def generate_cpp_files(file_path, var_name, header_file_path, cpp_file_path):
with open(file_path, 'rb') as f:
bs = f.read()
with open(header_file_path, 'w') as header_file, open(cpp_file_path, 'w') as cpp_file:
header_file.write('extern const char %s[] PROGMEM;\n' % (var_name))
... | magicoder | python |
You are tasked with implementing a dependency resolution algorithm for a build system. The build system has a set of rules, each with its own dependencies. Your goal is to write a function that determines whether a given rule can be fulfilled based on its dependencies and the current state of the build system.
You are... | ```rust
use std::collections::HashMap;
struct Rule {
name: String,
dependencies: Vec<String>,
}
struct BuildSystemState {
visited: HashMap<String, bool>,
}
impl BuildSystemState {
fn new() -> BuildSystemState {
BuildSystemState {
visited: HashMap::new(),
}
}
fn is... | magicoder | rust |
You are tasked with implementing a GraphQL cost directive to manage and restrict the complexity of queries in a GraphQL schema. The cost directive will allow the server to calculate the cost of executing a query and enforce a maximum cost threshold. To achieve this, you need to define the cost directive, integrate it i... | ```python
# Define the GraphQLCostDirective class to implement the cost directive logic
class GraphQLCostDirective:
def __init__(self, max_cost):
self.max_cost = max_cost
def get_cost(self, query):
# Implement the logic to calculate the cost of executing a query based on complexity and depth
... | magicoder | python |
You are tasked with creating a Python script to automate the process of updating outdated packages in a virtual environment. Your script should parse the output of the `pip list --outdated --local` command, extract the names of outdated packages, and then update each package to the latest version using `pip install -U`... | ```python
import subprocess
def update_outdated_packages():
try:
# Run the command to get a list of outdated packages
outdated_packages_output = subprocess.check_output(['pip', 'list', '--outdated', '--local']).decode('utf-8')
# Extract the names of outdated packages
outdat... | magicoder | python |
You are tasked with implementing a parser for a simple configuration file format. The configuration file consists of key-value pairs, where each key and value are separated by an equal sign (=). The keys are alphanumeric strings, and the values can be alphanumeric strings or numerical values. The parser should be able ... | ```python
class ConfigParser:
def parse(self, file_path):
try:
with open(file_path, 'r') as file:
config_data = {}
for line in file:
line = line.strip()
if line and not line.startswith('#'):
key, valu... | magicoder | python |
You are given a list of integers `zcw_g`, which represents the values of `g` in a mathematical equation. Your task is to find the correct value of `g` based on the given list. The correct value of `g` is the smallest positive integer that satisfies the following conditions:
1. The value of `g` is greater than 0.
2. The... | ```python
from typing import List
def find_correct_g(zcw_g: List[int]) -> int:
a, b = zcw_g
g = 1
for i in range(1, min(abs(a), abs(b)) + 1):
if a % i == 0 and b % i == 0:
g = i
return g
```
The `find_correct_g` function takes the list `zcw_g` as input and initializes `g` to 1. It ... | magicoder | python |
You are tasked with creating a Python class that models a seating arrangement in a theater. The theater consists of multiple rows, and each row contains a number of rooms. Your task is to design a class structure to represent this seating arrangement and provide methods to book seats in the rooms.
Your class should ha... | ```python
class Room:
def __init__(self, room_num, num_seats):
self.room_num = room_num
self.num_seats = num_seats
class Row:
def __init__(self, row_num, rooms):
self.row_num = row_num
self.rooms = rooms
class Theater:
def __init__(self, rows):
self.rows = rows
... | magicoder | python |
You are tasked with simulating the behavior of a server state change testing framework. The given code snippet is a part of a unit test case for testing server state changes. The test case involves starting a server, loading definitions, and checking the server's state.
Your task is to implement a function that simula... | ```cpp
#include <iostream>
int simulateServerStateChanges() {
InvokeServer invokeServer("Client:: ...test_server_state_changes:", SCPort::next());
if (!invokeServer.server_started()) {
std::cerr << "Server failed to start on " << invokeServer.host() << ":" << invokeServer.port() << std::endl;
r... | magicoder | cpp |
You are tasked with implementing a method to convert a given date and time into a specific format and then calculate the corresponding integer value. Your task is to write a function that takes a date and time as input and returns the integer value based on the specified format.
Write a function `convertDateToInteger`... | ```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter {
public static Integer convertDateToInteger(Date inputDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHH");
String formattedDate = dateFormat.format(inputDate);
return Integer.... | magicoder | java |
You are tasked with creating a Bash script that manipulates file paths and extensions. Your script should define a function `init` that initializes several variables based on the file paths and extensions of the script itself and its caller. The script should then output the initialized variables.
The variables to be ... | ```bash
#!/bin/bash
init() {
TEST_NUM=0
# expecteds
CALLER_NAME="$(basename "${BASH_SOURCE:-$0}")"
CALLER_PARENT="$(cd $(dirname ${BASH_SOURCE:-$0}); pwd)"
CALLER_PATH="$CALLER_PARENT/$CALLER_NAME"
CALLER_EXT="${CALLER_NAME##*.}"
CALLER_NAME_ID="${CALLER_NAME%.*}"
SELF_NAME="path.sh"
SELF_PARENT="$(cd $(dirna... | magicoder | shell |
You are tasked with creating a Python program that simulates a simple game of rock-paper-scissors. The program should allow a user to play against the computer, which will randomly select its choice. The user's input will be case-insensitive and should be validated to ensure it is a valid choice (rock, paper, or scisso... | ```python
import random
def rock_paper_scissors_game(user_choice):
choices = ['rock', 'paper', 'scissors']
user_choice = user_choice.lower()
while user_choice not in choices:
user_choice = input("Invalid choice. Please enter rock, paper, or scissors: ").lower()
computer_choice = rando... | magicoder | python |
You are tasked with creating a custom form type in a Symfony application for handling loan reports. The loan report form should include a field for a specific entity called "SprawozdaniePozyczkoweSkladnikWydzielony" from the "Parp\SsfzBundle\Entity" namespace. Your task is to implement the custom form type class that e... | ```php
<?php
namespace Parp\SsfzBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Parp\SsfzBundle\Entity\SprawozdaniePozyczkoweSkladnikWydzielony;
class LoanReportType extends AbstractType
{
publi... | magicoder | php |
You are tasked with implementing a Python function that builds binaries with debug symbols using a given dictionary of build parameters. The function should support an optional clean flag to perform a clean build before creating the binaries. You are also required to implement the helper functions used within the main ... | ```python
def build_binaries(dictionary=None, clean=True):
"""Build the binaries with dsym debug info."""
commands = []
if clean:
commands.append(["make", "clean", getCmdLine(dictionary)])
commands.append(["make", "MAKE_DSYM=YES", getArchSpec(
dictionary.get('architecture')), getCCSpec(... | magicoder | python |
You are tasked with implementing a custom type manager in Python. The type manager is responsible for handling different types of data and their associated handlers. The provided code snippet is a starting point for the implementation, but it lacks essential functionality.
Your task is to extend the `TypeManager` clas... | ```python
from ._typehandler import * # noqa
@public
class TypeManager(object):
__slots__ = ('_state', '_handlers')
def __init__(self, state=None):
super(TypeManager, self).__init__()
self._state = state
self._handlers = {} # Initialize an empty dictionary to store type handlers
... | magicoder | python |
You are tasked with implementing a function to calculate the minimum energy of a given RNA secondary structure. The energy calculation involves various parameters and constraints, including penalties, stacking energies, and loop free energies. The provided code snippet is a part of an RNA secondary structure prediction... | ```cpp
// Include necessary headers and define relevant data structures and functions
// Define the function to calculate the minimum energy of the RNA secondary structure
int calculateMinimumEnergy(int i, int j, CTStructure* ct, EnergyData* data) {
int rarray = INT_MAX; // Initialize rarray with a large value
... | magicoder | cpp |
You are working as a DevOps engineer for a blockchain company. Your task is to write a Bash script that automates the process of mounting a disk to a specific directory. The script should handle potential errors and ensure that the disk is mounted successfully.
You are provided with a partial code snippet that sets th... | ```bash
#! /bin/bash
set -e
PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
MOUNT_DIR="/mnt/disks/blockchain"
# Check if the disk is already mounted and unmount if necessary
if grep -qs "$MOUNT_DIR" /proc/mounts; then
umount "$MOUNT_DIR"
fi
# Mount the disk to the specified directory
mount... | magicoder | shell |
You are working on a project that involves processing images of license plates. The project involves using the `pytesseract` library for optical character recognition (OCR) and custom functions for image processing and database operations. The code snippet provided sets some configurations and imports necessary modules... | ```python
import os
import sys
import pytesseract
from custom_plate import sql_inserter_fetcher
ImageFile.LOAD_TRUNCATED_IMAGES = True
sys.path.append("..")
def process_license_plate_image(image_path):
# Load the image and extract text using pytesseract
extracted_text = pytesseract.image_to_string(Image.open(... | magicoder | python |
You are working on a project that involves analyzing sea ice concentration data. The data is stored in a 3D NumPy array `sicmo`, representing sea ice concentration values over time and space. The first dimension represents time, the second dimension represents latitude, and the third dimension represents longitude. You... | ```python
import numpy as np
def calculate_mean_sic(sicmo, years, start_year, end_year):
yearq = np.where((years >= start_year) & (years <= end_year))[0]
mean_sic = np.nanmean(sicmo[yearq, :, :], axis=0) * 100
return mean_sic
```
The `calculate_mean_sic` function first identifies the indices of the years w... | magicoder | python |
You are tasked with creating a command-line tool that processes user input and performs specific actions based on the provided commands. The tool should support commands for adding, removing, and listing items. The input will be provided as command-line arguments in the following format:
```
python my_tool.py <command... | ```python
# my_tool.py
from . import cmdline
def main():
command = cmdline.get_command()
if command == 'add':
item = cmdline.get_argument()
cmdline.add_item(item)
elif command == 'remove':
item = cmdline.get_argument()
cmdline.remove_item(item)
elif command == 'list':
... | magicoder | python |
You are tasked with implementing a Java class to process and validate solicitation forms for a financial institution. The `SolicitacaoForm` class represents a solicitation form with the following attributes: `cpf` (Brazilian taxpayer registry number), `email`, `name`, `address`, and `income`.
Your task is to implement... | ```java
import java.util.regex.Pattern;
public class SolicitacaoForm {
private String cpf;
private String email;
private String name;
private String address;
private double income;
public SolicitacaoForm(String cpf, String email, String name, String address, double income) {
this.c... | magicoder | java |
You are given a list of tuples, where each tuple contains three elements: two strings and a boolean value. The first two elements are strings, and the third element is a boolean indicating whether the first string can be transformed into the second string with a single edit operation. The edit operations allowed are: i... | ```python
def is_one_edit_away(s1, s2):
if abs(len(s1) - len(s2)) > 1:
return False
if len(s1) == len(s2):
return sum(c1 != c2 for c1, c2 in zip(s1, s2)) == 1
if len(s1) > len(s2):
s1, s2 = s2, s1
i, j = 0, 0
while i < len(s1) and j < len(s2):
if s1[i] != s2[j]:
... | magicoder | python |
You are working on a Python project that involves handling SSL connections and natural language processing using the NLTK library. As part of the project, you need to ensure that the necessary packages are downloaded and the system path is appropriately set. You have come across a code snippet that attempts to handle S... | The given code snippet has several issues and potential improvements:
1. Handling SSL Context:
The code attempts to handle SSL context by assigning `_create_unverified_https_context` to `ssl._create_default_https_context` within an `else` block after an `except AttributeError` block. However, the `except` block is ... | magicoder | python |
You are tasked with implementing a Netlist class that represents a collection of electronic components and their connections. The Netlist class should support the following operations:
1. Adding a component to the netlist.
2. Connecting two components in the netlist.
3. Checking if a component is present in the netlis... | ```python
class Component:
def __init__(self, component_id, component_type):
self.id = component_id
self.type = component_type
class Netlist:
def __init__(self):
self.components = {}
self.connections = set()
def add_component(self, component):
self.components[compon... | magicoder | python |
You are working on a networking application that involves sending data to multiple network devices. The application uses a `RouterStub` class to manage network connections and a `TunnelPolicy` class to handle the sending of data. The `TunnelPolicy` class has a method `sendToAllMembers` to send data to all members of a ... | The `MulticastTunnelPolicy` class extends the `TunnelPolicy` class and overrides the `sendMulticast` method to support multicast data transmission. Inside the overridden method, it retrieves the list of router stubs and uses the `sendToAllMembers` method to send the multicast data to all members of the network group. T... | magicoder | python |
You are tasked with creating a Python function that processes and validates data for a PostgreSQL database indexer. The function will take in a PostgreSQL indexer object and a list of expected data, and it should validate that the data in the indexer matches the expected data.
The function `validate_db_side(postgres_i... | ```python
def validate_db_side(postgres_indexer, expected_data):
ids, vecs, metas = zip(*expected_data) # Unpack expected_data into separate lists
with postgres_indexer.handler as handler:
cursor = handler.connection.cursor() # Create a cursor using the handler's connection
# Execute SQL que... | magicoder | python |
You are tasked with implementing a distributed training system using TensorFlow and the concept of gradient exchange between multiple worker nodes. The provided code snippet demonstrates the initialization and synchronization process for each worker node in the distributed system. Your task is to design a function that... | ```python
from typing import List
class Config:
def __init__(self, synchronous_training: bool):
self.synchronous_training = synchronous_training
class GradientExchange:
def __init__(self, session, cfg):
self.session = session
self.cfg = cfg
def send_ready(self):
# Implemen... | magicoder | python |
You are tasked with implementing a Python class for building embedding layers in a machine learning model. The class, `EmbeddingLayer`, is responsible for constructing embedding layers for both sparse and dense features. The class has a method `__call__` that builds the embedding layers for the sparse features. Your ta... | ```python
class EmbeddingLayer:
def __init__(self, sparse_features_configs, dense_features_configs, return_raw_features, **kwargs):
super(EmbeddingLayer, self).__init__(**kwargs)
self._sparse_features_configs = sparse_features_configs
self._dense_features_configs = dense_features_configs
... | magicoder | python |
You are tasked with implementing a custom string manipulation utility in Java. Your utility should provide a method to reverse the order of words in a given string. You are not allowed to use any built-in Java libraries or classes for string manipulation, such as `StringBuilder` or `StringTokenizer`. Instead, you shoul... | ```java
public class StringManipulator {
public String reverseWords(String input) {
char[] charArray = input.toCharArray();
int start = 0;
int end = charArray.length - 1;
// Reverse the entire string
reverse(charArray, start, end);
// Reverse each word in the string... | magicoder | java |
You are working on a web scraping project using the Scrapy framework to extract article URLs and additional data from a website. The code snippet provided is a part of the web scraping logic. The `can_add_url` function checks if a URL can be added to the list of articles based on a limit. The `ArticleInfo` class is use... | ```python
from datetime import datetime
def parse_additional_data(response, date_limit):
"""
Retrieves additional data about articles and updates the ArticleInfo objects with the publication date
:param response: Scrapy response
:param date_limit: Date limit in '%Y-%m-%d' format
:return: None
"... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.