query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a script to extract system information from different Unix-like operating systems. The script should handle variations in command options and output formats across different systems. Your task is to implement a function that takes the kernel name as input and returns the appropriate command... | ```python
def get_system_info_command(kernel: str) -> str:
if kernel == "Linux":
return "eval date ; eval uname -m ; eval uname -r ; eval uname -s ; eval uname -v ; eval uname -p"
elif kernel == "HP-UX":
return "eval date ; eval uname -m ; eval uname -r ; eval uname -s ; eval uname -v"
elif ... | magicoder | python |
You are tasked with implementing a function to process a series of images and generate a mesh representation. The function should take a list of image objects as input and return the mesh representation of the combined images.
You are given the following code snippet as a starting point:
```python
imgs_pil.append(im)... | ```python
from PIL import Image
import numpy as np
import trimesh
def mesh_imgs(imgs):
vertices = []
faces = []
for img in imgs:
# Convert PIL image to numpy array
img_array = np.array(img)
# Extract vertices and faces from the image
# For demonstration purpose... | magicoder | python |
You are tasked with implementing a function that processes a given input and returns a specific output based on the input type. The function should follow the rules outlined below:
- If the input is an integer, the function should return the input multiplied by 2.
- If the input is a string, the function should return... | ```python
def process_input(input):
if isinstance(input, int):
return input * 2
elif isinstance(input, str):
return input + " World"
elif isinstance(input, list):
return [x * 2 for x in input]
elif isinstance(input, dict):
return {key: value * 2 for key, value in input.it... | magicoder | python |
You are tasked with implementing a custom SQL function in Rust for calculating the square root of a floating-point number. The function should return the square root if the input is non-negative, and an error if the input is negative. The provided code snippet serves as a starting point for the implementation.
Your ta... | ```rust
// Define the EvalError enum with a variant for the specific error condition
#[derive(Debug, PartialEq)]
enum EvalError {
NegSqrt,
}
// Implement the custom SQL function for calculating the square root of a floating-point number
macro_rules! sqlfunc {
($($func:tt)*) => {
$($func)*
};
}
// ... | magicoder | rust |
You are tasked with implementing a Python class that processes a set of genes associated with a specific disease. The class, `DiseaseAssociatedGeneSet`, should be designed to store and process gene information related to a given disease. Additionally, you need to implement a method to validate whether a set of gene IDs... | ```python
class DiseaseAssociatedGeneSet:
def __init__(self, disease):
# Initialize the disease-associated gene set here
self.disease_associated_genes = self.load_disease_associated_genes(disease)
def load_disease_associated_genes(self, disease):
# Implement the logic to load disease-as... | magicoder | python |
You are tasked with implementing a simple routing system for a mobile application using Swift. The routing system should allow navigation between different view controllers based on a route identifier. You are provided with a partial implementation of the `HomeRouter` class, which conforms to a protocol named `Router`.... | ```swift
import UIKit
// Assume the Router protocol and NotificationsVC class are defined elsewhere
class HomeRouter: Router {
func route(to routeID: String, from context: UIViewController, parameters: Any?, animated: Bool) {
switch routeID {
case NotificationsVC.identifier:
if... | magicoder | swift |
You are tasked with implementing a function that resizes an input image to a specified dimension using a specific interpolation method. The function should take the original image and the target dimensions as input and return the resized image.
You are given the following code snippet as a starting point:
```python
fr... | ```python
import numpy as np
def imresize(frame_large, target_size):
target_height, target_width = target_size
height, width, channels = frame_large.shape
# Calculate the ratio of resizing for each dimension
height_ratio = height / target_height
width_ratio = width / target_width
# Generate n... | magicoder | python |
You are working on a network server application that requires secure communication using SSL/TLS. The given code snippet is a part of a Python class that manages SSL/TLS certificates and permissions for user access. The `ssl_file` method constructs the file path for SSL certificates, and the `allow` method grants permi... | ```python
class SSLManager:
def __init__(self):
self.permissions = {}
# Existing methods from the given code snippet
def ssl_file(self, name):
return os.path.join(system_test.DIR, 'ssl_certs', name)
def allow(self, user, address, permissions):
if user not in self.permissions:
... | magicoder | python |
You are tasked with creating a Python function that reads a type mapping file and constructs a nested dictionary representing the mapping relationships between source and target attributes. The type mapping file is a CSV file containing information about the mapping between source and target attributes, along with addi... | ```python
def atkis_read_type_mapping(type_mapping_file):
mapping = {}
with open(type_mapping_file, 'r', encoding='utf-8') as csv_file:
# Skip the header row
next(csv_file)
for row in csv.reader(csv_file):
source_table, source_attribute, source_value, target_table, ... | magicoder | python |
You are tasked with creating a command-line utility that simulates a simple version control system. Your program should support two main operations: `push` and `log`.
The `push` operation takes three arguments:
1. The path to the directory to be pushed.
2. The message associated with the push.
3. The current timestamp... | ```javascript
const fs = require('fs');
const path = require('path');
const logFilePath = path.join(__dirname, 'log.txt');
function push(directoryPath, message) {
const timestamp = new Date().toISOString();
const logEntry = `${timestamp}: ${message} - ${directoryPath}\n`;
fs.appendFile(logFilePath, logEntry, (... | magicoder | javascript |
You are tasked with implementing a data structure to manage movie ticket sales at a box office. The box office system should support operations for adding new movies, selling tickets, and retrieving sales statistics. You need to design a class `DataBoxOffice` that encapsulates the functionality of the box office system... | ```javascript
class Movie {
constructor(name, availableTickets) {
this.name = name;
this.availableTickets = availableTickets;
this.soldTickets = 0;
}
}
class DataBoxOffice {
constructor() {
this.movies = new Map();
this.totalSales = 0;
}
addMovie(movieName, availableTickets) {
if (!t... | magicoder | javascript |
You are tasked with implementing a function that generates a raw message based on a given input. The raw message is expected to follow a specific format and encoding rules. The input will consist of a string representing a series of data points, and the output should be a raw message adhering to the specified format.
... | ```javascript
function generateRawMessage(dataPoints) {
const rawMessage = `2A${dataPoints}C7\r\n`;
return rawMessage;
}
// Test the function
const input = "200000000000000000000000000000000000000000";
const output = generateRawMessage(input);
console.log(output); // Output: "2At20000000000000000000000000000000000... | magicoder | javascript |
You are tasked with creating a neural network model to classify handwritten digits from the MNIST dataset using TensorFlow and Keras. The MNIST dataset consists of 28x28 grayscale images of handwritten digits (0-9). Your goal is to build, train, and evaluate a neural network model to achieve high accuracy in classifyin... | ```python
import tensorflow as tf
# Load the MNIST dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Preprocess the data
x_train, x_test = x_train / 255.0, x_test / 255.0
# Build the neural network model
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten... | magicoder | python |
You are working on a project that involves implementing the K-Means clustering algorithm in Java. As part of the project, you need to compile the KMeans.java file, create a JAR file, and organize the compiled classes into a directory structure. The provided code snippet demonstrates the commands to achieve this.
Your ... | ```java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class KMeansCompiler {
public static void main(String[] args) {
String curDir = System.getProperty("user.dir");
String classDir = curDir +... | magicoder | java |
You are tasked with implementing a simple web service client in Swift. Your task is to create a class that interacts with a web service to fetch data and present it to a view. You will need to implement a presenter class that conforms to a specific protocol and interacts with a view controller and a router. The present... | ```swift
final class FirstScreenPresenter: FirstScreenPresenterProtocol {
private var service: WebService
private weak var view: FirstScreenViewControllerPresenterProtocol!
private weak var router: FirstScreenRouterProtocol!
init(view: FirstScreenViewControllerPresenterProtocol, router: FirstScreenRou... | magicoder | swift |
You are tasked with implementing a simplified version of a symbolic expression (S-expression) parser in C++. An S-expression is a nested list data structure commonly used in Lisp programming languages. Each S-expression can be either an atom or a list. An atom is a single data element, such as a number or a symbol. A l... | ```cpp
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
class SExpr {
private:
std::string expression;
public:
SExpr(const std::string& expr) : expression(expr) {}
std::string toString() const {
return expression;
}
bool isAtom() const {
return expression... | magicoder | cpp |
You are tasked with implementing a function that takes in a string and returns a new string with the characters reversed. However, there is a twist - you are not allowed to use any built-in string reversal functions or methods. You must implement the reversal algorithm manually.
Write a function `reverseString` that t... | ```javascript
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
```
The `reverseString` function initializes an empty string `reversed`. It then iterates through the input string `str` in reverse order, appending... | magicoder | javascript |
You are tasked with creating a custom decorator in TypeScript for Angular applications. Decorators are a design pattern that is used to separate modification or decoration of a class without modifying the original source code. In Angular, decorators are extensively used for various purposes such as component, directive... | ```typescript
// Define the custom decorator
function LogMethodCalls(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Method ${propertyKey} called with arguments: ${args}`);
return origin... | magicoder | typescript |
You are tasked with implementing a Java class that represents a simple database schema for storing information about archived class type information. The provided code snippet is a partial implementation of the `ArchivedClassTypeInfoSchema` class, which extends the `AbstractSchema` class and is used to define the schem... | ```java
package cppclassanalyzer.database.schema;
import cppclassanalyzer.database.record.ArchivedClassTypeInfoRecord;
import cppclassanalyzer.database.schema.fields.ArchivedClassTypeInfoSchemaFields;
public final class ArchivedClassTypeInfoSchema extends AbstractSchema<ArchivedClassTypeInfoRecord> {
private sta... | magicoder | java |
You are tasked with implementing a simplified version of a write operation for a custom networking library. The provided code snippet outlines a part of the library's API for sending data over a network connection. Your task is to create a function that simulates the behavior of the `Write` struct's `send` method.
You... | ```rust
use uvll;
use raw::{mod, Request, Allocated, Stream};
use UvResult;
fn custom_send<T, U>(handle: &mut U, buf: &[u8], cb: uvll::uv_write_cb) -> UvResult<()> {
// Simulate the behavior of the send method by performing the necessary operations
// to send the data over the network using the provided networ... | magicoder | rust |
You are tasked with creating a language translation service using Python. Your goal is to implement a class that can interact with a translation API to retrieve available translation models and to translate text from one language to another. The API provides two methods: `get_available_models` and `translate`.
The `ge... | ```python
class TranslationService:
def __init__(self, api_client):
self.api_client = api_client
def get_available_models(self, default, source, target):
params = {'default': default, 'source': source, 'target': target}
return self.api_client.request(method='GET', url='/v2/models', para... | magicoder | python |
You are tasked with creating a Python program to simulate a simple rock-paper-scissors game. The game should allow a user to play against the computer, which will randomly select its move. The game should display the user's choice, the computer's choice, and the outcome of the round. The program should also keep track ... | ```python
import random
# Function to randomly select the computer's move
def computer_move():
return random.choice(['rock', 'paper', 'scissors'])
# Function to determine the winner of a round
def determine_winner(user_choice, comp_choice):
outcomes = {'rock': {'rock': 'draw', 'paper': 'lose', 'scissors': 'wi... | magicoder | python |
You are tasked with implementing a simplified version of an ActiveRecord pattern for managing course information. The `Course` class should be able to store and retrieve information about various courses. The class should support basic CRUD (Create, Read, Update, Delete) operations for course objects.
Your task is to ... | ```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Modelo Course, maneja toda la información de los cursos
*/
class Course {
private int id;
private String name;
private String description;
... | magicoder | java |
You are tasked with creating a Python function that securely retrieves an authentication token from a file or generates a new one if the file does not exist. The function should handle file operations and token generation securely and efficiently.
Your task is to implement the `get_auth_token` function, which takes no... | ```python
import os
def get_auth_token():
base_path = os.path.dirname(__file__) # Get the base path of the current file
token_file_path = os.path.join(base_path, '..', 'config', 'token.txt') # Construct the token file path
try:
with open(token_file_path, 'r') as f:
token = f.read() ... | magicoder | python |
You are tasked with creating a script to automate versioning and packaging of a Python project using Poetry. The script should take a single argument, which can be "major", "minor", or "patch", indicating the type of version bump to perform. The script should perform the following steps:
1. Check if the provided argume... | ```bash
#!/bin/bash
set -e -x
if [ "${1}" != "major" -a "${1}" != "minor" -a "${1}" != "patch" ]; then
echo "Usage: ${0} (major|minor|patch)"
exit 1
fi
part="${1}"
poetry run bump2version "${part}"
poetry build
poetry run twine check dist/*
```
In the solution, we start by setting the script to exit immediately if... | magicoder | shell |
You are tasked with implementing a dynamic programming algorithm to solve a specific optimization problem. The problem involves finding the maximum value of a function given certain constraints. The function is represented by a two-dimensional array `DP`, and the constraints involve setting specific values at certain i... | ```python
import time
def dynamic_programming_algorithm(N):
# Initialize the DP array
DP = [[0 for _ in range(N)] for _ in range(N)]
# Implement the dynamic programming algorithm here
# ...
# Example: Setting a specific value at index [56][56]
DP[56][56] = 20
# Measure the time taken for... | magicoder | python |
You are tasked with implementing a change detector class that monitors a series of values and determines if the values are within a warning zone. The change detector class has a method to retrieve the warning zone status and another method to predict the next value in the series.
You are given the following code snipp... | ```java
/**
* ChangeDetector class monitors a series of values and determines if they are in the warning zone.
*/
public class ChangeDetector {
private boolean isWarningZone;
private int[] series;
/**
* Constructor for ChangeDetector class.
* @param series the series of values to monitor
*... | magicoder | java |
You are tasked with creating a RESTful API for managing a collection of programming languages. The API should support the following operations: retrieving all languages, retrieving a specific language, adding a new language, updating an existing language, and deleting a language.
You are given a partial implementation... | ```python
from flask import Flask, jsonify, request
app = Flask(__name__)
languages = [
{'name': 'Python', 'type': 'interpreted'},
{'name': 'Java', 'type': 'compiled'},
{'name': 'JavaScript', 'type': 'interpreted'}
]
# Retrieve all languages
@app.route('/langs', methods=['GET'])
def getAll():
return ... | magicoder | python |
You are tasked with creating a web application that displays a table of suppliers using DataTables, a popular jQuery plugin for enhancing HTML tables. The provided code snippet is a part of the JavaScript code for this application. The DataTable is configured to retrieve data from a server-side endpoint using AJAX and ... | ```php
// routes/web.php
Route::get('prov/data', 'ProveedorController@getData')->name('prov.data');
// app/Http/Controllers/ProveedorController.php
use App\Proveedor;
public function getData()
{
$suppliers = Proveedor::select('id', 'proveedor')->get();
return datatables()->of($suppliers)->toJson();
}
```
In... | magicoder | php |
You are tasked with implementing a simplified version of a call stack mechanism in a programming language. The call stack is a fundamental concept in computer science and is used to manage function calls and their associated data. In this problem, you will need to create a data structure to represent the call stack and... | ```python
class CallStack:
def __init__(self):
self.stack = []
def pushStack(self, frameSize, argumentCount, function, destination, instructions):
frame = {
"frameSize": frameSize,
"argumentCount": argumentCount,
"function": function,
"destination... | magicoder | python |
You are tasked with creating a PHP 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 account holder's name and account number. Implement the class with the following requirements:
... | ```php
<?php
namespace banking;
class BankAccount
{
private $accountNumber;
private $accountHolderName;
private $balance;
public function __construct($accountNumber, $accountHolderName)
{
$this->accountNumber = $accountNumber;
$this->accountHolderName = $accountHolderName;
... | magicoder | php |
You are tasked with creating a program that analyzes a given text file to count the occurrences of specific words. The program should read the text file, count the occurrences of each word, and then display the word count for a specified set of words.
Your task is to implement a function `wordCountAnalyzer` that takes... | ```python
from typing import List, Dict
def wordCountAnalyzer(file_path: str, words_to_count: List[str]) -> Dict[str, int]:
word_counts = {}
with open(file_path, 'r') as file:
content = file.read()
words = content.split()
for word in words:
word = word.strip('.,?!;:"')
... | magicoder | python |
You are tasked with implementing a program to generate a grid-based image with specific properties. The program should create a grid of cells, each of which can be colored black or white. The grid should have a minimum area size of 30x30 cells. Additionally, the program should have the capability to rotate semicircles ... | ```python
import numpy as np
import cv2
class GridImageGenerator:
def __init__(self):
self.min_area_size = 30*30
self.rotate_semicircle = False
self.angle_rotate = 30
self.black_color = 0
self.white_color = 255
self.grid = np.full((30, 30), self.white_color, dtype=np... | magicoder | python |
You are tasked with creating a Python function that simulates the behavior of a simplified version of the `urllib3-mock` library. The `urllib3-mock` library is used for mocking out the `urllib3` Python library, and it is an adaptation of the `responses` library. Your task is to implement a function that can handle HTTP... | ```python
class MockHTTPClient:
def __init__(self):
self.responses = {}
def register(self, url, method, status_code, response_body):
key = (url, method)
self.responses[key] = (status_code, response_body)
def request(self, url, method):
key = (url, method)
if key in ... | magicoder | python |
You are tasked with implementing a Python class that facilitates file transfer between two endpoints using the Globus Transfer service. The class should handle the transfer of a specified file from a source endpoint to a destination endpoint, ensuring data integrity through checksum verification and synchronization. Yo... | ```python
import globus_sdk
class GlobusFileTransfer:
def __init__(self, source_endpoint, destination_endpoint, label):
self._globus_transfer_client = globus_sdk.TransferClient()
self.source_endpoint = source_endpoint
self.destination_endpoint = destination_endpoint
self.label = lab... | magicoder | python |
You are tasked with implementing a distributed system for processing and storing sensor data. The system consists of a master node and multiple slave nodes. The master node is responsible for receiving sensor data, processing it, and storing the results in a Redis database. Each slave node is responsible for processing... | ```python
import asyncio
import aioredis
import json
from .master_async import MasterAsync, trans_int_to_float # Assuming the necessary imports are available
class SensorDataProcessor:
def __init__(self, slave_id):
self.slave_id = slave_id
async def process_sensor_data(self, data: dict) -> dict:
... | magicoder | python |
You are tasked with creating a program to analyze log entries from a web server. Each log entry contains a timestamp, log level, and a message. Your program needs to parse the log entries and extract specific information from them.
You are given a sample log entry in the following format:
```
DEBUG - 2020-08-15 13:45:... | ```python
from typing import Tuple
def parse_log_entry(log_entry: str) -> Tuple[str, str, str]:
parts = log_entry.split(" --> ")
timestamp = parts[0].split(" - ")[1].strip()
log_level, message = parts[1].split(" - ", 1)
return timestamp, log_level.strip(), message.strip()
# Test the function with the ... | magicoder | python |
You are tasked with implementing a custom extension for the `Zip2Sequence` type in Swift. The `Zip2Sequence` type represents a sequence of pairs built out of two underlying sequences. Your goal is to create an extension method that takes a closure as a parameter and applies this closure to each pair of elements in the ... | ```swift
extension Zip2Sequence {
func map<T>(_ transform: (Element.Element, Element.Element) -> T) -> [T] {
var result: [T] = []
for (element1, element2) in self {
result.append(transform(element1, element2))
}
return result
}
}
```
The `map` method for `Zip2Sequenc... | magicoder | swift |
You are given a Python code snippet that takes an integer input `a` and performs a series of operations to calculate the value of `n1`, `n2`, and `n3` based on the input. The code then prints the sum of these calculated values. Your task is to understand the operations performed in the code and write a function to achi... | ```python
def calculate_sum_of_replicated_integers(a):
n1 = int("%s" % a)
n2 = int("%s%s" % (a, a))
n3 = int("%s%s%s" % (a, a, a))
return n1 + n2 + n3
# Test the function with an example
input_integer = 5
result = calculate_sum_of_replicated_integers(input_integer)
print(result) # Output: 615
``` | magicoder | python |
You are tasked with creating a Python Flask application for managing categories. The application has a route for deleting a category, which requires the user to be logged in. The code snippet provided is a part of the Flask application and handles the deletion of a category based on the given ID. Your task is to implem... | ```python
from flask import flash
from flask_login import login_required
from app.models import Categoria # Assuming Categoria model is defined in app.models
@blueprint.route('/delete_categoria/<id>')
@login_required
def delete_categoria(id=None):
if not id:
flash(u'Devi fornire un id!', 'error')
else... | magicoder | python |
You are tasked with implementing a type-checking algorithm for a custom grammar representation in Rust. The grammar is represented using the `FGrammar` type, and the type-checking function `typecheck` takes an `FGrammar` as input and returns a `TGrammar` as output. The code snippet provided gives a glimpse of the type-... | ```rust
pub use front::ast::FGrammar;
use partial::*;
pub mod analysis;
pub mod typing;
pub fn typecheck(fgrammar: FGrammar) -> TGrammar {
Partial::Value(fgrammar)
.and_then(|grammar| at_least_one_rule_declared(grammar))
.and_then(|grammar| analysis::analyse(grammar))
.ensure("aborting due... | magicoder | rust |
You are tasked with creating a Python program to automate the downloading and zipping of manga chapters. Your program should be able to download images from a given URL, organize them into chapters, and optionally zip the chapters into a single file. You are provided with a code snippet that performs some of these task... | ```python
# Import necessary modules
import os
import zipfile
class MangaDownloader:
def __init__(self):
# Initialize any required variables or settings
pass
def current_url(self, chapter_number, page_number):
# Implement logic to generate the current URL for the given chapter and page... | magicoder | python |
You are tasked with creating a Discord bot command that generates a random "Fumo" character, represented by the emoticon ᗜˬᗜ. The bot should be able to select a random Fumo character from a predefined list and display it in the chat. Additionally, the bot should display information about the author and version of the "... | ```python
import discord
from discord.ext import commands
import random
class FumoCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.__author__ = "Your Name" # Replace with the actual author's name
self.__version__ = "1.0" # Replace with the actual version
def format_hel... | magicoder | python |
You are tasked with creating a Swift class that manages the presentation and dismissal of a debug view controller. The debug view controller should be presented modally and dismissed when a specific action is triggered. Additionally, you need to handle a type alias that has been marked as unavailable and renamed.
Your... | The `DebugViewControllerManager` class is implemented to manage the presentation and dismissal of the debug view controller. It includes methods to present and dismiss the debug view controller, as well as handling the unavailable type alias `DebugViewController`. The `dismissAction` method is called when dismissing th... | magicoder | swift |
You are working on a project to optimize the hyperparameters of a neural network for a machine learning task. The code snippet provided is a function call to train a neural network with the best hyperparameters obtained from a hyperparameter tuning process. Your task is to implement a function that performs hyperparame... | ```python
import itertools
def hyperparameter_tuning(df_full_train, y_full_train, df_test, y_test, inner_layers, droprate, learning_rate, input_droprate):
best_hyperparameters = {}
best_accuracy = 0.0
# Perform grid search to find the best combination of hyperparameters
for layers, dr, lr, input_dr in... | magicoder | python |
You are tasked with creating a script to monitor the CPU usage on a Linux system. The script should calculate the CPU usage percentage and display it along with a CPU icon.
Your task is to implement a function `cpuicon` that returns the CPU icon and a function `cpu` that calculates and displays the CPU usage percentag... | ```bash
# Function to return the CPU icon
cpuicon() {
echo ""
}
# Function to calculate and display CPU usage percentage
cpu() {
read cpu a b c previdle rest < /proc/stat
prevtotal=$((a+b+c+previdle))
sleep 0.5
read cpu a b c idle rest < /proc/stat
total=$((a+b+c+idle))
cpu=$((100*( (total-prevtotal) ... | magicoder | shell |
You are tasked with implementing a script that updates the version numbers of various tools based on the latest available versions from their respective Git repositories. The script uses a custom function `latest_version` to fetch the latest version from the Git repositories and then updates the version numbers in the ... | ```bash
#!/bin/bash
# Function to fetch the latest version from a Git repository
latest_version() {
local vcs="$1"
local repo="$2"
git ls-remote --tags --refs "https://github.com/$repo.git" | awk -F/ '{print $3}' | sort -V | tail -n1
}
# Update version numbers in the script
replace KUBEVAL_VERSION=.* KUBE... | magicoder | shell |
You are tasked with implementing a function to train a recurrent neural network (RNN) model using the Keras library for time series forecasting. The provided code snippet includes a function `compile_model` that sets up the architecture of the RNN model. Your task is to complete the implementation of the `compile_model... | ```python
from keras.models import Sequential
from keras.optimizers import Adam
def compile_model(nneurons, loss_fn, dropout=(0.0, 0.0)):
model = Sequential()
model.add(LSTM(nneurons[0], input_dim=1, return_sequences=True))
if dropout[0] > 0:
model.add(Dropout(dropout[0]))
model.add(LSTM(nneuro... | magicoder | python |
You are tasked with implementing a Python class for managing ad networks in a mobile app. The class should be able to decode and store information from various ad networks. You are provided with a code snippet that includes the beginning of the `AdNetwork` class and a method `_decode` for handling the decoding of ad ne... | ```python
from py_mplus.objects.external.ad_network.adsense import Adsense
from py_mplus.objects.external.ad_network.applovin import AppLoving
from py_mplus.objects.external.ad_network.facebook import Facebook
from py_mplus.objects.external.ad_network.mopub import Mopub
class AdNetwork(MPObject):
def __init__(self... | 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 RESTful API for a library management system. The application should allow users to perform CRUD (Create, Read, Update, Delete) operations on books in the library.
You are provided with a... | ```python
from flask import Flask, Blueprint, jsonify, request
app = Flask(__name__)
books = []
main_views = Blueprint('main_views', __name__)
@main_views.route('/books', methods=['GET'])
def get_books():
return jsonify(books)
@main_views.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
... | magicoder | python |
You are tasked with creating a Python program to manage a simple menu system for a text-based application. The program should allow users to navigate through different menu options and perform actions based on their selections.
Your task is to implement a Python class called `MenuSystem` that provides the functionalit... | ```python
class MenuSystem:
def __init__(self):
self.menus = {}
def add_menu(self, menu_name):
if menu_name not in self.menus:
self.menus[menu_name] = []
def add_item(self, menu_name, item_label):
if menu_name in self.menus:
self.menus[menu_name].append(item... | magicoder | python |
You are tasked with implementing a custom runtime decorator that measures the execution time of functions in Python. Your goal is to create a decorator `@meter.runtime(REPORT_NAME)` that can be applied to any function to measure its execution time and report the results using the provided `REPORT_NAME`. Additionally, y... | ```python
import time
class meter:
@staticmethod
def runtime(REPORT_NAME):
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_t... | magicoder | python |
You are tasked with implementing a movie search feature in a movie database application. The application uses a testing framework and a networking component for fetching movie data. The provided code snippet includes a test case and a test assembler for the movie search feature.
Your task is to create a function that ... | ```swift
struct Movie {
let title: String
}
protocol Networking {
func fetchMovies() -> [Movie]
}
class NetworkStub: Networking {
let filename: String
init(filename: String) {
self.filename = filename
}
func fetchMovies() -> [Movie] {
// Fetch movies from the specifie... | magicoder | swift |
You are tasked with implementing a function `sum_between` that takes a list of two integers as input and returns the sum of all integers between the two input integers, inclusive. If the input list does not contain exactly two integers, the function should raise a TypeError. For example, given the input [3, 7], the fun... | ```python
from typing import List
def sum_between(nums: List[int]) -> int:
if len(nums) != 2 or not all(isinstance(num, int) for num in nums):
raise TypeError("Input list must contain exactly two integers")
start, end = min(nums), max(nums)
return sum(range(start, end + 1))
``` | magicoder | python |
You are tasked with creating a function that processes a list of image filenames and performs specific operations based on the filenames. The function should handle cases where the input filename is an empty string.
Write a function `processImageList` that takes a list of image filenames as input and performs the fol... | ```python
from typing import List
def processImageList(imageList: List[str]) -> List[str]:
processedList = []
for filename in imageList:
if filename != "":
# Perform specific operation on the filename (not specified here)
processedList.append(filename) # Placeholder for the spe... | magicoder | python |
You are given an array of integers `nums`. Your task is to write a function that removes all duplicate occurrences of elements in the array, such that each element appears only once, and returns the modified array. The function should not allocate extra space for another array, but instead modify the input array in pla... | ```python
from typing import List
def remove_duplicates(nums: List[int]) -> int:
if not nums:
return 0
flag = 0
leng = len(nums)
sum_inx = 0
for flag in range(leng):
index = 0
while flag + index + 1 < leng and nums[flag] == nums[flag + index + 1]:
index += 1
... | magicoder | python |
You are tasked with creating a Python function that simulates a simple text-based game. The game involves a player navigating through a grid-based world, collecting treasures, and avoiding obstacles. The grid is represented as a 2D list, where each cell can contain one of the following characters:
- '.' representing an... | ```python
from typing import List
def collect_treasures(grid: List[List[str]]) -> int:
rows, cols = len(grid), len(grid[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
treasures_collected = 0
def is_valid_move(row, col):
return 0 <= row < rows and 0 <= col < cols and grid[row][col] != 'X'
... | magicoder | python |
You are tasked with implementing a pitch-shifting audio effect in a music player application. The application has an `audioPlayer` object with a `play()` method to start playing audio. You need to implement the `changePitchEffect(_:)` method, which takes a `pitch` value as a parameter and adjusts the pitch of the audio... | ```swift
private func changePitchEffect(_ pitch: Float) {
let audioEngine = AVAudioEngine()
let audioPlayerNode = AVAudioPlayerNode()
audioEngine.attach(audioPlayerNode)
let changePitchEffect = AVAudioUnitTimePitch()
changePitchEffect.pitch = pitch
audioEngine.attach(changePitchEffect)
aud... | magicoder | swift |
You are tasked with creating a script to automate the process of copying RPM packages from a development YUM repository to a production YUM repository. The script should take into account the package name, version, release, and provide an option to test the operation before actually performing the copy.
Your script sh... | ```bash
#!/bin/bash
# Input parameters
REPO_HOSTNAME="production-repo.example.com"
PROD_RPM_BASE="/var/www/html/yum/production"
TEST_OPTION="--test" # Optional flag to test the copy operation
PKG="example-package"
VER="1.0"
REL="1"
# SSH into the remote server and execute the copy_to_production.sh script
ssh -t $REP... | magicoder | shell |
You are tasked with implementing a class in TypeScript for creating and manipulating VRF (Verifiable Random Function) key link transactions. The provided code snippet outlines the interface for the `EmbeddedVrfKeyLinkTransactionBuilder` class, which is used to construct VRF key link transactions. Your task is to create... | ```typescript
// Define the necessary DTOs for the parameters
type KeyDto = string; // Assuming KeyDto is a string type
type NetworkTypeDto = string; // Assuming NetworkTypeDto is a string type
type EntityTypeDto = string; // Assuming EntityTypeDto is a string type
type LinkActionDto = string; // Assuming LinkActionDto... | magicoder | typescript |
You are tasked with implementing a simple ping-pong messaging system using Rust's asynchronous programming features. The system consists of two components: a sender and a receiver. The sender periodically sends a "ping" message to the receiver, and the receiver responds with a "pong" message. The sender and receiver co... | ```rust
use tokio::time::{Duration, sleep};
use tokio::sync::mpsc;
enum Message {
Ping,
Pong,
}
async fn sender(mut tx: mpsc::Sender<Message>) {
loop {
// Send a ping message every 10 seconds
if let Err(_) = tx.send(Message::Ping).await {
break;
}
sleep(Duration... | magicoder | rust |
You are given a code snippet that sets up a 2D grid and computes a discretized probability distribution over this grid. Your task is to write a function that takes this discretized distribution and calculates the probability of a given event occurring within a specified region of the grid.
You are provided with the fo... | ```python
import numpy as np
def calculate_probability(region):
# Extract region boundaries
xmin, xmax, ymin, ymax = region
# Get the grid step sizes
dx = (xbnds[1] - xbnds[0]) / Ns[0]
dy = (ybnds[1] - ybnds[0]) / Ns[1]
# Initialize probability sum
probability_sum = 0.0
#... | magicoder | python |
You are tasked with creating a script to manage language datasets. The script should handle the creation of a specified data directory and then navigate into it. Your task is to write a Bash script that accomplishes this, taking into account error handling and verbose output.
Your script should perform the following s... | ```bash
#!/bin/bash
# Check if the data directory exists
if [[ ! -d $DATADIR ]]; then
# Attempt to create the data directory
mkdir -p $DATADIR
if [[ $? -ne 0 ]]; then
# Display error message and usage information if directory creation fails
echo "Failed to create $DATADIR"
echo "Usa... | magicoder | shell |
You are tasked with implementing a custom method in the `Order` model class of a Laravel application. The `Order` model represents orders placed by customers in an e-commerce platform. The method should calculate the total price of an order, taking into account the quantity and unit price of each item in the order.
Th... | ```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Order extends Model {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'orders';
/**
* Calculate the total price of the order.
*
* @return float
*/
public function calculateTotalPri... | magicoder | php |
You are tasked with creating a script to automate the process of updating microcode on a Linux system. Microcode updates are essential for resolving firmware bugs and improving system stability. Your script should check for the presence of a specific error message related to microcode in the bootup screen or dmesg logs... | ```bash
#!/bin/bash
set -e
# Check for the presence of the error message related to microcode
if dmesg | grep -q "Firmware Bug.*TSC_DEADLINE disabled due to Errata"; then
echo "Error related to microcode detected. Updating microcode..."
# Install the "intel-ucode" package without requiring user confirmati... | magicoder | shell |
You are tasked with creating a Python class to manage the training and saving of machine learning models. Your class should include methods for starting the training process, fitting the model, and saving the final trained model. Additionally, the class should have the ability to display the training progress and handl... | ```python
import os
from sklearn.linear_model import LinearRegression
class ModelTrainer:
def __init__(self, model_dir):
self.model_dir = model_dir
def start_training(self):
print("Start training..")
def fit(self, X, y):
try:
model = LinearRegression()
mode... | magicoder | python |
You are tasked with implementing a custom data structure that supports efficient insertion, deletion, and retrieval of key-value pairs. The data structure should have a fixed size and use a specific collision resolution strategy.
Your task is to implement a hash table with linear probing as the collision resolution s... | ```java
public class CustomHashTable {
private static final int INITIAL_CAPACITY = 16;
private static final double LOAD_FACTOR_THRESHOLD = 0.75;
private int size;
private int capacity;
private String[] keys;
private int[] values;
public CustomHashTable(int capacity) {
this.capacity ... | magicoder | java |
You are tasked with implementing a Python unit test for a translation function using the `unittest` framework. The translation function, `trans_ch_eng`, takes a Chinese word as input and returns its English translation. Your goal is to write a test case that verifies the correctness of the translation function.
Your t... | ```python
class TestYoudao(unittest.TestCase):
def test_trans_ch_eng(self):
# Import the translation function from the module
from translator_module import trans_ch_eng
# Test case for a valid translation
self.assertEqual(trans_ch_eng('你好'), 'hello')
# Test case for an emp... | magicoder | python |
You are tasked with implementing a file management system for a version control software. The system should handle the creation and management of temporary files, as well as the generation of filenames for specific purposes.
You are provided with a Python class snippet that partially implements the file management sys... | ```python
class FileManagementSystem:
tempext = '.tmp'
def __init__(self, umask):
self.umask = umask
def subdirFilename(self, classname, nodeid, property=None):
# Implement the logic to generate filenames based on inputs and umask
# Example logic:
filename = f"{classname}_{... | magicoder | python |
You are tasked with implementing a function to create an EGL context for an X11 window in a C++ program. The function should take in context parameters, a window handle, and a shared context, and return a boolean indicating whether the creation was successful or not.
The function signature is as follows:
```cpp
bool E... | ```cpp
bool EGLContextX11::Create(const ContextParams& params, WindowHandle window, const EGLContextBase* shareContext)
{
// Initialize EGL display
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (display == EGL_NO_DISPLAY) {
// Handle error and return false
return false;
}
... | magicoder | cpp |
You are tasked with implementing a multithreaded application for performing BLAST (Basic Local Alignment Search Tool) sequence alignment. The provided code snippet imports a `BlastThread` class from a module named `blast`. The `BlastThread` class is responsible for executing BLAST sequence alignment in a separate threa... | ```python
from threading import Thread
class BlastThread(Thread):
def __init__(self, sequence_data):
super().__init__()
self.sequence_data = sequence_data
self.alignment_result = None
def run(self):
# Perform BLAST sequence alignment on self.sequence_data
# Set self.ali... | magicoder | python |
You are tasked with creating a web application that displays a breadcrumb navigation bar based on the given HTML code snippet. The breadcrumb navigation bar should dynamically display the path to the current page based on the URL and the structure of the website.
Your task is to implement a function or method that tak... | ```python
def generate_breadcrumb(url):
# Split the URL path into segments
segments = url.split('/')
# Remove empty segments and the domain part
segments = [segment for segment in segments if segment]
segments = segments[2:] # Remove the domain part
# Generate the breadcrumb HTML
... | magicoder | python |
You are given a list of elements, some of which may be nested lists. Your task is to write a Python function that counts the total number of elements in the list, including the elements within nested lists. You should implement a recursive approach to solve this problem.
Write a function `count_total_elements` that ta... | ```python
def count_total_elements(input_list):
total_count = 0
for item in input_list:
if isinstance(item, list):
total_count += count_total_elements(item) # Recursively count elements in nested lists
else:
total_count += 1 # Increment count for non-list elements
r... | magicoder | python |
You are tasked with creating a simple program to simulate a button-clicking game. The game will consist of a series of buttons, each with a specific point value. When a button is clicked, the player earns the designated points for that button. The goal is to accumulate the highest total score by strategically clicking ... | ```python
from typing import List
def maxScore(buttons: List[int], k: int) -> int:
n = len(buttons)
max_score = 0
for i in range(0, n, k):
max_score += max(buttons[i:i+k])
return max_score
``` | magicoder | python |
You are tasked with creating a Python function that simulates an authentication process for a web application. The function should take in a JSON payload representing user credentials and return a response indicating the success or failure of the authentication attempt. You are provided with a code snippet that tests t... | ```python
def authenticate_user(credentials: dict) -> dict:
# Simulate authentication process (dummy example)
valid_username = "user123"
valid_password = "pass123"
if credentials.get("username") == valid_username and credentials.get("password") == valid_password:
return {"status": "success"}
... | magicoder | python |
You are given a list of full file paths, where each path consists of directories and a file name separated by a forward slash '/'. Your task is to write a function that returns the longest common directory path shared by all the file paths. If there is no common directory path, the function should return an empty strin... | ```python
from typing import List
def longestCommonDirectory(paths: List[str]) -> str:
if not paths:
return ""
# Split each path into directories
split_paths = [path.split('/') for path in paths]
# Find the minimum length of paths
min_length = min(len(path) for path in split_paths)
#... | magicoder | python |
You are tasked with implementing a data extraction utility for a custom data format. The utility needs to extract specific values from a given data object and handle certain edge cases.
You are given a class `DataExtractor` with the following properties and methods:
- `ObjectId` (string): Represents the ID of the data... | ```csharp
public void ExtractData(string data, JObject rawData)
{
if (data != null)
{
ObjectId = data;
}
Name = rawData.ExtractValue<string>(Constants.Name);
var attributes = rawData.ExtractValue<JObject>(Constants.Attributes);
if (attributes != null)
{
ObjectType = attribute... | magicoder | csharp |
You are working on a project that involves fetching and integrating external libraries. As part of this process, you need to automate the fetching of these libraries from their respective repositories. Your task is to write a script that automates the fetching of the "libb64" and "tinyxml2" libraries from their GitHub ... | ```bash
#!/bin/bash
# Step 1: Copy libb64.a to ../../lib
cp libb64.a ../../lib
# Step 2: Copy include directory to ../../
cp -r ../include ../../
# Step 3: Print "Fetched b64"
echo "Fetched b64"
# Step 4: Change directory to the parent directory
cd ../../
# Step 5: Clone the tinyxml2 repository
git clone https://g... | magicoder | shell |
You are tasked with implementing a message queue system using the provided list of commands and frame types. The message queue system should support various operations such as identifying a client, subscribing to a topic, publishing messages, acknowledging message receipt, and handling errors.
You are given the follow... | To solve this problem, you can create a message queue system using a programming language of your choice. Below is a Python-based solution using classes to represent the message queue system and its operations.
```python
class MessageQueue:
def __init__(self):
self.clients = {}
self.topics = {}
... | magicoder | python |
You are tasked with implementing a simple rendering system for a virtual reality application. The provided code snippet is a part of the `Renderer` module, which is responsible for managing the rendering process. The `Renderer` struct has a method `new` for initializing a new renderer with a shared mutable reference to... | ```rust
impl Renderer {
// Existing code
pub fn render_frame(&mut self) {
if let Some(ref target) = self.target {
let pattern = match target {
RenderTarget::A => "AAAAA",
RenderTarget::B => "BBBBB",
RenderTarget::C => "CCCCC",
};
... | magicoder | rust |
You are tasked with implementing a function that calculates the factorial of a given non-negative integer. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of 5 (denoted as 5!) is 5 * 4 * 3 * 2 * 1 = 120.
Write a function `calculateFa... | ```python
def calculateFactorial(n):
if n < 0:
raise ValueError("Input must be a non-negative integer")
if n == 0 or n == 1:
return 1
total = 1
for i in range(2, n + 1):
total *= i
return total
```
The `calculateFactorial` function first checks if the input is a non-negative ... | magicoder | python |
You are tasked with creating a Python function that efficiently reads and processes a large CSV file. The function should be able to handle files that are too large to fit into memory and should return the sum of a specific column in the CSV file.
You are provided with a code snippet that demonstrates the creation of ... | ```python
import csv
import os
def calculate_csv_column_sum(file_path: str, column_index: int) -> float:
column_sum = 0.0
with open(file_path, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader) # Skip header if present
for row in csv_reader:
try:
... | magicoder | python |
You are tasked with implementing a caching system that utilizes both memcache and NDB (a data storage service in Google Cloud Platform). Your goal is to create a function that retrieves values from the cache, first checking memcache and then NDB if the value is not found in memcache. If the value is found in NDB, it sh... | ```python
def retrieve_value(key: str) -> str:
value = get_from_memcache(key)
if value is not None:
return value
else:
value = get_from_ndb(key)
if value is not None:
set_in_memcache(key, value)
return value
else:
return "Value not found"
`... | magicoder | python |
You are tasked with creating a Python package for web scraping called "UJSPortalScraper." The package should include a module for scraping data from a university job portal and a schema module for defining the structure of the scraped data.
Your task is to implement the necessary classes and functions to fulfill the r... | ```python
# core.py
class UJSPortalScraper:
def __init__(self, portal_url):
self.portal_url = portal_url
def scrape_data(self):
# Implement web scraping logic here
pass
def get_scraped_data(self):
# Return the scraped data
pass
# schema.py
class PortalResult:
d... | magicoder | python |
You are tasked with creating a Python function that simulates a simple banking system using FastAPI and EdgeDB. The system should allow users to create accounts, deposit and withdraw funds, and check their account balance. You are provided with a code snippet that sets up the FastAPI application and connects it to an E... | ```python
from fastapi import FastAPI
import edgedb
app = FastAPI()
# Connect to EdgeDB
settings = get_settings()
app.state.db = await edgedb.create_async_pool(settings.edgedb_dsn)
# Define the Account entity in EdgeDB schema
async with app.state.db.acquire() as conn:
await conn.execute("""
CREATE SCALAR... | magicoder | python |
You are tasked with creating a Python script that processes input arguments and performs specific operations based on the provided inputs. The script is intended to be used for processing data related to the CMS experiment at CERN.
The script is expected to accept command-line arguments and perform the following tasks... | ```python
import argparse
import re
import sys
parser = argparse.ArgumentParser()
parser.add_argument("--json",
help="If present with JSON file as argument, use JSON file for good lumi mask. " +
"The latest JSON file is available at /afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/cer... | magicoder | python |
You are tasked with creating a Python class that simulates a job registry system. The system should allow users to register and manage various job listings. Each job listing should have attributes such as title, company, location, and salary. Additionally, the system should provide functionality to display all register... | ```python
class Job:
def __init__(self, title, company, location, salary):
self.title = title
self.company = company
self.location = location
self.salary = salary
class JobRegistry:
def __init__(self):
self.job_listings = []
def register_job(self, title, company, lo... | magicoder | python |
You are tasked with implementing a class that manages the execution of function objects and tracks whether the `read()` function was called while the execution is ongoing. The class should have a switch to control the execution of the function objects and a flag to track if `read()` was invoked during execution.
Your ... | ```cpp
#include <functional>
class FunctionManager {
private:
bool execution_;
bool readDuringExecution_;
public:
FunctionManager() : execution_(true), readDuringExecution_(false) {}
void execute(const std::function<void()>& func) {
bool prevReadDuringExecution = readDuringExecution_;
... | magicoder | cpp |
You are tasked with creating a script to automate the process of calculating k-nearest neighbors for different subsets of a large dataset. The script should iterate through a range of sizes, calculate the k-nearest neighbors for each subset, and store the results in separate log files.
The given code snippet is a part... | ```bash
#!/bin/bash
largeFile="/scratch2/esadrfa/mlsvm_data/susy_4M_train_zsc_data.dat"
scale=1000 # Assuming a default value for scale
for i in `seq 1 1 10`
do
size=$((i*$scale))
echo $size
./petsc_utility/getSubMatrix -i $largeFile -s 0 -e $size -p $tmp_path -w "susy_"$size"_train_zsc_data.dat"
ds_name... | magicoder | shell |
You are given a directed acyclic graph (DAG) represented as an adjacency matrix `graph[][]` with `n` vertices. Each cell `graph[from][to]` contains the weight of the edge from vertex `from` to vertex `to`. Additionally, an array `indegrees[]` is used to store the indegree of each vertex in the graph.
Your task is to i... | ```cpp
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 1005; // Maximum number of vertices
int graph[MAXN][MAXN]; // Adjacency matrix representing the graph
int indegrees[MAXN]; // Array to store the indegree of each vertex
int n; // Number of vertices ... | magicoder | cpp |
You are tasked with implementing a pagination utility for a threaded messaging application. The provided code snippet is a simplified version of the pagination logic used to handle thread invitations. The `Paginate` class is responsible for paginating a list of thread invitation models based on the specified start and ... | ```python
class Paginate:
def __init__(self, start, limit, resource):
self.start = start
self.limit = limit
self.resource = resource
def paginate(self):
total_items = len(self.resource)
if self.start < 0 or self.limit <= 0:
return [], 0 # Return empty list a... | magicoder | python |
You are working for a cloud infrastructure management company that uses Terraform to provision resources on various cloud platforms. Your team is responsible for automating the deployment of Kubernetes clusters using Terraform. As part of the deployment process, you need to ensure that the Kubernetes cluster is secured... | ```hcl
provider "kubernetes" {
config_context_cluster = "my-cluster"
}
module "kubernetes_cluster" {
source = "terraform-google-modules/kubernetes-engine/google"
version = "15.0.0"
project_id = "my-project"
name = "my-cluster"
region = "us-central1"
node_pools = [
{
name ... | magicoder | hcl |
You are tasked with creating a program to organize and display a hierarchical list of items and item categories. Each item category can contain multiple items, and the items are to be displayed in a collapsible format on a web page. Your task is to implement a function that takes in a list of item categories and their ... | ```python
def generate_collapsible_list(item_categories):
html_code = '<div>\n'
html_code += ' <li class="collapsable startCollapsed"><strong>Items</strong> <a href="/item/add">+</a></li>\n'
for category in item_categories:
html_code += ' <div>\n'
html_code += f' <li class="section... | magicoder | python |
You are tasked with implementing a class that handles the preparation and retrieval of data in the context of Abstract Syntax Notation One (ASN.1) encoding. ASN.1 is a standard interface description language for defining data structures that can be serialized and deserialized in a cross-platform way. Your goal is to cr... | ```csharp
public interface IASN1PreparedElementData
{
// Define necessary methods and properties for handling prepared data
}
public class ASN1DataHandler
{
private IASN1PreparedElementData preparedData;
public void initWithDefaults()
{
// Implement initialization of data with default values
... | magicoder | csharp |
You are tasked with implementing a role-based access control system for a web application. The system should allow different levels of access to certain fields based on the user's role. You are given a Python class `RoleBased` that extends a class `FieldPerm`. The `RoleBased` class has an `__init__` method that takes a... | ```python
class RoleBased(FieldPerm):
def __init__(self, role_perms):
self.role_perms = role_perms
def check(self, field):
user = field.env.user
perms = set(self.role_perms.get('*', '')) # Retrieve permissions for wildcard role if user's role is not found
user_perms = self.role... | magicoder | python |
You are tasked with creating a custom testing framework for asynchronous Rust functions. The framework should support defining asynchronous test functions and running them, while also handling panics and reporting test results.
Your task is to implement the `mimicaw_framework` crate, which will provide the necessary m... | To implement the custom testing framework for asynchronous Rust functions, you can create the `mimicaw_framework` crate with the following components:
1. Define the `mimicaw_framework::test` attribute macro to mark asynchronous test functions:
```rust
#[proc_macro_attribute]
pub fn test(_args: TokenStream, input: Toke... | magicoder | rust |
You are tasked with implementing a neural network architecture using TensorFlow for a specific problem. The architecture will have a customizable number of input variables, hidden layers, and activation functions. Your goal is to create a Python function that takes in the number of input variables, a list specifying th... | ```python
import tensorflow as tf
def create_neural_network(num_inputs=2, layers=[10, 5], activation=tf.nn.tanh):
model = tf.keras.Sequential()
model.add(tf.keras.layers.InputLayer(input_shape=(num_inputs,)))
for nodes in layers:
model.add(tf.keras.layers.Dense(nodes, activation=activation))
... | magicoder | python |
You are tasked with creating a script to automate the installation of software packages on a Linux system. The script should handle the following scenarios:
1. Check if a specific file exists and remove it if it does.
2. If a `curl` command to download a file returns a non-zero exit code, handle the error appropriatel... | ```bash
#!/bin/bash
apt_source_path="/path/to/apt/source"
# Check if the file exists and remove it if it does
if [ -e $apt_source_path ]; then
rm $apt_source_path
fi
# Handle the non-zero exit code from curl
if [ "$curl_exit_code" -gt "0" ]; then
echo "Error: Failed to download the file using curl"
# Add error... | magicoder | shell |
You are tasked with implementing a Python class that manages a directory structure for a software project. The class should provide functionality to identify components within the project directory based on certain criteria.
Your task is to complete the implementation of the `ProjectManager` class, which has the follo... | ```python
import os
class ProjectManager:
def __init__(self, path, componentNames=None, componentHasTheseFiles=None, isComponent=None):
self.path = path
self.componentNames = componentNames if componentNames else []
self.componentHasTheseFiles = componentHasTheseFiles if componentHasTheseFi... | magicoder | python |
You are tasked with creating a script to automate the testing of a Kubernetes cluster using the `podman` tool. The script should run a container with specific configurations and execute a test suite inside the container. Your task is to write a Bash script that accomplishes this automation.
The script should perform t... | ```bash
#!/bin/bash
# Define the variables
KUBECONFIG="/path/to/kubeconfig"
OPT_PAYLOAD="some_payload"
# Run the container with podman
podman run --rm --interactive \
--volume "${KUBECONFIG}:/root/.kube/config:z" \
"registry.ci.openshift.org/origin/${OPT_PAYLOAD}:tests" \
/bin/bash -c 'export KUBECONFIG=/root/.... | magicoder | shell |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.