query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Python function to generate a unique encryption key for a given input string. The function should utilize the Django model `Key` provided below to store the generated key along with its initialization vector (IV) in the database. The `expire_date` for the key should be set to 30 days from... | ```python
import uuid
from datetime import datetime, timedelta
import hashlib
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from base64 import b64encode
def generate_encryption_key(input_string: str) -> None:
# Generate a unique key_ref
key_ref = uuid.uuid4()
# Generate a random... | magicoder | python |
You are tasked with implementing a Trie data structure in Java to efficiently store and retrieve strings. A Trie, also known as a prefix tree, is a tree-like data structure used to store a dynamic set of strings. It is commonly used for efficient searches and autocomplete features.
Your task is to complete the impleme... | ```java
import java.util.HashMap;
import java.util.Map;
abstract class TrieNode {
Map<Character, TrieNode> children;
boolean isEndOfWord;
public TrieNode() {
children = new HashMap<>();
isEndOfWord = false;
}
}
class Trie {
private TrieNode root;
public Trie() {
root ... | magicoder | java |
You are tasked with implementing a generic interface for managing the state of an object. The interface consists of two methods: `WriteState` and `ReadState`. The `WriteState` method is responsible for capturing the current state of an object and returning it, while the `ReadState` method is responsible for restoring t... | ```csharp
using System;
// Define the generic interface for managing state
interface IStateManagement<T>
{
T WriteState();
void ReadState(T memento);
}
// Define the Car class implementing the IStateManagement interface
class Car : IStateManagement<CarMemento>
{
public string Make { get; set; }
public... | magicoder | csharp |
You are given a list of student scores in a class. The task is to write a Python function that finds the highest score in the class and its position in the list. Additionally, the function should also find the lowest score in the class.
The function should take a list of student scores as input and return a tuple cont... | ```python
from typing import List, Tuple
def find_highest_lowest_score(student_scores: List[int]) -> Tuple[int, int, int, int]:
max_score = max(student_scores)
max_index = student_scores.index(max_score)
min_score = min(student_scores)
min_index = student_scores.index(min_score)
return max_score, m... | magicoder | python |
You are tasked with implementing a simplified version of a communication interface using Python. The provided code snippet outlines a basic structure for reading and writing messages using a custom `visalib` library. Your task is to extend this interface by creating a class that manages multiple communication sessions ... | ```python
from typing import Dict, Tuple
import constants # Assuming constants module is available
class CommunicationInterface:
def __init__(self):
self.sessions: Dict[int, str] = {}
def open_session(self, session_id: int) -> None:
self.sessions[session_id] = ""
def close_session(self, ... | magicoder | python |
You are tasked with creating a program to simulate an ATM cash withdrawal process. The program should prompt the user to input the desired withdrawal amount in Brazilian Reais (R$) and then proceed to dispense the cash using the available denominations of banknotes. The available denominations are 100, 50, 20, 10, 5, a... | ```python
# Function to calculate and display the banknote breakdown
def dispense_cash(amount):
denominations = [100, 50, 20, 10, 5, 2]
banknotes_count = [0, 0, 0, 0, 0, 0]
for i in range(len(denominations)):
banknotes_count[i] = amount // denominations[i]
amount %= denominations[i]
pr... | magicoder | python |
You are working on a Python project that involves defining custom types using the `NewType` function from the `typing` module. Your task is to create a function that processes a list of elements and categorizes them based on their type. The custom types are defined as follows:
```python
MethodTerminal = NewType("Metho... | ```python
from typing import List, Dict
import xml.etree.ElementTree as ET
from typing import NewType
MethodTerminal = NewType("MethodTerminal", ET.Element)
WhileLoop = NewType("WhileLoop", ET.Element)
Terminal = NewType("Terminal", ET.Element)
PairedConfigurableMethodCall = NewType("PairedConfigurableMethodCall", ET.... | magicoder | python |
You are working on a music library management system, and you need to implement a feature to process and manipulate song metadata. The system uses a configuration file to determine various settings, such as whether to save certain metadata to the songs themselves. Additionally, the system allows users to rate songs and... | ```python
class RATINGS:
default = "default"
def process_song_metadata(comments, config, email, RATINGS):
if "coverartmime" in comments:
del comments["coverartmime"]
if config.getboolean("editing", "save_to_songs"):
email = email or const.EMAIL
rating = comments.get("~#rating", RAT... | magicoder | python |
You are tasked with implementing a simple translation script for a 3D game object in Unity. The script should allow the user to move the GameObject relative to the camera using touch input. The script should also provide options to ignore touch input over GUI elements and specify the required number of fingers for the ... | ```csharp
using UnityEngine;
public class LeanTranslate : MonoBehaviour
{
[Tooltip("Ignore fingers with StartedOverGui?")]
public bool IgnoreStartedOverGui = true;
[Tooltip("Ignore fingers with IsOverGui?")]
public bool IgnoreIsOverGui;
[Tooltip("Ignore fingers if the finger count doesn't match? ... | magicoder | csharp |
You are tasked with implementing a MouseProvider class that interfaces with the GLFW library to handle mouse input in a C++ application. The provided code snippet is the beginning of the constructor for the MouseProvider class, which takes a GLFWwindow pointer as a parameter.
Your task is to complete the implementatio... | ```cpp
namespace demofw
{
namespace glfw
{
class MouseProvider
{
public:
MouseProvider(GLFWwindow* window)
: mWindow(window)
{
// Initialize mouse state and register GLFW callbacks
glfwSetCursorPosCallback(window, handleMouseMoveCallback);
glfwSetMouseButtonCall... | magicoder | cpp |
You are tasked with designing a database schema for a simple social media platform. The platform has two main entities: users and posts. Each user can create multiple posts, and each post is associated with a single user. The database schema should be designed using SQLAlchemy, a popular Python ORM (Object-Relational M... | ```python
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
# Create the SQLAlchemy engine
engine = create_engine('sqlite:///:memory:', echo=True)
# Create a base class for declarative... | magicoder | python |
You are tasked with creating a program to process and display a list of books in a table format. Each book is represented by a data structure containing its title, price, release date, publisher, and author. Your program should be able to sort the books based on different criteria and display the sorted results in a ta... | ```python
def sort_books(books, criterion, ascending=True):
if criterion not in ["title", "price", "releaseDate", "publisher", "author"]:
raise ValueError("Invalid sorting criterion")
reverse = not ascending
sorted_books = sorted(books, key=lambda x: x[criterion], reverse=reverse)
return sorted... | magicoder | python |
You are tasked with implementing a Python class that encodes messages into Protocol Data Units (PDUs) using a specific encoding scheme. The class should support the following functionalities:
1. Initialization with an initial encoding state.
2. Encoding a given message into a PDU using the current encoding state.
3. Up... | ```python
from typing import NamedTuple
class EncodeState(NamedTuple):
# Assume that the EncodeState class is already implemented with the required methods and attributes
coded_message: str
class PduEncoder:
def __init__(self, initial_state: EncodeState):
self.encoding_state = initial_state
d... | magicoder | python |
You are working on a web application that uses Django for its backend. The application has a file named `urls.py` which contains the URL patterns for routing incoming requests to the appropriate views. The code snippet provided is a part of this `urls.py` file.
Your task is to write a function that takes the given lis... | ```python
import re
def extract_url_view_mapping(url_patterns):
url_view_mapping = {}
for pattern in url_patterns:
if isinstance(pattern, tuple):
# Handle patterns() function
sub_mapping = extract_url_view_mapping(pattern[0])
url_view_mapping.update(sub_mapping)
... | magicoder | python |
You are tasked with implementing a simple entity system in a JavaScript application. The entity system should allow the creation and management of entities and their associated records. An entity is a unique object within the system, and a record is a collection of key-value pairs associated with an entity. You are pro... | ```javascript
// Entity class represents a unique object within the system
class Entity {
constructor(id) {
this.id = id;
this.records = new Map();
}
associateRecord(record) {
this.records.set(record.key, record.value);
}
disassociateRecord(key) {
this.records.delete(key);
}
getRecords(... | magicoder | javascript |
You are tasked with implementing a function `untilUnchange` that takes in three parameters: `init`, `callback`, and `comparator`. The `init` parameter represents the initial value, `callback` is a function that will be repeatedly called with the current value, and `comparator` is an optional function used to compare th... | ```javascript
function* untilUnchange(init, callback, comparator = (a, b) => a === b) {
let previousValue = init;
let currentValue = callback(init);
yield currentValue;
while (!comparator(previousValue, currentValue)) {
previousValue = currentValue;
currentValue = callback(currentValue);
yield curr... | magicoder | javascript |
You are tasked with creating a password validation function for a web application. The function should take two password inputs and determine if they meet the specified criteria. The criteria for a valid password are as follows:
1. The password must be at least 8 characters long.
2. The password must contain at least o... | ```python
import re
def validatePassword(password1: str, password2: str) -> bool:
# Check if both passwords are at least 8 characters long
if len(password1) < 8 or len(password2) < 8:
return False
# Check if both passwords contain at least one uppercase letter, one lowercase letter, one digit,... | magicoder | python |
You are tasked with implementing a training loop for a machine learning model using the given code snippet as a reference. The code snippet initializes variables for training and optimization and sets initial values for tracking the best score and loss. Your task is to complete the training loop by incorporating the op... | ```python
for epoch in range(n_epochs):
# Training loop
for batch in train_dataloader:
# Forward pass
inputs, labels = batch
outputs = model(inputs)
loss = compute_loss(outputs, labels) # Replace with actual loss calculation
# Backward pass and optimization
loss... | magicoder | python |
You are tasked with creating a Python script that parses a given source code file and extracts the name and email of the author from the copyright notice. The copyright notice is in the format shown in the code snippet below:
```python
# Copyright and Distribution
#
# Part of SimplePyGA: Simple Genetic Algorithms in... | ```python
import re
def extract_author_info(file_path):
with open(file_path, 'r') as file:
content = file.read()
match = re.search(r'Copyright and Distribution.*\((.*?)\)', content, re.DOTALL)
if match:
author_info = match.group(1).split()
name = author_info[0]
... | magicoder | python |
You are tasked with implementing a loss function creation module for a neural network training system. The provided code snippet is a part of this module and demonstrates the creation of loss functions based on a configuration setting. Your task is to complete the implementation by adding support for the L2 loss functi... | ```python
from . import LossType
import torch.nn as nn
import yacs
def create_loss(config: yacs.config.CfgNode) -> nn.Module:
loss_name = config.train.loss
if loss_name == LossType.L1.name:
return nn.L1Loss(reduction='mean')
elif loss_name == LossType.L2.name:
return nn.MSELoss(reduction='m... | magicoder | python |
You are tasked with implementing a function to detect the name of a playing card using Optical Character Recognition (OCR). The function `find_card_name` takes two parameters: `im`, which represents the image of the playing card, and `debug`, a boolean flag indicating whether debug information should be printed.
Your ... | ```python
import pytesseract
from PIL import Image
def find_card_name(im, debug):
# Convert the image to grayscale
im_gray = im.convert('L')
# Use OCR to extract text from the grayscale image
card_name = pytesseract.image_to_string(im_gray)
if debug:
print("Detected Text:", card_name)
... | magicoder | python |
You are tasked with creating a function that processes scheduling data for a fitness center. The scheduling data is stored in a table named `schedules` with the following columns:
- `scid`: schedule ID
- `weekday`: day of the week (1 for Monday, 2 for Tuesday, and so on)
- `start_hour`: start time of the schedule
- `en... | ```sql
CREATE OR REPLACE FUNCTION generate_weekly_schedule() RETURNS JSON AS $$
BEGIN
RETURN (
SELECT json_build_object(
'Monday', COALESCE(json_agg(
CASE
WHEN schedules.weekday <> 1 THEN NULL::json
ELSE json_build_object('schedule_id', sch... | magicoder | sql |
You are tasked with creating a Python function to automate the process of connecting an ESP8266 microcontroller to a Wi-Fi network and sending a tweet using the ThingSpeak API. The ESP8266 is already programmed to execute the provided code snippet, which includes a function `ConnectWIFI` to connect to a Wi-Fi network a... | ```python
import urequests
def ConnectWIFI(ssid, password):
# Implement the logic to connect ESP8266 to the specified Wi-Fi network
# Example: This could involve using the ESP8266's micropython library to establish a Wi-Fi connection
# Example: esp8266.connect(ssid, password)
def SendTweet():
api_key ... | magicoder | python |
You are tasked with implementing a program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Each account should have a unique account number, and the program should be able to handle multiple accounts.
Your task is to implem... | ```java
import java.util.HashMap;
class BankAccount {
private int accountNumber;
private double balance;
private static int nextAccountNumber = 1;
public BankAccount() {
this.accountNumber = createAccount();
this.balance = 0.0;
}
private static int createAccount() {
r... | magicoder | java |
You are given a list of integers `A`. Your task is to write a function that calculates a specific value based on the binary representation of the integers in `A`.
You need to implement a function `calculate_value(A)` that takes in a list of integers `A` and returns an integer value based on the following rules:
1. Con... | ```python
import collections
def calculate_value(A):
tmp = [bin(a)[2:].zfill(16) for a in A] # Convert each integer to its binary representation
one = {} # Dictionary to store the positions of '1's in each bit position
# Count the occurrences of '1' in each bit position
for i, a in enumerate(zip... | magicoder | python |
You are tasked with creating a script to automate the installation of a new kernel on a Linux system. The script should copy various kernel-related files to a designated boot directory and then display a message indicating the successful installation of the new kernel.
The script should perform the following actions:
... | ```bash
#!/bin/bash
# Define the boot directory and kernel version
BOOT="/boot"
VER="5.4.0"
# Copy kernel-related files to the boot directory
cp -v arch/x86_64/boot/bzImage $BOOT/vmlinuz-$VER
cp -v System.map $BOOT/System.map-$VER
cp -v vmlinux $BOOT/vmlinux-$VER
cp -v .config $BOOT/config-$VER
cp -v Module.symvers $... | magicoder | shell |
You are tasked with implementing a function that will flatten a multidimensional array into a single-dimensional array. The input array can contain nested arrays of arbitrary depth, and the output should be a flattened array with all the elements from the input array.
You need to implement the following function:
```... | ```php
function flattenArray($inputArray) {
$outputArray = array();
foreach ($inputArray as $element) {
if (is_array($element)) {
$outputArray = array_merge($outputArray, flattenArray($element));
} else {
$outputArray[] = $element;
}
}
return $outputArray;... | magicoder | php |
You are tasked with implementing a Python class that generates a minimum spanning tree (MST) using the Kruskal algorithm. The Kruskal algorithm is a greedy algorithm that finds a minimum spanning tree for a connected weighted graph. The class should take a graph represented as a list of edges and their weights, and ret... | ```python
class GenerateBasedKruskalRST:
def __init__(self, stpg):
self.stpg = stpg
self.parent = {}
self.rank = {}
def find(self, vertex):
if self.parent[vertex] != vertex:
self.parent[vertex] = self.find(self.parent[vertex])
return self.parent[vertex]
... | magicoder | python |
You are working on a graphics rendering engine, and you need to implement a function to manage a buffer for storing indices of vertices for rendering 3D models. The buffer will be used to store unsigned integers representing the indices of vertices in the vertex buffer. You are given the following code snippet as a sta... | ```cpp
#include <vector>
class IndicesBufferManager {
private:
std::vector<unsigned> indicesBuffer;
public:
// Method to initialize the indices buffer with a specified size
void initializeBuffer(size_t size) {
indicesBuffer.resize(size);
}
// Method to add an index to the buffer
void ... | magicoder | cpp |
You are tasked with implementing a function that processes a SQL query template and a set of parameter values to generate a valid SQL query. The SQL query template is a string that may contain placeholders for parameter values. Each placeholder is represented by a specific syntax, and the function should replace these ... | ```csharp
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class SQLQueryProcessor
{
public string ProcessSQLQueryTemplate(string queryTemplate, Dictionary<string, object> parameterValues)
{
foreach (var parameter in parameterValues)
{
str... | magicoder | csharp |
You are tasked with implementing a Python class that interacts with an external API using a private key and a consumer key. The class should handle the authentication process and provide methods for making requests to the API.
Your task is to complete the implementation of the `PrivateApp` class, which should have the... | ```python
import os
import requests
class PrivateApp:
def __init__(self, private_key, consumer_key):
if 'CONSUMER_KEY' not in os.environ:
raise EnvironmentError('Environment variable CONSUMER_KEY not found.')
self.private_key = private_key
self.consumer_key = os.environ['CONSUME... | magicoder | python |
You are tasked with implementing a binary classification model evaluation using the AUROC (Area Under the Receiver Operating Characteristic) metric. The given code snippet is part of a larger program that prepares data for AUROC calculation. The code snippet uses the NumPy library to manipulate arrays and concatenate t... | ```python
import numpy as np
from sklearn import metrics
# Assuming val_out and val_label are given arrays
# Calculate AUROC
auroc = metrics.roc_auc_score(val_label, val_out)
print(f'AUROC: {auroc}')
```
In the solution, we use the `roc_auc_score` function from the `sklearn.metrics` module to calculate the AUROC met... | magicoder | python |
You are tasked with implementing a property processing trait for a feature in a software system. The trait, `PropertyProcessor`, is responsible for processing property values associated with a feature. The trait has a single method, `property`, which takes in the index of the property, the name of the property, and the... | ```rust
use std::result;
// Define a custom error type for property processing
#[derive(Debug)]
struct PropertyProcessingError;
// Define the result type for property processing
type PropertyProcessingResult<T> = result::Result<T, PropertyProcessingError>;
// Define a struct for the specific feature implementing the... | magicoder | rust |
You are tasked with creating a function to verify the correctness of a given email address. The function should check if the email address is in a valid format and if the domain of the email exists. For the purpose of this problem, assume that the email address is in the format "username@domain.com".
Create a function... | ```python
import re
def verifyEmail(email):
# Check if the email address is in a valid format
if re.match(r"[^@]+@[^@]+\.[^@]+", email):
# Extract the domain from the email address
domain = email.split('@')[1]
# Verify if the domain exists using DNS resolution
return resolveDNS(... | magicoder | python |
You are tasked with creating a command-line interface (CLI) for a software tool. The CLI should support various options, each with its own default value and description. Your task is to implement a function that generates a help message for the CLI based on the provided options.
You are given a dictionary `options` co... | ```python
import os
def generate_help_message(options):
help_message = "Options:\n"
for option, details in options.items():
help_message += f"- {option}: {details['help']} Default: {details['def']}\n"
return help_message
``` | magicoder | python |
You are tasked with implementing a class that reads and processes motion data from a file. The file contains a series of binary data representing motion parameters for a 3D object. Your task is to create a class `MotionDataReader` with the following specifications:
- The class should have the following instance variab... | ```python
class MotionDataReader:
def __init__(self):
self.m_X = None
self.m_Type = 0
self.m_XMotionType = 0
self.m_YMotionType = 0
self.m_ZMotionType = 0
self.m_MinLimitX = 0.0
self.m_MaxLimitX = 0.0
self.m_MaxLimitY = 0.0
self.m_MaxLimitZ = 0... | magicoder | python |
You are tasked with implementing a type trait in C++ that checks if a given type is convertible to an integer type. Your goal is to create a metafunction that takes a type as a template parameter and evaluates to `true` if the type is convertible to an integer, and `false` otherwise.
Your task is to complete the imple... | ```cpp
#include <type_traits>
#include <boost/type_traits.hpp>
template <typename T>
struct is_convertible_to_int : boost::mpl::and_<
boost::mpl::not_<std::is_same<T, bool>>,
boost::mpl::not_<std::is_same<T, char>>,
boost::mpl::not_<std::is_same<T, unsigned char>>,
boost::mpl::not_<std::is_same<T, sign... | magicoder | cpp |
You are tasked with implementing a custom image processing pipeline using the `mmdet` library in Python. The pipeline will involve padding an input image and then applying a filter to it. You are provided with a code snippet that imports necessary modules and defines a function `test_pad()`.
Your task is to complete t... | ```python
from mmdet.datasets.pipelines.transforms import Pad, FilterBox
import numpy as np
import cv2
def test_pad():
raw = dict(
img=np.zeros((200, 401, 3), dtype=np.uint8)
)
# Pad the input image
pad_transform = Pad(size_divisor=32) # Example padding size divisor
padded_img = pad_trans... | magicoder | python |
You are tasked with implementing a function that will parse and extract specific information from an HTML file. The HTML file contains a script tag with JavaScript code inside it. Your goal is to extract the JavaScript code and count the occurrences of specific keywords within it.
You are given an HTML file `index.htm... | ```javascript
const fs = require('fs');
const cheerio = require('cheerio');
function countKeywordsInScript(filename, keywords) {
const htmlContent = fs.readFileSync(filename, 'utf8');
const $ = cheerio.load(htmlContent);
const scriptContent = $('script').text();
const keywordCounts = {};
keywords.... | magicoder | javascript |
You are tasked with implementing a function to perform image manipulation using the CodeIgniter framework's image library. The function should take in the original image path, target width, and target height as parameters, and then perform the following operations:
1. Calculate the x-axis position for cropping the ima... | ```php
/**
* Perform image manipulation using CodeIgniter image library.
*
* @param string $originalPath The original path of the image file.
* @param int $targetWidth The target width for the image.
* @param int $targetHeight The target height for the image.
* @return string The new path of the manipulated image... | magicoder | php |
You are tasked with implementing a drag-and-drop functionality for a list view in a web application. The application is written in Java and uses Elemental2, a library that provides Java bindings for the Web API. The drag-and-drop functionality should allow users to reorder items in the list view by dragging and droppin... | ```java
package org.kie.workbench.common.dmn.client.editors.types.listview.draganddrop;
import elemental2.dom.DataTransfer;
import elemental2.dom.Event;
import elemental2.dom.EventListener;
import elemental2.dom.EventTarget;
import elemental2.dom.HTMLDivElement;
import elemental2.dom.Node;
import jsinterop.base.Js;
p... | magicoder | java |
You are tasked with implementing a peer-to-peer networking protocol in Rust. The protocol involves decoding XOR-PEER-ADDRESS from a message using the `Getter` trait for the `PeerAddress` type. The `PeerAddress` type represents the address of a peer in the network, and the `Message` type represents a message sent over t... | ```rust
// Example types for reference
struct PeerAddress {
// Define the fields for the peer address
}
struct Message {
// Define the fields for the message
}
// Example error type for reference
enum Error {
// Define potential error variants
}
trait Getter {
fn get_from(&mut self, m: &Message) -> R... | magicoder | rust |
You are tasked with creating a program that simulates a simple banking system. The system should be able to handle basic banking operations such as account creation, deposit, withdrawal, and balance inquiry. The program should also be able to handle multiple accounts and ensure the security of the banking operations.
... | ```javascript
class BankAccount {
static nextAccountNumber = 1001;
#accountNumber;
#customerName;
#balance;
constructor(customerName) {
this.#accountNumber = BankAccount.nextAccountNumber++;
this.#customerName = customerName;
this.#balance = 0;
}
deposit(amount) {
this.#balance += amount... | magicoder | javascript |
You are tasked with creating a program that simulates a simple dice rolling game. The game should allow a player to roll a standard six-sided die and keep track of their total score. The game should continue until the player decides to stop or until they roll a 1, at which point their current score is lost. The program... | ```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int rollDie() {
return rand() % 6 + 1;
}
int rollDiceGame() {
int totalScore = 0;
int roll;
srand(time(NULL));
do {
roll = rollDie();
printf("Roll: %d, Total score: %d\n", roll, totalScore + roll);
if (roll == 1... | magicoder | c |
You are tasked with implementing a key derivation function for the ANSI X9.24 version 2009 Derived Unique Key Per Transaction (DUKPT) algorithm. DUKPT is a method for deriving a unique encryption key for each transaction, ensuring that the derived keys are not mathematically related to each other. The algorithm is comm... | ```java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
public class DUKPTKeyDerivation {
public static byte[] deriveKey(byte[] bdk, byte[] ksn) {
try {
byte[] ksnLeft = Arrays.copyOf(ksn, 8);
byte[] ksnRig... | magicoder | java |
You are tasked with implementing a function to adjust the contrast of an image. The function should take an input image as a numpy array and a contrast level as a scalar in the range [0, 1]. The function should then return the image scaled to the specified contrast level.
The function signature should be:
```python
de... | ```python
import numpy as np
def adjust_contrast(image, contrast_level):
"""
Return the image scaled to a certain contrast level in [0, 1].
Parameters:
- image: a numpy.ndarray representing the input image
- contrast_level: a scalar in [0, 1]; with 1 -> full contrast
Returns:
- numpy.ndar... | magicoder | python |
You are tasked with implementing a text truncation function that takes a string of HTML content and converts it to plain text, while ensuring that the resulting text does not exceed a certain length. You are given a code snippet that partially implements this functionality.
The `lead` method is part of a class and is ... | ```python
def lead(self):
text = html_to_text(self.description)
if len(text) > 160:
return text[:160] + '…'
else:
return text
```
The solution completes the `lead` method by returning the truncated plain text if its length exceeds 160 characters, followed by an ellipsis. If the length is 16... | magicoder | python |
You are tasked with creating a function that identifies and returns a list of empty folders within a given root directory. The function should iterate through the contents of the root directory, check for empty sub-folders, and retrieve the project IDs under each folder. If a folder is found to be empty and does not co... | ```python
def find_empty_folders(root_content, folders_service, projects_service, root_folder, EXCLUDE_EMPTY_FOLDER):
empty_folders = []
for folder in root_content:
no_sub_folders = folders_service.is_folder_empty(folder)
sub_projects = projects_service.get_projectIds_under_folder(folder)
... | magicoder | python |
You are working on a project that involves analyzing the correlation function of matter density fluctuations in the universe. You have come across a code snippet that uses the `cluster_toolkit` library to calculate the two-point correlation function, ξ(r), using the Davis & Peebles approximation (DK app1). The code sni... | ```python
import numpy as np
import cluster_toolkit
def calculate_halo_matter_correlation(r, M, rhos, conc, be, se, alpha, beta, gamma, delta, k, P, om, bias):
xi = np.zeros_like(r)
cluster_toolkit._lib.calc_xi_DK_app1(r.cast(), len(r), M, rhos, conc, be, se, alpha, beta, gamma, delta, k.cast(), P.cast(), len(... | magicoder | python |
You are tasked with implementing a function that converts a given integer into its English word representation. For example, the integer 123 would be converted to "one hundred twenty three". The function should support integers within the range of 0 to 999,999,999,999 (inclusive).
Your task is to implement the `int_to... | ```python
def int_to_english(n):
if n == 0:
return "zero"
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
teens = ["", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["", "ten", "twenty", "thirty"... | magicoder | python |
You are tasked with creating a program that generates a random string of consonants and spaces. The program should take the width of the terminal window into account and ensure that the generated string fits within the available space. If the terminal width is not available, the program should handle this scenario grac... | ```rust
use rand::{thread_rng, Rng};
use std::{thread, time};
use term_size;
fn generate_consonant_string() -> Result<String, String> {
let mut width = 0;
if let Some((w, _)) = term_size::dimensions() {
width = w;
} else {
return Err(String::from("Unable to get term size :("));
}
l... | magicoder | rust |
You are tasked with implementing a moving average calculator. Given a stream of integers and a window size, your goal is to calculate the moving average for each window of the specified size as the stream progresses.
Write a function `calculate_moving_average` that takes in two parameters:
- `stream` (list of integer... | ```python
def calculate_moving_average(stream, window_size):
if window_size > len(stream):
return []
moving_averages = []
window_sum = sum(stream[:window_size])
moving_averages.append(window_sum / window_size)
for i in range(window_size, len(stream)):
window_sum = window_sum - stre... | magicoder | python |
You are given a string `inputString` containing a series of words separated by spaces. Your task is to implement a function `reverseWords` that reverses the order of the words in the string while preserving the individual word order within each word. For example, if the input string is "hello world", the output should ... | ```java
public String reverseWords(String inputString) {
String[] words = inputString.split(" "); // Split the input string into individual words
StringBuilder reversedString = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversedString.append(words[i]); // Append each word in... | magicoder | java |
You are tasked with creating a Python class that handles HTTP requests and validates URL parameters. Your class should have a method to check the URL parameters and return a boolean indicating whether the parameters are valid. If the parameters are invalid, the class should set the HTTP status code to 400 and print an ... | ```python
class HTTPRequestHandler:
def get_url_params(self):
# Assume the URL parameters are obtained from the request and returned as a dictionary
return {'param1': 'value1', 'param2': 'value2'}
def check_url_params(self, http_params):
# Assume the validation logic for URL parameters
... | magicoder | python |
You are tasked with implementing a custom deserialization process for a Rust struct called `DcName`. The `DcName` struct represents a domain controller name and has a predefined set of valid values. Your goal is to create a custom deserializer for this struct using the Serde library in Rust.
The `DcName` struct is def... | ```rust
use serde::{Deserialize, Deserializer, de::{Visitor, Error}};
use std::fmt;
#[derive(Debug)]
struct DcName(String);
impl DcName {
fn values() -> Vec<&'static str> {
vec!["dc1", "dc2", "dc3"]
}
}
impl<'de> Deserialize<'de> for DcName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::... | magicoder | rust |
You are tasked with creating a program to calculate the expected offspring of a population displaying different genotypes. In this problem, you are given the number of offspring produced by each genotype pair and the probabilities of producing offspring with specific genotypes. Your task is to write a function to calcu... | ```python
def calculate_expected_offspring(offsprings, AA_AA, AA_Aa, AA_aa, Aa_Aa, Aa_aa, aa_aa):
allel_prob = [1, 1, 1, 0.75, 0.5, 0]
expected_offspring = sum([offsprings * prob for offsprings, prob in zip([AA_AA, AA_Aa, AA_aa, Aa_Aa, Aa_aa, aa_aa], allel_prob)])
return expected_offspring
```
The `calcula... | magicoder | python |
You are tasked with implementing a function that calculates the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your function should take two integers, `start` and `end`, as input and return the sum of all prime numb... | ```python
def is_prime(num: int) -> bool:
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def sum_of_primes(start: int, end: int) -> int:
prime_sum = 0
for num in range(max(2, start), end + 1):
if is_prim... | magicoder | python |
You are tasked with implementing a simplified version of a queue data structure using JavaScript. The queue should support the following operations:
1. `enqueue(value)`: Add a new element to the end of the queue.
2. `dequeue()`: Remove and return the element at the front of the queue.
3. `peek()`: Return the element a... | ```javascript
class Queue {
constructor() {
this.elements = [];
}
enqueue(value) {
this.elements.push(value);
}
dequeue() {
if (this.isEmpty()) {
return [new Error('Queue is empty'), null];
}
return [null, this.elements.shift()];
}
peek(... | magicoder | javascript |
You are tasked with implementing a function `get_tests_results(question)` that takes in a string `question` representing a multiple-choice question and returns a dictionary containing the test results. The input string `question` will consist of the question followed by a list of answers, each marked with a letter (A, ... | ```python
def get_tests_results(question):
answers = question.split("?")[1].strip().split(",") # Extracting the answers from the question
results = {answer.split(")")[0].strip(): 0 for answer in answers} # Creating a dictionary with answers as keys and initial count as 0
for answer in answers:
if... | magicoder | python |
You are tasked with implementing a memory allocation function similar to `realloc` in C. The function, named `__realloc`, takes a pointer to a memory block and a new size as its arguments. The function should resize the memory block to the new size if possible, and return a pointer to the resized memory block. However,... | ```c
#include <stdlib.h>
#include <string.h>
#include <assert.h>
void* __realloc(void* ptr, size_t new_size) {
if (new_size <= 16) {
return realloc(ptr, new_size);
} else if (new_size <= 48) {
void* originalPtr = ptr;
ptr = realloc(ptr, 48); // Attempt to grow to maximum allowed size
... | magicoder | c |
You are tasked with implementing a statistics library in C++ to calculate various statistical measures for a given dataset. Your goal is to implement the `variance` function in the `statistics` namespace, which takes a vector of numbers as input and returns the variance of the dataset. The variance of a dataset is a me... | ```cpp
#include <iostream>
#include <vector>
#include <cmath>
namespace statistics {
double mean(const std::vector<double>& data) {
double sum = 0.0;
for (const auto& value : data) {
sum += value;
}
return sum / data.size();
}
double variance(const std::vector<d... | magicoder | cpp |
You are tasked with implementing a Python function that simulates a simplified version of a neural network training process. The function will take in a list of training data and perform a series of training steps using a specified training algorithm. The training process involves iterating through the training data in... | ```python
def train_neural_network(training_data, train_steps, save_period, model_checkpoint_path, session, train_step_op, input_placeholder, output_placeholder, keep_prob_placeholder, accuracy_op):
import numpy as np
batch_size = 64
num_batches = len(training_data) // batch_size
saver = tf.train.Saver(... | magicoder | python |
You are tasked with creating a script to manage Docker containers. Your script should include two functions: `ct_docker_stop_all` and `ct_docker_rm_all`. The `ct_docker_stop_all` function should stop all running Docker containers, while the `ct_docker_rm_all` function should remove all Docker containers, whether runnin... | ```bash
#!/bin/bash
# Function to stop all running Docker containers
ct_docker_stop_all(){
docker stop $(docker ps -q)
}
# Function to remove all Docker containers
ct_docker_rm_all(){
docker rm $(docker ps -aq)
}
# Demonstrate the usage of the functions
echo "Stopping all running Docker containers..."
ct_doc... | magicoder | shell |
You are tasked with creating a Python function that calculates the average of a list of numbers. Your function should take a list of numbers as input and return the average as a floating-point number. You should also write unit tests using the `pytest` framework to ensure the correctness of your function.
Your functio... | ```python
def calculate_average(numbers: list) -> float:
if not numbers:
return 0.0 # Return 0 if the list is empty to avoid division by zero
return sum(numbers) / len(numbers)
# Unit tests using pytest
import pytest
def test_calculate_average_empty_list():
assert calculate_average([]) == 0.0
de... | magicoder | python |
You are tasked with implementing a simple item management system using React and Redux. The provided code snippet contains a part of a React component and Redux integration. Your goal is to complete the implementation by defining the missing functions and components.
You are given the following information:
- The `Ite... | ```javascript
// ItemCreator function to render individual items
const ItemCreator = (item) => {
return <li key={item.id}>{item.name}</li>;
};
// updateItem function to handle the update of an item
const updateItem = (itemId, updatedData) => {
// Implement the logic to update the item in the Redux store
};
// map... | magicoder | javascript |
You are tasked with implementing a MathML (Mathematical Markup Language) parser in C#. MathML is a markup language used to display mathematical expressions on web pages. Your task is to create a class that can parse a given MathML expression and perform specific operations on it.
You are given a code snippet that crea... | ```csharp
public class MathMLIdentifier
{
public List<MathMLNode> Children { get; } = new List<MathMLNode>();
}
public class MathMLTextNode : MathMLNode
{
public string Text { get; }
public MathMLTextNode(string text)
{
Text = text;
}
}
public abstract class MathMLNode
{
public List<M... | magicoder | csharp |
You are tasked with implementing a simple event handling system for different types of advertisements in a mobile application. The system should allow for registering event listeners and dispatching events when certain actions occur.
You are provided with the following interface declarations:
```java
interface AdList... | ```java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class AdManager {
private Map<Integer, Set<AdListener>> adListenersMap;
private Set<FacebookAdListener> facebookAdListeners;
public AdManager() {
adListenersMap = new HashMap<>();
facebo... | magicoder | java |
You are tasked with creating a command-line tool for selecting users from a list of available options. The tool should provide auto-completion for user names and allow the selection of multiple users. The user names should be displayed in a specific format, and the tool should prompt the user to review and validate the... | ```python
from typing import List
import prompt_toolkit
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit import prompt
import models # Assuming the existence of a 'models' module with a 'User' class
class UserCompleter(Completer):
def __init__(self, users: List[models.User]):
... | magicoder | python |
You are tasked with creating a function that processes currency conversion and validation for an e-commerce platform. The function should take in the order details and perform the following tasks:
1. Retrieve the currency details from the database using the provided currency code.
2. Check if the currency is not "BDT" ... | ```php
function processOrderCurrency($order) {
$curr = Currency::where('name', '=', $order->currency_code)->first();
// Check if the currency is not "BDT"
if ($curr->name != "BDT") {
return redirect()->back()->with('unsuccess', 'Please Select BDT Currency For Sslcommerz.');
}
// Retrieve g... | magicoder | php |
You are tasked with implementing a custom class in Python that inherits from a parent class and overrides its constructor method. Your task is to create a subclass called `CustomEmbed` that inherits from the `ContextualEmbedV2` class and overrides its constructor method. The `ContextualEmbedV2` class is not provided, b... | ```python
class CustomEmbed(ContextualEmbedV2):
def __init__(self, *args, **kwargs):
super(CustomEmbed, self).__init__(*args, **kwargs)
self.custom_param = args[0] # Assuming the first parameter is used to initialize custom_param
```
In this solution, the `CustomEmbed` class is defined as a subclas... | magicoder | python |
You are working on a project to optimize a numerical computation library using the Numba library for just-in-time compilation. As part of this project, you need to implement a function that performs a left geometric matrix multiplication (GMT) using Numba. The left GMT operation involves multiplying a multivector by a ... | ```python
import numba
import numpy as np
@numba.njit
def numba_left_gmt_matrix(x, k_list, l_list, m_list, mult_table_vals, ndims):
result = np.zeros_like(x)
m = len(k_list)
n = len(x)
for i in range(m):
k = k_list[i]
l = l_list[i]
m = m_list[i]
for j in range(n):
... | magicoder | python |
You are tasked with implementing a custom dependency injection container in Java. The container should support registering and resolving beans by their type. You need to implement the `SimpleBeanContainer` class, which should have the following functionalities:
1. Registering beans: The container should allow registeri... | ```java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SimpleBeanContainer {
private Map<Class<?>, List<?>> candidatesByType;
public SimpleBeanContainer() {
this.candidatesByType = new HashMap<>();
}
// Register a bean of a specific type
public <T> voi... | magicoder | java |
You are tasked with creating a command for a Discord bot that handles unbanning users from a server. The code snippet provided is a part of the configuration for the command. The `description` field specifies the purpose of the command parameter, and the `required` field indicates whether the parameter is mandatory. Ad... | ```javascript
function unbanUser(userToUnban, executingUserPermissions) {
const requiredPermissions = ["MANAGE_GUILD"];
if (executingUserPermissions.includes("MANAGE_GUILD")) {
// Unban the user
// Example: discordClient.guilds.get('yourGuildId').members.unban(userToUnban);
return `${userToUnban} has b... | magicoder | javascript |
You are tasked with implementing a simple dependency injection container in C#. A dependency injection container is a design pattern used to manage the dependencies of objects. The provided code snippet is a simplified version of a dependency injection container. The `Container` class has a private constructor and a pu... | ```csharp
using System;
using System.Collections.Generic;
public class Container
{
private static Container _instance;
private Dictionary<string, object> _registry;
public static Container Instance
{
get
{
if (_instance == null)
_instance = new Container();
... | magicoder | csharp |
You are tasked with creating a C# program that utilizes asynchronous programming to perform parallel tasks. Your program should use the `System.Threading.Tasks` namespace to demonstrate the parallel execution of multiple asynchronous operations. Specifically, you need to create a program that fetches data from two diff... | ```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string apiUrl1 = "https://api.example.com/data1";
string apiUrl2 = "https://api.example.com/data2";
Task<string> fetchDataTask1 = FetchDataAsync(apiUrl1)... | magicoder | csharp |
You are tasked with creating a script to manage Docker containers. Your script should be able to run a container with a specified tag and a specific command. The command should be executed in the container upon creation. Your task is to write a Bash script that accomplishes this.
Your script should accept two paramete... | ```bash
#!/bin/bash
# Check if the required parameters are provided
if [ $# -ne 2 ]; then
echo "Usage: $0 <tag> <command>"
exit 1
fi
TAG=$1
COMMAND=$2
# Run the Docker container with the specified tag and execute the command
CONTAINER=$(docker run -d ${TAG} ${COMMAND})
# Check if the container was created s... | magicoder | shell |
You are tasked with implementing a server reboot scheduler in Python. Your goal is to create a function that schedules a server reboot at a specified time. The function should handle the scheduling logic and initiate the reboot process at the designated time.
You are provided with a code snippet that includes a partia... | ```python
import time
import threading
import logging
# Logger setup
console_log = logging.getLogger('console')
console_log.setLevel(logging.INFO)
console_log.addHandler(logging.StreamHandler())
def reboot_server(at_time="now"):
def _reboot():
console_log.info("Initiating server reboot per manager request... | magicoder | python |
You are tasked with creating a Python program that utilizes the Streamlit library to build a web application for image processing. The program should allow users to upload an image, apply a specified image processing technique, and display the processed image on the web interface. The image processing technique to be i... | The provided Python program creates a web application using the Streamlit library for image processing and fetching the number of stars for a specified GitHub repository. The program defines a function `get_github_stars` to fetch the stars count using the GitHub API. The main function `main` sets up the Streamlit web a... | magicoder | python |
You are given a list of intervals, where each interval is represented by a pair of integers [start, end]. The intervals may overlap, and you need to find the minimum number of intervals needed to cover all the intervals.
Write a function `min_intervals` that takes a list of intervals as input and returns the minimum n... | ```python
from typing import List
def min_intervals(intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: x[1]) # Sort intervals based on end points
count = 1 # Initialize count to 1 for the first interval
end = intervals[0][1] # Initialize end to the end point of the first interval
for ... | magicoder | python |
You are tasked with creating a Python function that generates a unique temporary directory path for analysis. The function should ensure that the directory path does not already exist and then return the path.
Write a Python function `generate_unique_temp_path()` that accomplishes the following:
- It takes no input pa... | ```python
import os
import tempfile
def generate_unique_temp_path():
# Generate a temporary directory path
path_analysis_temp = tempfile.mkdtemp()
# Ensure that the directory path does not already exist
while os.path.exists(path_analysis_temp):
path_analysis_temp = tempfile.mkdtemp()
# Re... | magicoder | python |
You are working on a file management system for a database application. Your task is to write a Python script that will remove all the database files with a specific pattern in their filenames from a given directory.
Write a Python function called `remove_database_files` that takes two parameters:
1. `directory_path` ... | ```python
import os
import glob
def remove_database_files(directory_path, file_pattern):
file_list = glob.glob(os.path.join(directory_path, file_pattern))
for file in file_list:
os.remove(file)
return len(file_list)
# Test the function
directory_path = '/home/user/support/db/'
file_pattern = 'ftdb... | magicoder | python |
You are tasked with creating a Python class that normalizes email addresses using a mixin class. The mixin class, `NormalizeEmailSerializerMixin`, provides functionality to normalize email addresses. Your task is to create a new class, `EmailProcessor`, that inherits from the mixin class and adds additional functionali... | ```python
from .normalize_email_mixin import NormalizeEmailSerializerMixin
class EmailProcessor(NormalizeEmailSerializerMixin):
def __init__(self, email_list):
super().__init__()
self.email_list = email_list
def normalize_emails(self):
self.email_list = [self.normalize_email(email) for... | magicoder | python |
You are tasked with creating a Python function that simulates the process of exporting a frozen protobuf file from a TensorFlow detection model. The function should take no arguments and should utilize TensorFlow to build the detection graph, restore the weights from a specified checkpoint file, and then export the fro... | ```python
import tensorflow as tf
# Function to build the detection graph
def build_detection_graph():
# Implement the logic to build the detection graph
pass
# Path to the checkpoint file
CKPT_PATH = "path_to_checkpoint_file.ckpt"
def export_frozenPB():
tf.reset_default_graph()
# Build the detectio... | magicoder | python |
You are tasked with creating a program that generates a set of icons in various sizes from a given source image. The program should take an input image file and produce a set of icons in different sizes, following the standard naming conventions for different resolutions and sizes. The naming convention for the icons s... | ```python
import os
import subprocess
def generate_icons(input_image):
icon_sizes = [16, 32, 64, 128, 256, 512]
output_directory = "MyIcon.iconset"
if not os.path.exists(output_directory):
os.mkdir(output_directory)
for size in icon_sizes:
subprocess.run(["sips", "-z", str(siz... | magicoder | python |
You are tasked with creating a program that manages different sources of contact details for a company. The program should be able to handle contact details from various systems and provide a unified interface for accessing and manipulating this data.
You are provided with a code snippet from the existing system, whic... | To solve this problem, you can create an abstract class `ContactDetailsManager` that serves as the base for managing contact details from different source systems. This abstract class can define common methods for adding, retrieving, updating, and deleting contact information.
```csharp
public abstract class ContactDe... | magicoder | csharp |
You are tasked with implementing a simple automatic differentiation framework for tensors in Python. Your goal is to create a class `Tensor` that supports basic operations and automatic computation of gradients using the backpropagation algorithm.
You need to implement the following functionalities for the `Tensor` cl... | ```python
class Tensor:
def __init__(self, data, requires_grad=False):
self.data = data
self.requires_grad = requires_grad
self.grad = None
def sum(self):
return sum(self.data)
def backward(self, gradient):
if self.requires_grad:
self.grad = gradient
``` | magicoder | python |
You are tasked with creating a Python class method that generates b-reference codes for a given sports league, season, and date to crawl data from a website. The method should construct the b-reference codes for both regular season and post-season games for the specified league, season, and date.
The class has the fol... | ```python
class BReferenceCodeGenerator:
LEAGUES_TO_PATH = {
'nba': 'https://www.example.com/{0}/games/'
}
def __init__(self, league, season, date):
self.league = league
self.season = season
self.date = date
self.reg_s_codes_ = []
self.post_s_codes_ = []
... | magicoder | python |
You are working with a dataset containing daily information about a school year. The dataset is represented as a pandas DataFrame `df` with columns including "date" and other relevant data. The code snippet provided is a part of a data manipulation process. The snippet sets the "date" column as the index of the DataFra... | ```python
import pandas as pd
def get_school_year_extremes(df: pd.DataFrame) -> pd.DataFrame:
# Sort the DataFrame by date
df = df.sort_index()
# Get the first and last 4 days of the school year
first_days = df.head(4)
last_days = df.tail(4)
# Concatenate the first and last days into a new Da... | magicoder | python |
You are tasked with implementing a file path exclusion algorithm. Given a list of file paths and a list of exclusions, your goal is to exclude specific paths based on the provided exclusion list. The exclusion process involves removing any file paths that match the exclusion patterns.
You are to write a function `excl... | ```python
def excludePaths(file_paths, exclusions):
excluded_paths = []
for path in file_paths:
excluded = False
for exclusion in exclusions:
if exclusion in path:
excluded = True
break
if not excluded:
excluded_paths.append(path)
... | magicoder | python |
You are tasked with implementing a Python class for building convolutional neural network (CNN) models. The class should inherit from the `CnnModel` class and have the ability to construct a model using specific layers and activation functions. Your task is to complete the implementation of the `VEGGG` class by adding ... | ```python
class VEGGG(CnnModel):
def __init__(self, model_name):
super().__init__()
self.MODEL_NAME = model_name
def build_model(self):
layers = BasicLayers(relu_version='parametric')
input_tensor = Input(shape=self.INPUT_SHAPE)
x = input_tensor
# Add convoluti... | magicoder | python |
You are tasked with creating a Python class that parses a website to extract information about cities and their operating hours for a directory listing. Your task is to implement the `CityParser` class with the following requirements:
1. The `CityParser` class should have a method `parse` that takes a `response` objec... | ```python
import scrapy
class CityParser:
def parse(self, response):
paths = [response.urljoin(x.xpath("@href").extract_first()) for x in
response.css(".c-directory-list-content-item-link")]
for path in paths:
yield scrapy.Request(url=path, callback=self.parse_cities)
... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple bank account. The class should have methods for depositing funds, withdrawing funds, and checking the current balance. Additionally, the class should keep track of the total number of transactions (deposits and withdrawals) made on the account.
Yo... | ```python
class BankAccount:
def __init__(self, initial_balance):
self._balance = initial_balance
self._transactions = 0
def deposit(self, amount):
self._balance += amount
self._transactions += 1
def withdraw(self, amount):
if self._balance >= amount:
se... | magicoder | python |
You are tasked with implementing a Python function to calculate the magnitude of a given vector. The magnitude of a vector is defined as the square root of the sum of the squares of its elements. You are provided with the following helper functions:
```python
def dot(v, w):
"""v_1 * w_1 + ... + v_n * w_n"""
r... | ```python
import math
def magnitude(v):
"""Calculate the magnitude of a vector"""
return math.sqrt(sum_of_squares(v))
```
The `magnitude` function uses the `sum_of_squares` helper function to calculate the sum of squares of the vector elements and then returns the square root of the result, which represents t... | magicoder | python |
You are tasked with simulating a simple game scenario using Python. The game involves controlling the movement of a character within a 2D grid. The character can move left, right, up, or down, and the objective is to reach a specific target location within the grid. To achieve this, you need to implement a function tha... | ```python
import pykeyboard
import time
def generate_key_sequence(target_x, target_y):
key_sequence = ""
if target_x > 0:
key_sequence += "R" * target_x # Press right key
elif target_x < 0:
key_sequence += "L" * abs(target_x) # Press left key
if target_y > 0:
key_sequence += ... | magicoder | python |
You are tasked with implementing a program that reads a C++ header file and extracts the list of constants exported from a class. The header file follows a standard layout, as shown in the code snippet below. The constants are defined within the class and are to be extracted and printed in the output.
The header file ... | ```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
int main() {
std::ifstream file("example_header.hpp");
std::string line;
std::string constants;
bool inConstantsSection = false;
std::regex constantPattern("static const .*? ([A-Za-z_][A-Za-z0-9_]*)");
while (std... | magicoder | cpp |
You are tasked with implementing a class to manage the toxicity level of a substance. The class should provide methods to increase or decrease the toxicity level and to check if the substance is safe for use. The toxicity level should be represented as an integer value, and the class should have the following methods:
... | ```python
class ToxicManager:
def __init__(self, initial_toxicity):
self.toxic_level = initial_toxicity
def increase_toxicity(self, amount):
self.toxic_level += amount
def decrease_toxicity(self, amount):
self.toxic_level = max(0, self.toxic_level - amount)
def is_safe(self):
... | magicoder | python |
You are tasked with creating a program that simulates a simple package manager. Your program should be able to handle the installation of packages and their dependencies. The package manager will use a simple text-based interface to receive commands from the user. Each package can have dependencies, and when a package ... | ```python
class PackageManager:
def __init__(self):
self.packages = {}
def install(self, package):
if package in self.packages:
print(f"{package} is already installed")
else:
self.packages[package] = True
print(f"{package} and its dependencies install... | magicoder | python |
You are tasked with implementing a generic function in Rust that compares two arrays of a generic type `U`. The function should return `true` if the arrays are equal and `false` otherwise. The function should be implemented as a method for a generic type `T` that implements the `PartialEq` trait.
Your task is to compl... | ```rust
use std::cmp::PartialEq;
struct Array<T> {
data: Vec<T>,
}
impl<T> Array<T> {
fn new(data: Vec<T>) -> Array<T> {
Array { data }
}
}
impl<T, U> PartialEq<Array<U>> for Array<T>
where
T: PartialEq<U>,
{
#[inline]
fn eq(&self, other: &Array<U>) -> bool {
self.data == othe... | magicoder | rust |
You are given a list of integers representing the daily stock prices of a company. You need to write a function to calculate the maximum profit that can be obtained by buying and selling the stock at most once. If it is not possible to make any profit, return 0.
Write a function `maxProfit` that takes in a list of int... | ```python
def maxProfit(prices):
if not prices:
return 0
min_price = prices[0]
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
else:
max_profit = max(max_profit, price - min_price)
return max_profit
```
The `m... | magicoder | python |
You are tasked with implementing a custom neural network module in PyTorch for a reinforcement learning agent. The provided code snippet shows the initialization of the neural network module, including the definition of two linear layers. Additionally, there are commented-out lines that define parameters using `nn.Para... | ```python
import torch
import torch.nn as nn
class CustomNeuralNetwork(nn.Module):
def __init__(self, state_dim, num_actions):
super(CustomNeuralNetwork, self).__init__()
self.linear1 = nn.Linear(state_dim, 20)
self.linear2 = nn.Linear(20, num_actions)
self.W1 = nn.Parameter(torch.r... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.