query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a Python script that analyzes the distribution of programming languages and operating systems in a given dataset of software packages. The dataset is represented as a list of strings, where each string contains metadata information about a software package. The metadata includes details suc... | ```python
from typing import List, Dict
def analyze_metadata(dataset: List[str]) -> Dict[str, Dict[str, int]]:
language_os_distribution = {}
for data in dataset:
parts = data.split(" :: ")
if len(parts) == 2:
category, value = parts
if category == "Programming Langu... | magicoder | python |
You are tasked with creating a Python program that generates MIDI music using the `midiutil` library and plays the generated music using the `pygame` library. Additionally, the program should utilize the `timidity` software synthesizer to convert the MIDI file to an audio file and play it using the `mpg123` command-lin... | ```python
# Import necessary libraries
from midiutil import MIDIFile
import pygame
import subprocess
# Generate MIDI melody using midiutil
def generate_midi():
degrees = [60, 62, 64, 65, 67, 69, 71, 72] # MIDI note numbers
track = 0
channel = 0
time = 0 # In beats
duration = 1 # In beats
tem... | magicoder | python |
You are tasked with creating a Rust module that handles HTTP header values for various header types. Your goal is to implement the necessary structs and traits to represent and manipulate these header values.
Given the provided code snippet, you need to design and implement the following components:
1. Define a struct... | ```rust
// range_item_header_value.rs
pub struct RangeItemHeaderValue {
// Define the fields and methods for RangeItemHeaderValue
}
// range_condition_header_value.rs
pub struct RangeConditionHeaderValue {
// Define the fields and methods for RangeConditionHeaderValue
}
// entity_tag_header_value.rs
pub struc... | magicoder | rust |
You are tasked with implementing a Python class that manages a menu system for a restaurant. The class should handle customer requests, maintain a log of orders, and track the presence of staff members.
You need to create a class called `Menu` with the following attributes and methods:
Attributes:
- `Requests`: A lis... | ```python
class Menu:
def __init__(self):
self.Requests = []
self.log = {}
self.presences = set()
def add_request(self, request):
self.Requests.append(request)
def add_to_log(self, order_number, order_details):
self.log[order_number] = order_details
def add_pre... | magicoder | python |
You are tasked with implementing a function that calculates the mean of all possible combinations of perturbations for a given set of numbers. A perturbation of a number is defined as adding or subtracting a small value from the number. The function should take a list of numbers as input and return a list of means for ... | ```python
from itertools import product
import numpy as np
def calculate_perturbation_means(numbers, perturbation_value):
perturbations = [[num, num + perturbation_value, num - perturbation_value] for num in numbers]
combinations = list(product(*perturbations))
means = [np.mean(comb) for comb in combinatio... | magicoder | python |
You are tasked with simulating the movement of a character in a 2D grid. The character can move up, down, left, or right within the grid. The grid is represented as a 2D array of integers, where each cell contains a value indicating the cost to move to that cell. The character starts at the top-left corner of the grid ... | ```java
public int minCostPath(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
// Initialize the cost grid with the same dimensions as the input grid
int[][] cost = new int[m][n];
// Fill the cost grid with the minimum cost to reach each cell
cost[0][0] = grid[0][0];
f... | magicoder | java |
You are tasked with implementing a Python function that processes requests based on given keywords. The function should read a key file containing a list of keywords and their corresponding actions, and then handle incoming requests by executing the appropriate action based on the provided keyword.
The key file is for... | ```python
def handle_requests(request_file: str, key_file: str) -> None:
# Read keywords and actions from the key file
keyword_actions = {}
with open(key_file, 'r') as key_file:
for line in key_file:
keyword, action = line.strip().split(': ')
keyword_actions[keyword] = action... | magicoder | python |
You are tasked with implementing a memoizing dynamic Fibonacci number generator in Java. The memoizing dynamic Fibonacci number generator should use a cache to store previously computed Fibonacci numbers to improve performance.
Your task is to complete the implementation of the `generateFibonacciNumber` method in the ... | ```java
import java.math.BigInteger;
import java.util.ArrayList;
public class MemoizingDynamicFibonacciNumberGenerator {
private ArrayList<BigInteger> cache;
public MemoizingDynamicFibonacciNumberGenerator() {
cache = new ArrayList<>();
cache.add(BigInteger.ONE);
cache.add(BigInteger.O... | magicoder | java |
You are tasked with implementing a message processing system using Rust's asynchronous programming features. The system will read JSON messages from a stream, deserialize them, and then print the deserialized messages to the standard output. Your goal is to write a function that takes care of this message processing lo... | ```rust
use futures::stream::StreamExt;
use serde_json::Value;
use tokio::task::JoinHandle;
async fn process_messages<S>(stream: S) -> JoinHandle<()>
where
S: futures::stream::Stream<Item = Result<Vec<u8>, std::io::Error>> + Send + 'static,
{
tokio::task::spawn(async move {
let deserialized = stream
... | magicoder | rust |
You are tasked with creating a Java program that processes data from different types of data units. The program should implement a specific interface and handle exceptions appropriately.
Your task is to create a Java class that implements the `Component` interface from the LinkedPipes ETL framework. The `Component` i... | ```java
import com.linkedpipes.etl.dataunit.core.files.FilesDataUnit;
import com.linkedpipes.etl.dataunit.core.files.WritableFilesDataUnit;
import com.linkedpipes.etl.dataunit.core.rdf.SingleGraphDataUnit;
import com.linkedpipes.etl.executor.api.v1.LpException;
import com.linkedpipes.etl.executor.api.v1.component.Compo... | magicoder | java |
You are tasked with implementing a function to find the shortest path between two nodes in a directed graph. The graph is represented using an adjacency list and each edge has an associated weight. Your function should take the graph, the starting node, and the target node as input and return the shortest path from the... | ```python
import heapq
def shortest_path(graph, start, target):
# Initialize distances to all nodes as infinity except the start node as 0
distances = {node: float('inf') for node in graph}
distances[start] = 0
# Initialize the priority queue with the start node
queue = [(0, start)]
# Ini... | magicoder | python |
You are tasked with implementing a buffer management system for a microcontroller. The buffer is used to store serialized data, and the system needs to handle different block sizes efficiently. The code snippet provided is from a unit test suite for the buffer management system. The `TEST_F` macro is used to define tes... | To solve this problem, you need to implement the `try_array_block_X` functions to process the buffer using array blocks of size X. The implementation should handle different block sizes efficiently and ensure that the buffer management system can handle various block sizes effectively.
Here's an example implementation... | magicoder | python |
You are tasked with implementing a video streaming service that utilizes the HLS (HTTP Live Streaming) protocol to deliver content to users. The service should use the hls.js library to handle the HLS playback. Your goal is to create a function that initializes the HLS player for a given video channel.
You are provide... | ```javascript
import { Channel } from '../../../state';
import Hls from 'hls.js';
function initializeHLSPlayer(channel) {
const videoPlayer = document.getElementById('videoPlayer');
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(channel.videoUrl);
hls.attachMedia(videoPlayer);
hl... | magicoder | javascript |
You are tasked with designing a protocol and a corresponding data structure in Swift to facilitate planned failover operations in a distributed system. The planned failover process involves transitioning the system from its primary state to a secondary state in a controlled manner, typically for maintenance or upgrades... | ```swift
// Define the PlannedFailoverInputProtocol
protocol PlannedFailoverInputProtocol {
var plannedStartTime: Date { get set }
var plannedEndTime: Date { get set }
var failoverType: String { get set }
func initiateFailover()
}
// Implement the PlannedFailoverInputData conforming to the protoco... | magicoder | swift |
You are given a game where you need to guess a number chosen by the system. The system will provide feedback on whether your guess is higher or lower than the chosen number. You need to implement a strategy to efficiently guess the number within a given range.
You are provided with a pre-defined API `guess(int num)` w... | ```python
def guessNumber(n):
left, right = 1, n
while left <= right:
mid = left + (right - left) // 2
result = guess(mid)
if result == 0:
return mid
elif result == -1:
right = mid - 1
else:
left = mid + 1
return -1 # Chosen number... | magicoder | python |
You are tasked with creating a script that will analyze a given directory structure and list all the components present in the directory. The components are defined as subdirectories within the given directory. Your task is to write a Bash script that will achieve this functionality.
Your script should read the absolu... | ```bash
#!/bin/bash
# Get the absolute path of the script
SCRIPT=$(readlink -f $0)
# Absolute path of the directory this script is in
SCRIPT_PATH=$(dirname "$SCRIPT")
# Change to the script's directory
cd "$SCRIPT_PATH"
# List all subdirectories as components
COMPONENTS=$(ls -d */)
# Print the components
echo "$CO... | magicoder | shell |
You are given a list of integers representing the daily stock prices of a company. You need to write a function `maxProfit` to find the maximum profit that can be obtained by buying and selling the stock at most once. If no profit can be made, return 0.
The function should take in the following input:
```
maxProfit(pr... | ```python
def maxProfit(prices):
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_price)
return max_profit
``` | magicoder | python |
You are tasked with creating a Python program that utilizes the Autobahn library to establish a WebSocket connection between a client and a server. The Autobahn library provides the necessary tools for creating WebSocket clients and servers. Your task is to implement the `startClient` and `startServer` functions using ... | ```python
from autobahn.twisted.websocket import connectWS, \
listenWS, \
WebSocketClientFactory, \
WebSocketClientProtocol, \
WebSocketServerFactory, \
... | magicoder | python |
You are tasked with implementing a Python function that calculates the nth Fibonacci number using Cython, a language that makes it easy to write C extensions for Python. Your goal is to create a Cython function that efficiently computes the Fibonacci sequence and then call this function from a Python script.
Your task... | ```python
# fib_cython.pyx
cdef int fib_cython(int n):
if n <= 1:
return n
else:
return fib_cython(n-1) + fib_cython(n-2)
```
```python
# setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("fib_cython.pyx")
)
```
```bash
# Terminal ... | magicoder | python |
You are tasked with creating a program that processes a list of students and their corresponding grades. The program should calculate the average grade for each student and then determine the student with the highest average grade.
You are given a snippet of code that represents the end of an HTML form and a PHP cond... | ```php
function highestAverageGrade($students) {
$highestAverage = 0;
$topStudent = "";
foreach ($students as $name => $grades) {
$average = array_sum($grades) / count($grades);
if ($average > $highestAverage) {
$highestAverage = $average;
$topStudent = $name;
... | magicoder | php |
You are tasked with implementing a Python program to perform Principal Component Analysis (PCA) on a given dataset using the `eofs` library. PCA is a statistical method used to reduce the dimensionality of data while retaining trends and patterns. The `eofs` library provides tools for performing EOF (Empirical Orthogon... | ```python
import numpy as np
from eofs.standard import Eof
def perform_pca(dataset):
# Create an EOF solver to do the EOF analysis
solver = Eof(dataset)
# Retrieve the leading EOF, expressed as the covariance matrix
eofs = solver.eofs(neofs=dataset.shape[1])
# Retrieve the variance fraction
v... | magicoder | python |
You are tasked with implementing a command-line tool that allows users to search and repeat previously executed commands from their shell history. The tool should provide a user-friendly interface for selecting and executing historical commands.
Your task is to implement a function `repeat_history` that takes no argum... | ```bash
repeat_history() {
if [ -n "$ZSH_NAME" ]; then
eval $(fc -l 1 | fzf +s --tac | sed 's/ *[0-9]* *//')
else
eval $(history | fzf +s --tac | sed 's/ *[0-9]* *//')
fi
}
```
The `repeat_history` function first checks if the shell is Zsh by examining the `$ZSH_NAME` environment variable. If it is Zsh, t... | magicoder | shell |
You are working on a secure communication application that requires handling digital certificates. You need to implement a method to generate a manifest JSON object and a representation method for a class. The manifest JSON object should contain specific information about the responder, subject certificate, issuer cert... | ```python
from typing import Mapping
from base64 import b64encode
from uuid import UUID
class CertificateInfo:
def __init__(self, responder, subject, issuer, certificate_chain_uuid, retrieved):
self.responder = responder
self.subject = subject
self.issuer = issuer
self.certificate_c... | magicoder | python |
You are tasked with implementing a class to handle volatile registry keys in a Windows application. The class should provide methods to check for the existence of a volatile key, retrieve the volatile directory, look up a registry key handler, and extract the root from a given directory.
You are provided with the foll... | ```csharp
using Microsoft.Win32;
public class VolatileRegistryHandler
{
// Memory offset: 0x1A37BC0
public static bool VolatileKeyExists(string dir)
{
// Implementation to check for the existence of a volatile key in the specified directory
// ...
}
// Memory offset: 0x1A3672C
... | magicoder | csharp |
You are tasked with implementing a data pruning algorithm for a system that manages objects with associated creation and last seen timestamps. The algorithm should identify and prune objects that meet specific criteria based on their timestamps.
You are given a code snippet from the existing pruning algorithm, which c... | ```python
class DataPruningAlgorithm:
def __init__(self, deletion_threshold):
self._deletion_threshold = deletion_threshold
self._objects = [] # List of objects with creation and last seen timestamps
def prune_objects(self):
to_prune = []
for obj in self._objects:
t... | magicoder | python |
You are tasked with implementing a Swift program that processes outcome values for a healthcare application. The outcome values are represented by the `OutcomeValues` enum, which contains cases for different types of outcomes. Each case has an associated value that represents the actual outcome value.
The `OutcomeValu... | ```swift
func processOutcome(_ outcome: OutcomeValues) -> String {
switch outcome {
case .bloodPressure(let systolic, let diastolic):
return "Systolic: \(systolic), Diastolic: \(diastolic)"
case .heartRate(let bpm):
return "Heart Rate: \(bpm) bpm"
case .temperature(let celsius):
... | magicoder | swift |
You are tasked with creating a program to classify fruits based on their features using a decision tree classifier. The features include the mass, width, and height of the fruits. You are provided with a dataset that has been preprocessed and split into training and testing sets. Your goal is to train a decision tree c... | ```python
import numpy as np
from sklearn.model_selection import train_test_split
# Define the preprocess function to load and preprocess the fruit dataset
def preprocess():
# Load the fruit dataset
# Assume the dataset is stored in a file named 'fruits.csv' with the following format:
# Mass,Width,Height,L... | magicoder | python |
You are tasked with creating a web application that allows users to edit and update contributor details. The application uses the BForms library, which provides a set of helper methods for generating HTML elements. The code snippet provided is a partial view for displaying contributor details and includes a glyphicon f... | To implement the functionality for editing and updating contributor details using ASP.NET MVC and the BForms library, you can follow the steps outlined below:
1. Create a controller action to handle the editing and updating of contributor details.
```csharp
public ActionResult Edit(int contributorId)
{
... | magicoder | csharp |
You are given a string. Your task is to write a function to find the index of the first non-repeating character in the string. If there are no non-repeating characters, return -1.
For example:
- Given the input "leetcode", the output should be 0, as the first non-repeating character is 'l' at index 0.
- Given the inpu... | ```python
def firstUniqChar(s: str) -> int:
char_count = {}
# Count occurrences of each character
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# Find the first non-repeating character
for i, char in enumerate... | magicoder | python |
You are tasked with creating a Python function to extract workshop information from a given URL. The function should retrieve specific details about the workshop, such as its name, organizer, description, day, location, and link. Additionally, the function should handle potential connection errors when attempting to ac... | ```python
import urllib.request as request
from urllib.error import URLError
def extract_workshop_info(url):
workshop_dummy = {attribute: None for attribute in
["workshop_name", "workshop_organizer", "workshop_description", "workshop_day",
"workshop_location", "workshop... | magicoder | python |
You are given a list of integers representing the daily stock prices of a company. Your task is 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 two transactions.
Create a function `maxProfitTwo... | ```python
def maxProfitTwoTransactions(prices: List[int]) -> int:
n = len(prices)
if n < 2:
return 0
# Initialize variables to store the maximum profit after the first and second transactions
first_buy = second_buy = float('inf')
first_profit = second_profit = 0
for price in prices:
... | magicoder | python |
You are tasked with creating a program that simulates a simplified version of a command-line interface for managing tasks. The program should allow users to add, list, and remove tasks. Additionally, users should be able to set environment variables and execute commands within a specified directory.
Your task is to im... | ```python
import os
import subprocess
tasks = []
def add_task(task):
tasks.append(task)
print("Task added successfully.")
def list_tasks():
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task}")
def remove_task(index):
if 1 <= index <= len(tasks):
del tasks[index - 1]
... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple text-based adventure game. The game involves navigating through different rooms, picking up items, and using those items to solve puzzles. Your task is to create a class called `AdventureGame` that provides methods for moving between rooms, picking... | ```python
class AdventureGame:
def __init__(self, initial_room):
self.current_room = initial_room
self.inventory = {}
self.rooms = {}
def move(self, direction):
directions = {'north', 'south', 'east', 'west'}
if direction not in directions:
raise ValueError("... | magicoder | python |
You are tasked with implementing a Python function that performs gradient descent optimization to find the minimum of a given function. The function takes as input the initial guess for the minimum, the learning rate, the maximum number of iterations, and the function to be minimized. The function should return the est... | ```python
def gradient_descent(x0, learning_rate, max_iterations, objective_function):
xks = [x0]
it = 0
while it < max_iterations:
xk = xks[-1]
gradient = (objective_function(xk + 0.0001) - objective_function(xk)) / 0.0001 # Approximate gradient
xk -= learning_rate * gradient
... | magicoder | python |
You are tasked with creating a script to validate and retrieve specific properties from configuration files. The script should read a configuration file, remove comments, and extract the value of a specified property. The property name may contain special characters, and the script should handle them appropriately. Add... | ```bash
#!/bin/bash
get_property_value() {
local file="$1"
local property="$2"
local url="$3"
local escaped_property="${property//./\\.}" # Escape special characters in property name
if [ -f "${file}" ]; then
# Remove comments and print property value
sed -E '/^[[:blank:]]*\#/d' ... | magicoder | shell |
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should ignore punctuation and consider words with different capitalizations as the same word. The program should then output the word count for each unique word in alphabetical order.
For exa... | ```python
import string
def count_word_occurrences(file_name):
word_count = {}
with open(file_name, 'r') as file:
for line in file:
for word in line.split():
word = word.lower().strip(string.punctuation)
if word:
word_count[word] = word_co... | magicoder | python |
You are tasked with implementing a function to parse a raw data stream in a C++ class. The class `req` contains a method `__parse_raw()` which is responsible for parsing the raw data. The method has access to several member variables such as `_raw_len`, `_raw_readed_len`, `_stat`, `_buf_pos`, and `_buf_avail_size`. Add... | ```cpp
void req::__parse_raw() {
if (this->_raw_len == this->_raw_readed_len) {
this->_stat = rwg_web::req_stat::req_stat_end;
return;
}
while (this->_raw_readed_len < this->_raw_len) {
if (this->_buf_pos == this->_buf_avail_size) {
this->__load();
}
// A... | magicoder | cpp |
You are tasked with creating a program that processes student grades and calculates the average grade for a given set of students. The program should prompt the user to input the grades for each student and then calculate and display the average grade for the entire class.
The program should follow these specification... | ```python
def calculate_average_grade():
num_students = int(input("Enter the number of students: "))
total_grade = 0
for i in range(num_students):
grade = float(input(f"Enter the grade for student {i+1}: "))
total_grade += grade
average_grade = total_grade / num_students
print(f"Th... | magicoder | python |
You are tasked with implementing a Swift extension for the URL type to create a URL safely from a static string. The extension should handle any special characters in the input string and ensure that the resulting URL is valid and properly encoded.
Your task is to complete the implementation of the `URL` extension by ... | ```swift
public extension URL {
/// URL safe constructor from a static string
init?(safeInit string: String) {
guard let encodedString = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
return nil
}
if let url = URL(string: encodedString) ... | magicoder | swift |
You are tasked with creating a sentiment analysis tool for stock market data using Python. The sentiment analysis tool will utilize two APIs: `deeptrade.sentiment` for sentiment analysis and `deeptrade.stocks` for accessing stock data. The sentiment analysis API provides functions for analyzing the sentiment of text da... | ```python
# API sentiment
from deeptrade.sentiment import *
# API stocks
from deeptrade.stocks import *
def average_sentiment_score(stock_symbol, start_date, end_date):
# Retrieve news articles related to the stock_symbol within the specified date range
news_articles = deeptrade.stocks.get_news(stock_symbol, s... | magicoder | python |
You are tasked with implementing a file import dispatcher for a contact management system. The system uses a `ContactFileParser` class to determine the appropriate parser for different file types. Your goal is to complete the `dispatch_import_task` function, which takes an import task, a request, a group, and an option... | ```python
from go.contacts import utils
from go.contacts.parsers import ContactFileParser
class ContactImportException(Exception):
"""
Exception raised when an import handler determines that an import cannot
succeed.
"""
def dispatch_import_task(import_task, request, group, check_fields=None):
fil... | magicoder | python |
You are tasked with creating a program that reads a text file and counts the occurrences of each word in the file. Your program should ignore punctuation and consider words with different capitalization as the same word. You should then output the unique words along with their respective counts in alphabetical order.
... | ```python
import re
def count_word_occurrences(file_path):
word_counts = {}
with open(file_path, 'r') as file:
text = file.read()
words = re.findall(r'\b\w+\b', text.lower())
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
... | magicoder | python |
You are tasked with creating a program to validate a binary password. The binary password is represented as a string of 0s and 1s. The validation rules for the binary password are as follows:
1. The length of the binary password must be a multiple of 8.
2. The binary password must contain at least one occurrence of the... | ```python
def validate_binary_password(binary_password):
if len(binary_password) % 8 != 0:
return False
if "101" not in binary_password or "010" not in binary_password:
return False
return True
# Test cases
print(validate_binary_password("1010101001010101")) # Output: True
print(validate_b... | magicoder | python |
You are tasked with implementing a function that will parse an HTML document and count the number of nested HTML elements within a specific tag. The function should take in the HTML document as a string and the tag name as a parameter, and return the count of nested elements within the specified tag.
For example, give... | ```python
from html.parser import HTMLParser
class TagCounter(HTMLParser):
def __init__(self, tag_name):
super().__init__()
self.tag_name = tag_name
self.count = 0
self.inside_target_tag = False
def handle_starttag(self, tag, attrs):
if tag == self.tag_name:
... | magicoder | python |
You are tasked with implementing a function that processes text to resolve coreferences, which are words or phrases that refer to other words or phrases within the same text. The function should take in a text string and an optional boolean parameter `no_detail`, which defaults to `False`. If `no_detail` is `True`, the... | ```python
import urllib.request
import urllib.parse
def coref(text, no_detail=False):
base_uri = "https://example.com/coref?text="
encoded_text = urllib.parse.quote(text, safe='')
if no_detail:
query_param = '&no_detail=1'
else:
query_param = ''
raw_data = get_raw_data_from_web(ba... | magicoder | python |
You are working on a web application that involves handling database operations for a multilingual content management system. The code snippet provided represents an array configuration used for managing database fields in different contexts. Each array contains a set of fields relevant to a specific database operation... | ```php
function generateSQLQueries($config) {
$tableName = 'your_table_name';
$selectboxfields = implode(',', $config['selectboxfields']);
$displayfields = implode(',', $config['displayfields']);
$insertfields = implode(',', $config['insertfields']);
$selectQuerySelectBox = "SELECT $selectboxfields... | magicoder | php |
You are tasked with implementing a stack-based virtual machine for a simple programming language. The virtual machine has three stacks: `StackStoredLocals`, `Stack`, and `FloatingPointStack`. The `StackStoredLocals` stack is used to store local variables, the `Stack` stack is used for general operations, and the `Float... | ```csharp
using System;
using System.Collections.Generic;
public class LocalDefinition
{
// Define LocalDefinition properties and methods
}
public interface IAnalysedOperand
{
// Define IAnalysedOperand properties and methods
}
public class VirtualMachine
{
public Dictionary<int, LocalDefinition> StackSt... | magicoder | csharp |
You are working on a web application that manages documents and questionnaires. The application uses Django and has a set of URL patterns defined in the `urls.py` file as shown in the code snippet below:
```python
path('<int:pk>/document/create/', DocumentCreateView.as_view(), name='document-create'),
path('<int:pk>/q... | ```python
from django.views.generic import CreateView, DetailView, DeleteView, UpdateView
from .models import Document, Questionnaire
class DocumentCreateView(CreateView):
model = Document
fields = ['title', 'content']
class QuestionaireCreate(CreateView):
model = Questionnaire
fields = ['title', 'des... | magicoder | python |
You are tasked with implementing a token encoding and decoding system for managing attachments in a web application. The system should generate a token based on the user's UUID, customer information, and the type of attachment. Additionally, the system should be able to decode the token and validate its integrity.
The... | ```python
import hashlib
from datetime import datetime, timedelta
from freezegun import freeze_time
from django.core.exceptions import ValidationError
def encode_attachment_token(user_uuid, customer, attachment_type):
# Concatenate user UUID, customer information, and attachment type
token_data = f"{user_uuid}... | magicoder | python |
You are tasked with creating a Python program that utilizes the `infi.systray` library to build a system tray icon application. The program should allow the user to encrypt and decrypt sensitive information using the `traylert.traylert_crypto` module. The encryption and decryption functionality should be accessible thr... | ```python
import tkinter as tk
from infi.systray import SysTrayIcon
from traylert.traylert_crypto import encrypt, decrypt
def on_quit_callback(systray):
systray.shutdown()
def on_encrypt_callback(systray):
input_text = input("Enter the text to encrypt: ")
encrypted_text = encrypt(input_text)
systray.u... | magicoder | python |
You are tasked with creating a Python program that reads a JSON file containing information about different products and their prices. The program should then calculate the total cost of purchasing a specified quantity of each product and display the overall cost. If any errors occur during the processing of the JSON f... | ```python
import json
import traceback
def calculate_total_cost(products_file):
try:
with open(products_file, 'r') as file:
data = json.load(file)
total_cost = 0
for product in data['products']:
total_cost += product['price'] * product['quantity']
... | magicoder | python |
You are tasked with creating a function to format an address string based on a given data structure. The address data is stored in an object with the following properties: `alamat` (street address), `desa` (village), `kecamatan` (district), `kota` (city), and `kode_pos` (postal code). The address should be formatted in... | ```javascript
function camel_case($str) {
return str_replace(' ', '', ucwords(str_replace(['_', '-'], ' ', $str)));
}
function formatAddress($profil_desa) {
return "Alamat " . preg_replace('/(?!^)[A-Z]{2,}(?=[A-Z][a-z])|[A-Z][a-z]/', ' $0', ucfirst(camel_case($profil_desa->alamat)))
. ". Desa " . preg_rep... | magicoder | javascript |
You are tasked with implementing a class that simulates a simple banking system. The class should support basic operations such as creating accounts, depositing funds, withdrawing funds, and transferring funds between accounts.
Your task is to implement the `Bank` class with the following specifications:
- The `Bank` ... | ```cpp
// The solution provided is a complete implementation of the Bank class in C++ based on the given specifications.
#include <iostream>
#include <vector>
#include <string>
class Account {
public:
Account(int account_number, const std::string& customer_name) : account_number_(account_number), customer_name_(c... | magicoder | cpp |
You are tasked with creating a Python function that processes images using a pre-trained deep learning model and returns the top predicted classes for each image. The function should utilize TensorFlow and the Inception-ResNet-v2 model for image classification. Additionally, the function should leverage multiprocessing... | ```python
from typing import List, Dict, Tuple
from multiprocessing import Pool
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from os.path import join, exists
from tqdm import tqdm
from legacy.inception_preprocessing import preprocess_image
from legacy.inception_resnet_v2 import ince... | magicoder | python |
You are working on a project that involves processing large datasets using TensorFlow, a popular open-source machine learning library. As part of the data preprocessing pipeline, you need to parse a dataset using TensorFlow's `tf.io.parse_example` function. The dataset is represented as a collection of serialized examp... | ```python
import tensorflow as tf
def parallel_parse_dataset(dataset, features, num_parallel_calls):
def parse_example(serialized_example):
return tf.io.parse_example(serialized_example, features)
parsed_dataset = dataset.map(
parse_example,
num_parallel_calls=num_parallel_calls
)
... | magicoder | python |
You are tasked with implementing a function to calculate the area of the intersection between a rectangle and a list of rectangles. The rectangles are defined by their top-left and bottom-right coordinates. The function should take the main rectangle and a list of rectangles as input and return the total area of the in... | ```java
public int calculateIntersectionArea(Rect mainRect, List<Pair<Point, Point>> rectList) {
int totalArea = 0;
for (Pair<Point, Point> rect : rectList) {
int x1 = Math.max(mainRect.left, rect.first.x);
int y1 = Math.max(mainRect.top, rect.first.y);
int x2 = Math.min(mainRect.right, ... | magicoder | java |
You are working on a machine learning project that involves training a model to classify images into two categories: "true" and "negative". The model is implemented using TensorFlow, a popular machine learning library. The code snippet provided is part of the training process, where the true labels and negative labels ... | ```python
import tensorflow as tf
def calculate_binary_cross_entropy_loss(true_labels, neg_labels, total_input_batch, model):
total_labels = tf.concat((true_labels, neg_labels), axis=0)
scores = model(total_input_batch)
loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=total_labels, logits=scores)... | magicoder | python |
You are tasked with implementing a function that processes a given Rust code snippet to extract and count the number of unique Rust modules being imported. A Rust module is a collection of items, such as structs, enums, traits, functions, and type aliases, that can be used to organize and control the visibility of item... | ```rust
fn count_unique_modules(code: &str) -> usize {
let mut unique_modules = std::collections::HashSet::new();
for line in code.lines() {
if let Some(module_path) = line.strip_prefix("use ") {
let module_path = module_path.trim_end_matches(';').trim();
if let Some(module_name)... | magicoder | rust |
You are tasked with implementing a program to analyze the frequency of words in a given text. Your program should take a string of text as input and output a list of unique words along with their frequencies, sorted in descending order based on frequency.
For the purpose of this problem, a word is defined as a sequen... | ```python
import re
from collections import Counter
def word_frequency(text):
# Remove punctuation and convert to lowercase
text = re.sub(r'[^\w\s]', '', text).lower()
# Split the text into words
words = text.split()
# Define common stop words
stop_words = {'the', 'and', 'of', 'in', '... | magicoder | python |
You are tasked with implementing a Swift protocol and its associated types to model a simple banking system. The protocol should define the basic functionality required for a bank account, and the associated types should represent the account holder's information.
Define a protocol `BankAccount` with the following req... | ```swift
// Define the associated type AccountHolder
protocol AccountHolder {
var name: String { get }
var address: String { get }
}
// Implement the BankAccount protocol
protocol BankAccount {
associatedtype Holder: AccountHolder
var accountNumber: String { get set }
func deposit(amount: Doub... | magicoder | swift |
You are tasked with implementing a Python class that represents a Protocol Buffers message definition. Protocol Buffers is a method of serializing structured data, and it is used for communication protocols, data storage, and more. Your class should have the ability to store various properties of a message definition a... | ```python
class ProtoMessage:
def __init__(self, is_extendable, syntax, serialized_start, serialized_end):
self.is_extendable = is_extendable
self.syntax = syntax
self.extension_ranges = []
self.oneofs = []
self.serialized_start = serialized_start
self.serialized_end ... | magicoder | python |
You are working on a Python package for analyzing and visualizing regret and performance metrics in online learning algorithms. The package contains several modules for computing and plotting different metrics. One of the modules, `n_tree_sensitivity`, focuses on analyzing the sensitivity of performance metrics to the ... | ```python
from typing import List, Tuple, Dict
from sklearn.metrics import roc_auc_score
def compute_aucs_n_trees(n_trees_list: List[int], dataset: List[Tuple[List[int], List[float]]]) -> Dict[int, float]:
aucs = {}
for n_trees in n_trees_list:
# Perform computation for each number of trees
# P... | magicoder | python |
You are tasked with implementing a sorting algorithm for a list of bills based on their introduction dates. The given code snippet is a part of a larger program that manages a list of bills and updates a table view with the sorted data. The `bills` array contains objects with an `introduced_on` property representing th... | To correctly sort the bills based on their introduction dates, we can use the `sorted(by:)` method along with a custom comparator function. We can also utilize the `DateFormatter` to convert the date strings into `Date` objects for comparison.
```swift
// Define a DateFormatter to convert date strings to Date objects
... | magicoder | swift |
You are tasked with creating a script to parse a list of URLs and filter them based on specific criteria. Each URL is a string in the format "http://<hostname>:<port>/<path>". The script should output the URLs that meet the filtering conditions.
The filtering conditions are as follows:
1. URLs that contain the substri... | ```python
import re
def filter_urls(urls):
filtered_urls = []
for url in urls:
parts = url.split(':')
if "ingest" in url:
filtered_urls.append(url)
elif len(parts) == 2 and parts[1].isdigit():
port = int(parts[1])
if port > 4042:
filte... | magicoder | python |
You are tasked with implementing a function that processes a nested dictionary representing a set of filtering conditions for a database query. The dictionary contains column names as keys and filtering conditions as values. The filtering conditions can be simple (e.g., equality, inequality) or complex (e.g., logical A... | ```python
from typing import List, Dict, Any
def apply_filter_conditions(data: List[Dict[str, Any]], filters: Dict[str, Any]) -> List[Dict[str, Any]]:
def apply_condition(row, condition):
operator = condition["operator"]
value = condition["value"]
if operator == "==":
return row... | magicoder | python |
You are tasked with implementing a Facebook login feature in an Angular application using the `@ngrx/store` library for state management. The application has a `FacebookLoginComponent` that needs to interact with the Facebook JavaScript SDK to authenticate users and dispatch actions to update the authentication state i... | ```typescript
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import * as authReducer from '../store/auth.reducers';
import * as authActions from '../store/auth.actions';
import { FacebookLoginViewModel } from './facebook-login-view-model';
declare var FB: any;
@Component({
s... | magicoder | typescript |
You are tasked with implementing a generic algorithm for processing and transforming data using a binary operation. The algorithm iterates through two ranges of elements, applies the binary operation to each element in the first range, and stores the results in the corresponding positions of the second range. The binar... | ```cpp
// Definition of the BinOp struct
template <typename T>
struct BinOp {
static T neutral; // Neutral element for the binary operation
// Binary operation process function
static T process(T val1, T val2) {
// Define the binary operation process logic here
return val1 + val2; // Example: Addition ... | magicoder | cpp |
You are tasked with implementing a neural network architecture for an image processing task. The architecture consists of an encoder and a decoder. The encoder takes an input image and produces two sets of intermediate features, denoted as y1, p1, and y2, p2. The decoder then takes these intermediate features along wit... | ```python
# Solution
def forward(self, x):
x, (y1, p1, y2, p2) = self.encoder(x)
x = self.decoder(x, y1, p1, y2, p2)
return x
```
The provided code snippet is already a correct implementation of the forward pass for the given neural network architecture. The `forward` function takes an input tensor `x`, pa... | magicoder | python |
You are tasked with implementing a method to reverse the order of words in a given string. You need to create a method `ReverseWords` within the `StringExtensions` class, which takes a string as input and returns the string with the order of words reversed. A word is defined as a sequence of non-space characters.
The ... | ```csharp
public static class StringExtensions
{
public static string ReverseWords(this string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return input;
}
string[] words = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Array.Reve... | magicoder | csharp |
You are given a sorted array of integers where every element appears exactly twice, except for one element that appears only once. Your task is to write a function to find the unique element in the array. The array is guaranteed to be sorted in non-decreasing order.
You need to implement the following function:
```ja... | ```java
public int singleNonDuplicate(int[] nums) {
int lo = 0;
int hi = nums.length - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (mid % 2 == 1) {
mid--;
}
if (nums[mid] == nums[mid + 1]) {
lo = mid + 2;
} else {
hi = mid... | magicoder | java |
You are tasked with implementing a binary search algorithm to find the index of a given value in a sorted collection. The binary search algorithm compares the target value to the middle element of the collection. If they are not equal, the half in which the target cannot lie is eliminated, and the search continues on t... | ```python
from typing import List
def binary_search(collection: List[int], start: int, end: int, value: int) -> int:
while start <= end:
mid = start + (end - start) // 2
if collection[mid] == value:
return mid
elif collection[mid] < value:
start = mid + 1
els... | magicoder | python |
You are tasked with creating a Python function to preprocess audio features for a cough detection system. The function should take a file containing cough features as input and perform the necessary preprocessing steps to prepare the data for machine learning classification.
The function should perform the following s... | ```python
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from keras.utils import to_categorical
def coughdetect(coughfile):
# Read the cough features from the input file into a pandas DataFrame called featuresdf
featuresdf = pd.read_csv(coughfile)
# Convert features ... | magicoder | python |
You are tasked with implementing a parallel algorithm for dividing a 2D grid into equal sections based on the number of processes available. The given code snippet is part of a parallel program that aims to divide a 2D grid into sections for parallel processing. The code snippet is responsible for determining the start... | ```c
IndexRange divide_grid(int nx, int ny, int myid, int numprocs, int cut_dir) {
IndexRange range;
int n_layers;
if (cut_dir == CUT_DIR_X) {
range.start = (int) myid * ((double) nx / numprocs);
range.end = (int) (myid + 1) * ((double) nx / numprocs) - 1;
n_layers = nx;
} else ... | magicoder | c |
You are working for a telecommunications company that wants to analyze the relationship between the number of customers and the number of cancellations in different categories. The company has a dataset called "tabela" containing information about the categories of customers and their cancellation status. The dataset h... | ```python
import pandas as pd
def cancellation_analysis(tabela):
quantidade_categoria = tabela["Categoria"].value_counts() # Count of customers in each category
quantidade_categoria_percentual = tabela["Categoria"].value_counts(normalize=True) # Percentage of cancellations in each category
report = {}
... | magicoder | python |
You are tasked with creating a custom file loader for a specific data format. The data is stored in a NetCDF file, and you need to implement a method to load this data into a 3-dimensional array structure. The NetCDF file contains a variable named "data" which holds the actual data to be loaded. You are provided with a... | ```rust
use netcdf::{File as NcFile, Variable};
// Assume that Array3 is a 3-dimensional array type
struct Array3<T> {
// Implementation details for Array3
}
// Assume that Numeric is a trait representing numeric types
impl<T: Numeric> Array3<T> {
// Other methods and implementation details for Array3
}
imp... | magicoder | rust |
You are tasked with creating a program to simulate a simple game of generating and controlling ships using Python's Pygame library. The game will involve the player generating and controlling ships to navigate through obstacles and reach a specific destination.
Your task is to implement a function `generate_ships` tha... | ```python
import pygame
import random
# Initialize Pygame
pygame.init()
# Define colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Function to generate ships
def generate_ships(window_width, window_height, num_ships):
# Create Pygame window
window = pygame.display.set_... | magicoder | python |
You are tasked with implementing a class method that calculates the mutual information for a given band in a histogram. Mutual information is a measure of the mutual dependence between two variables. In this context, the variables are the intensity values in the band and the corresponding pixel positions in the image.
... | ```python
class HistogramCalculator:
def __init__(self, histogram, joint_histogram, band_index):
"""
:param band_index: Index of passed band.
"""
self.histogram = histogram
self.joint_histogram = joint_histogram
self.band_index = band_index
self.mutual_informa... | magicoder | python |
You are tasked with creating a Python class that handles incoming HTTP requests and performs asynchronous database insertions. Your class should utilize the Twisted framework for asynchronous event-driven programming. The provided code snippet is a partial implementation of the class, and your task is to complete the i... | ```python
from twisted.internet import reactor
class HTTPRequestHandler:
def __init__(self, request):
self.request = request
self.host = request.getHeader('Host')
self.path = request.path.decode('utf-8')
self.isSecure = request.isSecure()
reactor.callLater(1, self._insertInt... | magicoder | python |
You are tasked with implementing a caching mechanism for a database connection in Python. The given code snippet is part of a class that manages the database connection and caching. The `cache_key` is generated from the `filename` and is used as a unique identifier for caching. The class also enables callback traceback... | ```python
import sqlite3
class DatabaseConnection:
def __init__(self, filename):
self.filename = filename
self.cache = {} # Initialize an empty cache dictionary
# Generate cache key from filename
self.cache_key = filename.encode("utf8")
# Enable callback tracebacks for cu... | magicoder | python |
You are tasked with implementing a simple game logic using Rust. The game involves taking actions based on the outcome of rolling a die. The provided code snippet demonstrates a function `take_action_with_move` that takes a single argument `roll` representing the outcome of rolling a die. The function uses a `match` st... | ```rust
// Define the Actions enum to represent the possible actions in the game
enum Actions {
AddFancyHat,
RemoveFancyHat,
MovePlayer(u8),
}
impl Actions {
// Define associated functions to perform the actions
fn add_fancy_hat() {
// Implementation for adding a fancy hat
// ...
... | magicoder | rust |
You are tasked with implementing a simplified version of an offscreen effect player in C++. An offscreen effect player is responsible for applying image processing effects to offscreen render targets and then notifying the caller with the processed results.
You are provided with the following code snippet as a startin... | ```cpp
#include <memory>
#include <functional>
namespace bnb::oep::interfaces
{
class offscreen_render_target;
class effect_player;
}
using offscreen_render_target_sptr = std::shared_ptr<bnb::oep::interfaces::offscreen_render_target>;
using effect_player_sptr = std::shared_ptr<bnb::oep::interfaces::effect_pla... | magicoder | cpp |
You are tasked with implementing a function to colorize a given string using the Pygments library. Pygments is a syntax highlighting library that supports a wide range of programming languages and file formats. Your task is to create a function `colorize_string` that takes a string as input and returns the colorized ve... | ```python
import pygments
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
def can_colorize(s: str):
"""True if we can colorize the string, False otherwise."""
if pygments is None:
return False
return True
def colorize_s... | magicoder | python |
You are tasked with implementing a function to process and validate QR code information related to COVID-19 tests. The function should take a QR code string as input and return the result of the validation process. The QR code information will be in a specific format related to COVID-19 test results. The function shoul... | ```swift
struct CoronaTestResult {
// Define properties to represent the validated COVID-19 test information
}
enum QRCodeError: Error {
case invalidFormat
case invalidInformation
}
func processQRCodeInformation(_ qrCode: String, completion: (Result<CoronaTestResult, QRCodeError>) -> Void) {
// Valida... | magicoder | swift |
You are tasked with implementing a reinforcement learning algorithm for a discrete action space using a combined actor-critic network. The actor network is responsible for outputting a probability distribution of actions given a state, while the critic network estimates the value function for the given state. The provi... | ```python
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
class a_c_v_discrete(nn.Module):
'''
combine actor network and critic network, share some nn layers. use for discrete action space.
input: vector of state
output: probability distribution of actions... | magicoder | python |
You are tasked with implementing a function that generates all possible symmetric strings based on a given input string. A symmetric string is a string that remains unchanged when read backward. For example, "aba" and "1221" are symmetric strings. The function should take a string as input and return a list of all poss... | ```python
from typing import List
def generateSymmetricStrings(s: str) -> List[str]:
result = []
for char in "69":
result.append(char + s + char)
result.append("8" + s + "8")
return result
```
The `generateSymmetricStrings` function takes a string `s` as input and initializes an empty list `re... | magicoder | python |
You are working on a database manipulation system for electronic design automation. The system involves translating between two different representations of pins and nets. Pins are represented by the `Pin` class, and nets are represented by the `Net` class. Additionally, there are two helper functions: `staToDb` and `d... | ```cpp
Net* dbNetwork::net(const Term* term) const {
// Translate the Term object to a dbBTerm object using staToDb function
dbBTerm* bterm = staToDb(term);
// Get the dbNet object associated with the dbBTerm object
dbNet* dnet = bterm->getNet();
// Translate the dbNet object to a Net object using dbToSta f... | magicoder | cpp |
You are given a C++ class `StringManipulator` with a member function `reverseString` that takes a string `s` as input and reverses it. However, the implementation of the `reverseString` function is missing. Your task is to complete the implementation of the `reverseString` function using C++.
Class Definition:
```cpp
... | ```cpp
#include <string>
class StringManipulator {
public:
std::string reverseString(std::string s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
std::swap(s[left], s[right]);
left++;
right--;
}
return s;
}
};
```
... | magicoder | cpp |
You are tasked with simulating a simplified version of a disk I/O scheduler. In this scenario, you are given a series of write requests to be performed on a disk. Each write request consists of a buffer to be written, an offset on the disk, and a file descriptor representing the disk. Your goal is to implement a schedu... | ```rust
fn schedule_write_requests(requests: Vec<(i32, i32, i32)>) -> Vec<i32> {
let mut scheduled_order: Vec<i32> = Vec::new();
let mut current_offset: i32 = 0;
let mut grouped_requests: std::collections::HashMap<i32, Vec<(i32, i32)>> = std::collections::HashMap::new();
for (fd, buf, offset) in reque... | magicoder | rust |
You are tasked with implementing a multi-threaded game simulation where two players take turns to make a move. The provided code snippet initializes a boolean variable `yourTurn` which indicates whether it is currently the player's turn to make a move. Your task is to create a Java class `Game` that manages the turn-ba... | ```java
public class Game {
private boolean yourTurn = true;
public synchronized void player1Move() throws InterruptedException {
while (!yourTurn) {
wait();
}
// Player 1 makes a move
System.out.println("Player 1 makes a move");
yourTurn = false;
not... | magicoder | java |
You are tasked with creating a Python class method that retrieves and processes new videos from a video feed. The method should interact with a database, call an external feed, and make an API request to retrieve video data. Your task is to complete the implementation of the `get_new_videos` method within the given cla... | ```python
async def get_new_videos(self) -> None:
current_vid = await self.bot.db.field("SELECT ContentValue FROM videos WHERE ContentType = ?", "video")
for item in await self.call_feed():
data = await self.call_yt_api(item.yt_videoid)
thumbnails = data["snippet"]["thumbnails"]
duratio... | magicoder | python |
You are tasked with implementing a Python class that can parse and extract information from a message structure. The message structure consists of fields and nested messages, and the class should be able to recursively traverse the structure and extract the field names along with their corresponding types.
Your task i... | ```python
class Field:
def __init__(self, context, nested_msg=None):
self.context = context
self._nested_msg = nested_msg
class MessageParser:
def __init__(self):
self.fields = {}
def parse_message(self, message, expand_nested=False):
def recursive_helper(cur_name, cur_msg)... | magicoder | python |
You are tasked with creating a property-based test generator for manipulating text data structures. In this problem, you will be working with ropes, a data structure used for efficiently storing and manipulating large strings. Ropes are particularly useful for operations like concatenation and substring extraction.
Yo... | ```rust
// Import the necessary modules and types for the solution
use proptest::prelude::*;
use ropey::Rope;
use ropey::str_utils::AbsoluteCharOffset;
// Implementation of the arb_absolute_char_offset generator
fn arb_absolute_char_offset(max_len: usize) -> impl Strategy<Value = AbsoluteCharOffset> {
0..max_len.p... | magicoder | rust |
You are given a list of integers representing the scores of a game. The game has a special rule: if the current score is the same as the previous score, the current score is discounted. Your task is to calculate the total score after applying this rule and print the result.
Write a Python function `calculate_total_sco... | ```python
from typing import List
def calculate_total_score(scores: List[int]) -> int:
total_score = 0
prev_score = None
for score in scores:
if score != prev_score:
total_score += score
prev_score = score
return total_score
# Test the function
scores = [10, 5, 10, 8, 8, 8,... | magicoder | python |
You are tasked with creating a Python class to handle connections to a DVRIP (Digital Video Recorder Internet Protocol) client. The DVRIPClient class should establish a TCP connection to a specified host and port, and then authenticate using a given username and password. Your task is to implement the DVRIPClient class... | ```python
from socket import socket, AF_INET, SOCK_STREAM
class DVRIPClient:
def __init__(self, socket):
self.socket = socket
def connect(self, host, port, username, password):
try:
self.socket.connect((host, port))
# Perform authentication using the provided username a... | magicoder | python |
You are tasked with implementing a class that manages a collection of names, their associated contexts, and corresponding file paths. The class should provide methods for adding and retrieving this information.
You are given a code snippet that initializes three private arrays within the class: `$names`, `$contexts`, ... | ```php
class NameContextPathManager {
private $names = array();
private $contexts = array();
private $paths = array();
public function addNameContextPath($name, $context, $path) {
$this->names[] = $name;
$this->contexts[$name] = $context;
$this->paths[$name] = $path;
}
public function getConte... | magicoder | php |
A circular prime is a prime number that remains prime under cyclic shifts of its digits. For example, the number 197 is a circular prime because 197, 971, and 719 are all prime numbers. Your task is to write a program to determine how many circular primes exist below a given limit.
Write a function `count_circular_pri... | ```python
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def rotate_number(n):
n_str = str(n)
rotations = [int(n_str[i:] + n_str[:i]) for i in range(len(n_str))]
return rotations
def count_circular... | magicoder | python |
You are tasked with creating a script to automate the deployment process for a system processor application. The script should perform the following tasks:
1. Check if the executable file `exeSystemProcessor` exists in the `target/debug` directory.
2. If the file exists, display "SYS File found" and proceed to the nex... | ```bash
#!/bin/bash
if [ -f target/debug/exeSystemProcessor ]; then
echo "SYS File found"
if [ -f $HOME/Documents/Deploy/exeSystemProcessor ]; then
echo "SYS old removed"
rm -f $HOME/Documents/Deploy/exeSystemProcessor
fi
cp target/debug/exeSystemProcessor $HOME/Documents/Depl... | magicoder | shell |
You are tasked with creating a form validation function for a user registration page. The function should validate the input fields for telephone number, email, and CPF (Brazilian individual taxpayer registry identification). The validation rules for each field are as follows:
1. Telephone Number (id="telefone"):
-... | ```javascript
function validateForm() {
const telefoneInput = document.getElementById('telefone').value;
const emailInput = document.getElementById('email').value;
const cpfcnpjInput = document.getElementById('cpfcnpj').value;
const telefoneRegex = /^\((1[1-9]|[2-9][0-9])\) (9\d{4}|\d{5})-\d{4}$/;
... | magicoder | javascript |
You are working on a data visualization project and need to create a program to plot time series data. The data is stored in a pandas DataFrame `df` with a column named `cpm` representing counts per minute. You need to create a function to plot the data on a graph using matplotlib.
Write a Python function `plot_time_s... | ```python
import pandas as pd
import matplotlib.pyplot as plt
def plot_time_series(df):
# Resample data for every 4-hour interval and plot in red
hours = df['cpm'].resample('4H').mean()
hours = hours.iloc[1:-1] # Exclude first and last intervals
fig, ax1 = plt.subplots()
ax1.set_ylim((12, 20))
... | magicoder | python |
You are tasked with creating a Python function that processes a given text file and extracts the namespaces mentioned in the file. A namespace is a set of symbols that are used to organize objects of various kinds, allowing these objects to be referenced by name. The namespaces in the file are denoted by lines that sta... | ```python
from typing import List
def extract_namespaces(file_path: str) -> List[str]:
namespaces = []
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
if line.startswith('# ') and len(line) > 2:
namespace = line[2:]
namesp... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.