query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a custom decorator in TypeScript to automatically map properties of a class to a specified model. The decorator should iterate through the properties of the class and map them to the corresponding properties of the specified model. Your task is to create the `@AutoMap()` decorator and a... | ```typescript
function AutoMap() {
return function (target: any) {
const original = new target();
const keys = Object.keys(original);
keys.forEach((key) => {
Object.defineProperty(target.prototype, key, {
get: function () {
return original[key];
},
set: function (va... | magicoder | typescript |
You are tasked with implementing a function to calculate the implied volatility of a financial option using the Newton-Raphson method. Implied volatility is a crucial parameter in option pricing models, representing the market's expectation of future volatility. The function `implied_vol` takes three parameters: a call... | ```python
def implied_vol(func: Callable, price: float, kwargs: dict):
# Define the function for which we want to find the root
def f(volatility):
return func(volatility, **kwargs) - price
# Initial guess for implied volatility
initial_guess = 0.5
# Tolerance for convergence
tol = 1e-6... | magicoder | python |
You are tasked with implementing a coroutine manager in a game development framework. The manager should be able to start, stop, and check the status of coroutines. A coroutine is a function that can suspend its execution, allowing other code to run before resuming. Your task is to create a class that manages coroutine... | ```java
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class CoroutineManager {
private Map<String, Thread> runningCoroutines;
public CoroutineManager() {
runningCoroutines = new HashMap<>();
}
public String startCoroutine(Runnable coroutine) {
String id... | magicoder | java |
You are tasked with creating a Python function that processes a list of GitHub repository names and their star counts and returns a filtered list of repositories based on the star count range provided. Additionally, the function should import specific modules from the Django framework and define a view function that in... | ```python
def filter_repositories(repositories, star_range):
min_star, max_star = map(int, star_range.split('-'))
filtered_repositories = [(name, stars) for name, stars in repositories if min_star <= stars <= max_star]
return filtered_repositories
# Django view function incorporating the required modules
f... | magicoder | python |
You are tasked with implementing a class that simulates a web link checker. The class, `MustlWebLink`, has a method `Tick` that is responsible for checking the status of a web link at regular intervals. The method should perform the following tasks:
1. Send an HTTP request to the web link.
2. Receive the HTTP response ... | ```cpp
#include <iostream>
#include <chrono>
#include <ctime>
#include <curl/curl.h>
class MustlWebLink {
public:
void Tick() {
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com");
res =... | magicoder | cpp |
You are tasked with implementing a generic interface for converting between two types of objects. The interface, `IConverter<TSource, TDestination>`, has two methods: `Convert` and `ConvertBack`. The `Convert` method takes an object of type `TSource` and returns an object of type `TDestination`, while the `ConvertBack`... | ```csharp
namespace Application.Converters.Board
{
public class StickerContentConverter : IConverter<StickerContentRecord, StickerContent>
{
public StickerContent Convert(StickerContentRecord source)
{
return new StickerContent(source.Text, source.TimeTable);
}
publi... | magicoder | csharp |
You are tasked with implementing a class mapping system for pickled classes in Python. Pickling is the process of converting a Python object into a byte stream, and unpickling is the reverse process of reconstructing the original object from the byte stream. In this problem, you need to create a class that manages mapp... | ```python
class ClassMapper:
def __init__(self):
self.mapping = {}
def add_mapping(self, source_module, source_class, target_module, target_class):
self.mapping[(source_module, source_class)] = (target_module, target_class)
def get_mapping(self, source_module, source_class):
return... | magicoder | python |
You are tasked with creating a Python program to manage a contact list. The program should allow users to add, delete, and retrieve contacts. You are given a partial implementation of the program, along with a test function that checks the functionality of deleting all contacts.
Your task is to complete the implementa... | ```python
class Contact:
def __init__(self, first_name, last_name, nickname, email, birthdate, phone_number):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.email = email
self.birthdate = birthdate
self.phone_number = phone_numbe... | magicoder | python |
You are working on a machine learning project and need to automate the generation of configuration files for training different models. The code snippet provided is a part of a Python script that replaces placeholders in a template file with specific values and then saves the modified template to a new file.
The place... | ```python
import os
def generate_config_file(template_path, saving_dir, this_filename, d, l, b_n, b_s, sch):
with open(template_path, 'r') as f:
this_tmpl = f.read()
this_tmpl = this_tmpl.replace('@dropout', str(d)).replace('@lr', str(l))
this_tmpl = this_tmpl.replace('@batchnorm', str(b_n)).repla... | magicoder | python |
You are tasked with creating a test suite for a software project management tool. The tool is designed to check for conflicts between the requirements of different projects. Your task is to implement a test suite that ensures the functionality of the conflict detection feature.
You are provided with a Python code snip... | ```python
import unittest
class ConflictDetectionTest(unittest.TestCase):
def setUp(self):
# Initialize resources for the test cases
pass
def tearDown(self):
# Clean up any resources after the test cases have been executed
pass
def test_conflicting_requirements_detected(se... | magicoder | python |
You are tasked with implementing a serial port management system for a software application. The system should handle the allocation and release of serial ports used for communication with external devices. The provided code snippet is a part of this system and is responsible for releasing a serial port when it is no l... | ```python
class SerialPortManager:
def __init__(self):
self.serial_in_use_list = []
self.serial_monitor_dict = {} # Assuming this dictionary is used to store monitoring objects for each serial port
def allocate_serial_port(self, view_name):
serial_port = view_name.split('-')[1].strip()... | magicoder | python |
You are tasked with creating a Python program to manage user messages and replies in a database. You will need to define a class `UserMessage` that represents a user message and its corresponding reply in a database. The class should have the following attributes and methods:
Attributes:
- `message_id`: A unique ident... | ```python
class UserMessage:
def __init__(self, message_id, user_id, message_content, reply_content):
self.message_id = message_id
self.user_id = user_id
self.message_content = message_content
self.reply_content = reply_content
def save_to_db(self):
# Implementation to s... | magicoder | python |
You are tasked with implementing a VapourSynth plugin for image processing. The plugin should include functions for performing various image enhancement operations using different algorithms. Your goal is to create a function that applies the znedi3 algorithm to an input clip, with the option to specify parameters for ... | ```python
def znedi3_rpow2(clip, rfactor, correct_shift="zimg", nsize=0, nns=3, qual=None, etype=None, pscrn=None, opt=None, int16_prescreener=None, int16_predictor=None, exp=None):
import vapoursynth as vs
core = vs.get_core()
def edi(clip, field, dh):
return core.znedi3.nnedi3(clip=clip, field=fi... | magicoder | python |
You are tasked with implementing a file search function that recursively finds all files within a given directory and its subdirectories. You need to write a Python function `find_files` that takes a directory path as input and returns a list of all the file paths within that directory and its subdirectories.
For exam... | ```python
import os
def find_files(directory):
file_paths = []
for root, _, files in os.walk(directory):
for file in files:
file_paths.append(os.path.join(root, file))
return file_paths
```
The `find_files` function uses the `os.walk` method to traverse the directory tree and collect al... | magicoder | python |
You are tasked with implementing a Python function that manages the creation and deletion of DynamoDB tables. The function should handle potential errors and ensure that the table creation occurs after a specified delay following the deletion. Your task is to complete the implementation of the `manage_dynamodb_table` f... | ```python
import time
import boto3
def manage_dynamodb_table(table_name, attribute_definitions, key_schema, provisioned_throughput):
"""
Manages the creation and deletion of a DynamoDB table.
Args:
table_name (str): The name of the DynamoDB table.
attribute_definitions (list): A list of dictionari... | magicoder | python |
You are tasked with implementing a function that calculates the number of grapheme clusters in a given string. A grapheme cluster is a set of individual characters that are displayed as a single unit and may consist of multiple code points. For example, a grapheme cluster can include a base character and one or more co... | ```java
public int countGraphemeClusters(String input) {
int codePointIndex = 0;
int graphemeClusterCount = 0;
while (codePointIndex < input.length()) {
int codePoint = input.codePointAt(codePointIndex);
codePointIndex += Character.charCount(codePoint);
graphemeClusterCount++;
}
... | magicoder | java |
You are tasked with creating a Python function that interacts with a hypothetical OneView client to manage datacenters. The OneView client provides methods to retrieve, update, and search for datacenters. Your task is to implement a function that performs the following operations:
1. Retrieve a datacenter by its URI a... | ```python
def manage_datacenter(oneview_client):
# Retrieve a datacenter by its URI
datacenter = oneview_client.datacenters.get(datacenter_added['uri'])
print("\nGet Datacenter by URI: retrieved '{name}' successfully\n".format(**datacenter))
# Update the Datacenter
datacenter['name'] = "New Datacen... | magicoder | python |
You are tasked with implementing a password generator for a decryption tool. The decryption tool is represented by the `unpacker` class, and the password generator is a subclass called `unpacker_hoge`. The `make_pw` method in the `unpacker_hoge` class is responsible for setting the decryption password. Your task is to ... | ```python
import re
import sys
from unpacker import unpacker
from cli import cli
import random
import string
class unpacker_hoge(unpacker):
def make_pw(self) -> None:
"""
復号用パスワードを設定する
"""
pw:str = ""
while True:
pw = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(random.ran... | magicoder | python |
You are given a function that generates Pascal's triangle up to a given number of rows. Pascal's triangle is a triangular array of binomial coefficients, where each number is the sum of the two directly above it. The first few rows of Pascal's triangle look like this:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
You... | ```python
from typing import List
def generate_pascals_triangle(num_rows: int) -> List[List[int]]:
result = []
for i in range(num_rows):
temp = [1]
if i > 0:
for j in range(1, i):
temp.append(result[-1][j-1] + result[-1][j])
temp.append(1)
result.... | magicoder | python |
You are tasked with implementing a class that represents a computer processor. The processor can operate in two different performance modes: "high" and "ultra". The class should allow setting the performance mode and executing tasks based on the current mode.
The class should have the following methods:
1. `set_perfo... | ```python
class Processor:
HIGH = 'high'
ULTRA = 'ultra'
def __init__(self):
self.performance_mode = None
def set_performance_mode(self, mode):
if mode in (self.HIGH, self.ULTRA):
self.performance_mode = mode
else:
raise ValueError("Invalid performance m... | magicoder | python |
You are tasked with implementing a Bluetooth device management system for a mobile application. The system should handle the connection and disconnection of Bluetooth headsets and provide information about the connected devices.
You are given a code snippet from the existing system, which includes a method to update t... | ```java
public class BluetoothDeviceManager {
private static final String TAG = "BluetoothDeviceManager";
// Existing code snippet for updating the connected Bluetooth device
public void updateDevice() {
Log.d(TAG, "updateDevice");
List<BluetoothDevice> devices = bluetoothHeadset.getConnect... | magicoder | java |
You are tasked with implementing a Python class method for securing Real-Time Control Protocol (RTCP) packets. The method should take an RTCP packet as input and return a protected version of the packet. Additionally, the method should handle specific error cases by raising appropriate exceptions.
You are provided wit... | ```python
class Policy:
SSRC_ANY_OUTBOUND = "ssrc_any_outbound"
def __init__(self, key):
self.key = key
class Session:
def __init__(self, policy):
self.policy = policy
def protect_rtcp(self, packet):
if not isinstance(packet, bytes):
raise TypeError("packet must be... | magicoder | python |
You are given a 2D board of lowercase English letters and a word. You need to determine if the word exists in the board. The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once i... | ```python
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def dfs(board, word, i, j, k):
if not (0 <= i < len(board) and 0 <= j < len(board[0]) and board[i][j] == word[k]):
return False
if k == len(word) - 1:
... | magicoder | python |
You are tasked with implementing a user authentication system in Python using object-oriented programming. The provided code snippet defines a class `Object` that serves as the base for an authentication provider system. The class has an attribute `users` which is a dictionary mapping user IDs to user objects.
Your ta... | ```python
import typing as t
class User:
def __init__(self, user_id: str, password: str):
self.user_id = user_id
self.password = password
class Object:
def __init__(self):
self.users: t.Dict[str, User] = {}
class UserAuthentication(Object):
def add_user(self, user_id: str, user_ob... | magicoder | python |
You are tasked with implementing a function that processes a nested list of strings and returns a flattened list of unique strings. The input list may contain nested sublists, and the function should recursively flatten the list and return only unique strings in the flattened list.
You are given the following code sni... | ```python
def flatten_unique_strings(nested_list):
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(flatten_unique_strings(item))
else:
flattened.append(item)
return list(set(flattened))
```
The `flatten_unique_strings` function rec... | magicoder | python |
You are given a list of variables representing numbers in the format "numX = Y", where X is a digit and Y is an integer. Your task is to write a Python function that takes this list of variables and returns the sum of all the numbers represented by these variables.
For example, given the following list of variables:
`... | ```python
from typing import List
def sum_variable_numbers(variables: List[str]) -> int:
total_sum = 0
for var in variables:
num = int(globals()[var])
total_sum += num
return total_sum
``` | magicoder | python |
You are tasked with implementing a class method for a deep learning framework. The method `grad` is responsible for computing the gradients of a given input `x` with respect to the loss function, while the method `loss_cuda` is responsible for computing the loss function itself using CUDA for parallel processing. Your ... | ```python
import torch
class DeepLearningFramework:
def grad(self, x, labels):
# Compute gradients using autograd in PyTorch
x_tensor = torch.tensor(x, requires_grad=True)
loss = self._compute_loss(x_tensor, labels)
loss.backward()
gradients = x_tensor.grad
return gr... | magicoder | python |
You are tasked with implementing a Python class that represents a form with various fields. The form class should have the ability to add fields of different types such as text, number, and date. Each field should have a name and a type, and the form should be able to validate the input for each field type.
Your task ... | ```python
import datetime
class Form:
def __init__(self):
self.fields = []
def add_text_field(self, name):
self.fields.append({"name": name, "type": "text"})
def add_number_field(self, name):
self.fields.append({"name": name, "type": "number"})
def add_date_field(self, name):... | magicoder | python |
You are tasked with creating a script to automate the deployment process for a Django web application. The deployment process involves running specific commands to collect static files, perform database migrations, and start the Gunicorn server. Your script should execute these commands in the correct order and handle ... | ```python
import subprocess
def execute_command(command):
try:
subprocess.run(command, shell=True, check=True)
except subprocess.CalledProcessError as e:
print(f"Error executing command: {command}")
print(f"Command returned non-zero exit status: {e.returncode}")
print(f"Command ... | magicoder | python |
You are tasked with implementing a simple asynchronous task management system. The system should allow clients to submit tasks for execution and then wait until all tasks are completed before proceeding. You are provided with a code snippet that represents the client-side code for submitting a task and waiting for its ... | ```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TaskManager {
private ExecutorService executorService;
private int totalTasks;
private int completedTasks;
public TaskManager() {
this.executorService = Executors.newCachedThreadPool();
... | magicoder | java |
You are tasked with implementing a Unicode scalar property checker for emoji modifiers in Swift. Unicode defines various properties for characters, and one such property is `Emoji_Modifier_Base`, which indicates whether a scalar is one whose appearance can be modified by a subsequent emoji modifier.
Your task is to im... | ```swift
func isEmojiModifierBase(_ scalar: Unicode.Scalar) -> Bool {
let propertyValue = getProperty(of: scalar, named: "Emoji_Modifier_Base")
return propertyValue
}
func getProperty(of scalar: Unicode.Scalar, named propertyName: String) -> Bool {
// Simulated implementation to retrieve Unicode scalar pro... | magicoder | swift |
You are tasked with creating a Python function that extracts information from an HTML page using BeautifulSoup library. The function should take a URL as input, fetch the HTML content, and then extract the title, description, and snippet from the page using the provided code snippet as a reference.
The function signat... | ```python
import requests
import bs4
def extract_info(url: str) -> dict:
res = requests.get(url)
soup = bs4.BeautifulSoup(res.text, 'lxml')
title = soup.select('h1')[0].text.strip()
description = '\n'.join([p.text for p in soup.select('#section-overview p')])
snippet = soup.select('h1 + p')[0].te... | magicoder | python |
You are tasked with creating a program that generates a nested grid of subplots using Matplotlib's GridSpec. The program should allow the user to specify the number of rows and columns for the outer grid, as well as the number of rows and columns for each inner grid. Each subplot should display a unique index or label ... | ```python
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def create_nested_subplots(outer_rows, outer_cols, inner_rows, inner_cols):
fig = plt.figure()
outer_gs = gridspec.GridSpec(outer_rows, outer_cols, figure=fig)
for i in range(outer_rows):
for j in range(outer_cols):
... | magicoder | python |
You are tasked with implementing a function to calculate the end time of the current backup window and the start time of the next backup window. The function should take a string representing the current window and a maximum time difference as input and return the end time of the current window and the start time of th... | ```python
from datetime import datetime, timedelta
class BackupWindow:
@staticmethod
def get_window_edges(windowstr, MAX_DELTA=timedelta(hours=25)):
# Split the window string into start and end times
start_str, end_str = windowstr.split('-')
# Convert start and end times to dat... | magicoder | python |
You are tasked with implementing a custom serialization and deserialization mechanism for a specific data structure. The data structure is a class called `ExactMatcher` which has two properties: `serialise_matched_reference` and `serialise_reference`. Your goal is to create methods to serialize an instance of `ExactMat... | ```python
class ExactMatcher:
def __init__(self, serialise_reference, serialise_matched_reference):
self.serialise_reference = serialise_reference
self.serialise_matched_reference = serialise_matched_reference
def serialize(self):
matched_references = ','.join(self.serialise_matched_ref... | magicoder | python |
You are tasked with implementing a Python class method that processes and returns a dictionary containing specific data related to molecular fragments and their connections. The method takes in various data structures and performs operations to extract and remap certain elements before constructing the final dictionary... | ```python
class MolecularProcessor:
def process_data(self, p_start, p_end, r_start, r_end):
self.rec['rec_loaded'][rec_idx] = 1
p_mask = self.frag['frag_remapped'][p_start:p_end]
r_mask = self.rec['rec_remapped'][r_start:r_end]
return {
'p_coords': p_coords,
... | magicoder | python |
You are working on a scientific computing library and need to implement functions for calculating the complementary error function (erfc), the natural logarithm of the absolute value of the gamma function (lgamma), and the gamma function itself (tgamma). These functions are commonly used in statistical and mathematical... | ```python
import math
def erfc(x):
return 1 - math.erf(x)
def lgamma(x):
return math.lgamma(x)[0]
def tgamma(x):
return math.gamma(x)
```
In the solution, the math module in Python is utilized to implement the erfc, lgamma, and tgamma functions. The erfc function uses the math.erf function to calculate ... | magicoder | python |
You are tasked with creating a Python function that simulates a simple file system operation. Your function should take in a list of commands and execute them to manipulate a file system. Each command in the list represents a file system operation. The commands can be one of the following types:
1. `mkdir <directory_na... | ```python
def simulate_file_system(commands):
file_system = {}
def mkdir(directory_name):
file_system[directory_name] = []
def touch(file_name):
current_directory = file_system.get('current', [])
current_directory.append(file_name)
file_system['current'] = current_directory... | magicoder | python |
You are tasked with implementing a function that calculates the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1. For example, the first few terms of the Fibonacci sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21, and s... | ```python
def even_fibonacci_sum(limit):
a, b = 0, 1
total_sum = 0
while b <= limit:
if b % 2 == 0:
total_sum += b
a, b = b, a + b
return total_sum
```
The `even_fibonacci_sum` function initializes variables `a` and `b` to 0 and 1, respectively. It then iterates through the F... | magicoder | python |
You are tasked with implementing a function to parse and extract data from a JSON structure representing information about faces and persons. The JSON structure contains nested objects and arrays, and the goal is to extract specific data fields and store them in a structured format.
You are given a code snippet that d... | ```cpp
#include <iostream>
#include <string>
#include <json/json.h>
struct FacePose {
float pitch = 0.0f;
float roll = 0.0f;
float yaw = 0.0f;
};
struct FaceInfo {
long completeness = 0;
long faceNumber = 0;
FacePose pose;
};
struct PersonInfo {
std::string personNumber;
};
struct Parsed... | magicoder | cpp |
You are tasked with creating a Python class that performs XML validation against a given XML schema. Your task is to implement the `XMLValidator` class with the following specifications:
1. The class should have a method named `validate` that takes two parameters:
- `schema_path`: A string representing the file pat... | ```python
from lxml import etree
class XMLValidator:
def validate(self, schema_path, target_path):
try:
xsd_doc = etree.parse(schema_path)
xsd = etree.XMLSchema(xsd_doc)
xml = etree.parse(target_path)
passed = xsd.validate(xml)
return ValidationRe... | magicoder | python |
You are tasked with creating a Python function that generates a sequence of events based on a given frequency and batch size. The function should take two parameters: `every_nth` (the frequency of events) and `n` (the batch size). The function should return a 2D NumPy array representing the events, where each row corre... | ```python
import numpy as np
def generate_events(every_nth, n):
# Create some simple data of evenly spaced events recurring every_nth step
# Each is on (time, batch)-format
events = np.array([np.array(range(n)) for _ in range(every_nth)])
return events
# Test the function
every_nth = 3
n = 4
result = ... | magicoder | python |
You are tasked with implementing a class in C++ that serves as a delegate for a chooser bubble UI view. The delegate class will be responsible for handling user interactions and events related to the chooser bubble UI. The provided code snippet outlines the declaration of the delegate class and its constructor, copy co... | ```cpp
class ChooserBubbleUiViewDelegate {
public:
// Constructor
ChooserBubbleUiViewDelegate(Browser* browser, content::WebContents* web_contents, std::unique_ptr<permissions::ChooserController> chooser_controller)
: browser_(browser), web_contents_(web_contents), chooser_controller_(std::move(chooser... | magicoder | cpp |
You are tasked with implementing a custom error handling mechanism for asynchronous operations using Python's `asyncio` library. Your goal is to create a function that takes in a list of `asyncio.Future` objects and a default value, and returns the result of the first successful future or the default value if all futur... | ```python
import asyncio
_no_value = object()
def handle_async_futures(futures, default=_no_value):
first_future = None # Initialize first_future variable
for future in futures:
try:
result = future.result() # Get the result of the future
return result # Return the result if... | magicoder | python |
You are tasked with creating a program to analyze the availability of months in a given year. The program should take a list of months and years as input and output the years along with the available months for each year.
Write a function `analyzeAvailability` that takes a list of `Month` objects as input and returns ... | ```python
from typing import List, Dict
class Month:
def __init__(self, year: int, month: str):
self.year = year
self.month = month
def analyzeAvailability(months: List[Month]) -> Dict[int, List[str]]:
availability = {}
for month in months:
if month.year in availability:
... | magicoder | python |
You are tasked with creating a script to automate the installation of Elasticsearch on a Unix-based system. The script should extract a specified release of Elasticsearch, organize its files, and set appropriate permissions. Below are the specific requirements for the script:
1. Set the `SHARE_DIR` variable to the def... | ```bash
#!/bin/bash
# Set default value for SHARE_DIR if not already set
SHARE_DIR=${SHARE_DIR:-/usr/share/elasticsearch}
# Specify the directory for extracting the Elasticsearch release
BUILD_DIR=/path/to/build/directory
# Specify the release file to be extracted
TARGET_RELEASE=elasticsearch-1.7.2.tar.gz
# Specify... | magicoder | shell |
You are tasked with implementing a function that validates and processes snowflake IDs. Snowflake IDs are 64-bit unique IDs commonly used in distributed systems. The snowflake ID is composed of a timestamp, a worker ID, and a sequence number. The timestamp is the number of milliseconds since a custom epoch, the worker ... | ```python
import datetime
def process_snowflake(snowflake: int) -> dict:
if not isinstance(snowflake, int) or snowflake < 0 or snowflake > 9223372036854775807:
raise ValueError("Invalid snowflake ID provided.")
timestamp = (snowflake >> 22) + 1609459200000 # Custom epoch (January 1, 2021)
timesta... | magicoder | python |
You are tasked with implementing a custom caching system using an unordered map in C++. The cache should have a maximum capacity and support two operations: get and put. The get operation retrieves the value associated with a given key, and the put operation inserts or updates the value associated with a given key. Whe... | ```cpp
#include <unordered_map>
#include <list>
#include <utility>
using namespace std;
class LRUCache {
private:
int capacity;
unordered_map<int, pair<int, list<int>::iterator>> cache;
list<int> lru;
public:
LRUCache(int capacity) : capacity(capacity) {}
int get(int key) {
if (cache.find... | magicoder | cpp |
You are tasked with implementing a Python class for serializing and deserializing custom data types using a binary stream. The class should support writing and reading data to and from a stream in a specific format.
You are given a code snippet that demonstrates writing data to a stream using the `StreamIO` class. The... | ```python
class Tag:
def __init__(self, tag_type, elements):
self.tag_type = tag_type
self.elements = elements
def serialize(self, stream):
StreamIO.write_ubyte(stream, self.tag_type.TYPE_ID)
StreamIO.write_int(stream, len(self.elements))
for element in self.elements:
... | magicoder | python |
You are tasked with creating a Python function that processes a configuration file and extracts specific information from it. The configuration file is in YAML format and contains nested fields and keys. Your function should load the configuration file, iterate through its contents, and identify certain binary flags wi... | ```python
from typing import List
import yaml
def extract_binary_flags(config_file: str) -> List[str]:
binary_flags = []
with open(config_file, 'r') as file:
config = yaml.safe_load(file)
if 'fairseq' in config:
fairseq_section = config['fairseq']
for key, value in fairs... | magicoder | python |
You are tasked with implementing a secure user authorization service for a project management system backend. The service should use Argon2 hashing for password storage and validation. You are provided with a partial code snippet from the `AuthorizeService.cs` file, which includes the necessary imports and a partial cl... | ```csharp
using Isopoh.Cryptography.Argon2;
using Microsoft.Extensions.Configuration;
using project_manage_system_backend.Dtos;
using project_manage_system_backend.Models;
using project_manage_system_backend.Shares;
using System;
using System.Linq;
using System.Net.Http;
namespace project_manage_system_backend.Service... | magicoder | csharp |
You are tasked with implementing a function that simulates a simple packing algorithm for a rectangular canvas. The canvas is represented as a 2D grid of cells, where each cell can be either empty or occupied. The packing algorithm should place a given set of rectangular objects onto the canvas, ensuring that they do n... | ```python
def pack_canvas(canvas, objects):
def is_valid_position(x, y, width, height):
for i in range(x, x + width):
for j in range(y, y + height):
if i < 0 or i >= len(canvas) or j < 0 or j >= len(canvas[0]) or canvas[i][j] == 1:
return False
return ... | magicoder | python |
You are given the layout of a town represented by 100 houses in a row. Each house is numbered from 1 to 100. The police want to ensure the safety of the town by monitoring the houses. They have a limited capacity to monitor houses, and each police officer can monitor a range of x houses on either side of their position... | ```python
def safe_houses(T, cases):
result = []
for case in cases:
M, x, y, criminals = case
monitored_houses = [0] * 101 # Initialize an array to represent the houses being monitored
for criminal in criminals:
start = max(1, criminal - x * y) # Calculate the start of the ... | magicoder | python |
You are tasked with implementing a custom string interpolation method in Python. The goal is to create a class that supports the `__mod__` method, which will allow for string interpolation using a specific format. The `__mod__` method should take either a single `_FormatArg` or an iterable of `_FormatArg` objects and r... | ```python
from typing import Union, Iterable
class CustomStringInterpolation:
def __init__(self, value: bytes):
self.value = value
def __mod__(self, other: Union[_FormatArg, Iterable[_FormatArg]]) -> bytes:
if isinstance(other, _FormatArg):
return self.value % other # Perform stri... | magicoder | python |
You are tasked with implementing a server-side processing feature for a web application that utilizes DataTables, a popular jQuery plugin for creating interactive and feature-rich tables. The server-side processing involves handling and processing the parameters sent from the client-side DataTables plugin to efficientl... | ```python
def process_data_tables_request(params: dict) -> dict:
# Simulating database query and data retrieval
# Replace this with actual database query and data retrieval logic
total_records = 100 # Total number of records in the database table
filtered_records = 20 # Number of records after applyin... | magicoder | python |
You are tasked with implementing a custom line iterator in Rust that reads lines from a file using the `LineReader` struct and returns them as `Rc<String>`. The `RcLineIterator` struct has been partially implemented, and your goal is to complete the implementation by defining the necessary methods.
Your task is to imp... | ```rust
use std::io::{BufRead, Read};
use std::rc::Rc;
struct LineReader<TRead: Read> {
// Implementation details not shown
}
pub struct RcLineIterator<TRead: Read> {
line_reader: LineReader<TRead>,
buffer: Vec<Rc<String>>,
}
impl<TRead: Read> RcLineIterator<TRead> {
pub fn new(reader: TRead) -> RcLi... | magicoder | rust |
You are tasked with implementing a simple register-based I/O interface for a microcontroller. The provided code snippet is a part of a Rust program that defines a register for controlling an endpoint in a USB communication system. Your task is to create a Rust module that manages the endpoint control registers and prov... | ```rust
pub struct EndpointControl;
impl crate::Readable for EndpointControl {
#[doc = "`read()` method returns `R` reader structure"]
fn read(&self) -> R {
// Implement the logic to read from the endpoint control register
// Return the reader structure `R`
}
}
impl crate::Writable for End... | magicoder | rust |
You are tasked with implementing a Python class that manages localization and translation for a software application. The class should provide methods for setting localization parameters, retrieving translations, and extracting context information from the call stack.
Your task is to complete the implementation of the... | ```python
import gettext
import sys
class LocalizationManager:
def __init__(self, gettext_args):
self._gettext_args = gettext_args
def _default_localedir(self):
# Implement this method to return the default directory for localization files
return '/path/to/default/locale'
def _loc... | magicoder | python |
You are tasked with creating a Python class that simulates a simple banking system. The class should have the following functionalities:
1. Initialize with a bank name and an empty customer list.
2. Allow the addition of new customers with their initial balance.
3. Enable deposits and withdrawals for existing customers... | ```python
class Bank:
def __init__(self, bank_name):
self.bank_name = bank_name
self.customers = {}
def add_customer(self, customer_name, initial_balance):
if customer_name not in self.customers:
self.customers[customer_name] = initial_balance
else:
print... | magicoder | python |
You are tasked with implementing a Python class to manage a table of contents (TOC) for a legal document. The TOC will contain sections, appendices, and sub-labels, each with their own unique identifiers and properties. Your task is to create a class that can add, remove, and display these elements in a structured mann... | ```python
class TableOfContents:
def __init__(self):
self.sections = {}
self.appendices = {}
def add_section(self, section_id, label, sub_label):
self.sections[section_id] = {'label': label, 'sub_label': sub_label}
def add_appendix(self, section_id, label, sub_label, is_first_appen... | magicoder | python |
You are working on a project that involves loading machine learning models and performing text preprocessing using the Keras library. Your task is to create a Python function that takes a list of strings and performs one-hot encoding on the text data. Additionally, you need to load a pre-trained Keras model from a spec... | ```python
import os
import ctypes
import keras
from keras.preprocessing.text import one_hot
from numpy import array
import numpy as np
def load_and_predict_text_model(text_data):
# Perform one-hot encoding on the input text data
vocab_size = 10000 # Example vocabulary size
encoded_text = [one_hot(text, vo... | magicoder | python |
You are working as a DevOps engineer for a software development company. Your team is responsible for managing the deployment process of various applications using Docker containers. As part of the deployment pipeline, you need to automate the building and pushing of Docker images to a container registry. The company f... | ```python
import subprocess
def build_and_push_docker_image(org_name, app_name, version, dockerfile_path):
image_tag = f"{org_name}/{app_name}:{version}"
# Build the Docker image
build_command = f"docker build -t {image_tag} -f {dockerfile_path} ."
build_process = subprocess.Popen(build_command, s... | magicoder | python |
You are tasked with implementing a custom error handling system for a text formatting library in Rust. The provided code snippet shows the import of error-related modules from the library. Your task is to create a custom error type and implement the necessary traits to enable error handling within the library.
Your cu... | ```rust
use std::fmt;
// Define the custom error type
#[derive(Debug)]
enum FormatError {
ConfigurationError,
ErrorCode(u32),
}
// Implement the Display trait for FormatError
impl fmt::Display for FormatError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
FormatE... | magicoder | rust |
You are tasked with implementing a 3D octree data structure to efficiently store and query spatial data. An octree is a tree data structure in which each internal node has exactly eight children, corresponding to the eight octants of 3D space. Each node represents a cubic region of space, and the tree recursively subdi... | ```rust
impl Octree {
fn new(boundary: Boundary, capacity: usize) -> Self {
Octree {
boundary,
capacity,
points: Vec::new(),
children: None,
}
}
fn insert(&mut self, point: Point) {
if !self.boundary.contains_point(&point) {
... | magicoder | rust |
You are tasked with creating a program that extracts subject lines from sender names in real email messages using regular expressions. The program should take a real email message file as input and output the extracted subject lines along with their corresponding sender names.
Your task is to write a Python program th... | ```python
import re
def extract_subject_sender(input_file):
with open(input_file, 'r') as file:
lines = file.readlines()
for i in range(0, len(lines), 2):
sender_name = lines[i].strip()
subject_line = lines[i + 1].strip()
print(f"Sender: {sender_name}")
print(f"Subject:... | magicoder | python |
You are tasked with implementing a Python class that represents a data structure for tracking changes made to a dictionary. The class should support the following operations:
1. `add_item(key, value)`: Add a new key-value pair to the dictionary and record this action.
2. `remove_item(key)`: Remove a key-value pair fro... | ```python
class ChangeTracker:
def __init__(self):
self.changes = []
def add_item(self, key, value):
self.changes.append(f"Added {key}: {value}")
def remove_item(self, key):
self.changes.append(f"Removed {key}")
def change_value(self, key, new_value):
self.changes.appe... | magicoder | python |
You are tasked with implementing a custom data structure in C++ to store and manipulate various numeric data types. The data structure should support adding elements, removing elements, and finding the maximum element. To achieve this, you need to create a class that uses templates to handle different numeric types and... | ```cpp
#include <iostream>
#include <vector>
#include <limits>
#include <type_traits>
template <typename T>
class NumericContainer {
private:
std::vector<T> elements;
public:
void add(T element) {
elements.push_back(element);
}
void remove(size_t index) {
if (index < elements.size()) ... | magicoder | cpp |
You are tasked with creating a Python class that interacts with a web page using Selenium. The class should be able to perform actions such as locating elements and performing mouse actions. Your task is to complete the implementation of the class by adding methods to interact with the web page.
You are provided with ... | ```python
class WebPageInteractor:
_track = '(//li[contains(@class, "track")])[1]'
_next_btn = '//button[@id="next-btn"]'
def __init__(self, driver):
self.driver = driver
self.first_playlists = None
from selenium.webdriver.common.action_chains import ActionChains
def get_first_... | magicoder | python |
You are tasked with implementing a function to retrieve a list of tokens from a file and process them based on a given mood. The function `set_avi` takes a string `mood` as input and is expected to perform the following steps:
1. Check if a file named `<mood>.png` exists in the directory `~/.config/avi/images/`.
2. If ... | ```python
import os
def get_tokens():
# Placeholder for the get_tokens function implementation
pass
def set_avi(mood):
avi_directory = os.path.expanduser('~/.config/avi/images/')
mood_image = mood + '.png'
if mood_image in os.listdir(avi_directory):
tokens = get_tokens()
# Pro... | magicoder | python |
You are tasked with implementing a class in C++ that manages a collection of SCMProcessInfo objects and provides methods for manipulating and iterating through the collection. The class should implement the IEnumSCMProcessInfo interface, which includes the methods Skip, Reset, and Clone. Additionally, the class should ... | ```cpp
#include <vector>
#include <algorithm>
class SCMProcessInfoCollection : public IEnumSCMProcessInfo {
public:
// IEnumSCMProcessInfo interface methods
STDMETHOD(Skip)(ULONG cElems) override {
// Implement Skip method
// Skips the specified number of elements in the collection
}
S... | magicoder | cpp |
You are working on a data processing pipeline for analyzing brain connectivity data. The given code snippet is part of a Python script that sets up parameters for model fitting and data processing. Your task is to implement a function that processes these parameters and returns a dictionary containing the relevant sett... | ```python
import os
def process_parameters(save_dir, save_stem, experiments_fn, source_acronyms, solver, fit_gaussian, select_one_lambda, cross_val, save_mtx, cross_val_matrices, selected_fit_cmds, cmdfile):
settings = {
'save_dir': os.path.join('../../data/connectivities', save_stem),
'experiments... | magicoder | python |
You are tasked with implementing a function to calculate the total number of parameters in a neural network flow model. The flow model consists of multiple flow steps, each of which may have a different number of parameters. The function should take the batch size and the shapes of the tensors involved in the flow mode... | ```python
def calculate_total_parameters(batch_size, tensor_shapes):
total_params = 0
for shape in tensor_shapes:
total_params += shape[1] # Add the number of parameters in each flow step
return total_params
```
The `calculate_total_parameters` function iterates through the `tensor_shapes` list an... | magicoder | python |
You are tasked with implementing a class to manage email settings for a web clipping application. The class should allow for setting and retrieving various email-related properties. Your task is to create a Python class `EmailSettings` with the following properties and methods:
Properties:
- `address`: Represents the ... | ```python
class EmailSettings:
def __init__(self, address):
self.address = address
self.reply_to = None
self.make_default = False
def set_reply_to(self, reply_to):
self.reply_to = reply_to
def set_default(self, make_default):
self.make_default = make_default
de... | magicoder | python |
You are working on a machine learning project and need to implement a class method for calculating a quality metric called q2f3. The q2f3 metric is calculated based on the reference values, predicted values, and the training set labels. Additionally, you need to implement another method for calculating the root mean sq... | ```python
import numpy as np
class YourClass:
def calc_cliff_rmse(self, reference=None, predictions=None, tanimoto_cliff_compounds=None,
scaffold_cliff_compounds=None, levenshtein_cliff_compounds=None,
soft_consensus_cliff_compounds=None):
rmse_results = {}
... | magicoder | python |
You are tasked with implementing a Python class that utilizes a pre-trained model to perform similarity scoring on query embeddings. The class should have a method to compute the similarity scores between the query embeddings and the pre-trained embeddings using a provided utility function. Your task is to complete the... | ```python
class SimilarityScorer:
def __init__(self, dict_model):
self.qa = dict_model["qa"]
self.emb = dict_model["embeddings"]
def compute_similarity_scores(self, query_embedding, util):
sim_scores = util.pytorch_cos_sim(query_embedding, self.emb) # compute similarity scores
... | magicoder | python |
You are working on a natural language processing (NLP) project and need to implement a custom attention mechanism using TensorFlow. The attention mechanism is a key component in many NLP tasks, such as machine translation and text summarization. In this problem, you are tasked with implementing the calculation of atten... | ```python
import tensorflow as tf
def calculate_attention_scores(query, context):
# Assuming query and context are TensorFlow tensors
S = tf.matmul(query, tf.transpose(context, [0, 2, 1]))
return S
```
The `calculate_attention_scores` function takes the query and context tensors as input and uses TensorFl... | magicoder | python |
You are tasked with implementing a graph class for Deep Graph Convolutional Neural Network (DGCNN) using Python. The DGCNN graph class is responsible for initializing hyperparameters and building embeddings for the DGCNN model.
Your task is to complete the `DGCNNGraph` class by implementing the `build_embed` method. T... | ```python
from bert4keras.layers import ConditionalRandomField
from macadam import keras, K, O, C, L, M
from macadam.base.graph import graph
class DGCNNGraph(graph):
def __init__(self, hyper_parameters):
"""
Init of hyper_parameters and build_embed.
"""
# Initialize hyperparameters ... | magicoder | python |
You are tasked with implementing a custom layout manager for a graphical user interface (GUI) framework. The layout manager is responsible for positioning and sizing components within a container based on specified rules. The code snippet provided demonstrates the addition of a component to the layout manager, along wi... | ```python
def Add(component, pos=(x, y), size=(width, height), growX=False, growY=False):
# Logic to position and size the component within the container
# For example, using the sizer.Add method from the code snippet
sizer.Add(component, pos=(x, y), size=(width, height), growX=growX, growY=growY)
if DE... | magicoder | python |
You are tasked with implementing a configuration manager for a software project. The manager should allow the definition of configuration options with default values and the ability to override these defaults based on different epochs. An epoch represents a specific period of time during which certain configuration val... | ```python
class WellKnownProjectOption(object):
def __init__(self, key, default=None, epoch_defaults=None):
self.key = key
self.default = default
self.epoch_defaults = epoch_defaults if epoch_defaults else {}
def get_value(self, epoch=None):
if epoch and epoch in self.epoch_defa... | magicoder | python |
You are tasked with implementing a card game system that involves discarding cards from a player's hand. The game is designed for a maximum of 4 players. The code snippet provided is a part of the test suite for the `DiscardCard` class, which is responsible for managing the discarding of cards during the game. The `tes... | ```java
import tr.cobanse.batak.util.GameTestUtils;
public class DiscardCardTest {
private static final Integer MAX_PLAYER = 4;
private DiscardCard discardCard = new DiscardCard(new RequestCommandValidator());
// private CardDistributeService cardDistributeService = new CardDistributeServiceImpl();
... | magicoder | java |
You are tasked with creating a Python class that performs integer linear programming and its relaxation. Integer linear programming is a mathematical optimization problem where the objective is to find the values of variables that minimize or maximize a linear objective function, subject to linear equality and inequali... | ```python
import numpy as np
class IntegerProgram:
def __init__(self, A, b, c, z, sense, constraint_types, integer_indices, non_negative_indices):
self.A = A
self.b = b
self.c = c
self.z = z
self.sense = sense
self.constraint_types = constraint_types
self.int... | magicoder | python |
You are tasked with implementing a Java method that calculates the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first few numbers in the Fibonacci sequence a... | ```java
import java.math.BigInteger;
import java.util.List;
public class FibonacciGenerator {
public static List<BigInteger> generateFibonacciSequenceUpToLimit(BigInteger limit) {
List<BigInteger> fibonacciSequence = new ArrayList<>();
BigInteger a = BigInteger.ZERO;
BigInteger b = BigInteg... | magicoder | java |
You are tasked with implementing a class for managing compilation options for a JavaScript compiler. Your task is to create a class called `JavascriptCompilationOptions` with the following properties and methods:
Properties:
1. `TargetVersion` (string): Represents the target version of JavaScript for compilation.
2. `... | ```csharp
/// <summary>
/// Manages compilation options for a JavaScript compiler.
/// </summary>
public class JavascriptCompilationOptions
{
/// <summary>
/// Gets or sets the target version of JavaScript for compilation.
/// </summary>
public string TargetVersion { get; private set; } = "es5";
//... | magicoder | csharp |
You are tasked with implementing a custom data structure in C++ that represents a hierarchical tree-like structure. The structure should support the retrieval of leaf data and the determination of the segment path for a given node. You are provided with a code snippet that outlines the required functions for this data ... | ```cpp
#include <vector>
#include <string>
#include <utility>
// Define the LeafData type
struct LeafData {
// Define the structure of LeafData as per requirements
// ...
};
class CustomTree {
private:
// Define the internal representation of the hierarchical tree-like structure
// ...
public:
//... | magicoder | cpp |
You are tasked with implementing a Python class that serves as an encoder for observations in a reinforcement learning environment. The encoder should be capable of handling both discrete and continuous action spaces. Your task is to create the `Encoder` class with the appropriate methods and attributes to fulfill thes... | ```python
class Encoder:
def __init__(self, observation_shape, action_size, discrete_action):
self.observation_shape = observation_shape
self.action_size = action_size
self.discrete_action = discrete_action
def encode(self, observation):
# Implementation of encoding logic based ... | magicoder | python |
You are tasked with creating a Python program that simulates a connection provider for different operating systems. The program should include a base class for connection providers and two derived classes for Linux and Windows connection providers. The base class should have a method for establishing a connection, and ... | ```python
class ConnectionProvider:
def establish_connection(self):
raise NotImplementedError("Subclasses must implement this method")
class LinuxConnectionProvider(ConnectionProvider):
def establish_connection(self):
return "Establishing connection for Linux"
class WindowsConnectionProvider... | magicoder | python |
You are tasked with creating a Python function that processes image data using a pre-trained PyTorch model. The function should take a JSON input containing a list of image instances, convert them to PyTorch tensors, and then use a pre-loaded model to make predictions on the images. The model is loaded from a specified... | ```python
import os
import json
import torch
from typing import List
def process_images(data: str, model_path: str, model_filename: str) -> List[str]:
model_path = os.path.join(model_path, model_filename)
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
model = torch.load... | magicoder | python |
You are tasked with implementing a graph kernel calculation module for a graph analysis library. Graph kernels are used to measure the similarity between graphs based on their structural properties. The code snippet provided is a part of the graph kernel calculation process, where different types of graph kernels are b... | ```python
def calculate_all_graph_kernels(graphs):
kernel_results = {
'GaussianKernel': [],
'GeometricRandomWalkKernel': [],
'ExponentialRandomWalkKernel': []
}
for graph in graphs:
gaussian_kernel_value = gk.CalculateVertexEdgeHistGaussKernel(graph)
geometric_random... | magicoder | python |
You are tasked with implementing a PHP class that manages blog categories. The class should provide methods for retrieving, creating, updating, and deleting blog categories. Additionally, the class should support serialization of its data.
Your task is to complete the implementation of the `BlogCategoryManager` class ... | ```php
class BlogCategoryManager implements Serializable
{
public $modelClass = 'common\models\BlogCategory';
public $serializer = [
'attributes' => ['id', 'name', 'description'], // Define the attributes to be serialized
];
// Implement the Serializable interface methods
public function se... | magicoder | php |
You are working on a genetic algorithm implementation for optimizing a set of parameters. In the code snippet provided, a new gene value is being calculated based on the genes of two individuals (`ind0` and `ind1`) and a weight difference (`diff_weight`). The new gene value is then checked against a maximum threshold (... | ```java
public double calculateNewGene(double baseGene, double ind0Gene, double ind1Gene, double diffWeight, double xMax) {
double newGene = baseGene + (diffWeight * (ind0Gene - ind1Gene));
return Math.min(newGene, xMax);
}
``` | magicoder | java |
You are tasked with creating a program to manage and display daily calorie burn data for a fitness client. The program should allow the user to choose from a menu of options, including viewing the calories burned on a specific date and within a time period. The program should handle user input for dates and display the... | ```java
// Import statements and class definition
public class FitnessClientManager {
private int exitInt;
private static final Logger LOGGER = Logger.getLogger(FitnessClientManager.class.getName());
// Other class members and methods
public void handleUserSelection(int chosenOption) {
if (ch... | magicoder | java |
You are tasked with creating a program that generates a unique alphanumeric code for each user in a system. The code should be a combination of the user's name and a randomly generated number. The program should also include a method to validate the generated code.
Create a class `UserCodeGenerator` with the following... | ```csharp
using System;
public class UserCodeGenerator
{
private string userName;
private Random random;
public UserCodeGenerator(string name)
{
userName = name;
random = new Random();
}
public string GenerateCode()
{
int randomNumber = random.Next(1000, 10000); //... | magicoder | csharp |
You are tasked with implementing a function to calculate the nth Fibonacci number. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
Write a function `nth_fib(n)` that takes ... | ```python
def nth_fib(n):
if n <= 0:
return None
elif n == 1:
return 0
elif n == 2:
return 1
else:
a, b = 0, 1
for _ in range(2, n):
a, b = b, a + b
return b
```
The `nth_fib` function first checks if the input `n` is non-positive and returns N... | magicoder | python |
You are tasked with implementing a function to generate random permutations for a given set of items. The function should take into account an initial seed salt and example hashes to ensure reproducibility. Your task is to create a Python function that accomplishes this, using the provided code snippet as inspiration.
... | ```python
import hashlib
import numpy as np
import torch
def inverse_permutation(perm):
return torch.argsort(perm)
def generate_permutations(nr_items_per_example, index_offsets, initial_seed_salt, example_hashes):
random_seed_per_example = [
int(hashlib.sha256(f'{initial_seed_salt}{hash_val}'.encode('... | magicoder | python |
You are tasked with creating a function that builds a submenu based on a given set of permissions. The function should take an array of parent menu items as input and filter them based on the permissions associated with each submenu. If a submenu has specific permissions set, only those with matching permissions should... | ```php
private function buildSubMenu($parents)
{
$filteredSubmenu = array(); // Initialize an empty array to store the filtered submenus
foreach($parents as $submenu)
{
if(isset($submenu->permissions)){
$allowed = ($submenu->permissions != '*' ? explode('-',$submenu->permissions) : N... | magicoder | php |
You are tasked with implementing a command-line utility to print formatted text to a file. The utility should support printing text in different colors and styles, such as bold and underline. Your task is to implement the `printToFile` function, which takes in a text string, a color code, and a file path, and writes th... | ```bash
printToFile() {
text=$1
colorCode=$2
filePath=$3
# Open the file in append mode and write the formatted text
echo -e "${colorCode}${text}\e[0m" >> "$filePath"
}
```
The `printToFile` function takes the input parameters `text`, `colorCode`, and `filePath`. It uses the `echo` command with the `-e` opt... | magicoder | shell |
You are tasked with implementing a program to solve the classic 8-puzzle game using the A* search algorithm. The 8-puzzle consists of a 3x3 grid with 8 numbered tiles and a blank space. The objective is to rearrange the tiles from a given initial state to a goal state using the minimum number of moves.
Your task is to... | ```python
import heapq
# Define the goal state
goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
# Define a function to calculate the Manhattan distance between two points
def manhattan_distance(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
# Define a function to get the possible moves for the empty slot
... | magicoder | python |
You are given a list of tuples `testdata`, where each tuple contains three integers `(a, b, c)`. Your task is to write a function `sum_of_pairs` that takes in the list of tuples and returns a new list containing the sum of the first two elements of each tuple.
For example, given the `testdata` as:
```
testdata = [
... | ```python
def sum_of_pairs(testdata):
return [a + b for a, b, c in testdata]
testdata = [
(1, 1, 2),
(1, 0, 1),
(5, 5, 10)
]
print(sum_of_pairs(testdata)) # Output: [2, 1, 10]
``` | magicoder | python |
You are tasked with debugging and improving a Python function that is intended to retrieve temperature data from a bridge client. The provided code snippet contains a function `get_temperature` that attempts to fetch the temperature value from the bridge client and print it. However, the code is incomplete and contains... | ```python
import socket
def get_temperature():
while True:
try:
value = bridgeclient() # Assuming bridgeclient is a valid function
temperature = value.get('temperature') # Correcting the variable name
print(str(temperature))
except socket.error as e: # Handlin... | magicoder | python |
You are tasked with creating a Python function that processes a list of database migration operations and generates the corresponding SQL statements. Each migration operation is represented as a tuple containing the app name, migration name, and a list of migration operations. Each migration operation is represented as... | ```python
from typing import List, Union
class RenameField:
def __init__(self, model_name, old_name, new_name):
self.model_name = model_name
self.old_name = old_name
self.new_name = new_name
class AddField:
def __init__(self, model_name, field_name, field_type):
self.model_name... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.