query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a program to manage MongoDB databases in a Cosmos DB instance. Your program should include functionality to create a new MongoDB database with specified throughput settings, retrieve the created database's details, and verify the throughput settings.
Your program should interact with the C... | ```csharp
// Import necessary namespaces
using Microsoft.Azure.Management.CosmosDB;
using Microsoft.Azure.Management.CosmosDB.Models;
// Define the function to create a new MongoDB database with specified throughput settings
public async Task CreateMongoDBDatabase(string resourceGroupName, string databaseAccountName, ... | magicoder | csharp |
You are tasked with creating a custom view in a Django web application for managing a list of books. The view should allow users to add, update, and delete books, as well as view a list of all books and details of a specific book. You will need to implement the necessary Django views and URL configurations to achieve t... | ```python
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
genre = models.CharField(max_length=50)
publication_date = models.DateField()
# urls.py
from django.urls import path
from .views import BookLi... | magicoder | python |
You are tasked with implementing a custom input/output streaming mechanism for a C++ class called `NGPrimitive`. The class has two member variables: `unknown1` and `pins`. The given code snippet shows the overloaded `<<` and `>>` operators for the `NGPrimitive` class, which are used to stream data into and out of the c... | ```cpp
class NGPrimitive {
public:
int unknown1;
int pins;
// Overloaded stream output operator
friend NGStream& operator<<(NGStream& stream, const NGPrimitive& obj) {
return stream << obj.unknown1 << obj.pins;
}
// Overloaded stream input operator
friend NGStream& operator>>(N... | magicoder | cpp |
You are working on a project that involves processing raster data. You have a class `RasterProcessor` with the following relevant code snippet:
```python
band_i = self._src_data.GetRasterBand(b).ReadAsArray()
else:
band_i = self._src_data.GetRasterBand(b).ReadAsArray(
xoff, yoff, xsize, ysize)
band_array.a... | ```python
import numpy as np
def raster2uint8(ima: np.ndarray) -> np.ndarray:
# Normalize the input array to the range [0, 1]
min_val = np.min(ima)
max_val = np.max(ima)
normalized_ima = (ima - min_val) / (max_val - min_val)
# Scale the normalized array to the range [0, 255] and convert to uint8
... | magicoder | python |
You are tasked with implementing a custom value formatter for a charting library in Swift. The given code snippet is a starting point for creating a custom value formatter class. Your task is to complete the implementation of the `LargeValueFormatter` class by providing the necessary methods to format values for displa... | ```swift
import Foundation
import ChartsZyp
open class LargeValueFormatter: NSObject, IValueFormatter, IAxisValueFormatter {
private let numberFormatter: NumberFormatter
override init() {
numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 0
numberFormatter.maxi... | magicoder | swift |
You are tasked with implementing a custom video processing class in Python. The class, named `VideoProcessor`, is designed to handle video files and provide various functionalities for processing and analyzing the video content. Your task is to implement the `__len__` method of the `VideoProcessor` class, which should ... | ```python
import cv2
class VideoProcessor:
def __init__(self, video_file):
self._capture = cv2.VideoCapture(video_file)
def __len__(self):
assert self._capture.isOpened(), "Video file not opened"
assert self._capture, "Video capture object not initialized"
if not self.... | magicoder | python |
You are tasked with creating a function that parses HTML code to extract the breadcrumb navigation links and their corresponding URLs. The breadcrumb navigation is represented by an ordered list (`<ol>`) containing list items (`<li>`) with anchor (`<a>`) tags. Each anchor tag contains the text of the breadcrumb link an... | ```python
from bs4 import BeautifulSoup
def extractBreadcrumb(html):
soup = BeautifulSoup(html, 'html.parser')
breadcrumb_dict = {}
ol_tag = soup.find('ol', class_='breadcrumb')
if ol_tag:
for li_tag in ol_tag.find_all('li', class_='breadcrumb-item'):
anchor_tag = li_tag.find('a')
... | magicoder | python |
You are tasked with implementing a class called `Fabric` that represents a piece of fabric with a grid of cells. Each cell in the fabric can be occupied by a coordinate point. The `Fabric` class should provide methods to manipulate the fabric by adding and removing points at specific coordinates, as well as a method to... | ```java
import java.util.HashMap;
public class Fabric {
private HashMap<Coord, Integer> fabricGrid;
public Fabric() {
fabricGrid = new HashMap<>();
}
public void addPoint(int x, int y) {
Coord point = new Coord(x, y);
fabricGrid.put(point, fabricGrid.getOrDefault(point, 0) + 1... | magicoder | java |
You are tasked with creating a script to automate the installation of Composer and the subsequent removal of development packages to reduce the size of the PHAR file. The script should be written in a language of your choice and should handle the installation process and package removal seamlessly.
Your script should ... | ```bash
#!/bin/bash
# Define the directory for Composer installation
TERMINUS_BIN_DIR="/path/to/terminus/bin"
# Step 1: Download the Composer installer using curl
curl -sS https://getcomposer.org/installer | php -- --filename=$TERMINUS_BIN_DIR/composer.phar
# Step 2: Install Composer in the specified directory
if [ ... | magicoder | shell |
You are tasked with implementing a Python class that generates a build file for a software project. The class, named `BuildFileGenerator`, has several attributes and methods that handle the generation of the build file. The provided code snippet is a part of the `BuildFileGenerator` class and is responsible for creatin... | ```python
class BuildFileGenerator:
def __init__(self, target_name, package, main_class):
self.target_name = target_name
self.package = package
self.main_class = main_class
self._build_file = "build_file.txt"
def generate_build_file(self):
main_class_with_package = self.... | magicoder | python |
You are given a C++ code snippet that processes a set of words, times, and lengths to generate output. Your task is to implement a function that performs the same processing as the given code snippet.
The function signature is:
```cpp
void generateOutput(const std::vector<int>& words, const std::vector<double>& times,... | ```cpp
#include <vector>
#include <string>
#include <iostream>
void generateOutput(const std::vector<int>& words, const std::vector<double>& times, const std::vector<double>& lengths, const std::string& key, double frame_shift, std::ostream& ko) {
for (size_t i = 0; i < words.size(); i++) {
if (words[i] ==... | magicoder | cpp |
You are tasked with implementing a class hierarchy for managing files in a code editor. The base class `File` represents a generic file, while the derived class `Hdf5File` is specialized for handling HDF5 files. Your goal is to implement the missing methods and properties in the given code snippet to create a functiona... | ```typescript
import * as vscode from 'vscode';
class File {
private uri_: vscode.Uri;
private file_: Hdf5File;
constructor(uri: vscode.Uri, file: Hdf5File) {
this.uri_ = uri;
this.file_ = file;
}
public get uri(): vscode.Uri { return this.uri_; }
public get file(): Hdf5File {... | magicoder | typescript |
You are tasked with creating a time zone conversion utility in Rust. The utility should support converting a given UTC datetime to the corresponding local datetime for various cities around the world. To achieve this, you need to implement a struct `TimeZoneConverter` with associated functions for each city's time zone... | ```rust
use chrono::{DateTime, Utc, FixedOffset};
struct TimeZoneConverter;
impl TimeZoneConverter {
fn from_utc_datetime(datetime: DateTime<Utc>) -> DateTime<FixedOffset> {
// Implement the conversion logic for each city here
unimplemented!()
}
fn chungking_from_utc_datetime(datetime: Da... | magicoder | rust |
You are tasked with creating a Discord bot that utilizes the `discord.py` library to implement a "Swatter" cog. The Swatter cog should listen for specific events and perform actions based on the received messages and reactions. Your task is to complete the implementation of the Swatter cog by adding the missing event h... | ```python
from discord.ext import commands
class Swatter(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if self.bot.user in message.mentions:
await message.add_reaction('\U0001f5de')
if 'skynet' in me... | magicoder | python |
You are tasked with implementing a custom event system in Swift. The event system should allow the creation of events with or without associated data, and should provide a way to subscribe to these events.
You are provided with the following code snippet as a starting point:
```swift
import Foundation
func uniqueId(... | ```swift
import Foundation
class EventPublisher<Publisher> {
let name: String
let publisher: Publisher
init(name: String, publisher: Publisher) {
self.name = name
self.publisher = publisher
}
func publish() {
print("Event published: \(name)")
}
}
class EventPu... | magicoder | swift |
You are tasked with creating a Python program to process real estate advertisements from multiple countries and store the relevant information in a CSV file. The provided code snippet is part of this program and demonstrates the processing of real estate advertisements from Croatia. The program reads the content of eac... | ```python
import re
import csv
hise = []
st = 0
def ime_datoteke_hrvaska(st_strani):
return f"oglas_{st_strani}_hrvaska.txt"
def ime_datoteke(drzava, st_strani):
return f"oglas_{st_strani}_{drzava}.txt"
def izloci_iz_oglasa(oglas):
# Implement the logic to extract relevant information from the advertise... | magicoder | python |
You are tasked with implementing a simple text-based adventure game in Python. The game will involve navigating through different rooms, making decisions, and encountering various scenarios. To achieve this, you will need to create a Room class and a Player class, and implement methods for movement, interaction, and ga... | ```python
class Room:
def __init__(self, name, description):
self.name = name
self.description = description
self.exits = {}
def add_exit(self, direction, room):
self.exits[direction] = room
class Player:
def __init__(self, starting_room):
self.current_room = starti... | magicoder | python |
You are tasked with implementing a gRPC service for a trading platform. The service will handle the buying and selling of stocks. The protocol buffer file `trader.proto` defines the service and messages used for communication between the client and the server. The `trader.proto` file contains the following definitions:... | ```python
# Python gRPC server implementation for the StockTrader service
import grpc
import trader_pb2
import trader_pb2_grpc
class StockTraderServicer(trader_pb2_grpc.StockTraderServicer):
def BuyStock(self, request, context):
# Validate the BuyStock request
if request.quantity <= 0:
... | magicoder | python |
You are tasked with creating a script to automate the deployment and execution of a series of commands for generating and running a comparator circuit using Docker containers and a custom circuit generation tool. Your task is to write a Python script that will encapsulate the necessary commands and ensure the successfu... | ```python
import os
import subprocess
# Step 1: Change directory to "Intel" and execute the Python script "generate_comparator_v2.py"
os.chdir("Intel")
subprocess.run(["python", "generate_comparator_v2.py"])
# Step 2: Run a Docker container named "sam" using the "ubuntu" image, with a volume mount named "comparatorIn... | magicoder | python |
You are tasked with implementing a simplified version of a server-side component for handling HTTP requests using Java's NIO (Non-blocking I/O) framework. The provided code snippet is part of a server application that uses a `SocketChannel` to handle incoming HTTP requests. Your task is to complete the implementation o... | ```java
private void receive(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024); // Allocate a buffer for reading data
// Read the incoming HTTP request from the SocketChannel
int bytesRead = channel.read(buffer);
... | magicoder | java |
You are tasked with implementing a parser combinator library in Rust. Parser combinators are higher-order functions that can be used to combine simple parsers into more complex parsers. The code snippet provided is a part of the parser combinator library and defines a method `count` for a parser. The `count` method is ... | ```rust
// Define the Parser trait
trait Parser {
type Output;
fn parse(&self, input: &str) -> Result<Self::Output, &str>;
}
// Define the Count struct
struct Count<P> {
parser: P,
count: usize,
}
impl<P> Count<P> {
// Constructor for Count
fn new(parser: P, count: usize) -> Count<P> {
... | magicoder | rust |
You are tasked with creating a Python program that reads a given text file and extracts the copyright information from it. The copyright information is enclosed within triple double quotes (`""" ... """`). The program should extract the copyright holder's name and the years covered by the copyright.
Create a function ... | ```python
from typing import Tuple
import re
def extract_copyright_info(file_path: str) -> Tuple[str, str]:
with open(file_path, 'r') as file:
content = file.read()
match = re.search(r'"""Copyright \(c\) (\d{4}-\d{4}) (.+?)\b', content)
if match:
years = match.group(1)
... | magicoder | python |
You are tasked with implementing a Python class for a deep learning model trainer. The class is responsible for training a neural network model using various hyperparameters and settings. Your task is to complete the implementation of the `ModelTrainer` class by adding the `train_model` method, which will handle the tr... | ```python
import torch
import torch.nn as nn
import torch.optim as optim
import wandb
class ModelTrainer:
def __init__(self, encoder, wandb, device, fully_supervised, save_dir, num_classes, epochs=100, lr=0.001, batch_size=64, patience=5, method_name='default'):
self.encoder = encoder
self.wandb = ... | magicoder | python |
You are tasked with implementing a multi-step form component for a standalone server setup process. The form consists of multiple steps, and each step is represented by a separate component. The provided code snippet shows the usage of a `StandaloneServerPage` component, which takes several props to manage the form nav... | ```javascript
// Function to handle navigation to the previous step
const goToPreviousStep = () => {
if (currentStep > 1) {
// Update the current step to the previous step
setCurrentStep(currentStep - 1);
}
};
// Function to handle form submission when the final step is reached
const handleConfirmStandalon... | magicoder | javascript |
You are tasked with implementing a Python class for converting vectors to grids and vice versa. The class should provide methods for converting a vector to a grid and for retrieving a vector from a grid.
You are given a code snippet that partially implements the class. Your task is to complete the class by implementin... | ```python
import numpy as np
class VectorGridConverter:
def __init__(self, ndim, ngrid):
self.ndim = ndim
self.ngrid = ngrid
self.nbins = ngrid ** ndim
def convert_to_grid_idx(self, bin_idx):
grid_idx = []
for _ in range(self.ndim):
grid_idx.append(bin_idx %... | magicoder | python |
You are tasked with creating a Python function that calculates the area under a given curve using the trapezoidal rule. The trapezoidal rule is a numerical integration method that approximates the definite integral of a function. The function should take in the function to be integrated, the limits of integration, and ... | ```python
import numpy as np
def trapezoidal_rule_area(func, xmin, xmax, n):
x = np.linspace(xmin, xmax, n+1) # Generate n+1 equally spaced points between xmin and xmax
y = func(x) # Evaluate the function at the generated points
h = (xmax - xmin) / n # Calculate the width of each subinterval
# Appl... | magicoder | python |
You are tasked with creating a program that extracts and displays the copyright year and the application name from a given HTML code snippet. The HTML code contains PHP and Blade templating syntax, and the copyright year and application name are embedded within the code. Your program should be able to parse the HTML co... | ```php
function extractCopyrightAndAppName($htmlCode) {
$copyrightYear = null;
$applicationName = null;
// Extract copyright year using regular expression
if (preg_match('/© <?php echo date\("Y"\); ?>/', $htmlCode, $matches)) {
$copyrightYear = date("Y");
}
// Extract application ... | magicoder | php |
You are tasked with implementing a function that takes a list of version strings and returns the latest version based on semantic versioning rules. Semantic versioning is a versioning scheme that consists of three parts: major version, minor version, and patch version, separated by dots (e.g., "1.2.3"). The version str... | ```rust
fn find_latest_version(versions: Vec<String>) -> String {
let mut latest_version = String::new();
for version in versions {
if latest_version.is_empty() || is_newer_version(&version, &latest_version) {
latest_version = version;
}
}
latest_version
}
fn is_newer_versio... | magicoder | rust |
You are tasked with implementing a generic method to convert a DTO (Data Transfer Object) to its corresponding entity object in a Java application. The DTO and entity classes follow a specific naming convention, and the method should be able to handle this conversion for any DTO that extends the `BaseDTO` class. The DT... | ```java
import java.lang.reflect.Field;
public class DTOConverter {
public <T extends BaseDTO, U> U convertToEntity(T dto, Class<U> entityClass) throws IllegalAccessException, InstantiationException {
U entity = entityClass.newInstance();
Field[] dtoFields = dto.getClass().getDeclaredFields();
... | magicoder | java |
You are tasked with implementing a Python class for feature processing and classification. The class contains methods for running different feature processing techniques and classifiers. Your task is to complete the implementation of the `FeatureClassifier` class by adding the `run_BoVW` method and modifying the existi... | ```python
class FeatureClassifier:
def __init__(self, feature_name):
self.feature_name = feature_name
def run_MFCC(self):
"""run classifier on MFCC feature (single modality)
"""
print("\nbuilding a classifier on MFCC features (both frame-level and session-level)")
X_trai... | magicoder | python |
You are tasked with implementing a custom data structure in Swift that simulates a stack with an additional feature. The stack should support the standard push and pop operations, but it should also provide a method to retrieve the maximum element in the stack at any given time. You need to implement the `MaxStack` cla... | ```swift
class MaxStack {
private var stack: [Int]
private var maxStack: [Int]
init() {
stack = []
maxStack = []
}
func push(_ x: Int) {
stack.append(x)
if maxStack.isEmpty || x >= maxStack.last! {
maxStack.append(x)
}
}
func pop() -> In... | magicoder | swift |
You are tasked with understanding and resolving a conflict arising from the code snippet provided. The code snippet contains a protocol extension and a protocol method declaration, both named `didDisAppearCell`. However, the method in the protocol extension has an empty implementation, while the method declaration in t... | ```swift
// Define the protocol
protocol IMUIMessageCellProtocol {
func didDisAppearCell()
}
// Create a class conforming to the protocol
class MessageCell: IMUIMessageCellProtocol {
func didDisAppearCell() {
// Implement the method
print("Message cell disappeared")
}
}
// Usage
let cell =... | magicoder | swift |
You are tasked with creating a Python class that performs Git operations using subprocess and handles potential errors. Your class should include methods for initializing the repository, adding files, committing changes, and pushing to a remote repository. Additionally, the class should handle custom exceptions for Git... | ```python
# The provided code snippet defines a Python class `GitManager` that is responsible for managing Git operations using subprocess and handling potential errors. The class includes methods for initializing the repository, adding files, committing changes, and pushing to a remote repository. It also handles cust... | magicoder | python |
You are tasked with implementing a function to perform 1D interpolation of values based on mean and standard deviation arrays. The function should handle out-of-bounds values by clamping them to specified upper and lower bounds. Additionally, the implementation should utilize the Numba library for just-in-time compilat... | ```python
import numpy as np
import numba as nb
@nb.njit(nogil=True, cache=True)
def interp_values_1d(x: np.ndarray,
mean_values: np.ndarray,
std_values: np.ndarray,
num_stds: int = 3,
lbound: float = 0.0,
ubound: ... | magicoder | python |
You are given a positive integer `n` representing the size of a sequence. The sequence is generated using the following rules:
1. Start with the number 1.
2. If the current number is even, divide it by 2.
3. If the current number is odd, multiply it by 3 and add 1.
4. Repeat the process until the number becomes 1.
You... | ```python
def sequence_length(n: int) -> int:
length = 1
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
length += 1
return length
``` | magicoder | python |
You are tasked with creating a script to automate the comparison of MET spectra data using the ROOT framework. The provided code snippet is a part of a larger script and contains two commands. The first command runs a ROOT script named `compareMETspectra.C` with two arguments `${indir}` and `${outfiletext}`. The second... | ```python
import subprocess
import os
def run_compareMETspectra(indir, outfiletext):
command = f"root -l -b -q test_macros/compareMETspectra.C\\(\"{indir}\",\"{outfiletext}\"\)"
subprocess.run(command, shell=True)
def prep_out_dir(topdir, disphodir, outdir):
fulldir = os.path.join(topdir, disphodir, outdi... | magicoder | python |
You are tasked with simulating the functionality of a wireless network scanner and location fixer using the provided code snippet as a reference. Your goal is to implement a program that processes the output of a wireless network scan and determines the location based on the access points' data.
You are given a code s... | ```python
import re
def apscan(scan_output):
addresses = re.findall(r"Address: ([0-9A-F:]{17})", scan_output)
strengths = [int(strength.split('=')[1]) for strength in re.findall(r"Signal level=([-0-9]+)", scan_output)]
channels = [int(channel) for channel in re.findall(r"Channel (\d+)", scan_output)]
s... | magicoder | python |
You are tasked with implementing a Python class that performs a specific mathematical operation. The class should have a method that takes a single parameter and returns the result of the operation. Additionally, the class should have a method that returns the current state of the operation.
Your task is to complete t... | ```python
from abc import ABC, abstractmethod
class MathOperation(ABC):
@abstractmethod
def __call__(self, x):
pass
def state(self):
raise NotImplementedError("state method must be implemented in the subclass")
```
In the solution, the `MathOperation` class is defined as an abstract base ... | magicoder | python |
You are tasked with implementing a feature fusion mechanism in a neural network model. The feature fusion mechanism can be configured to use different fusion strategies, such as early concatenation or late addition. The feature fusion mechanism takes two input features and combines them using a specified fusion strateg... | ```python
class FeatureFusion:
def __init__(self, feat_fusion, feat_activ):
self.feat_fusion = feat_fusion
self.feat_activ = feat_activ
self.feat_layer = None
def early_concat_fusion(self, feature1, feature2):
# Implement early concatenation feature fusion logic
fused_fe... | magicoder | python |
You are given a code snippet from a React component that is part of a game. The game involves a sequence of colored segments, and the goal is to guess the correct sequence. The code snippet shows a part of the component responsible for displaying feedback about the correctness of a guess. The `className` attribute of a... | ```javascript
function provideFeedback(sequence, guess) {
const feedback = {
correctPosition: [],
inSequence: [],
notInSequence: []
};
const sequenceMap = new Map();
const guessMap = new Map();
for (let i = 0; i < sequence.length; i++) {
if (sequence[i] === guess[i]) {
feedback.correct... | magicoder | javascript |
You are tasked with creating a program to manage task completion times for a team of developers. The program should generate a random task completion date and time to avoid all users accessing the data server at the same time. The task completion time should be set to 17:30:00 (5:30 PM) to distribute the load on the se... | ```python
import random
from datetime import datetime, timedelta
def generate_task_completion_time():
# Set the task completion time to 17:30:00
task_time = datetime.now().replace(hour=17, minute=30, second=0, microsecond=0)
# Generate a random future date
random_days = random.randint(1, 30) # Ge... | magicoder | python |
You are tasked with implementing a locality-aware feedforward layer as part of a neural network architecture. The locality-aware feedforward layer is a key component of the Self-Attentive Transformer Network (SATRN), which is used for sequence modeling tasks such as language translation and image captioning.
The local... | ```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class LocalityAwareFeedforward(nn.Module):
"""Locality-aware feedforward layer in SATRN, see `SATRN <https://arxiv.org/abs/1910.04396>`_"""
def __init__(self, input_dim, hidden_dim, dropout=0.1):
"""
Initialize the Lo... | magicoder | python |
You are tasked with designing a modular audio processing system in Rust. The system should consist of several modules for audio input/output, device management, host configuration, audio playback, queuing, and stream management. Each module will have specific functionalities and interactions with other modules.
Your t... | ```rust
// def.rs
pub mod def {
// Define audio-related constants and structures
pub struct AudioData {
// Define audio data structure
}
// Other audio-related definitions
}
// device.rs
pub mod device {
use crate::def::AudioData;
pub struct AudioDevice {
// Define audio de... | magicoder | rust |
You are tasked with implementing a Python class that represents a list of objects with a specific attribute. The class should enforce that the list has at least one entry and that all the objects in the list have the same value for a particular attribute. Your task is to complete the implementation of the class by fill... | ```python
from string import Template
class Object:
def __init__(self, tss):
self.tss = tss
class ObjectList(list):
def __init__(self, *args):
super().__init__(*args)
# make sure it has at least one entry
if not (len(self)) > 0:
raise (Exception("There has to be at ... | magicoder | python |
You are tasked with implementing a function to parse and validate a NVMf (NVMe over Fabrics) Qualified Name (NQN) and extract its components. An NQN is a string that consists of two components separated by a colon. The first component is a string representing the subsystem name, and the second component is a UUID. The ... | ```rust
use std::num::ParseIntError;
#[derive(Debug)]
struct DeviceError {
message: String,
}
impl DeviceError {
fn new(message: &str) -> Self {
DeviceError {
message: message.to_string(),
}
}
fn from(message: String) -> Self {
DeviceError { message }
}
}
#[de... | magicoder | rust |
You are tasked with creating a script to automate the release process for a Node.js application. The script should perform the following tasks:
1. Extract the name and version of the application from the `package.json` file.
2. Remove any existing app bundle and source zip files with the same name and version.
3. Run ... | ```bash
#!/bin/bash
if [ "$1" == "release" ]; then
name=$(grep -oP '"name":\s*"\K(.*)(?=")' package.json)
version=$(grep -oP '"version":\s*"\K(.*)(?=")' package.json)
rm -f ${name}-${version}_appbundle.zip ${name}-${version}_source.zip
npm run prod
ln -s prod ${name}-${version}_appbundle
zip -... | magicoder | shell |
You are working on a computer graphics project and need to implement a new feature for simulating light interaction with materials. Specifically, you are tasked with creating a program that models the behavior of light as it interacts with different types of surfaces. One important aspect of this simulation is the calc... | ```python
def calculateRT(R, T, isSpecular, distrib, fresnel, eta, mode):
reflectance = 0
transmittance = 0
if R > 0:
reflectance += R * fresnel
if T > 0:
if isSpecular:
transmittance += T
else:
transmittance += T * (1 - distrib)
return ... | magicoder | python |
You are tasked with implementing a file format detection and parsing system for a data processing application. The system should be able to detect the format of input files, parse the data according to the detected format, and then output the parsed data to one or more output files in a specified format.
Your task is ... | ```python
class FileFormatDetector:
def __init__(self, input_file, **kwargs):
self.input = input_file
self.formats = {}
self.format_options = kwargs
if input_file is not None:
self.parser = self.detect_format(self.input)
def output(self, output_files):
deal_s... | magicoder | python |
You are tasked with implementing a lazy loading mechanism for adding modules to a program in a virtual machine environment. The virtual machine uses the NVVM (NVIDIA Virtual Machine) framework, and the provided code snippet is the beginning of a function that handles the lazy loading process.
The function `nvvmLazyAdd... | ```rust
struct LazyModule {
name: String,
code: Vec<u8>,
loaded: bool,
}
impl LazyModule {
fn new(name: String, code: Vec<u8>) -> LazyModule {
LazyModule {
name,
code,
loaded: false,
}
}
fn load(&mut self) {
// Simulate loading the mo... | magicoder | rust |
You are tasked with implementing a Python function to generate a list of prime numbers up to a given limit. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your function should take a non-negative integer `limit` as input and return a list of all prime numbers le... | ```python
# dojo.py
def primes(limit):
if limit < 2:
return []
sieve = [True] * limit
sieve[0], sieve[1] = False, False # 0 and 1 are not prime
for num in range(2, int(limit ** 0.5) + 1):
if sieve[num]:
for multiple in range(num * num, limit, num):
... | magicoder | python |
You are tasked with implementing a Python class that can stack bitmap masks and polygon masks. The class should be able to handle various operations on these masks, such as stacking multiple masks together.
You are provided with a code snippet that defines a Python class `Stack` within a larger module. Your task is to... | ```python
from mmdet.core import BitmapMasks, PolygonMasks
from ..builder import PIPELINES
@PIPELINES.register_module()
class Stack:
def __init__(self):
self.stacked_bitmap_masks = None
self.stacked_polygon_masks = None
def stack_bitmap_masks(self, bitmap_masks):
if not isinstance(bitm... | magicoder | python |
You are given a text file containing data in the following format:
```
Name: John Doe
Age: 25
City: New York
Name: Jane Smith
Age: 30
City: Los Angeles
```
Each record represents a person's information, with the fields "Name", "Age", and "City" separated by a colon and a space. Records are separated by a blank line.... | ```python
# Open the input file and read the data
with open('input.txt', 'r') as input_file:
data = input_file.read()
# Split the data into individual records
records = data.strip().split('\n\n')
# Initialize variables for total age and number of people
total_age = 0
num_people = 0
# Iterate through each record ... | magicoder | python |
You are tasked with implementing a custom slider element in TypeScript. The slider should extend the `ViewHTMLElement` interface, which includes optional properties for a progress view, progress bar, info view, and current view. Your task is to complete the implementation of the `SliderElement` class by adding the nece... | ```typescript
export class SliderElement extends ViewHTMLElement {
protected _min: number;
protected _max: number;
protected _step: number;
protected _value: number;
constructor(min: number, max: number, step: number, value: number) {
super();
this._min = min;
this._max = ma... | magicoder | typescript |
You are tasked with implementing a Python function that simulates a simple file system. The file system will consist of directories and files, and the function should be able to perform basic operations such as creating directories, creating files, listing the contents of a directory, and navigating through the file sy... | ```python
import sys
class FileSystem:
def __init__(self):
self.root = Directory("/")
def execute_command(self, command):
operation, path = command.split(" ", 1)
if operation == "mkdir":
return self.create_directory(path)
elif operation == "touch":
retur... | magicoder | python |
You are tasked with creating a Python function that generates URL patterns for a Django web application. The function should take a list of tuples, where each tuple contains a URL pattern and its corresponding view function. The function should then construct a list of URL patterns in the format required by Django.
Wr... | ```python
from django.conf.urls import url
from . import views
def generate_url_patterns(url_view_tuples):
url_patterns = []
for url_pattern, view_function in url_view_tuples:
url_patterns.append(url(r'^' + url_pattern + r'$', getattr(views, view_function)))
return url_patterns
```
The `generate_u... | magicoder | python |
You are tasked with creating a function that parses HTML code to extract information about premium status options for a video. The function should take the HTML code as input and return a dictionary containing the premium status options and their corresponding values.
The HTML code snippet provided represents a form f... | ```python
from bs4 import BeautifulSoup
def extract_premium_options(html_code):
premium_options = {}
soup = BeautifulSoup(html_code, 'html.parser')
premium_labels = soup.find_all('label', class_='w3-padding')
for label in premium_labels:
input_tag = label.find('input')
if input_tag:
... | magicoder | python |
You are tasked with implementing a class to manage a to-do list. The class should have the following attributes and methods:
Attributes:
- `tasks`: a list to store the tasks in the to-do list.
Methods:
- `add_task(task)`: a method to add a new task to the to-do list.
- `remove_task(task)`: a method to remove a task f... | ```python
class TodoList:
def __init__(self):
self.tasks = []
def add_task(self, task):
self.tasks.append(task)
def remove_task(self, task):
if task in self.tasks:
self.tasks.remove(task)
else:
print(f"{task} not found in the to-do list.")
def g... | magicoder | python |
You are tasked with creating a class that manages settings for a polygon modification tool in a graphical user interface (GUI) application. The provided code snippet is a part of the GUI setup for this tool. Your task is to implement the `QPolySettings` class, which will handle the settings for the polygon modification... | ```cpp
#include <QObject>
#include <QGroupBox>
#include <QVBoxLayout>
#include <QLineEdit>
class QPolySettings : public QObject {
Q_OBJECT
public:
QPolySettings() {
// Constructor implementation
// Initialize any necessary variables or connections
}
// Method to update the properties o... | magicoder | cpp |
You are tasked with designing a neural network architecture for a computer vision task. The network will consist of multiple layers, each with its own activation function and trainable parameters. Additionally, you need to implement an optimizer and a trainer to efficiently train the network.
Your task is to create a ... | ```python
class Layer:
def __init__(self, input_size, output_size, activation_func):
self.input_size = input_size
self.output_size = output_size
self.activation_func = activation_func
self.parameters = Parameters(input_size, output_size)
def forward(self, input_data):
# ... | magicoder | python |
You are tasked with implementing a C++ class that represents a URL for web services. The class should support the construction of URLs with various components such as scheme, authority, path, query, and fragment. Additionally, the class should provide methods for accessing and modifying these components.
Your task is ... | ```cpp
#include <string>
class URL {
public:
URL(std::string const & scheme="", std::string const & authority="")
: scheme(scheme), authority(authority) {}
void setPath(const std::string &newPath) {
path = newPath;
}
std::string getPath() const {
return path;
}
void ... | magicoder | cpp |
You are tasked with creating a class that processes a list of integers and performs specific operations on them. Your task is to implement a class called `IntegerProcessor` with the following specifications:
- The class should have a method called `ProcessIntegers` that takes a list of integers as input and returns a ... | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
public class IntegerProcessor
{
public List<int> ProcessIntegers(List<int> input)
{
// Remove negative integers
input = input.Where(x => x >= 0).ToList();
// Square each integer
for (int i = 0; i < inp... | magicoder | csharp |
You are tasked with creating a Python function that processes a list of recordings and generates a report based on certain conditions. Each recording is represented as a dictionary with the following keys: 'recording_name', 'duration', 'storageSize', and 'created'. The function should take the list of recordings as inp... | ```python
from datetime import datetime, timedelta
def generate_report(recordings):
report = []
for recording in recordings:
category = None
if recording['duration'] < 60:
category = 'Short recording'
elif recording['storageSize'] > 100:
category = 'Large file'
... | magicoder | python |
You are given a list of intervals, where each interval is represented by a pair of integers `[start, end]`. The intervals may not be sorted, and they may overlap. Your task is to merge overlapping intervals and return a new list of non-overlapping intervals.
Write a function `merge_intervals(intervals)` that takes in ... | ```python
class Interval:
def __init__(self, start, end):
self.start = start
self.end = end
def merge_intervals(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x.start) # Sort intervals based on start time
result = [intervals[0]] # Initialize the result ... | magicoder | python |
You are tasked with implementing a function that calculates the distance and direction between two points in a grid system. The function takes in the zone, easting, and northing of the first point, the grid conversion parameters, and the grid distance. Your task is to write a Python function that computes the distance ... | ```python
import math
def calculate_distance_and_direction(zone1, east1, north1, grid1to2, grid_dist):
# Assuming the grid conversion parameters are used to calculate the distance and direction
# Here, we are using the provided code snippet as a reference to calculate the distance and direction
# The actua... | magicoder | python |
You are tasked with creating a program that processes a given text and removes all characters except for letters (both lowercase and uppercase) and spaces. Additionally, if the input text contains more than one word, the program should concatenate the words into a single string and separate them with a period.
Write ... | ```python
def process_text(text):
# Concatenate words with a period if there are multiple words
if len(text.split()) > 1:
processed_text = '. '.join(text.split())
else:
processed_text = text
# Remove all characters except for letters (both lowercase and uppercase) and spaces
whiteli... | magicoder | python |
You are working on a machine learning project and need to implement several utility functions for processing model predictions. You are given three Python functions that utilize the NumPy and PyTorch libraries. Your task is to implement a new function that combines the functionality of the existing functions to process... | ```python
import numpy as np
import torch
def process_predictions(model, loader, threshold):
predictions = np.vstack(predict_batch(model, data[0]) for data in loader) # Get model predictions for the entire dataset
processed_predictions = get_predictions(predictions, threshold) # Convert probabilities to bina... | magicoder | python |
You are given a string representing a direction in the format "--direction X2Y", where "X" and "Y" are single uppercase letters representing the starting and ending points, and "2" is a digit representing the distance between the points. Your task is to write a program to calculate the number of possible paths from the... | ```python
def count_possible_paths(direction):
start, distance, end = direction[12], int(direction[10]), direction[11]
x_diff = abs(ord(end) - ord(start))
y_diff = distance - x_diff
if x_diff > distance or y_diff > distance:
return 0
return min(distance + 1, x_diff + 1) * min(distance + 1, y... | magicoder | python |
You are tasked with identifying and fixing a vulnerability related to improper resource shutdown or release in a C++ program. The vulnerability is categorized under CWE-404. The code snippet provided is part of a larger program that demonstrates the vulnerability and its potential fixes.
The vulnerability arises from ... | The vulnerability in the code snippet is the improper use of `fclose()` to close a file handle obtained using `CreateFile()`. The correct method for closing file handles obtained using `CreateFile()` is to use the `CloseHandle()` function.
To fix the vulnerability, the `fclose()` call should be replaced with a call to... | magicoder | cpp |
You are tasked with implementing a class that represents a record of expenses. The class should provide methods for adding and retrieving expense details, as well as for calculating the total amount spent. Your task is to complete the implementation of the `TtBuktiPengeluaran` class according to the following specifica... | ```javascript
class TtBuktiPengeluaran {
constructor() {
this.expenses = [];
}
addExpense(description, amount) {
this.expenses.push({ description, amount });
}
getExpenses() {
return this.expenses;
}
getTotalAmount() {
return this.expenses.reduce((total, expense) => total + expense.amou... | magicoder | javascript |
You are tasked with implementing a Python function that calculates the probability and prediction from a given output tensor. The output tensor is assumed to be the result of a neural network's forward pass and contains the raw output values for each class. The function should perform the following steps:
1. Find the i... | ```python
import torch
from typing import Tuple
def calculate_probability_and_prediction(output: torch.Tensor) -> Tuple[float, int]:
log_softmax, prediction = output.max(1)
probability = torch.exp(log_softmax).item()
prediction = prediction.item()
return round(probability, 16), prediction
``` | magicoder | python |
You are tasked with implementing a logging system for a software application. The logging system should support different log levels and be able to filter log messages based on their severity. Your task is to create a Python class called `CustomLogger` that provides this functionality.
The `CustomLogger` class should ... | ```python
import logging
class CustomLogger:
def __init__(self, log_level):
self.log_level = log_level
def debug(self, message):
if self.log_level <= 0:
print(f"DEBUG: {message}")
def info(self, message):
if self.log_level <= 1:
print(f"INFO: {message}")
... | magicoder | python |
You are tasked with creating a reinforcement learning agent to play the game of Tic-Tac-Toe using the TD(λ) algorithm. The game of Tic-Tac-Toe is represented by a 3x3 grid where two players take turns marking a cell with their respective symbols (X or O) until one player wins or the game ends in a draw.
To accomplish ... | ```python
from tic_tac_toe import TicTacToeGameSpec, play_game
from TD_lambda import TD_train
def train_tic_tac_toe_agent(num_episodes, learning_rate, discount_factor, lambda_value):
game_spec = TicTacToeGameSpec()
agent = TD_train(game_spec, num_episodes, learning_rate, discount_factor, lambda_value)
retu... | magicoder | python |
You are given two arrays, A and B, each containing N integers. Additionally, you are given two integers, X and Y. Your task is to find the maximum value of the expression (A[i] - B[j])^2 + (A[i] - X)^2 + (B[j] - Y)^2, where i and j are indices of arrays A and B, respectively.
Write a function `max_expression_value(N, ... | ```python
def max_expression_value(N, X, Y, A, B):
max_val = float('-inf')
for i in range(N):
for j in range(N):
expression_val = (A[i] - B[j])**2 + (A[i] - X)**2 + (B[j] - Y)**2
max_val = max(max_val, expression_val)
return max_val
# Test the function with the provided exam... | magicoder | python |
You are tasked with creating a program that processes and analyzes diagnostic output from a code analysis tool. The tool generates diagnostic messages in the form of comments within the source code. Each comment contains specific information about the code being analyzed. Your task is to extract and process this diagno... | ```python
import re
def extract_diagnostic_info(code_snippet):
diagnostic_info = {
"64-bit": {},
"32-bit": {}
}
pattern = r'// CHECK-(\d+): (.+)'
matches = re.findall(pattern, code_snippet)
for match in matches:
arch, info = match
arch = "64-bit" if arch == "64" el... | magicoder | python |
You are tasked with creating a function that processes job information and returns the status of a specific job. The job information is represented as an associative array with the following keys: "id", "name", "status", and "timestamp". The function should take in the job information array and the job ID as arguments ... | ```php
function getJobStatus($jobInfo, $jobId) {
foreach ($jobInfo as $job) {
if ($job['id'] === $jobId) {
return $job['status'];
}
}
return "Job ID not found";
}
// Test cases
$jobInfo = [
["id" => 1, "name" => "Job1", "status" => "pending", "timestamp" => "2022-01-01 12:00... | magicoder | php |
You are tasked with implementing a rate-limiting mechanism for a web service using the `ratelimit` package in Python. The web service interacts with a MySQL database using the `sqlalchemy` library. Your goal is to create a decorator function that limits the rate of incoming requests to the web service based on a specif... | ```python
# Import necessary libraries
from ratelimit import limits, RateLimitException
from sqlalchemy import create_engine, Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime, timedelta
from functools import wraps
# ... | magicoder | python |
You are tasked with implementing a text vectorization method that converts a given document into a numerical representation. The vectorization process involves assigning numerical values to each word in the document based on their frequency within the document.
You are provided with a Python class containing a method... | ```python
import numpy as np
from collections import Counter
class TextVectorizer:
def __init__(self):
pass
def vectorize(self, doc: str) -> np.ndarray:
"""
Identify the vector values for each word in the given document
:param doc: a string representing the input document
... | magicoder | python |
You are tasked with implementing a function that calculates the total number of UTF-16 code units in a given string. UTF-16 is a character encoding capable of encoding all 1,112,064 valid code points in Unicode using one or two 16-bit code units. The function should take a string as input and return the total number of... | ```java
public int calculateUTF16CodeUnits(String inputString) {
int ans = 0;
for (int i = 0; i < inputString.length(); i++) {
char ch = inputString.charAt(i);
ans += Character.charCount(ch); // const since 1.52
}
return ans;
}
```
The solution defines the function `calculateUTF16CodeUn... | magicoder | java |
You are tasked with implementing a function that calculates the number of trailing zeros in the factorial of a given integer. The factorial of a non-negative integer n is denoted as n! and is the product of all positive integers less than or equal to n. For example, 5! = 5 * 4 * 3 * 2 * 1 = 120. The number of trailing ... | ```rust
fn trailing_zeros_in_factorial(n: u64) -> u64 {
let mut count = 0;
let mut i = 5;
while n / i > 0 {
count += n / i;
i *= 5;
}
count
}
fn main() {
println!("{}", trailing_zeros_in_factorial(5)); // Output: 1
println!("{}", trailing_zeros_in_factorial(10)); // Output: ... | magicoder | rust |
You are tasked with implementing a data structure that stores key-value pairs, where the keys are strings and the values can be of any type. You need to create a class that encapsulates this data structure and provides methods for adding, retrieving, and removing key-value pairs.
Your task is to create a Swift class c... | ```swift
class KeyValueStore {
private var data: [String: Any]
init(_ data: [String: Any]) {
self.data = data
}
func setValue(_ key: String, _ value: Any) {
data[key] = value
}
func getValue(_ key: String) -> Any? {
return data[key]
}
func removeValue(_ key: S... | magicoder | swift |
You are tasked with implementing a function that performs a specific type of image processing operation. The function takes as input an image `_input`, an output image `_output`, and a window size for processing. The function is responsible for applying the image processing operation to the input image and storing the ... | ```cpp
void imageProcessingOperation(const Image& _input, Image& _output, const Size& window) {
for (int y = 0; y < _input.height(); ++y) {
for (int x = 0; x < _input.width(); ++x) {
// Apply the specific image processing operation to derive the corresponding pixel value in the output image
... | magicoder | cpp |
You are tasked with implementing a caching mechanism for a system that interacts with an external storage service, such as Amazon S3. The system needs to efficiently manage the retrieval of files from the external storage while minimizing the number of requests made to the service. The system should prioritize accessin... | To address the caching requirements, we can implement a caching system using a data structure such as a hash map to store the cached files. We can also use a set to keep track of the file types that have been populated in the cache. Here's a Python-based solution to demonstrate the caching system:
```python
class Cach... | magicoder | python |
You are tasked with implementing a data cleaning algorithm for a DataFrame containing columns `theme1`, `list1`, and `list2`. The given code snippet attempts to clean the data by handling KeyError and TypeError exceptions. Your task is to complete the data cleaning algorithm by implementing the missing parts and optimi... | ```python
# Import pandas library if not already imported
import pandas as pd
# Assuming df2 is the given DataFrame
# Complete the data cleaning algorithm for theme1 column
for i, l in df2.theme1.iteritems():
try:
df2.theme1.iloc[i] = l['theme']
except (KeyError, TypeError):
df2.theme1.iloc[i]... | magicoder | python |
You are tasked with implementing a program that simulates a simple banking system. The system should be able to create and manage bank accounts, allowing users to deposit, withdraw, and check their balance. Each bank account should have a unique account number and be associated with the account holder's name.
Your tas... | ```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
return f"Deposited... | magicoder | python |
You are tasked with creating a program that analyzes the frequency of words in a given text file and outputs the top N most frequent words along with their counts. The program should ignore common stop words (e.g., "the", "and", "is") and should be case-insensitive (i.e., "The" and "the" should be considered the same w... | ```python
import re
from collections import Counter
def top_n_words(file_path, n):
with open(file_path, 'r') as file:
text = file.read().lower()
words = re.findall(r'\b\w+\b', text)
stop_words = {'the', 'and', 'is', 'in', 'it', 'of', 'to', 'a', 'this', 'that', 'with', 'for', 'on', 'at', 'an... | magicoder | python |
You are tasked with creating a script to automate the backup and archiving of MySQL databases. The script should dump the SQL data, compress it, and then delete any backups older than 30 days. Below is a simplified version of the script that you need to expand upon:
```bash
#!/bin/bash
# Define the directory for stor... | ```bash
#!/bin/bash
# Define the directory for storing backups
DIR="/path/to/backups"
# Define the function to dump SQL data
dump_sql() {
mysqldump -u username -p password database_name
}
# Define the function to create an archive
create_archive() {
DATE=$(date +"%Y-%m-%d")
xz > "$DIR"/mysql."$(hostname -s)"."... | magicoder | shell |
You are tasked with creating a shell script that retrieves the kernel version of a Linux system and displays it. Your script should be able to extract the kernel version from the system and print it to the console.
Write a shell script named `kernel_version.sh` that accomplishes the following:
1. Retrieves the kernel ... | ```bash
#!/bin/sh
# Retrieve the kernel version using uname command
kernel_version=$(uname -r)
# Print the kernel version to the console
echo $kernel_version
```
The shell script `kernel_version.sh` uses the `uname -r` command to retrieve the kernel version from the system and stores it in the `kernel_version` varia... | magicoder | shell |
You are given a code snippet that demonstrates a bitwise operation within a loop. Your task is to understand the logic of the code and predict the final value of the "result" variable after the loop completes.
The code snippet is as follows:
```
Starting for loop:
i = 0:
result = result << 1 = 0000_0000_0000_0000_0000... | ```python
def final_result(n):
result = 0
for i in range(32): # Assuming 32-bit integer
result = result << 1
if n & 1:
result += 1
n = n >> 1
return result
```
The solution defines a function "final_result" that takes an integer "n" as input. It initializes the "result"... | magicoder | python |
You are given a code snippet that appears to be a part of a parser for a programming language. The snippet seems to be related to parsing a type declaration, specifically for a primitive type. The code includes comments and references to various data structures and functions, but it is not clear what the overall struct... | ```python
import re
def parse_type_declaration(type_str):
type_pattern = r'(int|bool|string)(?:\[(\d+)\])?'
match = re.match(type_pattern, type_str)
if match:
type_name = match.group(1)
size = match.group(2)
return (type_name, int(size)) if size else (type_name, None)
else:
... | magicoder | python |
You are tasked with implementing a function that processes a list of members and generates a dictionary containing relevant information about these members. The function should also handle the creation of collection links based on certain criteria.
You are given a code snippet that partially implements this functional... | ```python
def process_members(request, members):
members_list = []
for member in members:
member_dict = {
'cgsnapshot_id': member.get('cgsnapshot_id'),
'share_id': member.get('share_id'),
}
members_list.append(member_dict)
members_links = _get_collection_link... | magicoder | python |
You are tasked with creating a Python package for genetic sequence analysis. The package, named "codonPython," will provide various functionalities for working with DNA and RNA sequences. Your task is to define the package structure and dependencies using the provided code snippet as a starting point.
Your package sho... | ```python
from setuptools import setup, find_packages
setup(
name='codonPython',
version='0.1',
license='BSD',
packages=find_packages(),
install_requires=[
'numpy',
'pandas',
],
)
```
In the solution, the setup function is completed with the appropriate package details and depen... | magicoder | python |
You are tasked with creating a Python class to visualize the geometry of a 3D model using the Gmsh API. The given code snippet is a part of the class that initializes the visualization settings and assigns colors to different entities in the model. Your task is to complete the implementation of the `visualizeGeometry` ... | ```python
class ModelVisualizer:
def __init__(self, model):
self.model = model
self.groupColors = []
def visualizeGeometry(self):
# Complete the implementation to visualize the model geometry using the assigned colors
for i, entity in enumerate(self.model.entities):
... | magicoder | python |
You are tasked with creating a program that simulates the behavior of a simplified shell environment. Your program should implement the functionality of the `export` and `eval` commands, as well as handle the initialization of environment variables.
Your program should support the following commands:
- `export VAR=VAL... | ```python
from typing import List, Dict
def simulate_shell(commands: List[str]) -> Dict[str, str]:
environment = {}
for command in commands:
if command.startswith('export'):
parts = command.split(' ')
var, value = parts[1].split('=')
environment[var] = value.strip('"... | magicoder | python |
You are tasked with implementing a Python script that processes command-line arguments to invoke the zserio compiler. The zserio compiler is a tool used to generate code for serialization and deserialization in various programming languages. Your script should handle the command-line arguments and invoke the zserio com... | ```python
import argparse
import subprocess
import sys
import os
def main():
parser = argparse.ArgumentParser(description='Zserio Compiler Invocation')
parser.add_argument('-s', '--schema', help='Path to the zserio schema file to be compiled', required=True)
parser.add_argument('-l', '--language', help='Ta... | magicoder | python |
You are tasked with implementing a custom dataset class for PyTorch that generates random data for a machine learning task. The dataset should generate random input-output pairs for a given function and be capable of returning the data in both tensor and numpy array formats.
Your task is to complete the implementation... | ```python
import torch
import numpy as np
class RandomDataset(torch.utils.data.Dataset):
def __init__(self, size, input_dim, output_dim, function):
self.size = size
self.input_dim = input_dim
self.output_dim = output_dim
self.function = function
def __len__(self):
retur... | magicoder | python |
You are tasked with implementing a resampling algorithm for a dataset using the Metropolis-Hastings algorithm. The Metropolis-Hastings algorithm is a Markov chain Monte Carlo (MCMC) method used to generate a sequence of samples from a probability distribution. In this problem, you will be working with a dataset and spe... | ```python
import numpy as np
def metropolis_hastings_resampling(dataset, gamma_shape, sigma_shape, resample_high):
resampled_dataset = dataset.copy()
current_sample = dataset[0] # Initialize current sample
for _ in range(resample_high):
candidate_sample = np.random.normal(current_sample, sigma_sh... | magicoder | python |
You are tasked with implementing a simple locking mechanism for a display in a graphical user interface (GUI) application. The display can be unlocked by a user action, and the application must check if the display is unlocked before allowing certain operations to be performed.
You are given a pointer `unlockDisplay` ... | ```cpp
#include <iostream>
bool isDisplayUnlocked(void* unlockDisplay) {
return unlockDisplay != nullptr;
}
int main() {
// Example usage
void* unlocked = new int(1); // Simulating an unlocked display
void* locked = nullptr; // Simulating a locked display
std::cout << "Display is unlocked:... | magicoder | cpp |
You are tasked with implementing a custom class decorator in Python. The decorator should modify the behavior of the methods within the class by adding a new functionality. The decorator should be designed to track the execution time of each method and print the time taken for execution when the method is called.
Your... | ```python
import time
from functools import wraps
class TrackExecutionTime:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
start_time = time.time()
result = self.func(*args, **kwargs)
end_time = time.time()
time_taken = round(end_time - ... | magicoder | python |
You are tasked with implementing a function to generate a pair of public and private keys for asymmetric encryption. The function should take in a key size as a parameter and return the generated keys in the form of data objects. The keys should be non-nil and of the correct type and size.
Write a function `generateKe... | ```swift
class KeyGenerator {
func generatePrivateKey(keySize: Int) -> Data? {
// Implementation to generate private key
// Returns nil if key generation fails
// Example implementation using CryptoKit
guard keySize >= 256 else { return nil }
return SymmetricKey(size: .bits(k... | magicoder | swift |
You are tasked with creating a function that converts a given string into Morse code. Morse code is a method used in telecommunication to encode text characters as sequences of two different signal durations, called dots and dashes. Each character is represented by a unique combination of dots and dashes. The Morse cod... | ```python
def morse(s):
morse_code = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---',
'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-',
'U': '..-', '... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.