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 data structure called `CircularQueue` in Python. A circular queue is a data structure that follows the FIFO (First In First Out) principle, but the last element is connected to the first element to form a circle. The circular queue should support the following operations: 1. `_...
```python class CircularQueue: def __init__(self, k: int): self.queue = [None] * k self.max_size = k self.front = 0 self.rear = -1 self.size = 0 def enQueue(self, value: int) -> bool: if not self.isFull(): self.rear = (self.rear + 1) % self.max_size ...
magicoder
python
You are tasked with implementing a custom namespace resolver for a specific namespace in a C# application. The namespace resolver should be able to dynamically resolve and load classes from the specified namespace at runtime. Your task is to create a class that can dynamically load and instantiate classes from the give...
```csharp using System; using System.Reflection; namespace Ntreev.Crema.Services { public class NamespaceResolver { public object ResolveClass(string className) { string fullClassName = "Ntreev.Crema.Services." + className; // Assuming the class is in the specified namespace ...
magicoder
csharp
You are tasked with implementing a Python generator function that yields the ancestors of a given resource in a hierarchical structure. The resource is represented by an object with a `parent` attribute pointing to its parent resource. The generator function should yield each ancestor resource in sequence until reachin...
```python def ancestors_generator(resource): while resource.parent is not None: yield resource.parent resource = resource.parent ``` The `ancestors_generator` function uses a while loop to yield each ancestor of the input resource. It checks if the current resource has a parent, and if so, yields t...
magicoder
python
You are given a set of logical implications in the form of First Order Logic expressions. Each expression takes the form of "A(x) ⊃ B(x)", where A(x) and B(x) are predicates and x is a variable. This notation means that if A(x) is true, then B(x) must also be true. Your task is to write a program that can determ...
```python def is_consistent(implications): implications_dict = {} for imp in implications: A, B = imp.split(" ⊃ ") if A in implications_dict: implications_dict[A].append(B) else: implications_dict[A] = [B] def dfs(predicate, visited): i...
magicoder
python
You are tasked with implementing a transaction validation module for a cryptocurrency system. The provided code snippet is a partial excerpt from the module, showcasing the public interface and the modules it uses for transaction validation. Your task is to design and implement the validation logic for a cryptocurrenc...
```rust use std::collections::HashSet; // Define the TransactionValidationError and TransactionValidationResult types // ... // Implement the validation logic for the cryptocurrency transaction pub fn validate_transaction(inputs: &[TransactionInput], outputs: &[TransactionOutput], memo: Option<String>) -> Transaction...
magicoder
rust
You are given a 2D board of characters and a list of words. Your task is to implement a function that finds all the words from the list that can be formed by a sequence of adjacent characters on the board. The adjacent characters can be horizontally or vertically neighboring, but not diagonally. Each character on the b...
```python from typing import List def find_words(board: List[List[str]], words: List[str]) -> List[str]: def search(word_list, cur_sub_string, x, y): nonlocal res if (not 0 <= x < row) or (not 0 <= y < column) or board[y][x] == 0 or board[y][x] not in trie[cur_sub_string] or len(res) == len(word_li...
magicoder
python
You are tasked with implementing a class that represents a debugger expression value in a debugging environment. The class should handle different types of completion data and provide methods to retrieve the value's address, full name, and type name. Your task is to create a class `DebuggerExpressionValue` with the fo...
```csharp using Microsoft.VisualStudio.Debugger.Evaluation; public class DebuggerExpressionValue { private DkmVisualizedExpression visualizedExpression; private DkmExpressionValueHome valueHome; private ulong address; private string fullName; private string typeName; public DebuggerExpressionV...
magicoder
csharp
You are tasked with creating a Python class for managing entities in a simulation environment. The class contains two methods: `update_entity` and `publish_marker_array`. The `update_entity` method is responsible for updating the position and orientation of a specified entity in the simulation. It takes in the entity ...
```python # Sample usage of the EntitySimulator class # Create a dictionary mapping entity IDs to simulation IDs entity_id_map = { "entity1": 1, "entity2": 2 } # Create an instance of EntitySimulator simulator = EntitySimulator(entity_id_map, position_tolerance=0.01, client_simulator_id=0) # Update the positi...
magicoder
python
You are tasked with implementing a function that simulates a smooth scrolling effect on a web page using the provided code snippet as a reference. The function should take in the starting position, the target position, the duration of the scroll, and the easing function to be used. The easing function will determine th...
```javascript function smoothScroll(start, targetY, during, ease) { const easingFunctions = { easeInQuad: t => t * t, easeOutCubic: t => (--t) * t * t + 1 // Add more easing functions as needed }; const startTime = performance.now(); const animateScroll = () => { const c...
magicoder
javascript
You are tasked with implementing a Python class that manages data forwarding entries in a software-defined networking (SDN) controller. The provided code snippet is a partial implementation of a RESTful API endpoint using Flask and Flask-RESTful for adding and deleting data forwarding entries in the SDN controller. You...
```python class CoreDataForwardResource(Resource): @swagger.tags(['coreDataForwardAdd']) @swagger.response(response_code=201, description='Added data forward entry to core') @swagger.reqparser(name='CoreDataForwardParser', parser=parser) def post(self): logger.info('Core data forward entry reque...
magicoder
python
You are tasked with implementing a function that flattens a nested object into a single-level object, where the keys are concatenated using dot notation. For example, given the input object `{ a: { b: 1, c: { d: 2 } } }`, the output should be `{ 'a.b': 1, 'a.c.d': 2 }`. Write a function `flattenObject` that takes an i...
```typescript function flattenObject(object: { [key: string]: any }, prefix: string = ''): { [key: string]: any } { let flatten: { [key: string]: any } = {} for (const key in object) { const value = object[key] if (typeof value === 'object' && value !== null) { const nestedFlatten = flattenObject(valu...
magicoder
typescript
You are tasked with creating a tax calculation program for a country where the tax rates are based on income brackets. The tax calculation is based on the following rules: - If the tax base is less than or equal to 1200 times the value of MANWON, the tax is calculated as 6% of the tax base. - If the tax base is greater...
```python def calculate_tax(tax_base: int) -> float: MANWON = 1000000 if tax_base <= 1200 * MANWON: return tax_base * 0.06 elif tax_base <= 4600 * MANWON: return 72 * MANWON + (tax_base - 1200 * MANWON) * 0.15 elif tax_base <= 8800 * MANWON: return 582 * MANWON + (tax_base - 4600...
magicoder
python
You are tasked with implementing a class method that calculates the score of an object based on its location and orientation. The object is represented by a class with the following attributes and methods: Attributes: - `self.loc`: A 2D vector representing the location of the object. - `self.ry`: A scalar representing...
```python import numpy as np class Object: def __init__(self, loc, ry): self.loc = loc self.ry = ry self.score = None def calculate_score(self): beta = np.arctan2(self.loc[1], self.loc[0]) alpha = -np.sign(beta) * np.pi / 2 + beta + self.ry self.score = -1.0 # ...
magicoder
python
You are tasked with implementing a custom data structure to efficiently store and retrieve a collection of network resource properties. Each network resource property consists of a name and a description. The data structure should support adding new properties, retrieving properties by name, and listing all properties ...
```python class NetworkResourceProperties: def __init__(self): self.properties = {} def addProperty(self, name, description): self.properties[name] = description def getProperty(self, name): return self.properties.get(name, "Property not found") def listProperties(self): ...
magicoder
python
You are tasked with implementing a class for managing auto-heal rules in a game. The class, `AutoHealRules`, should allow setting conditions for when the auto-heal actions should be executed. The provided code snippet shows a method `withTriggers` that sets the triggers for auto-heal actions. Your task is to implement ...
```java // Define the AutoHealTriggers enum public enum AutoHealTriggers { LOW_HEALTH, TIME_INTERVAL, OUT_OF_COMBAT } // Implement the AutoHealRules class public class AutoHealRules { private AutoHealTriggers triggers; private int healthThreshold; // Threshold for LOW_HEALTH trigger private long timeIn...
magicoder
java
You are tasked with implementing a simple event stream processing system using JavaScript. The system will receive events from two Kafka-like message brokers and process them using the Most.js library. You are provided with a code snippet that sets up two instances of a fake Kafka message broker and creates an event s...
```javascript // Import the Most.js library const most = require('most'); // Define the FakeKafka class class FakeKafka { constructor() { this.listeners = []; } addEventListener(event, callback) { this.listeners.push({ event, callback }); } emitEvent(event, data) { this.listeners .filter(...
magicoder
javascript
You are tasked with creating a Rust program that analyzes a given Rust project's dependencies and provides a report on the number of external crates used. The program should read the project's `Cargo.toml` file, which contains information about its dependencies, and then count and display the number of external crates ...
```rust use std::fs; use toml::Value; fn count_external_crates(cargo_toml_path: &str) -> usize { let cargo_toml_content = fs::read_to_string(cargo_toml_path) .expect("Failed to read Cargo.toml file"); let toml_value = cargo_toml_content.parse::<Value>() .expect("Failed to parse Cargo.toml file...
magicoder
rust
You are tasked with implementing a parallel multiway merge algorithm using the STXXL library. The STXXL library is a C++ implementation of the C++ standard library STL for external memory computations. The given code snippet is a part of a program that utilizes the STXXL library for parallel multiway merging. Your tas...
```cpp #include <stxxl/vector> #include <stxxl/sorter> #include <stxxl/algorithm> #include <vector> std::vector<int> parallelMultiwayMerge(const std::vector<std::vector<int>>& sortedSequences) { std::vector<int> result; // Create STXXL vectors for input and output stxxl::vector<int> stxxlInput; for (c...
magicoder
cpp
You are given a C# program that is intended to print a pattern of asterisks in a diamond shape. However, the code snippet provided is incomplete and contains missing parts. Your task is to complete the given C# program to achieve the desired diamond pattern output. The program should take an integer input `n` and prin...
```csharp using System; class DiamondPattern { static void Main() { int n = int.Parse(Console.ReadLine()); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n - i; j++) { Console.Write(" "); } for (int j = 1; j <= 2 * i...
magicoder
csharp
You are tasked with implementing a simplified version of a task service that handles requests and optimizes an index. The task service is responsible for processing requests and optimizing the index when the request is made from an API. The provided code snippet is a part of the task service's logic. Your task is to c...
```cpp #include <iostream> #include <string> enum CallType { FromAPI, NotFromAPI }; class TaskService { public: bool optimizeIndex() { // Simulated index optimization return true; // Replace with actual index optimization logic } }; class Response { public: void addError(const std::strin...
magicoder
cpp
You are working on a data processing system that involves handling and persisting data packets in HDF5 format. The system utilizes various modules and utilities from the `pyon` and `ion` libraries. Your task is to implement a function that generates a unique identifier for a new data packet and persists the packet to a...
```python def generate_and_persist_data_packet(data_payload): # Generate a unique identifier for the data packet unique_id = create_simple_unique_id() # Construct the data packet using DataPacketBuilder data_packet = DataPacketBuilder.build_data_packet(data_payload) # Persist the data packet to an...
magicoder
python
You are working on a project that involves processing 3D point cloud data. The code snippet provided is a part of a Python class that manipulates the point cloud data. The class has two methods: `translate` and `histogramEqualize`. The `translate` method takes two parameters `centerY` and `centerZ`, and it subtracts t...
```python def normalizeCoordinates(self, minX, maxX, minY, maxY, minZ, maxZ): # Calculate the ranges for each coordinate axis rangeX = maxX - minX rangeY = maxY - minY rangeZ = maxZ - minZ # Normalize x, y, and z coordinates to the specified ranges self._points[:, 0] = (self._points[:, 0] -...
magicoder
python
You are tasked with creating a Python class that simulates a simple LED controller using the Raspberry Pi GPIO library. The class should allow users to turn the LED on and off, as well as set its brightness level. Your task is to complete the implementation of the LEDController class by adding the necessary methods. T...
```python import RPi.GPIO as GPIO class LEDController: def __init__(self, pin_number): self.pin = pin_number GPIO.setmode(GPIO.BCM) GPIO.setup(self.pin, GPIO.OUT) def turn_on(self): GPIO.output(self.pin, GPIO.HIGH) def turn_off(self): GPIO.output(self.pin, GPIO.LOW...
magicoder
python
You are tasked with creating a TypeScript class that interfaces with a user profile API to handle user profile updates and creations. The API provides several data transfer objects (DTOs) and input types for different operations. Your task is to create a TypeScript class that encapsulates the logic for making requests ...
```typescript import { UpdateUserProfileDto, UserProfileApi, UserProfileControllerCreateRequest, UserProfileControllerUpdateRequest, } from '../../gen/fetch' import { UpdateUserProfileInput } from './dto/updateUserProfileInput' import { CreateUserProfileInput } from './dto/createUserProfileInput' import { Creat...
magicoder
typescript
You are a DevOps engineer responsible for managing database credentials and ensuring their secure storage. You are tasked with creating a Python script to update database passwords and store them in a YAML file using the PyYAML library. Additionally, the script should execute SQL commands to update the database passwor...
```python import subprocess import yaml import getpass # Define the MyDumper class for custom YAML dumping class MyDumper(yaml.Dumper): def increase_indent(self, flow=False, indentless=False): return super(MyDumper, self).increase_indent(flow, False) # Define the database user, host, and password user = "...
magicoder
python
You are working on a project that involves implementing a deep learning model for predicting stock price movements based on order book data. The code snippet provided is from a Python module that imports two components: `LOBDeepPP_model` and `LOBDeepPP_params_files`. The `LOBDeepPP_model` likely contains the implementa...
```python from . import LOBDeepPP_model from . import LOBDeepPP_params_files class StockPricePredictor: def __init__(self, model_path, params_path): self.model_path = model_path self.params_path = params_path self.model = None self.parameters = None def load_model(self): ...
magicoder
python
You are tasked with creating a program to generate a grid layout for a collection view in an iOS app. The grid layout should consist of a 1-2-1 pattern, where the middle row spans the entire width of the grid, while the top and bottom rows each occupy half the width of the grid. The grid layout should be responsive to ...
```swift import UIKit func makeGridLayout(in environment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection { // Define the item size for the top and bottom rows let smallItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimen...
magicoder
swift
You are working on a project that involves configuring a particle physics event processing framework using the CMS (Compact Muon Solenoid) software. The provided code snippet is a part of the configuration script written in Python using the FWCore.ParameterSet.Config module. Your task is to complete the configuration ...
```python import FWCore.ParameterSet.Config as cms process = cms.Process("Demo") process.load("Configuration.Geometry.GeometryExtended2015Reco_cff") process.load("Geometry.RPCGeometry.rpcGeometry_cfi") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) ) # Define a module to read input data ...
magicoder
python
You are tasked with implementing a class that manages the disposal of resources. The class should have a method for disposing resources and a method for releasing unmanaged resources. Your task is to complete the implementation of the `ResourceHandler` class by adding the necessary methods to properly dispose of resour...
```csharp using System; public class ResourceHandler : IDisposable { private bool disposed = false; // Implement the Dispose method to release managed resources public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Implement the ReleaseUnmanagedResources metho...
magicoder
csharp
You are tasked with creating a Python program that processes genetic sequences to identify specific nucleotide components. The program should be able to read a DNA sequence from a file, count the occurrences of each nucleotide (A, C, G, and T), and then calculate the GC content of the sequence. Write a Python function...
```python def process_genetic_sequence(file_path): try: with open(file_path, 'r') as file: sequence = file.read().strip() if not sequence: return "Empty file." nucleotide_count = {'A': 0, 'C': 0, 'G': 0, 'T': 0} for nucleotide in sequence: ...
magicoder
python
You are tasked with creating a Python function that parses a help text for a Telegram bot and extracts the list of commands along with their descriptions. The help text is structured with each command followed by its description, and the command and description separated by a colon. The commands are prefixed with a for...
```python def parse_help_text(help_text: str) -> dict: commands = {} lines = help_text.split('\n') command = None description = "" for line in lines: line = line.strip() if line.startswith('/'): if command is not None: commands[command] = description.strip...
magicoder
python
You are tasked with creating a Python program that securely stores user credentials in a file using base64 encoding. The program should prompt the user to input their username and password, encode the credentials in base64 format, and then write the encoded credentials to a file named "secret". Additionally, the progra...
```python import base64 print("[*] Noodle - Secret writer") print("[*] This will store your credentials in base64-encoded format.") print("[*] Noodle needs this to authenticate with Moodle to function.") print("=" * 48) try: with open("secret", "wb") as f: u = input("Enter username: ") p = input("...
magicoder
python
You are tasked with implementing a Python class that utilizes the provided code snippet to create a web scraping utility. The class should have the ability to perform indirect web scraping by following a chain of URLs to reach the desired content. Your task is to complete the implementation of the `WebScraper` class by...
```python class WebScraper: def __init__(self, session): self.session = session def fetchUrl(self, url, data, baseUrl, nextSearch): # Simulate fetching the content of the given URL # Return the fetched result pass # Implement the fetchUrl method def getPageContent(self, ur...
magicoder
python
You are tasked with implementing a function to build an Address Resolution Protocol (ARP) message for IPv4. The ARP message consists of various fields such as EtherType, operation, source hardware address, source protocol address, target hardware address, and target protocol address. The function `build_arp_msg_ipv4` t...
```rust fn build_arp_msg_ipv4( ptype: EtherType, operation: ARPOperation, sha: MACAddr, spa: IPV4Addr, tha: MACAddr, tpa: IPV4Addr, ) -> [u8; 28] { let mut arp_msg: [u8; 28] = [0; 28]; // Set hardware type (Ethernet) - 2 bytes arp_msg[0] = 0x00; arp_msg[1] = ptype as u8; //...
magicoder
rust
You are tasked with creating a TypeScript class that implements a custom pipe for transforming form data. The pipe should take an input object containing form data, where each key represents a form field and the corresponding value is an object containing the field's properties. The pipe should then transform this inpu...
```typescript export class ExtractFormDataPipe implements PipeTransform { transform(value: { [key: string]: any }) { // Initialize an empty object to store the flattened properties const flattenedData: { [key: string]: any } = {}; // Iterate through each key-value pair in the input object for (const ...
magicoder
typescript
You are tasked with implementing a custom class `ByteString` that simulates a byte string object. The `ByteString` class should support the following operations: 1. Initialization: The class should be initialized with a sequence of bytes. 2. `lines()`: A method that returns a list of lines in the byte string, where a l...
```python class ByteString: def __init__(self, byte_sequence): self.byte_sequence = byte_sequence def lines(self): lines_list = [] current_line = b'' for byte in self.byte_sequence: if byte == 10: # ASCII code for newline character '\n' lines_list.ap...
magicoder
python
You are tasked with implementing a Python function to process image data using the DASC (Data Adaptive Smoothing and Clustering) algorithm. The DASC algorithm is used for image processing and analysis, and it involves generating a histogram and creating a movie from the processed image data. You are provided with the ...
```python from .plots import histogram_dasc, moviedasc def process_image_with_dasc(img, outdir, cadence): # Generate histogram of the input image histogram_dasc(img, outdir) # Create a movie from the processed image data moviedasc(img, outdir, cadence) ``` The `process_image_with_dasc` function encap...
magicoder
python
You are working as a data scientist for a marketing company. Your task is to build a predictive model to determine customer response to marketing campaigns. You have been provided with a dataset named "bank_cleaned.csv" containing various customer attributes and their response to previous marketing campaigns. The datas...
```python import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # Load the data from the "bank_cleaned.csv" file into a pandas DataFrame df = pd.read_csv("data/bank...
magicoder
python
You are given a Python function that takes two integers `X` and `N` as input and returns a list of sets. The function aims to find all unique combinations of numbers raised to the power of `N` that sum up to `X`. However, the code snippet provided is incomplete and lacks proper documentation. Your task is to understand...
```python def find_combinations(X, N): memory = [set() for _ in range(X+1)] all_combs = [] k = 1 next_X = X while True: for comb in memory[next_X]: if k not in comb: new_comb = comb | {k} if new_comb not in all_combs: all_combs...
magicoder
python
You are tasked with implementing a Python generator function that takes two lists as input and yields a sorted list of tuples. Each tuple should contain an element from the first list and its corresponding element from the second list. Additionally, you need to create a unit test case for this generator function using ...
```python import os import unittest def zip_and_sort(ids, weights): yield sorted(zip(ids, weights)) class TestZipAndSort(unittest.TestCase): """Unit test for zip_and_sort generator function""" @unittest.skipIf(not os.environ.get('GENSIM_BIG', False), "Large data test requires GENSIM_BIG environment varia...
magicoder
python
You are tasked with implementing a generic visitor pattern in Java to process different types of series data. The provided code snippet is a part of the declaration of a visitor interface for the series data. The `FIELDS` and `SeriesVisitor` are placeholders for actual code. Your task is to complete the implementation...
```java // Define the SeriesVisitor interface interface SeriesVisitor<TAG, T> { // Define the visit method for visiting a specific type of series data T visit(TAG tag); } // Example usage of the SeriesVisitor interface class ExampleSeriesVisitor implements SeriesVisitor<String, Integer> { @Override pub...
magicoder
java
You are tasked with implementing a function to prune communities in a social network represented by a graph. The graph is represented using an adjacency list, where each key-value pair represents a node and its corresponding neighbors. The function `prune_communities(G, min_size)` takes in the graph `G` and an integer ...
```python from typing import Dict, List def prune_communities(G: Dict[int, List[int]], min_size: int) -> Dict[int, List[int]]: def dfs(node, visited, community): visited.add(node) community.append(node) for neighbor in G[node]: if neighbor not in visited: dfs(nei...
magicoder
python
You are tasked with implementing a class `Max` that contains methods to find the maximum value among given input integers. The class should have the following methods: 1. `maxValue(int a, int b)`: This method should take two integer arguments `a` and `b` and return the maximum value among them. 2. `max(int a, int b, in...
```java public class Max { public int maxValue(int a, int b) { return Math.max(a, b); } public int max(int a, int b, int c) { return Math.max(Math.max(a, b), c); } } ``` The `Max` class contains two methods: `maxValue` and `max`. The `maxValue` method returns the maximum value between ...
magicoder
java
You are tasked with implementing a hierarchical classifier in Python. A hierarchical classifier is a machine learning model that organizes multiple classifiers into a hierarchical structure to make predictions. The given code snippet initializes a hierarchical classifier using existing category classifiers and a class ...
```python class HierarchicalClassifier: def __init__(self, cat_clfs, cd): self.cat_clfs = cat_clfs self.cd = cd def predict(self, input_data): # Start prediction from the root class predicted_class = self._predict_recursive('living_thing', input_data) return predicted_cl...
magicoder
python
You are tasked with implementing a CO2 emissions calculator for a survey application. The application collects user responses and calculates the corresponding CO2 emissions based on the user's input. The code snippet provided is a part of the CO2 emissions calculation logic. The `result` object contains the user's resp...
```javascript switch (questionIndex) { case 5: { answer.co2e = result.answers[2].answer.multiplier * answer.multiplier; return answer; } case 7: { answer.co2e = result.answers[3].answer.multiplier * answer.multiplier; return answer; } case 9: { if (answer.index === 125) { answer.co2e...
magicoder
javascript
You are tasked with implementing a user authentication system for a mobile application using Swift and Firebase. The provided code snippet is a part of the `SignIn` view controller, which is responsible for handling user sign-in functionality. The view controller contains two `UITextField` outlets for the username and ...
```swift import UIKit import Firebase class SignIn: UIViewController { @IBOutlet weak var usernameBox: UITextField! @IBOutlet weak var passwordBox: UITextField! let ref: DatabaseReference = Database.database().reference() var handle: AuthStateDidChangeListenerHandle? override func viewDidLoad() ...
magicoder
swift
You are tasked with designing a system to manage the workflow of a warehouse for an e-commerce company. The system should handle the placement and receipt of orders, inventory management, order backlog, order fulfillment, and cost tracking. Your task is to create a class structure that represents the various components...
```java // Class representing placed orders public class PedidosColocados { // Implementation details for placed orders } // Class representing received orders public class PedidosRecebidos { // Implementation details for received orders } // Class representing inventory management public class Estoque { ...
magicoder
java
You are tasked with creating a Python program to control smart shades in a smart home environment. The program should accept command-line arguments for the IP address of the hub and the name of the shade to control. The smart home hub provides an API for controlling the shades, and your program needs to make HTTP reque...
```python import argparse import requests def open_shade(ip, shade, position): url = f"http://{ip}/shades/{shade}/open?position={position}" response = requests.post(url) if response.status_code == 200: print(f"{shade} opened to position {position}") else: print(f"Failed to open {shade}:...
magicoder
python
You are tasked with implementing a function to determine if a given ray intersects with a triangle in 3D space and, if so, calculating the intersection point and the distance along the ray to the intersection. You are given the following code snippet as a starting point: ```cpp return Point(x, y, z); } // This funct...
```cpp bool Triangle::triangleIsIntersected(const Ray& ray, float& distAlongRayToHit, Point& hitPoint) const { const float EPSILON = 0.000001f; Vector edge1 = vertex2 - vertex1; Vector edge2 = vertex3 - vertex1; Vector h = cross(ray.direction, edge2); float a = dot(edge1, h); if (a > -EPSILON &...
magicoder
cpp
You are tasked with creating a Python function that processes a series of Linux networking commands and extracts specific information from them. The function should take a list of strings as input, where each string represents a command from the Linux `ip` utility. The function should then extract and return the names ...
```python from typing import List def extract_network_devices(commands: List[str]) -> List[str]: device_names = set() for command in commands: if command.startswith("ip"): parts = command.split() for part in parts: if part == "dev" and len(parts) > parts.index(pa...
magicoder
python
You are tasked with implementing a simplified version of a command-line tool that performs various operations based on user input. The provided code snippet is part of the main execution flow of the tool. Your task is to create a class hierarchy for the operations and handle exceptions appropriately. Your task is to c...
```python import sys import logging # Define the base class for operations class Operation: def __init__(self, qbertclient, args): self.qbertclient = qbertclient self.args = args def run(self): pass # Placeholder for the run method # Define specific operation classes class OperationA...
magicoder
python
You are tasked with simulating a ranking system for a sports competition. The ranking system follows a specific algorithm to update the ranks of the winners and losers after each match. The algorithm is as follows: 1. Calculate the winner's and loser's scores using the formula: - winner_score = winner_rank_transfor...
```python def update_ranks(winner_rank, loser_rank, winner_rank_transformed, opponent_rank_transformed, transformed_sum, weighting): winner_score = winner_rank_transformed / transformed_sum loser_score = opponent_rank_transformed / transformed_sum winner_rank = winner_rank + weighting * (1 - winner_score) ...
magicoder
python
You are tasked with creating a Python package for image processing. The package should include modules for image registration and transformation. The image registration module should handle the alignment of images, while the transformation module should provide functions for applying various transformations to images. ...
```python # img_reg.py class ImageRegistration: def __init__(self): # Initialize image registration parameters pass def align_images(self, image1, image2): # Implement image alignment logic pass # transformation.py import numpy as np def apply_rotation(image, angle): # A...
magicoder
python
You are tasked with creating a Python script that interacts with a PowerShell script to perform a specific task. The PowerShell script, named `dns.ps1`, is located in the current working directory. Your Python script should execute the PowerShell script using the `subprocess` module and wait for its completion before p...
```python import subprocess import os def execute_powershell_script(): # Execute the PowerShell script using subprocess # The PowerShell script is located in the current working directory # Wait for the PowerShell script to complete before proceeding script_p = subprocess.Popen([r'C:\WINDOWS\system32\W...
magicoder
python
You are tasked with implementing a data transmission protocol for a custom hardware device. The provided code snippet is a part of the data transmission process. The `lines` variable is a list of strings, and the code processes each line to prepare it for transmission. The `data` variable accumulates the processed line...
```python import time def prepare_data(lines): data = "" for ln in lines: line = ln + " " # Pad the line with spaces to ensure it's at least 20 characters long data += line[0:20] # Take the first 20 characters of the padded line and append to the data if len(data) < 80:...
magicoder
python
You are tasked with implementing a function to manage email subscriptions based on keywords. The function `subscribe_email` takes three parameters: `email` (a string representing the email address to subscribe), `kws` (a list of strings representing keywords), and `time_limit` (an integer representing the time limit in...
```python import time def get_all_keywords(): with open('keywords.txt', 'r') as f: kws = [kw.strip() for kw in f.read().splitlines() if kw.strip()] return kws def delete_email_from_list(email): with open('subscribed_emails.txt', 'r') as f: lines = [line.split(":") for line in f.read()....
magicoder
python
You are tasked with implementing a Python class that manages API requests using the aiohttp library. The class should handle the initialization of API parameters and provide an asynchronous context manager for making API requests. You need to create a class `APIManager` with the following specifications: - The class s...
```python import asyncio import aiohttp import sys from typing import Optional class APIManager: def __init__(self, token: str, loop=None, proxy=None, proxy_auth=None, session: Optional[aiohttp.ClientSession] = None) -> None: self.token = token self.loop = asyncio.get_event_loop() if loop is None e...
magicoder
python
You are tasked with creating a Python program to implement a number guessing game. The program should generate a random number between 1 and 100 (inclusive) and prompt the user to guess the number. After each guess, the program should provide feedback on whether the guess is too high, too small, or correct. The game sh...
```python import random def number_guessing_game(): number = random.randint(1, 100) guess = -1 while guess != number: guess = int(input("Enter your guess: ")) if guess > number: print("Your guess is too high") elif guess < number: print("Your guess is too s...
magicoder
python
You are tasked with implementing a Python function that processes and writes data to JSON files based on the given code snippet. The code snippet is part of a larger program that handles different types of security content and writes the processed data to JSON files. Your task is to complete the function `process_secur...
```python def process_security_content(type, data, output_path): if type == SecurityContentType.detections: obj_array = process_detections(data) JsonWriter.writeJsonObject(os.path.join(output_path, 'detections.json'), {'detections': obj_array}) elif type == SecurityContentType.stories: o...
magicoder
python
You are working with climate data stored in a NetCDF file format. Your task is to create a Python function that reads the temperature data from the file and processes it to calculate the average temperature for a specific time period. You are given a code snippet that demonstrates the initial steps of reading the data...
```python import netCDF4 as nc import numpy as np def calculate_average_temperature(file_path, start_date, end_date): f = nc.Dataset(file_path, 'r') time = f.variables['time'][:] time_units = f.variables['time'].units start_index = np.argmax(nc.num2date(time, time_units) >= start_date) end_index = ...
magicoder
python
You are tasked with creating a Python script that processes audio files using a pre-trained TensorFlow model for speech recognition. The script should take in command-line arguments to specify the frozen graph file, label file, and the audio file to be labeled. The frozen graph file contains the trained model, the labe...
```python import tensorflow as tf def predict_audio_label(graph_path: str, labels_path: str, audio_path: str) -> str: # Load the frozen graph with tf.io.gfile.GFile(graph_path, "rb") as f: graph_def = tf.compat.v1.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_...
magicoder
python
You are tasked with implementing a token-based authentication system for a RESTful API using Python's Flask-RESTful library. The code snippet provided is a starting point for creating a resource that requires token authentication. Your task is to extend the `TokenAuthResource` class to create a specific resource calle...
```python from flask import Flask from flask_restful import Api, Resource from functools import wraps app = Flask(__name__) api = Api(app) # Token authentication decorator def token_auth(func): @wraps(func) def decorated(*args, **kwargs): # Implement token authentication logic here # For examp...
magicoder
python
You are tasked with creating a script that processes a list of numbers and performs specific operations on them. The script should take a list of numbers as input and output the result of the operations. The operations to be performed are as follows: 1. Double the number if it is even. 2. Triple the number if it is odd...
```bash #!/bin/bash read -p "Enter the list of numbers: " numbers # Split the input into an array IFS=' ' read -r -a num_array <<< "$numbers" # Iterate through the array and perform the specified operations for num in "${num_array[@]}" do if (( num % 2 == 0 )); then echo $((num * 2)) else echo $((num * 3...
magicoder
shell
You are tasked with implementing a function to determine whether the current time falls within a trade window for a financial trading system. The trade window is defined to avoid the early morning and late night periods, as well as weekends, to prevent overnight gaps. The provided code snippet contains partial logic fo...
```python from datetime import datetime, timedelta class TradeWindowChecker: def __init__(self): pass def is_trade_window(self, short_symbol): """Determines if the current time falls within the trade window""" now = datetime.now() # Define the trade window with exclusions for e...
magicoder
python
You are tasked with creating a Python program that processes a given file and performs specific operations on its content. Your program should read a file path as a command-line argument and then perform the following tasks: 1. Check the file for PEP 8 compliance using the `flake8` tool with a maximum line length of 12...
```python import subprocess import sys def check_pep8_compliance(file_path): try: # Run flake8 command to check PEP 8 compliance result = subprocess.run(['flake8', '--max-line-length=120', file_path], capture_output=True, text=True, check=True) # If no PEP 8 violations found, print "PEP 8 ...
magicoder
python
You are tasked with creating a React component that renders an SVG icon representing a "Turn Right" arrow. The SVG icon should be designed to fit within a 2048x2048 viewport and should have a specific path defined to create the arrow shape. Your task is to write the React component code that generates the SVG icon as d...
```jsx import React from 'react'; const TurnRightIcon = ({ classes }) => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2048 2048" className={classes.svg} focusable="false"> <path d="M1451 43q9 0 44 29t82 73 100 97 97 100 74 82 29 45q0 7-17 29t-44 53-64 70-74 76-76 74-69 63-53 45-29 17q-20 0-33-14t-14-35...
magicoder
jsx
You are tasked with implementing a custom link processor for a markdown parser. The processor should be able to parse link destinations and titles from a given input and assert the correct format of the link closing characters. Your task is to complete the implementation of the `LinkCloserProcessor` class by defining ...
```python import re from typing import Tuple class LinkCloserProcessor(commonmark.LinkCloserProcessor): @backtrack_onerror def parse_link_destination(self, reader: TextReader, document: Element) -> Tuple[str, str]: reader.step() destination = LinkDestinationParser().parse(reader, document) ...
magicoder
python
You are given an array of integers `a` of length `n`. Your task is to pair up the elements of the array in such a way that the sum of the indices of each pair is minimized. In other words, you need to pair up the elements such that the sum of the indices of each pair is as small as possible. Write a function or progra...
```cpp #include <iostream> #include <algorithm> using namespace std; bool cmp(int i, int j) { return a[i] < a[j]; } void findPairsWithMinSumIndices(int a[], int n) { int x[n]; int tot = 0; for(int i=0; i<n; i++) { tot += a[i]; x[i] = i; } sort(x, x+n, cmp); int l = n / 2; ...
magicoder
cpp
You are tasked with creating a program that checks whether a given number is a perfect number or not. A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. For example, 6 is a perfect number because the sum of its proper divisors (1, 2, 3) equals 6. Write a function ...
```python def is_perfect_number(num): if num <= 0: return False # Perfect numbers are defined for positive integers only divisor_sum = 0 for i in range(1, num): if num % i == 0: divisor_sum += i return divisor_sum == num ``` The `is_perfect_number` function first checks if...
magicoder
python
You are tasked with implementing a review page for a code review system. The review page is part of a larger system that manages code reviews, code files, and comments. The code snippet provided is a partial class for the ReviewPageModel, which is responsible for handling the review page's logic and interactions with t...
```csharp public Dictionary<CodeFile, List<Comment>> GetCodeFilesWithComments(int reviewId) { Dictionary<CodeFile, List<Comment>> codeFilesWithComments = new Dictionary<CodeFile, List<Comment>>(); // Retrieve review details using ReviewManager Review review = _manager.GetReviewById(reviewId); if (revi...
magicoder
csharp
You are working on a machine learning project that involves splitting a dataset into training, validation, and testing sets. The dataset is stored in a JSON file, and you need to write a script to split the data into the three sets based on a given ratio. Additionally, you need to ensure that the JSON file paths for th...
```python import json import random import shutil def split_and_update_paths(original_path, train_path, val_path, test_path, ratio): with open(original_path, 'r') as file: data = json.load(file) random.shuffle(data) total_samples = len(data) train_samples = int(total_samples * ratio) v...
magicoder
python
You are tasked with creating a PHP class that processes event data for a web application. The class should handle incoming HTTP requests and manipulate date and time information using the Symfony and Drupal libraries. Your task is to implement a class called `EventsController` that includes methods for processing even...
```php <?php namespace Drupal\avoindata_events\Controller; use Symfony\Component\HttpFoundation\Request; use Drupal\Core\Datetime\DrupalDateTime; /** * Adds event controller. * * Class EventsController * Implements event controller. * * @package Drupal\avoindata_events\Controller */ class EventsController { ...
magicoder
php
You are tasked with creating a Python function that extracts the names of the models from the given code snippet. The function should take the code snippet as input and return a list of model names. Create a function called `extract_model_names` that takes a code snippet as a string input and returns a list of model n...
```python import re def extract_model_names(code_snippet): model_names = re.findall(r"'(.*?)'", code_snippet) return model_names ``` The `extract_model_names` function uses the `re.findall` method to extract all the strings enclosed in single quotes from the input code snippet. It then returns the list of mod...
magicoder
python
You are tasked with implementing a custom serialization mechanism for a Java application. The application uses a class `Constants` to define various constant values. One of the constants is `SERIALIZABLE_NULL_KEY_PATH`, which is used to represent a special key path for handling null values during serialization. Your t...
```java import java.io.*; final public class Constants implements Serializable { public final static String SERIALIZABLE_NULL_KEY_PATH = "___SERIALIZABLE_NULL_KEY_PATH___"; // Custom serialization logic private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject();...
magicoder
java
You are tasked with implementing a generic networking client in Swift that can handle asynchronous requests and decode the response data into a specified type. Your task is to complete the implementation of the `load` function within the `NetworkingClient` class. The `load` function takes three parameters: `service`, `...
```swift func load<U>(service: T, decodeType: U.Type, completion: @escaping (CCResult<U>) -> Void) where U: Decodable { call(service.request) { result in switch result { case .success(let data): do { let resp = try JSONDecoder().decode(decodeType, from: data) ...
magicoder
swift
You are working on a project to defend against adversarial attacks on machine learning models. As part of this project, you need to implement a method to generate adversarial examples for a given dataset and model. An adversarial example is a sample that has been modified to cause a machine learning model to make a mis...
```python from GrootTreeClassifier import GrootTreeClassifier from DecisionTreeAdversary import DecisionTreeAdversary def generate_adversarial_examples(X, y, epsilon, max_depth): attack_model = [epsilon] * X.shape[1] groot_tree = GrootTreeClassifier(attack_model=attack_model, max_depth=max_depth) groot_tre...
magicoder
python
You are tasked with implementing a text layout algorithm for rendering text using signed distance fields (SDFs). An SDF is a grayscale image where the pixel values represent the distance to the nearest boundary. The given code snippet is part of a text layout algorithm that processes SDFs to render text. The algorithm ...
```rust impl TextLayoutAlgorithm { fn process_sdf(&mut self, offset_x: i32, offset_y: i32, sdf_width: i32, sdf_height: i32, sdf: &Vec<Vec<f32>>) { self.offset_x = offset_x + sdf_width; // Update the x-offset by adding the width of the current SDF self.offset_y = offset_y as i32; // Update the y-offs...
magicoder
rust
You are tasked with creating a program to manage a video recording interface in a macOS application. The given code snippet is part of the setup for the user interface. The program should allow the user to control video recording, select audio and camera sources, and display a preview of the recorded video. Your task ...
```swift class VideoRecordingManager { var audioInputSource: String? var cameraInputSource: String? var isRecording = false func startRecording() { // Start the video recording process isRecording = true } func stopRecording() { // Stop the video recording proce...
magicoder
swift
You are tasked with implementing a command-line argument parser for a compiler tool. The tool accepts various command-line options, and your task is to parse and process these options. The options are specified in a specific format, and your parser should be able to extract the relevant information from the command-lin...
```python from typing import List, Dict def parseCommandLineOptions(args: List[str]) -> Dict[str, str]: options = {} i = 0 while i < len(args): if args[i].startswith('-'): option = args[i][1:] if i + 1 < len(args) and not args[i + 1].startswith('-'): descript...
magicoder
python
You are tasked with implementing a generic stack data structure in Java. The stack should support the following operations: 1. `push(item)`: Add an item to the top of the stack. 2. `pop()`: Remove and return the item at the top of the stack. 3. `peek()`: Return the item at the top of the stack without removing it. 4. `...
```java import java.util.ArrayList; import java.util.List; public class GeneralStack<T> { private List<T> stack; public GeneralStack() { stack = new ArrayList<>(); } public void push(T item) { stack.add(item); } public T pop() { if (isEmpty()) { throw new ...
magicoder
java
You are tasked with creating a script to automate the benchmarking of a video encoding tool called `kvazaar`. The script will utilize the `make` command to compile the tool, extract two video files using 7z, and then run the `kvazaar` tool with specific parameters to measure its performance. The script will capture the...
```bash #!/bin/bash # Compile kvazaar tool with maximum CPU cores make -j $(nproc) echo $? > ~/install-exit-status cd ~ # Extract video files 7z x Bosphorus_3840x2160_120fps_420_8bit_YUV_Y4M.7z -aoa 7z x Bosphorus_1920x1080_120fps_420_8bit_YUV_Y4M.7z -aoa # Create executable script for kvazaar echo "#!/bin/sh ./kvaz...
magicoder
shell
You are tasked with implementing a class method to calculate Brunet's statistic for a given set of sentences. Brunet's statistic is a measure of lexical diversity, which is used to quantify the richness of vocabulary in a text. The formula for Brunet's statistic is given by: \[ V = N^{(V^b)} \] Where: - \( V \) is th...
```python class Sentence: def __init__(self, words): self.words = words class BrunetStatisticCalculator: def __init__(self, sentence_objs): """The init method to initialize with an array of sentence objects """ self.sentence_objs = sentence_objs def handle(self): ""...
magicoder
python
You are given a graph representing a town with `n` vertices numbered from 1 to `n`. The graph is represented as an adjacency list `graph`, where `graph[i]` contains the neighbors of vertex `i`. Additionally, there is a list `town_color` of length `n` initialized with -1, which will store the color of each town. Your t...
```python from typing import List def assign_town_colors(graph: List[List[int]]) -> List[List[int]]: n = len(graph) town_color = [-1] * n group = [] def dfs(v, past, color): town_color[v] = color if len(group) <= color: group.append([v + 1]) else: group[...
magicoder
python
You are tasked with implementing a custom sorting algorithm for a specific data structure. The data structure consists of a list of `run_info` objects, each containing information about a neural network optimization run. Each `run_info` object has the following attributes: - `cpu_time`: The CPU time taken for the optim...
```python class RunInfo: def __init__(self, cpu_time, other_attributes): self.cpu_time = cpu_time self.other_attributes = other_attributes def custom_sort_run_info(results): n = len(results) for i in range(n): for j in range(0, n-i-1): if results[j].cpu_time > results[j+...
magicoder
python
You are given a code snippet that contains various shell functions and comments. Your task is to analyze the code and identify the specific patterns and operations being performed within the functions. Your goal is to write a program that can parse and extract relevant information from the given code snippet. Specifi...
```python import re def extractLabelInfo(input_str): match = re.match(r's(\d+) -> s(\d+) \[label="h\((\d+)\) / _"\];', input_str) if match: return f"missState(s{match.group(1)}, {match.group(3)}) == s{match.group(2)}" else: return "Invalid input format" def hitState(input_str): match =...
magicoder
python
You are tasked with implementing a Rust function that interacts with the Android Java Native Interface (JNI) to create an instance of the `Eq` class from the `DynamicsProcessing` package in the Android media framework. The provided code snippet demonstrates the usage of the JNI to call the constructor of the `Eq` class...
```rust use jni::{JNIEnv, JavaVM, objects::JValue, sys::jint, sys::jobject, sys::jboolean, sys::jintArray}; use jni::errors::Error; fn create_eq_instance(arg0: bool, arg1: bool, arg2: i32) -> Result<(), String> { let jvm = JavaVM::get_env().map_err(|e| format!("Failed to get JavaVM: {}", e))?; let env = jvm.at...
magicoder
rust
You are tasked with implementing a class for reading data from a ROS bag file. The ROSBagReader class should be able to read and process data from a ROS bag file, which is a file format used in the Robot Operating System (ROS) for storing time-series data, such as sensor data, messages, and other information. The ROSB...
```cpp #include <iostream> #include <string> #include <cstdint> class RosBagReader { private: uint64_t frame_num; // frame number in streaming session (stream is looped, video sequence will be repeated again and again) std::string bag_file_name; // name of the ROS bag file being read public: RosBagReade...
magicoder
cpp
You are tasked with creating a Python class to manage Amazon S3 buckets. The class should have two methods: `list_buckets` and `create_bucket`. The `list_buckets` method should retrieve and print the names of all existing S3 buckets, while the `create_bucket` method should create a new S3 bucket with a specified name. ...
```python import boto3 class S3BucketManager: def __init__(self): self.s3_client = boto3.client('s3') def list_buckets(self): bck_rep = self.s3_client.list_buckets() for buck in bck_rep["Buckets"]: print(buck["Name"]) def create_bucket(self, bucket_name): self....
magicoder
python
You are tasked with implementing a simple job management system in Rust. The system will handle job creation requests and store information about the jobs, including their status and duration. You are provided with a code snippet that defines a `CreateRequest` struct using the `serde` crate for deserialization. The `C...
```rust use std::collections::HashMap; #[derive(Clone, Debug, Deserialize)] pub struct Duration { hours: u32, minutes: u32, seconds: u32, } #[derive(Clone, Debug, Deserialize)] pub struct CreateRequest { // Fields for job details } #[derive(Clone, Debug)] pub enum Status { Pending, InProgress...
magicoder
rust
You are tasked with creating a program to generate spectrogram images for a given set of audio files. A spectrogram is a visual representation of the spectrum of frequencies of a signal as it varies with time. The program should iterate through a list of audio files and produce spectrogram images for each file. Your t...
```python import librosa import matplotlib.pyplot as plt import numpy as np from typing import List def generate_spectrograms(audio_files: List[str]) -> None: for file in audio_files: # Load audio file y, sr = librosa.load(file) # Compute spectrogram D = np.abs(librosa.stft(y)) ...
magicoder
python
You are tasked with implementing a logging system for affirmations in a Java application. The code snippet provided is part of a logging framework and contains a method to retrieve an active affirmation. The `getActiveAffirmation` method is responsible for obtaining an active affirmation from a set of supported asserti...
```java private static Affirmation getActiveAffirmation() { // Assuming SUPPORTED_ASSERTIONS is defined and contains the supported assertions PojoClass loggerPojoClass = FacadeFactory.getLoadedFacadePojoClass(SUPPORTED_ASSERTIONS); // Assuming InstanceFactory.getInstance method returns an instance of the lo...
magicoder
java
You are tasked with creating a script to automate the setup of the atftp (Advanced Trivial File Transfer Protocol) software. The script should perform the following tasks: 1. Remove the existing atftp directory within the specified working directory. 2. Create a new directory named "atftp" within the working directory...
```bash #!/bin/bash working_directory="/path/to/working_directory" root_directory="/path/to/root_directory" source_url="https://freefr.dl.sourceforge.net/project/atftp/atftp-0.7.2.tar.gz" # Task 1: Remove existing atftp directory rm -Rf $working_directory/build/atftp # Task 2: Create a new atftp directory mkdir -p $...
magicoder
shell
You are tasked with creating a program to calculate the total discount for a group of children attending an event. The discount is based on the number of children in the group, and the discount rates are as follows: - 2 children: 10% discount - 3 children: 15% discount - 4 children: 18% discount - 5 or more children: 1...
```python def calculate_discount(num_children: int) -> int: if num_children == 2: discount_total = 10 elif num_children == 3: discount_total = 15 elif num_children == 4: discount_total = 18 elif num_children >= 5: discount_total = 18 + (num_children - 4) return discou...
magicoder
python
You are given a list of integers, and your task is to find the highest product of three distinct numbers from the list. Write a function `highest_product_of_three(nums)` that takes in a list of integers `nums` and returns the highest product of three distinct numbers from the list. For example, given the input list `...
To solve this problem, we can use a greedy approach to find the highest product of three distinct numbers from the list. We can achieve this by keeping track of the highest three numbers and the lowest two numbers in the list. Here's the Python function to solve the problem: ```python def highest_product_of_three(num...
magicoder
python
You are tasked with creating a function that validates a given connection string for a Service Bus in Azure. The connection string should adhere to a specific pattern to be considered valid. The pattern for a valid connection string is as follows: - It should start with "Endpoint=sb://" - Followed by any characters (de...
```javascript function validateConnectionString(connectionString) { const pattern = new RegExp('^Endpoint=sb://.*;SharedAccessKeyName=.*;SharedAccessKey=.*$'); return pattern.test(connectionString); } ``` The `validateConnectionString` function uses a regular expression to define the pattern for a valid connec...
magicoder
javascript
You are tasked with implementing a function `get_utf8_value` that takes a single parameter `value`. The function should return the UTF-8 encoded byte representation of the input value. The input `value` can be of various data types, including integers, strings, and lists. The function should handle each data type appro...
```python def get_utf8_value(value): if isinstance(value, int): return value.to_bytes((value.bit_length() + 7) // 8, 'big') elif isinstance(value, str): return value.encode('utf-8') elif isinstance(value, list): return [element.encode('utf-8') if isinstance(element, str) else element...
magicoder
python
You are tasked with creating a Python function that processes a list of migration files and extracts the names of the models being created. Each migration file is represented as a string, and the model names are enclosed within the `migrations.CreateModel` function calls. The model names are enclosed in single quotes a...
```python from typing import List import re def extract_model_names(migration_files: List[str]) -> List[str]: model_names = [] for migration_file in migration_files: match = re.search(r"migrations\.CreateModel\(name='(\w+)'", migration_file) if match: model_names.append(match.group(...
magicoder
python
You are tasked with implementing a custom token management system in Java. Your goal is to create a class that generates unique tokens for use in a bundle management system. The tokens should be immutable and unique for each instance of the class. Your task is to create a Java class called `TokenManager` that contains...
```java import java.util.HashSet; import java.util.Set; final class BundleToken {} public class TokenManager { private Set<BundleToken> tokenSet; public TokenManager() { tokenSet = new HashSet<>(); } public synchronized BundleToken generateToken() { BundleToken token = new BundleToke...
magicoder
java
You are working on a task scheduler system that manages dependencies between tasks. The system uses a graph-based representation to track the dependencies and operations to be performed. The given code snippet is a part of a method in the task scheduler class that handles the creation of new tasks and their dependencie...
```python def create_new_task_node(self, gid: int) -> int: if gid not in self.nodes: newGid = self.get_next_gid() self.nodes[newGid] = { 'head': gid, 'gid': newGid, 'remaining_ops': list(LgGraph.operator_dic.keys()), 'deps': {'fork' + str(newGid): newG...
magicoder
python
You are tasked with implementing a function that calculates the color at a specific point within a gradient. The gradient is defined by two colors, a start point, an end point, and a set of locations. The function should take the start color, end color, start point, end point, and locations as input, and return the col...
```swift func calculateColorAtPosition(startColor: UIColor, endColor: UIColor, startPoint: CGPoint, endPoint: CGPoint, locations: [CGFloat], position: CGFloat) -> UIColor { // Calculate the distance between start and end points let dx = endPoint.x - startPoint.x let dy = endPoint.y - startPoint.y let di...
magicoder
swift