query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a Rust program that processes a list of strings and performs various operations on them. Your program should utilize the provided external crates and adhere to the following requirements: 1. Use the `lazy_static` crate to create a lazy-initialized static variable to store a regex pattern f...
```rust extern crate lazy_static; extern crate num; #[macro_use] extern crate regex; extern crate smallvec; extern crate string_cache; use regex::Regex; use smallvec::SmallVec; use std::str::FromStr; lazy_static! { static ref PATTERN: Regex = Regex::new(r"(\d+)").unwrap(); } fn process_strings(input: &[&str]) { ...
magicoder
rust
You are tasked with optimizing the performance of a web application's dashboard page. The given code snippet is from a Laravel controller method responsible for rendering the dashboard view. The method retrieves data from the database and passes it to the view for display. However, the current implementation may lead t...
```php public function index() { $newestOrders = Order::where('status', 0)->latest()->take(50)->get(); $latestOrders = Order::latest()->take(8)->get(); $latestProducts = Product::latest()->take(8)->get(); return view('admin.dashboard', compact('newestOrders', 'latestOrders', 'latestProducts')); } `...
magicoder
php
You are tasked with designing a Python class to manage power zones in a smart home system. The system has a database table named `power` with the following columns: `zone_name` (string), `running` (boolean), and `running_manually` (boolean). The class should have a method to update the status of a power zone in the dat...
```python import sqlalchemy class PowerZoneManager: def __init__(self, zone_name): self.zone_name = zone_name # Initialize the database connection self.engine = sqlalchemy.create_engine('sqlite:///smart_home.db') self.metadata = sqlalchemy.MetaData() self.power = sqlalchemy....
magicoder
python
You are tasked with creating a script to automate the mounting of various directories on a Linux system. The script should read a configuration file containing a list of directories and their corresponding UUIDs, and then mount each directory using the specified UUID. The configuration file will be in the following fo...
```bash #!/bin/bash # Function to check if a directory is mounted is_mounted() { mount | grep -q " $1 " } # Read the configuration file and mount directories while IFS= read -r line || [[ -n $line ]]; do directory=$(echo $line | awk '{print $1}') uuid=$(echo $line | awk '{print $2}') if is_mounted $d...
magicoder
shell
You are tasked with simulating a dice rolling game using C++. The game involves rolling two dice and recording the outcomes. Your task is to complete the code by implementing the `Die` and `Roll` classes, as well as the logic for rolling the dice and storing the results. The `Die` class should have a method `roll()` t...
```cpp #include <iostream> #include <vector> #include <cstdlib> #include <ctime> using namespace std; class Die { public: int roll() { return rand() % 6 + 1; } }; class Roll { private: int dice1Value; int dice2Value; public: Roll(int d1, int d2) : dice1Value(d1), dice2Value(d2) {} voi...
magicoder
cpp
You are tasked with creating a PHP class that manages user data in a database. The class contains methods for adding, editing, and deleting user records. The class uses a session to set flash messages for success or failure of the operations and then redirects the user to a specific page. Your task is to implement the...
```php class UserManager { private $db; private $session; public function __construct($db, $session) { $this->db = $db; $this->session = $session; } public function addUser($userData) { if($this->db->insert('tb_user', $userData)) { $this->session->set_flashdata('success', 'User added succe...
magicoder
php
You are tasked with implementing a class for handling requests related to the FIDO2 CTAP (Client to Authenticator Protocol) standard. The CTAP protocol is used for secure communication between a client device, such as a computer or smartphone, and an authenticator, such as a security key or biometric device. Your goal ...
```python class CtapGetAssertionRequest: OPTIONS_KEY = "options" def __init__(self, user_verification_required): self.user_verification_required = user_verification_required @classmethod def create(cls, options): if options is None: return cls(user_verification_required=Fal...
magicoder
python
You are tasked with creating a React component that displays a phrase and provides a link to show related GIFs. The component should take an `item` object as a prop, which contains the `phrase` and `phraseId` properties. The `phrase` property holds the text of the phrase, and the `phraseId` property holds the unique id...
```jsx import React from 'react'; import { FraseContent, StyledLink } from './styles'; // Import necessary styles const PhraseComponent = ({ item }) => { const publicUrl = process.env.PUBLIC_URL || ''; // Get the public URL return ( <FraseContent> <h3>{`"${item.phrase}" | `}</h3> <StyledLink to={`...
magicoder
jsx
You are tasked with creating a script that automates the deployment of a WildFly Swarm application. WildFly Swarm is a framework that allows you to package and run Java EE applications by embedding the WildFly application server within the application. The provided code snippet is a simplified version of a deployment s...
```bash #!/bin/sh jar_file="/opt/app-root/bin/builds-for-managers.jar" echo "Starting wildfly swarm app..." echo "JVM options => $JAVA_OPTIONS" echo if [ -f "$jar_file" ]; then java $JAVA_OPTIONS -jar "$jar_file" else echo "Error: The file $jar_file does not exist. Unable to run the application." exit 1 fi ```...
magicoder
shell
Vika, a schoolgirl, is preparing to celebrate her birthday at school by bringing N chocolate candies to share with her classmates. However, she encountered a problem when she went to the store to buy the candies a day before her birthday. The store only sells the candies in packs, with each pack containing exactly M ca...
```python def min_packs_to_buy(N: int, M: int) -> int: return -(-N // M) # Using the ceiling division to calculate the minimum number of packs needed ``` The solution uses the ceiling division to calculate the minimum number of packs Vika needs to buy. The expression `-(-N // M)` ensures that any remainder from t...
magicoder
python
You are tasked with creating a Python class that manages machine learning models loaded from XML representations. Your class should have the following functionalities: 1. A method to load a machine learning model from an XML string and store it in the class. 2. A method to update the XML representation of the stored m...
```python from sklearn.externals import joblib import xml.etree.ElementTree as ET class ModelManager: def __init__(self): self.model = None self.model_xml = None def load_model_from_xml(self, xml_string): if xml_string == "": raise ValueError("Empty XML string provided") ...
magicoder
python
You are tasked with implementing a dynamic 2D upsampling operation using the given code snippet as a reference. The function `dyn_2d_up_operation` takes in several parameters: `x` (input data), `lf_2d` (2D low-frequency data), `k_sz` (kernel size), and an optional parameter `sf` (scaling factor, default value 2). The g...
```python def dyn_2d_up_operation(x, lf_2d, k_sz, sf=2): """ Dynamic 2d upsampling """ with nn.parameter_scope("Dynamic_2D_Upsampling"): y = [] sz = lf_2d.shape lf_2d_new = F.reshape(lf_2d, (sz[0], sz[1], 1, sz[2], 1)) lf_2d_new = F.tile(lf_2d_new, (1, 1, sf, 1, sf)) ...
magicoder
python
You are tasked with implementing a simple event handling system in Python. Your goal is to create a class that allows objects to subscribe to and emit events. The class should have methods to subscribe to an event, unsubscribe from an event, and emit an event to all subscribed handlers. You need to implement a class `...
```python class EventHandler: def __init__(self): self.handlers = [] def subscribe(self, func): self.handlers.append(func) def unsubscribe(self, func): self.handlers.remove(func) def emit(self, *args): for func in self.handlers: func(*args) ``` The `EventHa...
magicoder
python
You are tasked with implementing a function that processes a given input and performs specific actions based on the input type. The input can be of type `string`, `number`, or `boolean`. The function should handle each input type differently and return a corresponding result. Additionally, the function should utilize t...
```javascript import process from 'process'; function InputCloudFoundry(input) { if (typeof input === 'string') { return input + " processed"; } else if (typeof input === 'number') { return input * input; } else if (typeof input === 'boolean') { return !input; } process.once('exit', () => { ...
magicoder
javascript
You are tasked with creating a Python function that processes the results of a machine learning model and visualizes its performance using various metrics. The function takes in a test dataset, applies a decision tree classifier to it, and then generates a classification report, visualizes the data, and plots a confusi...
```python from sklearn.metrics import classification_report, plot_confusion_matrix import matplotlib.pyplot as plt import pandas as pd def evaluate_model(tst_feats, tst_labels, decision_tree): """ Evaluates the performance of a decision tree classifier on a test dataset and visualizes the results. Args: ...
magicoder
python
You are given a code snippet for a job application system. The code is intended to process job applications and store relevant information. Your task is to implement a function that will parse the given input and extract the relevant data for each job application. The input consists of a series of job applications, ea...
```python from typing import List, Dict def parseJobApplications(applications: List[str]) -> List[Dict[str, str]]: parsed_applications = [] for app in applications: job_title, company_name, location, salary = app.split(',') parsed_applications.append({ 'JobTitle': job_title, ...
magicoder
python
You are tasked with creating a script to automate the setup of a wireless access point on a Linux system. The script should take user input for the country code, interface, SSID, and WPA passphrase, and then generate a configuration file for hostapd. Additionally, the script should reboot the system to apply the change...
```bash #!/bin/bash # Prompt user for input read -p "Enter country code: " country_code read -p "Enter interface: " interface read -p "Enter SSID: " ssid read -s -p "Enter WPA passphrase: " wpa_passphrase echo # Validate input if [[ -z $country_code || -z $interface || -z $ssid || -z $wpa_passphrase ]]; then echo "...
magicoder
shell
You are tasked with creating a program to parse and extract information from HTML code. Specifically, you need to extract the URLs and corresponding link text from anchor tags in the HTML code. Write a function `extractLinks(html)` that takes a string `html` representing the HTML code as input and returns a dictionary...
```python import re def extractLinks(html): link_pattern = r'<a\s+href="([^"]+)"[^>]*>\s*<span class="link-text">([^<]+)</span>\s*</a>' matches = re.findall(link_pattern, html) return {url: text for url, text in matches} # Test the function with the provided example html = ''' <a href="https://www.example...
magicoder
python
You are tasked with creating a custom plugin for a modeling tool called EDMM (TOSCA-based Environment for Deployment and Management). The EDMM tool provides a framework for modeling and transforming cloud applications. Your custom plugin will need to implement specific functionality to support the transformation proces...
```java import io.github.edmm.core.plugin.AbstractLifecycle; import io.github.edmm.core.plugin.support.CheckModelResult; import io.github.edmm.core.transformation.TransformationContext; import io.github.edmm.model.Compute; import io.github.edmm.plugins.ComputeSupportVisitor; import org.slf4j.Logger; public class Custo...
magicoder
java
You are tasked with creating a function to compress images and convert them to base64 format. The function should take an image as input and return the compressed image in base64 format. The compression level should be determined based on the image's size. You are given the following code snippet as a starting point: ...
```swift func compressAndConvertToBase64(image: UIImage) -> String { let KBsize = 1024 // 1 kilobyte in bytes let compressionFactor: Double = 0.5 // Example compression factor guard let imageData = image.jpegData(compressionQuality: CGFloat(compressionFactor)) else { return "" // Return empty strin...
magicoder
swift
You are tasked with creating a Python decorator that logs the execution time of a function and returns the result along with the execution time. The decorator should be able to handle functions that take in a list of integers and return a list of integers. The decorator should also handle functions that take in a custo...
```python import time from typing import List from infrastructure.cqrs.decorators.responseclass import responseclass from domain.operation.GetDataOperationJobExecutionLogList.GetDataOperationJobExecutionLogListDto import GetDataOperationJobExecutionLogListDto @responseclass class Response: def __init__(self, resul...
magicoder
python
You are tasked with implementing a simple routing system for a web server. The server should be able to handle different routes and resources, as well as handle errors and redirects. Your task is to create a class that manages these routes and resources, and to implement the necessary methods to add routes, set a defau...
```python class RoutingSystem: def __init__(self): self.routes = {} self.default_route = None self.sink = None self.error_serializer = None def add_route(self, path, resource): self.routes[path] = resource def add_sink(self, resource, prefix): self.sink = (r...
magicoder
python
You are tasked with creating a C++ unit testing framework for a simple role-playing game. The game consists of characters, commands, enemies, heroes, and the world. Your goal is to implement the necessary unit tests for each component using the Google Test framework. You have been provided with a code snippet that inc...
```cpp // character_test.cpp #include <gtest/gtest.h> #include "character.h" TEST(CharacterTest, Initialization) { Character character("Player1", 100); EXPECT_EQ("Player1", character.getName()); EXPECT_EQ(100, character.getHealth()); } // command_test.cpp #include <gtest/gtest.h> #include "command.h" TEST(Comm...
magicoder
cpp
You are tasked with creating a Python program to implement a simple encryption algorithm. The algorithm will take a key and a value as input and produce an encrypted output. The encryption process involves reading the contents of a file specified by the value and applying a simple substitution cipher using the characte...
```python def encrypt_text(key, value): encrypted_text = "" with open(value[1:]) as plaintext_fh: # Open the plaintext file for reading plaintext = plaintext_fh.read() # Read the contents of the plaintext file for char in plaintext: if char in key: # Check if the character is pres...
magicoder
python
You are tasked with implementing a class that generates HTML code for a title table. The class `HF_TitleTable` is a subclass of the `HtmlMaker` class and is responsible for creating HTML code for a title table. The class has a constructor, a destructor, and two member functions for producing titles. The constructor `H...
```cpp #include "HtmlMaker.h" #include "Xml.h" class HF_TitleTable : public HtmlMaker { public: HF_TitleTable(Xml::Element& o_rOut); virtual ~HF_TitleTable(); void Produce_Title(const char* i_title); void Produce_Title(const char* i_annotations, const char* i_label); // Uncommented overload private: ...
magicoder
cpp
You are given a Python code snippet that manipulates a dictionary called `pessoas`. Your task is to analyze the code and predict the output of each print statement. Additionally, you need to explain the changes made to the `pessoas` dictionary and the final state of the dictionary after the code execution. ```python p...
The output of the code snippet and the final state of the `pessoas` dictionary are as follows: Output: ``` 25 João masculino o nome pertence ao João o idade pertence ao 25 o sexo pertence ao masculino {'nome': 'João', 'idade': 25} {'nome': 'João', 'idade': 25, 'sexo': 'macho alfa'} outro codida daqui pra frente ``` E...
magicoder
python
You are tasked with implementing a simple neural network training loop using PyTorch. The given code snippet initializes a neural network model and sets up the training loop. Your task is to complete the training loop by incorporating the necessary steps for training the model on a dataset. You are provided with the f...
```python import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset # Assume the following: # - model: the neural network model # - loss: the CrossEntropyLoss function # - optimizer: the optimizer (e.g., SGD, Adam) for updating model parameters # - train_load...
magicoder
python
You are tasked with creating a script to analyze a database of software ports and identify any Python 3 packages that are missing a required hook in their respective Makefiles. The script should iterate through the database, extract the category and port name for each Python 3 package, and then check if the correspondi...
```bash #!/bin/sh # Iterate through the Python 3 packages in the database for _pkgpath in $(sqlite3 /usr/local/share/sqlports "select FULLPKGPATH from Ports where FULLPKGPATH like '%,python3';") ; do # Extract category and port name from the FULLPKGPATH _cat=$(echo "${_pkgpath}" | awk -F '/' '{print $1}') _port=$(e...
magicoder
shell
You are tasked with implementing a custom label metrics evaluation function for a machine learning model. The function should calculate the area under the curve (AUC) for each specified label and return the results in a dictionary format. You are given a code snippet that uses the `CustomLabelMetrics` class from the `m...
```python from sklearn import metrics import numpy as np def calculate_auc_per_label(y_true, y_pred, labels): auc_dict = {} for label in labels: label_indices = np.where(y_true == label)[0] label_true = np.zeros(len(y_true)) label_true[label_indices] = 1 label_pred = y_pred[:, l...
magicoder
python
You are tasked with implementing a custom random number generator class in Python. The class should have a method to generate random integers within a specified range using a linear congruential generator algorithm. The linear congruential generator algorithm is defined by the recurrence relation: Xn+1 = (a * Xn + c) ...
```python class RandomState: def __init__(self, seed): self.seed = seed self.multiplier = 1664525 self.increment = 1013904223 self.modulus = 2**32 def randint(self, a, b): self.seed = (self.multiplier * self.seed + self.increment) % self.modulus return a + self.s...
magicoder
python
You are tasked with creating a script to clean up a directory by removing all files except those specified in a whitelist file. The script should identify any unknown files in the directory and prompt the user to confirm deletion. Your script should take two arguments: 1. The directory path to be cleaned. 2. The whit...
```bash #!/bin/bash # Check if the correct number of arguments is provided if [ "$#" -ne 2 ]; then echo "Usage: $0 <directory_path> <whitelist_file>" exit 1 fi directory_path=$1 whitelist_file=$2 # Check if the directory exists if [ ! -d "$directory_path" ]; then echo "Error: Directory does not exist." exit ...
magicoder
shell
You are tasked with creating a Python program to control a traffic light system using a Raspberry Pi and the RPi.GPIO library. The traffic light has three colors: red, yellow, and green. The program should continuously prompt the user for input and respond to specific commands to control the traffic light. The traffic...
```python import RPi.GPIO as GPIO def main(): red_pin = 17 yellow_pin = 27 green_pin = 22 GPIO.setmode(GPIO.BCM) GPIO.setup(red_pin, GPIO.OUT) GPIO.setup(yellow_pin, GPIO.OUT) GPIO.setup(green_pin, GPIO.OUT) while True: cmd = raw_input("--> ") if cmd == "red on": ...
magicoder
python
You are tasked with creating a URL routing system for a music streaming web application using Django. The application has endpoints for managing playlists, songs, and user accounts. Your goal is to define the URL patterns for these endpoints based on the provided code snippet. Given the code snippet, you need to compl...
```python from django.conf.urls import patterns, url, include from rest_framework.urlpatterns import format_suffix_patterns from .views import PlaylistList, PlaylistDetail from .views import SongList, SongDetail from .views import CreatePlaylistFromYoutube from .views import UserList, UserCreate, UserDetail, CurrentUse...
magicoder
python
You are tasked with implementing a custom stack data structure that supports the standard push, pop, and peek operations, along with an additional operation `getMin` that returns the minimum element in the stack in constant time. Your implementation should have O(1) time complexity for all operations. You are given th...
```java import java.util.Stack; class MinStack { private Stack<Integer> stack; private Stack<Integer> minStack; public MinStack() { stack = new Stack<>(); minStack = new Stack<>(); } public void push(int x) { stack.push(x); if (minStack.isEmpty() || x <= minStack.p...
magicoder
java
You are tasked with implementing a function that evaluates a Python expression with extreme caution. The function `cautious_eval` takes in a Python expression as a string and an optional size limit for the evaluated expression. The goal is to carefully evaluate the expression, taking into account potential security ris...
```python import ast import sys import resource def cautious_eval(definition: str, size_limit: Optional[int] = None) -> Any: try: # Parse the input expression using Python's Abstract Syntax Trees (AST) parsed_expr = ast.parse(definition, mode='eval') # If a size limit is specified, check t...
magicoder
python
You are tasked with creating a Python function that generates a random symmetric matrix of a given size. A symmetric matrix is a square matrix that is equal to its transpose. Your function should take an integer `n` as input and return a NumPy array representing the symmetric matrix of size `n x n`. Your task is to im...
```python import numpy as np def generate_symmetric_matrix(n: int) -> np.ndarray: matrix = np.random.randint(1, 101, size=(n, n)) # Generate a random matrix sym_matrix = (matrix + matrix.T) / 2 # Ensure symmetry by averaging with its transpose return sym_matrix ```
magicoder
python
You are working on implementing a neural network training algorithm using a library that provides matrix operations for efficient computation. The code snippet provided is part of the backpropagation process for updating the weights and biases of a neural network. Your task is to implement a function that performs the...
```python import numpy as np def backpropagation_step(inp, h, delta, wu_w1, wu_b1, momentum): # Multiply the error signal delta by the derivative of the sigmoid activation function applied to the hidden layer output h delta *= h * (1 - h) # Update the weights connecting the input layer to the hidden layer...
magicoder
python
You are given a list of strings, where each string represents a word. Your task is to write a function that finds all pairs of words in the list that can be joined together to form a new word. A pair of words can be joined together if the end of the first word is the same as the beginning of the second word. For exampl...
```python def find_joinable_pairs(words): joinable_pairs = [] for i in range(len(words)): for j in range(len(words)): if i != j and words[i][-2:] == words[j][:2]: joinable_pairs.append((i, j)) return joinable_pairs ``` The `find_joinable_pairs` function iterates through ...
magicoder
python
You are tasked with creating a program that processes a list of GitHub repositories and their corresponding star counts. Your program should read in the repository data and perform specific operations based on the requirements outlined below. You are given a list of GitHub repositories in the following format: ``` <gh...
```python # Read in the input data input_data = [ "<gh_stars>0", "net.sf.jasperreports.engine.util.XmlNamespace", "<gh_stars>100", "user/repo1", "<gh_stars>50", "organization/repo2" ] # Process the input data repositories = [] total_stars = 0 for i in range(0, len(input_data), 2): stars = i...
magicoder
python
You are tasked with implementing a message processing system that processes message block elements and constructs a message using a StringBuilder. Each message block element is processed by a function `processElement` which takes the element and a context as input and returns a `ProcessingReturnValue`. The context cont...
```java public String processMessageBlock(MessageBlock messageBlock, Context context) { StringBuilder message = new StringBuilder(); LOGGER.trace("Processing block {}", context.getBlockName()); for (MessageBlockElement element : messageBlock.getElements()) { ProcessingReturnValue returnValue = pro...
magicoder
java
You are tasked with implementing a custom `subtract` function for arrays in Swift. The `subtract` function should take two arrays of the same type and return a new array containing the elements from the first array that are not present in the second array. If an element appears multiple times in the first array, it sho...
```swift func subtract<Element: Equatable>(_ lhs: [Element], _ rhs: [Element]) -> [Element] { var result = lhs for element in rhs { if let index = result.firstIndex(of: element) { result.remove(at: index) } } return result } ``` The `subtract` function takes two arrays `lhs`...
magicoder
swift
You are tasked with implementing a function that simulates the behavior of the `awaitCatcher` function. The `awaitCatcher` function takes a promise as an argument and returns a new promise that resolves to an array containing the resolved value of the original promise (if it resolves) and the error (if it rejects). You...
```javascript function awaitCatcher(promise) { return promise .then((data) => [data, undefined]) .catch((error) => [undefined, error]); } ```
magicoder
javascript
You are tasked with implementing a system to manage events in a music streaming application. The application supports various events related to playing songs, managing playlists, handling payments, and controlling the streaming service. Each event is represented by a unique string identifier. Your goal is to design a d...
```python class EventManager: def __init__(self): self.event_handlers = {} def register_event_handler(self, event, handler): if event in self.event_handlers: self.event_handlers[event].append(handler) else: self.event_handlers[event] = [handler] def trigger_...
magicoder
python
You are given a positive integer `n`. Your task is to write a function that calculates the sum of the digits in the thousands and hundreds place of the given number `n`. Write a function `sumOfThousandsAndHundreds` that takes in a positive integer `n` and returns the sum of the digits in the thousands and hundreds pla...
```java public class SumOfThousandsAndHundreds { public static int sumOfThousandsAndHundreds(int n) { if (n < 100) { return -1; // Return -1 if n has less than three digits } else { int thousand = n / 1000; // Calculate the digit in the thousands place int hundred...
magicoder
java
You are tasked with implementing a system for managing widgets in a game engine. The game engine uses the ECS (Entity-Component-System) architecture, where entities are objects in the game world, components are the data associated with entities, and systems are responsible for processing entities with specific componen...
```rust fn register_widgets(world: &mut World) { let entities = world .query::<()>() .with::<Self::Widget>() .without::<WidgetRegistered<Self::Widget>>() .iter() .collect::<Vec<_>>(); for (entity, ()) in entities { world.add_component(entity, WidgetRegistered::<S...
magicoder
rust
You are tasked with parsing and extracting autofocus information from a Canon camera's metadata. The autofocus information is stored in an array with 'fake' tags, and the values in this record are sequential. Some values have variable sizes based on the number of autofocus points (numafpoints), which can be 1, 5, 7, 9,...
```python def extract_autofocus_info(af_info: list, af_image_width: int, af_image_height: int) -> (int, list, str): num_af_points = af_info[0] # Extract the number of autofocus points af_area_coordinates = [(af_info[i], af_info[i + 1]) for i in range(1, num_af_points * 2, 2)] # Extract AFArea coordinates ...
magicoder
python
You are tasked with creating a Python class that acts as a wrapper for a command-line tool. The class should provide a convenient interface for executing the tool and handling its output. Your task is to implement the `AlignAceCommandline` class, which will serve as a wrapper for the AlignAce command-line tool. The `A...
```python import subprocess class AlignAceCommandline: def __init__(self, alignace_executable): self.alignace_executable = alignace_executable self.input_file = None self.output_file = None self.additional_options = [] self.stdout = None self.stderr = None def s...
magicoder
python
You are given a code snippet that appears to be part of a program written in C++ or a similar language. Your task is to understand the logic and purpose of the code and then implement a specific function based on the given code snippet. The code snippet seems to be part of a larger program that involves handling casca...
```cpp void processCascadingDecay(int m_vUomCascDcyBrP[], int iCascDcyBrCcP[][MAX_SIZE], int m_vVNCascDcyBrCcP[], int nCcPCascDcyBr[], bool m_ccSwitch, int m_vICcCompCascDcyBrP[], int nAllPCascDcyBr[], int nPCascDcyBr[], int j, int _iCascDcyBrP) { if (m_ccSwitch == true) { if (m_vICcCompCascDcyBrP[j] != 0) ...
magicoder
cpp
You are tasked with implementing a simple neural network model using Python and TensorFlow. The model should consist of a single layer of Transformer architecture. The Transformer model should be designed to perform a basic classification task on a given dataset. Your task is to complete the implementation of the model...
```python import tensorflow as tf from tensorflow.keras import layers # Define the Transformer model class Transformer(tf.keras.Model): def __init__(self, num_classes, d_model, num_heads, dff, input_vocab_size, maximum_position_encoding, rate=0.1): super(Transformer, self).__init__() self.d_model =...
magicoder
python
You are tasked with implementing a neural network classifier using PyTorch for a computer vision project. The given code snippet shows the beginning of the classifier definition, where a fully connected layer is added to the sequential model. Your task is to complete the classifier by adding additional layers and then ...
```python import torch import torch.nn as nn import torch.optim as optim import torchvision.models as models import torchvision.transforms as transforms import torchvision.datasets as datasets from torch.utils.data import DataLoader # Define the classifier model = models.vgg16(pretrained=True) for param in model.param...
magicoder
python
You are tasked with implementing a custom list queue data structure in Rust. The list queue should support the following operations: 1. `enqueue`: Add an 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 at the front of the queue withou...
```rust pub struct ListQueue<T> { elements: Vec<T>, } impl<T> ListQueue<T> { pub fn new() -> Self { ListQueue { elements: Vec::new() } } pub fn enqueue(&mut self, element: T) { self.elements.push(element); } pub fn dequeue(&mut self) -> Option<T> { if self.is_empty() {...
magicoder
rust
You are tasked with creating a simple iOS app that fetches data from a remote server using Moya for network requests and RxSwift for handling asynchronous operations. Your app needs to display a list of items retrieved from the server in a table view. Each item should have a title and a description. You have been prov...
```swift // Step 1: Define the model struct for the items struct Item { let title: String let description: String } // Step 2: Create a Moya provider for network requests let provider = MoyaProvider<ItemsService>() // Step 3: Implement a function to fetch the items using Moya func fetchItems() -> Observable<[...
magicoder
swift
You are tasked with creating a script that retrieves the latest release version of a given GitHub repository. Your script should utilize the `curl` command to fetch the release information from the GitHub API and then extract the latest release version using `grep` and `sed`. Additionally, the script should accept comm...
```bash #!/bin/bash POSITIONAL=() while [[ $# -gt 0 ]]; do key="$1" case $key in *) # Handle additional command-line arguments if needed POSITIONAL+=("$1") shift ;; esac done set -- "${POSITIONAL[@]}" # restore positional parameters get_latest_release() { local REPO=$1 curl --silent ...
magicoder
shell
You are tasked with implementing a Java class that represents a simple shopping cart. The shopping cart should be able to hold a collection of items, calculate the total cost of the items, and apply a discount if a promotional code is provided. Your task is to implement the `ShoppingCart` class with the following requ...
```java import java.util.ArrayList; import java.util.List; class Item { private String name; private double price; public Item(String name, double price) { this.name = name; this.price = price; } public double getPrice() { return price; } } class ShoppingCart { pr...
magicoder
java
You are working on a web application and need to implement a feature that involves parsing and extracting information from HTML code. Your task is to write a function that extracts the URL and text content from an anchor tag in the given HTML code. Write a function `extractAnchorTagInfo(htmlCode)` that takes a string ...
```javascript function extractAnchorTagInfo(htmlCode) { const anchorTagRegex = /<a\s+href="([^"]+)"[^>]*>([^<]+)<\/a>/; const match = htmlCode.match(anchorTagRegex); if (match) { return { url: match[1], text: match[2] }; } else { return null; // Return nul...
magicoder
javascript
You are tasked with creating a Python class to manage social media user profiles. The class should have the following functionalities: 1. Initialize a user profile with a name, active status, last seen date, and number of followers. 2. Provide methods to update the active status, last seen date, and number of followers...
```python from datetime import datetime class UserProfile: def __init__(self, name, active, last_seen, followers): self.name = name self.active = active self.last_seen = datetime.strptime(last_seen, "%d-%m-%Y") self.followers = followers def update_active_status(self, new_statu...
magicoder
python
You are tasked with implementing a VIPER (View, Interactor, Presenter, Entity, Router) architecture for a mobile application. The VIPER architecture is a design pattern used to separate the concerns of an application into distinct layers, promoting modularity and testability. In this problem, you will focus on the Pres...
```swift // Create and link modules with controller, return presenter input static func configure(with reference: ___VARIABLE_viperModuleName___ViewController) -> ___VARIABLE_viperModuleName___PresenterInput { let presenter = ___VARIABLE_viperModuleName___Presenter() let router = ___VARIABLE_viperModuleNam...
magicoder
swift
You are tasked with implementing a function to add directory entries to a buffer in a C program. The function `dirbuf_add` takes in parameters representing the directory entry information and adds it to the buffer. Your task is to complete the implementation of the `dirbuf_add` function according to the given specifica...
```c #include <cstddef> #include <cstring> #include <dirent.h> #include <cstdlib> int dirbuf_add(dirent **buf, size_t *remain, ino_t ino, off_t off, unsigned char type, const char *name) { const size_t align = alignof(dirent); const size_t dirent_noname = offsetof(dirent, d_name); size_t entry_size = diren...
magicoder
c
You are tasked with creating a file upload feature for a web application using PHP. Your goal is to implement a method that processes the uploaded file and saves it to the server. The web application uses the CodeIgniter framework, and you need to write the method within a controller class. You are provided with the f...
```php public function processUpload() { $config['upload_path'] = './uploads/'; // Define the upload directory $config['allowed_types'] = 'jpg|jpeg|png|pdf|docx'; // Define allowed file types $config['max_size'] = 5120; // Maximum file size in kilobytes (5MB) $config['file_name'] = uniqid() . '_' . $_FI...
magicoder
php
You are tasked with implementing a Python function that updates a code snippet in a database using FastAPI and SQLAlchemy. The function takes in a data object representing the snippet data, an authentication token, and returns a response object representing the updated snippet. The function is responsible for handling ...
```python def update_snippet( data: schemas.snippet.SnippetData, auth_token: str = fastapi.Depends(oath) ) -> schemas.snippet.SnippetResponse: """ update the code snippet with the specified id. """ try: # Authenticate the user using the provided auth_token user = authenticate_use...
magicoder
python
You are tasked with implementing a partial key collector data structure in Rust. The `PartialKeyCollector` struct is designed to store partial keys, which can be either string references or integer values. The collector should allow adding and retrieving partial keys, and it should enforce certain constraints on the ke...
```rust use std::collections::HashSet; /// Partial key collector. #[derive(Debug)] pub struct PartialKeyCollector<'a> { pub(crate) str_key: HashSet<&'a str>, pub(crate) int_key: Option<usize>, } impl<'a> PartialKeyCollector<'a> { pub(crate) fn new() -> Self { Self { str_key: HashSet::n...
magicoder
rust
You are tasked with implementing a 2D Gaussian blur operation using the provided code snippet as a starting point. The `GaussianBlur2D` class extends `DefaultBenchmarkableModule` and contains a private field `sigma` of type `Double`. Your goal is to complete the implementation of the Gaussian blur operation by adding t...
```java import net.haesleinhuepf.clij.benchmark.DefaultBenchmarkableModule; import net.haesleinhuepf.clij.clearcl.ClearCLBuffer; import net.haesleinhuepf.clij.CLIJ; public class GaussianBlur2D extends DefaultBenchmarkableModule { private Double sigma; private ClearCLBuffer input; private ClearCLBuffer out...
magicoder
java
You are tasked with implementing a service management system that allows users to create, update, and delete services within different environments. The system is designed to work with a RESTful API, and you are provided with a partial code snippet for the `delete_service` method of the service management class. Your t...
```python import requests class ServiceManagement: def __init__(self, base_url, auth_token): self.base_url = base_url self.auth_token = auth_token def get_url(self, endpoint): return '{0}/{1}'.format(self.base_url, endpoint) def delete_service(self, environment_id, session_id, ser...
magicoder
python
You are tasked with implementing a basic AVL tree data structure in Python. An AVL tree is a self-balancing binary search tree, where the heights of the two child subtrees of any node differ by at most one. Your task is to implement the `AVLTree` class with the following methods: 1. `update(self, key_value_pair)`: Thi...
```python class AVLNode: def __init__(self, key, value): self.key = key self.value = value self.left = None self.right = None self.height = 1 class AVLTree: def __init__(self): self.root = None def update(self, key_value_pair): key, value = key_value...
magicoder
python
You are tasked with simulating the movement of a simple human arm in a 3D environment. The arm is represented by a set of joints and links, and its movement is controlled by specifying joint angles. Your goal is to implement a function that calculates the end-effector position of the arm given a set of joint angles and...
```python import numpy as np def calculate_end_effector_position(human_arm, joint_angles, target_position): # Set the joint angles of the human arm human_arm.set_joint_angles(joint_angles) # Calculate the end-effector position end_effector_position = human_arm.calculate_end_effector_position() ...
magicoder
python
You are tasked with creating a Rust function that interacts with an API to retrieve random clues for a game. The provided code snippet is part of an asynchronous Rust program that makes use of the reqwest library for making HTTP requests. The function `get_random_clues` takes a reference to `self` and a `count` paramet...
```rust use reqwest::Client; use serde::Deserialize; // Define the Clue struct based on the expected structure #[derive(Debug, Deserialize)] struct Clue { // Define the fields of the Clue struct based on the actual structure // For example: // id: u64, // text: String, // category: String, // ....
magicoder
rust
You are tasked with creating a Python script to blind the files in a directory for analysis. The script should be non-destructive, meaning it will create a copy of the files to be blinded and record their identities to a text file. The blinding process involves creating a copy of each file in the directory, renaming th...
```python import os import shutil import datetime def blind_files(directory_path): try: # Create a new directory within the original directory new_directory = os.path.join(directory_path, 'blinded_files_' + datetime.datetime.now().strftime('%Y%m%d_%H%M%S')) os.makedirs(new_directory) ...
magicoder
python
You are given a code snippet for a file header in a programming project. Your task is to write a program that extracts the creation date and the author's name from the header. The header follows the format: ``` // // Created by [Author's Name] on [Creation Date]. // Copyright © [Year] [Author's Name]. All rights res...
```python import re def extract_header_info(header): author_name = re.search(r'\[([^\]]+)\]', header).group(1) creation_date = re.search(r'on (\d{4}/\d{2}/\d{2})', header).group(1) return f"Author's Name: {author_name}\nCreation Date: {creation_date}" code_header = """ // // Created by 天明 on 2018/7/11. /...
magicoder
python
You are tasked with implementing a function to process context logs from a given log store using a provided client. The function should retrieve context logs forward, extract pack information, and print relevant details. You are given a code snippet as inspiration, which demonstrates the process of retrieving context l...
```python def process_context_logs(client, project, logstore, forward_start_log): # Get context logs forward. log = forward_start_log for _ in range(0, 3): pack_id, pack_meta = extract_pack_info(log) response = client.get_context_logs(project, logstore, pack_id, pack_meta, 0, 10) pri...
magicoder
python
You are tasked with implementing a Python class that calculates the average loss of examples in a mini-batch. The class should inherit from `BaseLoss` and provide a method `calculate_loss` that takes in prediction scores, labels, and additional parameters. The prediction scores are stored in a 2D tensor, where each row...
```python class CustomLoss(BaseLoss): def calculate_loss(self, unused_predictions, unused_labels, **unused_params): # Your implementation of the calculate_loss method # Calculate the loss based on the prediction scores and labels # Return the average loss of the examples in the mini-batch ...
magicoder
python
You are tasked with implementing a Python function that simulates a simplified version of the `conda_remove` function from the given code snippet. The `conda_remove` function is responsible for deactivating a conda environment and restoring the original system PATH. You need to create a Python function `simulate_conda...
```python def simulate_conda_remove(env_name, old_path): if env_name == "sci3": return old_path else: return old_path ``` The `simulate_conda_remove` function checks if the specified `env_name` is "sci3". If it is, the function returns the original system PATH `old_path` without any modificatio...
magicoder
python
You are tasked with implementing a function that can efficiently determine the length of the longest namespace chain in a given C++ code snippet. A namespace chain is a sequence of nested namespaces, and the length of the chain is the number of nested levels. For example, in the code snippet provided, the longest names...
```cpp #include <iostream> #include <string> #include <sstream> int longestNamespaceChainLength(const std::string& codeSnippet) { std::istringstream iss(codeSnippet); std::string line; int maxChainLength = 0; int currentChainLength = 0; while (std::getline(iss, line)) { int openBraces = 0;...
magicoder
cpp
You are tasked with creating a script to automate the process of applying a custom theme to the dwm window manager and setting a wallpaper. The script should prompt the user to choose a theme from a directory, copy the necessary theme files to the appropriate locations, and then compile the dwm window manager. Your sc...
```bash #!/bin/bash echo "Choose a theme:" && ls theme/ read theme cp theme/$theme/colors.h dwm-6.2/ cp theme/$theme/$theme.png $HOME/.config/wallpaper.png cd dwm-6.2 make clean make ``` The provided shell script accomplishes the required tasks. It prompts the user to choose a theme, copies the necessary theme file...
magicoder
shell
You are tasked with implementing a function to find the upper bound of a given key in a binary search tree. The function `upper_bound` takes in two parameters: `root`, an optional reference to the root node of the binary search tree, and `key`, a reference to the key whose upper bound needs to be found. The function sh...
```rust impl<K: Ord> Node<K> { fn upper_bound(&self, key: &K) -> usize { let mut result = 0; let mut current = Some(self); while let Some(node) = current { if *key < node.key { result = node.key; current = node.left.as_ref().map(|n| &**n);...
magicoder
rust
You are tasked with implementing a function that executes a command on a network node and prints the command as well as the output of the command. You are given a code snippet that outlines the function signature and usage. Your task is to create the function `exec_cmd` that takes a `node` object, a `cmd` string, and r...
```python from typing import Tuple import subprocess class Node: # Define the Node class as per the requirements def exec_cmd(node: Node, cmd: str) -> Tuple[int, str, str]: try: process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process...
magicoder
python
You are tasked with creating a Python class that simulates a simple banking system. The class should have methods for depositing funds, withdrawing funds, and checking the account balance. Additionally, you need to implement a method for transferring funds from one account to another. To ensure security, the system sho...
```python class BankAccount: def __init__(self, account_number, initial_balance): self.account_number = account_number self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance >= amount: self.ba...
magicoder
python
You are tasked with implementing a container management system that can retrieve containers based on their status. The system has a method `_get_containers_with_state` which takes in a list of container names, a boolean flag `select_random`, and variable number of container states. The method retrieves containers with ...
```python import random class Container: def __init__(self, name, status): self.name = name self.status = status class ContainerManager: def __init__(self, containers): self.containers = containers def _get_all_containers(self): return self.containers def _get_contain...
magicoder
python
You are tasked with implementing a class that manages event handling and transport setup for a logging system. The class should provide methods for creating events from messages, setting up the transport, and starting a native client with specific options. Additionally, the class should have a property to indicate the ...
```typescript // Define the Severity enum enum Severity { Info, Warning, Error, // ... other severity levels } // Define the EventHint and Event types (for illustration purposes) type EventHint = { // Define EventHint properties }; type Event = { // Define Event properties }; type Transport = { // Defi...
magicoder
typescript
You are tasked with implementing a module resolution algorithm for a simple JavaScript module system. The module system uses the `export * from 'module'` syntax to re-export all the exports from another module. Your task is to write a function that resolves the exports for a given module, taking into account the re-exp...
```javascript function resolveModuleImports(importStatements) { const resolvedExports = {}; const resolveModule = (moduleName) => { const moduleExports = require(moduleName); // Assuming a Node.js environment for simplicity Object.assign(resolvedExports, moduleExports); }; importStatements.forEach((im...
magicoder
javascript
You are tasked with creating a program that processes images from a webcam, detects objects within the images, and applies a grayscale filter to the detected objects. The program reads a file containing class names, creates a detection model, and continuously captures images from the webcam while a specific exit key is...
```python # Sample implementation of the missing functions def detect_objects_in_image(image): # Placeholder implementation for object detection # Replace this with actual object detection logic using a detection model # For example, using OpenCV's object detection algorithms # This function should retu...
magicoder
python
You are working as a DevOps engineer for a company that uses Docker extensively for its applications. Your team is responsible for managing and deploying various Docker containers across different environments. One of the challenges you face is ensuring that the containers are launched with the correct configurations a...
```python import re def parse_docker_command(command: str) -> dict: docker_info = { "image": "", "tag": "", "restart": "", "volumes": [], "environment": [] } # Extract image and tag image_tag_match = re.search(r'(\S+):(\S+)', command) if image_tag_match: ...
magicoder
python
You are tasked with creating a Python function that verifies the existence of resources in a given template against the actual resources in a cloud environment. The function should compare the expected resources from the template with the actual resources in the cloud and raise an assertion error if the counts do not m...
```python def verify_resources(test, reality, tmpl): for name in tmpl.resources: rsrc_count = len(reality.resources_by_logical_name(name)) test.assertEqual(1, rsrc_count, 'Found %d copies of resource "%s"' % (rsrc_count, name)) all_rsrcs = reality.all_resources() # ...
magicoder
python
You are tasked with implementing a Python function that uses the `selectors` module to create a simple TCP echo server. The server should be able to accept incoming connections, read data from the client, and then echo the received data back to the client. The server should also keep track of the number of connections ...
```python import selectors import socket import types from typing import Callable def create_echo_server(port: int) -> Callable[[str], None]: sel = selectors.DefaultSelector() num_connections = 0 def start_server(): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_s...
magicoder
python
You are tasked with implementing a function that generates a payload for a 32-bit or 64-bit architecture. The payload will be used to exploit a vulnerability in a program by controlling the offset of the first formatter, providing a dictionary of addresses and values to write, and specifying the number of bytes already...
```python def generate_payload(offset: int, writes: dict, numbwritten: int, bits: int) -> bytes: payload = b'' # Calculate the total number of bytes to be written total_bytes = numbwritten + len(writes) * bits // 8 # Construct the payload based on the architecture size if bits == 32: ...
magicoder
python
You are tasked with implementing a function that processes data from reinforcement learning paths. The function takes in three arguments: `adjusted_rewards`, `env_infos`, and `agent_infos`. The `adjusted_rewards` is a 2D array of shape (batch_size, max_path_length), while `env_infos` and `agent_infos` are dictionaries ...
```python import numpy as np def process_data(adjusted_rewards, env_infos, agent_infos): assert type(adjusted_rewards) == np.ndarray, 'adjusted_rewards must be a numpy array' assert type(env_infos) == dict, 'env_infos must be a dictionary' assert type(agent_infos) == dict, 'agent_infos must be a dictionary...
magicoder
python
You are working on a constrained device that communicates using the CoAP (Constrained Application Protocol) and need to implement a function to handle CoAP options. The CoAP options are encoded in a compact manner, and you need to parse the option details from the received buffer. The code snippet provided is part of ...
```c #include <stdio.h> #include <stdint.h> #define kOption1ByteExtension 13 void parseCoapOptions(const uint8_t* buf, size_t bufSize) { size_t offset = 0; while (offset < bufSize) { uint8_t optionLength = buf[offset] & 0x0f; offset += sizeof(uint8_t); if (optionLength == 13) { ...
magicoder
c
You are tasked with creating a Python function that parses a given file to extract the license information. The license information is typically found within a file's comments and includes details such as the copyright holder, license type, and any additional notes. Your function should be able to identify and extract ...
```python import re def extract_license_info(file_path: str) -> dict: with open(file_path, 'r') as file: content = file.read() # Regular expression to match the license information pattern = r'(?<=Copyright\s\().*?(?=\))|(?<=This file is licensed under the ).*?(?=\n)|(?<=# ).*?(?=\n)' matches ...
magicoder
python
You are tasked with implementing a property validation library in PHP. The library should allow users to define validation rules for various properties of objects. The validation rules should cover common scenarios such as required fields, minimum and maximum values, string length, and custom validation functions. You...
```php namespace PropertyValidator; class PropertyValidator { private $rules = []; public function addRule(string $propertyName, string $rule, $value = null) { $this->rules[$propertyName][] = ['rule' => $rule, 'value' => $value]; } public function validate(object $object): array { $er...
magicoder
php
You are tasked with creating a command-line interface (CLI) tool for setting up pipelines for Unity projects. The tool should support various options and parameters to customize the pipeline setup based on the user's requirements. Your task is to implement a function or method that parses the command-line arguments an...
```csharp using System; using System.Collections.Generic; public class UnityPipelineSetup { public void SetupPipeline(string[] args) { // Parse the command-line arguments and options Dictionary<string, string> options = ParseCommandLineArgs(args); // Check for the presence of specific ...
magicoder
csharp
You are tasked with simulating a simplified workflow engine that processes a series of activities and gateways. The engine is represented by the given code snippet, which includes the creation of a pipeline, runtime, and engine, followed by the execution of the pipeline and subsequent actions. Your goal is to implement...
```python def determine_next_activity(pipeline, eg_id, act_executed_id): # Extract the relevant information from the pipeline data activities = pipeline["activities"] incoming_relationships = {} for activity_id, activity_data in activities.items(): incoming_relationships[activity_id] = activity_...
magicoder
python
You are tasked with analyzing a dataset containing information about different machine learning models' performance on various datasets. The dataset is represented as a pandas DataFrame `df` with the following columns: "m" (model type), "ds" (dataset), and "tech" (technology used). Your goal is to write a Python funct...
```python import pandas as pd def calculate_average_performance(df): performance_mapping = { "d2h1": "Prediction", "d2h2": "Fairness", "d2h3": "Overall" } average_performance = {} for ds in df["ds"].unique(): for m in ["d2h1", "d2h2", "d2h3"]: model_type = p...
magicoder
python
You are tasked with implementing a custom math library for embedded systems that only support 32-bit floating-point operations. The library should include the functions `cosf32` and `tanf32`, which calculate the cosine and tangent of a given angle in radians, respectively. However, due to the limited resources of the e...
```c #include <stdint.h> typedef float float32; #define PI 3.14159265358979323846f inline float32 cosf32(const float32 value) { // Reduce the angle to the range [-π, π] float32 angle = value; while (angle > PI) { angle -= 2 * PI; } while (angle < -PI) { angle += 2 * PI; } ...
magicoder
c
You are tasked with implementing a script that processes symbolic links in a given directory. Your script should identify all symbolic links and determine their target paths. Write a Bash script that takes a directory path as an argument and outputs the symbolic links within that directory along with their correspond...
```bash #!/bin/bash function resolve_link() { local target=$1 local resolved=$(readlink -f "$target") if [ -h "$resolved" ]; then resolve_link "$resolved" else echo "$target -> $resolved" fi } if [ $# -ne 1 ]; then echo "Usage: $0 <directory>" exit 1 fi directory=$1 if [ ! -d "$directory" ]; t...
magicoder
shell
You are tasked with creating a function that processes a list of scene transition events in a mobile app. Each event is represented by a string containing the event type and the scene name. The function should return a dictionary containing the count of each event type for each scene. If a scene has no events of a cert...
```swift func processSceneEvents(_ events: [String]) -> [String: [String: Int]] { var eventCounts: [String: [String: Int]] = [:] for event in events { let components = event.components(separatedBy: ",") if components.count == 2 { let eventType = components[0] let sceneNa...
magicoder
swift
You are tasked with creating a function that processes a given HTML snippet to extract specific information. The HTML snippet represents a card element displaying a pending "Provide Help" request in a financial system. The snippet contains the amount of the pending request in Nigerian Naira (NGN) and some descriptive t...
```javascript function extractPendingRequestInfo(htmlSnippet) { const parser = new DOMParser(); const doc = parser.parseFromString(htmlSnippet, 'text/html'); const status = doc.querySelector('.card-title').textContent.trim(); const currencySymbol = doc.querySelector('.text-primary').textContent.tri...
magicoder
javascript
You are tasked with implementing a simple event handling system for a graphical application. The application has a window with a key press function that triggers an action when a key is pressed. Your goal is to create a class that manages the key press events and their associated actions. You are given a partial code ...
```cpp #include <iostream> #include <unordered_map> #include <functional> class Window { public: void GetSize(int& width, int& height) { // Implementation to get window size } void SetKeyPressFunction(std::function<void(int, int, int, int)> keyPressFunction) { // Implementation to set key p...
magicoder
cpp
You are tasked with creating a Python script that generates a configuration file for Supervisor, a process control system. The configuration file should include specific settings and environment variables for running a Python application under Supervisor. The configuration file should have the following properties: - ...
```python def generate_supervisor_config(): config_content = """autostart=true autorestart=true user=pythonapp environment=VIRTUAL_ENV="/home/pythonapp/miniconda/envs/app-env/",PATH="/opt/app/tutorial/google_cloud/sinewave/env/bin",\ HOME="/home/pythonapp",USER="root" stdout_logfile=syslog stderr_logfile=syslog...
magicoder
python
You are tasked with implementing a Python class that performs fuzzy string matching using the Levenshtein distance algorithm. The Levenshtein distance between two strings is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other. You need to ...
```python import Levenshtein class _fuzzymatchLevenshteinDistance(action._action): checkString = str() matchString = str() matchAboveScore = int() def run(self, data, persistentData, actionResult): # Calculate the Levenshtein distance between checkString and matchString distance = Leve...
magicoder
python
You are tasked with implementing a game scoring system. The game has a concept of frames and a score that increases based on the duration of gameplay. The game has a function `Render()` that is called to update the game display. Your task is to write a function that calculates the score based on the given rules. You a...
```c void CalculateScore(GameInstance* instance) { instance->frames++; instance->currentSecond++; if (instance->currentSecond == 60 && instance->gameState == isGamePlay) { instance->score++; instance->currentSecond = 0; } Render(); } ``` The `CalculateScore` function increments the `...
magicoder
c
You are tasked with creating a Python function that retrieves the number of stars for a given GitHub repository and the version of a specified package from the PyPI repository. You will need to use the GitHub API to fetch the number of stars for the repository and the PyPI API to retrieve the version of the package. C...
```python import requests def fetch_repo_info(repo_name, package_name): # Fetching GitHub repository info github_url = f"https://api.github.com/repos/{repo_name}" github_response = requests.get(github_url) github_data = github_response.json() stars_count = github_data['stargazers_count'] # Fet...
magicoder
python