query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a custom routing module for a web application using the Microsoft Dynamics CRM (Customer Relationship Management) Portal framework. The routing module will be responsible for mapping incoming URLs to specific resources within the web application.
Your task is to implement a custom routing ... | ```csharp
using System;
using System.Web;
namespace Microsoft.Xrm.Portal.Web.Routing
{
public class CustomRoutingModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += OnBeginRequest;
}
public void Dispose()
{
... | magicoder | csharp |
You are working on a project that involves processing EEG data using the MNE-Python library. Your task is to create a function that handles resampling of the EEG data. The function should take a list of MNE Evoked objects, resample the data, and return the resampled objects. However, there is a problem with the current... | ```python
import logging
import numpy as np
def resample_eeg_data(evoked_objects):
total = []
for es in evoked_objects:
if len(es[0].data) != EXPECTED_SAMPLES: # Assuming EXPECTED_SAMPLES is defined
sample_rate = int(1 / (es[0].times[1] - es[0].times[0])) # Calculate sample rate dynamical... | magicoder | python |
You are tasked with creating a Rust program that utilizes the `objr` crate to interact with Objective-C code. The `objr` crate provides bindings for Objective-C libraries, allowing Rust programs to interface with Objective-C objects and methods.
Your task is to create a Rust program that uses the `objr` crate to inter... | ```rust
// Import the necessary modules from the objr crate
use objr::bindings::*;
// Define an Objective-C struct for the MTLDrawable class using the objc_instance macro
objc_instance! {
pub struct MTLDrawable;
}
// Implement a function that creates an instance of MTLDrawable and calls a method on it
fn main() {... | magicoder | rust |
You are tasked with implementing a custom error handling mechanism for a Python web service. The service is designed to handle various types of exceptions and return appropriate error responses based on the exception type. The provided code snippet is a part of the error handling logic within the service.
Your task is... | ```python
def handle_error(exception):
if isinstance(exception, XMLError):
self.log.error(u'Erro ao ler o XML da requisição.')
return self.response_error(3, exception)
elif isinstance(exception, EquipamentoNotFoundError):
return self.response_error(117, id_equipamento)
elif isinstanc... | magicoder | python |
You are tasked with creating a Python function that processes network address information using the `socket` and `hr` modules. The `hr` module is a hypothetical module that provides a high-level interface for working with network addresses. The `AddrInfo` class represents a network address, and it contains information ... | ```python
from typing import List, Dict
import socket
import hr
def process_network_addresses(addresses: List[hr.AddrInfo]) -> Dict[str, int]:
unique_ipv4_addresses = set()
unique_ipv6_addresses = set()
for addr_info in addresses:
if addr_info.family == socket.AF_INET:
unique_ipv4_addr... | magicoder | python |
You are tasked with implementing a fair lock using Python's trio library. A fair lock ensures that threads or tasks acquire the lock in the order they requested it. The provided code snippet includes an asynchronous function `lock_taker` that acquires and releases a lock, and an asynchronous function `test_lock_fairnes... | ```python
import trio
async def lock_taker(lock, task_id):
async with lock:
print(f"Task {task_id} acquired the lock")
await trio.sleep(1) # Simulate some work
print(f"Task {task_id} released the lock")
async def test_lock_fairness():
lock = trio.Lock()
async with lock:
as... | magicoder | python |
You are tasked with implementing a simplified version of a tweak management system for startup applications. The system allows users to add and remove startup tweaks, which are represented as objects with a "clicked" event and associated functionality. Additionally, the system provides a group for organizing these twea... | ```python
class StartupTweakManager:
def __init__(self):
self.tweaks = []
def add_tweak(self, tweak, callback):
tweak.btn.connect("clicked", callback)
self.tweaks.append(tweak)
def organize_tweaks(self, title, css_class, *tweaks):
tweak_group = ListBoxTweakGroup(title, *twe... | magicoder | python |
You are given a list of strings representing actions taken by employees in a company. Each string can either be "online" or "offline" to indicate whether an employee has come online or gone offline, and "leave" to indicate that the employee has taken a break. Your task is to write a function that calculates the total t... | ```python
from typing import List, Dict
def calculate_online_time(actions: List[str]) -> Dict[str, int]:
online_time = {}
for i in range(0, len(actions), 3):
employee = actions[i]
online_count = actions[i+2:].count("online")
offline_index = actions[i+2:].index("offline")
online_... | magicoder | python |
You are tasked with creating a Python unit test for a web scraping application. The application consists of a SpiderCore class responsible for crawling web pages, a Tuliu_Processor class for processing the fetched data, and two pipelines: ConsolePipeline and TestPipeline. The SpiderCore class fetches data from web page... | ```python
import unittest2 as unittest
from fetchman.processor.test_processor import Tuliu_Processor
from fetchman.spider.spider_core import SpiderCore
from fetchman.pipeline.console_pipeline import ConsolePipeline
from fetchman.pipeline.test_pipeline import TestPipeline
class TestTuliuProcessor(unittest.TestCase):
... | magicoder | python |
You are tasked with creating a Python function that restores the original order of a list of runs. A run is defined as a consecutive sequence of identical elements in the list. For example, the list [1, 1, 2, 3, 3, 3, 4, 4, 4, 4] contains four runs: [1, 1], [2], [3, 3, 3], and [4, 4, 4, 4]. Your task is to implement th... | ```python
from typing import List
def restore_runs(runs: List[List[int]]) -> List[int]:
result = []
for run in runs:
result.extend(run)
return result
```
The `restore_runs` function iterates through each run in the input list and extends the result list with the elements of each run. Finally, it r... | magicoder | python |
You are tasked with implementing a custom estimator for a Support Vector Machine (SVM) model that calculates the probability of inclusion for each data point in the model. The probability of inclusion is a measure of how likely a data point is to be included in the support vectors of the SVM model.
Your task is to com... | ```python
from sklearn.svm import SVC
import numpy as np
class ProbabilityOfInclusionSVM(BaseEstimator):
def calculate_probability_of_inclusion(self, svm_model, X_train):
# Get the distance of each data point to the decision boundary
decision_function = svm_model.decision_function(X_train)
... | magicoder | python |
You are working on a simulation program for modeling fluid flow through a porous medium. The code snippet provided is a part of the program that calculates the strain-dependent permeability of the medium. The program uses a tensor representation to model the anisotropic behavior of the porous medium. Your task is to im... | ```cpp
#include <cmath>
void calculatePermeability(double Q[3][3], double F[3][3], double m_perm0, double m_perm1[3], double m_perm2[3], double J, double phi0, double m_alpha0, double m_alpha[3], double m_M0, double m_M[3], double k[3]) {
double m[3][3]; // Texture tensor in the current configuration
for (int ... | magicoder | cpp |
You are given a string containing a comment block from a software file. The comment block may contain multiple lines and may include various characters, including special characters and whitespace. Your task is to write a function to extract the license information from the comment block.
Write a function `extractLice... | ```python
import re
def extractLicenseInfo(commentBlock: str) -> str:
# Find the index of the "License" or "license" keyword
license_index = commentBlock.lower().find("license")
if license_index == -1:
return "License information not found."
# Extract the license information from the comment b... | magicoder | python |
You are tasked with implementing a search functionality for a web application that lists doctors. The application uses a Django REST framework for its backend. The provided code snippet is from the views.py file of the application.
The `search_fields` list contains the fields on which the search functionality should b... | ```python
from your_app.models import Doctor
from your_app.serializers import DoctorApiSerialzer
from django.db.models import Q
def perform_search(query_params):
search_fields = ['name', 'specialization', 'location', 'experience']
serializer_class = DoctorApiSerialzer
# Constructing the Q objects for the ... | magicoder | python |
You are tasked with implementing a function that calculates the distance between two points in a 2D plane. The function should take in the coordinates of the two points and return the Euclidean distance between them. The Euclidean distance between two points (x1, y1) and (x2, y2) is given by the formula: distance = sqr... | ```python
import math
def calculate_distance(x1, y1, x2, y2):
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
return distance
# Example usage
x1, y1 = 1, 2
x2, y2 = 4, 6
print(calculate_distance(x1, y1, x2, y2)) # Output: 5.0
``` | magicoder | python |
You are tasked with creating a Python program to parse an XML file containing server information and perform specific operations based on the data. The XML file has the following structure:
```xml
<servers>
<server>
<name>Server1</name>
<ip>192.168.1.1</ip>
<status>active</status>
</ser... | ```python
import xml.etree.ElementTree as ET
# Load the XML file
xml_file = "servers.xml"
tree = ET.ElementTree(file=xml_file)
root = tree.getroot()
active_servers_count = 0
inactive_servers_count = 0
# Iterate through the server elements
for server in root.findall('server'):
name = server.find('name').text
... | magicoder | python |
You are tasked with implementing a Python function that interacts with a Windows DLL using the `ctypes` library. The DLL contains a function called `VariantInit` which is used to initialize a VARIANT data type. The `VariantInit` function takes a pointer to a VARIANT as its argument and does not return any value. Your g... | ```python
from ctypes import POINTER, WinDLL, Structure, c_void_p
class VARIANT(Structure):
_fields_ = []
oleaut32 = WinDLL('OleAut32')
def initialize_variant():
pvarg = POINTER(VARIANT)()
oleaut32.VariantInit(pvarg)
```
In the solution, we define a `VARIANT` structure using the `ctypes` library to repr... | magicoder | python |
You are tasked with implementing a neural network architecture using PyTorch for image classification. The given code snippet is part of the neural network model definition and includes the initialization of a max pooling layer and a fully connected layer.
Your task is to complete the neural network model by adding th... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class YourNeuralNetwork(nn.Module):
def __init__(self, input_channels, num_classes, maxPoolKernel_dim, maxPoolKernel_stride, fc_input_dim, fc_output_dim):
super(YourNeuralNetwork, self).__init__()
self.conv1 = nn.Conv2d(in... | magicoder | python |
You are tasked with creating a Rust program that utilizes the `kaitai_struct` library to parse a binary file containing a list of expressions and their positions in the input file. The `ExprIoPos` struct from the `rust` module is used to represent expressions with their positions.
Your task is to implement a function ... | ```rust
use kaitai_struct::KaitaiStruct;
use std::io::Cursor;
#[derive(KaitaiStruct, Debug)]
pub struct ExprIoPos {
pub substream: Option<Box<ExprIoPos>>,
pub pos: u32,
pub expression: String,
}
fn parse_expr_io_pos(data: &[u8]) -> Result<Vec<ExprIoPos>, kaitai_struct::Error> {
let mut cursor = Cursor... | magicoder | rust |
You are tasked with creating a Python program to process weather data and display it on a graphical user interface (GUI). The program should utilize the provided code snippet as a reference for formatting and displaying temperature information.
The program should have the following functionalities:
1. Fetch weather d... | ```python
import requests
import tkinter as tk
# Function to fetch weather data from an API
def fetch_weather_data():
api_key = 'YOUR_API_KEY' # Replace with your actual API key
city = 'New York' # Replace with the desired city
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_ke... | magicoder | python |
You are tasked with creating a Django model for tracking employee assignments within different companies. The model should include fields for the start date of the assignment, the end date (if applicable), and the name of the company. Additionally, you need to implement a method to represent the model instance as a str... | ```python
from django.db import models
from django.contrib.auth.models import User
class EmployeeAssignment(models.Model):
fecha_inicio = models.DateTimeField()
fecha_fin = models.DateTimeField(null=True)
empresa = models.CharField(max_length=50)
user = models.ForeignKey(User, on_delete=models.CASCADE)... | magicoder | python |
You are tasked with creating a Python class that manages a coffee shop's inventory. The class should have methods to add new items to the inventory, update the quantity of existing items, and calculate the total value of the inventory. Additionally, the class should be able to generate a report of the inventory, listin... | ```python
class CoffeeInventory:
def __init__(self):
self.inventory = {}
def add_item(self, item, quantity):
self.inventory[item] = quantity
def update_quantity(self, item, new_quantity):
if item in self.inventory:
self.inventory[item] = new_quantity
else:
... | magicoder | python |
You are given a code snippet that appears to be related to generating prime numbers. Your task is to complete the code by implementing a function to find the nth prime number.
You need to implement a function `findNthPrime` that takes an integer `n` as input and returns the nth prime number. The function should use t... | ```cpp
#include <iostream>
#include <cmath>
#define PR_ARR 1000000 // Define the upper limit for prime number generation
bool b[PR_ARR+1] = {0}; // Initialize an array to mark non-prime numbers
__int64 a[PR_ARR+1] = {0}; // Initialize an array to store prime numbers
__int64 an = 0; // Initialize a variable to keep tra... | magicoder | cpp |
You are tasked with implementing a simplified version control system for projects. The system will involve managing project objects and their associated version history. Each project can be created, deleted, and committed to the version control system. Your task is to implement the necessary classes and methods to supp... | ```python
class Project:
def __init__(self, name):
self.name = name
self.deleted = False
def delete(self):
self.deleted = True
class VersionControlAPI:
def __init__(self):
self.projects = []
def commit(self):
for project in self.projects:
if project... | magicoder | python |
You are tasked with creating a Python script to verify the installation of required third-party helper programs for COT (Customization of OVF Templates). The script should check for the presence of specific programs and their manual pages. The required third-party helper programs are qemu-img, mkisofs, ovftool, fatdisk... | ```python
import subprocess
def verify_helpers_installation():
required_programs = ["qemu-img", "mkisofs", "ovftool", "fatdisk", "vmdktool"]
missing_programs = []
for program in required_programs:
try:
subprocess.check_output(f"which {program}", shell=True)
except subprocess.Ca... | magicoder | python |
You are tasked with creating a Python function that processes a list of email addresses and returns a dictionary containing the domain names as keys and the corresponding list of usernames as values. The function should also handle cases where the email addresses are invalid or do not contain a domain name.
The functi... | ```python
from typing import List, Dict
import re
def process_email_addresses(emails: List[str]) -> Dict[str, List[str]]:
email_dict = {}
for email in emails:
match = re.match(r'^([\w.-]+)@([\w.-]+)$', email)
if match:
username, domain = match.groups()
email_dict.setdefa... | magicoder | python |
You are tasked with creating a Python program to analyze a CSV data file. The program should read the file, check if it exists, verify the number of columns, and ensure that the data is in the correct format (integer or float). The program should make the following assumptions:
1. The first row contains the column name... | ```python
import csv
import os
def analyze_csv_file(file_path):
if not os.path.exists(file_path):
print("File not found")
return
with open(file_path, 'r') as file:
reader = csv.reader(file)
column_names = next(reader)
for row in reader:
if len(row) != le... | magicoder | python |
You are tasked with implementing a 3D axis entity in a graphics rendering system. The given code snippet is a part of a larger program and demonstrates the creation and addition of a 3D axis entity to the rendering scene. The `Axis3DEntity` class is used to represent the axis, and the `initialize` method is called to s... | ```typescript
class Axis3DEntity {
private size: number;
constructor() {
this.size = 0;
}
initialize(size: number): void {
this.size = size;
}
// Other methods for rendering and manipulation can be added here
}
// Usage
let axis: Axis3DEntity = new Axis3DEntity();
axis.initia... | magicoder | typescript |
You are tasked with implementing a program that processes a list of integers and performs a specific operation on the list. The program should remove all the even numbers from the list and then print the removed even numbers in a specific format.
Your task is to write a function `remove_even_numbers` that takes a list... | ```python
def remove_even_numbers(nums):
removed = [str(num) for num in nums if num % 2 != 0]
even_numbers = [str(num) for num in nums if num % 2 == 0]
print("Removed: ", ", ".join(even_numbers))
return [num for num in nums if num % 2 != 0]
# Example usage
input_list = [1, 2, 3, 4, 5, 6]
result = remov... | magicoder | python |
You are tasked with creating a Python decorator that measures the execution time of a function and prints the time taken for its execution. Your decorator should be able to handle functions with any number of arguments and keyword arguments. Additionally, you need to create a function that uses the decorator to measure... | ```python
import time
from functools import wraps
def execution_time_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_time - start_time
print(f'Execution time f... | magicoder | python |
You are working on a cryptocurrency project and need to implement a time-locked transaction creation mechanism. The time-locked transaction will require a specific locktime before it can be spent. Your task is to create a Python function that takes in various parameters and generates the necessary data for the time-loc... | ```python
PROTOCOL_VERSION = '0.12'
def create_timelock_transaction(message_id, oracle_fees, miners_fee_satoshi, return_address, locktime, pubkey_list, req_sigs):
transaction_data = {
'message_id': message_id,
'oracle_fees': oracle_fees,
'miners_fee_satoshi': miners_fee_satoshi,
're... | magicoder | python |
You are tasked with implementing a feedback service connection class in Java that communicates with the Apple Push Notification Service (APNS) feedback service. The feedback service provides information about devices that have uninstalled an app or disabled push notifications. Your goal is to create a method that retri... | ```java
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java... | magicoder | java |
You are tasked with implementing a Python function that determines the type of a given value based on the following rules:
- If the input value is an integer, the function should return 4.
- If the input value is a string, the function should return 1.
- If the input value is neither an integer nor a string, the functi... | ```python
def determine_type(value: any) -> int:
if isinstance(value, int):
return 4
elif isinstance(value, str):
return 1
else:
return 0
```
The `determine_type` function checks the type of the input value using the `isinstance` function. If the value is an integer, it returns 4. If... | magicoder | python |
You are tasked with creating a Python function that processes a dictionary representing a tracklist for multiple artists and their albums. The function should take in the tracklist dictionary and return a new dictionary containing the albums as keys and the number of tracks in each album as values.
The tracklist dicti... | ```python
def album_track_count(tracklist):
album_count = {}
for artist, albums in tracklist.items():
for album in albums:
if albums[album] not in album_count:
album_count[albums[album]] = 1
else:
album_count[albums[album]] += 1
return album_co... | magicoder | python |
You are tasked with creating a benchmarking tool for a Rust project using the `criterion` crate. The `criterion_main!` macro is used to define and execute the benchmarks. Your task is to write a function that calculates the average time taken by a given set of functions to execute and returns the results in a specific ... | ```rust
use criterion::{criterion_group, criterion_main, Criterion};
fn calculate_average_time(functions: Vec<fn()>) -> String {
let mut result = String::new();
let mut group = criterion_group::criterion_group("benchmark_group");
for (index, function) in functions.iter().enumerate() {
group.be... | magicoder | rust |
You are tasked with implementing a module system for a bare-metal embedded system using Rust. The system is designed to interface with various hardware components such as clocks, GPIO (General Purpose Input/Output), serial communication, timers, and watchdogs. The provided code snippet is a partial representation of th... | ```rust
// src/clocks.rs
pub mod clocks {
// Implementation for configuring and controlling system clocks
// ...
pub struct SystemClock {
// Define system clock properties and methods
// ...
}
}
// src/gpio.rs
pub mod gpio {
use crate::gpio_trait::GpioTrait;
// Implementation ... | magicoder | rust |
You are tasked with creating a command-line tool that can remove specific polygons from a given shapefile based on a user-defined attribute. The shapefile contains various polygons, each associated with different attributes. Your task is to implement a Python script that takes user input to specify the attribute value ... | ```python
import os
import sys
import fiona
from optparse import OptionParser
from shapely.geometry import shape, mapping
from fiona import collection
def remove_polygons(shapefile, attribute, value):
output_shapefile = os.path.splitext(shapefile)[0] + "_filtered.shp"
with fiona.open(shapefile, 'r') as input_f... | magicoder | python |
You are given a Python function `combsum` that takes in a list of integers `nums` and an integer `target`. The function is intended to return a list of all unique combinations of elements from `nums` that sum up to the `target`. However, the given code snippet is incomplete and lacks the implementation for finding the ... | ```python
from typing import List
class Solution:
def combsum(self, nums: List[int], target: int) -> List[List[int]]:
if target == 0:
return [[]]
if not nums or nums[0] > target or target < 1:
return []
result = []
nums.sort()
def backtrack(remain, ... | magicoder | python |
You are tasked with implementing a Python module that provides various laws and equations related to fluid dynamics and magnetohydrodynamics (MHD). The module should include functions for calculating the Euler gamma law, special relativity (SR) Euler gamma law, SR MHD, SR RMHD, and SR MF. The module should be designed ... | ```python
# fluid_dynamics.py
import math
__all__ = ["euler_gamma_law", "sr_euler_gamma_law", "sr_mhd", "sr_rmhd", "sr_mf"]
def euler_gamma_law(density, velocity, pressure):
"""
Calculate the result of the Euler gamma law.
Args:
density (float): The density of the fluid.
velocity (float): The ve... | magicoder | python |
You are tasked with implementing a finite difference method (FDM) to solve a one-dimensional wave equation. The wave equation is given by:
\[ \frac{\partial^2 u}{\partial t^2} = v_s^2 \frac{\partial^2 u}{\partial x^2} \]
Where:
- \( u \) is the displacement of the wave
- \( t \) is time
- \( x \) is the spatial coord... | ```python
import numpy as np
def finite_difference_wave_equation(dx, dt, vs, x, u0, u1, t_max):
num_steps = int(t_max / dt)
num_points = len(x)
displacements = [u0, u1]
for _ in range(2, num_steps + 1):
u_next = np.zeros(num_points)
for i in range(1, num_points - 1):
u_next... | magicoder | python |
You are tasked with implementing a simple web application that processes and manipulates text input. The application should have two endpoints: one for processing a given sentence and another for stopping the application.
The processing endpoint should accept a sentence as input and return the processed sentence. The ... | ```python
from flask import Flask, request
import threading
app = Flask(__name__)
def process_sentence(sentence):
# Implement the processing logic for the given sentence
# Example: Reversing the sentence
return sentence[::-1]
def proc_stop():
# Implement the logic to stop any running processes or thr... | magicoder | python |
You are tasked with creating a configuration module for a web application using C#. The configuration module should utilize the Jimu framework for modular development and the Microsoft.Extensions.Configuration library for managing application settings. Your task is to implement a class that encapsulates the configurati... | ```csharp
using Jimu.Module;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
namespace Jimu.Module
{
public class WebAppConfiguration
{
private IConfigurationRoot _configuration;
public void LoadFromJsonFile(string filePath)
{
var b... | magicoder | csharp |
You are given a grid of size n x m, where each cell contains a non-negative integer. The grid represents a matrix of values, and you are allowed to move only right or down from the top-left cell to the bottom-right cell. At each cell (r, c), you can choose to move either down or right, and the value of the chosen path ... | ```python
class Solution:
def __init__(self, rows_count, columns_count):
self.rows_count = rows_count
self.columns_count = columns_count
def maxPathSum(self, down, right):
M = [[0] * (self.columns_count) for _ in range(self.rows_count)]
for r in range(self.rows_count):
... | magicoder | python |
You are tasked with creating a program to simulate a staircase view using a given number of steps. The program should take an integer input representing the number of steps and output a visual representation of the staircase using the '#' character. The staircase should be displayed in a way that resembles the code sni... | ```python
def printStairsView(numSteps):
for i in range(numSteps, 0, -1):
print(" " * (i - 1) + "#" * (numSteps - i + 1))
```
The `printStairsView` function takes the input `numSteps` and iterates from `numSteps` down to 1. For each iteration, it prints a line containing the appropriate number of spaces fo... | magicoder | python |
You are given a Python code snippet that contains functions for processing and normalizing adjacency matrices used in graph theory. Your task is to implement a function that takes an adjacency matrix as input and returns the preprocessed and normalized adjacency matrix as a NumPy array.
The given code snippet includes... | The `preprocess_adj` function first calls the `normalize_adj` function to normalize the input adjacency matrix `adj`. It then adds an identity matrix to the normalized adjacency matrix and returns the resulting preprocessed and normalized adjacency matrix as a NumPy array. | magicoder | python |
You are given a text file containing a software license agreement. Your task is to write a program that counts the occurrences of each word in the agreement and outputs the top N most frequently occurring words along with their counts.
You should consider a word to be any sequence of letters, digits, or underscores. ... | ```python
import re
from collections import Counter
def count_top_words(file_path, N):
with open(file_path, 'r') as file:
text = file.read().lower()
words = re.findall(r'\w+', text)
stop_words = set(['the', 'and', 'or', 'is', 'in', 'it', 'to', 'of', 'for', 'on', 'with', 'a', 'an'])
... | magicoder | python |
You are tasked with creating a program that simulates a simple text-based game. The game involves navigating through a mysterious abyss, encountering various challenges and making decisions that affect the outcome. The abyss is represented as a grid, and the player can move in four directions: up, down, left, and right... | ```python
def explore_abyss(abyss):
rows, cols = len(abyss), len(abyss[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
def is_valid_move(row, col):
return 0 <= row < rows and 0 <= col < cols and abyss[row][col] != '#'
def dfs(row, col):
if not is_valid_move(row, col):
r... | magicoder | python |
You are tasked with creating a command-line utility for processing OpenStreetMap (OSM) data. The utility should accept command-line arguments using the `structopt` crate in Rust. The provided code snippet shows a part of the `Args` struct that defines the command-line options for the utility. The `Args` struct has fiel... | ```rust
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
pub struct Args {
/// Verbose mode (-v, -vv, -vvv, etc.)
#[structopt(short, long, parse(from_occurrences))]
pub verbose: u8,
/// Input OSM pbf file
#[structopt(name = "input", parse(from_os_str))]
pub input: ... | magicoder | rust |
You are tasked with implementing a program builder in Rust for a graphics processing library. The program builder is responsible for constructing a program that can be executed on a graphics processing unit (GPU). The provided code snippet is a simplified version of the program builder implementation.
Your task is to ... | ```rust
use std::borrow::Cow;
pub struct Context;
pub struct ProgramBuilder<'a, T: ProgramBuilderType> {
ctx: &'a Context,
ty: T,
sources: Vec<&'a [u8]>,
opts: Option<Cow<'a, str>>,
}
pub trait ProgramBuilderType {}
pub struct FromSource<'a> {
sources: Vec<&'a [u8]>,
}
impl<'a> ProgramBuilderTy... | magicoder | rust |
You are tasked with implementing a class that processes JSON data representing the status of a system. The class should have methods to set and retrieve various system status indicators. The JSON data contains key-value pairs where the key represents the status indicator and the value represents the status value. Your ... | ```cpp
#include <iostream>
#include <string>
#include <unordered_map>
#include <json/json.h> // Assuming the use of a JSON library
class SystemStatus {
private:
bool m_setupFailed;
int m_shuttingDown;
bool m_startFailed;
bool m_setupFailedHasBeenSet;
bool m_shuttingDownHasBeenSet;
bool m_startF... | magicoder | cpp |
You are tasked with implementing a file export service for a reporting application. The `ReportExportServiceProvider` class needs to support exporting reports to various file formats such as PDF, CSV, and Excel. Additionally, the service should be extensible to accommodate future file formats without modifying the exis... | ```typescript
// Define an interface for report export format
interface ReportExportFormat {
export(reportData: any): void;
}
// Implement PDF export format
class PDFExportFormat implements ReportExportFormat {
export(reportData: any): void {
// Logic to export report to PDF
}
}
// Implement CSV export form... | magicoder | typescript |
You are tasked with creating a Rust library for astronomical calculations. The library should provide functionality to request information about astronomical events and positions of celestial bodies. You need to implement the necessary structures and methods to achieve this functionality.
Your task is to create a modu... | ```rust
// Define the astroevent module for astronomical event information
mod astroevent {
// Define the AstroEventRequest structure for requesting event information
pub struct AstroEventRequest {
// Define the fields for the event request
// ...
}
impl AstroEventRequest {
// I... | magicoder | rust |
You are tasked with creating a Python class that simulates a simple banking system. The class should be able to handle basic banking operations such as account creation, deposit, withdrawal, and balance inquiry. Additionally, the class should have a method to display the account details.
Your task is to implement the ... | ```python
class BankAccount:
def __init__(self, account_number, account_holder):
self.account_number = account_number
self.account_holder = account_holder
self.balance = 0
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited ... | magicoder | python |
You are tasked with implementing a Python function that processes an Evaluation Pack Message (EPM) and retrieves specific information from it. The EPM is represented as a binary string, and you are required to extract relevant data from it using the provided code snippet as a starting point.
Your task is to complete t... | ```python
def process_evaluation_pack_message(evaluationpack):
epm = irb.EvaluationPackMessage()
epm.ParseFromString(evaluationpack)
# Extract relevant information from the parsed EPM
name = epm.name
score = epm.score
timestamp = epm.timestamp
# Format the extracted information into a stri... | magicoder | python |
You are tasked with creating a Rust function that processes a collection of file paths and opens each file, storing the file handle in a HashMap. Additionally, the function should check if a specified output file path exists and perform an action based on its existence.
You are given the following code snippet as a st... | ```rust
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::path::Path;
struct FileError {
mod_path: &'static str,
error: io::Error,
}
impl FileError {
fn new(mod_path: &'static str, error: io::Error) -> Self {
FileError { mod_path, error }
}
}
fn process_files(file_paths:... | magicoder | rust |
You are tasked with implementing a class that simulates a device with a heartbeat mechanism. The provided code snippet is a part of the `_thread_body` method of the device class. The class has an attribute `HEARTBEAT_INTERVAL_SECONDS` representing the interval at which the device should send a heartbeat signal. The met... | ```python
import threading
import time
class Device:
def __init__(self, heartbeat_interval_seconds):
self.HEARTBEAT_INTERVAL_SECONDS = heartbeat_interval_seconds
self._shutdown = False
self._thread = threading.Thread(target=self._thread_body)
self._thread.start()
def _thread_bo... | magicoder | python |
You are tasked with implementing a function to clean up HTML content by removing specific tags and attributes. Your function should take in a string of HTML content and a list of tags and attributes to remove, and return the cleaned HTML content.
You are given the following code snippet as a starting point:
```python... | ```python
from bs4 import BeautifulSoup
def clean_html(html_content, tags_to_remove):
soup = BeautifulSoup(html_content, 'html.parser')
for tag in tags_to_remove:
for element in soup.find_all(tag):
element.decompose()
return str(soup)
```
The solution uses the BeautifulSoup library to ... | magicoder | python |
You are tasked with simulating a simple audio signal processing system using Python. The system consists of a server, groups, and synthesizers. The server manages the audio synthesis and processing, while groups are used to organize and control the synthesizers. Synthesizers generate audio signals based on specified pa... | ```python
import supercollider # Assuming the existence of a supercollider library for audio synthesis
class AudioSystem:
def __init__(self):
self.server = supercollider.Server() # Initialize the audio server
def create_group(self):
return self.server.new_group() # Create a new group and re... | magicoder | python |
You are given a sorted array of distinct integers and a target value. Your task is to implement a function to search for the target in the array using a modified binary search algorithm. The modification is as follows:
- If the middle element of the current subarray is less than the target and the last element of the s... | ```java
public static int modifiedBinarySearch(int[] arr, int n, int target) {
int s = 0, e = n - 1;
while (s <= e) {
int mid = s + (e - s) / 2;
if (arr[mid] == target) {
return mid;
} else {
if (arr[mid] < target && arr[e] >= target) {
s = mid + 1... | magicoder | java |
You are tasked with creating a Rust program that involves serializing and deserializing a custom data structure using the `serde` library. The custom data structure, `PdaBuilder`, represents parameters for an instruction and contains fields for various types such as `PublicKey`, `u64`, and `String`.
Your task is to im... | ```rust
use serde::{Serialize, Deserialize};
use serde_json;
#[derive(Serialize, Deserialize)]
pub struct PdaBuilder {
from_public_key: PublicKey,
to_public_key: PublicKey,
base: PublicKey,
space: u64,
owner: PublicKey,
seed: String,
lamports: u64,
}
// Serialization and Deserialization im... | magicoder | rust |
You are tasked with creating a script to manage user authentication and installation checks for a system. The script should include a function to retrieve a user's password from a file, as well as installation checks for configuration files. The script should also handle process management by writing its process ID to ... | ```bash
userPass() {
if [ -z "$1" ] || [ -z "$2" ]; then
echo "Usage: userPass <username> <user_info_file>"
return 1
fi
local username="$1"
local user_info_file="$2"
if [ ! -f "$user_info_file" ]; then
echo "---- [ERROR] User info file not found ----"
return 1
fi
local password=$(grep "... | magicoder | shell |
You are given a company with n employees, where each employee has a unique ID from 0 to n-1. The head of the company is the one with headID. Each employee in the company has one direct manager given in the manager list, where manager[i] is the direct manager for employee i. The company has a communication structure whe... | ```python
from typing import List
def numOfMinutes(n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
children = [[] for i in range(n)]
for i, m in enumerate(manager):
if m >= 0:
children[m].append(i)
def dfs(value):
if not children[value]:
retu... | magicoder | python |
You are given a text file containing a software license agreement. Your task is to write a Python program to count the occurrences of each unique word in the file, ignoring case and punctuation. The program should then display the top N most frequently occurring words along with their counts.
For example, given the fo... | ```python
import re
from collections import Counter
def count_words_in_file(file_path, top_n):
with open(file_path, 'r') as file:
text = file.read()
words = re.findall(r'\b\w+\b', text.lower()) # Extract words and convert to lowercase
word_counts = Counter(words)
top_words = word_c... | magicoder | python |
You are tasked with implementing a Python function that processes a list of strings representing a code snippet. The code snippet contains a class definition and a method call, but it is heavily corrupted due to formatting issues. Your goal is to write a function that can clean up the code snippet by properly formattin... | ```python
from typing import List, Tuple
def process_code_snippet(code: List[str]) -> Tuple[str, str]:
class_name = ''
method_name = ''
for line in code:
if 'class' in line:
class_name = line.split(' ')[1].strip(':')
if 'def setUp(self):' in line:
for inner_line in ... | magicoder | python |
You are tasked with simulating a network reconnection mechanism in a multiplayer game environment. The given code snippet initializes a `ReconnectThread` to handle the reconnection process and creates a new screen for the game interface. Your task is to implement the `ReconnectThread` class and the `DisconnectedScreen`... | ```java
// ReconnectThread class for managing the reconnection process
class ReconnectThread extends Thread {
private Server server;
private long startPeriod;
private long endPeriod;
private boolean connected;
public ReconnectThread(Server server, long startPeriod, long endPeriod) {
this.se... | magicoder | java |
You are tasked with implementing a Python function that interacts with an API to retrieve information about browser extensions. The function should accept either an extension ID or a key as an argument, but not both. If an invalid extension ID or key is provided, the function should raise a specific exception.
You are... | ```python
import api.impl
class InvalidExtensionId(Exception):
pass
class InvalidExtensionKey(Exception):
pass
def get_extension_info(extension_id=None, key=None):
if extension_id is not None and key is not None:
raise ValueError("Exactly one of 'extension_id' and 'key' should be used")
if e... | magicoder | python |
You are tasked with implementing a Python function that processes a list of image filenames and extracts specific views from each image. The function should take in the list of filenames and extract the front, front-left, side-left, front-right, and side-right views from each image. The image extraction process is perf... | ```python
from typing import List
def image_processor(path: List[str]) -> List[str]:
processed_images = []
for filename in path:
# Assuming the existence of the image_extractor function
front = image_extractor(filename, "Front")
front_left = image_extractor(filename, "Front_left")
... | magicoder | python |
You are tasked with implementing a function that manipulates a data structure representing a binary tree. The binary tree is represented using a standard array-based representation, where the root is at index 0, and for any node at index i, its left child is at index 2i + 1 and its right child is at index 2i + 2. Each ... | ```javascript
function maxPathSum(tree) {
let maxSum = Number.MIN_SAFE_INTEGER;
function maxPathSumHelper(nodeIndex) {
if (nodeIndex >= tree.length || tree[nodeIndex] === null) {
return 0;
}
const leftSum = Math.max(0, maxPathSumHelper(2 * nodeIndex + 1));
const rightSum = Math.max(0, maxPat... | magicoder | javascript |
You are tasked with implementing a function to extract comments from a given piece of Java code. The comments can be either single-line or multi-line comments and should be returned as a list of strings.
You need to write a function `extractComments` that takes a string `code` as input and returns a list of comments p... | ```java
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CommentExtractor {
public static List<String> extractComments(String code) {
List<String> comments = new ArrayList<>();
Pattern pattern = Pattern.compile("(//[^\\n... | magicoder | java |
You are tasked with implementing a Python class that represents a neural network with multiple heads for different action subspaces. The network should be able to handle the initialization of multiple heads and provide a method for making predictions using these heads.
Your task is to complete the implementation of th... | ```python
class MultiHeadNetwork:
def __init__(self, input_size, num_heads):
"""
Initialize the MultiHeadNetwork with the given input size and number of heads.
Create separate layers for each head and initialize them appropriately.
"""
self.num_heads = num_heads
self.... | magicoder | python |
You are tasked with creating a program that processes a series of Unicode code points and their corresponding names, and converts them to UTF-8 encoded text. The input will consist of a series of lines, each containing a Unicode code point and its associated name, separated by a colon. Your program should process each ... | ```java
import java.nio.charset.StandardCharsets;
public void processUnicodeLines(String[] inputLines, String origin) {
for (String line : inputLines) {
int colonIndex = line.indexOf(':');
if (colonIndex != -1) {
String codePointStr = line.substring(0, colonIndex);
String na... | magicoder | java |
You are tasked with implementing a class that performs linear extrapolation based on given data points. The class should provide a method to inform it of new data points and another method to extrapolate a value for a given input.
You are given the following code snippet as a reference:
```cpp
extrapolator.Inform(0, ... | ```cpp
#include <iostream>
#include <map>
class Extrapolator {
private:
std::map<int, int> dataPoints;
public:
void Inform(int input, int output) {
dataPoints[input] = output;
}
const int* Extrapolate(int input) {
auto lower = dataPoints.lower_bound(input);
if (lower == dataPo... | magicoder | cpp |
You are given an array of integers representing the heights of a series of buildings. Your task is to find the maximum area of a rectangle that can be formed by a contiguous sequence of buildings. The width of each building is assumed to be 1 unit, and the height of the rectangle is determined by the height of the shor... | ```python
def maxRectangleArea(heights):
stack = []
maxArea = 0
i = 0
while i < len(heights):
if not stack or heights[i] >= heights[stack[-1]]:
stack.append(i)
i += 1
else:
top = stack.pop()
width = i if not stack else i - stack[-1] - 1
... | magicoder | python |
You are tasked with implementing a program that reads a specific file format and extracts information from its header. The file format is based on the New Executable (NE) file format used in early versions of Microsoft Windows. The header of the NE file contains various fields, each with a specific data type and purpos... | ```python
class NEHeader:
def __init__(self, ne_segtab, ne_rsrctab, ne_restab, ne_modtab, ne_imptab, ne_nrestab, ne_cmovent, ne_align, ne_cres, ne_exetyp, ne_flagsothers, ne_pretthunks, ne_psegrefbytes):
self.ne_segtab = ne_segtab
self.ne_rsrctab = ne_rsrctab
self.ne_restab = ne_restab
... | magicoder | python |
You are tasked with implementing a simple banking system using object-oriented programming concepts in Java. The system should support basic operations such as creating accounts, depositing funds, withdrawing funds, and transferring funds between accounts.
Your task is to create a `BankAccount` class that encapsulates... | ```java
// BankAccount class
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}
public void deposit(double amount) {
balance += amount;
}
... | magicoder | java |
You are tasked with simulating the joint stock price movements of two correlated stocks over a given number of time steps. The stock prices are modeled using a bivariate geometric Brownian motion. The risk-free rate, correlation coefficient, volatilities of the two stocks, number of time steps, and the number of simula... | ```python
import numpy as np
def simulate_stock_prices(r, rho, sigma1, sigma2, nSteps, nSimulation):
dt = 1.0 / nSteps
stock_prices = np.zeros((nSteps + 1, 2, nSimulation))
for i in range(nSimulation):
Z1 = np.random.normal(0, np.sqrt(dt), nSteps)
Z2 = np.random.normal(0, np.sqrt(dt), ... | magicoder | python |
You are given a 2D list `cost` representing the cost of traveling through a grid. Each cell `cost[i][j]` represents the cost of traveling to that cell. You can only move right or down in the grid. The task is to find the minimum cost to reach the bottom-right cell from the top-left cell.
Write a function `min_cost_pat... | ```python
def min_cost_path(cost):
m, n = len(cost), len(cost[0])
# Initialize a 2D list to store the minimum cost to reach each cell
dp = [[0] * n for _ in range(m)]
# Base case: initialize the first cell with its cost
dp[0][0] = cost[0][0]
# Fill the first row with cumulative co... | magicoder | python |
You are working on a project to optimize the scheduling of tasks using linear programming. As part of this project, you need to create a Python program that utilizes the PuLP library to model and solve a linear programming problem. The problem involves minimizing the cost per minute (CPM) for a set of tasks, subject to... | ```python
from pulp import LpProblem, LpVariable, LpMinimize, lpSum, value
# Define the task durations and cost per minute
task_durations = [10, 15, 20, 8] # durations in minutes
cost_per_minute = [5, 7, 6, 4] # cost per minute for each task
# Create a PuLP linear programming problem
problem = LpProblem("TaskSchedu... | magicoder | python |
You are tasked with implementing a simple user interface feature for a game. The game has a panel that can be toggled on and off, and the panel can be in either a regular mode or a level mode. You need to create a class that manages the panel's state and provides a method to toggle the panel between regular and level m... | ```java
public void togglePanel() {
isLevel = !isLevel; // Toggle the isLevel field
if (isLevel) {
// Switch to level mode
System.out.println("Panel switched to level mode");
} else {
// Switch to regular mode
System.out.println("Panel switched to regular mode");
}
}
```
... | magicoder | java |
You are tasked with implementing a file synchronization algorithm for a media streaming service. The service has multiple streams, each with a video file that needs to be synchronized to an archive location. The provided code snippet shows a method `sync_streams` within a class, which iterates through the streams and u... | ```python
import subprocess
class MediaStreamManager:
def __init__(self, goodStreams, logger=None):
self.streams = goodStreams
self.logger = logger
def sync_streams(self):
for s in self.streams:
syncCmd = ['rsync', '-rlptg', s['VideoPath'], s['ArchivePath']]
if ... | magicoder | python |
You are tasked with implementing a train scheduling system for a railway company. The company operates a network of trains that travel between various stations. Each train has a unique identifier and a schedule that includes the departure and arrival times for each station along its route. The schedule is represented a... | ```python
from typing import List, Tuple
from datetime import datetime
def find_conflicts(schedule: List[Tuple[str, str, str]]) -> List[Tuple[str, str, str, str]]:
conflicts = []
for i in range(len(schedule) - 1):
current_station, current_departure, current_arrival = schedule[i]
next_station, n... | magicoder | python |
You are tasked with implementing a class in PHP for managing Elasticsearch (ES) upgrade configurations. The class should provide methods for setting the ES version, checking for upgrade only, and specifying the target X-Pack edition. The class should also include appropriate getter and setter methods for these properti... | ```php
class ElasticsearchUpgradeConfig {
private $esVersion;
private $checkOnly = false;
private $licenseType = 'basic';
public function setEsVersion(string $EsVersion) {
$validVersions = ['6.4.3', '6.8.2', '7.5.1'];
if (in_array($EsVersion, $validVersions)) {
$this->esVers... | magicoder | php |
You are tasked with implementing a Python function that performs data binning and smoothing using Extremely Randomized Trees (ExtraTrees) for a given dataset. The function should take into account the number of partitions for binning and the number of trees in the ExtraTrees ensemble for continuous smoothing.
You are ... | ```python
from sklearn.ensemble import ExtraTreesRegressor
import numpy as np
def bin_and_smooth_data(data, discrete=True, partitions=10, n_estimators=100):
if discrete:
# Perform discrete binning
bin_edges = np.histogram_bin_edges(data, bins=partitions)
binned_data = np.digitize(data, bin_... | magicoder | python |
You are working on a project that involves processing and merging data from various sources. In this scenario, you have been given a code snippet that concatenates several arrays using the `np.concatenate` function from the NumPy library. Your task is to understand the code snippet and write a function to perform a sim... | ```python
import numpy as np
def concatenate_arrays(aux_id_var, lat_var, mid_pt_lat_var, lon_var, mid_pt_lon_var, elev_var, point_type_var, seg_name_var, np_rwis_aux_id, np_rwis_lat, np_rwis_mid_pt_lat, np_rwis_lon, np_rwis_mid_pt_lon, np_rwis_elev, np_rwis_point_type, np_rwis_seg_name):
concatenated_arrays = {
... | magicoder | python |
You are tasked with implementing a simple game using the provided game framework. The game framework consists of a module named `code.game` which contains the necessary classes and functions for creating and running games. The code snippet given initializes a game instance for "level01" and starts the game using the `m... | ```python
# Import the necessary classes and functions from the game framework
from code.game import Level, Game
# Define the Level02 class that inherits from the Level class
class Level02(Level):
def __init__(self):
super().__init__()
# Define the layout, obstacles, and game mechanics specific to ... | magicoder | python |
You are tasked with creating a program that processes a given HTML snippet and extracts the text content within the `<li>` tags. Each `<li>` tag contains an icon represented by a `span` element with a specific class, followed by a description of a feature. Your program should extract the icon and the feature descriptio... | ```python
from bs4 import BeautifulSoup
def extractFeatures(html):
features = []
soup = BeautifulSoup(html, 'html.parser')
list_items = soup.find_all('li', class_='list-group-item')
for item in list_items:
icon_span = item.find('span')
icon_class = icon_span['class'][0]
fea... | magicoder | python |
You are tasked with creating a Python function that takes a list of file paths and a root directory path as input and generates a zip file containing specific files based on certain conditions. The function should iterate through the list of file paths, identify unique file names without extensions, and add correspondi... | ```python
import os
import zipfile
from typing import List
def generate_zip(files: List[str], root: str, zip_filename: str) -> None:
with zipfile.ZipFile(zip_filename, 'w') as zf:
for f in list(set([x.rsplit('.',1)[0] for x in files])):
found = False
for ext in ('.pyc', '.so', '.pyo... | magicoder | python |
You are tasked with creating a Python package that processes and stitches together a series of images to create a panoramic view. The package, named "panorama," is authored by "romainx" and is currently at version "0.2.0." The package contains a module named "panorama" with functionalities for image processing and stit... | ```python
from typing import List
from PIL import Image
import numpy as np
import cv2
def create_panorama(images: List[str]) -> Image:
# Load the images
img_list = [cv2.imread(img) for img in images]
# Initialize the stitcher
stitcher = cv2.Stitcher_create()
# Stitch the images
status, stitch... | magicoder | python |
You are tasked with implementing a simple messaging system using ZeroMQ in Python. The code snippet provided initializes a list of sockets and connects a socket to a specific port for system synchronization. Your task is to extend this code to create a basic client-server messaging system.
Your goal is to implement a ... | ```python
import zmq
import threading
def server_task():
context = zmq.Context()
server_socket = context.socket(zmq.ROUTER)
server_socket.bind("tcp://*:5555")
clients = {}
while True:
identity, message = server_socket.recv_multipart()
if identity not in clients:
client... | magicoder | python |
You are tasked with creating a function that extracts the class attribute value from an HTML tag. The function should take a string representing an HTML tag as input and return the value of the class attribute if it exists, or an empty string if the class attribute is not present.
For example, given the input string:
... | ```python
import re
def extractClassAttribute(tag: str) -> str:
match = re.search(r'class="([^"]+)"', tag)
if match:
return match.group(1)
else:
return ""
```
The `extractClassAttribute` function uses the `re` module to search for the class attribute within the input HTML tag string. It lo... | magicoder | python |
You are tasked with implementing a custom search functionality for a celestial event database. The database contains information about various celestial events, including their primary key (`pk`), name, coordinates (`radiant_ra` and `radiant_dec`), start date, peak date, end date, and zenithal hourly rate (`zhr`). The ... | ```python
from typing import List, Dict, Any
def search_celestial_events(query: str, events: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
matching_events = []
query = query.lower() # Convert query to lowercase for case-insensitive search
for event in events:
for field in event:
if fi... | magicoder | python |
You are tasked with implementing a simple text editor that supports undo and redo operations. The editor should be able to handle text modifications and selections. Your goal is to implement the undo functionality for text selection erasure.
You are given a code snippet from the text editor's source code:
```java
((G... | ```java
public class GMeasurement implements Recordable {
private String originalText;
private String erasedSelection;
// Other class members and methods
public void eraseSelectionUndone(String action) {
// Restore the erased text selection
// Assuming the editor has a text area compon... | magicoder | java |
You are given a code snippet that represents a SHA-256 hash and its corresponding size. Your task is to write a program that can generate a SHA-256 hash for a given input string and calculate its size in bytes.
Write a function or program that takes a string as input and returns the SHA-256 hash of the input string al... | ```python
import hashlib
def calculate_sha256_and_size(input_string):
# Calculate the SHA-256 hash
sha256_hash = hashlib.sha256(input_string.encode()).hexdigest()
# Calculate the size in bytes
size_in_bytes = len(input_string.encode('utf-8'))
return sha256_hash, size_in_bytes
# Example usage
inp... | magicoder | python |
You are tasked with creating a script to manage user accounts and execute commands with the appropriate user privileges. Your script should take a user ID as input and create a new user with the specified ID. Additionally, it should set the user's shell to `/bin/bash`, create a home directory for the user, and then exe... | ```bash
#!/bin/bash
# Either use the LOCAL_USER_ID if passed in at runtime or fallback
LOCAL_USER_ID=${LOCAL_USER_ID:-9001}
echo "Starting with UID : $LOCAL_USER_ID"
# Create a new user with the specified user ID
useradd --shell /bin/bash -u "$LOCAL_USER_ID" -o -c "" -m user
# Set the HOME environment variable
expo... | magicoder | shell |
You are working on a project that involves implementing a neural network using TensorFlow. As part of the preprocessing step, you need to convert input data into one-hot encoded vectors and then reduce them to a single vector. You decide to use TensorFlow to achieve this transformation. Below is a simplified version of... | ```python
import tensorflow as tf
def preprocess_input(input_var, input_dim):
batch_size = tf.shape(input_var)[0]
input_var = tf.one_hot(input_var, input_dim, axis=-1)
input_var = tf.reduce_sum(input_var, axis=1)
return input_var
```
The `preprocess_input` function takes the input data `input_var` and ... | magicoder | python |
You are tasked with implementing a class `MedianFinder` that can efficiently find the median of a stream of integers. The class should support two operations:
1. `MedianFinder()`: Initializes the `MedianFinder` object.
2. `void addNum(int num)`: Adds the integer `num` from the data stream to the data structure.
The m... | ```java
import java.util.PriorityQueue;
class MedianFinder {
private PriorityQueue<Integer> maxQueue; // Max-heap to store the lower half of the numbers
private PriorityQueue<Integer> minQueue; // Min-heap to store the higher half of the numbers
public MedianFinder() {
maxQueue = new PriorityQueue... | magicoder | java |
You are given a 2D grid representing a map with cells. Each cell has an integer value indicating the height of the terrain at that location. Your task is to find the maximum number of adjacent cells (up, down, left, right) where the terrain is strictly higher than the current cell.
You are to implement a function or m... | ```python
def max_adjacent_higher_terrain(grid):
rows, cols = len(grid), len(grid[0])
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
result = [[0] * cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
count = 0
for dx, dy in directions:
... | magicoder | python |
You are tasked with implementing a binary search tree data structure that supports memory management operations for a memory allocator. The binary search tree is used to manage memory blocks, and the operations involve coalescing contiguous memory blocks and removing them from the tree.
Your task is to implement the `... | ```rust
// Define the Node and BinarySearchTree structs
struct Node {
memory_address: MemoryAddress,
// Other relevant fields
}
struct BinarySearchTree {
root: Option<Box<Node>>,
// Other relevant fields and methods
}
impl BinarySearchTree {
// Other methods
fn blocks_to_coalesce(&self, inser... | magicoder | rust |
You are given a string containing a code snippet with some errors. Your task is to identify and fix the errors in the code snippet. The code snippet is as follows:
```python
pass
else:
print na<ref>me
```
Your task is to correct the code snippet so that it runs without errors and produces the expected output. | The given code snippet has a syntax error and a misspelled variable. The corrected code snippet is as follows:
```python
if True:
print("name")
```
The corrected code snippet uses the `if` statement instead of the `pass` statement and fixes the misspelled variable by replacing `na<ref>me` with `"name"`. When execut... | magicoder | python |
You are tasked with implementing a Python class that simulates a web request with retries and exponential backoff. Your class should have the following functionality:
1. The class should be named `WebRetriever` and should be initialized with two parameters: `tries` (an integer representing the number of retry attempts... | ```python
import requests
import time
import random
class WebRetriever:
def __init__(self, tries, sleep):
self.tries = tries
self.sleep = sleep
def get_with_retry(self, url):
for _ in range(self.tries):
time.sleep(random.random() * self.sleep * 2)
try:
... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.