query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with implementing a parallel tokenization function for processing a collection of documents. The function should take a list of documents, a tokenizer function, and a maximum number of tokens as input, and then parallelize the tokenization process across multiple CPU cores using the `joblib` library.
Th... | ```python
from joblib import Parallel, delayed
def tokenize_job(documents, tokenizer, max_tokens, job):
return [tokenizer(doc)[:max_tokens] for doc in documents]
def tokenize_parallel(documents, tokenizer, max_tokens, n_jobs=-1):
def get_parallel_slices(n_tasks, n_jobs):
if n_jobs == -1:
n... | magicoder | python |
You are tasked with creating a Python script to automate the configuration of CPU frequency settings on a Linux system. The script should read a configuration file containing the desired settings and apply them to the appropriate system files.
The configuration file will contain lines in the following format:
```
<cor... | ```python
import os
def apply_cpu_settings(config_file):
with open(config_file, 'r') as file:
for line in file:
core_number, hispeed_freq, target_loads, use_sched_load = line.split()
cpu_path = f"/sys/devices/system/cpu/cpu{core_number}/cpufreq/interactive/"
try:
... | magicoder | python |
You are tasked with creating a Python class that interacts with a database using the `muttlib` library. The `muttlib` library provides utilities for database connections and operations. Your task is to create a class that encapsulates the functionality to perform CRUD (Create, Read, Update, Delete) operations on a spec... | ```python
import logging
from muttlib.dbconn.base import BaseClient
class DatabaseTableManager(BaseClient):
def __init__(self, table_name, connection_params):
super().__init__(**connection_params)
self.table_name = table_name
self.logger = logging.getLogger(__name__)
def create_record(... | magicoder | python |
You are tasked with implementing a message logging system in Python. The system should support logging messages of different types (error, warning, info) and provide a way to retrieve the messages based on their type and timestamp.
Your task is to implement the `MessageLogger` class with the following requirements:
1.... | ```python
import datetime
class MessageLogger:
def __init__(self):
self.messages = []
def log_message(self, type, message):
timestamp = datetime.datetime.now()
self.messages.append((type, message, timestamp))
def get_messages_by_type(self, type):
filtered_messages = [msg f... | magicoder | python |
You are tasked with implementing a custom decorator in Python that replicates the functionality of the `@login_required` decorator commonly used in web frameworks like Django. The `@login_required` decorator is used to restrict access to certain views in a web application to only authenticated users. When a user tries ... | ```python
def login_required(view_func):
def wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated:
return view_func(request, *args, **kwargs)
else:
redirect_to_login()
return wrapped_view
```
In the solution, the `login_required` decorator function ta... | magicoder | python |
You are tasked with implementing a dynamic embedding service that maps input keys to embeddings based on a given configuration. The service interacts with a knowledge bank service and supports various functionalities such as handling empty keys, specifying a unique variable name, controlling gradient updates, and setti... | ```python
def dynamic_embedding_service(keys, config, var_name, service_address, skip_gradient_update, timeout_ms):
# Handle empty keys
if keys == "":
return zero_embedding # Assuming zero_embedding is defined elsewhere
# Use default service address if not provided
if service_address == "":
... | magicoder | python |
You are tasked with creating a simple web application using Flask, a popular Python web framework. Your goal is to implement a basic message board feature where users can post messages and view all the messages posted by other users. To achieve this, you need to define a Flask blueprint for the message board functional... | ```python
from flask import Blueprint, request, jsonify
# Define a simple in-memory data structure to store messages
messages = []
# Create a Flask blueprint for the message board feature
message_board_blueprint = Blueprint('message_board', __name__)
# Define a route to display all messages posted on the message boa... | magicoder | python |
You are given a Python code snippet that operates on a variable `s`. The code snippet contains a series of operations using slicing and indexing, and a comment indicating the calculation of the exponent of the constant `e`. Your task is to understand the operations being performed and write a Python function that repli... | ```python
import pandas as pd
import math
def process_s(s):
results = []
# Print the first element of the series s
results.append(s.iloc[0])
# Print the first three elements of the series s
results.append(s.iloc[:3].tolist())
# Print the elements of the series s that are greater ... | magicoder | python |
You are tasked with implementing a generic index buffer class in C++ to manage indices for various types of graphics primitives. The index buffer should support adding and retrieving indices, as well as resizing the buffer when necessary. Your task is to complete the implementation of the `IndexBufferBase` class by add... | ```cpp
#include <iostream>
#include <vector>
class IndexBufferBase {
protected:
std::vector<int> indices;
public:
// Add an index to the buffer
virtual void AddIndex(int index) = 0;
// Get the index at a specific position
virtual int GetIndex(int position) const = 0;
// Get the total number ... | magicoder | cpp |
You are tasked with creating a Python program to simulate a rock-paper-scissors game against a computer opponent. The program should take user input for their choice (rock, paper, or scissor) and then randomly generate the computer's choice. The program should then determine the outcome of the game based on the choices... | ```python
import random
# Function to determine the outcome of the game
def determine_outcome(player_choice, ia_choice):
if player_choice == 'rock':
if ia_choice == 'rock':
return 'draw'
elif ia_choice == 'scissor':
return 'victory'
elif ia_choice == 'paper':
... | magicoder | python |
You are tasked with implementing a class that manages a document editing form in a Windows Forms application. The form contains a group box for editing document options, including a numeric up-down control for setting line width. However, the given code snippet seems to be incomplete and contains some errors. Your task... | ```csharp
using System;
using System.Windows.Forms;
public class DocumentOptionsEditForm : Form
{
private GroupBox groupBox1;
private NumericUpDown nudLineWidth;
private ErrorProvider errorProvider;
public DocumentOptionsEditForm()
{
this.Name = "DocumentOptionsEditForm";
// Initi... | magicoder | csharp |
You are tasked with implementing a Python function that performs slicing on a multi-dimensional array. The function should take in a multi-dimensional array `m`, a list of slices `slices`, and an axis `axis`. The function should return the sliced array based on the provided slices along the specified axis.
The functio... | ```python
import numpy as np
def multi_dim_slice(m, slices, axis):
sl = [slice(None)] * m.ndim
sl[axis] = slices
return m[tuple(sl)]
```
The `multi_dim_slice` function first creates a list `sl` containing `slice(None)` for each dimension of the input array `m`. It then replaces the slice at the specified `... | magicoder | python |
You are working on a natural language processing project and need to process evaluation metrics for machine translation models. You have a file containing evaluation results in the following format:
```
RESULT: baseline: BLEU: AVG: 0.75
RESULT: baseline: METEOR: AVG: 0.68
```
You need to write a Python function to pa... | ```python
def extract_evaluation_scores(file_path):
scores = {"BLEU": None, "METEOR": None}
with open(file_path, 'r') as file:
for line in file:
if line.startswith("RESULT: baseline: BLEU: AVG:"):
bleu_score = float(line.split(":")[4])
scores["BLEU"] = bleu_sc... | magicoder | python |
You are tasked with creating a Python unit test for a class representing a Heroku application. The class has several methods for interacting with the application, and the unit test framework being used is `unittest` with `mock` for mocking external calls.
Your task is to write a unit test for the `HerokuApp` class, sp... | ```python
import unittest
from unittest.mock import Mock, patch
from heroku_app import HerokuApp # Assuming HerokuApp class is defined in heroku_app module
class TestHerokuApp(unittest.TestCase):
def test_buildpack(self):
app = HerokuApp()
with patch('subprocess.check_call') as mock_check_call:
... | magicoder | python |
You are tasked with creating a Python class that represents a collection of official documents. Each document has a unique identifier, a title, and a content. Your task is to implement the `OfficialDocument` class and the `OfficialDocumentsCollection` class to manage these documents.
The `OfficialDocument` class shoul... | ```python
class OfficialDocument:
def __init__(self, identifier, title, content):
self.identifier = identifier
self.title = title
self.content = content
def __str__(self):
return f"ID: {self.identifier}, Title: {self.title}"
def get_content(self):
return self.conten... | magicoder | python |
You are tasked with implementing a class that simulates a simple banking system. The class should have methods to deposit funds, withdraw funds, and check the current balance. Additionally, the class should keep track of the total number of transactions (deposits and withdrawals) made on the account.
You need to creat... | ```java
public class BankAccount {
private double balance;
private int numTransactions;
public BankAccount() {
this.balance = 0;
this.numTransactions = 0;
}
public void deposit(double amount) {
this.balance += amount;
this.numTransactions++;
}
public boolea... | magicoder | java |
You are tasked with creating a TypeScript class that represents a user subscription. The class should have a `userId` property of type `string` and a `validUntil` property of type `string`, representing an ISO date. Additionally, the `validUntil` property should be annotated with a decorator that sets its default value... | ```typescript
import { Entity, Column } from 'typeorm';
@Entity()
export class Subscription {
@Column('uuid')
userId: string;
@Column('timestamp', { default: () => 'timezone(\'utc\', now()) + interval \'2 days\'' })
validUntil: string; // ISO Date
}
```
In the solution, we define a TypeScript class `Subscrip... | magicoder | typescript |
You are tasked with creating a script to automate the installation of PHP PEAR packages on a Debian system. The script should handle configuring PHP via PHP PEAR, updating PEAR channels, and installing required packages. Your task is to write a Bash script that accomplishes these tasks.
Your script should perform the ... | ```bash
#!/bin/bash
base_logfile="install_log.txt"
print_status() {
echo "$1"
}
# Set preferred state of PEAR packages to "alpha"
print_status "Setting preferred state of PEAR packages to alpha.."
pear config-set preferred_state alpha &>> $base_logfile
# Update the PEAR channel for pear.php.net
print_status "Upda... | magicoder | shell |
You are tasked with implementing a Bloom Filter data structure in Python. A Bloom Filter is a space-efficient probabilistic data structure used to test whether an element is a member of a set. It may return false positives but never false negatives. Your task is to complete the implementation of the BloomFilter class b... | ```python
class BitArray:
def __init__(self, size):
self.size = size
self.array = [0] * size
def set_bit(self, index):
self.array[index] = 1
def check_bit(self, index):
return self.array[index] == 1
def print(self):
return ''.join(str(bit) for bit in self.array... | magicoder | python |
You are tasked with implementing a synchronization mechanism for different types of data in a web application. The given code snippet is part of a function that handles synchronization based on a specified mechanism. The function takes a `context` object as a parameter, which contains a `mechanism` property indicating ... | ```javascript
// Synchronization function for serversync mechanism
function serversync(context) {
// Implement synchronization logic for serversync mechanism
return "Synchronized with server";
}
// Synchronization function for cookiesync mechanism
function cookiesync(context) {
// Implement synchronization logic... | magicoder | javascript |
You are tasked with implementing a class for managing user information. The class should have the following attributes and methods:
Attributes:
- `name`: a string representing the user's name
- `password`: a string representing the user's password
- `email`: a string representing the user's email
Methods:
- `__init__... | ```python
class User:
def __init__(self, name: str, password: str, email: str) -> None:
"""
Initialize User attributes with provided values.
:type password: ``str``
:param email: The email associated with the backup unit.
Bear in mind that this email d... | magicoder | python |
You are working on a project that requires creating a Python function to build a map using a specific projection. The function will utilize the Basemap module from the mpl_toolkits library to generate the map. The function, map_RegCMdomain, takes several parameters to define the map's domain and projection properties. ... | ```python
# Import modules you need
#-----------------------------------------------------
from mpl_toolkits.basemap import Basemap, cm
import matplotlib.pyplot as plt
import numpy as np
######################################################
### Python fuction to build a map using a specific projection
#-------------... | magicoder | python |
You are tasked with creating a Python function that processes and validates car data received from a web request. The function should take in three parameters: `body_type`, `mileage`, and `mileage_unit`. The `body_type` parameter represents the type of car body (e.g., sedan, SUV), `mileage` represents the mileage of th... | ```python
def process_car_data(body_type, mileage, mileage_unit):
# Validate body_type
if not isinstance(body_type, str) or not body_type:
raise ValueError("Invalid body_type: must be a non-empty string")
# Validate mileage
if not isinstance(mileage, int) or mileage <= 0:
raise ValueErr... | magicoder | python |
You are given a code snippet that processes polygon vertices and indices to generate a list of vertices. Your task is to implement a function that takes in the polygon vertices, polygon indices, and a starting index, and returns a list of vertices based on the given indices.
Write a function `GenerateVertices` that ta... | ```csharp
using System;
using System.Collections.Generic;
public class Program
{
public static List<Vector3> GenerateVertices(List<Vector3> polyVertices, int[] polyIndices, int startIndex)
{
List<Vector3> vertices = new List<Vector3>();
if (polyIndices.Length < 3)
return vertices; ... | magicoder | csharp |
You are tasked with implementing a simple event handling mechanism using the Observer pattern in Swift. You are provided with a `ViewModel` class that represents the view model of a user interface component. The `ViewModel` class has a property called `disposeBag` of type `DisposeBag`, which is used to manage the dispo... | ```swift
// Define the Observable protocol
protocol Observable {
associatedtype Event
var observers: [ObjectIdentifier: (Event) -> Void] { get set }
func addObserver(_ observer: AnyObject, handler: @escaping (Event) -> Void)
func removeObserver(_ observer: AnyObject)
func notifyObservers(_ even... | magicoder | swift |
You are tasked with creating a Python program that simulates a simple text-based adventure game. The game will involve the player making choices that affect the outcome of the story. The game will be implemented using Python's `tkinter` library for the graphical user interface (GUI).
Your task is to implement a functi... | ```python
import tkinter as tk
def start_game():
# Implement the game logic and interactions here
pass # Placeholder for game logic
def create_game_interface():
window = tk.Tk()
window.title("Text Adventure Game")
label2 = tk.Label(window, text="授权许可证:", height=4)
label2.place(x=30, y=130)
... | magicoder | python |
You are tasked with creating a simple library management system using the Rust programming language. The system should allow users to add, remove, and search for books in the library. Additionally, users should be able to check out and return books.
You are provided with the following code snippet as a starting point:... | ```rust
use uapi::*;
struct Book {
title: String,
author: String,
available: bool,
}
impl Book {
fn new(title: &str, author: &str) -> Book {
Book {
title: title.to_string(),
author: author.to_string(),
available: true,
}
}
}
fn add_book(title: &... | magicoder | rust |
You are tasked with implementing a simplified version of a control flow graph (CFG) creation utility in a programming language of your choice. A control flow graph is a representation of a program's control flow, where nodes represent individual statements or expressions, and edges represent the flow of control between... | ```java
// CFANode class representing a node in the control flow graph
class CFANode {
private String function;
private int nodeId;
public CFANode(String function) {
this.function = function;
this.nodeId = generateUniqueId(); // Assume a method to generate unique node IDs
}
// Gett... | magicoder | java |
You are given a list of integer differences `diffs`. Your task is to write a function to find the maximum sum of a subsequence of `diffs` such that no two elements in the subsequence are adjacent in the original list. In other words, you need to find the maximum sum of non-adjacent elements in the list.
Write a functi... | ```python
def max_non_adjacent_sum(diffs):
if not diffs:
return 0
if len(diffs) <= 2:
return max(0, max(diffs))
max_sum = [0] * len(diffs)
max_sum[0] = max(0, diffs[0])
max_sum[1] = max(max_sum[0], diffs[1])
for i in range(2, len(diffs)):
max_sum[i] = max(max_sum[i-1], ... | magicoder | python |
You are tasked with implementing a function to process font characters and their corresponding Unicode values. The given code snippet is part of a font processing module and contains two methods: `characterIdToUnicode` and `guessSpaceCharacterId`. The `characterIdToUnicode` method attempts to find the Unicode represent... | ```swift
func findUnicodeForCharacterId(_ char: PDFFontFile.CharacterId) -> Unicode.Scalar? {
let res = toUnicodeCharMapLookup(char) ?? differences.characterIdToUnicode(char) ?? encodingConvertCharacter([UInt8(char)]) ?? fontFileCharMapLookup(char) ?? String(bytes: [UInt8(char)], encoding: .isoLatin1)?.unicodeScala... | magicoder | swift |
You are given a list of integers and a target sum. Your task is to write a function that finds all unique combinations in the list that sum up to the target. Each number in the list may only be used once in the combination. The solution set must not contain duplicate combinations.
Function Signature:
```python
def co... | ```python
from typing import List
def combination_sum(nums: List[int], target: int) -> List[List[int]]:
def backtrack(start, target, path, res):
if target < 0:
return
if target == 0:
res.append(path)
return
for i in range(start, len(nums)):
if... | magicoder | python |
You are tasked with implementing a Python program that simulates a simple database entry system. The program should read input from a file, process the data, and save the entries to a database. However, the provided code snippet contains a critical error that needs to be identified and fixed.
The code snippet is as fo... | The issue in the code snippet is the presence of an unmatched closing parenthesis `)` at the beginning of the code. This will cause a syntax error when the program is executed. Additionally, the print statement "done, you fuck." contains inappropriate language and should be replaced with a more professional message.
T... | magicoder | python |
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 main():
try:
random_number = random.randint(1, 100)
while True:
guess = int(input("Guess the number (between 1 and 100): "))
if guess < random_number:
print("Too low! Try again.")
elif guess > random_number:... | magicoder | python |
You are tasked with creating a script to automate the build process for a PHP project. The provided code snippet is a part of the buildphp function, which is responsible for setting up the PHP source code and running the necessary configuration steps.
The function starts by changing the current directory to the locati... | ```bash
#!/bin/bash
buildphp() {
cd "${PHP_SRC}"
if [ ! -f ./configure ]; then
echo "Autoconf PHP"
./buildconf --force
fi
if [ ! -f Makefile ]; then
echo "Configuring PHP"
./configure --prefix=/usr/local/php
fi
echo "Compiling PHP"
make
echo "Installin... | magicoder | shell |
You are tasked with implementing a function that groups a list of events by their date and returns a dictionary where the keys are the dates and the values are lists of events that occurred on that date. The events are represented as dictionaries with a 'date' key containing the date of the event.
You need to write a ... | ```python
from itertools import groupby
def group_events_by_date(events):
groups = groupby(events, lambda o: o['date'])
grouped_events = {
date: list(events)
for date, events in groups
}
return grouped_events
``` | magicoder | python |
You are tasked with creating a Python program that simulates a simple logging and reporting system. The program should utilize the `logging` module to set different levels of logging and then generate reports based on the logged data.
Your task is to complete the Python program by implementing the missing parts. The p... | ```python
import logging
def setup_logging():
levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
logging.basicConfig(level=levels[3])
def stats_report():
# Generate a report based on the logged data
# Example: Fetch data from logs and calculate statistics
logging.debug("This is... | magicoder | python |
You are tasked with implementing a function that filters a given array of movies based on a set of criteria. Each movie is represented as an associative array with 'title' and 'year' as keys. The function should take the movie array and a filter array as input and return a new array containing only the movies that sati... | ```php
function filterMovies(array $movies, array $filters): array {
if (empty($filters)) {
return $movies;
}
$filteredMovies = $movies;
if (isset($filters['title'])) {
$filteredMovies = array_filter($filteredMovies, function ($movie) use ($filters) {
return stripos($movie[... | magicoder | php |
You are tasked with implementing a version control system for a software project. The system should support the ability to apply a series of transformers to a set of instances of a given type. Each transformer will modify the instances in a specific way. Your task is to write a class method that takes an ID as input, r... | ```typescript
// Implementation of the VersionControlSystem class
class VersionControlSystem<T> {
private generator: (id: number) => T[];
private transformers: ((instances: T[]) => T[])[];
constructor(generator: (id: number) => T[], transformers: ((instances: T[]) => T[])[]) {
this.generator = gene... | magicoder | typescript |
You are tasked with implementing a lock-free concurrent data structure for managing a collection of unique elements. The data structure should support adding, removing, and checking for the presence of elements in a thread-safe manner. To achieve this, you will utilize the `crossbeam-epoch` library, which provides lock... | ```rust
extern crate crossbeam_epoch as epoch;
use epoch::pin;
use std::sync::Arc;
struct ConcurrentSet<T> {
inner: Arc<epoch::Atomic<T>>,
}
impl<T: PartialEq> ConcurrentSet<T> {
fn new() -> Self {
ConcurrentSet {
inner: Arc::new(epoch::Atomic::null()),
}
}
fn insert(&sel... | magicoder | rust |
You are tasked with implementing a file storage system that enforces restrictions on the allowed file extensions. Your task is to create a class `FileStorage` with the following requirements:
- The class should have a method `add_allowed_extension` that takes a single argument `extension` (a string) and adds it to the... | ```python
class FileStorage:
def __init__(self):
self.allowed_extensions = []
def add_allowed_extension(self, extension):
self.allowed_extensions.append(extension)
def store_file(self, file_name, extension):
if extension.lower() not in self.allowed_extensions:
raise Val... | magicoder | python |
You are tasked with implementing a custom exception class and handling the exception in a Python program. The custom exception class should be designed to handle a specific error condition, and the program should demonstrate the usage of this custom exception.
Your task is to create a Python program that simulates a l... | ```python
class UnknownLogKind(Exception):
def __init__(self, value):
message = "Unknown log entry kind %r" % value
super(UnknownLogKind, self).__init__(message)
class NoExtraField(Exception):
pass
def process_log_entry(log_kind, extra_field):
if log_kind not in ["info", "warning", "erro... | magicoder | python |
You are tasked with creating a number guessing game using a Raspberry Pi and its GPIO pins. The game will display a binary number on three LEDs, and the player must press a button to submit their guess. The binary number will be converted to decimal, and the player's guess will be compared to the actual number. If the ... | ```python
import RPi.GPIO as GPIO
# Set up GPIO mode and pins
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT) # LED 1
GPIO.setup(13, GPIO.OUT) # LED 2
GPIO.setup(15, GPIO.OUT) # LED 3
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin
# Global variable to store the correct number
correct_num... | magicoder | python |
You are given a string representing a license file. The license file contains a series of comments and a list of software packages with their respective licenses. Each comment starts with `//` and ends with a newline character. Each software package entry starts with `// *` and ends with `// *`. The software package en... | ```python
def extractLicenses(licenseFile: str) -> dict:
licenses = {}
lines = licenseFile.split('\n')
for line in lines:
if line.startswith('// *'):
package, license_type = line[5:].split(': ')
licenses[package.strip()] = license_type.strip()
return licenses
``` | magicoder | python |
You are tasked with implementing a function that processes a given set of data and returns a specific result based on certain conditions. The function takes in two optional String parameters: `name` and `flag`. The function should return a message based on the following conditions:
- If `name` is not provided, the func... | ```swift
func greet(name: String?, flag: String?) -> String {
if let name = name {
if let flag = flag {
if flag == "friend" {
return "Hello, \(name)! You are my friend."
} else if flag == "enemy" {
return "Hello, \(name)! I don't want to see you."
... | magicoder | swift |
You are tasked with creating a command-line tool that simulates a simple task scheduler. The tool should be able to execute tasks in a specified order and handle dependencies between tasks. Your task is to implement the logic for the task scheduler.
You are given the following code snippet as a starting point:
```bas... | ```python
import sys
def execute_task(task):
print(f"Executing task: {task}")
def main():
args = sys.argv[2:] # Exclude the first two arguments which are script name and 'run'
dependencies = {}
tasks = []
current_task = None
for arg in args:
if arg == "--dependencies":
cu... | magicoder | python |
You are tasked with implementing a function to create an oracle for a quantum computing simulation. The oracle is a crucial component in quantum algorithms, and it is used to encode the problem-specific information into the quantum state. The oracle is created based on a given method, and the user can input a custom st... | ```python
def create_oracle(oracle_method):
oracle_text = {"log": "~A & ~B & C", "bit": "00001000"}
# set the input
num_iterations = 0 # Initialize the number of iterations
print("Enter the oracle input string, such as: " + oracle_text[oracle_method] + "\nOr enter 'def' for a default string.")
orac... | magicoder | python |
You are tasked with implementing a simplified version of a header parsing algorithm for a data processing application. The given code snippet is part of the header parsing process, which involves reading and processing specific sections of the header data.
The header is represented by an array `hz.header` of bytes, an... | ```csharp
// Implementation of the RToken function
int RToken(int min, int max)
{
// Generate a random number within the specified range [min, max]
Random random = new Random();
return random.Next(min, max + 1);
}
// Function to process the entire header
void ProcessHeader()
{
line = 1;
state = 0;
... | magicoder | csharp |
You are working on a deployment script for a software release. The script is responsible for creating and setting permissions for specific directories. The code snippet provided is a part of the deployment script and contains some shell commands.
Your task is to write a function that simulates the behavior of the code... | ```bash
deploy_release() {
RELEASEDIR=$1
RELPART=$2
if [ ! -d $RELEASEDIR ]; then
mkdir -p $RELEASEDIR
chown -R build $RELEASEDIR
fi
DESTDIR=$RELPART/d1
if [ ! -d $DESTDIR ]; then
mkdir -p $DESTDIR
chown -R build $DESTDIR
fi
}
```
The `deploy_release` funct... | magicoder | shell |
You are tasked with creating a Python program to generate a PDF file containing a specific geometric shape. The program should utilize the `reportlab` library to draw the shape and save it as a PDF file. The code snippet provided below is a part of the program that accomplishes this task.
```python
from reportlab.lib.... | ```python
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
import math
def draw_polygon_pdf(sides, radius):
# Create a canvas object
can = canvas.Canvas("shape.pdf", pagesize=letter)
# Calculate the center of the page
center_x = letter... | magicoder | python |
You are tasked with implementing a custom property wrapper in Swift that ensures a given floating-point value falls within a specified range. The property wrapper should validate the input value and, if it falls outside the specified range, return the nearest boundary value. The property wrapper should be used to decor... | ```swift
@propertyWrapper
struct Clamped<T: Comparable> {
var value: T
let min: T
let max: T
init(wrappedValue: T, min: T, max: T) {
self.min = min
self.max = max
self.value = min(max(wrappedValue, min), max)
}
var wrappedValue: T {
get { value }
... | magicoder | swift |
You are tasked with creating a Python class that simulates a simple file management system. The class should handle file operations such as creating, deleting, and searching for files, as well as providing information about the files.
Your task is to implement the `FileManager` class with the following specifications:... | ```python
from datetime import datetime
import errno
class FileManager:
def __init__(self):
self.files = {}
def create_file(self, name: str):
self.files[name] = datetime.now()
def delete_file(self, name: str):
if name in self.files:
del self.files[name]
else:
... | magicoder | python |
You are tasked with creating a function that parses a given TypeScript interface and returns the number of GitHub stars associated with the interface name. The GitHub stars are denoted by the placeholder `<gh_stars>` followed by the number of stars. The function should take the TypeScript interface as input and return ... | ```typescript
function getGitHubStars(interfaceString: string): number {
const starRegex = /<gh_stars>(\d+)/;
const match = interfaceString.match(starRegex);
if (match) {
return parseInt(match[1]);
} else {
return 0; // Return 0 if no stars are found
}
}
``` | magicoder | typescript |
You are working on a computer graphics project and need to implement a rendering function that can handle different rendering modes. The rendering function takes a list of rendering modes and a set of hidden parameters, and it should render all the instances in the renderer and read the output from the framebuffer into... | ```python
import torch
class Renderer:
def __init__(self, width, height):
self.width = width
self.height = height
self.color_tex_3d = None # Assume this is initialized elsewhere
self.pc_tensor = torch.zeros((width, height)) # Assume this is initialized elsewhere
def map_tenso... | magicoder | python |
You are tasked with creating a Python class to retrieve the market capitalization of a cryptocurrency on a specific date using the CoinGecko API. Your class should include a method `get_market_cap_by_date` that takes three parameters: `coingecko_id` (the unique identifier of the cryptocurrency), `date` (the date for wh... | ```python
import requests
import datetime
import logging
COIN_GECKO_BASE_URL = 'https://api.coingecko.com/api/v3/'
class CryptoData:
@staticmethod
def get_market_cap_by_date(coingecko_id, date, currency):
date_string = date.strftime('%d-%m-%Y')
url = COIN_GECKO_BASE_URL + 'coins/' + coingecko_... | magicoder | python |
You are tasked with implementing a color class in Python that supports the representation and manipulation of colors in the HSB (Hue, Saturation, Brightness) color model. The HSB color model is a cylindrical-coordinate representation of colors, where the three parameters Hue, Saturation, and Brightness are used to defi... | ```python
class Color:
def __init__(self, hue=0, saturation=0, brightness=0):
self.hue = hue
self.saturation = saturation
self.brightness = brightness
def set_hue(self, hue):
self.hue = hue
def get_hue(self):
return self.hue
def set_saturation(self, saturation)... | magicoder | python |
You are tasked with creating a Python class for word vector analysis. The class should be able to load pre-trained word vectors, perform various operations on word vectors, and evaluate the accuracy of the word vectors using a specific dataset.
Your task is to implement the `WordVectorAnalyzer` class with the followin... | ```python
from gensim.models import KeyedVectors
class WordVectorAnalyzer:
def __init__(self):
self.word_vectors = None
def load_vectors(self, file_path):
self.word_vectors = KeyedVectors.load_word2vec_format(file_path, binary=False)
def find_similar_words(self, word):
if self.wor... | magicoder | python |
You are tasked with implementing a function that takes in a list of strings representing words and returns a dictionary containing the frequency of each unique word in the list. The function should ignore case sensitivity, treating "Word" and "word" as the same word. Additionally, any non-alphabetic characters should b... | ```python
from typing import List, Dict
import re
def word_frequency(words: List[str]) -> Dict[str, int]:
word_count = {}
for word in words:
# Remove non-alphabetic characters and convert to lowercase
cleaned_word = re.sub(r'[^a-zA-Z]', '', word).lower()
if cleaned_word:
wor... | magicoder | python |
You are tasked with creating a unit test for a component in an Angular application. The component, `RegisterCityComponent`, is responsible for handling the registration of cities. The test framework being used is Jasmine with Angular's TestBed and ComponentFixture.
Your goal is to write a unit test that ensures the pr... | ```typescript
describe('RegisterCityComponent', () => {
let component: RegisterCityComponent;
let fixture: ComponentFixture<RegisterCityComponent>;
let cityService: CityService; // Assuming CityService is the service for city registration
beforeEach(async(() => {
TestBed.configureTestingModule({
decl... | magicoder | typescript |
You are tasked with creating a Python function that processes a given text file to extract and count the occurrences of unique words. The function should read the contents of the file, tokenize the words, and then return a dictionary containing each unique word as a key and its frequency as the corresponding value.
Yo... | ```python
def count_unique_words(file_path):
word_freq = {}
with open(file_path, 'r') as file:
content = file.read()
words = content.lower().split() # Convert to lowercase and tokenize
for word in words:
word = word.strip('.,') # Remove punctuation
if word:
... | magicoder | python |
You are tasked with creating a Python program to interact with a SQLite database containing information about genes. The database has a table named "Genes" with two columns: "gid" (gene ID, primary key) and "name" (gene name). Your program should provide functionality to insert new gene records, retrieve gene informati... | ```python
import sqlite3
# Connect to the SQLite database
conn = sqlite3.connect('genes.db')
cursor = conn.cursor()
# Create the Genes table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS Genes
(
gid TEXT PRIMARY KEY,
name TEXT
);
''')
# Function to insert a new gene re... | magicoder | python |
You are tasked with implementing a rating system for a sports league using the Elo rating system. The Elo rating system is a method for calculating the relative skill levels of players in two-player games such as chess. In this problem, we will adapt the Elo rating system for a team-based sports league.
The Elo rating... | ```python
def calculate_new_rating(old_rating: float, result: float, opponent_rating: float, k_factor: float) -> float:
team_quotient = 10 ** (old_rating / 400)
opponent_quotient = 10 ** (opponent_rating / 400)
expected_result = team_quotient / (team_quotient + opponent_quotient)
new_rating = old_ratin... | magicoder | python |
You are tasked with implementing a lazy initialization mechanism for a service in a Swift application. The lazy initialization should ensure that the service is only instantiated when it is first accessed and then reused for subsequent accesses. You are provided with a code snippet that demonstrates the lazy initializa... | ```swift
// Define a generic Lazy class to encapsulate lazy initialization logic
class Lazy<T> {
private let initializer: () -> T
private var value: T?
init(initializer: @escaping () -> T) {
self.initializer = initializer
}
// Access the service, ensuring it is lazily initialized and reuse... | magicoder | swift |
You are tasked with creating a Python class that implements the Observer design pattern. The Observer pattern is a behavioral design pattern where an object (known as the subject) maintains a list of its dependents (observers) and notifies them of any state changes, usually by calling one of their methods. Your task is... | ```python
class Subject:
def __init__(self):
self.observers = []
def addObserver(self, observer):
if observer not in self.observers:
self.observers.append(observer)
def removeObserver(self, observer):
if observer in self.observers:
self.observers.remove(obse... | magicoder | python |
You are given two integer arrays, `nums1` and `nums2`, representing two sequences of numbers. A line connecting two numbers in the sequences is called an "uncrossed line" if the line does not intersect any other line. Your task is to find the maximum number of uncrossed lines that can be drawn between the two sequences... | ```java
public class Solution {
public int maxUncrossedLines(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (num... | magicoder | java |
You are tasked with implementing a Python class to calculate and store shipping charges, including tax details. The class `ShippingCharge` has the following attributes and methods:
Attributes:
- `is_tax_known`: a boolean indicating whether the tax information is known for the shipping charge.
- `excl_tax`: a decimal r... | ```python
from decimal import Decimal as D
class TaxationDetail:
def __init__(self, authority_name):
self.authority_name = authority_name
class ShippingComponent:
def __init__(self):
self.taxation_details = []
class ShippingCharge:
def __init__(self):
self.is_tax_known = False
... | magicoder | python |
You are tasked with creating a Python function that simulates a simplified version of the `open` function for file handling. Your function, `custom_open`, should take a file path and a mode as input and return a file object. The mode can be one of the following: "r" for reading, "w" for writing, or "a" for appending. I... | ```python
def custom_open(file_path, mode):
if mode not in ["r", "w", "a"]:
raise ValueError("Invalid mode. Mode must be 'r', 'w', or 'a'.")
if mode == "r":
try:
file_obj = open(file_path, "r")
return file_obj
except FileNotFoundError:
raise FileNotFo... | magicoder | python |
You are tasked with implementing a Long Short-Term Memory (LSTM) neural network for time series prediction. The LSTM class is provided with a configuration file "settings.ini" that contains all the necessary hyperparameters and settings for the LSTM model. Your goal is to complete the implementation by defining the LST... | ```python
import configparser
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Dense
class LSTM:
def __init__(self, settings_file):
self.settings_file = settings_file
def run_on_datasets(self):
# Load settings from the configuration file... | magicoder | python |
You are given a string `reg` which represents a regular expression pattern. Your task is to write a function `match_pattern` that takes a list of strings and returns a new list containing only the strings that match the given regular expression pattern.
The regular expression pattern `reg` can contain the following sp... | ```python
import re
from typing import List
def match_pattern(reg: str, strings: List[str]) -> List[str]:
pattern = re.compile(reg)
return [s for s in strings if pattern.match(s)]
reg = "a.*b"
strings = ["apple", "abc", "abacus", "banana", "cab"]
print(match_pattern(reg, strings)) # Output: ["apple", "abacus... | magicoder | python |
You are working on a compiler optimization tool that analyzes Swift code. Your task is to implement a part of the tool that identifies and optimizes unnecessary borrow and copy operations in the code.
Given the following Swift code snippet:
```swift
// CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]]
// CHECK: s... | ```swift
func optimizeBorrowAndCopy(codeSnippet: String) -> String {
// Regular expression to match the unnecessary borrow and copy operations
let pattern = #"// CHECK:.*copy_value.*\n// CHECK:.*store.*\n// CHECK:.*end_borrow.*\n"#
// Replace unnecessary borrow and copy operations with an empty string
... | magicoder | swift |
You are tasked with implementing a function that manipulates a binary search tree (BST). A binary search tree is a data structure in which each node has at most two child nodes, referred to as the left child and the right child. For each node, all elements in its left subtree are less than the node, and all elements in... | ```java
public class BST {
private Node root;
public void insert(int value) {
root = insertRec(root, value);
}
private Node insertRec(Node root, int value) {
if (root == null) {
root = new Node(value);
return root;
}
if (value < root.value) {
... | magicoder | java |
You are tasked with implementing a class-based interface for generating alternate names for command-line options. The interface `IPropertyOptionAlternateNameGenerator` defines the contract for generating alternate names for options represented by properties.
Your task is to create a class that implements the `IPropert... | ```csharp
using System;
using System.Collections.Generic;
using System.Reflection;
namespace YourNamespace
{
public class CustomPropertyOptionAlternateNameGenerator : IPropertyOptionAlternateNameGenerator
{
public List<string> GetAlternateNames(PropertyInfo propertyInfo)
{
List<stri... | magicoder | csharp |
You are tasked with implementing a PermissionFragmentFactory class that manages the creation and retrieval of permission fragments in an Android application. The factory should ensure that only one instance of each type of permission fragment is created and reused when requested.
The PermissionFragmentFactory class sh... | ```java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import java.util.HashMap;
import java.util.Map;
public class PermissionFragmentFactory {
private static final String FRAGMENT_TAG = "permission_fragment_tag";
priv... | magicoder | java |
You are working on a secure messaging application that requires the use of digital certificates for encryption and decryption. Your task is to implement a function that fetches a specific certificate from a given set of certificates and returns its encoded value.
You are given a code snippet that includes a function c... | ```swift
func fetch(with identifier: String, from certificates: [String: String]) throws -> String {
guard let encodedValue = certificates[identifier] else {
throw CertificateError.certificateNotFound
}
return encodedValue
}
enum CertificateError: Error {
case certificateNotFound
}
```
The `fe... | magicoder | swift |
You are tasked with designing a data structure to represent the configuration settings for an S3 File Gateway. The S3 File Gateway is a service that enables on-premises applications to use Amazon Simple Storage Service (S3) storage. Your task is to create a Swift struct that encapsulates the configuration settings for ... | ```swift
struct CacheAttributes {
// Define the properties and methods for CacheAttributes if not already defined
}
struct S3FileGatewayConfig {
let auditDestinationARN: String?
let bucketRegion: String?
let cacheAttributes: CacheAttributes?
let clientList: [String]?
let clientToken: String
... | magicoder | swift |
You are tasked with implementing a simplified version of a tensor operation called MTTKRP (Matrix-Vector Tensor Contraction along a specified mode) using C++.
MTTKRP is a fundamental operation in tensor computations, and it involves multiplying a tensor by a matrix along a specified mode to produce a new tensor. In th... | ```cpp
#include <vector>
std::vector<int> MTTKRP(const std::vector<std::vector<std::vector<int>>>& tensor, const std::vector<std::vector<int>>& matrix, int mode) {
int I = tensor.size();
int J = tensor[0].size();
int K = tensor[0][0].size();
int R = matrix[0].size();
std::vector<int> result(I, 0);... | magicoder | cpp |
You are working on a project that involves processing a dataset of images of playing cards. The dataset is stored in a pandas DataFrame called `data_df`, which has the following columns:
- "image_id": a unique identifier for each image
- "categories": a list of categories (e.g., "hearts", "diamonds", "clubs", "spades")... | ```python
import pandas as pd
def create_validation_dataset(data_df):
test_df = pd.DataFrame()
unique_cards = data_df["categories"].drop_duplicates().head(15) # Get the first 15 unique card categories
for i in range(15):
temp = data_df.loc[
data_df["categories"].apply(
... | magicoder | python |
You are given a list of items, each with a specific weight and value. Your task is to write a function to determine the maximum value that can be obtained by selecting a subset of the items to fit into a knapsack of a given capacity. The function should take the list of item weights, item values, and the knapsack capac... | ```python
def knapsack_max_value(weights, values, capacity):
n = len(values)
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
for i in range(n + 1):
for w in range(capacity + 1):
if i == 0 or w == 0:
dp[i][w] = 0
elif weights[i - 1] <= w:
... | magicoder | python |
You are tasked with creating a TypeScript type definition generator for a given set of function declarations. The input will be an array of function declarations, each containing the function name and its parameters. Your goal is to write a function that takes this input and generates a TypeScript type definition for t... | ```typescript
interface FunctionDeclaration {
kind: string;
name: string;
parameters: Array<FunctionParameter>;
}
interface FunctionParameter {
name: string;
type: string;
}
function generateTypescriptType(declarations: Array<FunctionDeclaration>): string {
const result: Array<string> = [];
for (const ... | magicoder | typescript |
You are tasked with implementing a file processing class in Python that handles writing sensor and weather data to CSV files. The class, `FileProcessor`, has an `__init__` method to initialize the file name, file path, and rotation location. It also has a `write_to_csv` method to write data to the CSV file. The `write_... | ```python
import csv
from datetime import date
import os
class FileProcessor:
counter = 0
fieldnames = ['sensor_data', 'weather_data'] # Example field names for the CSV file
def __init__(self, file_name, file_path):
self.file_name = file_name
self.file_path = file_path
self.rotate... | magicoder | python |
You are tasked with implementing a graph algorithm to find the maximum clique size and number of edges in a given graph. A clique in a graph is a subset of vertices such that every two distinct vertices in the clique are adjacent. The number of edges in a graph is the count of unique pairs of vertices that are connecte... | ```python
class Solution:
def __init__(self):
self.max_clique_size = 0
self.number_of_edges = 0
self.assignment = []
def find_max_clique(self, graph):
def is_clique(candidate, graph):
for i in range(len(candidate)):
for j in range(i + 1, len(candidate... | magicoder | python |
You are tasked with implementing a simple encoding and decoding algorithm for a custom data type called `BitVec`. The `BitVec` type represents a vector of bits, and it supports encoding and decoding operations. The encoding process converts a value of a specific type into a bit vector, while the decoding process conver... | ```rust
use bitvec::prelude::*;
struct BitVec<Endian, T> {
endianness: Endian,
value: T,
}
impl<Endian, T> BitVec<Endian, T>
where
Endian: BitOrder,
T: BitStore,
{
fn encode(&self) -> BitVec<Msb0, T> {
let mut bits = BitVec::new();
bits.extend_from_slice(self.value.as_bitslice::<En... | magicoder | rust |
You are tasked with implementing a generic data structure that supports storing elements of any type and provides a handle to access and manipulate these elements. The provided code snippet defines the public interface of the data structure, specifying the element type and the handle type.
Your task is to implement th... | ```cpp
#include <unordered_map>
template <typename ElemT, typename HandleT>
class GenericDataStructure {
public:
using ElementType = ElemT;
using HandleType = HandleT;
private:
std::unordered_map<HandleType, ElementType> data;
public:
// Adds an element to the data structure and returns a handle to t... | magicoder | cpp |
You are tasked with creating a program to implement a custom k-fold cross-validation for a machine learning model. The program should read a CSV file containing training data, split the data into k folds, and assign fold numbers to each row in the dataset. The program should use the StratifiedKFold method from the scik... | ```python
import os
import pandas as pd
from sklearn.model_selection import StratifiedKFold
def custom_kfold_cv(file_path, target_column, k, seed):
# Read the CSV file into a pandas DataFrame
df = pd.read_csv(file_path, sep='\t')
# Initialize fold columns with -1
for i in range(k):
df[f'kfold_... | magicoder | python |
You are working on a network security application that needs to handle various types of data and network configurations. The given code snippet defines several constants using bitwise left shift operations. These constants are used to represent different data types, file types, and network configurations. Your task is ... | ```python
from typing import List
def parse_flags(flags: int) -> List[str]:
flag_descriptions = {
1 << 0: "IPv4 Mapping",
1 << 1: "IPv6 Mapping",
1 << 2: "Blacklist File",
1 << 7: "Binary Data",
1 << 2: "Tree Data",
1 << 3: "String Data",
1 << 4: "Small Integ... | magicoder | python |
You are given a string containing a series of paragraphs. Each paragraph contains sentences with placeholders denoted by `<NAME>`. Your task is to write a program to replace these placeholders with actual names provided in a separate list. If a placeholder appears multiple times in a paragraph, all occurrences should b... | ```python
def replace_names(paragraphs, names):
for i in range(len(paragraphs)):
for name in names:
paragraphs[i] = paragraphs[i].replace("<NAME>", name)
return paragraphs
input_string = """
<p>However Mary, who splits her time between the UK and Canada, has called their late mother a 'love... | magicoder | python |
You are tasked with implementing a command-line tool for managing software releases. The tool uses a library called `release_plz_core` to perform various release-related operations. The code snippet provided is a part of the command processing logic for this tool. Your task is to understand the code and design a data s... | ```rust
// Define the data structure for representing the command-line arguments
struct UpdateRequest {
// Define fields to capture the necessary information for the update command
// Example fields: version: String, changes: Vec<String>, author: String, etc.
}
struct ReleasePrRequest {
github: GithubSetti... | magicoder | rust |
You are tasked with creating a Python function that generates a unique hostname and starts a Docker container with specific configurations. The function should take two parameters: a string `name` and an integer `uid`. The `format_hostname` function is provided to format the hostname based on the input parameters. The ... | ```python
import common
import docker
def start_nfs_container(name, uid):
# Format the hostname using the provided function
hostname = common.format_hostname([name.replace('/', '-').strip('-'), 'nfs'], uid)
# Define the local path and Docker image
path = "/localpath" # Replace with the actual loc... | magicoder | python |
You are given a sequence of integers representing the values of elements in a game. The goal is to maximize the sum of selected elements subject to certain constraints. The constraints are as follows:
1. You can't select two consecutive elements.
2. If you select an element, you can't select the next element.
3. If the... | ```python
def maxSumWithConstraints(arr):
n = len(arr)
maxSum = [0] * n
sols = [[] for _ in range(n)]
for i in range(n - 1, -1, -1):
if i == n - 1:
maxSum[i] = arr[i]
sols[i] = [arr[i]]
elif i == n - 2:
maxSum[i] = max(arr[i], arr[i + 1])
... | magicoder | python |
You are tasked with implementing a quantum algorithm to solve a specific type of optimization problem. The problem involves creating a quantum oracle and using Grover's algorithm to find the optimal solution. The code snippet provided initializes the quantum oracle, sets up the Grover algorithm, selects a backend for q... | ```python
from qiskit.aqua.algorithms import Grover
from qiskit.aqua import QuantumInstance
from qiskit import BasicAer
def run_quantum_algorithm(oracle_cls, simulator, mct_mode):
if oracle_cls == TTO:
optimization = 'qm-dlx'
else:
optimization = 'espresso'
oracle = oracle_cls(input, o... | magicoder | python |
You are tasked with implementing a function that converts a color from the RGB (Red, Green, Blue) color space to the HSV (Hue, Saturation, Value) color space. The RGB color space represents colors using the intensities of red, green, and blue, while the HSV color space represents colors using their hue, saturation, and... | ```javascript
class Hsv {
constructor({ h, s, v }) {
this.h = h;
this.s = s;
this.v = v;
}
}
function rgbToHsv(rgbColor) {
const r = rgbColor.r / 255;
const g = rgbColor.g / 255;
const b = rgbColor.b / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const delta = max - m... | magicoder | javascript |
You are tasked with implementing a Python class to manage a history graph for composing tasks. The class, `ComposingHistoryGraph`, should be designed using the `dataclass` decorator and should have the following attributes:
- `uid` (str): A unique identifier for the history graph.
- `dataset_name` (str): The name of th... | ```python
from dataclasses import dataclass
@dataclass
class ComposingHistoryGraph:
uid: str
dataset_name: str
task_name: str
is_finished: bool
nodes: list
def add_node(self, node):
self.nodes.append(node)
def finish_task(self):
self.is_finished = True
```
In this solution... | magicoder | python |
You are given a list of integers representing the daily stock prices of a company. Your task is to write a function that calculates the maximum profit that can be obtained by buying and selling the stock on different days. However, you are only allowed to make at most one transaction (i.e., buy one and sell one share o... | ```python
from typing import List
def maxProfit(prices: List[int]) -> int:
if not prices:
return 0
max_profit = 0
min_price = prices[0]
for price in prices:
if price < min_price:
min_price = price
else:
max_profit = max(max_profit, price - min_p... | magicoder | python |
You are tasked with creating a program that reads a series of integers from an input file, performs a specific operation on each integer, and then writes the results to an output file. The operation to be performed on each integer is as follows: if the integer is even, it should be divided by 2; if the integer is odd, ... | ```cpp
#include <iostream>
#include <fstream>
void performOperation(int n, std::ofstream& output) {
while (n != 1) {
output << n << " ";
if (n % 2 == 0) {
n /= 2;
} else {
n = 3 * n + 1;
}
}
output << "1" << std::endl << "Lie absolutely" << std::endl;... | magicoder | cpp |
You are tasked with creating a custom error type in Rust to handle specific error scenarios in a file processing application. Your custom error type should encapsulate different kinds of errors that can occur during file processing, such as file not found, permission denied, or invalid file format. Additionally, you ne... | ```rust
use std::error;
use std::fmt;
// Define the custom error type
#[derive(Debug, Clone)]
enum FileError {
FileNotFound,
PermissionDenied,
InvalidFileFormat,
}
// Implement the std::error::Error trait for FileError
impl fmt::Display for FileError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Res... | magicoder | rust |
You are tasked with creating a word guessing game in Python. The game will randomly select a word from a predefined list, and the player must guess the letters of the word within a limited number of attempts. The player will be provided with a partially completed word, and they must guess the remaining letters to compl... | ```python
def guess_word(guessed_word: str, random_word: str, attempts: int) -> str:
for char in range(len(random_word)):
if guessed_word[char] == "_":
guess = input("Guess a letter: ")
if guess.upper() == random_word[char].upper():
guessed_word = guessed_word[:char] ... | magicoder | python |
You are given a code snippet that is part of a function. Your task is to complete the function by implementing the missing logic. The function takes an array of integers as input and is expected to return a modified array based on certain conditions.
The function signature is as follows:
```python
def process_array(ar... | ```python
from typing import List
def process_array(arr: List[int]) -> List[int]:
modified_arr = []
if not arr: # Check if the input array is empty
return modified_arr # Return an empty array if input is empty
else:
for num in arr:
if num % 2 == 0: # If the number is even
... | magicoder | python |
You are tasked with creating a program that analyzes a given TypeScript file to extract information about the imported modules. Your program should be able to identify the imported modules and count the occurrences of each module. For the purpose of this problem, you can assume that the TypeScript file follows the Angu... | ```javascript
function analyzeImports(fileContent) {
const importRegex = /import\s*{\s*([^}]*)\s*}\s*from\s*['"]([^'"]*)['"]/g;
let imports = {};
let match;
while ((match = importRegex.exec(fileContent)) !== null) {
const importedModules = match[1].split(',').map(module => module.trim());
const importP... | magicoder | javascript |
You are tasked with implementing a constraint solver for a simple layout system. The system uses constraints to position UI elements within a view. Each constraint is defined by a pair of attributes, a relation, and an optional constant. The attributes can be top, bottom, leading, trailing, etc., and the relation can b... | ```swift
struct Constraint {
let attribute: String
let relation: Relation
let constant: CGFloat
}
enum Relation {
case equal
case lessThanOrEqual
case greaterThanOrEqual
}
func resolveConstraints(_ constraints: [Constraint]) -> [String: CGFloat] {
var resolvedValues: [String: CGFloat] = [:... | magicoder | swift |
You are tasked with implementing a secure login system for a web application. The provided code snippet is a part of the login functionality, which includes capturing user login details and authenticating the user session. The code also ensures that the user is accessing the login page over a secure HTTPS connection.
... | ```python
def index():
"""Summary - Default login screen used to capture user login details
and authenticate user session
"""
session['regionaltoken'] = None
if request.headers.get('x-forwarded-proto') != 'https':
secure_url = request.url.replace("http://", "https://")
return redire... | magicoder | python |
You are tasked with creating a function that calculates the distance between two geographical coordinates using the Haversine formula. The Haversine formula is a well-known equation used to calculate the distance between two points on the Earth's surface given their latitude and longitude. The formula is as follows:
\... | ```python
import math
def calculateDistance(lat1, lng1, lat2, lng2):
R = 6371 # Radius of the Earth in kilometers
lat1_rad = math.radians(lat1)
lng1_rad = math.radians(lng1)
lat2_rad = math.radians(lat2)
lng2_rad = math.radians(lng2)
delta_lat = lat2_rad - lat1_rad
delta_lng = lng2_rad - ... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.