id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
52
7.08k
00c88d2c64b3d335b588
```python import json class WebSocketClient: def on_message(self, message): """Callback for a message received from a WS client. Args: message: A JSON message. If not formatted appropriately, it is discarded. """ try: json_message = json.loads(me...
00ca537fdefaa47a2efd
```python def validate_path(path, HARDENED): if path[0] != 44 | HARDENED: return False if path[1] != 134 | HARDENED: return False if path[2] < HARDENED or path[2] > 1000000 | HARDENED: return False return True ``` The `validate_path` function replicates the logic of the given cod...
00ca581dbac5bf748d60
```python import pkg_resources def get_package_version(package_name): try: version = pkg_resources.get_distribution(package_name).version return version except pkg_resources.DistributionNotFound: return "Package not found" # Test the function print(get_package_version("simcore-models-l...
00cbb09f214d4d775c5e
```python from datetime import datetime, timedelta def floor_to_hour(dt): # Calculate the difference in minutes from the start of the hour minutes_past_hour = dt.minute + (dt.second / 60) # Subtract the minutes and seconds to round down to the start of the hour rounded_dt = dt - timedelta(minutes=...
00cc6aeb051a1f038f35
```python class Pipeline: def __init__(self): self.stages = [] def add_stage(self, func): # Add the provided function as a stage to the pipeline self.stages.append(func) def execute(self, data): # Execute the entire pipeline on the input data result = data f...
00cdd9f576d6b2646295
```python class Stack: def __init__(self): self.items = [] def push(self, item): """Add an item to the top of the stack.""" self.items.append(item) def pop(self): """Remove and return the item at the top of the stack.""" if not self.is_empty(): return se...
00ce467343d5e23d3d6d
```python from typing import List, Tuple def sort_files_by_stars(file_star_tuples: List[Tuple[str, str]]) -> List[str]: def get_average_stars(star_range: str) -> int: min_stars, max_stars = map(int, star_range.split('-')) return (min_stars + max_stars) // 2 file_star_tuples.sort(key=lambda x: ...
00ceab5c71b172b4cb90
```csharp public void ResolveBug(int bugId, string resolution) { // Assuming _client is an instance of the bug tracking client string comment = $"Resolution has changed to {resolution} by VersionOne"; _client.ResolveBug(bugId, resolution); _client.AddCommentToBug(bugId, comment); } ``` In the solution, ...
00cfa81801bef51ce417
To fulfill the requirements, you can use the following memory management system: ```cpp CMainControlPanelDlg* AllocateMainControlPanelMemory() { CMainControlPanelDlg* allocatedMemory = nullptr; try { allocatedMemory = new CMainControlPanelDlg; if (!allocatedMemory) { throw std::bad_...
00d1bf640e3f2ff8c4ec
```csharp public class HWPenSign { public void HWInitialize() { // Implementation for initializing the hardware pen sign device } public void HWFinalize() { // Implementation for finalizing the hardware pen sign device } public string HWGetBase64Stream(int index) { ...
00d64452c0e8eba01ee0
The `OAuthRedirect` class is implemented with the required properties `redirect` and `kind`, along with the methods `setRedirectUrl` and `setRedirectKind`. The constructor initializes the `redirect` and `kind` properties to empty strings. The `setRedirectUrl` method sets the redirection URL, and the `setRedirectKind` m...
00d6e401b708dc8f292a
```python class NeuralSignalAnalyzer: def __init__(self, sfreq, sw_settings): self.sfreq = sfreq self.sw_settings = sw_settings self.troughs_idx = [] def calculate_interval(self, trough_idx): if self.sw_settings["sharpwave_features"]["interval"] is True: if len(self....
00d75234709cf6f6f582
```python import tensorflow as tf import pyredner def set_gpu_flag(): if tf.test.is_gpu_available(cuda_only=True, min_cuda_compute_capability=None): pyredner.set_use_gpu(True) return True else: return False # Test the function print(set_gpu_flag()) ``` The `set_gpu_flag` function firs...
00dba1dd810652801dd0
```javascript function calculatePagination(data) { this.dtUsersCL = data['data']['user_list']; this.showingRecordsCL = data['data']['user_list'].length; this.totalRecordsCL = data['data']['totalRecords']; if (this.totalRecordsCL % this.showingRecordsCL == 0) { this.lastPageCL = (this.totalRecordsCL / this.s...
00dc27f91f02f6df1397
```swift func getText() { let text = getTextHandler() let processedText = processText(text) print(processedText) } func processText(_ text: String) -> String { let words = text.components(separatedBy: " ") let reversedWords = words.reversed() let reversedText = reversedWords.joined(separator: " ") return...
00dc84d5b64b7199fe23
```python # Step 1: Create a custom exception class class ConfigException(Exception): pass # Step 2: Modify the given code snippet to raise ConfigException try: # Your code that may raise a KeyError raise KeyError("example_key") except KeyError as e: raise ConfigException( 'Integration "{}" is ...
00dce5ad13ab0bc8c668
```python def key_to_path(k): return int.from_bytes(k, 'big') def find_max_path_value(keys): max_path_value = 0 for key in keys: path_value = key_to_path(key) if path_value > max_path_value: max_path_value = path_value return max_path_value # Test the function keys = [b'\x0...
00dcf9f8b93f93d4fce1
```cpp #include <iostream> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_debye.h> int main() { double input; std::cout << "Enter a value for the special functions calculation: "; std::cin >> input; // Calculate and display the scaled Bessel function of the first kind of order zero double bes...
00def417ee4be42693ba
```python class TableGenerator: def output_table(self, data): if not data: return '' # Return empty string if data is empty table_html = '<table>\n<tr>\n' headers = list(data[0].keys()) # Extract column headers from the first dictionary # Create header row for...
00df296edb55867f1d3e
```python def ccphiADD(circuit, q, ctl1, ctl2, a, n, inv): angle = getAngles(a, n) for i in range(n): if inv == 0: circuit.cu1(angle[i], ctl1, q[i]) circuit.cu1(angle[i], ctl2, q[i]) else: circuit.cu1(-angle[i], ctl1, q[i]) circuit.cu1(-angle[i], c...
00e0214fc789a264ca42
```python import aiohttp async def retrieve_data(dateField, from_, to_, on, last, first, sort, interval, **extra_params) -> str: base_url = "https://api.example.com/data" # Construct the query parameters params = { "dateField": dateField, "from": from_, "to": to_, "on":...
00e0b08af614c5450ae4
```bash #!/bin/bash # Function to handle errors handle_error() { echo "Error occurred: $1" exit 1 } # Print "STARTING EXPR DATA" echo "STARTING EXPR DATA" # Execute setup-expr.sh script if ! bash scripts/data/setup-expr.sh; then handle_error "Failed to set up experimental data" fi # Print "STARTING CHEM DATA"...
00e2122cfbe0d58677c7
```java protected void onMessageReceived(String channel, byte[] data, String pattern) { log.message("收到事件") .context(context -> { context.put("channel", channel); context.put("pattern", pattern); context.put("data", new String(data)); }) .log(); } ``` In ...
00e2358d0c7205755580
```python import sqlite3 class Database: def __init__(self, db_name): self.connection = sqlite3.connect(db_name) self.cur = self.connection.cursor() def test_database_connection(self): assert type(self.cur) is sqlite3.Cursor assert type(self.connection) is sqlite3.Connection #...
00e3e4d04ca37574f667
```python def parseCommand(command: str) -> dict: parts = command.split() program = parts[0] options = [part for part in parts[1:] if part.startswith('-')] arguments = [part for part in parts[1:] if not part.startswith('-')] return { "program": program, "options": options, "a...
00e54a75f09aa2ab28b0
```python import json from typing import List def execute_scripts(script_info_file: str) -> List[str]: with open(script_info_file, 'r') as file: data = json.load(file) scripts = data.get('scripts', []) script_map = {script['name']: script for script in scripts} executed_scripts = [] d...
00e7aa5eac1948633598
```typescript import { Component, OnInit, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef, Injector } from '@angular/core'; import { ToastComponent } from './toast.component'; // Assuming the existence of a ToastComponent @Component({ selector: 'app-toaster-container', template: ` <div clas...
00e7e66ac732c9f1ce88
```python import numpy as np from skimage.measure import ransac def estimate_transformation(input_data, output_data, simple=True): if simple: model, _ = tf.estimate(input_data, output_data) return model else: model, inliers = ransac((input_data, output_data), transform, min_samples=3, r...
00e965c6b6e133ba7312
```java import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class AdminLoginServlet extends HttpServlet { // Method to handle admin login public boolean han...
00eaaf5407a08f0aaaa3
```python from typing import List, Dict, Union def parse_arguments(args: List[str]) -> Dict[str, Union[str, int, bool]]: options = {'target': '', 'threads': 256, 'port': 80, 'tor': False, 'help': False} i = 0 while i < len(args): if args[i] in ['-t', '--target']: options['target'] = arg...
00ec595236d19829e932
```python class Layer: def __init__(self): pass def forward(self, input_data): raise NotImplementedError("forward method must be implemented in the derived class") class GLU(Layer): def __init__(self): super().__init__() def forward(self, input_data): # Implement Gate...
00ec6dd777e6d652ed66
```python import functools class LibraryNoCommit: def __init__(self): self.transaction_started = False self.query_result = None def start_transaction(self): # Logic to start a transaction self.transaction_started = True def commit_transaction(self): # Logic to comm...
00ed60a07a086f1c005b
```java class MeasurableMetrics { public static double average(Employee[] employees, MeasurableAttribute attribute) { double sum = 0; for (Employee employee : employees) { sum += attribute.getValue(employee); } return sum / employees.length; } public static doubl...
00ee2be07df378007fa9
```csharp using System; // Class representing a beatmap class Beatmap { public string File { get; set; } public string Path { get; set; } public string Background { get; set; } public string Track { get; set; } } // Class representing the beatmap manager class BeatmapManager { public Beatmap Worki...
00ee7cb86a162555c0ca
```php function generateRandomString($length, $characters) { $randomString = ''; $charactersLength = strlen($characters); for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } ``` The `generateRandomString` function initia...
00ee8f7197aebb1f8d92
```python def minimize_waiting_time(jobs): sorted_jobs = sorted(jobs, key=lambda x: x[0]) # Sort jobs by start time waiting_time = 0 scheduled_jobs = [] for job in sorted_jobs: waiting_time += job[1] * len(scheduled_jobs) # Calculate waiting time for the current job scheduled_jobs.app...
00ef2871a615d2aee709
```python def parameter_validator(annotation: dict): """ Decorator function that performs parameter validation and default value assignment for a given function. Args: annotation (dict): A dictionary containing parameter annotations and default values. Returns: function: The decorated function...
00ef9dded6943dd4189c
```python import os import sys import re def grep(pattern, directory): for root, dirs, files in os.walk(directory): for file in files: if file.endswith(".md"): file_path = os.path.join(root, file) with open(file_path, 'r') as f: for line in f:...
00f1c114f3889a6482a7
```python def reverse_abbreviations(rounds: dict) -> dict: return {abbrev: full for full, abbrev in rounds.items()} ``` The `reverse_abbreviations` function takes the input dictionary `rounds` and uses a dictionary comprehension to create a new dictionary with abbreviated round names as keys and the corresponding ...
00f2a1b76b9e17b8fec4
```cpp #include <functional> #include <iostream> #include <vector> class Callback { public: void AsStdFunction() { // Implementation not shown } }; class Child { private: std::vector<std::function<void()>> drainCloseCallbacks; public: auto addOnDrainCloseCb(const std::function<void()>& callba...
00f2cb33e7be2ecfeeee
```python from django.db import models from django_admin_thumbnails.fields import AdminThumbnail class ContentItem(models.Model): name = models.CharField(max_length=100) thumbnail = models.ImageField(upload_to='thumbnails/') @property @AdminThumbnail(image_field='thumbnail') def icon_thumbnail(sel...
00f98961358380b283eb
```cpp #include <iostream> #include <vector> class SlabAllocator { private: size_t slabSize; size_t numSlabs; std::vector<void*> memoryBlocks; std::vector<void*> freeBlocks; public: SlabAllocator(size_t slabSize, size_t numSlabs) : slabSize(slabSize), numSlabs(numSlabs) { for (size_t i = 0...
00fb196fa0c08c66fef1
```rust fn modify_string(input: &str, separators: &[char], alphabet: &[char]) -> String { let mut modified_string = String::new(); for c in input.chars() { if separators.contains(&c) { modified_string.push(c); } else if let Some(index) = alphabet.iter().position(|&x| x == c) { ...
00fb1e24def59ab60c6c
```python def extractAnswer(dataset, id): for person in dataset: if person["id"] == id: answer = person["answer"] # Replace placeholders with actual values for placeholder in set(re.findall(r'___MASK\d+___', answer)): placeholder_id = placeholder.strip('_M...
00fdaf0673600e711bdc
```python def fuel_required(mass): fuel = max(0, mass // 3 - 2) return fuel def calculate_total_fuel(masses): total_fuel = 0 for mass in masses: fuel = fuel_required(mass) total_fuel += fuel while fuel > 0: fuel = fuel_required(fuel) if fuel >= 0: # igno...
00fdc01f1005bc022db9
```python import subprocess def install_multipass(): try: subprocess.run(["sudo", "snap", "install", "multipass", "--classic"], check=True) print("Multipass installed successfully.") except subprocess.CalledProcessError as e: print(f"Error installing Multipass: {e}") def set_local_driv...
00fdf750ab85f75dc56e
```java import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; public class SamlProcessingFilter extends AbstractAuthenticationProcessingFilter { public SamlProcessingFilter() { super(new An...
00fffd176765c9fe6489
```python def categorize_dutch_words(words): verbs = [word for word in words.split() if word.endswith("en")] prepositions = [word for word in words.split() if word.islower() and not word.endswith("en")] return verbs, prepositions dutch_words = """ van veel voor vaak vanaf vandaan vanuit vanwege veeleer ve...
0100abf2a05bf20e2947
```python import multiprocessing import requests def worker_process(task_reader, task_writer): while True: # Receive tasks (URLs) from the task pipeline urls = task_reader.recv() # Scrape the content of the URLs results = {} for url in urls: try: ...
010193c2ab67cab8a44d
```python class RoboticsParameters: def __init__(self, dt: float = 0.08, gui: bool = True, num_substeps: int = 1, num_solver_iterations: int = 5, contact_erp: float = 0.9): # Initialize the class with default parameter values self.dt = dt self.gui = gui self.num_substeps = num_subste...
0101a7bc12efdc520c1a
```cpp #include <iostream> int main() { int inst, data1, data2, data0; std::cin >> inst >> data1 >> data2; if (inst == OP_ADD) data0 = data1 + data2; else if (inst == OP_SUB) data0 = data1 - data2; else if (inst == OP_MUL) data0 = data1 * data2; std::cout << "Result: ...
01030043345f8c24b837
```python class MultilabelsHead: def __init__(self): # Initialize the list of labels self.labels = [] def add_label(self, label): # Add the label to the list of labels self.labels.append(label) class Classifier: def __init__(self): # Initialize the list of labels a...
010331de2edb9d81ce27
```c TimerNode* allocateTimerNode() { if (UniqsTimerFreeCount > 0) { UniqsTimerFreeCount--; TimerNode* pTimer = __pFreeTimerHeadMem; __pFreeTimerHeadMem = pTimer->pNext; return pTimer; } else { // Handle error when no free timer nodes are available return NULL; ...
01038257f219311a7be5
```cpp #include <memory> #include <vector> // Define the Chunker class class Chunker { public: // ProcessFinal function to split the partial buffer into chunks std::vector<std::shared_ptr<Buffer>> ProcessFinal(std::shared_ptr<Buffer> partial, size_t first_pos) { // Assuming SliceBuffer function is avai...
0104421cba619c06097e
```rust fn even_fibonacci_sum(limit: u32) -> u32 { let (mut a, mut b) = (1, 2); let mut sum = 0; while b <= limit { if b % 2 == 0 { sum += b; } let next = a + b; a = b; b = next; } sum } fn main() { let limit = 4000000; println!("Sum of ...
0104570e43ae599f6f93
```csharp using System; using System.Text.RegularExpressions; public class UniqueIdentifier { private string _id; public string Id { get { return _id; } internal set { if (IsValidIdFormat(value)) { _id = value; } else ...
010577898a0da00aea9e
```javascript class Prefetcher { constructor() { this.pageMap = new Map(); // Map to store visited pages and their visit counts this.currentPage = null; // Variable to store the current page } visitPage(page) { if (this.pageMap.has(page)) { this.pageMap.set(page, this.pageMap.get(page) + 1); //...
0105d831d44b6cec976a
```python from PIL import Image import numpy as np import trimesh def mesh_imgs(imgs): vertices = [] faces = [] for img in imgs: # Convert PIL image to numpy array img_array = np.array(img) # Extract vertices and faces from the image # For demonstration purpose...
0105f1c8041904cda521
```python from sklearn.cluster import DBSCAN import numpy as np def run(data, epsilon=0.001, min_samples=200): X = np.array(data) clustering = DBSCAN(eps=epsilon, min_samples=min_samples).fit(X) labels = clustering.labels_ res = {} for i, label in enumerate(labels): if label not in res...
0106f382b11924d1e44e
Swift Package Manifest File (Package.swift): ```swift // swift-tools-version:5.3 import PackageDescription let package = Package( name: "MarketingVersionSetter", platforms: [ .macOS(.v10_15) ], products: [ .executable(name: "set-marketing-version", targets: ["SetMarketingVersionTool"]),...
01078493ad4314e25880
```python from rest_framework import serializers from .models import BoardProfile class BoardProfileSerializer(serializers.ModelSerializer): rendered_username = serializers.ReadOnlyField(source='get_rendered_username') rendered_rank = serializers.ReadOnlyField(source='get_rendered_rank') class Meta: ...
0107f6f806bed540c10a
```python import unittest from unittest.mock import Mock, patch def post_conf_load(): # Function to load post-processing configuration pass class TestPostProcessingRegistration(unittest.TestCase): @patch('module_name.p_Script') def test_post_conf_load_call_count(self, mock_p_script): post_conf...
0108081f611930a7c4df
```python from typing import List def replace_modname(folder_prefixes: List[str], mod_name: str) -> List[str]: for i, prefix in enumerate(folder_prefixes): if prefix == '%modname%': folder_prefixes[i] = mod_name return folder_prefixes ``` The `replace_modname` function iterates through the...
0108e37c9b837d205342
```swift import Foundation struct WebPage { let url: URL var content: String? enum WebPageError: Error { case invalidURL case contentFetchError } init(fromURL url: URL) throws { guard url.absoluteString.hasPrefix("http://") || url.absoluteString.hasPrefix("https://") else ...
0109b3b96f4a91275539
```python import cv2 def process_and_save_images(file_names): processed_images = {} for file_name in file_names: image_data = load_images(file_name) # Assume load_images function is available grayscale_image = cv2.cvtColor(image_data, cv2.COLOR_BGR2GRAY) processed_image = apply_specifi...
010b6b81cc78f3f6e4d9
```java import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class WordCounter { public static void main(String[] args) { File textFile = new File("input.txt"); File stopWordsFile = new File("stopwords.txt"); Map<String, Integer> wordCount = new HashMap<>()...
010b735abbd42f272458
```javascript function calcTime(time) { const hours = Math.floor(time / 3600); const minutes = Math.floor((time % 3600) / 60); const seconds = time % 60; return `${hours}:${minutes}:${seconds}`; } ``` The `calcTime` function takes the input `time` in seconds and calculates the time in hours, minutes, and secon...
010c6e8562b19aa921e8
```csharp using System; using System.Runtime.InteropServices; using System.Threading.Tasks; public interface IAwaiter<TResult> { bool IsCompleted { get; } TResult GetResult(); void OnCompleted(Action continuation); } [StructLayout(LayoutKind.Auto)] public struct ValueAwaiter<TResult> : IAwaiter<TResult> {...
010ca442eeee2e0f1e8a
```python import os import sys import requests from bs4 import BeautifulSoup from urllib.parse import urljoin, urlparse from urllib.request import urlretrieve def validate_url(url): try: response = requests.head(url) return response.status_code == 200 except requests.RequestException: r...
010cb1f24fae8a283af8
```java import jdk.nashorn.api.scripting.JSObject; import java.lang.reflect.Field; public class PropertyManager { public void addProperty(JSObject jsObject, String propertyName, Object value) { try { Field field = TestHelper.class.getDeclaredField("jsObject"); field.setAccessible(tr...
010da2bd04503dc5432f
```python from sqlalchemy import update def update_database_record(table, update_values, condition): # Construct the update statement update_stmt = update(table).where(condition).values(update_values) # Execute the update statement with engine.connect() as connection: # Assuming 'engine' is the S...
010dcbd9c43d21ef0982
```python def calculateAverageTime(num_robots, coverage_percent, dim_length, robot_type): efficiency_dict = { "type1": 0.9, # Efficiency factor for type1 robot "type2": 0.8, # Efficiency factor for type2 robot "type3": 0.7 # Efficiency factor for type3 robot } area_to_cover = (c...
010fd666ee17e1a7ff4b
```csharp private void DoWork(object state) { // Implement the task to be executed at regular intervals _logger.LogInformation("Executing timed task at: {time}", DateTime.Now); // Add your task logic here } ``` In the DoWork method, you can implement the specific task that needs to be executed at regular i...
010fdad1d1d5759f628e
```java import java.util.HashMap; import java.util.Map; public class TeamManager { private Map<String, Team> teams; public TeamManager() { this.teams = new HashMap<>(); } public void addPlayerToTeam(String playerName, String prefix, String suffix, int sortPriority, String playerTag, String te...
0112f4f36cd9b668fa15
```python from typing import List from torchvision.datasets import ImageFolder def calculate_label_distribution(dataset_path: str) -> List[int]: if not dataset_path: # Check if dataset_path is empty or None return None # Load the dataset using ImageFolder dataset = ImageFolder(root=dataset_path) ...
01140dd78a3f24c4df14
```python import re def countCSSClasses(html): class_pattern = r'class="([^"]+)"' classes = re.findall(class_pattern, html) class_counts = {} for css_class in classes: if css_class in class_counts: class_counts[css_class] += 1 else: class_counts[css_class] = 1 ...
011434a32213f9a01e62
```python import uuid from datetime import datetime def validate_build_plan_schema(build_plan_dict): # Check if all required keys are present in the dictionary required_keys = ['id', 'project_id', 'build_id', 'job_id', 'plan_id', 'date_created'] if not all(key in build_plan_dict for key in required_keys): ...
01149b9db3c3636c744e
```javascript // Memoization function to cache results of expensive computations function memoize(func) { const cache = new Map(); // Create a cache to store results return function (...args) { const key = JSON.stringify(args); // Generate a unique key for the function inputs if (cache.has(key)) { re...
0116426bfad1a778a253
```python def process_policy_kwargs(self, policy_kwargs: dict) -> None: self.units_critic = policy_kwargs.get("vf", 64) ``` In the solution, the `get` method of the dictionary is used to retrieve the value associated with the key "vf". If the key is present, its value is assigned to `self.units_critic`. If the key...
0117b2e2dcd97e5d6c8a
```javascript function getCloudinaryHostedTracks(musicDataArray) { return musicDataArray .filter(track => track.file.includes('res.cloudinary.com')) .map(track => track.title); } ``` The `getCloudinaryHostedTracks` function filters the music data array to include only tracks hosted on "res.cloudinary.com" by...
01188d415e07e752c4fb
```cpp class DataCache { private: // Private cache to store the data // ... public: // Other methods and members are not shown for brevity // GetData method to retrieve the data from the private cache // The data is copied out of the private cache // Implement this method Data GetData() { ...
01190f50a1dca96b69af
```python class Event: def __init__(self, event_type, can): self.event_type = event_type self.can = can @classmethod def from_bytes(cls, m): # Assuming m contains the necessary information to construct an Event instance # Implement the logic to create an Event instance from ...
0119ab7143c8963e27a7
The issues in the provided code snippet are as follows: 1. The `clearLoader` method is not being called properly within the `ngOnInit` and `ngOnDestroy` lifecycle hooks. 2. The arrow function syntax is not being used correctly. To correct the issues, the code should be modified as follows: ```typescript import { Comp...
0119c690b30b69cae754
```java import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; public class Feed...
011a94a7422206b7da5b
```javascript function exportModule(exports) { return { ...exports }; } // Usage const Constants = { PI: 3.14159, E: 2.71828, }; const exportedConstants = exportModule(Constants); console.log(exportedConstants.PI); // Output: 3.14159 console.log(exportedConstants.E); // Output: 2.71828 ```
011d5ed5b6910b9f9b2e
```python import requests def get_user_info(username_or_id, mode="0", search_by_id=False): base_url = "https://osu.ppy.sh/api/get_user" api_token = "your_osu_api_token" # Replace with your actual osu! API token params = { "k": api_token, "u": username_or_id, "m": mode, "ty...
011f6a77ec50f95bb1ce
```bash #!/bin/bash # Install rsync and vim vagrant ssh -- "sudo apt-get -q -y install rsync vim" # Install vagrant-vbguest plugin vagrant plugin install vagrant-vbguest # Check and install vagrant-hostsupdater plugin if AUTOMATICALLY_MANAGE_HOST_ENTRIES is set to "yes" if [ "$AUTOMATICALLY_MANAGE_HOST_ENTRIES" = "y...
01226d83d26f3dc4d085
```python from typing import List def process_class_folders(classes: List[str]) -> List[str]: output = [] for this_class in classes: # Perform the specific operation on the files within the class folder # Append the result of the operation to the output list output.append(f"Processed fi...
01239fc4f1a4535d6284
```python from typing import List, Tuple, Set def extract_app_labels(operations: List[Tuple[str, str]]) -> Set[str]: app_labels = set() for operation in operations: app_labels.add(operation[0]) return app_labels ```
01256bb11ad104ba3277
```rust struct Product { name: String, stock_quantity: u32, } struct Inventory { products: Vec<Product>, } impl Inventory { // Add a new product to the inventory fn add_product(&mut self, name: String, stock_quantity: u32) { self.products.push(Product { name, stock_quantity }); } ...
012723eb90aea4d2d31a
```swift import SwiftUI struct AchievementViewModel { var imageURL: URL // Other properties related to the achievement } struct AchievementsCardView: View { @Binding var achievementViewModel: AchievementViewModel var body: some View { LazyVStack { ZStack { AsyncIma...
0127cc6bcda81394f5b2
```python class TestJsonData(unittest.TestCase): @requests_mock.Mocker() def test_import_json_data_success(self, m): # Mock the HTTP request and response m.get(endpoint, text=response_request) # Create an instance of HandleJsonData handle_json = HandleJsonData() # Impor...
012868f4b1e89c903503
```python import numpy as np def simplexy(img, **kwargs): # Transpose the image and convert to float32 transposed_img = np.ascontiguousarray(img.T, dtype=np.float32) # Call the run_simplexy function with transposed image and keyword arguments r = run_simplexy(transposed_img, **kwargs).T #...
0129b57575dd4e0f24f5
```python def isWin(board): for i in range(3): # Check rows and columns for a win if board[i][0] == board[i][1] == board[i][2] != False or board[0][i] == board[1][i] == board[2][i] != False: return True # Check diagonals for a win if board[0][0] == board[1][1] == board[2][2] != ...
0129f7ac206aea90c86c
```python import pathlib def get_file_types(directory_path): directory = pathlib.Path(directory_path) file_types = set() for file_path in directory.iterdir(): if file_path.is_file(): file_types.add(file_path.suffix[1:]) return list(file_types) ``` The `get_file_types` function firs...
012ab0e66b881e57607a
```csharp public override void OnStartLocalPlayer() { // Assuming the specific action is jumping // Play the jump sound effect audioData.PlayOneShot(jumpSoundClip); } ``` In the solution, the `OnStartLocalPlayer` method is completed to play a sound effect when the player character performs a specific actio...
012b7c8f4c368b2dc341
```python def custom_normpath(path: str) -> str: components = path.split('/') stack = [] for component in components: if component == '' or component == '.': continue elif component == '..': if stack and stack[-1] != '..': stack.pop() else:...
012d2dc2a3b86754d34d
```java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import java.util.Queue; import java.util.LinkedList; class Producer implements Runnable { // ... (same as in the problem description) public void run() { while (true) { consumer_lock.lock(...
012e1e456eaefe0a6667
```python def calculate_average_metrics(metrics_data): metric_sums = {} metric_counts = {} for data in metrics_data: for metric, value in data.items(): if metric in metric_sums: metric_sums[metric] += value metric_counts[metric] += 1 else:...
01316011ebbe538b4ab8
```python from datetime import datetime class TimexRelativeConvert: @staticmethod def convert_timex_to_string_relative(timex: str) -> str: input_time = datetime.strptime(timex, "%Y-%m-%dT%H:%M:%S") current_time = datetime.now() if input_time > current_time: time_di...