id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
52
7.08k
02146a4186568c550820
```python import re from collections import Counter def count_words_in_file(file_path, top_n): with open(file_path, 'r') as file: text = file.read() words = re.findall(r'\b\w+\b', text.lower()) # Extract words and convert to lowercase word_counts = Counter(words) top_words = word_c...
0216165640fa67c6e670
```python import pandas as pd def sort_features_by_priority(features, prev_importance_df, using_prev_fit_fi): # Create a DataFrame for the current features curr_importance_df = prev_importance_df[~prev_importance_df.index.isin(using_prev_fit_fi)] # Sort the features by importance sorted_prev_fit_f...
021622e8054ce800018f
```cpp #include <iostream> #include <vector> template <typename T> class Vector { public: Vector(int size) : data(size, 0) {} T& operator[](int index) { return data[index]; } const T& operator[](int index) const { return data[index]; } void zero() { for (auto& element : data) { elem...
02176c04c05bf86f0e1f
```python from enum import Enum class Action: def perform(self, character): pass class StepAction(Action): def perform(self, character): character.step() class TurnAction(Action): def perform(self, character): character.turn() class ActionType(Enum): STEP = 'STEP', StepAction...
02183ce64c67f5be6138
```rust struct Token { name: String, symbol: String, // Other fields can be added if necessary } fn decode_erc20_token(rpc_responses_unmarshalled: &UnmarshalledResponses, pair_token_address: &str) -> Result<Token, String> { let decoded_name = read_string(rpc_responses_unmarshalled.responses[1].raw.as_r...
0218d09ca36769ba6c87
```javascript function foo(arr) { let maxSum = arr[0]; let currentSum = arr[0]; for (let i = 1; i < arr.length; i++) { currentSum = Math.max(arr[i], currentSum + arr[i]); maxSum = Math.max(maxSum, currentSum); } return maxSum; } ``` The solution uses Kadane's algorithm to find the maximum sum of a ...
0219cbb2c87c7fb1a129
```python from django import forms from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User class LoginForm(AuthenticationForm): username = forms.CharField( max_length=255, widget=forms.TextInput(attrs={'class': 'form-control form-control-sm'}), h...
0219eecf25cb51aa7201
```python import urllib.parse def serialize_payload(action, **kwargs): payload = f"Action={action}&" for key, value in kwargs.items(): payload += f"{key}={urllib.parse.quote(str(value))}&" return payload.rstrip('&') ``` The `serialize_payload` function takes the action as a mandatory parameter and...
021c5a5c1b01594c53d6
```python import rospy from std_msgs.msg import String, StdString from std_msgs.msg import Float32MultiArray import scipy.io as io memory = {} # Initialize memory data structure def label_callback(data): # Process the received String message for 'label' pass # Add your processing logic here def labelstd_ca...
021e736109710a5fa9c1
```java // Assuming the XML layout file contains EditText elements for user input and TextView elements for displaying the information. // Retrieve user input and display the information @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.a...
021f794a934dbf5375ac
```java public class InvoiceController { private InvoiceService invoiceService; // Other methods and dependencies are not shown for brevity /** * Update delivery date of an existing invoice * * @param authorization User's auth token * @param deliveryDateMap Delivery date information...
021fcef19c23ef2c9df2
```python import logging def log_users_with_no_shared_libraries(users): logger = logging.getLogger(__name__) for user in users: if not user["shared_libraries"]: logger.warning(f"Skipped User with No Libraries Shared: {user['username']}") ``` The `log_users_with_no_shared_libraries` functio...
022016527b11b71a4623
```rust // third-party imports use criterion::{criterion_group, criterion_main, Criterion}; use serde_json as json; use stats_alloc::{Region, StatsAlloc, INSTRUMENTED_SYSTEM, Stats}; #[global_allocator] static GLOBAL: &StatsAlloc<System> = &INSTRUMENTED_SYSTEM; fn benchmark(c: &mut Criterion) { let mut c = c.benc...
022168a14c63e4520112
```python # Prompt the user to input the volume of the substance volume = float(input("Enter the volume of the substance please: ")) # Define the density of the substance density = 1.2 # Density in g/cm³ # Calculate the mass using the provided formula mass = volume * density # Display the calculated mass rounded to...
02219b2fdc59ddf16821
```cpp #include <iostream> #include <fstream> #include <string> std::string generateMenuEntryCode(const std::string& appName) { std::string codeSnippet = "MenuEntry(std::make_shared<AppLauncher>(c, std::make_shared<" + appName + ">()))"; return codeSnippet; } int main() { std::string appName = "Calculator...
02224140896f12098854
```php function generateOrderBadges($orderStatuses) { $html = ''; foreach ($orderStatuses as $status) { switch ($status) { case 'Processing': $html .= '<span class="badge badge-outline-primary">' . $status . '</span>'; break; case 'Delivered': ...
022258e6b57d24a39781
```python import numpy as np class ReinforcementLearningAgent: def __init__(self): self.epsilon = 0.1 @lab_api def sample(self): # Simulates a sample from the environment # Implement logic to sample from the environment and return the observed state observed_state = ... # ...
022588872c6e24d55bfd
```python class ShoppingCart: def __init__(self): self.products = [] def add_product(self, product_name, price): self.products.append((product_name, price)) def remove_product(self, product_name): for product in self.products: if product[0] == product_name: ...
02269b08ea6173ca7a61
```rust fn serialize_data(data: &[u8], has_len_field: bool) -> Vec<u8> { let content_len = data.len(); let mut buffer = Vec::with_capacity(content_len + if has_len_field { 2 } else { 1 }); let mut header: u8 = 0; if has_len_field { header += 0b1000_0000; // Set the MSB to indicate the presence...
0227614a102813378b64
```python class EnvLogger: @staticmethod def error_observe_before_reset(): # Log an error message indicating that the environment is being observed before it has been reset logging.error("Error: Observing the environment before it has been reset") @staticmethod def error_state_before_re...
0227a6186d1e97010364
```python from typing import List def max_sum_subarray(num: List[int]) -> int: max_sum = float('-inf') current_sum = 0 for i in range(len(num) - 11): # Ensure the subarray is at least 12 elements long for j in range(i, len(num)): current_sum += num[j] if j - i >= 11: # Che...
0228be8a15503d93ffb4
```php try { // Establish a secure database connection using PDO $dsn = "mysql:host=localhost;dbname=your_database_name"; $username = "your_username"; $password = "your_password"; $pdo = new PDO($dsn, $username, $password); // Set PDO to throw exceptions on error $pdo->setAttribute(PDO::ATT...
022927f60adff3871497
```python import argparse from pathlib import Path def clean_ipynb_file(ipynb_file_path, back_up, keep_output): # Implement the logic to clean the .ipynb file by clearing output and formatting the code using isort and black # Optionally, create a backup of the original file and retain the output cells based on...
0229b57bd8cfd436b99d
```python import numpy as np def peak_intensity_value(image): # Flatten the 2D image array into a 1D array flattened_image = image.flatten() # Calculate the intensity histogram using numpy's histogram function hist, bin_edges = np.histogram(flattened_image, bins=range(256)) # Find the int...
022a2c7108e3288c3551
```python import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from contextlib import closing def create_and_drop_test_database(host: str, user: str, password: str) -> None: # Connect to the PostgreSQL server and create a new test database with closing(psycopg2.connect(host=host, user=use...
022aa1984c6c63462feb
```java import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.Thumbnails.Builder; import java.io.File; import java.io.IOException; public class ImageTransformationHandler implements TransformationHandler { @Override public void handleTransformation(Builder builder) { try { ...
022acfe1cbc24803a685
```python def generate_install_commands(packages): package_list = packages.split() install_commands = ["sudo apt install " + package for package in package_list] return install_commands ``` The `generate_install_commands` function first splits the input string `packages` into a list of individual package n...
022b3f6d6f0de9571045
```python from typing import List, Tuple from django.db import migrations def extract_file_field_info(operations: List[migrations.AlterField]) -> List[Tuple[str, str, str]]: file_field_info = [] for operation in operations: if isinstance(operation.field, migrations.FileField): model_name = ...
022c93584ddd006d831e
```c UINT64 sumLookup(const BYTE* pb, UINT nQuantumSize, UINT nOuterQuantum, UINT nInnerQuantum, UINT nIndex) { UINT64 sum = 0; // Lookup the value in the monotonic data structure UINT64 monotonicValue = lookupMonotonic(pb, nQuantumSize, nIndex); sum += monotonicValue; // Lookup the value in the p...
022e0966eb13a2f1d4b2
```java public String mergeCandidates() { return String.join(", ", mergeCandidates); } ``` The `mergeCandidates` method uses the `String.join` method to concatenate all the candidates in the list into a single result, separated by a comma and a space. If the list is empty, it returns an empty string. This solution...
022eea529114ac33b1c1
```cpp #include <iostream> #include <sstream> #include <string> void parseFailureConnectionCondition(const std::string& input, std::string& name) { std::stringstream stream(input); char discard; // To discard characters like '#', '=', '(', etc. // Discard the initial characters until the opening parenthes...
022f266ed106905ff9bd
```cpp void remove(size_t index) { if (index >= size) { throw std::out_of_range("Index out of range"); } for (size_t i = index; i < size - 1; ++i) { elements[i] = elements[i + 1]; } size--; } ```
022fe3038a605e67f3d7
```cpp #include <iostream> class CswClockedDevice { private: int _nChannels; // Number of channels int pSampleRate; // Sample rate public: CswClockedDevice(): _nChannels(0), pSampleRate(100) {} void setChannels(int channels) { _nChannels = channels; } int getSampleRate() { re...
0230458583f7e59d61c3
```python from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField() display_name = serializers.CharField(max_length=100) last_modified = serializers.DateTimeField() icon_media_key = serializers.CharField(max_length...
023216881d1c979cc946
```python def perform_parameter_mapping(measurement_df, condition, sbml_model, condition_df): cur_measurement_df = measurements.get_rows_for_condition(measurement_df, condition) if 'PREEQUILIBRATION_CONDITION_ID' not in condition \ or not isinstance(condition['PREEQUILIBRATION_CONDITION_ID'], str) ...
02348597f98e8fa08fb4
```csharp public class HandlerScope { public async Task ProcessMessageAsync(Handler handler, Context context, Message msg) { try { await handler.ProcessAsync(context, msg); } catch (Exception ex) { // Allow the caller to decide an appropriate respo...
023506817aaa9d354592
```python import sys import subprocess def pylint(file_list): # Simulate running pylint on the given file list for file in file_list: # Perform pylint analysis and print results print("- {}: {} issues found".format(file, simulate_pylint_analysis(file))) def simulate_pylint_analysis(file): ...
02355f7007e057d34977
```python def chunks(fp, bufsize=4096): while True: chunk = fp.read(bufsize) if not chunk: break yield chunk def chars(fp, bufsize=4096): for chunk in chunks(fp, bufsize): for char in chunk: yield char def handle_ref_input(src, offset, length): """Fi...
0237cddb476b56dc26a7
```python class PackageManager: def __init__(self): self.dependencies_map = {} def add_dependency(self, package, dependencies): """ Add a package and its dependencies to the dependencies map. :param package: str, the name of the package :param dependencies: list of str,...
0239a4913b95c92d15c4
```python import requests class Base: def __init__(self, auth_token): self.auth_token = auth_token def get_url(self, extra=''): base_url = 'https://api.example.com' return base_url + self.__endpoint__ + extra def validate_response(self, response): return response.status_co...
0239bb63993faec84e56
```python def count_word_occurrences(file_name, words_to_search): word_counts = {word: 0 for word in words_to_search} with open(file_name, 'r') as file: for line in file: for word in words_to_search: word_counts[word] += line.upper().count(word) for word, count in word_...
023a13516e8eca03cc79
```python class AnimationSystem: def __init__(self): self.animationTimer = AnimationTimer() self.frame = 0 def setUpdateInterval(self, interval): # Set the update interval of the animation timer self.animationTimer.setUpdateInterval(interval) def setDuration(self, duration)...
023a8136dcbd735268bd
```java public class Farm { private String name; private Map<String, Integer> animalInventory; public Farm(String name) { this.name = name; this.animalInventory = new HashMap<>(); } public String getName() { return name; } public void addAnimal(String animalName, i...
023b624924f7eb1922db
```python def write(self, name: str, f: File[T], *, _retry: bool = False) -> None: fullpath = self.output.fullpath(name) try: with open(fullpath, 'w') as file: file.write(f.content) # Assuming the File class has a 'content' attribute representing the file's content except FileNotFoundEr...
023b79386c59fc6225c5
The issue in the provided code snippet is that the JavaScript function `redirection` is being referenced without being defined. Additionally, the PHP syntax is incomplete and does not have a corresponding opening tag. To fix the issue and achieve the desired redirection behavior, the JavaScript function `redirection` ...
023cf5c32b4beadd1dbd
```csharp using System; using System.Collections.Generic; using System.Linq; public class MedianStars { public static int FindMedianStars(List<int> stars) { stars.Sort(); int n = stars.Count; if (n % 2 == 0) { return (stars[n / 2 - 1] + stars[n / 2]) / 2; } ...
023dde30a2c93f937f1e
```bash #!/bin/bash running_total=0 while [ $# -gt 0 ]; do case "$1" in -a) shift running_total=$((running_total + $1)) ;; -s) shift running_total=$((running_total - $1)) ;; -m) shift running_to...
023e732818275365fea1
```java public static String findClosestSensor(int[] sensorDistances) { int minDistance = Integer.MAX_VALUE; int closestSensorIndex = 0; for (int i = 0; i < sensorDistances.length; i++) { if (sensorDistances[i] < minDistance) { minDistance = sensorDistances[i]; closestSensor...
023e9e41cd165fd1d3b0
```rust struct ParseError(String); impl ParseError { fn new(message: &str) -> Self { ParseError(message.to_string()) } } impl From<Option<()>> for ParseError { fn from(_: Option<()>) -> Self { ParseError::new("Script unexpectedly ended.") } } ``` The provided solution completes the im...
023f471eac72debc4a7c
```swift class MenuSystem { func menuDidClose(node: Node) { print("Menu closed: \(node.name)") } } class Node { let name: String init(name: String) { self.name = name } } // Example usage let menuSystem = MenuSystem() let node1 = Node(name: "File") let node2 = Node(name: "Edit...
02428bf317f6f38a2ba9
```python import theano import theano.tensor as T def calculate_mean_std(_input): mean_expression = T.mean(_input) std_expression = T.sqrt(T.mean(T.sqr(_input - mean_expression))) return mean_expression, std_expression ```
024305b147db356e4f40
```javascript class Bot { constructor(name) { this.name = name; } greet() { return `Hello, ${this.name}!`; } } export default Bot; ``` The completed implementation of the bot class sets the bot's name using the constructor and ensures that the `greet` method returns the correct greeti...
02447a59008829fc3d11
```python def check_edge_condition(px, py, pyaw, start_x, start_y, start_yaw, end_x, end_y, end_yaw): assert abs(px[0] - start_x) <= 0.01, "Start x position mismatch" assert abs(py[0] - start_y) <= 0.01, "Start y position mismatch" assert abs(pyaw[0] - start_yaw) <= 0.01, "Start yaw orientation mismatch" ...
02459ad84790f8cb5eeb
```java public class Rectangulo { private int lado; private int altura; public Rectangulo(int lado, int altura) { this.lado = lado; this.altura = altura; } public int calcularArea() { return lado * altura; } public int calcularPerimetro() { return 2 * (lado...
0245b0bbe5493d2d7aa4
```python from typing import Dict class DataProcessingPipeline: def __init__(self, config: Dict, logdir: str): self._config = config self._logdir = logdir self.stages_config: Dict = {} def __prepare_logdir(self): # Implementation of setting up the log directory pass ...
02461099ebe8a785a540
```php class TestFramework { /** * Prepare the database before running the test suite. */ public static function prepare() { // Use Laravel's Artisan commands to migrate the database schema \Artisan::call('migrate'); // Use Laravel's Artisan commands to seed the database w...
0248683b31140450a8ad
```javascript // Sample data structure for tasks and folders const folders = [ { id: 1, name: 'Work' }, { id: 2, name: 'Personal' } ]; const tasks = [ { id: 1, folderId: 1, description: 'Complete project report', isComplete: false }, { id: 2, folderId: 1, description: 'Prepare presentation slides', isComplete:...
024998c5738de209e98e
```javascript function stringToHTML(input) { const wrapper = document.createElement('div'); wrapper.innerHTML = input; return wrapper.firstChild; } ``` The `stringToHTML` function creates a temporary `div` element using `document.createElement` and sets its `innerHTML` to the input string. This effectively conve...
0249a2c63e81c370c474
```python import math class DistanceCalculatorImpl(DistanceCalculator): def __init__(self): self.points = [] def add_point(self, x, y): self.points.append((x, y)) def get_distance(self, i, j): x1, y1 = self.points[i] x2, y2 = self.points[j] return math.sqrt((x2 - x...
024b5ec890907fa12c80
```python from bs4 import BeautifulSoup class HTMLLinkExtractor: def __init__(self): self.LinkList = [] def extract_links(self, html_content, filetype): soup = BeautifulSoup(html_content, 'html.parser') for tp in soup.find_all('a', href=True): tp_link = tp.get('href') ...
024c56566dde8a714425
```swift private func _process(_ response: ImageResponse, isCompleted: Bool, processors: [ImageProcessing]) { guard let processor = processors.last else { self.decompressImage(response, isCompleted: isCompleted) return } var remainingProcessors = processors remainingProcessors.remov...
024c61c04071c0e1638d
```python from typing import Dict from pyroute2 import IPRoute from dataclasses import dataclass @dataclass class WireGuardClient: remove: bool # Indicates whether to remove FDB entries def bridge_fdb_handler(client: WireGuardClient) -> Dict: with IPRoute() as ip: operation = "del" if client.remove e...
024faa1aea312f7f0f39
```c #include <stdio.h> typedef struct { int id; int size; char type[20]; } cache_t; void set_caches(cache_t *caches, int num_caches) { for (int i = 0; i < num_caches; i++) { printf("Setting attributes for cache %d:\n", caches[i].id); printf("Size: %d\n", caches[i].size); print...
024fec13e7951429db8f
```python from flask import Flask from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity from flask_restful import Resource, Api app = Flask(__name__) app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this to a secure random key in production api = Api(app) jwt = JWTManage...
0251d18529b4008cf22d
```python from typing import List, Tuple from sympy import mod_inverse from functools import reduce class Shamir: @staticmethod def split_secret(secret: int, num_shares: int, threshold: int) -> List[Tuple[int, int]]: shares = [] coefficients = [secret] + [randint(1, 100) for _ in range(threshol...
0252cfbbefbc022d9fd4
```python import re def normalize_words(msg): # Remove non-alphabetic characters and convert to lowercase words = re.findall(r'\b\w+\b', msg.lower()) return words ``` The `normalize_words` function uses the `re` module to find all word sequences in the input message, converts them to lowercase, and return...
0254c3b483b5d11c164a
```python from pycrunch_trace.client.api import trace from time import sleep def alternative_ways_to_trace(): with trace("sleep_execution"): sleep(0.25) trace_data = trace.get("sleep_execution") elapsed_time = trace_data.elapsed_time print(f"The execution time of sleep(0.25) is: {elapsed_time} ...
02562d2e643d58322d29
```php class PropertyHistoryManager { private $oldValue = null; private $history = []; public function updateValue($newValue) { $this->history[] = $this->oldValue; $this->oldValue = $newValue; } public function getHistory() { return $this->history; } } ``` In t...
0256cf11b2759e568a2b
```python self.up1 = upblock(in_channels=256, out_channels=256) # Returns out_channels / 2, and spatial size x 2, (128x64x128) self.up2 = upblock(in_channels=128, out_channels=128) # Returns out_channels / 2, and spatial size x 2, (64x128x256) self.up3 = upblock(in_channels=64, out_channels=64) # Returns out_channel...
0258ff0c2877bb729995
```python class Perfil: def __init__(self, username, tipo): self.username = username self.tipo = tipo self.carritoDCompras = [] # Initialize an empty shopping cart for each user class Reporter(Perfil): def __init__(self, username, tipo="Reporter"): super().__init__(username, ti...
0259ef88551daa4fc097
```jsx import React from 'react'; const NavBarComponent = () => { return ( <nav> <ul> <li><a href="#home">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#services">Services</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav> ); }; expor...
025aa43bead6bf3f33fa
```python from collections import Counter def calculate_total(prices, cart): total_cost = 0.0 for product, units in cart.items(): total_cost += units * prices[product] return total_cost # Test the function prices = {"course": 97.99, "book": 54.99, "wallpaper": 4.99} cart = Counter(course=1, book=3...
025c24bc13993827f69e
```python def generateSystemId(countryCode, networkCode, cellId): systemId = (countryCode * 65536) + (networkCode * 256) + cellId return systemId # Test the function countryCode = 123 networkCode = 45 cellId = 67 print("System ID =", generateSystemId(countryCode, networkCode, cellId)) ``` The `generateSystemI...
025d8b8882ee97649937
```python import random def donald_response(message): responses = [ "ドナルドは偉大なリーダーです。", "ドナルドの政策には賛成です。", "ドナルドについての話題は避けたいです。", "ドナルドのことはよく知りません。", ] if 'ドナルド' in message: return random.choice(responses) else: return "" ``` The `donald_response` fun...
0261b9159bb2e5179f24
```python import socket import os import mimetypes from threading import Thread class MipiWSServer: def __init__(self, mipi): self.host, self.port = mipi self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEAD...
0261de91c88a5e749090
```python import os import shutil from pathlib import Path def rename_files(src_dir, file_ext): count = 1 for file in os.listdir(src_dir): if file.endswith(file_ext): file_rename = file.replace(file_ext, f"_{count}{file_ext}") shutil.move(Path(src_dir) / file, Path(src_dir) / fi...
026250bdff2292001a3f
```python import torch def forward_pass_with_log_det(x, neural_network_forward): # Perform the forward pass of the neural network y = neural_network_forward(x) # Compute the Jacobian matrix using automatic differentiation J = torch.autograd.functional.jacobian(neural_network_forward, x) # Compute...
0262830614d3d6d7ba10
```csharp void Update() { if (lifetime > 0) { lifetime -= Time.deltaTime; if (lifetime <= 0) { Destroy(gameObject); } } } void OnTriggerEnter2D(Collider2D col) { if (col.gameObject.tag == "Player") { // Handle power-up collection by the player // Example: Grant temporary ability to the ...
0264aa3db7f54b538df6
```python import help as hp import torch try: # load the data print('Loading data') data_path = "path_to_data_directory" train_loader, validation_loader, test_loader = hp.data_load(data_path) # build model architecture = "specified_architecture" print(f'Loading weights from {architecture}'...
0264b4199b0621ced6fc
```python import plotly.graph_objects as go def add_violin_trace(fig, y, name): showlegend = False if name == "" else True fig.add_trace( go.Violin( y=y, name=name, box_visible=True, showlegend=showlegend, ) ) ``` The `add_violin_trace` funct...
02655ec43e0d8f460244
```python from typing import List, Union class RenameField: def __init__(self, model_name, old_name, new_name): self.model_name = model_name self.old_name = old_name self.new_name = new_name class AddField: def __init__(self, model_name, field_name, field_type): self.model_name...
0265b9e9315d36f28250
```swift open func resetToInitial() { self.selected = selectedStateMemory } ``` In the `resetToInitial` method, the switch's `selected` property is set to the value stored in `selectedStateMemory`, effectively resetting the switch to its initial state. This solution leverages the `selectedStateMemory` variable to ...
0266274b683cd02677c7
```python import datetime # Constants representing the file time epoch and the number of microseconds in one unit of file time FILE_TIME_EPOCH = datetime.datetime(2000, 1, 1) # Example epoch date FILE_TIME_MICROSECOND = 1 # Example value def convert_file_time_to_datetime(file_time): # Convert the file time to m...
026839d75b90e46d5a1d
```python import docker def restart_apache_in_container(container_id, service_name): try: client = docker.from_env() container = client.containers.get(container_id) if container: exec_command = f"service {service_name} restart" exec_response = container.exec_run(exec...
02686daa929492da01e2
```python import sys class Hub: def device_obj_from_id(self, device_id): # Implementation of device_obj_from_id method pass # Create a hub object hub_obj = Hub() # Retrieve the device object based on the command-line argument args = sys.argv if len(args) > 1: if args[1] == "type": nod...
0269df059ef9ec79d190
```python from pathlib import Path from typing import List class VocMaskFile: def __init__(self, file_path: Path): self.file_path = file_path class SingleSplitSplitter: def split(self, data): return [data] class VocMaskParser: def __init__(self, masks_dir: Path): self.masks_dir = ...
026d7cb65ab2371099f4
```bash #!/bin/bash # Navigate to the coreapi directory and install Node.js packages cd /opt/gopath/src/github.com/hyperledger/fabric/work/server/coreapi npm install # Navigate to the exp directory and install Node.js packages cd lib/common/exp npm install # Navigate to the fabric_v1.0 directory and install Node.js ...
026e1af061ad5a8becd8
```java import java.util.Map; public class ChunkStatusHelper { public static String getParentStatus(Map<String, String> chunkStatuses, String statusName) { if (chunkStatuses.containsKey(statusName)) { String parentStatus = chunkStatuses.get(statusName); return parentStatus != null ?...
026e3b3e6cfd0cfb90dd
```python class DataProcessor: @classmethod def process_output_single(cls, data, stm): res = None # Default result if not isinstance(data, OutputData) or stm is None or not stm.readable(): cls._logger.error("Invalid OutputData object or stream for output single") return ...
0271644660f171447913
```csharp using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using System.Text; namespace Cybtans.Tests.Services { public class JwtAuthenticationService : IAuthenticationService { private readonly string _secretKey; public J...
02736e4ed931c3045655
```python # Open the file named WORDLIST_FILENAME in read mode with open(WORDLIST_FILENAME, 'r') as inFile: # Initialize variables to store the longest word and its length longest_word = "" max_length = 0 # Iterate through each line in the file for line in inFile: # Remove any leading o...
0274656c0f9a4e7c24d4
```php <?php class UserProfile { private $username; private $password; private $nama; // Name in Indonesian private $email; private $gender; private $alamat; // Address in Indonesian public function setUsername($username) { $this->username = $username; } public function get...
0274a1912263ca9c20e0
```bash #!/bin/bash process_files() { local current_dir="$1" for file in "$current_dir"/*; do if [ -d "$file" ]; then echo "processing directory $file" process_files "$file" # recursively process files within the directory else echo "processing file $file" fi done } for dir in /pa...
02754a48234c339c5987
```java public class EquipmentItem { private String id; private int index; private boolean twoHanded; public EquipmentItem(String id, int index, boolean twoHanded) { this.id = id; this.index = index; this.twoHanded = twoHanded; } public String getDescription() { ...
0275f3cdc6bead3d3610
```csharp using System; using System.Collections.Generic; class CommandLineParser { private Dictionary<string, Action<int, int>> commands; public CommandLineParser() { commands = new Dictionary<string, Action<int, int>>(); } public void AddCommand(string command, Action<int, int> action) ...
027aad75022217ceb8be
```python import os from setuptools import find_packages, setup # Read the application's version from the specified module from app import __version__ # Read the dependencies from the requirements file here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'requirements.txt')) as f: all_re...
027aff95942022d83061
```csharp using System; public class Auth0FactoryOptions { public string Domain { get; set; } public string ClientId { get; set; } public string ClientSecret { get; set; } public bool ReuseAccessToken { get; set; } } public class AuthValidator { public bool ValidateAuth0Configuration(Auth0FactoryO...
027ba85d101d7a47062d
```python class NoteTakingApp: def __init__(self): self.notes = {} def add_note(self, title, content): self.notes[title] = content def view_note(self, title): if title in self.notes: return self.notes[title] else: return "Note not found." def de...
027c6435228c361e2432
```rust fn update_cur(&mut self, port_nb: midi::PortNb, ports: &midi::Ports) { // Retrieve the MIDI port corresponding to the given port_nb if let Some(port) = ports.list().find(|p| p.port_number() == port_nb) { // Update the current state of the specified MIDI port based on the retrieved port informati...
027c6dc6967dcc485875
```python def enforce_max_length(arg, max_length): if len(arg) > max_length: message = f"The argument must be no more than {max_length} characters ({len(arg)}/{max_length})." raise ValueError(message) return arg ``` The `enforce_max_length` function takes two parameters: `arg` and `max_length`. ...