query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a function to calculate the Sinkhorn divergence between clusters of data points. The Sinkhorn divergence is a measure of dissimilarity between two probability distributions, often used in machine learning and data analysis. The function `sinkhorn_divergence` takes as input the weights a...
```python from typing import List import numpy as np def sinkhorn_divergence(a: List[float], x: List[float], b: List[float], y: List[float], epsilon: float) -> float: n = len(a) m = len(b) cost_matrix = np.zeros((n, m)) for i in range(n): for j in range(m): cost_matrix[i, j] = -epsi...
magicoder
python
You are working on a security tool that processes indicators of compromise (IOCs) in JSON format. One of the functions in the tool, `panos_url_formatting`, is responsible for formatting URLs and handling port numbers. The function takes the following parameters: - `iocs_json`: A JSON object containing IOCs in the form ...
```python import re def panos_url_formatting(iocs_json, drop_invalids, strip_port): formatted_urls = {} total_indicators = 0 for indicator_type, indicators in iocs_json.items(): formatted_indicators = [] for indicator in indicators: if ":" in indicator and strip_port: ...
magicoder
python
You are tasked with creating a function to validate a Sudoku board. The function should take a 9x9 grid representing the Sudoku board as input and return True if the board is valid, and False if it is not. A valid Sudoku board is one where each row, column, and 3x3 subgrid contains the numbers 1 to 9 without repetitio...
```python def is_valid_sudoku(grid): def is_valid_row(row_num, num): return num not in grid[row_num] def is_valid_col(col_num, num): for row in range(9): if grid[row][col_num] == num: return False return True def is_valid_box(start_row, start_col, num): ...
magicoder
python
You are tasked with implementing a PHP class that parses a given string containing HTML-like tags and their metadata. The class should have a method `parseTags` that takes the input string and returns an associative array where the keys are the tag names (in lowercase) and the values are the corresponding metadata. Th...
```php class TagParser { public function parseTags($inputString) { $tags = []; preg_match_all('/<(\w+)(?:\s(.*?))?>/', $inputString, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $tag_name = strtolower($match[1]); $metadata = isset($match[2]) ? trim($match...
magicoder
php
You are tasked with creating a function to convert an integer to its base 7 representation. The function should take an integer as input and return a string representing the base 7 equivalent of the input number. The base 7 representation should be in the form of a string. The base 7 representation of a number is obta...
```python def convertToBase7(num: int) -> str: result = '' n = abs(num) while n: n, curr = divmod(n, 7) result = str(curr) + result return '-' * (num < 0) + result or '0' ``` The solution defines the function `convertToBase7` which takes an integer `num` as input and returns a string re...
magicoder
python
You are tasked with creating a program to calculate the nth Fibonacci number using an efficient algorithm. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The program should take an integer input n and return the nth Fibonacci numbe...
```csharp using System; class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int result = Fibonacci(n); Console.WriteLine(result); } static int Fibonacci(int n) { if (n <= 1) { return n; } int ...
magicoder
csharp
You are working on a software module for tracking particles in a particle physics experiment. The code snippet provided is a part of this module and is responsible for creating a new track, `newTrack`, and populating a vector `componentHits` with hits that fall within the track's tolerance range. The `math::XYZPoint` ...
```cpp bool TotemTimingLocalTrack::containsHit(const Hit& hit, float tolerance) { // Calculate the distance between the hit and the track's position in 3D space float distance = sqrt(pow(hit.getX() - position.getX(), 2) + pow(hit.getY() - position.getY(), 2) + p...
magicoder
cpp
You are tasked with implementing a class to manage bus information for a transportation company. The class, `LanitBusInfo`, contains a static method `get_nearest_bus` that takes in the user's current location and their destination, and returns the nearest bus to their location. The `Locations` and `Destinations` are e...
```python from enum import Enum import logging class Locations(Enum): MARINA_ROSHHA = 1 # Add more locations as needed class Destinations(Enum): # Define destination enums as needed pass class LanitBusInfo: @staticmethod def get_nearest_bus(location: Locations, destination: Destinations) -> s...
magicoder
python
You are given a list of tuples, each representing a significant date and its corresponding event. The first element of each tuple is the month (as an integer), the second element is the day (as an integer), and the third element is the event name (as a string). Your task is to write a function that takes this list of t...
```python def organize_events(events): event_dict = {} for event in events: month = event[0] event_name = event[2] if month in event_dict: event_dict[month].append(event_name) else: event_dict[month] = [event_name] return event_dict ``` The `organize_...
magicoder
python
You are tasked with creating a Python function that processes images based on their EXIF metadata. The function should take an image object and its corresponding EXIF data as input and apply the necessary transformations to the image based on the orientation tag in the EXIF data. The orientation tag specifies the orien...
```python from PIL import Image, ExifTags def process_image(img, exif): if exif is not None: for tag, value in exif.items(): if ExifTags.TAGS.get(tag) == 'Orientation': if value == 3: img = img.rotate(180) elif value == 6: ...
magicoder
python
You are tasked with creating a program that generates a secure password based on specific criteria. The password must meet the following requirements: 1. Length: The password must be between 8 and 12 characters long, inclusive. 2. Composition: The password must contain a mix of uppercase letters, lowercase letters, num...
```java import java.security.SecureRandom; public class PasswordGenerator { private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String LOWER = "abcdefghijklmnopqrstuvwxyz"; private static final String DIGITS = "0123456789"; private static final String SPECIAL = "!@#$%...
magicoder
java
You are tasked with creating a script to manage the installation and configuration of dotfiles on a user's system. Dotfiles are configuration files for various programs and tools, typically stored in the user's home directory. The script should support customization of the clone URL and destination path, as well as the...
```bash #!/bin/bash # Set default values for clone URL and destination path CLONE_URL_DEFAULT="https://github.com/username/dotfiles.git" DOTFILES_PATH="$HOME/.dotfiles" # Set up environment variables with default or provided values CLONE_URL=${ARG_CLONE_URL-$CLONE_URL_DEFAULT} CONFIG_PATH=${ARG_DEST_PATH-$DOTFILES_PA...
magicoder
shell
You are tasked with creating a Python script that processes command-line arguments to output the adjacencies of leaf genomes of a given phylogeny in DeCo format. The DeCo format is a specific format used to represent the genome adjacencies in a phylogenetic tree. Your script should take the following command-line argu...
```python import argparse def parse_species_tree(species_tree_file): # Implement parsing of the species tree file and return the parsed tree pass def parse_leaf_genomes(leaf_genome_files): # Implement parsing of the leaf genome files and return the parsed genomes pass def output_adjacencies(species_t...
magicoder
python
You are given a code snippet that represents a character literal in the C programming language. Your task is to write a program that takes this character literal as input and converts it to its corresponding ASCII value. Your program should take the character literal as input and output the ASCII value of the characte...
```c #include <stdio.h> int main() { char inputChar = '&'; // Replace '&' with the given character literal int asciiValue = (int)inputChar; // Convert the character to its ASCII value printf("The ASCII value of %c is %d\n", inputChar, asciiValue); // Output the ASCII value return 0; } ```
magicoder
c
You are working on a project to set up a search system using Terrier, an open-source search engine platform. As part of the setup process, you need to perform several configuration and setup tasks. The given code snippet provides some commands and comments related to this setup process. Your task is to write a script ...
```bash #!/bin/bash # Step 1: Run trec_setup.sh script to set up collection mapping and index files ./bin/trec_setup.sh corpus/TREC # Step 2: Replace the default configuration file with the customized configuration file rm -f etc/terrier.properties cp etc/terrier.custom etc/terrier.properties echo "Terrier setup com...
magicoder
shell
You are tasked with implementing a Python class for a game character that moves within a game map. The class has an `__init__` method that initializes the character's attributes based on the provided parameters. The character's initial position and movement direction are determined by the `moveDir` parameter. The `spee...
```python class GameCharacter: hp = 1 def __init__(self, screen, gameMap, moveDir, speed): self.screen = screen self.gameMap = gameMap self.moveDir = moveDir self.speed = speed * 0.3 + 0.5 if moveDir == 1: self.x = screen.get_width() / 2 elif moveDir ...
magicoder
python
You are tasked with creating a class hierarchy for a library management system. The system should be able to handle different types of users, such as librarians and patrons, and store information about the books in the library. Your task is to design and implement the necessary classes to represent users and books, ens...
```csharp using System; public class User { public string UserName { get; set; } public string Email { get; set; } public bool VerifyUser() { // Implementation to verify user's identity return true; } } public class Librarian : User { public int EmployeeId { get; set; } p...
magicoder
csharp
You are tasked with implementing a function to calculate peri-event time histograms (PETHs) and firing rates for a set of spike data. The spike data consists of spike times and corresponding cluster IDs, and the PETHs and firing rates are calculated with respect to a set of event times. You are given the following inf...
```python import numpy as np def calculate_peths(spike_times, spike_clusters, cluster_ids, align_times): peths = [] fr = [] bin_size = 50 # Define the time bin size in milliseconds for cluster_id in cluster_ids: spike_times_cluster = spike_times[spike_clusters == cluster_id] peth_clus...
magicoder
python
You are tasked with implementing a class for solving 2D linear elasticity problems using the Green strain method. The provided code snippet is the constructor of the `GreenStrain_LIMSolver2D` class, which initializes the variable `Beta` to 100. Your task is to complete the implementation of the `GreenStrain_LIMSolver2D...
```cpp #include "GreenStrain_LIMSolver2D.h" #include "TriangleMesh.h" // Define the GreenStrain_LIMSolver2D class class GreenStrain_LIMSolver2D { private: double Beta; // Material property public: // Constructor to initialize Beta GreenStrain_LIMSolver2D() { Beta = 100; } // Method to calculate the Gre...
magicoder
cpp
You are tasked with implementing a macro in Rust that generates a sequence of durations based on a given input. The macro should take a variable number of expressions representing durations and combine them into a sequence using a specified method. The provided code snippet serves as a starting point for the macro impl...
```rust macro_rules! seq_with_dur { ($expr:expr) => { $expr }; ($head:expr, $($tail:expr $(,)?)+) => { $head.seq_with_dur($crate::seq_with_dur!($($tail,)*)) } } ``` The solution provides the complete implementation of the `seq_with_dur!` macro in Rust. The macro uses Rust's `macro_rules...
magicoder
rust
You are tasked with implementing a function to parse and extract information from a file header in the given format. The file header is a comment block at the beginning of a source file, and it contains metadata such as the file name, author, and copyright information. Your task is to write a function that extracts thi...
```cpp #include <iostream> #include <map> #include <regex> #include <string> std::map<std::string, std::string> parseFileHeader(const std::string& fileContent) { std::map<std::string, std::string> metadata; std::regex pattern("@file\\s(\\S+)|@brief\\s(.+)|@author\\s(.+)|Copyright\\s(\\d+-\\d+)\\s(.+)"); s...
magicoder
cpp
You are tasked with implementing a messaging system for a social networking platform. The provided code snippet includes partial implementations of two classes: `BaseMessage` and `FriendRequestMessage`. Your task is to complete the implementation of the `FriendRequestMessage` class by adding necessary methods and attri...
```python class BaseMessage: def __init__(self, data=None): if data: self._parse_dict(data) def _parse_dict(self, data): self.message_type = data.get('message_type') def to_dict(self): data = {'message_type': self.message_type} return data class FriendRequestM...
magicoder
python
You are tasked with implementing a function to parse and process a set of rules defined in a given code snippet. Each rule is represented by a line of text, and the rules are categorized by prefixes denoting their type. The prefixes are as follows: - `*` for general rules - `#` for utility rules Your task is to create...
```python def parse_rules(code_snippet: str) -> dict: rules_dict = {"general_rules": [], "utility_rules": []} lines = code_snippet.strip().split("\n") for line in lines: line = line.strip() if line.startswith("*"): rules_dict["general_rules"].append(line.lstrip("*").strip(",")) ...
magicoder
python
You are tasked with implementing a Python class for post-processing soft masks generated by an instance segmentation model. The class should support different post-processing methods and thresholding techniques. Your task is to create the `PostProcessor` class with the specified functionality. Your `PostProcessor` cla...
```python class PostProcessor: def __init__(self, post_proc_method, thresh_method="naive", thresh=0.5): self.post_proc_method = post_proc_method self.thresh_method = thresh_method self.thresh = thresh def process_soft_masks(self, soft_masks): # Implement post-processing based on...
magicoder
python
You are tasked with implementing a device descriptor system for a capture device in a multimedia application. The device descriptor points to a dispatch table and contains a list of filter descriptors that describe the filter types supported by the device. Your goal is to design a data structure and associated function...
```cpp #include <iostream> #include <vector> // Assume the existence of KsCreateFilterFactory function for creating filter factories class FilterDescriptor { private: std::string filterType; public: FilterDescriptor(const std::string& type) : filterType(type) {} std::string getFilterType() const { ...
magicoder
cpp
You are tasked with creating a Python function that processes a TensorFlow model and exports its weights and biases to a Wolfram Exchange Format (WXF) file. The function should take in the following parameters: - `reader`: An object representing the TensorFlow model reader, which provides access to the model's variable...
```python import wxf def export_to_wxf(reader, name): all_variables = list(reader.get_variable_to_shape_map().keys()) # Get all variable names npy = dict(zip(all_variables, map(reader.get_tensor, all_variables))) # Create a dictionary of variable names and their tensor values wxf.export(npy, name + '.wxf...
magicoder
python
You are working on a 3D graphics application and need to implement a function to draw a 3D cube using OpenGL. The cube should be centered at the origin and have a specified size. You are given the following code snippet as a starting point: ```c glVertex3f( WORLD_MAX, 0.0f, WORLD_MAX); glColor3f(0.0f, 0.0f, 0.0f);...
```c void drawCube(float size) { float halfSize = size / 2.0f; // Draw the front face glBegin(GL_QUADS); glColor3f(1.0f, 0.0f, 0.0f); // Red glVertex3f(-halfSize, -halfSize, halfSize); glVertex3f(halfSize, -halfSize, halfSize); glVertex3f(halfSize, halfSize, halfSize); glVertex3f(-half...
magicoder
c
You are tasked with creating a program that processes a list of GitHub repository URLs and checks for the presence of a license file in each repository. If a license file is found, the program should print a formatted message containing the repository ID, name, and the URL to the license file. You are given a code sni...
```python import requests def check_license(repo_urls): for repo in repo_urls: repo = repo[:-1] if repo.endswith('.git'): repo = repo[:-4] license_url = repo + "/blob/master/LICENSE" response = requests.get(license_url) if response.status_code == 200: ...
magicoder
python
You are given an array of strings and an integer k. Your task is to find the maximum sum of the lengths of k non-overlapping subarrays, where each subarray contains only distinct elements. If there are multiple possible combinations that result in the same maximum sum, you should return the lexicographically smallest c...
```python def max_sum_of_lengths(n, data, k): max_sum = 0 max_sum_indices = [] for i in range(len(data)): subarray_set = set() current_sum = 0 for j in range(i, len(data)): if data[j] not in subarray_set: subarray_set.add(data[j]) current_s...
magicoder
python
You are tasked with implementing a function to preprocess a set of graphs for a machine learning task. The function takes a list of filenames representing graph data and a set of labels as input. The goal is to normalize the graph data and prepare it for further processing. The provided code snippet shows a part of the...
```python import numpy as np import networkx as nx def preprocess_graphs(filenames, labels): def read_labels(labels_file): # Assume implementation for reading labels from a file pass def normalize_graph_data(graphs): normalized_graphs = [] for graph in graphs: adjac...
magicoder
python
You are tasked with implementing a neural network model using TensorFlow to classify handwritten digits from the MNIST dataset. The MNIST dataset contains 28x28 pixel grayscale images of handwritten digits (0-9). Your goal is to create a neural network model that can accurately classify these images into their respecti...
```python import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Step 1: Define input and output placeholders X = tf.placeholder(tf.float32, [None, 784]) # Input placeholder for 28x28 images Y = tf.placeholder(tf.float32, [None, 10]) # Output placeholder for digit classes (0-9) # Step...
magicoder
python
You are tasked with creating a program to analyze the coefficients of a transformed target regressor model trained using cross-validation. The transformed target regressor model is a machine learning technique that applies a transformation to the target variable before fitting a regressor model. The code snippet provid...
```python import numpy as np def analyze_coefficients(cv_model: dict) -> (list, list): coefficients = [est["transformedtargetregressor"]["regressor_"]["coef_"] for est in cv_model["estimator"]] average_coeffs = np.mean(coefficients, axis=0) std_coeffs = np.std(coefficients, axis=0) return average_coeff...
magicoder
python
You are tasked with implementing a basic Flask web application that provides a RESTful API for hashing text. The application should utilize Flask, Flask-SQLAlchemy, and Flask-Login to handle user authentication and store hashed text in a database. Your task is to complete the implementation of the Flask app by adding t...
```python from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy import flask_login from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///hashes.db' app.config['SECRET_KEY'] = 'supersecretkey' db = S...
magicoder
python
You are tasked with implementing a volume control system for a device. The system is configured using the following parameters: - `button_down`: The button used to decrease the volume. If set to 0, this functionality is disabled. - `button_mute`: The button used to toggle mute. If set to 0, this functionality is disabl...
```python from typing import List, Dict def volume_control(initial_volume: int, button_clicks: List[str], button_config: Dict[str, int]) -> int: volume = initial_volume for click in button_clicks: if click == "down" and button_config["button_down"] != 0: volume = max(0, volume - 1) ...
magicoder
python
You are working on a project that involves evaluating clusters of data points using a specific method. The code snippet provided is part of a larger program that uses the `evaluate_clusters_range` function to assess clusters within a given range of values. Additionally, the code snippet utilizes hierarchical clustering...
```python import numpy as np import scipy.cluster.hierarchy as hc import scipy.spatial.distance as sd def calculate_clusters(N_range, Dist, linkage_method, seed_thresholds): # Evaluate clusters within the given range Scores = gd.evaluate_clusters_range(np.arange(min(N_range), max(N_range) + 1), Dist, linkage_m...
magicoder
python
You are tasked with creating a function that simulates an asynchronous HTTP request using JavaScript's `Promise` object. Your function should mimic the behavior of the `$.ajax` method from the jQuery library, but without using jQuery itself. The function should take an object as a parameter, which contains the request ...
```javascript function simulateAjaxRequest(requestConfig) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open(requestConfig.method, requestConfig.url, true); for (const header in requestConfig.headers) { xhr.setRequestHeader(header, requestConfig.headers[header]);...
magicoder
javascript
You are tasked with implementing a thread-safe class for managing aeron subscriptions. The class should provide methods for resetting and stopping the subscriptions, ensuring that these operations are performed in a synchronized manner. Additionally, the class should enforce a specific state before allowing the stop op...
```java import java.util.concurrent.locks.ReentrantLock; public class AeronSubscriptionManager { private final ReentrantLock lock = new ReentrantLock(); private State state = State.STARTED; public synchronized void reset() { closeAeron(); } public void stop() { lock.lock(); ...
magicoder
java
You are tasked with creating a program that processes a given string to extract and manipulate specific information. The input string will contain a series of numbers and characters, and your program should extract the numbers and perform specific operations based on the characters present in the string. You are given...
```python import re def process_input_string(input_string): # Extract numbers and phrases from the input string using regular expressions numbers = re.findall(r'\d+', input_string) phrase_present = "ou mais" in input_string # Perform operations based on the extracted information first_number = int...
magicoder
python
You are tasked with creating a Rust function that parses command-line arguments and constructs a `SubstrateSyncParams` struct. The `SubstrateSyncParams` struct is used for configuring a synchronization process in a blockchain application. Your task is to complete the implementation of the `substrate_sync_params` functi...
```rust use crate::substrate_sync_loop::consts::*; use relay_ethereum_client::types::Address; struct SubstrateSyncParams { eth_contract_address: Address, } fn substrate_sync_params(matches: &clap::ArgMatches) -> Result<SubstrateSyncParams, String> { let eth_contract_address: Address = match matches.value_of("...
magicoder
rust
You are working on a system that manages orders for a retail company. The system uses Python and the pytest library for testing. The code snippet provided is part of a test fixture for the order management system. The `order` object represents an order in the system, and it has methods to set items and attributes. The...
```python def calculate_total_price(order): total_price = 0 for item in order.get_items(): # Assuming there is a method get_items() to retrieve the items in the order total_price += item.get_attribute('price') # Assuming there is a method get_attribute() to retrieve the price of the item return to...
magicoder
python
You are tasked with implementing a pagination function for a hypothetical AWS client. The function `paginate` takes in various parameters and is responsible for paginating through a list of Fargate profiles. Your goal is to write a function that can paginate through the list of Fargate profiles and return the paginated...
```swift func paginate<Result: AWSClientProtocol>( input: ListFargateProfilesRequest, initialValue: Result, client: AWSClient, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListFargateProfilesResponse, EventLoop) -> EventLoopFuture<(Bool, ...
magicoder
swift
You are tasked with implementing a function that processes a given array of commands and returns the final state of a system. Each command in the array is represented as a string and can be one of the following types: - "add x": Add the value x to the system. - "subtract x": Subtract the value x from the system. - "mul...
```javascript function processCommands(commands) { let state = 0; for (let command of commands) { const [operation, value] = command.split(' '); switch (operation) { case 'add': state += parseInt(value); break; case 'subtract': state -= parseInt(value); break; ...
magicoder
javascript
You are tasked with creating a Python program that parses the IANA Private Enterprise Numbers registry and extracts relevant information. The IANA Private Enterprise Numbers registry contains a list of assigned enterprise numbers for private use. Each entry in the registry includes the enterprise number, the organizati...
```python import requests from bs4 import BeautifulSoup def parse_iana_registry(url): response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.content, 'html.parser') table = soup.find('table', {'class': 'alt'}) if table: rows = table.find_a...
magicoder
python
You are tasked with creating a program that simulates a simple file management system. The system should be able to handle basic file operations such as creating, deleting, and listing files and directories. Your program should also support navigating through directories and displaying the current working directory. Y...
```python import os class FileManager: def __init__(self): self.current_directory = '/' def mkdir(self, directory_name): new_directory = os.path.join(self.current_directory, directory_name) os.makedirs(new_directory, exist_ok=True) def touch(self, file_name): new_file = os...
magicoder
python
You are tasked with implementing a Python class that manages different types of output destinations for a data processing pipeline. The code snippet provided defines a dictionary `OUTS_MAP` that maps output destinations to their respective classes. Each class is responsible for handling the output to a specific destina...
```python class OutputHDFS: def send(self, data): # Implementation for sending data to HDFS print(f"Sending data to HDFS: {data}") class OutputS3: def send(self, data): # Implementation for sending data to S3 print(f"Sending data to S3: {data}") class OutputLocal: def send(...
magicoder
python
You are tasked with implementing a function to compute the KKT (Karush-Kuhn-Tucker) system for a parallel nonlinear model predictive control (parNMPC) algorithm. The parNMPC algorithm is used to control a group of robots in a parallelized manner. The KKT system is computed for each time step in the algorithm, and the f...
```cpp void computeKKTSystem(Robot& robot, GridInfo& gridInfo, const std::vector<double>& prev_q, const std::vector<double>& prev_v, const State& current_s, const State& next_s, Matrix& kkt_matrix, Vector& kkt_residual) { //...
magicoder
cpp
You are tasked with creating a program to manage a library's book inventory. The program should allow users to add new books, remove existing books, and search for books by title or author. Additionally, the program should be able to display the entire inventory of books. You are provided with a partial implementatio...
```swift class Book { var title: String var author: String var isbn: String init(title: String, author: String, isbn: String) { self.title = title self.author = author self.isbn = isbn } } class Library { var inventory: [Book] init() { self.inventor...
magicoder
swift
You are tasked with implementing a Python function that calculates the percentage of occurrences of each unique element in a given list. The function should take a list of elements as input and return a dictionary where the keys are the unique elements from the input list, and the values are the percentages of occurren...
```python def calculate_percentages(input_list): counts = {} percentages = {} total_elements = len(input_list) # Count occurrences of each element for element in input_list: if element in counts: counts[element] += 1 else: counts[element] = 1 # Calculate...
magicoder
python
You are given a web page's HTML code snippet that represents a table structure. Your task is to write a program that parses this HTML code and extracts the data from the table. The HTML code snippet is as follows: ``` </div> ...
```python from bs4 import BeautifulSoup # Given HTML code snippet html_code = ''' </div> </div> </div> </div> ...
magicoder
python
You are tasked with creating a web application that utilizes a template system to display content. The application uses a popular PHP framework that allows for the creation of reusable templates. The code snippet provided is a simplified representation of a template file in the application. Your task is to implement a...
```php function generateContentSection($sectionName, $content) { // Generate the HTML code to include the content within the specified section $html = "@extends('layouts.app_template')\n"; $html .= "@section('$sectionName')\n"; $html .= $content . "\n"; $html .= "@stop\n"; return $html; } // Te...
magicoder
php
You are tasked with implementing a learning rate scheduler for a neural network training process. The provided code snippet contains configuration settings for the learning rate schedule. Your task is to write a function that takes these configurations and computes the learning rate for a given epoch during training. ...
```python import numpy as np def compute_learning_rate(epoch, steps_per_epoch, lr_configs, base_learning_rate): if lr_configs.learning_rate_schedule == 'compound': factors = lr_configs.factors.split('*') if 'constant' in factors: constant_factor = float(factors[factors.index('constant')...
magicoder
python
You are tasked with implementing a utility function for managing CSS class names in a React application. The function should take in a series of utility functions and return a string of concatenated class names based on the provided utilities. Each utility function corresponds to a specific CSS property and value. You...
```javascript function classnames(...args) { return args.map(fn => fn()).join(' '); } ``` The `classnames` function takes any number of utility functions as arguments using the spread operator. It then maps over the arguments, invoking each function to get the corresponding CSS class name and finally joins the result...
magicoder
javascript
You are tasked with creating a function that takes in a JavaScript object representing a style sheet and returns an array of all the unique colors used in the style sheet. Each key in the object represents a style class, and the value is an object containing style properties and their values. For example, given the fo...
```javascript function extractUniqueColors(styleSheet) { const colorSet = new Set(); for (const key in styleSheet) { const style = styleSheet[key]; for (const prop in style) { if (prop === 'color') { colorSet.add(style[prop]); } } } return Array.from(colorSet); } // Test the f...
magicoder
javascript
You are tasked with creating a Python function that processes a set of IP addresses obtained from a Redis database and returns a list of unique IP addresses along with their corresponding dates. The function should connect to the Redis database, retrieve the IP addresses and dates, and then return the unique IP address...
```python import redis def get_unique_ips_with_dates(size=100): r = redis.Redis() # Connect to the Redis database ip_date_map = {} # Dictionary to store IP addresses and their corresponding dates # Retrieve IP addresses and dates from the 'tncorejobs' sorted set for job_key in r.zrange('tncorejobs'...
magicoder
python
You are tasked with implementing a Python function to extract radial, sulcal, and gyral orientations from a gyral coordinate NIFTI file. The NIFTI file contains 3D brain images and is commonly used in neuroimaging research. The gyral coordinate NIFTI file represents the gyral pattern of the brain, and the goal is to ex...
```python import nibabel as nib import numpy as np def extract_orientations(nifti_file_path: str) -> dict: nifti_img = nib.load(nifti_file_path) data = nifti_img.get_fdata() # Implement algorithms or methods to extract radial, sulcal, and gyral orientations from the data # Example: Calculate orientati...
magicoder
python
You are tasked with creating a Python program that converts RGB color values to CMYK color values. The RGB color model is represented by three values (R, G, B) ranging from 0 to 255, while the CMYK color model is represented by four values (C, M, Y, K) ranging from 0% to 100%. The conversion formulas are as follows: C...
```python # Prompt user for RGB color values R, G, B = [float(X) / 255 for X in input('RGB: ').split()] # Calculate CMYK color values K = 1 - max(R, G, B) C = round((1 - R - K) / (1 - K) * 100, 1) M = round((1 - G - K) / (1 - K) * 100, 1) Y = round((1 - B - K) / (1 - K) * 100, 1) K = round(K * 100, 1) # Display the C...
magicoder
python
You are tasked with implementing a feature gate mechanism in Rust to conditionally enable or disable certain modules based on a configuration setting. The code snippet provided includes a module `hashing_utils` and a comment indicating the intention to feature gate the `serde_utils` module. Your task is to create a fu...
```rust use std::collections::HashSet; pub struct FeatureGate { enabled_modules: HashSet<String>, } impl FeatureGate { pub fn new() -> Self { FeatureGate { enabled_modules: HashSet::new(), } } pub fn enable_module(&mut self, module_name: &str, enable: bool) { if en...
magicoder
rust
You are given a list of integers and a target value. Your task is to implement a function `find_target_indices(nums: List[int], target: int) -> List[Tuple[int, int]]` that returns a list of tuples, where each tuple contains the indices of two elements from the input list that sum up to the target value. If no such pair...
```python from typing import List, Tuple def find_target_indices(nums: List[int], target: int) -> List[Tuple[int, int]]: num_indices = {} result = [] for i, num in enumerate(nums): complement = target - num if complement in num_indices: result.append((num_indices[complement...
magicoder
python
You are tasked with creating a function that determines whether a given user belongs to a specific group of students in a database. The database schema includes tables for users, groups, and memberships. The function should take the user ID and the IDs of the student groups as input and return a boolean value indicatin...
```python def is_user_student(user_id, student_group_ids): # Query the database to check if the user belongs to any of the specified student groups student_membership = db( (db.auth_membership.user_id == user_id) & (db.auth_membership.group_id.belongs(student_group_ids)) ).select().first() ...
magicoder
python
You are tasked with creating a Python script that processes a directory of text files and extracts specific information from them. The script should take in a directory path as a command-line argument and then perform the following tasks for each text file in the directory: 1. Extract the file name and creation date o...
```python import os import glob import re from datetime import date import argparse import subprocess from pathlib import Path def extract_information(directory): try: files = glob.glob(os.path.join(directory, '*.txt')) for file in files: file_name = os.path.basename(file) c...
magicoder
python
You are tasked with creating a function that can determine the longest common prefix among an array of strings. The longest common prefix is the longest string that is a prefix of all strings in the array. If there is no common prefix, the function should return an empty string. Write a function `longestCommonPrefix` ...
```python def longestCommonPrefix(strs): if not strs: return "" # Sort the array of strings to easily find the common prefix strs.sort() # Compare the first and last strings to find the common prefix first = strs[0] last = strs[-1] prefix = "" for i in range(len(first)): ...
magicoder
python
You are tasked with implementing a class that manages different modes of operation for an application. The class should handle the selection of an icon to determine the active mode and update the corresponding mode when necessary. You are given a code snippet from the existing application that demonstrates how the ico...
```cpp #include <iostream> enum Mode { App, Editor, Settings }; class ModeManager { private: Mode m_mode; public: ModeManager() : m_mode(App) {} void setMode(Mode mode) { m_mode = mode; } void updateMode(int iconIndex) { if (m_mode != static_cast<Mode>(iconIndex) && iconIndex >=...
magicoder
cpp
You are tasked with implementing a function to load thermodynamic data from a database and perform specific operations on the data. The thermodynamic data is stored in a database represented by the `thermodb` variable. The `load_thermoDB` function is responsible for loading the thermodynamic data into the `thermodb` va...
```python from typing import Tuple # Sample data structure for thermodynamic data class ThermodynamicData: def __init__(self, data: dict): self.data = data def load_thermoDB(thermodb: ThermodynamicData) -> ThermodynamicData: # Implementation of loading thermodynamic data from a database # Assume t...
magicoder
python
You are working on a project that involves managing access control policies using the eXtensible Access Control Markup Language (XACML). As part of this project, you need to develop a Java program that can dynamically load XACML policy files from a specified directory and extract certain information from these policies...
```java import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.logging.Logger; import com.sun.xacml.ParsingException; import com.sun.xacml.finder.PolicyFinder; import com.sun.xacml.support.finder.PolicyReader; public class XacmlPolicyManager { public static void main(Stri...
magicoder
java
You are tasked with implementing a function to calculate the information gain in a decision tree. Information gain is a measure used in the construction of decision trees to determine the attribute that provides the greatest amount of information about the classification of a set of items. The function `info_gain(prev_...
```python import math def Entropy(dist): total_count = sum(dist.values()) entropy = 0 for count in dist.values(): if count != 0: proportion = count / total_count entropy -= proportion * math.log2(proportion) return entropy def info_gain(prev_dist, new_dist): prev_en...
magicoder
python
You are tasked with implementing a caching mechanism for a web application's configuration settings. The application has a class `API` that provides access to various settings, and a class `Cache` that handles caching. The `API` class has a method `GetValueOrDefault` to retrieve settings, and the `Cache` class has a me...
```csharp protected string AmazonKeyID { get { return this.Cache15.PerLifetime("AmazonKeyID", () => { return this.API.Direct.GlobalSettings.GetValueOrDefault(string.Format(CommonAssumptions.CONFIG_KEY_AMAZON_KEY, this.EnvironmentName), string.Empty); }); } } protected st...
magicoder
csharp
You are given the definition of a singly linked list node and a method to reverse the linked list. Your task is to complete the implementation of the `reverse` method to reverse the given linked list. If the input linked list is empty or has only one node, the method should return the head of the original list. The de...
```python class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def reverse(self, head): if head is None or head.next is None: return head prev_node = None current_node = head next_node = None while curr...
magicoder
python
You are tasked with implementing a function that checks the validity of a given PHP code snippet. The function should determine if the PHP code snippet contains a specific function call and if it is properly terminated. You are given a PHP code snippet as a string. The code snippet may contain various PHP constructs,...
```php function validatePHPCode(string $code): bool { // Find the position of the function call $functionCallPos = strpos($code, 'end_admin_panel()'); // If the function call is found if ($functionCallPos !== false) { // Check if the function call is properly terminated with a semicolon ...
magicoder
php
You are given a function `sum(n, k)` that takes in two integers `n` and `k`. The function should return the sum of all integers from `k` to `n` inclusive. However, the function should only be called if `n` is non-negative and `k` is a non-negative integer not exceeding 10^9, and `n` is greater than or equal to `k`. If ...
```python def conditional_sum(n, k): if 0 <= n and k <= 10**9: if n >= k: return sum(range(k, n+1)) return -1 ```
magicoder
python
You are tasked with implementing a constant-time branch operation function in Python. The function should take three parameters: `subject`, `result_if_one`, and `result_if_zero`. The function should return `result_if_one` if `subject` is 1, and `result_if_zero` if `subject` is 0. The catch is that the function should e...
```python def select(subject, result_if_one, result_if_zero): """Perform a constant time branch operation""" mask = -subject # If subject is 1, mask will be -1, if subject is 0, mask will be 0 return (result_if_one & mask) | (result_if_zero & ~mask) ``` The provided solution implements the `select` functi...
magicoder
python
You are tasked with creating a Python function that takes a list of package names and their dependencies as input and returns a valid installation order for the packages. The input will be provided in the form of a dictionary, where the keys are package names and the values are lists of package dependencies. The functi...
```python def install_order(packages: dict) -> list: # Create a graph to represent the dependencies graph = {package: set(dependencies) for package, dependencies in packages.items()} # Create a set of all packages all_packages = set(graph.keys()) # Create a set of installed packages installed ...
magicoder
python
You are tasked with implementing a rate limiting system for a web application called BubbleBBS. The application has various actions that need to be rate-limited to prevent abuse and ensure fair usage. The rate limits are defined in the code snippet provided. Each rate limit is specified in terms of a maximum number of ...
```python import time from collections import defaultdict # Define rate limits rate_limits = { 'DEFAULT': {'per_day': 400, 'per_hour': 100}, 'LIST_THREADS': {'per_minute': 20, 'per_second': 1}, 'VIEW_SPECIFIC_POST': {'per_minute': 20, 'per_second': 1}, 'NEW_REPLY': {'per_hour': 20, 'per_second': 1, 'pe...
magicoder
python
You are given a grid of size m x n, where each cell contains a non-negative integer value. You are initially positioned at the top-left cell and are required to reach the bottom-right cell. You can only move either down or right at any point in time. Additionally, you need to find the minimum sum of values along a path...
```python from typing import List def minPathSum(grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) # Initialize the first row for j in range(1, n): grid[0][j] += grid[0][j-1] # Initialize the first column for i in range(1, m): grid[i][0] += grid[i-1][0] ...
magicoder
python
You are given a code snippet that appears to be part of a merge sort algorithm. Your task is to implement the missing functions and complete the merge sort algorithm to sort an array of integers. The `merge_sort` function takes in an array `nums1`, an auxiliary array `nums0`, and the indices `low` and `high`. It is ex...
```java public class MergeSort { public void merge_sort(int[] nums1, int[] nums0, int low, int high) { if (low < high) { int pos = (low + high) / 2; merge_sort(nums1, nums0, low, pos); merge_sort(nums1, nums0, pos+1, high); merge(nums0, nums1, low, pos, high);...
magicoder
java
You are tasked with implementing a method to determine whether a given attribute is present within a custom data structure representing Swift type attributes. The data structure is defined using an enumeration with associated values, and the method should recursively search through the structure to find the specified a...
```swift extension TypeAttribute { func containsAttribute(named attribute: String) -> Bool { switch self { case .optional(let wrapped), .implicitlyUnwrappedOptional(let wrapped): return wrapped.containsAttribute(named: attribute) case .attributed(_, let attributes): r...
magicoder
swift
You are given a snippet of code representing a set of variables initialized to 0. Your task is to write a function that takes in a list of variable names and returns the sum of the values of these variables. The function should consider only the variables provided in the input list and ignore any other variables. For ...
```python from typing import List def calculate_variable_sum(variables: List[str]) -> int: variable_values = { 'c23_2d': 0, 'c24_2d': 0, 'up2_2d': 0, 'c30_2d': 0, 'c31_2d': 0, 'c32_2d': 0, 'c33_2d': 0, 'c34_2d': 0, } total_sum = 0 for var ...
magicoder
python
You are tasked with implementing a function to compare the result of an inverse kinematics (IK) solver with an expected set of joint configurations. The IK solver computes joint configurations for a robotic arm given a desired end-effector pose. The joint configurations are represented by a set of RevoluteJoint objects...
```cpp #include <iostream> #include <vector> #include <memory> #include <cmath> class Joint { public: virtual double getAngle() const = 0; }; class RevoluteJoint : public Joint { private: double angle; public: RevoluteJoint(double a) : angle(a) {} double getAngle() const override { return an...
magicoder
cpp
You are working on a medical imaging project and need to process MRI data using Python and R. You have a 3D MRI image stored in the NIfTI format (.nii) and want to perform some statistical analysis on the image data. To achieve this, you need to read the MRI data using Python's nibabel library, convert it to a NumPy ar...
```python import numpy as np import nibabel as nib import rpy2.robjects as robjects from rpy2.robjects.numpy2ri import numpy2ri def process_mri_data(file_path): # Read MRI data using nibabel mri_img = nib.load(file_path) mri_data = mri_img.get_fdata() # Perform preprocessing (e.g., normalization) ...
magicoder
python
You are tasked with creating a script to automate the setup of a development environment for a specific project. The script should perform the following tasks: 1. Create a folder named "artifact". 2. Navigate into the "artifact" folder. 3. Clone a specific GitHub repository named "foundational_boogie" into the "artifa...
```bash #!/bin/bash # Create artifact folder echo "Setting up artifact folder" mkdir artifact cd artifact # Clone foundational_boogie repository git clone https://github.com/gauravpartha/foundational_boogie/ cd foundational_boogie # Checkout specific commit git checkout 26245973788c cd .. # Add boogie session to RO...
magicoder
shell
You are tasked with implementing a function that reorders child elements within a rendering hierarchy and removes a specific element. The rendering hierarchy is represented by a tree-like structure, where each node is a `RenderObject`. The function should also update the rendering hierarchy to set a full-screen rendere...
```cpp void RenderFullScreen::setPlaceholder(RenderBlock* placeholder) { RenderObject* child; while ((child = firstChild())) { child->remove(); // Remove the child from its current position in the rendering hierarchy holder->parent()->addChild(child, holder); // Add the removed child to the pa...
magicoder
cpp
You are given a Python function `simulate(reg_0, find_non_loop)` that takes two parameters: - `reg_0`: An integer representing the initial value of a register. - `find_non_loop`: A boolean flag indicating whether to find the first non-looping value or not. The function simulates a register machine with the following r...
```python def simulate(reg_0: int, find_non_loop: bool) -> int: seen = set() c = 0 last_unique_c = -1 while True: if reg_0 in seen: if find_non_loop: return reg_0 else: return c seen.add(reg_0) if reg_0 % 2 == 0: ...
magicoder
python
You are tasked with creating a program that parses HTML code to extract specific information. Given an HTML snippet as input, your program should identify and extract all the form IDs present in the code. For example, given the following HTML snippet: ``` <span class="loading"></span> ...
```python import re def extract_form_ids(html_snippet): form_ids = re.findall(r'<form.*?id="(.*?)"', html_snippet) return form_ids # Example usage html_snippet = ''' <span class="loading"></span> </div> </div> </div> <div cla...
magicoder
python
You are tasked with implementing a program to validate a string based on certain criteria. The string should only contain valid letters, and it should have a valid format based on the values assigned to each letter. The program should have the following functionalities: 1. Check if the provided string contains only v...
```java public class StringValidator { public static void main(String[] args) { String input = "ABCD"; try { if (!hasValidLetters(input.toCharArray())) { throw new IllegalArgumentException("Provided string contains invalid letters!"); } int[] value...
magicoder
java
You are given a string `word` and a character `ch`. Your task is to reverse the substring of `word` starting from the beginning of `word` up to and including the first occurrence of `ch`, and then concatenate the rest of the `word` as is. Write a function `reversePrefix` that takes in the string `word` and the charact...
```python def reversePrefix(word: str, ch: str) -> str: if ch in word: index = word.find(ch) return ''.join(reversed(word[:index + 1])) + word[index + 1:] else: return word ``` The `reversePrefix` function first checks if the character `ch` is present in the input string `word`. If it i...
magicoder
python
You are tasked with implementing a custom comparison function for a Rust enum type called `Currencies`. The `Currencies` enum has two variants: `InGame(currencies)` and `Cash(currencies)`. The comparison function should compare two instances of `Currencies` based on the following rules: 1. If both instances are of type...
```rust use std::cmp::Ordering; enum Currencies { InGame(u32), Cash(u32), } impl Currencies { fn custom_cmp(&self, other: &Currencies) -> Ordering { match (self, other) { (Currencies::InGame(currencies1), Currencies::InGame(currencies2)) => { currencies1.cmp(currencies2...
magicoder
rust
You are tasked with creating a program to visualize the loss and associated metrics throughout the training process. The program will take the path to a directory for a specific training run as its first argument. The directory will contain the necessary data for plotting the loss and metrics. Your task is to implemen...
```python import os import matplotlib.pyplot as plt import pandas as pd def visualize_training(directory_path): # Read data files from the directory files = [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))] # Extract metrics from data files metrics = defaul...
magicoder
python
You are tasked with implementing a function that processes data from a collection of dictionaries and returns a specific result based on the given criteria. The function should take in a list of dictionaries, each representing a data entry, and return a new list containing specific information extracted from the input ...
```python def process_data(visual_conf, rel_coll_data): result = [] for tag, description in visual_conf.items(): for data_entry in rel_coll_data: if tag in data_entry.get("labels", []): result.append((tag, data_entry["name"])) break # Once a match is found, m...
magicoder
python
You are working on a web application using the Flask framework and SQLAlchemy for database management. You have come across the configuration variable `SQLALCHEMY_TRACK_MODIFICATIONS` set to `True` in the application's configuration file. You are concerned about the potential performance implications of this setting an...
```python def explain_sqlalchemy_track_modifications(): explanation = { "purpose": "Enables or disables the modification tracking for objects.", "impact": "Setting SQLALCHEMY_TRACK_MODIFICATIONS to True can consume additional memory and negatively impact performance, especially in large applications...
magicoder
python
You are tasked with creating a database migration script for a Laravel application that manages user roles, permissions, and their associations. The provided code snippet is a part of the migration script and is responsible for creating foreign key constraints for the `role_id` and `user_id` columns in a table. Your ta...
```php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePermissionUserTable extends Migration { public function up() { Schema::create('permission_user', function (Blueprint $table) { $table->id(); ...
magicoder
php
You are tasked with implementing a library management system that tracks actions performed by students on books. The provided code snippet contains a method signature for connecting an action to its referenced objects and a method signature for retrieving actions by their type. Your task is to implement the `connectAct...
```java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LibraryManagementSystem { private Map<Action, List<Object>> actionReferences; public LibraryManagementSystem() { this.actionReferences = new HashMap<>(); } /** * Connec...
magicoder
java
You are working on a bioinformatics pipeline for evaluating the accuracy of variant calls in VCF (Variant Call Format) files. As part of this pipeline, you need to write a script to run the `vcfeval` tool to compare a sample VCF file against a truth VCF file. The `vcfeval` tool is typically used to assess the performan...
```bash #!/bin/bash # Compress and index the sample VCF file bgzip ${SAMPLE_VCF_BASENAME}.vcf tabix -f -p vcf ${SAMPLE_VCF_BASENAME}.vcf.gz # Compress and index the truth VCF file bgzip truth.vcf tabix -f -p vcf truth.vcf.gz # Run vcfeval within the Singularity container module load singularity singularity exec vcfe...
magicoder
shell
You are given a maze represented as a 2D grid of cells. Each cell can be either open or blocked. The objective is to find the shortest path from the start cell to the end cell, where movement is only allowed to adjacent open cells (up, down, left, and right). Write a function `shortestPath` that takes the maze grid, t...
```cpp #include <vector> #include <queue> #include <utility> int shortestPath(std::vector<std::vector<int>>& maze, int start_row, int start_col, int end_row, int end_col) { int rows = maze.size(); int cols = maze[0].size(); std::vector<std::vector<int>> distance(rows, std::vector<int>(cols, -1)); std::...
magicoder
cpp
You are tasked with implementing a simplified version of a logging system using C++. The system will utilize a YAML file format to store atomic operations. You are provided with a partial code snippet for the `YamlLogger` class, which uses a private implementation pointer (`_pimpl`) to interact with the underlying impl...
```cpp #include <iostream> #include <fstream> #include <yaml_library> // Assume the existence of a YAML library for parsing and serialization // Define the AtomicOperation class to represent a single atomic operation class AtomicOperation { // Define member variables and methods as per the requirements }; // Define...
magicoder
cpp
You are tasked with implementing a class `GridWorld` that represents a grid-based world with various features located at different positions. The class should have the following functionalities: 1. `feature_locations`: A method that returns a dictionary where the keys are the features present in the grid and the value...
```python class GridWorld: def __init__(self, grid): self.grid = grid def feature_locations(self): features = {} for row_idx, row in enumerate(self.grid): for col_idx, feature in enumerate(row): if feature != ' ': if feature not in feature...
magicoder
python
You are tasked with implementing a genetic algorithm to optimize a specific function. The genetic algorithm involves the use of a fitness function, selection, crossover, and mutation operations. Your goal is to write a Python function that takes in a population of candidate solutions and returns the next generation of ...
```python # Sample usage of the genetic_algorithm function initial_population = np.random.uniform(-5, 5, size=10) next_generation = genetic_algorithm(initial_population) print("Next Generation:", next_generation) ``` The `genetic_algorithm` function applies the genetic algorithm operations to the given population and ...
magicoder
python
You are tasked with creating a Python class to manage time windows for social distancing and travel restrictions during a pandemic. The class should be able to calculate the effectiveness of social distancing measures and the impact of travel restrictions based on the provided time windows. You are given a code snippe...
```python from datetime import datetime, timedelta class Window: def __init__(self, start_days, end_days, ramp_up, ramp_down, effectiveness): self.start_days = start_days self.end_days = end_days self.ramp_up = ramp_up self.ramp_down = ramp_down self.effectiveness = effectiv...
magicoder
python
You are tasked with implementing a gene set z-score calculation method in Python. The gene set z-score is a statistical measure used in bioinformatics to assess the enrichment of a gene set within a larger dataset. You are provided with a class `GeneSetAnalyzer` that contains a method `gs_zscore` for calculating the z-...
```python import pandas as pd class GeneSetAnalyzer: def __init__(self, df): if df.empty: raise ValueError("Input Dataframe is empty, please try with a different one.") else: self.df = df def gs_zscore(self, names='Zscore', gene_set=[]): if self.df.empty: ...
magicoder
python
You are tasked with implementing a Python function that calculates the unbalanced loss for a given set of masked maps. The function should take into account various parameters such as balance loss, main loss type, negative ratio, and whether to return the unbalanced loss or not. You are given the following function si...
```python import numpy as np def calculate_unbalanced_loss(mask, balance_loss=True, main_loss_type='DiceLoss', negative_ratio=3, return_origin=False, eps=1e-6): """ Calculate unbalanced loss for masked maps. Args: - mask (variable): masked maps. - balance_loss (bool): whether balance loss or not, ...
magicoder
python
You are tasked with creating a program that simulates a simplified version of an online code submission system. Your program should take a user's code submission, language choice, and problem ID, and then make a POST request to a specified URL with the provided data. You are given the following code snippet as a start...
```python import requests def submit_code(url: str, problem_id: str, language: str, source: str, language_code: dict) -> None: data = { 'localid': problem_id, 'language': language_code[language], 'code': source } session = requests.Session() session.post(url, data=data) ``` The...
magicoder
python
You are tasked with implementing a custom Metropolis Monte Carlo sampler for a simple 1D Gaussian distribution. The sampler should perform a series of steps to explore the distribution and generate samples. The Gaussian distribution is defined as `f(x) = (1/sqrt(2*pi*sigma^2)) * exp(-(x-mu)^2 / (2*sigma^2))`, where `mu...
```python import numpy as np class MetropolisMC: def __init__(self, mu, sigma, proposal_std): self.mu = mu self.sigma = sigma self.proposal_std = proposal_std def proposal(self, x): return np.random.normal(x, self.proposal_std) def acceptance_probability(self, x, x_new): ...
magicoder
python