query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a function that extracts the conversation name from a given data structure and then calculates the anchor point for a context menu based on the provided coordinates.
You are given the following code snippet as a reference:
```javascript
<p>
{getConversationName(conversation)}
</p>
... | ```javascript
function calculateAnchorPoint(conversation, anchorPoint) {
// Assuming some calculations are performed here to determine the updated anchor point
// For the purpose of this example, the original anchor point is returned as is
return { x: anchorPoint.x, y: anchorPoint.y };
}
``` | magicoder | javascript |
You are given a 4x4 matrix represented as a 1D array of 16 elements. The matrix represents a perspective projection transformation in computer graphics. The elements of the array are arranged in row-major order. The matrix is defined as follows:
```
| (right+left)/(right-left) (top+bottom)/(top-bottom) -(far+near)/(... | ```python
from typing import List
def perspective_projection_matrix(arr: List[float]) -> List[List[float]]:
matrix = [[0 for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
matrix[i][j] = arr[i*4 + j]
return matrix
``` | magicoder | python |
You are tasked with implementing a function to open a sub-directory within a given directory using the provided code snippet as a reference. The function should handle the directory opening and manipulation of the path based on the given input.
Write a function `openSubDirectory` that takes three parameters:
1. `dirPr... | ```rust
use std::path::{Path, PathBuf};
struct IOUtil;
impl IOUtil {
fn open_directory(parent_dir: &Path, sub_dir: &Path) -> Result<PathBuf, std::io::Error> {
// Implementation for opening a sub-directory
// This implementation may involve error handling and actual directory opening operations
... | magicoder | rust |
You are tasked with implementing a template tag system for a web application. The `TemplateTag` class provides two static methods, `test` and `test2`, which will be used to define template tags. The template tag system should accept a variable passed in from the template as the first argument, and additional arguments ... | ```javascript
class TemplateTagSystem {
constructor() {
this.tags = {};
}
registerTag(tagName, callback) {
this.tags[tagName] = callback;
}
render(template, data) {
let renderedTemplate = template;
for (const tag in this.tags) {
const regex = new RegExp(... | magicoder | javascript |
You are tasked with implementing a Python class that can parse a given text input into a specific data structure. The input text consists of multiple lines, each containing a fixed number of items separated by spaces. Your goal is to create a parser that can extract and organize these items into a structured format.
Y... | ```python
from typing import List, NamedTuple
class LinearParser:
def __init__(self, lines: List[List[str]]):
self.lines = lines
@classmethod
def from_string(cls, text: str):
lines = text.strip().split('\n')[1:] # Extract lines from the input text
parsed_lines = [line.split() for ... | magicoder | python |
You are tasked with creating a Python program that utilizes the Turtle graphics library to draw a specific geometric shape. The program should prompt the user to input the number of sides for the shape and then use the Turtle library to draw the corresponding polygon. Additionally, the program should calculate and disp... | ```python
import turtle
# Function to draw a polygon with n sides
def draw_polygon(n):
t = turtle.Turtle()
angle = 360 / n
for _ in range(n):
t.forward(100) # Assuming side length as 100
t.left(angle)
# Function to calculate the interior angle of a polygon with n sides
def calculate_inter... | magicoder | python |
You are tasked with implementing a function to parse XML data from a file and extract specific information. The XML data contains various tags and attributes, and your goal is to retrieve the value of a specific tag based on certain conditions.
You are given a Rust code snippet that demonstrates the initial steps of p... | ```rust
use roxmltree::Node;
use std::path::Path;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum CustomError {
#[error("File reading error: {0}")]
FileReadingError(#[from] std::io::Error),
#[error("XML parsing error: {0}")]
XmlParsingError(#[from] roxmltree::Error),
#[error("Tag not found: ... | magicoder | rust |
You are working on a project management tool that integrates with various Git services such as GitHub and BitBucket. Your task is to implement a function to refresh the access token for a given Git service using a provided refresh token. The function should return the new access token and handle any errors that may occ... | ```swift
enum GitService {
case GitHub
case BitBucket
}
struct ProjectAuthenticator {
var accessToken: String
}
enum ErrorType: Error {
case refreshTokenExpired
case networkError
case invalidResponse
}
typealias ParamKey = String
typealias SecretFromResponseParams = String
class ProjectManag... | magicoder | swift |
You are tasked with creating a script to automate the deployment of a Hyperledger Fabric chaincode using Docker and the Hyperledger Fabric CLI. The chaincode is written in Node.js and needs to be installed on the peer node with specific parameters.
The command to be executed is as follows:
```
docker exec cli peer cha... | Here's a sample solution in Bash to generate and execute the specified command with dynamic input for the chaincode parameters:
```bash
#!/bin/bash
# Input parameters
chaincode_name="tradenet"
chaincode_version="1"
chaincode_path="/opt/gopath/src/github.com/trade-ts"
chaincode_language="node"
# Construct the command... | magicoder | shell |
You are tasked with implementing a function that processes a list of managed schema ARNs and returns a paginated response. The function should handle the pagination by utilizing a token-based approach. The input and output keys for the pagination tokens are provided, along with a logger and event loop for asynchronous ... | ```swift
func paginateManagedSchemaArns(managedSchemaArns: [String], nextToken: String?) -> ([String], String?) {
// Simulate asynchronous processing using event loop
let eventLoop = EventLoop()
// Simulate processing the managedSchemaArns based on the nextToken
let pageSize = 10
let startIndex... | magicoder | swift |
You are tasked with creating a Python web application that manages tasks using Flask. Your goal is to implement a task management system that allows users to create, retrieve, update, and delete tasks. To achieve this, you need to define a blueprint for the task-related routes and integrate it into the Flask applicatio... | ```python
from flask import Flask, jsonify, request
from tasks import task_bp
app = Flask(__name__)
tasks = []
@task_bp.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify(tasks)
@task_bp.route('/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
for task in tasks:
if task['i... | magicoder | python |
You are tasked with implementing a function to parse a symbol table in a 64-bit ELF (Executable and Linkable Format) binary file. The symbol table is represented by the `symtab` variable, and the parsing function is `parse_sym64`. The function takes three arguments: `data`, `symtabsh`, and `strtabsh`. The `data` parame... | ```python
def parse_sym64(data, symtabsh, strtabsh):
symtab = []
if symtabsh['sh_size'] == 0:
return symtab
sym_offset = symtabsh['sh_offset']
sym_entry_size = symtabsh['sh_entsize']
sym_count = symtabsh['sh_size'] // sym_entry_size
str_offset = strtabsh['sh_offset']
for i in rang... | magicoder | python |
You are tasked with implementing a function to generate a mathematical problem based on a given difficulty level. The function should take the difficulty level as input and return a `Problem` object containing the question text and the expected answer.
The `generateProblem` function is provided with the following sign... | ```swift
// Define the ProblemDifficulty enum
enum ProblemDifficulty {
case easy, medium, hard
}
// Define the MathSymbols enum
enum MathSymbols: String {
case times = "×"
func padded(with padding: String) -> String {
return padding + self.rawValue + padding
}
}
// Define the Problem stru... | magicoder | swift |
You are tasked with implementing a function that processes and renders 3D meshes based on the given code snippet. The code snippet is part of a larger rendering system and represents the rendering pipeline for a deferred rendering technique. Your task is to create a function that performs a specific operation on the 3D... | ```cpp
void MDeferredRenderWork::DrawNormalMesh(MRenderInfo& info)
{
for (MMaterialGroup& group : info.vMaterialRenderGroup)
{
// Perform rendering operations for each material group
// Example: Set shader parameters, draw meshes, etc.
info.pRenderer->SetShaderParamSet(info.pPrimaryComma... | magicoder | cpp |
You are tasked with implementing a binding helper class in C# that facilitates the binding of properties between two objects. The binding helper should allow for the synchronization of properties between the source and target objects, ensuring that changes in one object are reflected in the other. Your task is to creat... | ```csharp
using System;
using System.Collections.Generic;
public class BindingHelper
{
private readonly Dictionary<string, string> bindings = new Dictionary<string, string>();
private readonly object source;
private readonly object target;
public BindingHelper(object source, object target)
{
... | magicoder | csharp |
You are tasked with creating a Python function that calculates the range of a symbolic variable using the Z3 theorem prover library. The Z3 library is commonly used for solving constraints arising from program analysis, verification, and other related tasks. Your function should take a symbolic variable and a boolean f... | ```python
from z3 import *
def calculate_range(sym, upper):
s = Solver()
s.add(sym) # Add the symbolic variable to the solver
if upper:
s.add(Not(sym <= sym)) # Add constraint for upper bound
else:
s.add(Not(sym >= sym)) # Add constraint for lower bound
if s.check() == sat:
... | magicoder | python |
You are tasked with implementing a custom hit testing method for a subclass of `UIScrollView` in a Swift iOS application. The goal is to modify the behavior of the hit testing process to allow only the subview `tableView` to respond to touch events, while preventing the underlying `scrollView` from intercepting these e... | ```swift
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// Perform hit testing to determine the view at the given point
let hitView = super.hitTest(point, with: event)
// Check if the hit view is the underlying scrollView
if hitView == self {
// If the hit view i... | magicoder | swift |
You are tasked with creating a Python class that can store and manage system facts related to sysctl variables. The sysctl command in Unix-like operating systems is used to view, set, and manage kernel parameters at runtime. Your task is to implement a class that can store sysctl variable names and their corresponding ... | ```python
from leapp.models import Model, fields
from leapp.topics import SystemFactsTopic
class SysctlVariable(Model):
topic = SystemFactsTopic
name = fields.String()
value = fields.String()
class SysctlVariablesFacts(Model):
topic = SystemFactsTopic
```
The solution provides the implementation of ... | magicoder | python |
You are given a simplified assembly-like language with the following instructions:
- `cpy x y`: Copies the value of register or integer `x` into register `y`.
- `inc x`: Increases the value of register `x` by 1.
- `dec x`: Decreases the value of register `x` by 1.
- `mul x y z`: Multiplies the values in registers `x` a... | ```python
from typing import List, Dict
def get_value(param: str, r: Dict[str, int]) -> int:
if param.isdigit() or (param[0] == '-' and param[1:].isdigit()):
return int(param)
else:
return r[param]
def execute_instructions(insts: List[List[str]]) -> Dict[str, int]:
r = {chr(i): 0 for i in ... | magicoder | python |
You are tasked with creating a Rust program that interacts with the Bodhi service, a system for managing updates to Fedora. The program should retrieve a list of usernames from the Bodhi service and display them in a specific format.
Your task is to complete the `main` function to achieve the following:
1. Use the `bo... | ```rust
use bodhi::{BodhiServiceBuilder, UserNameQuery};
fn main() -> Result<(), String> {
// construct bodhi client for the production instance
let bodhi = BodhiServiceBuilder::default().build().map_err(|err| format!("Failed to build Bodhi service: {}", err))?;
// Query the Bodhi service to retrieve a li... | magicoder | rust |
You are tasked with implementing a Python function to generate a Bitcoin address from a given private key. Bitcoin addresses are derived from the public key, which in turn is derived from the private key using elliptic curve cryptography. The code snippet provided gives a glimpse of this process, where a private key is... | ```python
from cryptography.hazmat.primitives.asymmetric import ec
from hashlib import sha256, new
import base58
def generate_bitcoin_address(private_key):
# Generate the public key from the private key
public_key = point_to_public_key(private_key.public_key().public_numbers(), compressed=True)
# Conv... | magicoder | python |
You are tasked with creating a Python program to simulate a simplified version of the classic game "Rock, Paper, Scissors." The program should prompt the user to input their choice (rock, paper, or scissors) and then randomly generate a choice for the computer. The program should then determine the winner based on the ... | ```python
import random
# Prompt the user to input their choice
player_choice = input("Enter your choice (rock, paper, or scissors): ").lower()
# Map the player's choice to an integer value
choices_map = {'rock': 0, 'paper': 1, 'scissors': 2}
player = choices_map.get(player_choice, -1) # -1 represents an invalid cho... | magicoder | python |
You are tasked with implementing a Python class that represents a Pet. The class should have the following properties and methods:
Properties:
1. `id`: An integer representing the unique identifier of the pet.
Methods:
1. `__init__(self, name: str, age: int)`: Constructor method that initializes the name and age of t... | ```python
class Pet:
_id_counter = 0 # Class-level variable to keep track of the unique identifier
def __init__(self, name: str, age: int):
self._name = name
self._age = age
self._id = Pet._id_counter # Assign the current id
Pet._id_counter += 1 # Increment the id counter for... | magicoder | python |
You are tasked with creating a TypeScript type decorator for a Vuex store in a Vue.js application. The decorator should be able to infer the types of various commit and dispatch functions within the store and apply them to the respective modules.
Given the code snippet provided, you need to create a type decorator tha... | ```typescript
type BaseModuleDecorator<TCommit, TDispatch> = {
commit: TCommit;
dispatch: TDispatch;
};
// Example usage
type DecoratedModule = BaseModuleDecorator<
typeof store.commit.createPair,
typeof store.commit.removeLiquidity,
typeof store.commit.rewards,
typeof store.dispatch.prices,
typeof store... | magicoder | typescript |
You are tasked with creating a Python function that processes and summarizes growth observations from a dataset. The function should take a list of records as input and perform the following tasks:
1. Summarize and pivot the growth observations based on the week and attribute.
2. Add dimension calculations to the summa... | ```python
def process_growth_observations(recs):
import pandas as pd
# Create a DataFrame from the input records
df = pd.DataFrame(recs)
# Summarize and pivot the growth observations based on the week and attribute
summarized_data = df.pivot_table(index='week', columns='attribute', values='value',... | magicoder | python |
You are tasked with implementing a retry mechanism for sending XML data to a specified IP address. The `enviar` method takes two parameters: a string `xml` representing the XML data to be sent and a string `ip` representing the destination IP address. The method attempts to send the XML data using the `enviarAux` metho... | ```java
public class XmlSender {
private static final int MAX_RETRIES = 5;
private static final int RETRY_DELAY_MS = 1000; // 1 second delay between retries
public void enviar(String xml, String ip) {
int envio = 0;
while (envio < MAX_RETRIES) {
try {
envio++;
... | magicoder | java |
You are tasked with implementing a module for a smoke basin simulation system. The module should handle the calculation and management of smoke dispersion within a basin. The system is designed to model the behavior of smoke particles in a controlled environment.
Your task is to create a function within the `day9_smok... | ```rust
pub fn calculate_smoke_dispersion(
basin_dimensions: (f64, f64, f64),
initial_positions: Vec<(f64, f64, f64)>,
initial_velocities: Vec<(f64, f64, f64)>,
time_interval: f64
) -> Vec<(f64, f64, f64)> {
let mut final_positions = Vec::new();
for i in 0..initial_positions.len() {
... | magicoder | rust |
You are tasked with implementing a class that reads input from a file and provides a method to retrieve the next input as an (offset, line) tuple. The class has an internal state to keep track of whether it has iterated through the input file and handles a special case where it may need to skip reading the first line.
... | ```python
class InputReader:
def __init__(self, blob_reader):
self._blob_reader = blob_reader
self._has_iterated = False
self._read_before_start = True
def next(self):
"""Returns the next input from as an (offset, line) tuple."""
if self._read_before_start:
s... | magicoder | python |
You are tasked with creating a Python class that simulates a network device and its user management system. The class should be able to handle commands, manage user accounts, and verify the state of the device.
Your task is to implement the `Device` class with the following requirements:
- The `Device` class should ha... | ```python
import re
class Device:
def __init__(self, host, port, protocol, log_level, mock):
self.host = host
self.port = port
self.protocol = protocol
self.log_level = log_level
self.mock = mock
self.users = {}
def open(self):
# Simulate opening a conne... | magicoder | python |
You are tasked with implementing a Python function that performs a specific operation on a given input. The function is intended to extend the functionality of a neural network layer for a non-separable 2D complex-valued non-negative symmetric overcomplete lapped transform (Nsolt). The layer is designed to concatenate ... | ```python
import numpy as np
def concatenate_channels(input_tensor: np.ndarray) -> np.ndarray:
nSamples, nRows, nCols, nChsTotal = input_tensor.shape
concatenated_tensor = np.concatenate((input_tensor[:, :, :, :-1], input_tensor[:, :, :, -1][:, :, np.newaxis]), axis=-1)
return concatenated_tensor
``` | magicoder | python |
You are tasked with implementing a class that manages user login information in a web application. The class should handle various properties and methods related to user authentication.
Your task is to create a C# class named `UserLoginManager` that includes the following functionalities:
1. A private field `loginPro... | ```csharp
public class UserLoginManager
{
private string loginProviderName;
private string providerUserKey;
private ApplicationUser user;
private Int32 id;
public UserLoginManager()
{
id = 0; // Initialize ID to a default value
}
public Int32 ID => id; // Read-only property acc... | magicoder | csharp |
You are tasked with implementing a class for handling cryptographic operations in a software system. The class, named `CryptoHandler`, is responsible for managing encryption and decryption using various parameters and plugins. The provided code snippet is a part of the `CryptoHandler` class's method that processes a re... | ```cpp
#include <iostream>
#include <string>
// Define the CryptoHandler class
class CryptoHandler {
private:
std::string m_key;
std::string m_blockMode;
std::string m_padding;
std::string m_authenticationData;
std::string m_customParameters;
std::string m_cryptoPluginName;
public:
// Cons... | magicoder | cpp |
You are tasked with creating a function that simulates a secure login system. The function should take a username and password as input and return a boolean value indicating whether the login was successful or not. Additionally, the function should have a built-in mechanism to prevent brute force attacks by locking out... | ```python
import math
# Dictionary to store failed login attempts for each username
failed_attempts = {}
def protectedLog(x):
try:
return math.log(x)
except ValueError:
return 1
def login(username, password):
if username in failed_attempts and failed_attempts[username] >= 3:
retur... | magicoder | python |
You are tasked with analyzing a set of route definitions in a Laravel application. The given code snippet contains route definitions for users and companies in the application. Each route is associated with a specific controller method and has a unique name.
Your task is to write a function that takes the route defini... | ```php
function extractControllerMethods($routes) {
$controllerMethods = [];
foreach ($routes as $route) {
$controllerMethod = $route['controller'];
if (!in_array($controllerMethod, $controllerMethods)) {
$controllerMethods[] = $controllerMethod;
}
}
return $controlle... | magicoder | php |
You are working on a PHP application that involves processing user data. You have a class `User` with various setter methods to set different user attributes. The code snippet provided demonstrates how the `User` object's attributes are being set based on the data array passed to it.
Your task is to implement a functi... | ```php
class User {
private $userId;
private $userName;
private $isContractor;
public function setUserId($userId) {
$this->userId = $userId;
}
public function setUserName($userName) {
$this->userName = $userName;
}
public function setIsContractor($isContractor) {
... | magicoder | php |
You are tasked with implementing a Python package that provides a route service for a transportation application. The package includes a module named `service`, which contains a class called `RouteService`. The `RouteService` class is responsible for handling route-related functionalities such as finding the shortest p... | ```python
# service.py
class RouteService:
def __init__(self, graph):
self.graph = graph
def calculate_shortest_path(self, start, end):
distances = {node: float('inf') for node in self.graph}
distances[start] = 0
unvisited_nodes = set(self.graph)
while unvisited_nodes:
... | magicoder | python |
You are tasked with creating a function that will parse a given Swift code snippet and extract all the appearance customization calls made to the `UITableView` class. The function should return a list of tuples, where each tuple contains the method name and the color parameter passed to it. The appearance customization... | ```swift
func extractTableViewAppearanceCustomizations(from code: String) -> [(String, String)] {
var customizations: [(String, String)] = []
let lines = code.components(separatedBy: .newlines)
for line in lines {
if line.contains("UITableView.appearance()") {
if let methodCall = li... | magicoder | swift |
You are tasked with implementing a function that processes a string containing a PHP docblock comment and extracts the parameter name and type. The docblock comment follows the PHPDoc standard format and includes a description, parameter name, and type. Your function should parse the input string and return the paramet... | ```php
function parseDocBlock(string $docBlock): array {
$matches = [];
preg_match('/@param\s+(\w+)\s+\$(\w+)/', $docBlock, $matches);
return [$matches[2] => $matches[1]];
}
// Test the function with the provided example
$docBlock = "/**\n * Set poidtotal\n *\n * @param string \$poidtotal\n */";
$result = ... | magicoder | php |
You are tasked with implementing a Union-Find data structure, also known as Disjoint Set Union (DSU), which supports two operations: union and find. The union operation merges two sets, while the find operation determines whether two elements belong to the same set.
You are given a Python code snippet that contains as... | ```python
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
root_x = self.find(x)
... | magicoder | python |
You are given the definition of a TreeNode class and a function `inorderTraversal` that takes a pointer to the root of a binary tree and returns a vector containing the inorder traversal of the tree. The TreeNode class is defined as follows:
```cpp
class TreeNode {
public:
int val;
TreeNode* left;
TreeNode... | ```cpp
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> s;
TreeNode* current = root;
while (current != nullptr || !s.empty()) {
while (current != nullptr) {
s.push(current);
current = current->left;
}
current = s.top();
... | magicoder | cpp |
You are tasked with implementing a rate-limiting mechanism for an API endpoint in a Django web application. The application should allow customization of the rate-limiting parameters through the Django settings. The rate-limiting mechanism should restrict the number of requests made with the same key within a specified... | ```python
import time
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def rate_limit_request(key: str) -> bool:
lifetime = getattr(settings, 'DJANGOLG_LIFETIME', 300)
max_requests = getattr(settings, 'DJANGOLG_MAX_REQUESTS', 20)
recaptcha_on = getattr(settings, 'DJA... | magicoder | python |
You are given a sequence of numbers representing the partial sums of a series. The sequence starts with the first term, and each subsequent term is the sum of all the previous terms plus the next term in the series. For example, given the series 1, 2, 3, 4, the partial sums would be 1, 3, 6, 10. Your task is to write a... | ```python
from typing import List
def findOriginalSeries(partial_sums: List[float]) -> List[float]:
n = len(partial_sums)
original_series = [partial_sums[0]]
for i in range(1, n):
original_series.append(partial_sums[i] - partial_sums[i-1])
return original_series
``` | magicoder | python |
You are given a snippet of HTML code that represents the end of a web page. Your task is to write a function that can determine if the HTML code is properly formatted and closed. The function should return true if the HTML tags are properly closed and nested, and false if they are not.
The HTML code snippet is as foll... | ```python
def isHTMLProperlyClosed(htmlCode: str) -> bool:
stack = []
for line in htmlCode.split('\n'):
line = line.strip()
if line.startswith('</'):
if not stack or stack[-1] != line:
return False
stack.pop()
elif line.startswith('<'):
... | magicoder | python |
You are tasked with implementing a hot module replacement (HMR) mechanism for a web application. HMR allows for the replacement of modules in a running application without a full reload, enabling developers to see the changes instantly during development.
Your goal is to create a function that handles the module repla... | ```javascript
function handleHotModuleReplacement(module, createApp, appElement, require) {
if (module.hot) {
module.hot.accept("./components/App", () => {
console.log("hot module reload");
const NextApp = require<{ App: typeof App }>("./components/App").App;
ReactDOM.render(createApp(NextApp), ... | magicoder | javascript |
You are tasked with creating a shell script that processes command-line arguments to set configuration variables based on the provided input. The script should handle two different cases: one where the input starts with "file:" and another where it starts with "/". In the "file:" case, the script should set the CFG_URL... | ```bash
#!/bin/bash
case $1 in
file:/*)
CFG_URL=$2
CFG_INDEX=$3
;;
/*)
CFG_URL=$1
CFG_INDEX=$2
;;
*)
echo "Invalid input format"
exit 1
;;
esac
echo "CFG_URL: $CFG_URL"
echo "CFG_INDEX: $CFG_INDEX"
```
The script uses a `case` statement to handle the different input formats.... | magicoder | shell |
You are tasked with implementing a user token cache system for a web application. The user token cache system should record access to user tokens and provide a mechanism to retrieve and update the access records. The access records will be used for monitoring and analyzing user token usage patterns.
You are provided w... | ```javascript
// UserTokenCache module implementation
class UserTokenCache {
constructor() {
this.accessRecords = [];
}
// Method to record access to user tokens
recordAccess() {
const accessRecord = {
timestamp: new Date(),
userId: getCurrentUserId(), // Assume a function getCurrentUserId(... | magicoder | javascript |
You are given two strings `x` and `y`, and an integer `k`. Your task is to write a function or method to determine whether it is possible to transform string `x` into string `y` by performing exactly `k` operations. Each operation involves removing a character from either end of the string, and concatenating the remain... | ```python
def canTransform(x: str, y: str, k: int) -> str:
if len(x) + len(y) <= k:
return "Yes" # It is possible to transform x into y by removing all characters and concatenating them
common_prefix_len = 0
for i in range(min(len(x), len(y))):
if x[i] == y[i]:
common_prefix_le... | magicoder | python |
You are tasked with creating a program to perform support vector machine (SVM) classification on a given dataset using the scikit-learn library in Python. The dataset is loaded from a CSV file and contains features and labels for the classification task.
Your task is to implement a Python program that accomplishes the... | ```python
from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
# Load the dataset from the CSV file
url = "C:/Users/USUARIO/Desktop/Tesis/centroides-Apriori4.csv"
datos = pd.read_csv(url, sep=",")
# Preprocess the dataset
X = datos.iloc[:, :-1] ... | magicoder | python |
You are working on a project that involves processing quaternion data using the PyTorch library. Quaternions are a four-dimensional number system that extends the complex numbers. In this problem, you are required to implement a method to transform quaternion data into a specific format.
You are given a Python class w... | ```python
import torch
class QuaternionProcessor:
@staticmethod
def transform_from_quaternion(quater: torch.Tensor):
# Normalize the quaternion vectors
norm = torch.norm(quater, p=2, dim=1, keepdim=True)
normalized_quater = quater / norm
# Convert normalized quaternions to Eule... | magicoder | python |
You are tasked with implementing a custom data structure called `MemoryQueue` that simulates the behavior of a queue with additional memory suspension capabilities. The `MemoryQueue` should support the following operations:
1. `enqueue(value)`: Add a new element to the end of the queue.
2. `dequeue()`: Remove and retur... | ```java
import java.util.LinkedList;
class MemoryQueue<T> {
private LinkedList<T> queue;
private LinkedList<T> memory;
public MemoryQueue() {
queue = new LinkedList<>();
memory = new LinkedList<>();
}
public void enqueue(T value) {
queue.addLast(value);
}
public T... | magicoder | java |
You are tasked with implementing a command parser for a simple shell-like program. The parser should be able to handle three types of commands: `exec`, `cd`, and `echo`. The `exec` command can also include output redirection using `>>`. The parser should extract the command type, arguments, and output redirection file ... | ```rust
#[derive(Debug, PartialEq)]
enum Action {
Execute(String, Option<String>),
ChangeDirectory(String),
Echo(String),
}
fn command_exec(input: &[char]) -> Result<Action, &'static str> {
let input_str: String = input.iter().collect();
let parts: Vec<&str> = input_str.split_whitespace().collect()... | magicoder | rust |
You are tasked with implementing a simplified version of an interceptor system for handling HTTP requests and responses in a JavaScript application. The provided code snippet includes TypeScript interfaces and a partial implementation of the interceptor system.
Your task is to complete the implementation of the interc... | ```typescript
import InterceptorManager from './InterceptorManager'
interface IAxiosRequestConfig {
// Define the properties for the request configuration
}
interface IAxiosResponse {
// Define the properties for the response
}
interface IAxiosPromise {
// Define the properties for the promise
}
type IFulfill... | magicoder | typescript |
You are given a staircase with n steps. You can climb the staircase by taking either 1 step, 2 steps, or 3 steps at a time. Write a function `countWays` to find the number of distinct ways to reach the top of the staircase.
The function should take an integer `n` as input and return the number of distinct ways to reac... | ```python
def countWays(n):
if n == 0 or n == 1:
return 1
elif n == 2:
return 2
else:
dp = [0] * (n + 1)
dp[0], dp[1], dp[2] = 1, 1, 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]
return dp[n]
# Test the function
print(count... | magicoder | python |
You are tasked with implementing a signal renaming system for a hardware description language (HDL) design. The system should take a list of signals and their corresponding renaming conditions, and generate the renamed signals based on these conditions.
You are given a code snippet that represents a part of the signal... | ```python
def rename_signal(original_signal, renaming_condition, new_name):
# Implement the rename_signal function to apply the renaming condition and generate the renamed signal
# Assume that the original_signal, renaming_condition, and new_name are valid inputs
# Apply the renaming condition to the o... | magicoder | python |
You are tasked with creating a function that calculates the viewport size of a web page. The function should handle scenarios where the viewport size is hard-coded to 0, as is the case with Chrome headless mode. You are given a code snippet that retrieves the viewport size and handles the Chrome headless mode scenario.... | ```javascript
async function calculateViewportSize() {
const calculatedViewportSize = {
width: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
height: Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
};
if (calculatedViewportSize.width > 0 && calculatedView... | magicoder | javascript |
You are tasked with implementing a class to load and manipulate data from an index file. The index file contains information about a dataset, including fields and time information. Your task is to create a class that can load the index file, retrieve the default field and time, and perform validation checks on the load... | ```python
class LoadIdxDataset:
def __init__(self, filename):
self.filename = filename
self.dataset = None
def save(self, filename_idx):
# Implementation to save the index file
pass
def load(self):
# Implementation to load the dataset from the index file
# P... | magicoder | python |
You are tasked with implementing a signal-slot mechanism in C++ similar to the one used in the Qt framework. The signal-slot mechanism allows objects to communicate with each other in a loosely coupled manner. Signals are emitted by objects when certain events occur, and slots are functions that can be connected to the... | ```cpp
#include <functional>
#include <vector>
template <typename... Args>
class Signal {
public:
using SlotFunction = std::function<void(Args...)>;
void connect(SlotFunction slot) {
slots_.push_back(slot);
}
void emit(Args... args) {
for (const auto& slot : slots_) {
slot... | magicoder | cpp |
You are tasked with implementing a VaR (Value at Risk) calculator using the Cornish-Fisher expansion method. VaR is a measure used to assess the potential loss in value of a risky asset or portfolio over a specific time period under normal market conditions. The Cornish-Fisher expansion is a technique used to adjust th... | ```java
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.analysis.FunctionUtils;
import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.analysis.function.Gaussian;
public class CornishFisherVaRCalculator {
private static final doub... | magicoder | java |
You are tasked with creating a Python function that reads a PDF file and sends it as a document in response to a message, while also providing a custom keyboard for the user to interact with. You are given a code snippet that partially accomplishes this task using the `open` function to read the PDF file and the `answe... | ```python
import telebot # Assuming telebot library is used for the messaging functionality
async def send_pdf_with_keyboard(file_path: str, message: str, keyboard_type: str) -> None:
with open(file_path, 'rb') as file:
# Assuming 'bot' is the telebot instance
await bot.answer_document(file, messa... | magicoder | python |
You are tasked with implementing a function that parses a nested object structure and returns an array of all the field names present in the object. Each field name is represented by a path that includes all the keys leading to the field. For example, in the given code snippet, the field names would be "subPage.edges.f... | ```javascript
function extractFieldNames(obj, path = []) {
let fieldNames = [];
for (let key in obj) {
if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
fieldNames = fieldNames.concat(extractFieldNames(obj[key], [...path, key]));
} else {
fieldNames.push([...path, key].join('.'));
... | magicoder | javascript |
You are tasked with implementing a custom hash function in Java using the `org.cryptimeleon.math.hash.UniqueByteRepresentable` interface. The `UniqueByteRepresentable` interface is used for objects that can be uniquely represented as a byte array, and it requires the implementation of a method `getUniqueByteRepresentat... | ```java
import org.cryptimeleon.math.hash.UniqueByteRepresentable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class CustomHashFunction implements UniqueByteRepresentable {
private String input;
public CustomHashFunction(String input) {
this.input = input;... | magicoder | java |
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. The program should read the text file, tokenize the words, and then count the occurrences of each word. However, the program should exclude any words that are found within a block comment in the text file.... | ```python
def countWordOccurrences(filePath, wordsToCount):
with open(filePath, 'r') as file:
text = file.read()
in_comment = False
word_counts = {word: 0 for word in wordsToCount}
current_word = ""
for char in text:
if char == '/' and text[text.index(char) + 1] == '*':
... | magicoder | python |
You are tasked with implementing a currency conversion feature for an online donation platform. The platform supports multiple currencies, and the conversion rates are based on the donor's main currency and the creator's preferred currency. The following code snippet is a part of the test suite for this feature:
```py... | ```python
def convert_currency(donor_currency, creator_currency, donation_amount):
# Assume access to a currency conversion API or service to fetch real-time exchange rates
exchange_rate = fetch_exchange_rate(donor_currency, creator_currency)
equivalent_amount = donation_amount * exchange_rate
return ro... | magicoder | python |
You are tasked with implementing a Python decorator that adds safety features to a function. The decorator, `safeThread`, takes two optional arguments: `timeout` and `queue`. When applied to a function, it ensures that the function is executed within a specified time limit and that any exceptions raised during its exec... | ```python
import threading
import queue
import functools
class SafeUtils:
def __init__(self):
self.appQueue = queue.Queue()
def safeThread(self, timeout=None, queue=None):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result_q... | magicoder | python |
You are tasked with implementing a Dijkstra's algorithm to find the shortest path in a weighted graph. The graph is represented using an adjacency list and the algorithm should find the shortest path from a given source node to all other nodes in the graph.
You are given a class `Graph` that represents the weighted gr... | ```java
import java.util.Arrays;
class Graph {
private int V;
private int[][] graph;
public Graph(int vertices) {
V = vertices;
graph = new int[V][V];
}
public void addEdge(int source, int destination, int weight) {
graph[source][destination] = weight;
graph[destin... | magicoder | java |
You are given a list of `file_data`, where each element represents a timestamp in the format "YYYY-MM-DD HH:MM:SS". Additionally, there is a function `get_time_members(data)` that takes a timestamp string as input and returns its individual time components (year, month, day, hour). The code snippet provided iterates th... | ```python
from typing import List, Tuple
def get_time_members(timestamp: str) -> Tuple[int, int, int, int]:
year, month, day = map(int, timestamp.split()[0].split('-'))
hour = int(timestamp.split()[1].split(':')[0])
return year, month, day, hour
def process_file_data(file_data: List[str]) -> List[List[int... | magicoder | python |
You are given a Python code snippet that appears to be part of a larger image processing algorithm. Your task is to create a function that simulates the behavior of the `rot_scale` function and the `cube_collapse` function, as well as the `llsg` function from the `vip` library.
Your function should take in a 3D array... | ```python
import numpy as np
from vip import llsg
def image_processing(cube, angle_list, scale_list, fwhm, rank, asize, n_segments, collapse, imlib, interpolation, nproc):
def rot_scale(mode, cube, residuals_cube, angle_list, scale_list, imlib, interpolation):
# Implement the rotation and scaling logic bas... | magicoder | python |
You are tasked with implementing a class that processes an array of strings. The `ProcessData` method of the class should perform a specific operation on the input array. Your task is to complete the implementation of the `ProcessData` method based on the given requirements.
You are provided with the following code sn... | ```csharp
using System;
using System.Linq;
public class DataProcessor
{
public virtual string ProcessData(string[] dataArray)
{
if (dataArray.Length == 0)
{
throw new ArgumentException("Input array cannot be empty.");
}
if (dataArray.All(s => int.TryParse(s, out _))... | magicoder | csharp |
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 account holder's name and account balance.
Create a Python class `BankAccount` ... | ```python
class BankAccount:
def __init__(self, account_holder, initial_balance=0):
self._account_holder = account_holder
self._balance = initial_balance
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if amount > self._balance:
re... | magicoder | python |
You are tasked with implementing a function that performs arithmetic operations on numbers with varying precision. The precision is defined by the type `Precision`, which can be either `Rational` or `Floating`. For `Rational` precision, the numbers are represented as fractions, while for `Floating` precision, the numbe... | ```rust
use std::ops::Range;
use std::cmp::Ordering;
enum Bound<T> {
Inclusive(T),
Exclusive(T),
}
enum Precision {
Rational {
denominator_range: (u32, u32),
numerator_range: Range<Bound<i32>>,
},
Floating(f64),
}
fn add(left: &Precision, right: &Precision) -> Precision {
matc... | magicoder | rust |
You are tasked with implementing a Tooltip system for a user interface. The Tooltip system should support two types of tooltips: TooltipType and TooltipElementArray. The TooltipType represents a simple tooltip with text content, while the TooltipElementArray represents a more complex tooltip with an array of TooltipEle... | ```csharp
using System;
using System.Collections.Generic;
public class TooltipElement
{
public string Content { get; set; }
// Other properties and methods for TooltipElement
}
public class Tooltip
{
public TooltipType TooltipType { get; set; }
public List<TooltipElement> TooltipElementArray { get; se... | magicoder | csharp |
You are tasked with creating a Python function that processes a list of file paths and returns a dictionary containing the count of unique file extensions present in the list. The function should ignore case sensitivity when comparing file extensions.
Create a function called `count_file_extensions` that takes a list ... | ```python
def count_file_extensions(file_paths):
file_extension_counts = {}
for file_path in file_paths:
file_extension = file_path.split('.')[-1].lower()
file_extension_counts[file_extension] = file_extension_counts.get(file_extension, 0) + 1
return file_extension_counts
# Test the functio... | magicoder | python |
You are tasked with creating a Python script that processes a list of strings and performs specific operations based on the elements in the list. Your script should handle the following operations:
1. If an element in the list is a string, it should be converted to uppercase.
2. If an element in the list is a number, i... | ```python
def process_list(input_list):
processed_list = []
for element in input_list:
if isinstance(element, str):
processed_list.append(element.upper())
elif isinstance(element, int) or isinstance(element, float):
processed_list.append(element ** 2)
elif isinsta... | magicoder | python |
You are tasked with implementing a Python class that represents a 2D transformation matrix and provides methods for rotation and scaling operations. The class should be able to perform a rotation transformation and print the resulting matrix.
Your task is to complete the implementation of the `TransformationMatrix` cl... | ```python
import math
class TransformationMatrix:
def __init__(self, matrix):
self.matrix = matrix
def rotate(self, angle):
radian_angle = math.radians(angle)
rotation_matrix = [
[math.cos(radian_angle), -math.sin(radian_angle)],
[math.sin(radian_angle), math.co... | magicoder | python |
You are tasked with implementing a feature for a car rental app that utilizes iBeacon technology to provide location-based services. The app has a view controller that displays a list of nearby beacons and their corresponding information. The code snippet provided is a part of the view controller's implementation, spec... | ```swift
if error != nil {
// Handle the error condition, e.g., display an error message to the user
print("Error occurred while retrieving beacon data: \(error!.localizedDescription)")
} else {
// Update the cars array with the retrieved beacon data
if let beacons = beacons as? [Beacon] {
self.... | magicoder | swift |
You are tasked with implementing a multi-threaded queue system using C++11's threading and synchronization primitives. The queue should support waiting for a specified amount of time until a condition is met.
Your task is to complete the implementation of the `wait` function in the `Queue` class. The `wait` function t... | ```cpp
void wait(int timeout, std::function<bool()> condition) {
std::unique_lock<std::mutex> lock(mutex);
std::chrono::milliseconds duration(timeout);
if (!condition()) {
if (condition_variable.wait_for(lock, duration, condition)) {
return true;
} else {
return false... | magicoder | cpp |
You are tasked with implementing a concurrent programming problem involving condition variables and synchronization.
You are given a concurrent program that uses condition variables to manage the synchronization of tasks. The code snippet provided is a part of this program. The `state.waiters` is a map containing the... | To solve this problem, you can create a function or method that utilizes the appropriate synchronization primitives to handle the signaling and unblocking of tasks. Here's a possible solution using Rust's standard library and its synchronization primitives:
```rust
use std::sync::{Arc, Mutex, Condvar};
struct State {... | magicoder | rust |
You are tasked with implementing a class that represents a form field in a web application. The class should have the ability to store the field's name, type, and value. Additionally, it should provide a method to render the HTML representation of the form field.
You are given a partial code snippet for the form field... | ```php
class FormField
{
protected $name;
protected $value;
protected $type;
public function __construct($name, $type, $value = null)
{
$this->name = $name;
$this->value = $value;
$this->type = $type;
}
public function render()
{
switch ($this->type) {
... | magicoder | php |
You are tasked with creating a function that processes blog post content based on certain conditions. The function should take a blog post object as input and return the processed content based on the specified rules. The blog post object has the following properties and methods:
- `$post->url($locale)`: Returns the U... | ```php
function processBlogPostContent($post) {
$showFullText = config('binshopsblog.show_full_text_at_list');
if ($showFullText) {
return "<div class='blog-content'>
<h3 class='blog-title'>
<a href='" . $post->url($locale) . "'>" . $post->title . "</a>
... | magicoder | php |
You are tasked with implementing a string manipulation library in Rust. Your task is to create a struct `SysString` that represents a system string and implement several methods for this struct.
The `SysString` struct has a private field `0` of type `BSTR`, which is a pointer to a null-terminated Unicode string. You n... | ```rust
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use winapi::um::oleauto::{SysAllocString, SysStringLen, SysStringByteLen, SysFreeString, BSTR};
struct SysString(BSTR);
impl SysString {
fn new(s: &str) -> SysString {
let wide_chars: Vec<u16> = OsString::from(s).encode_wide().collect... | magicoder | rust |
You are tasked with implementing a function to calculate the error in energy flux computation for a computational fluid dynamics simulation. In the given code snippet, `xp_mom_flux`, `xp_tau`, `vflux`, `discr`, `eos`, `cv`, `grad_cv`, `grad_t`, `efluxerr` are variables related to the simulation. The `viscous_flux` func... | ```python
import numpy as np
def compute_energy_flux_error(vflux_energy, xp_e_flux, norm_type='inf'):
if norm_type == 'inf':
error = np.linalg.norm(vflux_energy - xp_e_flux, np.inf) / np.linalg.norm(xp_e_flux, np.inf)
elif norm_type == '2':
error = np.linalg.norm(vflux_energy - xp_e_flux, 2) / ... | magicoder | python |
You are tasked with implementing a function that simulates a simplified file system mounting operation. The function should take in three parameters: `source` (a string representing the source directory), `dest` (a string representing the destination directory), and `readonly` (a boolean indicating whether the mount sh... | ```rust
use nix::mount;
use nix::mount::MsFlags;
use nix::Error;
use std::fs;
use std::path::Path;
fn mount_directory(source: &str, dest: &str, readonly: bool) -> Result<(), String> {
let dest_path = Path::new(dest);
if dest_path.exists() {
let cloned_dest = dest_path.with_file_name(format!("{}_clone",... | magicoder | rust |
You are given a 2D grid representing a map of a city. Each cell in the grid contains a non-negative integer representing the height of the corresponding building. You are tasked with calculating the total surface area of all the buildings in the city, considering the following conditions:
- The surface area of each bu... | ```python
from typing import List
def calculate_surface_area(grid: List[List[int]]) -> int:
N = len(grid)
ans = 0
for i in range(N):
for j in range(N):
if grid[i][j] == 0:
continue
height = grid[i][j]
ans += 2
for h in range(1, height ... | magicoder | python |
You are tasked with implementing a JSON parser in C++ using the given code snippet as a starting point. The `JsonArrayNode` and `JsonObjectNode` classes are already provided for representing JSON arrays and objects, respectively. The `parse` function takes a JSON string `src` and two function objects `f` and `e`. The `... | ```cpp
#include "JsonArrayNode.hpp"
#include "JsonObjectNode.hpp"
#include <stack>
namespace json {
void parse(std::string src, std::function<void(nodeptr)> f, std::function<void(std::string)> e) {
// Stack to keep track of nested objects and arrays
std::stack<nodeptr> nodeStack;
// Parse ... | magicoder | cpp |
You are tasked with implementing a Python function to calculate the gradient of an image using Sobel Kernels. The function should take an input image and return the gradient image, which represents the gradient orientation of the input image.
You are provided with a code snippet that contains a method `_create_gradien... | ```python
import cv2
import numpy as np
class ImageProcessor:
def __init__(self, canny):
self.canny = canny
self.gradient = self._create_gradient(self.canny)
@staticmethod
def _create_gradient(image):
"""
Convolve an image with Sobel Kernels in X and Y direction to create a... | magicoder | python |
You are tasked with implementing a custom smart pointer in Rust. The smart pointer should behave similarly to a reference-counted pointer, but with the added functionality of tracking the number of times the smart pointer is cloned and dropped. Your task is to implement the necessary traits and methods for the custom s... | ```rust
use std::ops::{Deref, Drop};
struct CustomPointer<T> {
data: T,
clone_count: usize,
drop_count: usize,
}
impl<T> CustomPointer<T> {
fn new(data: T) -> Self {
CustomPointer {
data,
clone_count: 0,
drop_count: 0,
}
}
}
impl<T> Deref for Cu... | magicoder | rust |
You are tasked with creating a program that processes and analyzes data from a large dataset using the MapReduce framework. In this scenario, you are given a Java code snippet that sets the output path for the MapReduce job and waits for its completion.
Your task is to implement the missing parts of the MapReduce prog... | ```java
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org... | magicoder | java |
You are tasked with implementing a user authentication system using Swift and Vapor framework. Your goal is to create a function that authenticates a user's email and password, generates a token for the user if one does not already exist, and saves the token to the database.
You are provided with a code snippet that d... | ```swift
func authenticateUser(email: String, password: String) throws {
guard let user = try User.makeQuery().filter(User.Field.email, email).first() else { throw invalidCredentials }
if try BCryptHasher().verify(password: password, matches: user.password) {
if try user.token() == nil {
... | magicoder | swift |
You are tasked with implementing a function that calculates the number of unique paths in a grid. The grid is represented as a 2D matrix, and the goal is to move from the top-left corner to the bottom-right corner. You can only move down or right at any point in time. The dimensions of the grid are given as a tuple `in... | ```python
def unique_paths(input_shape):
m, n = input_shape
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[m-1][n-1]
```
The `unique_paths` function initializes a 2D array `dp` with all elements set to 1. T... | magicoder | python |
You are working on a project that involves training a deep learning model for semantic segmentation using the Cityscapes dataset. The dataset contains images of urban street scenes with pixel-level annotations for various classes such as road, sidewalk, car, pedestrian, etc. Your task is to create a Python function tha... | ```python
def preprocess_data(image_dir: str, annotation_dir: str, batch_size: int) -> DataLoader:
# Load Cityscapes dataset
cityscapes_dataset = cityscapes.Cityscapes(image_dir, annotation_dir)
# Create data loader
data_loader = DataLoader(cityscapes_dataset, batch_size=batch_size, shuffle=True)
... | magicoder | python |
You are tasked with implementing a Python function that calculates the average score for a given set of students based on their performance in a series of tests. The function should take in a dictionary containing the test scores for each student and return a new dictionary with the average score for each student. Addi... | ```python
from statistics import mean, median, mode
def calculate_average_scores(scores, average_type='mean'):
average_functions = {
'mean': mean,
'median': median,
'mode': mode
}
average_func = average_functions.get(average_type, mean)
average_scores = {}
for student, sco... | magicoder | python |
You are tasked with implementing a Python function that generates a random graph with a specified number of nodes and edges. The graph will be represented using the `graph` module, and the function will add nodes and random edges to the graph.
You are given the following code snippet as a starting point:
```python
# ... | ```python
# Solution
def generate(graph, num_nodes, num_edges, weight_range=(1, 1)):
"""
Add nodes and random edges to the graph.
Parameters:
graph (graph.Graph): The graph to which nodes and edges will be added.
num_nodes (int): The number of nodes to add to the graph.
num_edges (int): The num... | magicoder | python |
You are tasked with creating a program that can efficiently parse and analyze file paths to extract specific information. Your program should be able to handle various file path formats and extract relevant details from them.
Write a function `parseFilePath` that takes a file path as input and returns the repository n... | ```javascript
function parseFilePath(filePath) {
const parts = filePath.split('/');
const repository = parts.slice(0, parts.length - 1).join('/');
const command = parts[parts.length - 1];
return {
repository,
command
};
}
// Test the function
const filePath = "vimc/montagu-webapps/node_modules/mocha-... | magicoder | javascript |
You are given a code snippet that involves the use of the FEniCS library for finite element computations in Python. Your task is to create a function that performs a specific operation related to finite element computations and then use this function to solve a given problem.
Write a Python function `n1curl_1_canonica... | ```python
from dolfin import *
def n1curl_1_canonical_projection(f, mesh, quad_degree):
# Create a FunctionSpace V on the given mesh using the "N1curl" element of degree 1
V = FunctionSpace(mesh, "N1curl", 1)
# Create a Function u in the FunctionSpace V
u = Function(V)
# Permute the average edge ... | magicoder | python |
You are tasked with creating a Java program that simulates a simple drawing application using JavaFX. The application should allow the user to draw basic shapes on a canvas and provide functionality to clear the canvas. Your task is to implement the `DrawingApplication` class with the following requirements:
1. The `D... | ```java
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.stage.Stage;
public class DrawingApplication extends Application {
@Override
public void start(Stage primaryStage) {... | magicoder | java |
You are tasked with creating a program that parses and extracts information from a software license header. The license header is a comment block at the beginning of a source code file, and it contains important information such as the copyright holder, contact information, and the license under which the software is d... | ```python
import re
def extract_license_info(source_code):
license_info = {}
match = re.search(r'/\*([^*]|(\*+[^*/]))*\*/', source_code, re.MULTILINE)
if match:
header = match.group()
copyright = re.search(r'Copyright \(C\) (\d+) (.+)', header)
contact = re.search(r'Contact: (.+) \(... | magicoder | python |
You are tasked with creating a PHP class that manages a simple log system for a web application. The class should allow for logging messages with different levels of severity and provide a method to retrieve the log entries based on the severity level. Additionally, the class should be able to set a date flag for the l... | ```php
<?php
namespace GoFunCrm;
class LogManager
{
private $logs = [];
private $dateFlag = 'off';
public function log($message, $severity)
{
$this->logs[] = [
'message' => $message,
'severity' => $severity,
'timestamp' => date('Y-m-d H:i:s'),
];
... | magicoder | php |
You are tasked with implementing a function that calculates the area of the largest rectangle that can be formed within a given binary matrix. The matrix consists of 0s and 1s, where 1 represents a filled cell and 0 represents an empty cell. The function should take the matrix as input and return the area of the larges... | ```python
def largestRectangleArea(matrix):
def largestRectangleAreaHistogram(heights):
stack = []
max_area = 0
i = 0
while i < len(heights):
if not stack or heights[i] >= heights[stack[-1]]:
stack.append(i)
i += 1
else:
... | magicoder | python |
You are working on a file processing system that involves extracting parent folder names from a given file path. The provided code snippet is a part of a Python script that uses a custom class `GetRecipeParentFolderName` to execute the file processing logic. The script sets environment variables to store the output var... | ```python
import os
def get_parent_folder_name(file_path: str) -> str:
# Normalize the file path to handle both Unix and Windows formats
normalized_path = os.path.normpath(file_path)
# Extract the parent folder name using the os.path.basename function
parent_folder_name = os.path.basename(os.path.... | magicoder | python |
You are given the definition of a binary tree node and two functions related to binary trees. The definition of the binary tree node is as follows:
```cpp
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
```
The two functions are a... | ```cpp
bool areLeafValuesSame(TreeNode* root1, TreeNode* root2) {
auto getLeafValue = [](TreeNode* root) -> std::vector<int> {
std::vector<int> result;
if (root) {
if (root->left == nullptr && root->right == nullptr) {
result.push_back(root->val);
} else {
... | magicoder | cpp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.