query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a command-line tool for managing instances of a board application. The code snippet provided is part of a method that refreshes an instance by clearing its data pool. The `refreshInstance` method is part of a class that extends a base command class and is responsible for handling variou...
```php class ClearBoardInstanceDataPoolCommand { private $instance; public function setInstance(Instance $instance) { $this->instance = $instance; } public function execute() { // Logic to clear the data pool of the specified board instance // This could involve interac...
magicoder
php
You are tasked with creating a script to automate the setup and initialization of a local network of nodes for a blockchain application. The script should generate configuration files for a specified number of nodes and start each node using the generated configuration. The script should perform the following steps: 1...
```bash #!/bin/bash # Define the path to the script for generating configuration files pathToOtNode="/path/to/otNode" # Define the number of nodes to be set up numberOfNodes=5 echo "==============================" echo "====== Generating configs ====" echo "==============================" # Generate configuration f...
magicoder
shell
You are tasked with creating a function to determine whether a given integer password meets specific criteria. The function should check if the password satisfies the following conditions: 1. It is a six-digit number. 2. It contains at least two adjacent digits that are the same. 3. The digits never decrease from left ...
```python def valid_password(password): password_str = str(password) # Check if it is a six-digit number if len(password_str) != 6: return False # Check for adjacent digits and non-decreasing order has_adjacent = False for i in range(5): if password_str[i] == password_s...
magicoder
python
You are tasked with creating a Django REST framework view that allows users to search for item transfers based on specific fields. The `ItemTransfer` model represents the transfer of items from one location to another within a system. The `ItemTransferSerializer` is used to serialize the `ItemTransfer` model for API re...
```python from rest_framework import generics from rest_framework import filters from .models import ItemTransfer from .serializers import ItemTransferSerializer class ItemTransferSearchView(generics.ListAPIView): queryset = ItemTransfer.objects.all() serializer_class = ItemTransferSerializer filter_backen...
magicoder
python
You are tasked with implementing a clocked flip-flop using the provided trait `Clocked`. The `Clocked` trait defines methods for handling rising and falling edges of a clock signal. Your goal is to create a specific implementation of this trait for a D flip-flop, a fundamental building block in digital circuit design. ...
```rust // Define a struct for the D flip-flop pub struct DFlipFlop { q: bool, // Current state } // Implement the ClockState trait for boolean values pub trait ClockState: Copy {} impl ClockState for bool {} // Implement the Clocked trait for the D flip-flop impl Clocked<bool, bool> for DFlipFlop { fn rising...
magicoder
rust
You are tasked with implementing a function to merge properties from multiple objects into a single object. The function should handle nested objects and arrays, and should also support mixins and extensions. You are given a code snippet that includes a partial implementation of the `mergeProps` function. The function...
```javascript function mergeProps(to, from, optionsType = 'props') { const { mixins, extends: extendsOptions, ...otherProps } = from; // Merge otherProps into to Object.keys(otherProps).forEach((prop) => { if (typeof otherProps[prop] === 'object' && otherProps[prop] !== null) { if (Array.isArray(otherP...
magicoder
javascript
You are tasked with creating a Python class that simulates a simple file server using TCP/IP sockets. Your task is to implement a class called `GPFDistServer` that extends the `SocketServer.ThreadingTCPServer` class. The `GPFDistServer` class should handle incoming connections and distribute files to clients upon reque...
```python import SocketServer import os class GPFDistServer(SocketServer.ThreadingTCPServer): def __init__(self, server_address, RequestHandlerClass): SocketServer.ThreadingTCPServer.__init__(self, server_address, RequestHandlerClass) class GPFDistRequestHandler(SocketServer.StreamRequestHandler): def...
magicoder
python
You are tasked with implementing a Python class that can parse a report and store the parsed data. The class should have a method called `parse` that takes a report and stores the parsed data in a variable called `issued`. The `parse` method should be implemented to handle the parsing of the report and store the releva...
```python class ReportParser: def __init__(self): self.issued = [] def parse(self, report): entries = report.strip().split('\n\n') # Split the report into individual entries parsed_entries = [] for entry in entries: lines = entry.strip().split('\n') # Split each en...
magicoder
python
You are tasked with creating a Swift function that retrieves details of a game item from the Blizzard API. The function should handle asynchronous completion and error handling. You are given the following code snippet as a starting point: ```swift func getItemDetails(item: SCEquipmentItem, completion:@escaping (_ di...
```swift func getItemDetails(item: SCEquipmentItem, completion:@escaping (_ dict: [String: Any]?,_ isSuccess: Bool)->()){ guard let region = UserDefaults.standard.object(forKey: "region") as? String, let slug = item.slug, let id = item.id else{ completion(nil,false) return }...
magicoder
swift
You are working on a real estate data processing system that involves joining, filtering, and repairing data. The system uses Python and various custom functions and libraries for data manipulation. Your task is to implement a function that repairs data by referencing an inner dataset and an outer dataset. You are giv...
```python import pandas as pd def repair_with_reference(joined_data, reference_datasets, datasets_composition, data_context_columns, target_schema, repaired_columns): # Reference dataset selection based on data context columns reference_dataset = None for dataset in datasets_composition: if all(col...
magicoder
python
You are tasked with creating a command-line tool to manage a project named "xroad-drive-demo". The tool should support various operations related to this project, such as creating, updating, and deleting project files, as well as performing other project management tasks. Your task is to implement the functionality to ...
```python import os import sys def create_file(file_name): try: with open(file_name, 'w'): pass print(f"File '{file_name}' created successfully.") except OSError as e: print(f"Error creating file '{file_name}': {e}") def update_file(file_name): if os.path.exists(file_na...
magicoder
python
You are given a set of vertices representing points on the Earth's surface. Each vertex is represented by its coordinates in a three-dimensional space. Your task is to implement a function that identifies the vertices on the equator that are in the opposite hemisphere to another set of vertices based on a given distanc...
```python import numpy as np def opposite_hemisphere_vertices(vertices, dist_thresh=None): equator_vertices = [v for v in vertices if v[2] == 0] # Select vertices on the equator (z=0) if dist_thresh is None: dist_thresh = np.finfo(float).eps # Use default threshold based on input data type oppo...
magicoder
python
You are given a code snippet from an assembly language program. Your task is to understand the code and write a function that simulates its behavior. The code snippet performs bitwise operations and conditional checks. The variable `cc` is a 16-bit integer representing a condition code, and `ctx` is an object providin...
```python def evaluate_condition_code(cc, ctx): cb = (cc >> 1) & 0b111 if cb == 0b111: cond = imm(1, 8) # Set cond to immediate value 1 with width 8 bits else: cond = ctx.tmp(8) # Set cond to temporary value stored in the context with width 8 bits if cb == 0b000: ctx.emit...
magicoder
python
You are tasked with implementing a class to manage the state of a network connection in a messaging system. The provided code snippet outlines a partial definition of the `ConnectionState` class, which is responsible for managing the state of the connection. Your task is to complete the implementation of the `Connectio...
```cpp #include <string> enum class ConnectionState_t { CONNECTED, DISCONNECTED, RECONNECTING }; struct AmqpVersion { int major; int minor; }; class ConnectionState { public: ConnectionState(const std::string& name) : name_(name), closeReceived_(false), closeSent_(false) {} virtual ~Conn...
magicoder
cpp
You are tasked with creating a Python class that implements a simple version of a boosting algorithm for regression. The boosting algorithm will be used to predict housing prices based on various features. Your task is to complete the implementation of the `BitBoostRegressor` class by adding the functionality to train ...
```python import numpy as np class BitBoostRegressor: def __init__(self): self.objective = None self.models = [] def fit(self, X, y, n_estimators=100, learning_rate=0.1): if self.objective == "l2": loss_function = lambda y_true, y_pred: (y_true - y_pred) ** 2 elif s...
magicoder
python
You are tasked with designing a database schema for a system that tracks violations and the users who report them. The schema should include tables for violations, users, and a table to track the relationship between violations and the users who report them. Additionally, you need to create foreign key constraints to m...
```sql -- Create the violations table CREATE TABLE violations ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY ); -- Create the users table CREATE TABLE users ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY ); -- Create the violation_reports table with foreign key constraints CREATE TABLE violation_reports ( id ...
magicoder
sql
You are tasked with implementing a TypedColumnProcessor class that retrieves the template parameter of the columns in a table. The table is obtained from a StorageManager using the _target_table_name. Your goal is to create a TypedColumnProcessor class that can process the columns of the table and retrieve their templa...
```cpp #include <iostream> #include <string> #include <vector> // Assume the StorageManager and Table classes are defined elsewhere class StorageManager { public: static StorageManager& get() { static StorageManager instance; return instance; } Table get_table(const std::string& table_name...
magicoder
cpp
You are working on a computer vision project and need to implement a custom convolutional neural network (CNN) architecture. As part of this task, you are required to create a specific block within the CNN architecture. The block is defined by the following code snippet: ```python self.shortcut = nn.Sequential( nn...
```python import torch.nn as nn class CustomBlock(nn.Module): def __init__(self, in_channels, out_channels, stride): super(CustomBlock, self).__init__() self.shortcut = nn.Sequential( nn.Conv2d(in_channels, in_channels, 3, stride=stride, padding=1, groups=in_channels), nn.Ba...
magicoder
python
You are tasked with implementing a custom hash table data structure in C++. The hash table will use open addressing with linear probing for collision resolution. You need to implement the destructor and the assignment operator for the `ClpHashValue` class, which is responsible for managing the hash table's values. The...
```cpp // Destructor implementation ClpHashValue::~ClpHashValue() { delete[] hash_; } // Assignment operator implementation ClpHashValue& ClpHashValue::operator=(const ClpHashValue& other) { if (this != &other) { // self-assignment check // Deallocate existing memory delete[] hash_; /...
magicoder
cpp
You are tasked with creating a Python program that simulates a simple game of "Guess the Number." The program should generate a random number between 1 and 100, and then prompt the user to guess the number. After each guess, the program should provide feedback on whether the guess was too high, too low, or correct. The...
```python import random import time def guess_the_number(): number_to_guess = random.randint(1, 100) start_time = time.time() while True: if time.time() - start_time > 60: print("Time's up! You took too long to guess.") break user_guess = input("Guess the number (b...
magicoder
python
You are tasked with implementing a function to calculate the Intersection over Union (IoU) for object detection. The IoU is a metric used to evaluate the accuracy of object detection algorithms by measuring the overlap between the ground truth bounding box and the predicted bounding box. The function should take the co...
```python def calculate_iou(gt, pred): # Calculate the coordinates of the intersection rectangle x1 = max(gt[0], pred[0]) y1 = max(gt[1], pred[1]) x2 = min(gt[2], pred[2]) y2 = min(gt[3], pred[3]) # Calculate the area of intersection intersection_area = max(0, x2 - x1 + 1) * max(0, y2 - y1 ...
magicoder
python
You are tasked with implementing a simplified version of a reactive programming pattern using Combine framework in Swift. Your goal is to create a class that fetches champion data from a remote repository and updates its internal state accordingly. You are provided with a partial code snippet of a `ChampionManager` cl...
```swift import Combine class ChampionManager { private var champions: [Champion] = [] private let riotRepository: RiotRepository private let championsRepository: ChampionsRepository private var cancellables = Set<AnyCancellable>() init(riotRepository: RiotRepository, championsRepository: Champion...
magicoder
swift
You are tasked with implementing a simple routing system for a web application using Python. Your goal is to create a class that acts as a WSGI middleware to map incoming requests to WSGI apps based on specified routes. Your task is to complete the implementation of the `Router` class, which should be initialized with...
```python class Router(object): """WSGI middleware that maps incoming requests to WSGI apps.""" def __init__(self, mapper): """Create a router for the given routes.Mapper. Each route in `mapper` must specify a 'controller', which is a WSGI app to call. You'll probably want to specify ...
magicoder
python
You are tasked with implementing a simple search algorithm for a cursor in a 2D grid. The cursor can move in four directions: up, down, left, and right. The grid is represented as a 2D array of integers, where each integer represents the value at that position in the grid. The cursor starts at position (0, 0) and the s...
```python class Cursor: def __init__(self, grid): self.grid = grid self.n = len(grid) def search(self, target): visited = [[False for _ in range(self.n)] for _ in range(self.n)] queue = [(0, 0, 0)] # (x, y, steps) directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] # right...
magicoder
python
You are given a Python code snippet that uses the `numpy` library to perform matrix operations. Your task is to write a function that replicates the functionality of the `dot` method from the `numpy` library. The `dot` method computes the dot product of two arrays. The dot product of two arrays `A` and `B` is calculate...
```python def custom_dot(A, B): if len(A[0]) != len(B): raise ValueError("Number of columns in A must be equal to the number of rows in B") result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))] for i in range(len(A)): for j in range(len(B[0])): for k in range(len(B)): ...
magicoder
python
You are tasked with creating a Python function that can serialize and deserialize Python datetime objects using base64 encoding and pickle. Your task is to implement the `serialize_datetime` and `deserialize_datetime` functions, which will take a datetime object as input and return its base64 encoded representation and...
```python import base64 import pickle from datetime import datetime def serialize_datetime(dt): pickled_dt = pickle.dumps(dt) encoded_dt = base64.b64encode(pickled_dt) return encoded_dt def deserialize_datetime(encoded_dt): pickled_dt = base64.b64decode(encoded_dt) dt = pickle.loads(pickled_dt) ...
magicoder
python
You are given a list `ls` containing command-line strings for running a Python script. Each string represents a command to execute the `main.py` script with different configuration files. The configuration files are specified using the `--configs` flag followed by the file path. Your task is to extract the fold numbers...
```python import re def extract_fold_numbers(ls): fold_numbers = [] pattern = r"fold(\d+)" # Regular expression pattern to match fold number for command in ls: match = re.search(pattern, command) # Search for the pattern in the command if match: fold_number = int(match.group(...
magicoder
python
You are working on a project to preprocess medical question-answering data for a machine learning model. The preprocessing involves creating directories, running Python scripts, and passing command-line arguments to these scripts. Your task is to write a script that automates this preprocessing pipeline. Write a Pytho...
```python import os import subprocess # Create directories os.makedirs('../model_data/', exist_ok=True) os.makedirs('../mediqa_processed/', exist_ok=True) # Preprocess the ground truth files for evaluation try: subprocess.run(['python', 'get_mediqa_gt_processed.py'], check=True) except subprocess.CalledProcessErr...
magicoder
python
You are tasked with creating a Python function that interacts with a database manager to execute a query using the provided arguments. The function should construct the argument list and call the `run_query` method of the `db_manager` object, passing the query, arguments, and a flag indicating whether to return the res...
```python class DatabaseManager: def __init__(self): # Initialize database connection and other attributes def run_query(self, query: str, args: list, return_result: bool) -> None: # Execute the query using the provided arguments and return the result if return_result is True def execute_q...
magicoder
python
You are tasked with creating a Python function that simulates the process of web scraping to extract weather forecast information for a given location. You will need to utilize the `selenium` library to interact with a web page and extract the forecast data. Your task is to complete the `get_weather_forecast` function...
```python from selenium import webdriver from selenium.webdriver.common.by import By def get_weather_forecast(driver, location): searchBox = driver.find_element(By.ID, "forecast-input-0") searchBox.clear() searchBox.send_keys(location) searchButton = driver.find_element(By.CSS_SELECTOR, "span.input-gro...
magicoder
python
You are given a 2D grid of size n x n, initially filled with the character '.'. Your task is to implement a function `f` that takes this grid as input and returns the number of valid paths from the top-left corner to the bottom-right corner. In this grid, you can only move right or down, and you cannot visit a cell mor...
```cpp #include <vector> #include <string> using namespace std; class GridPaths { private: vector<string> grid; int ans; void f(int x, int y, int right, int down) { if (x == grid.size() - 1 && y == grid[0].size() - 1) { ans++; return; } if (right < grid.size...
magicoder
cpp
You are tasked with implementing a function to validate user information during social network authentication. The function should take in the user details and the logged-in user's information and perform the following checks: 1. If the user's email is not provided, it should return an error message indicating the requ...
```python import urllib def validate_social_network_user(details, logged_in_user): if not details.get('email'): error = "Sorry, but your social network (Facebook or Google) needs to provide us your email address." return error if logged_in_user: if logged_in_user.lower() != details.get...
magicoder
python
You are tasked with creating a program to manage a collection of fruits. Each fruit is represented by the `Fruit` struct, which has the following properties: - `id`: A unique identifier for the fruit, represented as a Unicode character (e.g., "🍌"). - `name`: The name of the fruit. - `weight`: The weight of the fruit i...
```swift struct Fruit { var id: String var name: String var weight: Double var color: Color static var bootstrap: [Fruit] = [ Fruit(id: "🍌", name: "Banana", weight: 118, color: .brown), Fruit(id: "🍓", name: "Strawberry", weight: 12, color: .red), Fruit(id: "🍊", name: ...
magicoder
swift
You are given a positive integer n. You need to write a function to return the smallest good base of n. A good base is a base k such that all numbers in base k are 1 followed by some number of 0s. For example, the numbers 1, 10, 100, and 1000 are all good numbers in base 10. Write a function `smallestGoodBase` to fin...
```java public String smallestGoodBase(String n) { long num = Long.parseLong(n); for (int m = (int)(Math.log(num + 1) / Math.log(2)); m > 2; m--) { long l = 2, r = (long)Math.pow(num, 1.0 / (m - 1)) + 1; while (l < r) { long mid = l + (r - l) / 2, sum = 0; for (int i = 0;...
magicoder
java
You are tasked with creating a program to validate Brazilian CPF (Cadastro de Pessoas Físicas) numbers. CPF is a unique identification number assigned to each Brazilian citizen, similar to a social security number in the United States. The CPF number is a 11-digit numeric code with a specific format and a built-in vali...
```python def validate_cpf(cpf: str) -> bool: cpf_digits = [int(digit) for digit in cpf if digit.isdigit()] if len(cpf_digits) != 11: return False # Calculate first verification digit sum_1 = sum([cpf_digits[i] * (10 - i) for i in range(9)]) verification_digit_1 = 0 if sum_1 % 11 <...
magicoder
python
You are tasked with implementing a higher-order function in Python that checks whether a given function satisfies the conditions to be considered a higher-order function. In Python, a higher-order function is a function that takes another function as an argument or returns a function as a result. To be considered a hig...
```python def is_higher_order(func): if callable(func): # Check if the input is a function try: # Attempt to pass a function as an argument or return a function result = func(lambda x: x) # Pass a lambda function as an argument return callable(result) # Check if the re...
magicoder
python
You are tasked with creating a Python program to analyze and visualize data from a fictional company's sales performance. The company sells six different products, and you have been provided with a CSV file containing the sales data for each product over the past year. Your goal is to create a program that reads the CS...
```python import pandas as pd import matplotlib.pyplot as plt # Step 1: Read the sales data from the CSV file sales_data = pd.read_csv('sales_data.csv') # Step 2: Calculate the total sales for each product total_sales = sales_data.sum(axis=1) # Step 3: Generate a bar chart to visualize the total sales for each produ...
magicoder
python
You are tasked with implementing a user management system for a web application. The system should support switching a user's role between guest and admin, and handle the associated data for each role. You are provided with a partial code snippet for a User struct and its associated methods in Rust. The User struct ca...
```rust use std::collections::HashSet; struct GuestData(String); struct Invite { // Define fields for Invite } struct ApiUser { // Define fields for ApiUser } enum User { Guest(GuestData), Admin { token: String, invites: HashSet<Invite>, users: HashSet<ApiUser>, }, } imp...
magicoder
rust
You are given a list of integers `a`. Your task is to write a function to calculate the sum of all distinct substrings of the list `a`. A substring is a contiguous sequence of elements within the list. For example, given the list `a = [1, 2, 3]`, the distinct substrings are `[1], [2], [3], [1, 2], [2, 3], [1, 2, 3]`, ...
```python from typing import List def sum_of_distinct_substrings(a: List[int]) -> int: n = len(a) s = n * (n + 1) // 2 # Sum of all substrings return s ``` The solution calculates the sum of all substrings using the formula `n * (n + 1) // 2`, where `n` is the length of the list `a`. This formula represen...
magicoder
python
You are tasked with implementing a custom expression evaluator in Swift. The evaluator should be able to parse and evaluate simple boolean expressions containing variables and comparison operators. The expression should be able to replace variables with values from a provided context and then evaluate the resulting exp...
```swift class Phrase { private var expression: String var context: [String: Any] = [:] init(_ expression: String) { self.expression = expression } func evaluate() throws -> Bool { var evaluatedExpression = expression for (variable, value) in context { if let va...
magicoder
swift
You are tasked with implementing a statistical calculation for a given dataset. The dataset consists of a series of numerical values, and you are required to calculate the standard deviation of these values. The standard deviation is a measure of the amount of variation or dispersion of a set of values. It is calculate...
```csharp using System; using System.Collections.Generic; namespace Statistics { public class CorrelationCalculator { public double CalculateStandardDeviation(List<double> values) { if (values.Count < 2) { throw new ArgumentException("At least two values ...
magicoder
csharp
You are tasked with implementing a Python class to represent a stretched segment. The segment is defined by its start and end points, and it can be stretched by a given ratio. Additionally, the segment can be reversed. Your task is to create a class that can handle these operations and pass the provided unit tests. Yo...
```python class Segment: def __init__(self, start, end, width, stretchRatio, reverse): self.start = start self.end = end self.width = width self.stretchRatio = stretchRatio self.reverse = reverse def stretch_segment(self): if self.stretchRatio != 1.0: ...
magicoder
python
You are tasked with implementing a Swift program to manage user agents for a web application. The program should define structures to represent user agents and headers, and provide functionality to manipulate and retrieve information about them. You are given the following code snippet as a starting point: ```swift s...
```swift struct UserAgent { let name, symbol, symbolNative: String } // MARK: - Header struct Header { var totalUserAgent: Int var listUserAgent: [UserAgent] mutating func addUserAgent(_ userAgent: UserAgent) { if !listUserAgent.contains(where: { $0.name == userAgent.name }) { list...
magicoder
swift
You are tasked with implementing a file packing and unpacking system using the given interface. The interface provides methods for erasing files from the pack, extracting a file to a destination, and extracting a file to memory. Your goal is to create a class that implements this interface and provides the necessary fu...
```cpp #include <iostream> #include <vector> #include <string> // Define the interface class FilePackerInterface { public: virtual bool EraseFiles(const std::vector<std::string>& paths) = 0; virtual bool ExtractFile(const std::string& path, const std::string& dest) = 0; virtual bool ExtractFileToMemory(con...
magicoder
cpp
You are working as a system administrator for a company that uses a custom monitoring system to track various processes running on its servers. The monitoring system uses a combination of shell scripts and command-line tools to manage and monitor these processes. One of the critical components of the monitoring system ...
```bash #!/bin/bash # Use ps and grep to find the PID of the date-pipe.sh process pid=$(ps auxwww | grep "date-pipe.sh" | grep -v grep | awk '{print $2}') # Check if the PID is not empty if [ -n "$pid" ]; then # Terminate the process using the identified PID kill -9 $pid echo "The date-pipe.sh process with PID ...
magicoder
shell
You are tasked with implementing a function to parse and process data from an interface representing the result of unsealing a cryptographic seal. The interface, `IUnsealResult`, contains the following properties: - `sealed`: a boolean indicating whether the seal is still sealed - `t`: a number representing a time valu...
```typescript interface IUnsealResult { sealed: boolean; t: number; n: number; progress: number; version: string; cluster_name: string; cluster_id: string; } function processUnsealResult(result: IUnsealResult): string { const sealedStatus = result.sealed ? "true" : "false"; const progressPercentage =...
magicoder
typescript
You are tasked with creating a Python function that generates an HTML report using Jinja2 templating and includes thumbnail images encoded in base64. Your function should take a summary object as input and return the HTML report as a string. The summary object contains a result attribute, which in turn contains a thumb...
```python from jinja2 import Environment, PackageLoader, select_autoescape from io import BytesIO import base64 class ReportGenerator: def __init__(self): pass def html(self, summary) -> str: """Returns an HTML version of the report, as a string.""" def thumburl(summary): d...
magicoder
python
You are tasked with implementing a custom processor for a game engine that handles the validation, instantiation, and visualization of specific types of objects within the game world. The provided code snippet is a partial implementation of this custom processor. Your task is to complete the implementation of the custo...
```csharp { public override bool ValidateProcessor(Type neosType) { return neosType.IsSubclassOf(typeof(SyncObject)) && !TypeBlacklist.Contains(neosType.FullName); } public override object CreateInstance(Type neosType) { SyncObject obj = Activator.CreateInstance(neosType) as SyncObj...
magicoder
csharp
You are tasked with creating a class to manage products in an e-commerce system. The class should have methods to set the product ID, description, and additional text, as well as handle the uploading of product images. Your task is to implement the missing `Produto` class with the required methods and properties. The ...
```php class Produto { private $idProduto; private $desc; private $texto; public function setIdProduto($id) { $this->idProduto = $id; } public function setDesc($desc) { $this->desc = $desc; } public function setTexto($text) { $this->texto = $text; } pu...
magicoder
php
You are tasked with creating a program that searches for specific functions within shared libraries. The program will take command-line arguments to specify the directory to search in and whether to match imported or exported functions. The program will then process these arguments and perform the search based on the s...
```rust use std::path::PathBuf; use goblin::Object; use std::fs; use std::io; fn search_functions(dir: &PathBuf, imported: bool) -> Vec<String> { let mut result = Vec::new(); // Read the directory and filter for shared libraries if let Ok(entries) = fs::read_dir(dir) { for entry in entries { ...
magicoder
rust
You are tasked with implementing a custom `FadeInOut` component in React Native that can animate the visibility, scaling, and rotation of child components. The component should accept different props to control these animations. Your goal is to create the `FadeInOut` component and demonstrate its usage with the provide...
```jsx import React, { useState, useRef, useEffect } from 'react'; import { Animated, Easing, View, Image, Button } from 'react-native'; const FadeInOut = ({ visible, duration, scale, rotate, children }) => { const fadeAnim = useRef(new Animated.Value(0)).current; const scaleAnim = useRef(new Animated.Value(1)).cu...
magicoder
jsx
You are tasked with implementing a TypeScript class that extends a base class and implements an interface. The base class represents a navigation bar, and the interface defines the structure of a menu element. Your task is to complete the implementation of the `Menu` class by providing the missing methods and propertie...
```typescript import { Navbar, IMenuElement, INavbar } from "../../ts-navbar"; export class Menu extends Navbar<IMenuElement> implements INavbar { constructor(element?: string | HTMLElement, config?: any) { super(element, config); // Initialize any additional properties or perform setup here } ...
magicoder
typescript
You are given a two-dimensional array `arr` of size (N+1) x (S+1), where N and S are positive integers. The array is initialized with zeros. You need to implement a method `solve` that fills in the array according to the following rules: 1. Initialize `arr[0][0]` to 1. 2. For each index (n, s) in the array where n ran...
```python from typing import List class Solution: def solve(self, N: int, S: int) -> List[List[int]]: arr = [[0] * (S + 1) for _ in range(N + 1)] arr[0][0] = 1 for n in range(N): for s in range(S): if arr[n][s] == 1: arr[n+1][s+1] = 1 ...
magicoder
python
You are tasked with implementing a Catalog class that manages a hierarchical structure of catalogs. Each catalog can contain sub-catalogs and items. The code snippet provided demonstrates the usage of the Catalog class and its associated methods. Your task is to implement the `Catalog` class and its methods to ensure t...
```python import os import json import uuid class Catalog: def __init__(self, root, id=None): self.root = root self.id = id if id else str(uuid.uuid4()) self.sub_catalogs = [] def create(self, root): catalog_data = {'root': self.root, 'id': self.id, 'sub_catalogs': []} ...
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 frequencies. For this problem, a word is defined as a sequence of alphanumeric characters, excluding any punctuatio...
```python import re from collections import Counter def analyze_word_frequency(file_path, N): with open(file_path, 'r') as file: text = file.read() words = re.findall(r'\b\w+\b', text.lower()) # Extract words and convert to lowercase word_counts = Counter(words) top_words = word_co...
magicoder
python
You are tasked with implementing a simple physics simulation program to calculate the trajectory of a projectile in a 2D space. The program should take into account the effects of gravity and air resistance on the projectile's motion. You are given the following code snippet as a starting point for the simulation: ``...
```cpp void calculateTrajectory(double time) { const double g = 9.81; // m/s^2 const double rho = 1.225; // kg/m^3 const double Cd = 0.47; // dimensionless const double A = 0.01; // m^2 (assuming a small cross-sectional area for simplicity) double vx = initialVelocity * cos(launchAngle); do...
magicoder
cpp
You are tasked with implementing a function to load files from a directory and calculate the sum of the Fibonacci numbers present in those files. The function should take the directory path as input and return the sum of all Fibonacci numbers found in the files within that directory. The Fibonacci numbers are defined...
```rust use std::fs; use std::path::Path; fn is_fibonacci(num: u64) -> bool { let mut a = 0; let mut b = 1; while b < num { let temp = b; b = a + b; a = temp; } b == num } fn sum_fibonacci_from_directory(directory_path: &str) -> Result<u64, String> { let path = Path::ne...
magicoder
rust
You are tasked with implementing a test case for a manual query process in a transaction system. The test case is part of a larger testing suite for a financial transaction system and is specifically focused on querying transaction details after performing a direct bank transaction. The provided code snippet is a part ...
```php function test_manual_queryOrder_queryDirectBank_order_step_2() { // Obtain the transaction details from the direct bank transaction $transactionDetails = performDirectBankTransactionAndGetDetails(); // Perform the manual query process for the obtained transaction details $queriedDetails = queryT...
magicoder
php
You are tasked with creating a Python program to analyze trip data from a series of CSV files. Each file contains trip data for a specific month, and the program needs to read and process each file to extract relevant information. The program should calculate the average trip duration for each month and identify the mo...
```python import csv from datetime import datetime def calculate_trip_duration(start_time, end_time): start = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S") end = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S") duration = end - start return duration.total_seconds() / 60 # Convert duration to minu...
magicoder
python
You are given a Python function that is part of a program to draw a line using the Bresenham's line algorithm. The function takes in the current y-coordinate `py` and the change in x-coordinate `dx1`. If the current y-coordinate is less than or equal to 0, the function updates the y-coordinate using the formula `py = p...
```python def draw_line(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dx1 = 2 * dy dy1 = 2 * dx line_pixels = [(x1, y1)] py = 0 if dx >= 0: # Line with positive slope if abs(dx) >= abs(dy): # Shallow slope yi = 1 D = 2 * dy - dx for x in range(x1 +...
magicoder
python
You are tasked with automating the deployment process for a Docker container that hosts a Visual Studio 2017 environment with GDB for debugging. The provided Bash script is a part of this deployment process. Your goal is to write a Bash script that automates the deployment of the Docker container, ensuring that it is s...
```bash #!/bin/bash # Build the Docker image docker build -t vs2017_gdb . # Remove any existing Docker container docker rm -f vs2017_gdb # Run a new Docker container with the specified configurations docker run -d --restart always -v /d/vcpkg:/vcpkg -v /c/Users/fananchong/Desktop/projects:/projects -p 1022:22 --name...
magicoder
shell
You are tasked with implementing a simulation success checker for a hardware verification tool. The provided code snippet is part of a simulation class for a hardware design, and it contains a method to set the pass and fail addresses for determining the success of the simulation. Additionally, there is a comment indic...
```cpp #include <cstdint> class verilator_sim { public: void set_pass_fail_addrs(uint32_t pass, uint32_t fail) { this->pass_address = pass; this->fail_address = fail; } bool run_simulation() { // Simulate the hardware and check the pass and fail addresses // Assuming memory...
magicoder
cpp
You are working on a reinforcement learning algorithm that involves updating weights, flags, and glows based on certain conditions. The code snippet provided is a part of this algorithm and involves manipulating NumPy arrays. Your task is to implement a function that takes in the current state, action index, reward, we...
```python import numpy as np def update_arrays(state, action_index, reward, weights, flags, glows, n, gamma, memory) -> dict: # Update glows array updated_glows = np.array([1.0 if i == action_index else (1 - n) * g for i, g in enumerate(glows)]) # Update weights array updated_weights = weights.copy() ...
magicoder
python
You are given a Swift code snippet that represents a higher-order function. Your task is to understand the code and implement a similar function in Python. The given Swift code snippet is as follows: ``` return { try second(first($0)) } } ``` Your task is to create a Python function that mimics the behavior of th...
```python def create_composed_function(first, second, input_func): def composed_func(x): return second(first(input_func(x))) return composed_func ```
magicoder
python
You are tasked with creating a function that processes a given file and extracts information about the file name, file type, and the number of GitHub stars for the project. The function should handle different file types and return the extracted information in a structured format. You are given a code snippet from a T...
```typescript function extractFileInfo(filePath: string): { fileName: string, fileType: string, githubStars: number } { const fileParts = filePath.split('/'); const fileNameWithExtension = fileParts[fileParts.length - 1]; const fileName = fileNameWithExtension.split('.')[0]; const fileType = fileNameWithExtensi...
magicoder
typescript
You are tasked with implementing a program to measure the time taken to execute a specific operation and then optimizing the operation to run within a certain time limit. You are given a code snippet that measures the time taken to execute a loop and increases the loop size until the time taken exceeds 0.2 seconds. Y...
To optimize the loop operation to run within the time limit, we can use a more efficient algorithm to perform the specific operation on the range of numbers. Let's consider an example where the specific operation is to calculate the sum of squares of numbers in the range. ```python import time def optimized_operation...
magicoder
python
You are tasked with implementing a function to connect primary input and output pins in a netlist for a digital circuit. The netlist is represented as a directed graph, where each node corresponds to a component or a pin, and each edge represents a connection between them. The netlist is stored in the `local_routing_ne...
```python import copy import networkx as nx def connect_primary_pins(local_routing_netlist): netlist = copy.deepcopy(local_routing_netlist) # Group local routing input pins by the driving net ipins = {} for u, attrs in local_routing_netlist.nodes(data=True): if u.split('.', 1)[0] == '1': ...
magicoder
python
You are tasked with creating a program that automates the process of filling out a web form using the White framework in C#. The White framework is a UI automation library that allows interaction with desktop applications. The `System.Windows.Automation` and `White.Core.UIItems` namespaces are used to access the necess...
```csharp using System; using System.Diagnostics; using System.Windows.Automation; using White.Core; using White.Core.UIItems; using White.Core.UIItems.Finders; using White.Core.UIItems.WindowItems; namespace FormAutomation { class Program { static void Main(string[] args) { // Laun...
magicoder
csharp
You are tasked with implementing a file monitoring system for a software build tool. The system should detect changes in specific files and trigger a build process when a change is detected. Your task is to write a function that monitors a file for changes and triggers a build process when the file is modified. You ar...
```swift import Foundation func monitorFileAndBuild(filePath: String, buildCommand: String) { let fileManager = FileManager.default var previousModificationDate = fileManager.attributesOfItem(atPath: filePath)?[.modificationDate] as? Date while true { if let modificationDate = fileManager.attribut...
magicoder
swift
You are given a directed graph represented by a set of vertices and their pairwise distances. Your task is to implement a function that computes the shortest paths between all pairs of vertices in the graph using the Floyd-Warshall algorithm. The Floyd-Warshall algorithm is used to find the shortest paths between all ...
```python from typing import List, Dict, Tuple from math import inf Node = int # Assuming nodes are represented as integers def all_pairs_shortest_paths(vertices: List[Node], distances: Dict[Tuple[Node, Node], float]) -> Dict[Tuple[Node, Node], float]: dist = { (u, v): inf for u in vertices for v in vertices } ...
magicoder
python
You are working on a web scraping project to extract information about medicines from a pharmaceutical website. The website contains multiple pages with lists of medicines, and each medicine has its own page with detailed information. Your task is to write a function to extract the names of medicines from a specific pa...
```bash get_medicines_from_page() { main="https://pharmawebsite.com" lists="medicines" if [ "$2" -eq 1 ]; then curl_rand "$main/$lists/?lettre=$1" | tr "\n" "|" | grep -o '<tbody>.*</tbody>' | sed 's/\(<tbody>\|<\/tbody>\)//g' | sed 's/|/\n/g' | egrep -v 'tr>|td>|details' | sed ':a;N;$!ba;s/<br>\n/\...
magicoder
shell
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. Your program should read in a text file and then prompt the user to input a list of words to search for within the file. The program should then output the count of each word in the list that appears in th...
```python def count_word_occurrences(): file_name = input("Enter the file name: ") try: with open(file_name, 'r') as file: text = file.read().lower() # Convert the text to lowercase for case-insensitive comparison except FileNotFoundError: print("File not found.") return...
magicoder
python
You are tasked with creating a function that converts a given data size from a human-readable format to a machine-readable format. The function should take a string representing the data size and its unit (e.g., "100 MiB") and return the size in bytes as an integer. If no unit is provided, the default unit is assumed t...
```rust use std::str::FromStr; #[derive(Debug)] enum ByteUnit { KiB, MiB, GiB, TiB, PiB, } impl ByteUnit { fn to_bytes(&self) -> i64 { match self { ByteUnit::KiB => 1024, ByteUnit::MiB => 1024 * 1024, ByteUnit::GiB => 1024 * 1024 * 1024, ...
magicoder
rust
You are tasked with creating a custom hook in React that manages the state of a form within a drawer component. The hook should handle form submission, validation, and imperatively expose the form's imperative methods. Your task is to implement the `useDrawerForm` custom hook, which will be used within a React functio...
```jsx import React, { useState, useCallback, useImperativeHandle, useRef } from 'react'; const useDrawerForm = (initialFormData, onSubmit, validateForm) => { const [formData, setFormData] = useState(initialFormData); const [formErrors, setFormErrors] = useState({}); const handleSubmit = useCallback(() => { ...
magicoder
jsx
You are tasked with implementing a CUDA-accelerated force computation module for a Discrete Element Method (DEM) simulation in a molecular dynamics framework. The provided code snippet is a part of the interface for the DEM2DForceComputeGPU class, which is responsible for computing forces on particles using GPU acceler...
```cpp #ifdef ENABLE_CUDA #include "DEM2DForceComputeGPU.h" #include "cuda_runtime.h" #include "cuda.h" #include <stdexcept> #include <iostream> #include <hoomd/extern/pybind/include/pybind11/pybind11.h> using namespace std; class DEM2DForceComputeGPU { public: DEM2DForceComputeGPU(std::shared_ptr<SystemDefini...
magicoder
cpp
You are working on a machine learning framework that involves loading and uploading weights and results to and from a node. The provided code snippet shows two methods, `_load_weight` and `_upload_result`, within a class. The `_load_weight` method is responsible for loading weights from a node and updating the paramete...
```python def _check_upload_size(self) -> bool: with TemporaryFile("w+b") as f: params = self.get_params() arr = self._alg.params_to_result(params) serialize.dump_arr(f, arr) f.seek(0) upload_size = len(f.read()) return upload_size <= self.max_upload_size ``` In the ...
magicoder
python
You are given a list of integers representing the daily stock prices of a company. You need to write a function to calculate the maximum profit that can be obtained by buying and selling the stock on different days. However, you are only allowed to complete at most one transaction (i.e., buy one and sell one share of t...
```python def maxProfit(prices): if not prices: return 0 min_price = prices[0] max_profit = 0 for price in prices: if price < min_price: min_price = price else: max_profit = max(max_profit, price - min_price) return max_profit ``` The `m...
magicoder
python
You are tasked with creating a Python class that simulates a simple database connection. The class should handle the opening and closing of the database connection, and it should also provide a method for executing SQL queries. Your task is to implement the `Database` class with the following requirements: - The class...
```python class Database: def __init__(self, db_name): self.db_name = db_name self.client = None def open_connection(self): # Simulate opening the database connection self.client = f"Connection to {self.db_name} established" print(f"Connected to {self.db_name}") def...
magicoder
python
You are working on a transaction verification system for a financial institution. The system processes transactions and then verifies their execution and commits them to the database. However, there seems to be an issue with the verification process, as the number of finished programs after execution does not match the...
The code snippet provided seems to be a part of a transaction verification system. The discrepancy in the number of finished and verified programs could be due to various reasons. Here's a potential solution to address this issue: 1. **Review the execute() and validateAndCommit() methods**: Check the implementation of...
magicoder
python
You are tasked with implementing a custom loading view in a mobile application using Swift. The loading view should be centered within the main view and should have a width and height equal to a fraction of the main view's width and height, respectively. You are given a code snippet that adds a background view to the m...
```swift // Create and configure the loading view let loadingView = UIView() loadingView.backgroundColor = UIColor.gray // Set the background color as an example // Add the loading view to the main view view.addSubview(loadingView) // Center the loading view within the main view loadingView.centerXAnchor.constraint(e...
magicoder
swift
You are tasked with implementing a simple 2D game using C++ and the SFML library. The game will involve rendering and manipulating points on the screen. You are provided with a code snippet that defines a class `PointDemo` which inherits from `DrawableGameComponent` and takes a `Game` object and a `shared_ptr` to a `Ca...
```cpp #include <SFML/Graphics.hpp> #include <vector> #include <memory> class Camera { // Implementation of Camera class }; class Game { // Implementation of Game class }; class DrawableGameComponent { public: DrawableGameComponent(Game& game, std::shared_ptr<Camera> camera) : m_game(game), m_camera(std:...
magicoder
cpp
You are tasked with creating a Python program to perform K-means clustering on a randomly generated dataset using the `sklearn` library. The program should generate a random dataset with multiple variables and then use the KMeans algorithm to cluster the data points. Finally, the program should visualize the clusters u...
```python import numpy as np from sklearn.cluster import KMeans import msmexplorer as msme import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Step 1: Generate a random dataset np.random.seed(0) X = np.random.rand(100, 4) # Step 2: Perform KMeans clustering kmeans = KMeans(n_clusters=3, random_s...
magicoder
python
You are tasked with implementing a Python class method for a remote file management system. The method `copy` should copy a file or a directory from a remote source to a remote destination on the same remote machine. The method takes in the following parameters: - `remotesource`: The remote source file or directory to ...
```python class RemoteFileManager: def __init__(self, connection): self.connection = connection def copy(self, remotesource, remotedestination, *args, **kwargs): """ Copy a file or a directory from remote source to remote destination (On the same remote machine) """ ...
magicoder
python
You are tasked with implementing a tokenizer for processing Weibo (a popular Chinese microblogging platform) text data. The tokenizer should split the input text into Weibo tokens, which consist of a word and its associated part-of-speech (POS) tag. Each Weibo token is represented as a tuple of two elements: the word a...
```python class WeiboToken: def __init__(self, word, pos_tag): self.word = word self.pos_tag = pos_tag def weibo_tokenize(weibo_text): tokens = weibo_text.split() # Split the input Weibo text into tokens based on whitespace delimiter weibo_tokens = [] for token in tokens: word,...
magicoder
python
You are given a code snippet that calculates the factorial and modular inverse of numbers. Your task is to write a program to find the modular inverse of a given number. You need to implement a function `modularInverse` that takes two integers `a` and `mod` as input and returns the modular inverse of `a` modulo `mod`....
```cpp #include <iostream> #define ll long long #define mod 1000000007 ll fact[1000001]; ll inv[1000001]; ll f(ll a, ll b) { if (b == 0) return 1; ll t = f(a, b / 2); t = (t * t) % mod; if (b % 2 == 0) return t; else return (a * t) % mod; } int modularInverse(int a, int mod) { fact[0] = 1; ...
magicoder
cpp
You are tasked with creating a program that processes a given HTML file and extracts specific information from it. The HTML file contains a section with a list of age categories and their corresponding titles. Your goal is to extract the titles of the age categories and present them in a structured format. Write a fun...
```python from bs4 import BeautifulSoup def extractAgeCategories(html): soup = BeautifulSoup(html, 'html.parser') age_category_titles = [h2.text for h2 in soup.find_all('h2', class_='age-categories__title')] return age_category_titles ``` The `extractAgeCategories` function uses the BeautifulSoup library ...
magicoder
python
You are tasked with implementing a simple dictionary-based interpreter for a custom scripting language. The interpreter should be able to read and execute simple commands from a script file. Your task is to complete the implementation of the `read_table` method in the given code snippet. The `read_table` method should ...
```python class EOS: def __init__(self): self.interp = {} def read_table(self, fname): """ Initialize the EOS object from a table file :param fname: The file name of the table file """ with open(fname, 'r') as file: for line in file: l...
magicoder
python
You are given a vector of integers representing the heights of a series of buildings. Your task is to find the maximum area of a rectangle that can be formed by selecting a contiguous sequence of buildings. The width of the rectangle is the number of buildings selected, and the height of the rectangle is the minimum he...
```cpp int maxRectangleArea(const vector<int>& heights) { int n = heights.size(); stack<int> st; int maxArea = 0; for (int i = 0; i <= n; ++i) { while (!st.empty() && (i == n || heights[i] < heights[st.top()])) { int height = heights[st.top()]; st.pop(); int w...
magicoder
cpp
You are working on a Swift project that involves associating objects with other objects using the Objective-C runtime. The provided code snippet demonstrates a function `associateObject` that associates an object of type `T` with a given base object using the Objective-C runtime. Additionally, there is a function that ...
The `ObjectAssociation` class is implemented as a generic class in Swift. It uses the Objective-C runtime functions `objc_setAssociatedObject` and `objc_getAssociatedObject` to associate and retrieve objects with a base object. The `associate` method sets the associated object with the given base object using the provi...
magicoder
swift
You are tasked with implementing a filtering system for a list of names based on specific criteria. The system should support adding and removing filters to dynamically modify the list of names. The filters can be applied based on whether a name starts with or ends with a specified parameter. You are given a partial c...
```csharp using System; using System.Collections.Generic; using System.Linq; public class NameFilteringSystem { private List<string> names; private List<string> temp; public NameFilteringSystem(List<string> initialNames) { names = initialNames; temp = new List<string>(names); } ...
magicoder
csharp
You are tasked with implementing a simple image processing algorithm to perform erosion on a given image. Erosion is a fundamental operation in morphological image processing that involves shrinking the boundaries of regions of foreground pixels. The provided code snippet demonstrates the application of erosion to an i...
```python import numpy as np from scipy import ndimage def apply_image_processing(control, post_shape, erode_kwargs, iterations): # Resample the control image to the desired shape control = ndimage.zoom(control, (post_shape[0] / control.shape[0], post_shape[1] / control.shape[1], 1)) # Apply erosion itera...
magicoder
python
You are working on a network function that handles Policy and Charging Control Function (PCF) messages in a 5G network. One of the tasks is to process Update BAR Session Modification Request messages, which contain various Traffic Influence Control (TIC) information. The TIC information is represented using Type-Length...
```c void parseUpdateBARSessionModificationRequest(ogs_pfcp_tlv_update_bar_session_modification_request_t *tlv, uint8_t *barId, uint8_t *notificationDelay, uint16_t *bufferingPack...
magicoder
c
You are tasked with implementing a multithreaded server application in Swift. The server will handle incoming socket connections and process them using a queue-based approach. Your goal is to design a system that efficiently manages socket connections and ensures thread safety. Your task is to implement a `SocketHandl...
```swift import Foundation class SocketHandler { let socketfd: Int init(socketfd: Int) { self.socketfd = socketfd } func processSocket() { // Implement socket processing logic here } } class Server { let socketHandlersQueue = DispatchQueue(label: "com.server.socketHandlers", ...
magicoder
swift
You are tasked with creating a TypeScript function that filters a list of gateway devices based on certain criteria. Each gateway device is represented by the following interface: ```typescript interface GatewayDevice { status?: string; version: string; location?: string; coordinates?: [number, number]; floo...
```typescript function filterGateways(gateways: GatewayDevice[], criteria: GatewayFilterCriteria): GatewayDevice[] { return gateways.filter(gateway => { if (criteria.status && gateway.status !== criteria.status) { return false; } if (criteria.location && gateway.location !== criteria.location) { ...
magicoder
typescript
You are given a Python code snippet that contains a copyright notice. Your task is to write a Python function that takes the code snippet as input and extracts the years mentioned in the copyright notice. The function should return a list of years found in the copyright notice. Function Signature: `def extract_years(c...
```python from typing import List import re def extract_years(copyright_notice: str) -> List[str]: years = re.findall(r'\b\d{4}\b', copyright_notice) return years ```
magicoder
python
You are tasked with creating a script to automate the installation process for a software package. The installation process involves running a series of commands in the terminal. The commands are as follows: ``` ./configure --with-experimental make sudo make install sudo ldconfig ``` Your script should execute these co...
```bash #!/bin/bash # Script to automate the installation process for a software package # Step 1: Run ./configure --with-experimental echo "Running ./configure --with-experimental" if ! ./configure --with-experimental; then echo "Error: Failed to run ./configure" exit 1 fi # Step 2: Run make echo "Running make"...
magicoder
shell
You are tasked with implementing a simple parser for a custom rule-based language. The provided code snippet is part of a parser library and contains a method for defining parsing rules and a method for scanning input code based on these rules. The `scan` method takes a reference to a string `code` and returns a resul...
```rust // Define the Rule type struct Rule; // Define the RuleError type struct RuleError; // Define the Instr type enum Instr<T> { Range(i32, i32, T), // Add other instruction types as needed } // Define the Parser type struct Parser<T> { instr: Vec<Instr<T>>, } impl<T> Parser<T> { // Method to ad...
magicoder
rust
You are tasked with creating a Python program to manage the training and evaluation of convolutional neural network (CNN) models for image classification. The program should allow the user to iteratively construct, train, and evaluate multiple CNN models with varying configurations. Your program should prompt the user...
```python import numpy as np from cnn_model import CNNModel # Assume the existence of a CNNModel class for creating and training CNN models models = [] # List to store constructed CNN models predictions = [] # List to store predictions of each model def previous_experiment(model): # Function to perform operati...
magicoder
python
You are tasked with implementing the insertion sort algorithm to sort an array of integers in non-decreasing order. The insertion sort algorithm works by iteratively building a sorted portion of the array, one element at a time. At each iteration, the algorithm takes the next unsorted element and inserts it into its co...
```python from typing import List def sort_insertion(arr: List[int]) -> List[int]: for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr ``` The `sort_insertion` function ...
magicoder
python
You are tasked with implementing a function 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 function should take an integer `n` as input and return the sum of all prime numbers up to and...
```python def sumOfPrimes(n): 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 prime_sum = 0 for i in range(2, n + 1): if is_prime(i): prime_sum +...
magicoder
python