query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with writing a script to automate the setup of directories and download necessary helper scripts for a geospatial data processing application. The script should create specific directories if they do not exist and download helper scripts if they are not present in the designated location. Write a shell ...
```bash #!/bin/bash # Create directories if they do not exist for d in 'app/bin' 'app/configuration' 'tec' 'data/incoming/osm' 'data/incoming/poly' 'data/incoming/gpx' 'data/incoming/naturalearth' 'data/incoming/openstreetmapdata' 'tmp' 'generated/Shapes' 'generated/osm' 'generated/Shapes/corridor'; do if [ ! -d $d ...
magicoder
shell
You are tasked with creating a function that processes user room data in a chat application. The application uses Rust and asynchronous programming to handle interactions and data retrieval. Your goal is to implement a function that retrieves and processes user room data based on the provided code snippet. You are giv...
```rust use crate::{commands::get_option, error, typemap::TypeMapSharedCache}; pub async fn execute(ctx: Context, interaction: Interaction) { let data = ctx.data.read().await; let cache = data.get::<TypeMapSharedCache>().unwrap(); let rooms = match cache.get_user_room_map().get(&interaction.member.user.id...
magicoder
rust
You are tasked with writing a script to automate the installation of a boot loader on a Unix-like system. The script should prompt the user for confirmation before proceeding with the installation. The script will also extract the disk name from a given root directory and use it to install the boot loader. Write a she...
```bash #!/bin/bash # Copy boot_monitor to $BOOT cp "$MDEC/boot_monitor" "$BOOT" # Extract disk name from $ROOT disk=$(echo "$ROOT" | sed 's/s[0-3]//') # Prompt user for confirmation echo -n "Install bootxx_minixfs3 into $disk? (y/N) " read ans # Check user's response if [ "$ans" != "y" ]; then echo "Exiting......
magicoder
shell
You are tasked with implementing a user authentication system for a web application. The system should allow different types of users to log in and access specific features based on their user type. You are given a code snippet from the authentication module of the application, which handles the creation of a user sess...
```php // Extend user session creation functionality if ($type == 'admin') { $app_user = array( 'user' => $profile->name, 'type' => 'admin', 'user_id' => $profile->profile_id, ); } elseif ($type == 'manager') { $app_user = array( 'user' => $profile->name, 'type' => 'm...
magicoder
php
You are tasked with implementing a simplified version of a placement group management system. A placement group is a logical grouping of resources in a distributed system, and it can have a placement strategy associated with it. The given code snippet is a part of the implementation of this system. The `GcsPlacementGr...
```cpp #include <iostream> // Enum class representing different placement strategies enum class PlacementStrategy { RANDOM, PACK, STRICT_PACK }; // Struct containing data about the placement group struct PlacementGroupTableData { PlacementStrategy strategy; // Other placement group data members }; // Class...
magicoder
cpp
You are tasked with creating a Django test case for a web application that involves checking the behavior of an API endpoint. The test case is designed to verify the functionality of the API endpoint that counts missing "def codes" in a specific context. The test is written using the pytest framework and involves mocki...
```python import pytest from datetime import datetime from rest_framework import status @pytest.mark.django_db def test_def_code_count_missing_defc(client, monkeypatch, disaster_account_data, helpers): # Mock the current date to December 31, 2022 helpers.patch_datetime_now(monkeypatch, 2022, 12, 31) #...
magicoder
python
You are tasked with implementing a Python function that can handle various edge cases, accommodate regular doctest formats, and detect inline tests. The function should be able to process the input and output the results as specified. Your task is to create a function `process_tests` that takes a string containing doct...
```python def process_tests(test_cases: str) -> dict: test_dict = {} lines = test_cases.split('\n') expr = None for line in lines: if line.startswith(">>>"): expr = line[4:] elif expr and line.strip() != "": expected_output = line.split("==")[1].strip() ...
magicoder
python
You are tasked with creating a script to automate the installation of a specific software package on a Debian-based system. The script should check for the presence of the required command, install the package if it is not available, and then perform some post-installation cleanup. Write a shell script that accomplish...
```bash #!/bin/bash set -euo pipefail export DEBIAN_FRONTEND=noninteractive if ! command -v git &> /dev/null; then apt-get update apt-get install -y --no-install-recommends git fi pushd "${TMPDIR:-/tmp}" git clone https://github.com/alaturka/bats.git sudo bats/install.sh /usr/local rm -rf bats ``` In this ...
magicoder
shell
You are tasked with implementing a cacheable response trait for a given struct in Rust. The `impl_macro` function takes a `syn::DeriveInput` as input and generates the implementation code for the `CacheableResponse` trait for the given struct. Your task is to complete the implementation of the `impl_macro` function to...
```rust pub fn impl_macro(ast: &syn::DeriveInput) -> TokenStream { let name = &ast.ident; let gen = quote! { impl CacheableResponse for #name { fn is_cacheable(&self) -> bool { if let syn::Data::Struct(data) = &ast.data { for field in &data.fields { ...
magicoder
rust
You are tasked with creating a Django REST Framework serializer for a model that represents measures taken in response to incidents. The serializer should include fields that retrieve related data from other models and present it in a readable format. Given the code snippet provided, you need to complete the `Measure...
```python from rest_framework import serializers from .models import Measures, MeasureType, IncidentCategory class MeasuresSerializer(serializers.ModelSerializer): measure_type_name = serializers.CharField(source='measure_type_id.measure_name', read_only=True) incident_category_name = serializers.CharField(sou...
magicoder
python
You are given a Python code snippet that appears to be part of a 3D graphics rendering algorithm. The code seems to be generating triangular and quadrilateral faces for a 3D mesh. Your task is to understand the code and create a programming problem based on the concepts and operations involved in this code snippet. Cr...
```python # Sample Solution for the created problem # Problem: Mesh Face Generation # Given a 3D mesh represented by vertices and edges, write a function to generate faces for the mesh based on the provided rules. def generate_faces(resolution): tri_faces = [] faces = [] for j in range(2 * resolution): ...
magicoder
python
You are tasked with implementing a class that calculates the moving average of a stream of numbers. The class should have the following methods: 1. `__init__(self)`: Initializes the class with necessary variables. 2. `update(self, val, n=1)`: Updates the moving average with a new value `val` and an optional parameter ...
```python class MovingAverage: def __init__(self): self.sum = 0 self.count = 0 def update(self, val, n=1): self.sum += val * n self.count += n def get_average(self): if self.count == 0: return 0 return self.sum / self.count ```
magicoder
python
You are tasked with implementing a custom error handling mechanism for a web application. The application has a component called `UnrecoverableErrorComponent` which is responsible for displaying an unrecoverable error message to the user. Your goal is to enhance this component by adding a method that logs the error det...
```typescript import { OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; export class UnrecoverableErrorComponent implements OnInit { constructor(private http: HttpClient) { } ngOnInit(): void { this.logErrorToServer('Unrecoverable error occurred'); } logErrorToServer(erro...
magicoder
typescript
You are tasked with implementing a function that converts a given array of language keys and their corresponding translations into a nested object structure. The input array contains language keys in the format 'Namespace.key' and their corresponding translations. Your goal is to transform this array into a nested obje...
```javascript function convertToNestedObject(translations) { const result = {}; for (const key in translations) { const parts = key.split('.'); let current = result; for (let i = 0; i < parts.length - 1; i++) { if (!current[parts[i]]) { current[parts[i]] = {...
magicoder
javascript
You are tasked with implementing a class that renders path goals in a 2D environment. The class `PathGoalRenderer` is responsible for drawing the geometry associated with path goals. The code snippet provided is a part of the implementation of this class. The `PathGoalRenderer` class inherits from an unspecified base c...
```cpp void PathGoalRenderer::doDrawGeometry() const { // Assuming PathGoal class has methods to retrieve necessary data Menge::Math::Vector2 goalPosition = pathGoal.getPosition(); float goalRadius = pathGoal.getRadius(); // Assuming drawCircle method is available in the vector library drawCircle(g...
magicoder
cpp
You are tasked with implementing a reinforcement learning algorithm to train an agent to navigate a grid-based environment. The environment is represented as a grid, where the agent can move in four directions: up, down, left, and right. The agent receives a reward for reaching the goal state and incurs a penalty for h...
```python import numpy as np from typing import Tuple, List class QLearningAgent: def __init__(self, env: GridEnvironment, epsilon: float = 0.1): self.env = env self.epsilon = epsilon self.Q = np.zeros((env.rows, env.cols, len(env.actions))) def get_action(self, state: Tuple[int, int],...
magicoder
python
You are tasked with implementing a C++ class that manages a collection of documents and provides functionality to manipulate and access them. The class should support adding, removing, and retrieving documents, as well as performing operations on the documents themselves. Your task is to complete the implementation of...
```cpp #include <vector> #include <stdexcept> class SwVbaDocument : public SwVbaDocument_BASE { private: std::vector<css::uno::Reference<css::text::XTextDocument>> documents; public: void addDocument(css::uno::Reference<css::text::XTextDocument> document) { documents.push_back(document); } vo...
magicoder
cpp
You are tasked with creating a Python web application that handles custom error pages for both 404 (page not found) and 500 (internal server error) status codes. Your application should utilize the Flask framework to achieve this functionality. Additionally, you need to ensure that the application runs in debug mode an...
```python from flask import Flask app = Flask(__name__) @app.errorhandler(404) def page_not_found(e): """Return a custom 404 error.""" return 'Sorry, nothing at this URL.', 404 @app.errorhandler(500) def internal_server_error(e): """Log the error and raise an exception.""" error = 'An internal server...
magicoder
python
You are tasked with simulating the growth of a population over a number of generations. The population size is initially set to `INITIAL_POPULATION`. Each generation, the population size increases based on a growth rate. The growth rate is determined by the number of individuals in the population and a fixed growth fac...
```python def simulate_population_growth(generations, growth_rate_percentage): population = 20 # INITIAL_POPULATION for _ in range(generations): population += population * (growth_rate_percentage / 100) return round(population, 4) ``` The `simulate_population_growth` function initializes the popula...
magicoder
python
You are tasked with implementing a class that performs a specific operation on a given input. The class should have a method that takes an array of integers as input and returns the result of a specific operation. The operation involves finding the maximum difference between two elements in the array, where the second ...
```php class MaxDifference { public function findMaxDifference($arr) { $maxDiff = 0; $n = count($arr); for ($i = 0; $i < $n - 1; $i++) { for ($j = $i + 1; $j < $n; $j++) { if ($arr[$j] > $arr[$i]) { $diff = $arr[$j] - $arr[$i]; ...
magicoder
php
You are working as a system administrator for a web hosting company. Your task is to create a Python script that automates the process of restarting the Apache web server on multiple servers. The script should be able to handle multiple servers and restart the Apache service on each of them. Write a Python function `r...
```python import subprocess def restart_apache(servers): results = {} for server in servers: command = f'ssh {server} "sudo systemctl restart apache2"' try: subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) results[server] = ...
magicoder
python
You are given a Python code snippet that processes a string input and performs various operations on it. Your task is to understand the operations being performed and write a function to replicate the final output. The given code snippet performs the following operations: 1. Splits the input string `strin` into a list...
```python from typing import List, Tuple def cut_string(s: str, segment_length: int) -> List[str]: return [s[i:i+segment_length] for i in range(0, len(s), segment_length)] def process_input(strin: str) -> List[Tuple[str, str]]: strin_split = strin.split('$$\n')[:-1] strin_split_content = [line.split('\n')...
magicoder
python
You are tasked with creating a Python program to analyze the performance of a given set of functions and report the top 10 functions sorted by the total amount of time spent in each. Your program should also log the profiling result and include the output in the log. You are provided with a code snippet that demonstra...
```python import cProfile import io import logging import pstats # Define the functions to be profiled def function1(): # Function implementation pass def function2(): # Function implementation pass # Profile the functions profiling_output = io.StringIO() cProfile.run('function1(); function2()', prof...
magicoder
python
You are tasked with creating a Python function that interacts with an AWS service to deploy an EC2 instance based on a given commit. The function should take the commit as input and return the deployment status in JSON format. You are provided with the following code snippet as a starting point: ```python def deploy_...
```python import boto3 import json def deploy_ec2(commit): # Initialize AWS EC2 client ec2_client = boto3.client('ec2') # Define the parameters for the EC2 instance based on the commit instance_params = { 'ImageId': 'ami-0abc123', # Replace with the appropriate AMI ID 'InstanceType': 't2.micro', # Replace w...
magicoder
python
You are tasked with implementing a feature selection algorithm for image processing using the Kanade-Lucas-Tomasi (KLT) algorithm. The given code snippet is a part of the `_KLTSelectGoodFeatures` function, which is responsible for selecting good features from an input image. The function takes four parameters: - `tc`:...
```python def _KLTSelectGoodFeatures(tc, img, nFeatures, mode): # Initialize the list of KLT feature objects featurelist = [KLT_Feature() for i in range(nFeatures)] # Implement feature selection based on the specified mode if mode == "mode1": # Implement feature selection logic for mode1 ...
magicoder
python
You are tasked with creating a custom loader component in an Angular application. The loader component should utilize the `DxLoadPanelModule` from the DevExtreme library to display a loading panel when data is being fetched or processed. Your goal is to implement the loader component and integrate it into the applicati...
```typescript import { Component, Input } from '@angular/core'; @Component({ selector: 'app-loader', template: ` <dx-load-panel *ngIf="isLoading" [visible]="true"></dx-load-panel> ` }) export class LoaderComponent { @Input() isLoading: boolean; } ``` ```typescript import { NgModule } from '@angular/core';...
magicoder
typescript
You are working on a project that involves cryptographic operations using the secp256k1 elliptic curve. As part of this project, you need to implement a function to sum a set of nonces using the Musig protocol. The Musig protocol is used for multi-signature schemes and involves combining nonces from multiple parties to...
```csharp internal static void secp256k1_musig_sum_nonces(Span<GEJ> summed_nonces, MusigPubNonce[] pubnonces) { int i; summed_nonces[0] = GEJ.Infinity; summed_nonces[1] = GEJ.Infinity; // Iterate through the MusigPubNonce array and sum the nonces for (i = 0; i < pubnonces.Length; i++) { ...
magicoder
csharp
You are tasked with creating a program that analyzes a given Java source file and counts the occurrences of specific license-related comments. The license-related comments are defined as any comment block (multi-line comment) that contains the word "License" or "licence" (case-insensitive). A comment block is defined a...
```java public class LicenseCommentCounter { public static int countLicenseComments(String javaSourceCode) { int count = 0; boolean insideComment = false; String[] lines = javaSourceCode.split("\n"); for (String line : lines) { if (line.trim().startsWith("/*")) { ...
magicoder
java
You are tasked with implementing a program to calculate the sum of all the digits in the result of multiplying two large numbers. The program should take two positive integers as input, multiply them, and then sum the digits of the resulting product. Write a function `sum_of_digits_in_product` that takes two positive ...
```python def sum_of_digits_in_product(num1, num2): product = num1 * num2 # Calculate the product of num1 and num2 digit_sum = 0 # Initialize the sum of digits to 0 # Convert the product to a string to iterate through its digits product_str = str(product) # Iterate through each digit in the prod...
magicoder
python
You are tasked with implementing a custom decoding protocol in Swift. The `HBDecodable` protocol is similar to the `Decodable` protocol in Swift, but with some differences. Your goal is to create a custom implementation of the `HBDecodable` protocol and use it to decode a simple struct. The `HBDecodable` protocol requ...
```swift // Solution protocol HBDecodable { init(decoder: HBDecoder) throws } struct TestObj: HBDecodable { var message: String? var id: Int? init() {} init(decoder: HBDecoder) { message = try? decoder.decode("message") id = try? decoder.decode("id") } } // Example us...
magicoder
swift
You are given a list of integers representing the scores of students in a class. Your task is to write a function to calculate the deciles of the scores. The deciles divide the data into ten equal parts, and the "Zeroth" decile represents the minimum value, while the "Tenth" decile represents the maximum value. Write ...
```python def calculate_deciles(scores): scores.sort() deciles = {} for i in range(11): index = int((len(scores) - 1) * (i / 10)) deciles[i] = scores[index] return deciles ``` The `calculate_deciles` function first sorts the input list of scores. Then, it iterates through the range of 1...
magicoder
python
You are tasked with creating a SwiftUI view for a social networking app that allows users to add new contacts. The code snippet provided is a part of the view implementation and shows a button with an image and text for adding contacts. Your task is to complete the implementation of the SwiftUI view by adding the neces...
```swift import SwiftUI struct AddContactsView: View { @State private var name: String = "" @State private var email: String = "" @State private var phoneNumber: String = "" @State private var isInputValid: Bool = false var body: some View { VStack { HStack { Im...
magicoder
swift
You are tasked with creating a Python function that simulates a batch process for data manipulation. The function should initialize a `SimBatch` object with specific parameters and then clear all memory data associated with it. You are given the following code snippet as a starting point: ```python def simbatch(): ...
```python import os import sys class SimBatch: def __init__(self, n, ini_file=None): self.n = n self.ini_file = ini_file def clear_all_memory_data(self): # Implement code to clear all memory data associated with the SimBatch object pass def simbatch(): current_dir = os.pat...
magicoder
python
You are tasked with implementing a custom error handling system for a web application. The application is built using the Laravel framework, and you need to create a new custom exception class to handle internal server errors. The custom exception class should extend the base Exception class provided by Laravel and sho...
```php <?php use Illuminate\Http\Request; use Illuminate\Http\JsonResponse; class InternalServerErrorException extends Exception { public function render(Request $request): JsonResponse { return response()->json(['error' => 'Internal server error'], 500); } } class CustomController extends Contro...
magicoder
php
You are tasked with implementing a Sudoku solver using Rust programming language. Sudoku is a logic-based combinatorial number-placement puzzle. The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid contain all of the digits from 1 to 9. ...
```rust // Define the Sudoku puzzle structure struct Puzzle { grid: [[u8; 9]; 9], } impl Puzzle { // Method to print the puzzle grid fn print(&self) { for row in &self.grid { println!("{:?}", row); } } } // Define the Sudoku solver library struct SudokuSolver; impl SudokuS...
magicoder
rust
You are tasked with implementing a signal handling mechanism in a Python application. Signals are a way for different parts of the application to communicate events to each other. In this problem, you will create a signal for tracking the funding status of a project. You are provided with a code snippet that defines a...
```python from django.dispatch import Signal # Define the project_funded signal project_funded = Signal(providing_args=["first_time_funded"]) # Function to handle the project_funded signal def handle_project_funded(sender, **kwargs): if kwargs.get('first_time_funded'): print("Project funded for the first ...
magicoder
python
You are tasked with creating a Python function that retrieves a list of 13F filings from the U.S. Securities and Exchange Commission's EDGAR database for a given date. The function should utilize the `edgar3` library to access the EDGAR index and retrieve the filings as a pandas DataFrame. Write a function `get_13f_li...
```python import datetime import pandas as pd from edgar3 import edgar_index def get_13f_listings(date: datetime.datetime, populate: bool) -> pd.DataFrame: ed_i = edgar_index.edgar_index() if populate: ed_i.populate_full_index() df = ed_i.get_full_listing_as_pd(date) return df ``` In the soluti...
magicoder
python
You are tasked with implementing a Greedy Search algorithm to find the shortest path between cities. The cities are represented as nodes in a graph, and the distances between them are given. Your task is to write a Python class that performs the Greedy Search algorithm to find the shortest path between two given cities...
```python import heapq class GreedySearch: def __init__(self, graph): self.visited_cities = set() self.travelled_distance = 0 self.border = [] def search(self, start_city): start_city.visited = True self.visited_cities.add(start_city) current_city = start_city ...
magicoder
python
You are tasked with creating a custom attribute in C# that can be applied to classes. The attribute should have properties to store arrays of objects and strings. Additionally, you need to implement a method to retrieve the custom attribute from a given class and perform assertions on the attribute's properties. Creat...
```csharp using System; using System.Linq; using System.Reflection; using Xunit; public class CustomAttribute : Attribute { public object[] ObjectArray { get; set; } public string[] StringArray { get; set; } } public class CustomAttributeProblem { public CustomAttribute GetCustomAttribute(Type type) {...
magicoder
csharp
You are tasked with creating a Python class that manages resources for a product inventory system. The class should have methods to add, remove, and update the quantity of a product in the inventory. Additionally, it should provide a method to retrieve the current quantity of a specific product. You are given a code s...
```python class InventoryManager: def __init__(self): self.inventory = {} def add_product(self, product_name, quantity): if product_name in self.inventory: self.inventory[product_name] += quantity else: self.inventory[product_name] = quantity def remove_prod...
magicoder
python
You are tasked with simulating a simplified version of a pipeline system using named pipes in a Unix-like environment. Named pipes, also known as FIFOs, are special files that allow unrelated processes to communicate with each other. In this scenario, the pipeline consists of four stages, each represented by a named pi...
```bash #!/bin/bash # Create named pipes for each stage mkfifo fifo/il_S1_eltcalc_P18 mkfifo fifo/il_S1_summarycalc_P18 mkfifo fifo/il_S1_pltcalc_P18 mkfifo fifo/il_S1_summary_P18.idx # Stage 1: Wait for input, perform calculations, and pass output cat fifo/il_S1_eltcalc_P18 | some_calculation > fifo/il_S1_summarycal...
magicoder
shell
You are tasked with implementing the autocorrelation method for finding an all-pole model in signal processing. The all-pole model is used to represent a signal as the output of a system with poles but no zeros. The autocorrelation method involves finding the coefficients of the all-pole model by analyzing the autocorr...
```python import numpy as np from typing import Tuple def acm(x: np.ndarray, p: int) -> Tuple[np.ndarray, float]: # Compute the autocorrelation function of the input signal R = np.correlate(x, x, mode='full') R = R[len(x)-1:len(x)+p] # Formulate the Yule-Walker equations R_matrix = np.array([R[i:i...
magicoder
python
You are tasked with creating a Python function that interacts with a database using asynchronous methods. The provided code snippet demonstrates an asynchronous database call using the `async_db_call` function. Your task is to implement a new asynchronous function that retrieves specific data from the database and proc...
```python from typing import List from urllib import parse import os from sqlalchemy import create_engine, select, text async def async_db_call(fn): url = parse.urlparse(os.environ.get("DATABASE_URL", "postgres://localhost:5432/supers")) engine_attrs = { 'database': url.path[1:], 'user': url.us...
magicoder
python
You are working on a project that involves implementing a neural network using Theano, a popular Python library for defining, optimizing, and evaluating mathematical expressions involving multi-dimensional arrays. Your task is to create a program that constructs a simple neural network using Theano to perform binary cl...
```python import numpy as np import theano import theano.tensor as T # Define input and output variables X = T.matrix('X') y = T.vector('y') # Initialize weights and biases np.random.seed(0) w_hidden = theano.shared(np.random.randn(2, 3), name='w_hidden') b_hidden = theano.shared(np.zeros(3), name='b_hidden') w_outpu...
magicoder
python
You are given a vector `A` containing unsigned integers. You are also given an unsigned integer `average`. Your task is to implement a function that filters the elements of `A` based on whether they are greater than `average` or not. The filtered elements greater than `average` should be stored in a new vector `B`, and...
```cpp #include <iostream> #include <vector> std::pair<std::vector<unsigned>, std::vector<unsigned>> filterElements(const std::vector<unsigned>& A, unsigned average) { std::vector<unsigned> B, C; for (auto x : A) { if (x > average) B.push_back(x); else C.push_back(x); ...
magicoder
cpp
You are given a Python function that takes a dictionary `i` as input. The dictionary `i` has a key 'intent' which itself is a dictionary containing keys 'name' and 'probability'. The function is intended to return the value of the key 'name' from the 'intent' dictionary if the probability is greater than 0.5, otherwise...
```python def process_intent(i): if 'intent' in i and 'probability' in i['intent'] and i['intent']['probability'] > 0.5: return i['intent']['name'] else: return None ``` In the solution, we first check if the key 'intent' exists in the input dictionary `i`. Then we check if the key 'probability'...
magicoder
python
You are tasked with implementing a simple class hierarchy in Python for a fictional game. The game has different types of characters, each with unique abilities and attributes. Your task is to create the base class `Character` and two subclasses `Warrior` and `Mage`, each with their own specific attributes and methods....
```python class Character: def __init__(self, name, health): self.name = name self.health = health def take_damage(self, damage): self.health -= damage class Warrior(Character): def __init__(self, name, health, strength): super().__init__(name, health) self.strengt...
magicoder
python
You are tasked with creating a script to automate the processing of image data using ImageJ. The script should execute the `cellStats.py` script for multiple configurations, each corresponding to a specific field of view (fov) in the image data. The script should handle potential failures and provide appropriate feedba...
```python import subprocess # List of fov identifiers fov_identifiers = ["TRE1_fov2", "TRE2_fov1", "TRE2_fov2"] # Path to ImageJ executable fiji_path = "${FIJI_PATH}/ImageJ-linux64" # Iterate through fov identifiers for fov in fov_identifiers: print(fov) config_path = "/media/nwalczak/XFS_Test/Resilio\ Sync/...
magicoder
python
You are tasked with creating a web application that tracks and displays the scores of users in a game. The application uses the Spark Java framework to handle HTTP requests and responses. The code snippet provided registers a route for the application to handle a GET request to "/observarPuntaje" using the `get` method...
```java import spark.Request; import spark.Response; import spark.Route; public class AppControl { // Assume the user scores are stored in a Map with user identifiers as keys and scores as values private static Map<String, Integer> userScores = new HashMap<>(); public static void main(String[] args) { ...
magicoder
java
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific license-related comments. The comments are formatted in a specific way and contain information about the license type and its limitations. Your program should be able to identify and count the occurrences of thes...
```python def count_license_comments(file_path): with open(file_path, 'r') as file: content = file.read() comments = content.split('LICENSE_END') count = len(comments) - 1 # Exclude the last empty comment after the last LICENSE_END print(f'Total count of license-related comments: {c...
magicoder
python
You are working on a project that involves integrating various libraries and frameworks for handling different aspects of a distributed system. One of the requirements is to implement a message queue system using the Foundatio library in C#. You need to create a class that encapsulates the functionality of a message qu...
```csharp using Foundatio.Queues; using Foundatio.Messaging; using System; using System.Threading.Tasks; public class FoundatioMessageQueue { private readonly IMessageBus _messageBus; private readonly IQueue<QueueEntry> _queue; public FoundatioMessageQueue() { var messageBus = new InMemoryMess...
magicoder
csharp
You are tasked with implementing a simplified version of the Word2Vec algorithm for word embedding. Word embedding is a technique used to represent words as dense vectors in a continuous vector space, where the similarity between words is captured by the proximity of their corresponding vectors. The Word2Vec algorithm ...
```python import pandas as pd import numpy as np from pathlib import Path class Word2VecRec: def __init__(self, vector_size=100, window=5): self.vector_size = vector_size self.window = window self.word_vectors = {} def fit(self, df): # Preprocessing and building vocabulary ...
magicoder
python
You are tasked with creating a program that reads ASCII data from a file and performs specific operations on the data. The ASCII data represents a grid of characters, where each character represents a cell in the grid. The program should read the data from the file and then perform a series of operations on the grid. ...
```python def read_ascii_data(fname): with open(fname, 'r') as file: ascii_data = [line.strip() for line in file.readlines()] return ascii_data def count_total_cells(grid): total_cells = sum(len(row) for row in grid) return total_cells def calculate_dimensions(grid): num_rows = len(grid) ...
magicoder
python
You are working on a project to develop a synchronization tool called SyncPy. As part of the project, you need to write a script to automate the setup process for SyncPy on a Linux system. The script should perform the following tasks: 1. Set the permissions of the `/SyncPy2/` directory to allow full access for all us...
```bash #!/bin/bash # Set permissions for /SyncPy2/ directory sudo chmod -R 777 /SyncPy2/ # Remove SyncPy-master directory and master.zip file rm -R SyncPy-master rm master.zip # Check if SyncPy2 file exists in the user's home directory if [ -f $HOME/SyncPy2 ]; then # Remove the existing SyncPy2 file rm $HOM...
magicoder
shell
You are tasked with implementing a sound player class in Python that can handle playing sound samples and caching them for future use. The class should also provide a method for synchronous sound playback. Additionally, the class should be able to log any errors that occur during sound playback, unless explicitly instr...
```python import functools as ft import logging class SoundPlayer: def __init__(self, trap_errors=False): self.trap_errors = trap_errors self.log = logging.getLogger('SoundPlayer') def play(self, name): try: # Implement this method to play the sound sample with the given na...
magicoder
python
You are tasked with creating a custom authorization attribute for an ASP.NET Core web application. The attribute should restrict access to a specific page based on the user's role. The application uses Razor Pages for its UI and requires the use of the `Microsoft.AspNetCore.Authorization` namespace for implementing cus...
```csharp using System; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace ePiggyWeb.Authorization { public class CustomRoleAuthorizationAttribute : AuthorizeAttribute, IAsyncAuthori...
magicoder
csharp
You are working on a quantum computing project and need to create a Python function to perform specific operations using Qiskit, a popular quantum computing framework. Your task is to implement a function that takes a quantum circuit as input and returns the statevector of the quantum system after applying the circuit....
```python from qiskit import QuantumCircuit, Aer, execute import numpy as np def get_statevector_after_circuit(circuit): backend = Aer.get_backend('statevector_simulator') job = execute(circuit, backend) result = job.result() statevector = result.get_statevector() return statevector ``` The `get_s...
magicoder
python
You are tasked with creating a program that parses a given text file to extract the license information and count the occurrences of each unique license type. The license information is embedded within comments in the text file and follows a specific format. Your program should be able to identify and extract the licen...
```python import re def extract_license_info(file_path): license_counts = {} with open(file_path, 'r') as file: for line in file: match = re.search(r'licensed under the (.+?) \(', line) if match: license_type = match.group(1) if license_type in li...
magicoder
python
You are tasked with implementing a state machine for a mail drop system. The system allows users to send emails to multiple recipients, and the state machine manages the different states of the email sending process. The provided code snippet shows a Java class representing the "WaitingForOtherRecipientsState" in the s...
```java public class ReadyToSendState extends State { /** * Create a ready to send state. * * @param mailDropRequest The mail drop request. */ public ReadyToSendState(MailDropRequest mailDropRequest) { super(mailDropRequest); } @Override public void onEnterState() { ...
magicoder
java
You are tasked with creating a test suite for a networking library in Swift. The library provides functionality for making network requests and handling responses. Your goal is to write a test case that verifies the correct behavior of the networking library's request and response handling. You are given a Swift test ...
```swift func testNetworkRequest() { // Create a network request using the networking library let request = URLRequest(url: URL(string: "https://api.example.com/data")!) // Send the request and wait for the response let expectation = XCTestExpectation(description: "Network request expectation") let...
magicoder
swift
You are tasked with implementing a distributed memory model using the KDistributedMemory class from the pyctm library. The KDistributedMemory class is responsible for creating and managing a distributed memory model for use in topic modeling and related natural language processing tasks. The distributed memory model is...
```python from pyctm.memory.k_distributed_memory import KDistributedMemory import numpy as np # Step 1: Import the KDistributedMemory class from the pyctm library # Already imported in the code snippet # Step 2: Initialize an instance of the KDistributedMemory class num_topics = 10 vector_dim = 100 num_iterations = 1...
magicoder
python
You are tasked with implementing a command-line argument parser for a federated learning system. The system is designed to handle different datasets and partitioning strategies. Your task is to extend the existing argument parser with new options for specifying the partitioning strategy and its associated arguments. Y...
```python import argparse parser = argparse.ArgumentParser(description='Federated Learning System') # Existing options parser.add_argument('--data_folder', type=str, default='benchmark/datasets/mnist/data', help='The folder contains all datasets.') parser.ad...
magicoder
python
You are tasked with creating a script to process surface data for a 3D modeling application. The script will take input from a set of files and generate a command to be executed. Your task is to write a function that takes the number of surfaces, an array of topographical files, and an array of coordinate files as inpu...
```python def generateCommand(NSURFACES, topoFiles, coordFiles): instr4 = 'quickspec -spec spec.surfaces.smoothed' for i in range(NSURFACES): part = f' -tn 1D {topoFiles[i]} {coordFiles[i]}' instr4 += part part = f' -tsnad 1D S_inflated {coordFiles[-2]} {coordFiles[-1]} N {topoFiles[-1]}' ...
magicoder
python
You are tasked with implementing a post-processing function for object detection in a real-time video processing system. The function takes several input parameters and performs various operations to refine the detected bounding boxes and draw them on the original frames. Your task is to understand the given code snipp...
```python import queue import time import numpy as np def postprocess_mp(Predicted_data, original_frames, Processed_frames, Processing_times, input_size, CLASSES, score_threshold, iou_threshold, rectangle_colors, realtime): def postprocess_boxes(pred_bbox, original_image, input_size, score_threshold): # Pe...
magicoder
python
You are tasked with implementing a Java method that compares two dates and throws a ComparisonFailure if the dates differ by minutes only. The method should be named `throwsComparisonFailureWhenDatesDifferMinutesOnly` and should be part of a class with a `DATE_FORMAT` field of type `SimpleDateFormat`. The method should...
```java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateComparator { private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS"); public void throwsComparisonFailureWhenDatesDifferMinutesOnly() throws ParseExce...
magicoder
java
You are tasked with creating a Python script to automate the process of training reinforcement learning agents using OpenAI's Baselines library. The script should be able to handle different environments and algorithms, and it should also notify the user via email when the training starts and finishes. Additionally, th...
```python import subprocess def train_rl_agent(repo_name, email_address, alg, env, num_timesteps, num_env, save_path): # Send email notification when training starts start_notification = f"Started Training {env} for {alg} on instance 3" subprocess.run(f'echo "{start_notification}" | ssmtp {email_address}',...
magicoder
python
You are tasked with implementing a function that calculates the total cost of a customer's shopping cart. The function should take into account the prices of the items in the cart, any applicable discounts, and tax. The function should also be able to handle different types of discounts, such as percentage-based discou...
```swift func calculateTotalCost(cartItems: [(String, Double)], discounts: [String: Double], taxRate: Double) -> Double { var totalCost = 0.0 for (item, price) in cartItems { var discountedPrice = price if let discount = discounts[item] { if discount < 1.0 { ...
magicoder
swift
You are tasked with implementing a generic data structure that represents a fixed-size circular buffer. A circular buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. When the buffer is full and a new element is inserted, it overwrites the oldest element. The circular bu...
```java import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CircularBuffer<T> { private final int capacity; private final List<T> elements; private int currentIndex; public CircularBuffer(int capacity) { this.capacity = capacity; this.elements ...
magicoder
java
You are tasked with creating a Python program to predict the price of houses based on their features using the scikit-learn library. You will need to implement a linear regression model and use it to make predictions on a given dataset. Your program should perform the following steps: 1. Import the necessary libraries...
```python import numpy as np from sklearn.linear_model import LinearRegression # Load the dataset from a CSV file data = np.genfromtxt('house_prices.csv', delimiter=',', skip_header=1) data_X = data[:, :-1] # Features (independent variables) data_y = data[:, -1] # Target (dependent variable) # Create and train the...
magicoder
python
You are tasked with implementing a function that processes a given file and extracts sentences from it based on certain criteria. The function takes in the file path of the target file, the maximum length of source sentences, and the maximum length of target sentences. It then returns two lists: one containing the extr...
```python from typing import List, Tuple def extract_sentences(fpath2: str, maxlen1: int, maxlen2: int) -> Tuple[List[str], List[str]]: sents1 = [] # List to store source sentences sents2 = [] # List to store target sentences with open(fpath2, 'r', encoding='utf-8') as file: for line in file: ...
magicoder
python
You are tasked with implementing a Python class that calculates the Percentage Price Oscillator (PPO) for a given set of stock prices. The PPO is a technical momentum indicator that shows the relationship between two moving averages in percentage terms. The class should have the following methods: 1. `add(self, v)`: T...
```python class EMA: def __init__(self, alpha): self.alpha = alpha self.value = None def add(self, v): if self.value is None: self.value = v else: self.value = self.alpha * v + (1 - self.alpha) * self.value def v(self): return self.value cl...
magicoder
python
You are tasked with creating a Python function that processes a configuration file and extracts specific information based on the provided arguments. The function will need to parse the arguments, authenticate with a server, and retrieve the configuration details. Your task is to implement the function to achieve this ...
```python # Import cliauto and Splunk SDK libs from cliautolib.cliauto_configconf import configconf def process_config(fargs, sargs): cc = configconf(fargs, sargs, os.getpid()) # Create a configconf object gc = cc.getconfig() # Retrieve the configuration details return gc # Return the retrieved configur...
magicoder
python
You are tasked with developing a script to automate the submission of jobs to a high-performance computing (HPC) cluster using the Slurm workload manager. The script should parse a configuration file and generate a Slurm job submission script based on the specified parameters. The configuration file will contain inform...
```python def generate_slurm_script(config_file_path: str) -> str: slurm_script = "#!/bin/bash\n" with open(config_file_path, 'r') as config_file: for line in config_file: key, value = line.strip().split('=') key = key.strip() value = value.strip() if key...
magicoder
python
You are tasked with implementing a logging system for a taskforce server. The server has a method `_log` that takes in a message and an optional `error` flag. The `error` flag is set to `False` by default. The server also has a `help` string and an `args` string that specifies the optional argument for the `_log` metho...
```python class TaskforceServer: def __init__(self, verbose=False): self._verbose = verbose def _log(self, msg, error=False): if self._verbose or error: print(msg) # Example usage server = TaskforceServer(verbose=True) server._log("Taskforce server started.") # Output: Taskforce s...
magicoder
python
You are working on a project that involves integrating the BASS audio library into a Python application using ctypes. The BASS library provides functions for creating audio streams from files and URLs. You need to create a Python wrapper for the BASS_AAC_StreamCreateFile and BASS_AAC_StreamCreateURL functions to enable...
```python import ctypes # Define the necessary types for the function signatures HSTREAM = ctypes.c_void_p BOOL = ctypes.c_byte QWORD = ctypes.c_ulonglong DWORD = ctypes.c_ulong DOWNLOADPROC = ctypes.CFUNCTYPE(ctypes.c_ulong, HSTREAM, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p) # Load the BASS library bass_aac_...
magicoder
python
You are tasked with implementing a custom recurrent neural network (RNN) model for sequence-to-sequence (seq2seq) learning. The RNN model will be used for natural language processing tasks such as machine translation or text summarization. Additionally, you need to design a custom loss function and implement beam searc...
```python # Custom RNN model class CustomRNN: def __init__(self, input_size, hidden_size, output_size): # Initialize RNN parameters pass def forward(self, input_sequence): # Implement forward pass of the RNN pass def backward(self, loss_gradient): # Implement backwa...
magicoder
python
You are given a Python code snippet that imports modules and defines a function for testing the KD (KDJ) indicator, a technical analysis tool used in stock trading. Your task is to create a program that generates simulated stock price data, calculates the KD indicator values, and visualizes the results using matplotlib...
```python import pyximport import matplotlib.pyplot as plt from datautils import gen_ohlc from kd import kd # Generate simulated stock price data ohlc_data = gen_ohlc() # Calculate the KD indicator values k_values, d_values = kd(ohlc_data) # Plot the stock's closing prices and the KD indicator values fig, (ax1, ax2)...
magicoder
python
You are tasked with implementing a Python class that manages the operation of a robotic system. The class, named `RobotController`, should include methods for controlling the robot's motors and establishing and closing connections. Your task is to complete the implementation of the `RobotController` class by adding the...
```python class RobotController: def __init__(self, connection_type): self.connection_type = connection_type # Initialize any other necessary attributes def startMotors(self): # Implement the logic to start the robot's motors pass def stopMotors(self): # Implement t...
magicoder
python
You are tasked with implementing a Python function that processes a list of strings representing code lines and returns the number of leading spaces or tabs in each line. The function should ignore empty lines and return the count of leading spaces or tabs for non-empty lines. The function signature is: ```python def ...
```python from typing import List def count_leading_spaces(code_lines: List[str]) -> List[int]: indentslist = [] for line in code_lines: if line.strip(): # Check if the line is not empty nindents = 0 for char in line: if char == ' ': nindents...
magicoder
python
You are tasked with implementing a Python decorator called `chainable` that allows chaining of methods in a class. The decorator should be used to mark methods in a class such that they return `self`, enabling method chaining. Additionally, you need to implement the `make_deferred`, `return_value`, and `lock` functions...
```python def chainable(func): """ Decorator to mark methods in a class as chainable. """ def wrapper(self, *args, **kwargs): func(self, *args, **kwargs) return self return wrapper def make_deferred(func): """ Function to mark a method as deferred execution. """ def ...
magicoder
python
You are tasked with creating a program to parse and process a set of rules for a game. Each rule is represented as a string and needs to be parsed into a structured format for further processing. The rules are provided as input in the form of a list of strings. Your task is to write a function that parses each rule str...
```python from typing import List class Rule: def __init__(self, type, **kwargs): self.type = type for key, value in kwargs.items(): setattr(self, key, value) def parse_rule(rule_string: str) -> Rule: parts = rule_string.split() rule_type = parts[0] if rule_type == "move": ...
magicoder
python
You are working on a project where you need to automate the process of modifying text in various source files. Your task is to write a script that performs a series of file operations and text replacements based on specified variables. The script should handle the following tasks: 1. Unzipping a file and moving its co...
```bash #!/bin/bash # Unzip the file and move its contents to the current directory mv $BASEJIT_BASE-master/** ./ mv $BASEJIT_BASE-master/.[!.]* ./ rm $BASEJIT_BASE.zip # Remove the unzipped folder rmdir $BASEJIT_BASE-master # Change basejit text in all source files to the specified values from command line find ./s...
magicoder
shell
You are tasked with implementing a function that converts an intersection match object to a GML (Geography Markup Language) format. The intersection match object contains information about a geographical intersection, and the GML format is an XML-based encoding standard for geographic data. Your task is to write a func...
```java public String intersectionMatchToGML(IntersectionMatch match) { StringBuilder gmlBuilder = new StringBuilder(); gmlBuilder.append("<Intersection>\n"); gmlBuilder.append(" <Name>").append(match.intersectionName).append("</Name>\n"); gmlBuilder.append(" <Location>\n"); gmlBuilder.append(...
magicoder
java
You are tasked with implementing a Brace Expansion algorithm that takes a string as input and expands it into all possible combinations. The input string will consist of lowercase letters and curly braces. The curly braces will contain comma-separated options, and the algorithm should expand the string by replacing the...
```cpp #include <iostream> #include <vector> #include <string> class BraceExpansion { public: static std::vector<std::string> braceExpansion(const std::string& input) { std::vector<std::string> result; std::string current; expand(input, 0, current, result); return result; } pri...
magicoder
cpp
You are given an array `nums` of non-negative integers. The array `nums` is considered special if there exists a number `x` such that there are exactly `x` numbers in `nums` that are greater than or equal to `x`. Notice that `x` does not have to be an element in `nums`. Return `x` if the array is special; otherwise, re...
```python from typing import List def findSpecialValue(nums: List[int]) -> int: nums.sort(reverse=True) # Sort the array in descending order for i, num in enumerate(nums): if num <= i: # Check if the current number is less than or equal to its index return i # Return the special value if...
magicoder
python
You are tasked with creating a Python program that simulates a sticker calibration process for a robotic system. The program should prompt the user to input the sticker's current location and the desired location. The program should then calculate the necessary adjustments to move the sticker from its current location ...
```python class Calibrate_Sticker_Location_Program: def __init__(self): self.current_location = (0, 0) self.desired_location = (0, 0) def set_current_location(self, x, y): self.current_location = (x, y) def set_desired_location(self, x, y): self.desired_location = (x, y) ...
magicoder
python
You are working on a project that involves processing machine learning models in TensorFlow Lite (TFLite). As part of this project, you need to handle the input and output types of TFLite models. The TFLite model input and output types are represented as a tuple of constants, where each constant can be one of the follo...
```python from collections import defaultdict def count_input_output_types(types_tuple): type_count = defaultdict(int) for t in types_tuple: type_count[t] += 1 return dict(type_count) ``` The `count_input_output_types` function takes a tuple of TFLite model input and output types as input. It init...
magicoder
python
You are tasked with implementing a booking system for a property rental service. The system should handle bookings for various properties located in different locations. Each booking is associated with a specific property and location. Your task is to design and implement the classes and methods necessary to manage boo...
```php class Booking { private $propertyId; private $locationId; private $bookingDate; public function __construct($propertyId, $locationId, $bookingDate) { $this->propertyId = $propertyId; $this->locationId = $locationId; $this->bookingDate = $bookingDate; } // Add any...
magicoder
php
You are tasked with implementing a custom actor system in C++. The custom actor system is designed to manage actors with specific implementations. The provided code snippet includes part of the implementation for the `CustomActor` class, which is derived from the `Actor` class. The `CustomActor` class has two construct...
```cpp class CustomActorImpl { // Implementation details for CustomActor }; namespace Internal { class CustomActor { // Internal details for CustomActor }; } class Actor { // Base class for actors }; class CustomActor : public Actor { public: // Constructor taking a reference to CustomActorImpl Custo...
magicoder
cpp
You are tasked with creating a script to update the contents of multiple `buildpack.toml` files found within a directory structure. The script should read the content of a variable `updated` and overwrite the existing content of each `buildpack.toml` file with the value of `updated`. The script should be designed to ha...
```bash #!/bin/bash # Set the content to be updated in the buildpack.toml files updated="new content" # Find and update buildpack.toml files while IFS= read -r -d '' buildpack_toml_path; do echo "${updated}" > "${buildpack_toml_path}" done < <(find . -name buildpack.toml -print0) ``` In this solution, we first s...
magicoder
shell
You are tasked with implementing a mixin in JavaScript that can be used to apply text styling to HTML elements. The mixin should provide a set of predefined text styles that can be easily applied to different elements in a web application. Your task is to create a `TextStyleMixin` that can be used to apply text styles...
```javascript const TextStyleMixin = { styles: { heading: { fontSize: '24px', fontWeight: 'bold', color: 'black', }, subheading: { fontSize: '18px', fontWeight: 'normal', color: 'gray', }, link: { fontSize: '16px', fontWeight: 'bold', color: 'b...
magicoder
javascript
You are tasked with implementing a function to load a Digital COVID Certificate (DCC) rule from an API. The function should handle potential errors and provide appropriate error messages. You are given a code snippet that includes a mock session and an assertion test. Your task is to implement the `loadDCCRule` functi...
```swift import XCTest import NIO enum APIError: Error { case invalidResponse } struct DCCRule { // Define the structure of DCCRule } class DCCRuleLoader { let session: URLSession init(session: URLSession) { self.session = session } func loadDCCRule(country: String, hash: String) ->...
magicoder
swift
You are tasked with creating a program to process ticket information for a train journey. The ticket includes fields denoted by key-value pairs, where the key represents the field name and the value represents the position of that field on the ticket. Additionally, there is a "my ticket" field that contains your person...
```python def calculate_departure_product(field_pos, my_ticket): p = 1 for field, positions in field_pos.items(): if field.startswith("departure"): p *= my_ticket[positions[0]] return p ```
magicoder
python
You are tasked with implementing a function to create and bind a socket to a specified port using the given code snippet as a reference. The function should handle the socket creation, binding, and error checking. You are provided with a partial code snippet that demonstrates the binding process using the `sockaddr_in`...
```cpp SocketStatus createAndBindSocket(int port) { int socketHandle = socket(AF_INET, SOCK_STREAM, 0); if (socketHandle == -1) { std::cerr << "Failed to create socket" << std::endl; return Error; } sockaddr_in address = priv::SocketImpl::createAddress(INADDR_ANY, port); if (bind(so...
magicoder
cpp
You are given a code snippet from a file in a GitHub repository. Your task is to extract relevant information from the snippet and present it in a structured format. Write a function `extract_info_from_code` that takes a string `code_snippet` as input and returns a dictionary containing the following information: - `r...
```python import re def extract_info_from_code(code_snippet): info_dict = {} # Extract repository name and file path using regular expressions match = re.search(r'<reponame>(.*?)<filename>(.*?)\n', code_snippet) if match: info_dict['repository_name'] = match.group(1) info_dict['fil...
magicoder
python
You are tasked with implementing a Python function that simulates a simple gambling game using binomial distribution. The game involves flipping a biased coin multiple times, and the player wins if a certain number of heads are obtained within a specified number of flips. The function should take the probability of get...
```python import numpy as np def win_probability(head_probability: float, num_flips: int, target_heads: int) -> float: # Simulate the game using binomial distribution num_successes = np.random.binomial(num_flips, head_probability) # Calculate the probability of winning win_count = np.sum(np.random...
magicoder
python
You are given a Rust program that contains a test function for sorting an array of strings. Your task is to implement the sorting algorithm used in the test function and ensure that it sorts the array of strings in lexicographical order. The test function is as follows: ```rust #[cfg(test)] mod tests { use super::...
```rust fn sort_strings(strings: &mut [&str]) { strings.sort(); } ``` The `sort_strings` function takes a mutable reference to an array of strings and uses the `sort` method to sort the strings in lexicographical order. This solution ensures that the array of strings is sorted as expected, satisfying the requireme...
magicoder
rust
You are tasked with creating a Python script that manages a mocking feature for a web proxy server. The script should enable or disable the mocking feature based on the value of the `isMockEnabled` variable. Additionally, the script should set up an `onExit` handler to gracefully shut down the mocking feature when the ...
```python import json import os import subprocess import signal # Enables or disables the mocking feature as a whole isMockEnabled = True # Function to enable mocking feature def enable_mocking(): subprocess.Popen("sh proxy_on.sh".split(), stdout=subprocess.PIPE) # Function to disable mocking feature def disable...
magicoder
python
You are tasked with creating a program that processes a web archive file and extracts specific information from HTML content. The input file is in the WARC (Web ARChive) format and is compressed using bzip2. The provided code snippet is a command-line instruction that uses the `bzcat` utility to decompress the file, th...
```python import subprocess import json import re # Step 1: Read the input WARC file in bzip2 compressed format warc_file_path = 'iawide.warc.bz2' try: # Use subprocess to run bzcat and capture its output bzcat_process = subprocess.Popen(['bzcat', warc_file_path], stdout=subprocess.PIPE) warc_content, _ = ...
magicoder
python
You are tasked with implementing a logging system for a software application. The logging system should support logging messages at different levels of severity and should be able to filter messages based on their severity level. Additionally, the logging system should be able to output the logged messages to different...
```java import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class Logger { public enum Level { DEBUG, INFO, WARNING, ERROR, CRITICAL } private Level minLevel = Level.DEBUG; private List<PrintWriter> handle...
magicoder
java