query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with creating a memoized selector function in a Redux application using the `reselect` library. The `reselect` library provides a `createSelector` function that allows for efficient memoization of selectors, preventing unnecessary recalculations when the Redux state changes. Your task is to write a memo...
```typescript import { createSelector } from 'reselect'; // Define the AppState type assumed to be defined elsewhere type AppState = { // Define the structure of the application state // ... }; // Define the memoizedStateSelector function using createSelector const memoizedStateSelector = createSelector( (s: Ap...
magicoder
typescript
You are tasked with creating a Rust macro for generating a list of items. The macro should take a list of item names and generate code to import and use these items in a Rust module. The macro should also ensure that the items are only accessible within the module where the macro is used. Your task is to implement the...
```rust macro_rules! sketchlist { ($($item:ident::$Item:ident),*) => { $( use $item::$Item; pub(self) use $item::$Item; )* }; } ``` The `sketchlist!` macro is implemented using Rust's macro_rules. It takes a list of item names in the format `item::Item` and generates code...
magicoder
rust
You are tasked with implementing a function that processes a list of `raw_matches` and constructs a list of dictionary objects based on certain conditions. Each `raw_match` is an object with attributes `external_references` and `kill_chain_phases`. The function should iterate through each `raw_match` and extract releva...
```python def process_raw_matches(raw_matches): technique_list = [] for match in raw_matches: xid = '' xphase = '' for ref in match.external_references: if ref.source_name == 'mitre-attack': xid = ref.external_id for phase in match.kill_chain_phases: ...
magicoder
python
You are tasked with implementing a class that simulates a simple banking system. The class should have the ability to create accounts, deposit funds, withdraw funds, and check the balance of an account. Additionally, the class should enforce certain security measures to protect the account balances. Your task is to im...
```php class BankAccount { private $balance; public function createAccount() { $this->balance = 0; } public function deposit($amount) { if ($amount > 0) { $this->balance += $amount; } } public function withdraw($amount) { if ($amount > 0 && $amount ...
magicoder
php
You are tasked with designing a messaging system for a financial data application. The system needs to handle various types of messages, including reactor channel events, default messages, RDM login messages, RDM directory messages, and RDM dictionary messages. To achieve this, you need to create an interface in Java t...
```java public interface ProviderCallback extends ReactorChannelEventCallback, DefaultMsgCallback, RDMLoginMsgCallback, RDMDirectoryMsgCallback, RDMDictionaryMsgCallback { // This interface does not contain any method declarations, as it is a marker interface // meant to group the callback interfaces t...
magicoder
java
You are tasked with implementing a class method that checks whether a given set of tags matches the tags associated with a record. The record and the class have a set of tags associated with them. The method should return a boolean value indicating whether the tags match. You are given the following code snippet as a ...
```python class RecordChecker: def __init__(self, tags): self.tags = tags def check_tags_match(self, record): for t in record.tags: if t in self.tags: if self.tags[t]: should_cb = True continue else: ...
magicoder
python
You are tasked with creating a program to control an RGB LED connected to a microcontroller via a serial port. The microcontroller expects a specific serial command format to set the color and brightness of the LED. The command should be in the format "red,green,blue,lower,higher\n" where red, green, and blue are integ...
```python import serial def send_serial_command(red, green, blue, lower, higher, serial_port): serial_command = f"{red},{green},{blue},{lower},{higher}\n" if serial_port: try: ser = serial.Serial(serial_port, 115200, parity=serial.Parity.NONE, bytesize=8, stopbits=serial.STOPBITS_ONE) ...
magicoder
python
You are given a date in the format "YYYY/MM/DD". Your task is to write a function to determine the day of the week for that date. The function should take the date as input and return the corresponding day of the week as a string. For example, given the date "2021/3/31", the function should return "Wednesday". You ca...
To solve this problem, we can use the `datetime` module in Python, which provides a convenient way to work with dates and times. We can parse the input date string into a `datetime` object and then use the `strftime` method to obtain the day of the week. Here's the implementation of the `day_of_the_week` function: ``...
magicoder
python
You are tasked with implementing a custom data structure called `MaybeOwned` in Rust. The `MaybeOwned` data structure can hold either a borrowed reference or an owned value. Your task is to implement the `get_value` method for the `MaybeOwned` enum, which returns the inner value regardless of whether it is borrowed or ...
```rust enum MaybeOwned<'a, T: 'a> { Borrowed(&'a T), Owned(T), } impl<'a, T: 'a> MaybeOwned<'a, T> { fn get_value(self) -> &'a T { match self { MaybeOwned::Borrowed(v) => v, MaybeOwned::Owned(v) => &v, } } } fn main() { let value = 42; let borrowed_mayb...
magicoder
rust
You are tasked with implementing a custom hyperparameter search algorithm for a support vector classifier (SVC) using the Hyperband algorithm. The Hyperband algorithm is a resource allocation method that balances the number of configurations evaluated and the resources allocated to each configuration. In this problem, ...
```python from sklearn.model_selection import ParameterSampler from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score def hyperband_search_cv(model, param_distributions, max_iter, eta): s_max = int(np.log(max_iter) / np.log(eta)) B = (s_max + 1) * max_iter for s in...
magicoder
python
You are tasked with implementing a function to process a data structure representing joint positions from a motion capture system. The data structure contains an array of 3D vectors representing the positions of 21 joints in a human body, along with a confidence value for the captured data. You need to implement a met...
```csharp public class JointProcessor { public float CalculateAverageJointDistance(JointData jointData) { float totalDistance = 0; int pairCount = 0; for (int i = 0; i < jointData.joints.Length; i++) { for (int j = i + 1; j < jointData.joints.Length; j++) ...
magicoder
csharp
You are tasked with creating a function that will parse a given code snippet and extract the number of GitHub stars for a repository and the name of the search icon file. The code snippet is written in JavaScript and may contain other unrelated code. The GitHub stars count is denoted by the placeholder `<gh_stars>` and...
```javascript function parseCodeSnippet(codeSnippet) { const ghStarsRegex = /<gh_stars>(\d+)/; const searchIconRegex = /require\(".*\/(.*?)\.svg"\)/; const ghStarsMatch = codeSnippet.match(ghStarsRegex); const searchIconMatch = codeSnippet.match(searchIconRegex); if (ghStarsMatch && searchIconMatch) { c...
magicoder
javascript
You are given a Python code snippet that simulates the generation of a file containing pairs of source and destination addresses. The addresses are represented by indices and offsets into an array of pages. Your task is to write a program to process this file and perform specific operations on the addresses. The code ...
```python from collections import Counter # Read the file containing pairs of source and destination addresses with open('address_pairs.txt', 'r') as file: address_pairs = [list(map(int, line.split())) for line in file] # Calculate the total number of unique source addresses unique_sources = set(pair[0] for pair ...
magicoder
python
You are tasked with creating a Python function that processes configuration files for software packages and starts the ones marked for autostart. The configuration files are in YAML format and are stored in a specific directory. Your function should read each configuration file, check if the package is set to autostart...
```python from temiReceiver import start_pack, working_dir, get_packs import yaml import os def process_autostart_packages() -> None: packs_dir = os.path.join(working_dir, "packs") for pack in get_packs(): config_file = os.path.join(packs_dir, f"{pack}.yml") if os.path.exists(config_file): ...
magicoder
python
You are tasked with creating a C++ program that interfaces with two different devices: a CMPS14 compass module over I2C and an Arduino for motor control over serial communication. The program should read data from the compass module and send control commands to the Arduino for motor control. The program should also han...
```cpp #include <sys/ioctl.h> #include <iostream> #include <fstream> using namespace std; #include <ctime> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <linux/i2c-dev.h> #include <wiringPiI2C.h> #define I2C_DEVICE_ADDRESS 0x60 #define ARD...
magicoder
cpp
You are tasked with implementing a command-line argument parser for a tool called `torshammer.py`, which is used for launching a DDoS attack through Tor. The tool has several command-line options that need to be parsed and processed. Your task is to write a Python function that takes a list of command-line arguments an...
```python from typing import List, Dict, Union def parse_arguments(args: List[str]) -> Dict[str, Union[str, int, bool]]: options = {'target': '', 'threads': 256, 'port': 80, 'tor': False, 'help': False} i = 0 while i < len(args): if args[i] in ['-t', '--target']: options['target'] = arg...
magicoder
python
You are tasked with creating a Python class to perform structural analysis on a beam using the finite element method. The given code snippet is part of a larger program that uses the created class to analyze a beam's behavior under various loads and boundary conditions. Your task is to implement the `BeamAnalysis` cla...
```python import numpy as np class BeamAnalysis: def __init__(self): self.nodes = [] self.elements = [] self.E = None self.I = None self.loads = [] self.supports = [] def add_beam(self, coord, E, I): self.E = E self.I = I # Add beam coord...
magicoder
python
You are tasked with implementing a custom serializer and deserializer for a Python application that handles Jaeger tracing metadata propagation. The provided code snippet includes a method `deserialize_context` and a class `ProfilerRequestContextSerializer` that needs to be extended to support the serialization and des...
```python class ProfilerRequestContextSerializer(RequestContextSerializer): """Serializer and deserializer impl. Serializer and deserializer impl based on Jaeger tracing metadata propagation. For usage check out docs/how-to.md . This is the only impl that is important. """ def serialize_conte...
magicoder
python
You are tasked with creating a function that calculates the total area of a given grid layout. The grid layout is represented as a string, where each character represents a cell in the grid. The grid is defined by the number of rows and columns, and each character in the string represents the type of cell in the corres...
```typescript function calculateTotalArea(gridLayout: string): number { const rows = gridLayout.split('\n').filter(row => row.trim() !== ''); const numRows = rows.length; const numCols = rows[0].length; return numRows * numCols; } // Test the function const gridLayout = "....#.\n..##..\n.#....\n......"; consol...
magicoder
typescript
You are tasked with implementing a simple microservice that reads a configuration file and starts a server based on the configuration. The configuration file is in JSON format and contains the following fields: - `address`: a string representing the IP address and port number to bind the server to (e.g., "127.0.0.1:808...
```rust use std::net::{TcpListener, TcpStream}; use std::io::{Read, Write}; use std::fs::File; use serde::{Serialize, Deserialize}; use std::path::Path; #[derive(Serialize, Deserialize)] struct Pref { address: String, handler: String, } struct Microservice; impl Microservice { fn start_server(address: &s...
magicoder
rust
You are tasked with creating a Python function that calculates the duration between two given times. The function should take two parameters, `start_time` and `end_time`, both in the format "HH:MM" (24-hour format). The function should return a dictionary containing the duration in hours and minutes. Create a function...
```python def calculate_duration(start_time, end_time): start_hour, start_minute = map(int, start_time.split(':')) end_hour, end_minute = map(int, end_time.split(':')) total_start_minutes = start_hour * 60 + start_minute total_end_minutes = end_hour * 60 + end_minute duration_minutes = total_end_m...
magicoder
python
You are tasked with creating a function that analyzes the Angular module configuration and returns the list of imported modules. The Angular module configuration is represented using the `@NgModule` decorator in TypeScript. The function should parse the module configuration and extract the list of imported modules. Th...
```typescript function extractImportedModules(moduleConfig: string): string[] { const importStartIndex = moduleConfig.indexOf('imports: [') + 'imports: ['.length; const importEndIndex = moduleConfig.indexOf(']', importStartIndex); const importsString = moduleConfig.substring(importStartIndex, importEndIndex); c...
magicoder
typescript
You are tasked with implementing a Python class for natural language processing. The class, named `InferenceEngine`, is responsible for processing input data and running inference to predict tags and part-of-speech (POS) for the given input. The class has several methods that need to be implemented. The `InferenceEngi...
```python class InferenceEngine: def __init__(self, logger): self.logger = logger def tokenize(self, data): # Implement tokenization logic here # Example implementation: tokens = data.split() # Split input data into tokens valid_positions = [i for i, token in enumerate(...
magicoder
python
You are tasked with implementing a settings form for a desktop application. The form should allow users to input and save various settings for the application. The form should include text boxes, checkboxes, and buttons for saving and resetting the settings. Your task is to create a class that represents the settings...
```csharp public partial class SettingsForm : Form { private TextBox setting1TextBox; private CheckBox setting2CheckBox; private Button saveButton; private Button resetButton; public SettingsForm() { InitializeComponent(); InitializeControls(); AttachEventHandlers(); ...
magicoder
csharp
You are given a string `num` representing a non-negative integer. Additionally, you are given an integer `target`. Your task is to write a function `addOperators` that takes the string `num` and the integer `target` as input and returns all possible expressions that evaluate to the `target`. The expressions should be f...
```cpp #include <vector> #include <string> using namespace std; class Solution { private: void backtrack(vector<string>& result, string& num, int target, string& expr, long long diff, long long curr, int pos) { if (pos == num.size()) { if (curr == target) { result.push_back(expr...
magicoder
cpp
You are tasked with creating a Python script that automatically generates a version number for a software project. The version number follows the format "major.minor.patch[.dev]", where "major", "minor", and "patch" are integers, and "dev" is an optional development tag. The script should be able to increment the versi...
```python def increment_version(version): parts = version.split('.') if '.dev' in parts[-1]: parts[-1] = str(int(parts[-1].replace('.dev', '')) + 1) + '.dev' else: parts[-1] = str(int(parts[-1]) + 1) + '.dev' return '.'.join(parts) ```
magicoder
python
You are given a code snippet that appears to contain a comment in a non-English language. Your task is to decipher the comment and translate it into English. The comment is written in a language that uses accented characters and may require special handling for proper translation. Write a program that takes the given ...
```python import re from googletrans import Translator # Extract the comment from the code snippet code_snippet = """ SNAKUR1XHNIT(300), // y hnit snáka í eins og tveggja leikmanna útgáfu """ comment = re.search(r'//(.+)', code_snippet).group(1) # Translate the comment into English translator = Translator() t...
magicoder
python
You are tasked with implementing a custom sequence set data structure in Java. The sequence set should support adding elements, removing elements, and checking if a given element is present in the set. Additionally, the sequence set should maintain the order of elements as they are added. Your task is to implement the...
```java import java.util.ArrayList; import java.util.List; public class SequenceSet<T> { private List<T> elements; public SequenceSet() { elements = new ArrayList<>(); } public void add(T element) { if (!elements.contains(element)) { elements.add(element); } } ...
magicoder
java
You are tasked with creating a Python function that processes a list of module objects representing components on a printed circuit board (PCB). Each module object contains information about the component's position, orientation, description, layer, and footprint. Your function should filter out modules based on certai...
```python from typing import List class Module: def __init__(self, position, orientation, description, layer, footprint): self.position = position self.orientation = orientation self.description = description self.layer = layer self.footprint = footprint def filter_modules(...
magicoder
python
You are tasked with implementing the A* algorithm to find the shortest path in a weighted graph. The A* algorithm is an informed search algorithm that uses heuristics to efficiently find the shortest path between two nodes in a graph. You are given a graph represented as an adjacency list and two nodes: the start node...
```python import heapq class Graph: def __init__(self): self.adjacency_list = {} def add_edge(self, u, v, cost): if u not in self.adjacency_list: self.adjacency_list[u] = [] self.adjacency_list[u].append((v, cost)) def heuristic_estimate(node, goal): # Implement the he...
magicoder
python
You are tasked with creating a class to manage student groups in a school system. The class should have the ability to store information about the group, such as the ID of the group leader, the class name, the type of class, and timestamps for creation, update, and deletion. Your task is to create a PHP class called `...
```php class StudentGroup { protected $fillable = ['id_ketua_kelas', 'kelas', 'tipe_kelas', 'created_at', 'updated_at', 'deleted_at']; private $id_ketua_kelas; private $kelas; private $tipe_kelas; private $created_at; private $updated_at; private $deleted_at; public function __construc...
magicoder
php
You are tasked with creating a program to calculate the pay for employees based on their hours worked and hourly rate. The program should prompt the user to input the number of hours worked and the hourly rate, and then calculate the total pay. The pay should be calculated based on the following rules: - If the number ...
```python # Prompt the user to input the number of hours worked and the hourly rate hours_worked = float(input("Enter hours worked: ")) hourly_rate = float(input("Enter hourly rate: ")) # Calculate the pay based on the rules provided if hours_worked <= 40: pay = hours_worked * hourly_rate else: pay = (40 * hou...
magicoder
python
You are working on a project to implement a factor graph representation for a probabilistic graphical model. In this project, you need to create a function that constructs factor graph edges and factor map entries based on given input data. The factor graph represents the relationships between variables and factors in ...
```python def construct_factor_graph(edges, fmap, factor_index, vid, var_map, fmp_index, feature_id, features, variables): def binary_edge(edge_index, factor_index, var1_index, var2_index): # Implementation of binary_edge function is assumed to be provided elsewhere pass edges.append(binary_edg...
magicoder
python
You are tasked with implementing a generic function in Rust that reads data from a given source and performs an operation based on the read data. The function signature is as follows: ```rust pub fn read<W>(&mut self, bytes: W, offset: libc::off_t, event_queue: &mut EventQueue) -> SyscallResult where W: std::io::Write...
```rust pub fn read<W>(&mut self, bytes: W, offset: libc::off_t, event_queue: &mut EventQueue) -> SyscallResult where W: std::io::Write + std::io::Seek { // Perform the read operation based on the type of data source // Example implementation for a file-based data source let mut file = bytes; file.seek(...
magicoder
rust
You are tasked with implementing a simple point-of-sale system for a retail store. The system should be able to display receipts on various output devices. You are given a code snippet that demonstrates the usage of a `display` method on a `device` object. Your task is to create a class representing the `device` and im...
```python # Define an abstract base class for output devices from abc import ABC, abstractmethod class OutputDevice(ABC): @abstractmethod def display(self, content): pass # Implement specific output device classes class Printer(OutputDevice): def display(self, content): for line in content...
magicoder
python
You are tasked with implementing a view management system for a graphical user interface (GUI) library. The system should support the creation, retrieval, and deletion of views, as well as the ability to check if a view exists. Each view is identified by a unique integer ID. You need to implement the following operatio...
```java import java.util.HashMap; import java.util.Map; class ViewManager { private Map<Integer, Boolean> views; public ViewManager() { views = new HashMap<>(); } public void createView(int viewId) { views.putIfAbsent(viewId, true); } public int retrieveView(int viewId) { ...
magicoder
java
You are tasked with implementing a higher-order component (HOC) in a React application. The provided code snippet demonstrates the usage of the `BindComponentProps` HOC to bind the state and dispatch functions to the `Card` component. Your goal is to create a similar HOC that binds the state and dispatch functions to a...
```javascript // BindListProps.js import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; const BindListProps = (mapStateToProps) => (WrappedComponent) => { const mapDispatchToProps = (dispatch) => ({ // Define any action creators that need to be bound to dispatch here // Example:...
magicoder
javascript
You are tasked with implementing a data loading function for a machine learning project. The function is responsible for loading training and testing data from a specified source and returning the data in the form of tuples. Your task is to complete the implementation of the data loading function based on the provided ...
```python import numpy as np def load_data(): ''' :return: (X_train, Y_train), (X_test, Y_test) dtype: ndarry ''' # Load training and testing data from specified sources (e.g., files or databases) # Replace the following placeholders with actual data loading code X_train = np.array([[1, 2, ...
magicoder
python
You are tasked with creating a function that simulates the behavior of a simplified version of the AutoMapper library. The function should take in two parameters: a source object and a destination class, and return a new instance of the destination class populated with the corresponding properties from the source objec...
```javascript function mapObject(source, destinationClass) { const destination = new destinationClass(); for (const key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { destination[key] = source[key]; } } return destination; } ```
magicoder
javascript
You are tasked with implementing a function that parses a given HTML-like code snippet and extracts all the class names from the `className` attributes within the `span` tags. The function should return a list of unique class names found in the code snippet. Write a function `extractClassNames(htmlCode: string): strin...
```typescript function extractClassNames(htmlCode: string): string[] { const classRegex = /className="([^"]*)"/g; const classNames: string[] = []; let match; while ((match = classRegex.exec(htmlCode)) !== null) { const classList = match[1].split(' '); classNames.push(...classList); } return Ar...
magicoder
typescript
You are working on a project that involves optimizing a machine learning model using PyTorch and performing calculations on the trained variables. As part of this project, you need to implement a function that calculates the posterior values based on the optimized trained variances. The posterior is assumed to be Gauss...
```python import torch import numpy as np def calculate_posterior_values(trained_variances, red, red_fft, green, green_fft): # Convert trained variances to torch tensor trained_variance_torch = torch.tensor(trained_variances, dtype=torch.float32) # Calculate posterior values using tpd.tmac_evidence_and_po...
magicoder
python
You are tasked with implementing a job status management system for a distributed computing environment. The system should support various job lifecycle states and allow for custom messages to be associated with state transitions. Your task is to create a class that encapsulates the job status management functionality ...
```python class JobLifeCycle: STOPPED = 'STOPPED' RUNNING = 'RUNNING' COMPLETED = 'COMPLETED' FAILED = 'FAILED' class Job: def __init__(self, initial_status): self.valid_transitions = { JobLifeCycle.STOPPED: {JobLifeCycle.RUNNING}, JobLifeCycle.RUNNING: {JobLifeCycle...
magicoder
python
You are tasked with implementing a class that manages the display of video content based on various criteria. The class has several properties that control the behavior of the video display. Your task is to create a method within the class that filters and returns a specified number of videos based on the given criteri...
```php /** * Class VideoManager */ class VideoManager { /** * @var string Order criteria for video display */ public $order = 'ctr'; /** * @var int Number of videos to display */ public $limit = 20; /** * @var string Time constraint for video display */ public $ti...
magicoder
php
You are tasked with implementing a secure password generator using the provided code snippet as a starting point. The `GetBytes` method uses a `RandomNumberGenerator` to generate a byte array of specified length, which can be used to create strong, cryptographically secure passwords. Your task is to create a password ...
```csharp using System; using System.Security.Cryptography; using System.Text; public class SecurePasswordGenerator { private RandomNumberGenerator rng = RandomNumberGenerator.Create(); public string GeneratePassword(int length) { const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN...
magicoder
csharp
You are tasked with implementing a custom input function for a machine learning prediction model. The model takes in a single image as input and produces a prediction based on that image. The code snippet provided is a part of a Python script for this task. The script first checks the command-line arguments and exits w...
```python def input_fn(image): # Assuming the model expects input in a specific format, such as a NumPy array or a TensorFlow tensor # Convert the processed image to the expected input format # Example: If the model expects input as a NumPy array input_image = image_to_numpy_array(image) # Perf...
magicoder
python
You are tasked with implementing a Tiramisu code that performs matrix multiplication. Tiramisu is a domain-specific language for expressing fast and portable data parallel computations. The code snippet provided includes the necessary Tiramisu headers and libraries. Your task is to write a Tiramisu program that multip...
```c #include <tiramisu/core.h> #include <tiramisu/debug.h> #include <tiramisu/tiramisu.h> int main(int argc, char* argv[]) { const int M = 10; const int K = 5; const int N = 8; // Declare Tiramisu function tiramisu::init("matrix_multiplication"); // Declare input and output buffers tiram...
magicoder
c
You are tasked with creating a Python function that simulates a simple game of dice rolling. The function should take in the number of dice to roll and the number of times to roll them. It should then simulate the rolling of the specified number of dice the specified number of times and return the frequency of each pos...
```python import random def simulate_dice_rolling(num_dice: int, num_rolls: int) -> dict: frequencies = {i: 0 for i in range(num_dice, num_dice * 6 + 1)} # Initialize frequencies for possible outcomes for _ in range(num_rolls): outcome = sum(random.randint(1, 6) for _ in range(num_dice)) # Simulate r...
magicoder
python
You are given a Python function `maxlinedev(x, y)` that takes in two arrays `x` and `y` representing the x and y coordinates of points on a 2D plane. The function is intended to calculate the maximum deviation of a contour formed by these points and return the maximum deviation and the index of the point with the maxim...
```python from typing import Tuple import math def maxlinedev(x, y) -> Tuple[float, int]: # Number of points is the size of the input array. num_pts = len(x) # Check whether array has enough points to form a contour. if num_pts == 1: maxdev = 0 index_max = 1 dist_contour = 1 ...
magicoder
python
You are tasked with creating a Python program to process a CSV file containing information about gene regulatory binding sites. The program should read in the CSV file, perform some data manipulation, and then generate output figures based on the processed data. The CSV file, named 'RegulonDB_20170630_BindingSiteSet.c...
```python import pandas as pd import os import matplotlib.pyplot as plt # Load in the summary csv file df = pd.read_csv('RegulonDB_20170630_BindingSiteSet.csv', comment='#') # Perform data manipulation to extract relevant information # For example, let's say we want to create a figure showing the distribution of bind...
magicoder
python
You are tasked with creating a function that generates a report for a user based on their urbanism and neighbors' properties. The function should retrieve the necessary data and format it for display in a view. The provided code snippet is a part of a Laravel application and contains some relevant context for the probl...
```php public function GeneraReportePagos() { $user_id = Auth::user()->id; // Step 1: Retrieve user's ID ini_set('max_execution_time', 900000); // Step 2: Set maximum execution time // Step 3: Retrieve the urbanism ID associated with the user $idurbanismo = Neighbors::where('user_id', '=', $user_id)->f...
magicoder
php
You are working on a project that involves implementing a graph-based algorithm. As part of this project, you need to create a method to update tabu edges in a graph. Tabu edges are pairs of vertices that are temporarily forbidden from being included in a solution. Your task is to implement a function that takes a list...
```python from typing import List, Tuple def update_tabu_edges( idx_group: List[int], tabu_edges: List[Tuple[int, int]], tabu_idx_group: bool, ) -> List[Tuple[int, int]]: if tabu_idx_group: updated_tabu_edges = tabu_edges + [(idx_group[i], idx_group[i+1]) for i in range(len(idx_group)-1)] e...
magicoder
python
You are tasked with creating a custom module for a NestJS application that integrates with an AMQP (Advanced Message Queuing Protocol) system. Your goal is to implement the necessary functionality to establish a connection to an AMQP server and manage its lifecycle within the NestJS application. Your task is to comple...
```typescript import { DiscoveryModule } from '@golevelup/nestjs-discovery'; import { ModuleRef } from '@nestjs/core'; import { DynamicModule, Global, Module, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import { AMQPContainer } from './amqp.container'; import { AMQPExplorer } from './amqp.explorer'; import {...
magicoder
typescript
You are tasked with implementing a Python class for image deblurring using various loss functions and a learning rate scheduler. The class should be able to initialize with given options and perform the necessary operations for image deblurring. Your task is to complete the `ImageDeblur` class by implementing the foll...
```python from models.losses.perceptual_loss import PerceptualLoss from models.losses.ssim_loss import SSIM from torch.optim.lr_scheduler import StepLR from tqdm import tqdm class ImageDeblur: def __init__(self, opt): self.opt = opt self.perceptual_loss = None self.ssim_loss = None ...
magicoder
python
You are tasked with creating a program that analyzes the frequency of words in a given text file. Your program should read a text file and output the top N most frequently occurring words along with their respective counts. For the purpose of this problem, a word is defined as a sequence of alphanumeric characters sepa...
```python import re from collections import Counter def analyze_word_frequency(file_path, N): # Read the text file with open(file_path, 'r') as file: text = file.read().lower() # Convert text to lowercase # Tokenize the text into words words = re.findall(r'\b\w+\b', text) # Exclude stop ...
magicoder
python
You are tasked with implementing a function that calculates the intersection area of two rectangles in a 2D plane. The rectangles are defined by their top-left and bottom-right coordinates. The function should take in the coordinates of the two rectangles and return the area of their intersection. You are given the fo...
```java public double calculateIntersectionArea(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { double x_overlap = Math.max(0, Math.min(x2, x4) - Math.max(x1, x3)); double y_overlap = Math.max(0, Math.min(y2, y4) - Math.max(y1, y3)); return x_overlap * y_overlap; } ...
magicoder
java
You are working on a Python project that involves symbolic mathematics using the SageMath library. While importing the necessary modules, you encounter a code snippet that uses the `lazy_import` function. This function is used to import modules only when they are first accessed, which can help reduce startup time and m...
```python import importlib import warnings def simulate_lazy_import(module_name, symbol, deprecation=None): def lazy_import_wrapper(): module = importlib.import_module(module_name) globals()[symbol] = module if deprecation: warnings.warn(f"{module_name} is deprecated as of vers...
magicoder
python
You are tasked with implementing a custom drop connect layer in TensorFlow for a neural network model. The drop connect layer is a variation of the dropout technique, where instead of dropping individual neuron outputs, it drops entire connections between neurons and their subsequent layers. This helps in regularizing ...
```python import tensorflow as tf class DropConnectDense(tf.keras.layers.Layer): def __init__(self, units, drop_connect_prob=0.5): super(DropConnectDense, self).__init__() self.units = units self.drop_connect_prob = drop_connect_prob def build(self, input_shape): self.kernel = ...
magicoder
python
You are tasked with implementing a priority queue using a min-heap data structure. A priority queue is an abstract data type that operates similar to a regular queue or stack, but where each element has a priority associated with it. In a min-heap priority queue, the element with the smallest priority value should be d...
```javascript class PriorityQueue { constructor() { this.heap = []; } enqueue(value, priority) { const node = { value, priority }; this.heap.push(node); this.bubbleUp(this.heap.length - 1); } dequeue() { if (this.isEmpty()) { throw new Error('Priority queue is empty'); } co...
magicoder
javascript
You are tasked with creating a Python function that simulates the behavior of the `shutil.which` function for Python versions earlier than 3.3. The `shutil.which` function is used to locate a program in the system's PATH. Your function should take the name of a program as input and return the full path to the program i...
```python import os import stat import sys def which(program): def is_executable_file(path): return os.path.isfile(path) and os.access(path, os.X_OK) def search_path(program): path_dirs = os.environ["PATH"].split(os.pathsep) for path_dir in path_dirs: exe_file = os.path.joi...
magicoder
python
You are given two strings, A and B, each consisting of lowercase English letters. Your task is to find the minimum number of operations required to make the two strings equal. The allowed operations are insertion, deletion, or substitution of a single character. The cost of each operation is 1. You need to implement a ...
```python def minOperations(A, B): m, n = len(A), len(B) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: dp[i][j] = i + j elif A[i - 1] == B[j - 1]: dp[i][j] = dp[i - 1][j - 1] ...
magicoder
python
You are tasked with creating a word guessing game in Python. The game will involve a player guessing letters in a word, with a limited number of attempts. The code snippet provided is a part of the main game loop, handling exceptions and updating the game state. The game has the following components: - The word to be ...
```python def check_same(guess, output): if guess == output: print("You already guessed that!") return output def check_letter(guess, word, tries): if len(guess) == 1 and guess.isalpha(): if guess in word: print("Good guess!") for i in range(len(word)): ...
magicoder
python
You are tasked with creating a Python script that monitors the availability of a Plex media server and sends an alert if the server becomes unreachable. The script should use the `plexapi` library to connect to the Plex server and periodically check its availability. If the server is not reachable, the script should se...
```python import smtplib from email.message import EmailMessage from configparser import ConfigParser from plexapi.server import PlexServer import schedule import time # Read configuration settings from config.ini config = ConfigParser() config.read('config.ini') plex_server_url = config.get('Settings', 'plex_server_u...
magicoder
python
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. Your program should read the text file, tokenize the words, and then count the occurrences of each word. Additionally, the program should ignore any words listed in a provided set of stop words. The stop w...
```python def word_count_analysis(file_path, stop_words): word_counts = {} with open(file_path, 'r') as file: text = file.read().lower() words = text.split() for word in words: word = word.strip('.,!?"\'').lower() if word not in stop_words: if word...
magicoder
python
You are tasked with implementing a function that converts a given set of coordinates to Well-Known Binary (WKB) format. Well-Known Binary is a binary representation of geometry data, commonly used in geographic information systems (GIS). The WKB format consists of a header byte indicating the geometry type, followed by...
```cpp #include <vector> #include <cstdint> // Define the Point struct to represent coordinates struct Point { double x; double y; }; // Define the WKB struct to represent Well-Known Binary format struct WKB { uint8_t headerByte; std::vector<uint8_t> binaryData; }; // Function to convert coordinates ...
magicoder
cpp
You are tasked with creating a Python function that parses a list of URL patterns and returns a dictionary mapping the URL patterns to their corresponding view functions. Each URL pattern is represented as a string, and the view function is represented as a string as well. You are given a list of URL patterns in the f...
```python import re def parse_url_patterns(url_patterns): pattern_function_map = {} for pattern in url_patterns: match = re.search(r"url\((.*?)\)", pattern) if match: url_pattern = match.group(1) view_function = pattern.split("include('")[1].split("')")[0] pa...
magicoder
python
You are tasked with implementing a Python class that simulates a simple text comparison tool. The class should provide a method to compare two strings and identify the differences between them. Your task is to complete the implementation of the `TextComparator` class by adding the `compare` method. The `TextComparator...
```python class TextComparator: def __init__(self, text): self.text = text def compare(self, other_text): original_lines = self.text.split('\n') other_lines = other_text.split('\n') for line in original_lines: if line not in other_lines: print(f"-{li...
magicoder
python
You are tasked with creating a Python class that generates random instances of various data structures and provides methods for comparing and converting these instances. Your task is to implement the `RandomDataGenerator` class with the following requirements: 1. The class should have a method `generate_random` that t...
```python import numpy as np class RandomDataGenerator: @staticmethod def generate_random(size): return np.random.rand(*size) @staticmethod def compare_instances(instance1, instance2): return np.array_equal(instance1, instance2) @staticmethod def convert_to_bytes(instance): ...
magicoder
python
You are tasked with designing a reservation system for a university's lecture rooms. The system should allow students to reserve a room for a specific course at a given time. The provided code snippet is a part of the backend logic for checking and handling reservations. The code snippet is a Python script that intera...
```python import sqlite3 def check_reservation(codice: str, start: str, username: str) -> bool: con = sqlite3.connect('reservation_database.db') # Connect to the database cur = con.cursor() # Execute the SQL query to check for reservations query = "SELECT * FROM `mrbs_entry` E JOIN `mrbs_room` R ON E...
magicoder
python
You are tasked with implementing a function that extracts values from a database source based on a given expression. The database source is represented by the `source` parameter, which is an `Option` containing a reference to a `Source` object. The `Source` object has a lifetime parameter `'b` and its associated type `...
```rust fn extract_value<'b, Storage>( expr: &SExpression<'b>, source: Option<&Source<'b, <Storage::Info as DatabaseInfo>::ColumnValue>>, ) -> Result<<Storage::Info as DatabaseInfo>::ColumnValue, ExecuteError> { match expr { &SExpression::Value(ref v) => Ok(v.clone()), &SExpression::ColumnFi...
magicoder
rust
You are tasked with implementing a generic ZipFileFilter class that filters a list of FileResource objects based on certain criteria. The provided code snippet includes a method to set the file resources and a method to retrieve the file resources, along with the use of the @JsonIgnore annotation. Your task is to crea...
```java import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.ArrayList; import java.util.List; public class ZipFileFilter { private List<FileResource> fileResources; public ZipFileFilter() { this.fileResources = new ArrayList<>(); } @JsonIgnore public List<FileResource> ge...
magicoder
java
You are tasked with creating a function that validates whether a given string is a valid JSON object or not. You need to implement the `IsJsonString` function in the programming language of your choice. The function should return `true` if the input string is a valid JSON object and `false` otherwise. The `IsJsonStrin...
```javascript function IsJsonString(data) { try { JSON.parse(data); return true; } catch (error) { return false; } } ``` The `IsJsonString` function takes a string `data` as input and attempts to parse it using `JSON.parse`. If the parsing is successful, it returns `true`, indicatin...
magicoder
javascript
You are tasked with implementing a custom serializer for a blog post model in a Python Django application. The `Post` model has the following fields: `title` (string), `content` (text), `author` (foreign key to the User model), and `created_at` (datetime). Your goal is to create a custom serializer class `PostSerialize...
```python from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): author = serializers.SerializerMethodField() def get_author(self, post): return post.author.username class Meta: model = Post fields = ['id', 'title', 'cont...
magicoder
python
You are working on a natural language processing (NLP) project and need to implement a function to create a padding mask for sequences. The input sequences are represented as batched tensors, and you are required to create a mask that identifies the padded positions in each sequence. You are given the following code s...
```python import torch def create_padding_mask(x: torch.Tensor, PAD_TOKEN_INDEX: int, target_len: int) -> torch.Tensor: padded_positions = x == PAD_TOKEN_INDEX pad_mask = padded_positions.unsqueeze(1).expand(x.size(0), target_len, x.size(1)) return pad_mask ```
magicoder
python
You are tasked with implementing a property wrapper for UserDefaults in Swift. The property wrapper should provide a way to store and retrieve values from UserDefaults with a specified key and default value. Additionally, it should support clearing the stored value. Your task is to create a `UserDefaultsBacked` proper...
```swift import XCTest // Define a protocol for types that can be stored in UserDefaults protocol UserDefaultsCompatible { associatedtype UserDefaultsValueType var userDefaultsValue: UserDefaultsValueType { get } init?(userDefaultsValue: UserDefaultsValueType) } // Implement the UserDefaultsCompatible pro...
magicoder
swift
You are tasked with implementing a simplified version of the Gilded Rose inventory management system. The system manages the inventory of various types of items, each with its own set of rules for quality and sell-in date updates. Your goal is to write a program that updates the quality and sell-in date of each item in...
```swift class GildedRose { var items: [Item] init(items: [Item]) { self.items = items } func updateQuality() { for item in items { switch item.name { case "Aged Brie": if item.quality < 50 { item.quality += 1 ...
magicoder
swift
You are tasked with simulating a Poisson population of neurons to generate spike trains for a neuroscience research project. The goal is to create a Python function that simulates the firing activity of a population of neurons based on a Poisson process. The function should take into account the simulation time, sampli...
```python import numpy as np def sim_poisson_pop(n_seconds, fs, n_neurons=1000, firing_rate=2): spike_trains = [] for _ in range(n_neurons): spike_train = [] t = 0 while t < n_seconds: dt = np.random.exponential(1 / firing_rate) t += dt if t < n_secon...
magicoder
python
You are tasked with creating a script to monitor the status of a Selenium server using the `curl` command and a success command defined by the `SUCESS_CMD` variable. The script should continuously check the status of the Selenium server until the success condition is met, and then stop and display the final status. Gi...
```python import requests import json import time SEL_STATUS_URL = "http://selenium-server/status" # Replace with the actual Selenium server status URL # Define the success condition based on Selenium version # For Selenium <= 3.3.1, the success condition is when the status equals 13 # For Selenium >= 3.5.0, the suc...
magicoder
python
You are tasked with implementing a URL shortening service. Your goal is to create a function that takes an original URL as input and returns a shortened version of the URL. The shortened URL should be unique and should be generated using a combination of alphanumeric characters. Additionally, you need to implement a fu...
```python import string import random class URLShortener: def __init__(self): self.url_map = {} self.chars = string.ascii_letters + string.digits def shorten_url(self, original_url): if original_url in self.url_map: return self.url_map[original_url] else: ...
magicoder
python
You are given a text file containing a software license agreement. Your task is to write a program that reads the file and extracts the total count of words in the agreement, as well as the frequency of each unique word. For the purpose of this problem, a word is defined as any sequence of characters separated by white...
```python def analyze_license_agreement(file_path: str) -> dict: word_frequency = {} total_word_count = 0 with open(file_path, 'r') as file: content = file.read() words = content.split() for word in words: total_word_count += 1 word_frequency[word] = word_fr...
magicoder
python
You are tasked with creating a custom feature configuration for a Minecraft mod. The feature configuration will define the properties of a new world feature that will be generated in the game world. Your task is to implement the feature configuration class using the provided code snippet as a reference. The code snipp...
```java package com.dayofpi.super_block_world.world.feature.utility.feature_config; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.codecs.RecordCodecBuilder.Instance; import net.minecraft.util...
magicoder
java
You are tasked with creating a PHP class that manages a library of books. The class should have methods to add a new book, retrieve book details by ID, and display all books in the library. You are provided with a partial implementation of the `BookController` class in Laravel framework. Your task is to complete the cl...
```php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Book; class BookController extends Controller { public function index($id=null){ if($id){ $book_details=Book::findOrFail($id); }else{ $book_details=[]; } } public func...
magicoder
php
You are given a partial implementation of a class `Rotatable` in C++ that is designed to identify rotatable variables in a Boolean satisfiability problem. The class takes a CNF (Conjunctive Normal Form) as input and is responsible for identifying the rotatable variables based on a given model. The `Rotatable` class ha...
```cpp void Rotatable::get_rotatables(const vec<lbool>& model, VarSet& rotatables) { for (Var index = 1; index < model.size(); ++index) { // Check if flipping the variable affects the satisfiability CNF modified_cnf = input_cnf; // Create a copy of the original CNF modified_cnf[index].clear(); // Remo...
magicoder
cpp
You are tasked with implementing a function to calculate the sum of all prime numbers within a given range. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your function should take two integers, `start` and `end`, as input and return the sum of all prime numbers...
```python def is_prime(num): if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True def sum_of_primes(start, end): prime_sum = 0 for num in range(max(2, start), end + 1): if is_prime(num): prime_sum ...
magicoder
python
You are tasked with creating a program that reads a file containing copyright information and extracts the year(s) mentioned in the copyright notice. The copyright notice is a comment block in the file, and the years are mentioned in the format "YYYY". Your program should then output the distinct years mentioned in the...
```python import re def extract_copyright_years(filename): with open(filename, 'r') as file: content = file.read() years = re.findall(r'\b\d{4}\b', content) distinct_years = sorted(set(years)) return distinct_years filename = 'copyright_notice.txt' # Replace with the actual filena...
magicoder
python
You are tasked with creating a program to perform Vigenère cipher encryption and decryption. The Vigenère cipher is a method of encrypting alphabetic text by using a simple form of polyalphabetic substitution. It uses a keyword to shift the letters in the plaintext to produce the ciphertext. The encryption and decrypti...
```python def vigenere_encrypt(plaintext, key): alphabet = 'abcdefghijklmnopqrstuvwxyz' ciphertext = '' key = key.lower() text_count = 0 key_count = 0 for char in plaintext: if char.isalpha(): if char.isupper(): shift = (alphabet.index(key[key_count % len(key)...
magicoder
python
You are tasked with creating a program to update SKUs (Stock Keeping Units) in an e-commerce system. The program will read SKU data from a file and update the corresponding records in the system using asynchronous requests to a remote server. The program must handle concurrent requests and enforce a rate limit to avoid...
```rust use std::error::Error; use std::num::NonZeroU32; use reqwest::Client; use tokio::time::{sleep, Duration}; pub async fn update_skus( file_path: String, client: &Client, account_name: String, environment: String, concurrent_requests: usize, rate_limit: NonZeroU32, ) -> Result<(), Box<dyn ...
magicoder
rust
You are tasked with creating a Python function that interacts with an API to retrieve information about coding challenges and their rewards. The function should take in two parameters: `url` and `headers`. The `url` parameter specifies the type of reward to retrieve, and the `headers` parameter contains the headers req...
```python import requests def retrieve_challenge_rewards(url: str, headers: dict) -> dict: valid_urls = {'prize', 'points', 'knowledge', 'all'} if url not in valid_urls: return {'error': 'Invalid URL parameter. Please provide a valid URL: prize, points, knowledge, or all.'} api_endpoint =...
magicoder
python
You are tasked with implementing a PolynomialPredictor class that can predict future values in a time series using polynomial regression. The PolynomialPredictor class takes in a time series of values and the number of periods to predict into the future. The predict_counts() method of the PolynomialPredictor class shou...
```python import numpy as np from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression class PolynomialPredictor: def __init__(self, time_series, num_predicted_periods): self.time_series = time_series self.num_predicted_periods = num_predicted_periods ...
magicoder
python
You are tasked with creating a React component that handles search functionality. The component should include a search input field and should be able to pass the search results and any errors to its parent component. You are given a code snippet that represents part of the React component. The component is enclosed w...
```jsx import React, { useState } from 'react'; const SearchComponent = (props) => { const [searchTerm, setSearchTerm] = useState(''); const [searchResults, setSearchResults] = useState([]); const [error, setError] = useState(null); const handleSearch = () => { // Perform the search operation using the se...
magicoder
jsx
You are tasked with implementing a payment processing system that involves presenting additional payment details using plugins. The system has a `PaymentDetailPresenter` class with a method `show` that takes additional payment details, a plugin, and a completion handler as parameters. The plugin is responsible for pres...
```swift class PaymentDetailPresenter { weak var navigationController: UINavigationController? internal func show(_ details: AdditionalPaymentDetails, using plugin: AdditionalPaymentDetailsPlugin, completion: @escaping Completion<[PaymentDetail]>) { guard let navigationController = navigationContro...
magicoder
swift
You are tasked with creating a web application for a laundry service company. The company offers various features accessible through a navigation menu. The code snippet provided is a part of the HTML code for the navigation menu. Each list item (`<li>`) represents a feature with a corresponding link and icon. The links...
```python from typing import List, Dict import re def extract_features(html_code: str) -> List[Dict[str, str]]: features = [] pattern = r'<li><a href="(.+?)".*?>(?:<img src="(.+?)".*?>|<i class="(.+?)"></i>)?\s*<span>(.+?)</span></a></li>' matches = re.findall(pattern, html_code) for match in matc...
magicoder
python
You are tasked with implementing a class that represents a frequency range. The class should have methods to set the lower and upper bounds of the frequency range in hertz. Additionally, it should provide a method to check if a given frequency is within the defined range. You are provided with a partial code snippet f...
```java public class FrequencyRange { private double freqLowBound = 110; private double freqHighBound; /** * Ustawia górną (przybliżoną) granicę częstotliwości w hercach. * @param upperBound górna granica częstotliwości */ public void setUpperBound(double upperBound) { freqHighBo...
magicoder
java
You are working with genomic data and need to manipulate BAM files using the Samtools software. Samtools is a suite of programs for interacting with high-throughput sequencing data. One of the tasks involved in this process is to filter out reads with the 0x400 flag and create a new BAM file from the original one. Afte...
```bash #!/bin/bash # Check if input BAM file is provided if [ -z "$1" ]; then echo "Usage: $0 <input_bam_file>" exit 1 fi # Load Samtools module module load samtools/1.10-foss-2018b # Filter out reads with the 0x400 flag and create a new BAM file input_bam="$1" output_bam="${input_bam%.*}_noDup_BQSR.bam" samtoo...
magicoder
shell
You are tasked with implementing a deep copy method for a custom class in Python. The class has various attributes, including primitive data types, lists, and other objects. Your task is to create a `copy` method within the class that returns a deep copy of the object, ensuring that all attributes and nested objects ar...
```python import copy class CustomClass: def __init__(self, name, age, hobbies, address): self.name = name self.age = age self.hobbies = hobbies self.address = address def copy(self): return CustomClass( self.name, self.age, copy.deep...
magicoder
python
You are tasked with creating a Rust macro that generates a set of HTTP route handlers for a web server framework. The macro should take in a list of keywords and generate corresponding route handler functions for each keyword. Each route handler function should have a specific behavior based on the keyword it is associ...
```rust macro_rules! generate_route_handlers { ($($keyword:ident),*) => { $( fn $keyword_handler(req: Request) -> Response { match req.method() { "POST" => { // Perform specific actions for the $keyword on POST request ...
magicoder
rust
You are tasked with creating a PHP class method that performs various actions based on the user and product provided as parameters. Your task is to complete the `actions` method in the given PHP class. The method should perform the following actions based on the user and product: 1. If the user is an admin and the pro...
```php class ProductActions { /** * @param User $user * @param Product $product * @return mixed * @throws Exception */ public function actions(User $user, Product $product) { if ($user->isAdmin() && $product->isActive()) { return $product->getDetails(); }...
magicoder
php
You are tasked with implementing a function that processes a two-dimensional array and performs operations based on the input parameters. The function takes in an array of arrays and a parameter that determines the type of operation to be performed. The array of arrays represents a table with rows and columns, and the ...
```php function processArray(array $rows, $columns): array { if (is_string($columns)) { $columnIndex = (int)$columns; $result = array_column($rows, $columnIndex); } elseif (is_array($columns)) { $result = []; foreach ($rows as $row) { $key = ''; foreach ($...
magicoder
php
You are tasked with creating a program that calculates the sum of all prime numbers up to a given integer `n`. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your program should take an integer `n` as input and output the sum of all prime numbers less than or eq...
```python def is_prime(num): if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True def sum_of_primes(n): prime_sum = 0 for num in range(2, n + 1): if is_prime(num): prime_sum += num return prime...
magicoder
python
You are given a Python function that processes a game matrix and returns a solution. Your task is to understand the function and implement a similar function in another programming language. The function `offdiag_refill` takes four parameters: `run`, `names`, `queue`, and an optional parameter `count`. The `run` param...
```python # Example solution in Python import json import numpy as np def offdiag_refill(run, names, queue, count=1): n = (json.symmetric_games(run) .reindex(index=names, columns=names) .fillna(0)) # Implement the rest of the function logic here # ... return activelo.solve(n....
magicoder
python
You are tasked with creating a Python function that processes data from a CSV file and generates a graph using the Plotly library. The function, `graph_difficulties`, takes two optional boolean parameters: `is_by_height` and `show`. The function reads data from a CSV file, creates a Plotly figure, and adds a scatter pl...
```python import pandas as pd import plotly.graph_objects as go def graph_difficulties(is_by_height: bool = False, show: bool = False): difficulties_filename = "path_to_difficulties.csv" # Replace with the actual path to the CSV file df = pd.read_csv(difficulties_filename) fig = go.Figure() if i...
magicoder
python