query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are tasked with creating a custom error handling mechanism for a remote procedure call (RPC) network in Rust. The provided code snippet shows the implementation of the `RpcHandlerError` trait for the `RpcNetworkInfoError` type. Your goal is to extend this error handling mechanism by defining a new custom error type... | ```rust
use std::error::Error;
use std::fmt;
// Define a custom error type for RPC connection errors
#[derive(Debug)]
struct RpcConnectionError {
message: String,
}
impl fmt::Display for RpcConnectionError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "RPC connection error: {}", s... | magicoder | rust |
You are tasked with creating a Python class to tune the hyperparameters of a neural network model using different text vectorization techniques. The class should be able to handle various hyperparameters and vectorization methods, and save the resulting scores to a CSV file. Your task is to implement the `TuneNeuralNet... | ```python
import numpy as np
import pandas as pd
from sklearn.neural_network import MLPClassifier
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.model_selection import cross_val_score
class TuneNeuralNet:
def __init__(self, train_data, epochs, stopwords, model_type):
... | magicoder | python |
You are tasked with creating a Python class to manage daily tasks for a habit-building application. The class should inherit from a base class `HabixUser` and have the following fields:
- `habixuser_ptr`: A one-to-one relationship field with the `HabixUser` class.
- `task_name`: A string field to store the name of the ... | ```python
from django.db import models
from api.models import HabixUser
class DailyTasks(HabixUser):
task_name = models.CharField(max_length=200)
streak_graph = models.CharField(max_length=50000)
created_at = models.DateField(auto_now_add=True)
best_streak = models.PositiveIntegerField(default=0)
```
... | magicoder | python |
You are tasked with creating a JavaScript function that processes a list of webpack configuration objects and returns an array of unique module names that are being ignored due to specific warnings.
The webpack configuration objects are represented as an array of objects, each containing the following properties:
- `v... | ```javascript
function getIgnoredModules(configs) {
const ignoredModules = new Set();
configs.forEach(config => {
config.ignoreWarnings.forEach(warning => {
const moduleName = warning.module.toString().match(/\/([^/]+)$/)[1];
ignoredModules.add(moduleName);
});
});
return Array.from(ignore... | magicoder | javascript |
You are tasked with implementing a data structure to efficiently store and retrieve key-value pairs, with the added requirement of maintaining the order of insertion. To achieve this, you need to create a class called `OrderedDataStore` that utilizes a custom data class called `Data`. The `Data` class should have three... | ```python
from dataclasses import dataclass
from typing import Any, List, Optional
@dataclass
class Data:
key: int
time: int
value: Any
class OrderedDataStore:
def __init__(self):
self.data_store = {}
self.insertion_order = []
def put(self, key: int, value: Any):
current_t... | magicoder | python |
You are tasked with implementing a file streaming service for a web application. The provided code snippet is a part of an Express.js route handler that streams a private audio file to the client. The `filesService` is an instance of a service class that provides methods for accessing and manipulating files. The `getPr... | ```javascript
// Implementation of filesService class
class FilesService {
// Assume privateFiles is a map of file IDs to file content
constructor(privateFiles) {
this.privateFiles = privateFiles;
}
getPrivateFile(id) {
return new Promise((resolve, reject) => {
const fileContent = this.privateFil... | magicoder | javascript |
You are tasked with implementing a custom pooling layer for a convolutional neural network. The custom pooling layer will perform a modified form of max pooling, where the maximum value within each pooling window is replaced by the average value of all the elements within the window. Additionally, the custom pooling la... | ```python
import tensorflow as tf
from tensorflow.keras.layers import Layer
class CustomPooling2D(Layer):
def __init__(self, pool_size=(2, 2), strides=None, padding='valid', **kwargs):
super(CustomPooling2D, self).__init__(**kwargs)
self.pool_size = pool_size
self.strides = strides
... | magicoder | python |
You are given a dataset `df` containing sea level measurements at different time intervals. The dataset has columns `sea_level_0m`, `pandas_l`, and `pandas_h`. The code snippet provided is used to calculate the rolling mean of `sea_level_0m` and the difference between `sea_level_0m` and its rolling mean. However, there... | ```python
import pandas as pd
def calculate_rolling_mean_and_difference(df):
window_size = 240
rolling_mean = df['sea_level_0m'].rolling(window=window_size, center=True, min_periods=1).mean()
df['pandas_l'] = rolling_mean
df['pandas_h'] = df['sea_level_0m'] - rolling_mean
return df
```
The `calcul... | magicoder | python |
You are tasked with creating a program that analyzes software licenses to extract key information. The licenses are provided as text strings, and your program needs to parse the text and extract specific details. Each license text follows a specific format, containing information about the license type, permissions, an... | ```python
def parseLicense(license_text):
lines = license_text.split('\n')
if len(lines) != 4:
return None
if not all(line.startswith('// ') for line in lines[:3]):
return None
license_type = lines[0][11:].strip()
permissions = [p.strip() for p in lines[1][14:].split(',')]
limita... | magicoder | python |
You are tasked with creating a Python program that processes energy usage data from a smart meter and generates daily usage and average daily usage statistics. The program should utilize classes and modules to organize the code effectively.
Your task is to implement the following classes and modules:
1. Create a modu... | ```python
# const.py
DOMAIN = "energy_usage"
DOMAIN_DATA = "domain_data"
ATTRIBUTION = "Data provided by the smart meter"
# DailyUsageSensor.py
from .const import DOMAIN, DOMAIN_DATA, ATTRIBUTION
class FplDailyUsageSensor:
def __init__(self, data):
self.data = data
def get_daily_usage(self):
... | magicoder | python |
You are tasked with creating a Python function that processes date-related queries for a blog post database. The function should take in either a start and end date or a single date and return a MongoDB query to find posts based on the provided date(s).
The function should be named `generate_date_query` and should hav... | ```python
from datetime import datetime
def generate_date_query(start_date: str = None, end_date: str = None, date: str = None) -> dict:
if start_date and end_date:
start_date_obj = datetime.strptime(start_date, "%d/%m/%Y")
end_date_obj = datetime.strptime(end_date, "%d/%m/%Y")
assert (star... | magicoder | python |
You are tasked with implementing a function to process geographic tiles for a mapping application. The function takes in a set of parameters and performs various operations on them. Your task is to complete the implementation of the function by filling in the missing parts.
The function is defined as follows:
```pyth... | ```python
import os
def process_tiles(p, name, zoom):
dest = os.path.join(p.get(name, 'dest'), "%s_zoom%i.jpeg" % (name, zoom))
tilestore = p.get(name, 'tilestore')
# parse bounding box
txt = p.get(name, 'bbox')
c = [float(v) for v in txt.split('"')[1::2]]
bbox = dict(list(zip(['e', 'n', 's', ... | magicoder | python |
You are tasked with implementing a web crawler that will fetch and process questions from a specific topic on a programming Q&A website. The crawler is designed to operate with multiple threads and can fetch a specified number of pages. Your task is to complete the implementation of the `Crawler` class by adding a meth... | ```python
import threading
import time
import random
class Crawler:
# initialises a crawler object
def __init__(self, threads, pages, verbose):
self.num_threads = threads
self.num_pages = pages
self.verbose_output = verbose
# the following values can be changed if necessary: #
... | magicoder | python |
You are tasked with implementing a tic-tac-toe game using Python. The game should allow two players to take turns marking the spaces in a 3x3 grid with their respective symbols (X and O) until one player wins or the game ends in a draw.
Your task is to implement the `minimax_alpha_beta` function, which uses the minima... | ```python
def minimax_alpha_beta(board, player, depth, alpha, beta, maximizing_player, move, original_board):
# Base cases for game over or maximum depth reached
if board.is_winner(player):
return 1, move, board
if board.is_winner(board.get_next_player(player)):
return -1, move, board
if... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple file system. The file system should support the creation of directories, subdirectories, and files, as well as the ability to navigate through the file structure and retrieve information about the files and directories.
Your task is to create a cl... | ```python
class FileSystem:
def __init__(self):
self.root = {}
def create_file(self, path, content):
directories, filename = path.rsplit('/', 1)
curr = self.root
for directory in directories.split('/')[1:]:
if directory not in curr:
curr[directory] = ... | magicoder | python |
You are tasked with creating a Swift function to retrieve records from a Core Data entity based on specific criteria. Core Data is a framework provided by Apple to manage the model layer objects in an application. The given code snippet demonstrates the creation of a record in Core Data, and now you need to implement a... | ```swift
func retrieveRecords(nameSubstring: String, latitudeRange: ClosedRange<Float>, timePeriod: ClosedRange<Date>) -> [Cidade] {
let fetchRequest: NSFetchRequest<Cidade> = Cidade.fetchRequest()
fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [
NSPredicate(format: "nome CO... | magicoder | swift |
You are tasked with creating a Python function that reads a JSON file and returns a dictionary with string keys and values. However, the JSON file contains Unicode strings, and you need to ensure that the function returns only string objects instead of Unicode ones. You should implement the function `read_json_file` to... | ```python
import json
def read_json_file(file_path: str) -> dict:
with open(file_path, "r") as file:
data = file.read()
json_data = json.loads(data)
return convert_to_string_keys(json_data)
def convert_to_string_keys(data: dict) -> dict:
if isinstance(data, dict):
return {str(k... | magicoder | python |
You are tasked with creating a class to manage movie information in a media server application. The class should include properties for various attributes of a movie, such as its ID, title, availability, quality, request status, approval status, URLs for streaming on Plex and Emby, overview, poster path, and release da... | ```csharp
public class Movie
{
public string TheMovieDbId { get; set; }
public string Title { get; set; }
public bool Available { get; set; }
public string Quality { get; set; }
public bool Requested { get; set; }
public bool Approved { get; set; }
public string PlexUrl { get; set; }
pub... | magicoder | csharp |
You are tasked with creating a web application for a blogging platform. The application should have a registration and login system for users. You need to implement the backend functionality for user registration and login using PHP and MySQL.
Create a PHP script that handles user registration and login. The registrat... | ```php
<?php
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "blog_db";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connec... | magicoder | php |
You are working on a Java project that utilizes dependency injection. You have been using the `javax.inject.Named` annotation to provide a name to the components being injected. However, you want to ensure that the names provided are unique to avoid any conflicts or ambiguities in the dependency injection process.
You... | ```java
import javax.inject.Named;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class UniqueNamedChecker {
public static boolean areNamesUnique(List<Class<?>> classes) {
Set<String> namesSet = new HashSet<>();
for (Class<?> clazz : classes) {
Named named... | magicoder | java |
You are tasked with implementing a chess move representation for the en passant move in a chess game. In chess, the en passant move allows a pawn to capture an opponent's pawn that has moved two squares forward from its starting position. This move must be represented in the codebase using object-oriented programming p... | ```typescript
import { Move } from './Move';
import { Pawn } from './Pawn';
import { Coordinate } from './Coordinate';
export class EnPassantMove extends Move {
enemyPawn: Pawn;
constructor(pawn: Pawn, from: Coordinate, to: Coordinate, enemyPawn: Pawn) {
super(pawn, from, to);
this.enemyPawn = enemyPawn;
... | magicoder | typescript |
You are tasked with implementing a method to parse and extract local variable slots from a given method using the provided code snippet as a reference. The method should traverse the method's scope and identify all local variables, including those within nested scopes.
Your task is to implement the `GetLocalVariableS... | ```csharp
using System.Collections.Immutable;
public static class ISymUnmanagedMethodExtensions
{
public static ImmutableArray<string> GetLocalVariableSlots(this ISymUnmanagedMethod method)
{
var localVariableSlots = ImmutableArray.CreateBuilder<string>();
ISymUnmanagedScope rootScope = method.... | magicoder | csharp |
You are tasked with implementing a media playback system for a video streaming application. The system should support both local and remote playback modes. The provided code snippet is part of a Swift class that manages the playback functionality. The class has a method `loadMedia` to load media for playback and a meth... | ```swift
func switchToRemotePlayback() {
print("switchToRemotePlayback; mediaInfo is \(String(describing: mediaInfo))")
if playbackMode == .remote {
return // Already in remote playback mode, no need to switch
}
if let castSession = sessionManager.currentSession as? GCKCastSession {
// S... | magicoder | swift |
You are tasked with creating a token generator for a volunteer management system. The system has an Appointment model, which represents a volunteer's scheduled appointment. The token generator is responsible for creating unique tokens for password reset functionality. The token is generated based on the volunteer's inf... | ```python
from six import text_type
from django.contrib.auth.tokens import PasswordResetTokenGenerator
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, appointment, timestamp):
return (text_type(appointment.volunteer) + text_type(appointment.pk) + text_type(timestamp))
```
In ... | magicoder | python |
You are tasked with implementing a class that represents a courier service. The class should have the ability to store the addresses of delivery locations and set the name of the courier. Below is a partial implementation of the Courier class in C++.
```cpp
#include <iostream>
#include <string>
using namespace std;
c... | ```cpp
#include <iostream>
#include <string>
using namespace std;
class Courier {
private:
string nume;
string adrese[10];
public:
void setAdresa(int i, string adresa) {
this->adrese[i] = adresa;
}
void setNume(string nume) {
this->nume = nume;
}
void displayAdrese() {
... | magicoder | cpp |
You are given the definition of a singly linked list node and a function to delete the next node in the list. Your task is to implement a function to delete the nth node from the end of the list and return the head of the updated list.
Definition of a singly linked list node:
```python
class ListNode:
def __init__... | ```python
def delete_nth_from_end(head, n):
dummy = ListNode(0)
dummy.next = head
first = dummy
second = dummy
# Move the second pointer to the (n+1)th node from the beginning
for _ in range(n + 1):
second = second.next
# Move both pointers until the second pointer reaches the end
... | magicoder | python |
You are tasked with implementing a middleware in a Django web application that enforces authentication for certain routes. The middleware should redirect unauthenticated users to the login page.
Your task is to complete the `AuthRequiredMiddleware` class by implementing the `__call__` method to check if the user is au... | ```python
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import authenticate
class AuthRequiredMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
LOGIN_URL = reverse('users:l... | magicoder | python |
You are given a string containing a disclaimer text. Your task is to write a function that extracts all the unique words from the disclaimer and returns them in a sorted list. A word is defined as a sequence of characters separated by spaces, punctuation marks, or line breaks.
Create a function called `extract_unique_... | ```python
import re
def extract_unique_words(disclaimer_text):
# Convert the text to lowercase and use regular expression to find all words
words = re.findall(r'\b\w+\b', disclaimer_text.lower())
# Return the sorted list of unique words
return sorted(list(set(words)))
``` | magicoder | python |
You are tasked with creating a JavaScript class for managing music controls on a web page. The class should handle the creation and translation of a music control container and append it to the document body. The provided code snippet is a part of the class constructor, where a music control container is created, its c... | ```javascript
class MusicControl {
constructor() {
this.__element = document.createElement('div');
this.__element.innerHTML = $globalScope.$SimpleCache.Use('CopyrightPage');
$globalScope.$Language.Translate(this.__element);
document.body.appendChild(this.__element);
}
setMusic(musicURL) {
con... | magicoder | javascript |
You are tasked with creating a Python function that securely stores sensitive information, such as passwords and API keys, using a custom encryption scheme. The function should take in the sensitive information as input and return the encrypted string. Additionally, you need to implement a decryption function that take... | ```python
import base64
def encrypt_sensitive_info(info, key):
encoded_info = base64.b64encode(info.encode()).decode()
encrypted_info = ''.join([chr((ord(char) + key) % 256) for char in encoded_info])
return encrypted_info
def decrypt_sensitive_info(encrypted_info, key):
decrypted_info = ''.join([chr(... | magicoder | python |
You are tasked with implementing a logging decorator for a Python web service. The decorator should log the details of the HTTP request and response for each API call. Your task is to complete the implementation of the `log_request_response` decorator function.
The `log_request_response` decorator function should log ... | ```python
import json
import datetime
def code_log(response, message):
timestamp = datetime.datetime.now().isoformat()
print("[{}] {}".format(timestamp, message))
def log_request_response(func):
def wrapper(*args, **kwargs):
timestamp = datetime.datetime.now().isoformat()
http_method = "GE... | magicoder | python |
You are tasked with creating a Python program that utilizes the face recognition library to identify and label faces in a live video stream. The program should capture video from the default camera, load a sample image, and compare the faces detected in the live video with the loaded sample image. The goal is to displa... | ```python
import cv2
import face_recognition
video_capture = cv2.VideoCapture(0)
# Load sample
image1 = face_recognition.load_image_file("Your Image Here with extension")
encoding1 = face_recognition.face_encodings(image1)[0]
known_face_encodings = [encoding1]
known_face_names = ["Put Your Name Which U Wants to See ... | magicoder | python |
You are tasked with implementing a function to retrieve test cases for a specific resource type. The function `get_resource_wrong_cases(resource_type)` is supposed to return a list of wrong test cases for the given resource type. However, the implementation seems to be incomplete, as it references a function `create_al... | ```python
def get_resource_wrong_cases(resource_type):
# Assuming spec_basepath is defined elsewhere
spec_basepath = '/path/to/specs/' # Example base path
# Assuming create_all_test_case4type is defined elsewhere
def create_all_test_case4type(file_path, resource_type):
# Implementation of crea... | magicoder | python |
You are tasked with implementing a Python class to represent a deck of playing cards. The class should have methods to draw a card from the top or bottom of the deck, as well as a method to recreate a new standard deck and shuffle it. Each card has a face (e.g., "Ace", "2", "3", ..., "King") and a suit (e.g., "Hearts",... | ```python
import random
class Card:
def __init__(self, face, suit):
self.face = face
self.suit = suit
class Deck:
def __init__(self):
self.cards = []
def draw_top(self):
return self.cards.pop(0)
def draw_bottom(self):
return self.cards.pop()
def recreate_... | magicoder | python |
You are tasked with implementing a generic repository pattern for a .NET application. The repository pattern is a design pattern that abstracts the data access layer from the rest of the application. In this problem, you will create a generic interface for a repository and then implement it for a specific entity.
Your... | ```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DeltaX.Domain.Common.Repositories
{
public interface IRepository<T>
{
Task<T> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task AddAsync(T entity);
Task UpdateAsync(T e... | magicoder | csharp |
You are tasked with implementing a custom `TextFieldStyle` in Swift that enforces a specific character limit on the text input. Your custom style should restrict the user from entering more characters than the specified limit and provide visual feedback to indicate the character limit has been reached.
Your custom `Te... | ```swift
import UIKit
public struct CharacterLimitedTextFieldStyle: TextFieldStyle {
let characterLimit: Int
public init(characterLimit: Int) {
self.characterLimit = characterLimit
}
public func apply(to textField: UITextField) {
textField.addTarget(self, action: #selector(lim... | magicoder | swift |
You are working on a data validation project and need to create a custom validation rule using Python and the Spectacles library. The Spectacles library provides functionality for validating LookML models and dimensions in Looker, a data platform for business intelligence.
Your task is to create a custom validation ru... | ```python
from abc import ABC, abstractmethod
from spectacles.client import LookerClient
from spectacles.lookml import Project, Model, Dimension
from spectacles.select import is_selected
from spectacles.validation import ValidationRule, ValidationMessage, ValidationContext
class SelectedDimensionValidation(ValidationR... | magicoder | python |
You are tasked with creating a Python function that processes and formats cryptocurrency data for display. The function will take a pandas DataFrame `df` containing cryptocurrency data and a string `sortby` representing the column to sort the data by. The function should perform the following tasks:
1. Check if the Dat... | ```python
import pandas as pd
COINS_COLUMNS = ["Market Cap [$]", "Volume [$]"]
def lambda_very_long_number_formatter(x):
if x >= 1e12:
return f"{x/1e12:.2f}T"
elif x >= 1e9:
return f"{x/1e9:.2f}B"
elif x >= 1e6:
return f"{x/1e6:.2f}M"
elif x >= 1e3:
return f"{x/1e3:.2f}... | magicoder | python |
You are tasked with implementing a simple linear regression model using the provided code snippet as a starting point. The code snippet initializes a regressor and imports the `LinearRegression` class from the `ols` module. Your task is to complete the implementation of the `LinearRegression` class by adding methods to... | ```python
# Complete the implementation of the LinearRegression class
class LinearRegression:
def __init__(self):
self.coefficients = None
def fit(self, X, y):
"""
Fit the linear regression model to the training data.
Parameters:
X (array-like): Input features, shape (n... | magicoder | python |
You are tasked with creating a PHP function that filters roles based on privileges. The function should take in a role ID and a type ID as parameters and return the appropriate privileges based on the type. The type ID determines which table to query for privileges: 1 corresponds to "privileges_roles_admin" and any oth... | ```php
public function scopeRoleWithPrivilege($query, int $pc_role_id, int $type_id) {
$table_type = ($type_id === 1) ? "privileges_roles_admin" : "privileges_roles_master";
// Assuming the existence of a database connection and appropriate model
$privileges = DB::table($table_type)
->w... | magicoder | php |
You are tasked with implementing a function that evaluates a conversation event within a planning context. The function takes in three parameters: a `planning` object of type `SequenceContext`, an `event` of type `DialogEvent`, and a `preBubble` boolean flag. The function returns a Promise that resolves to an array of ... | ```typescript
async function evaluate(planning: SequenceContext, event: DialogEvent, preBubble: boolean): Promise<StepChangeList[]|undefined> {
// Your implementation here
// Example implementation:
if (preBubble) {
// Evaluate the leading edge of the event
// Perform necessary operations an... | magicoder | typescript |
You are tasked with implementing a simple publisher-subscriber pattern in Swift. The publisher is responsible for updating subscribers with new data and notifying them when it has finished. Your goal is to create a class that manages this pattern and handles the updating and finishing of the publisher.
You are given t... | ```swift
// Define the Feed protocol
protocol Feed {}
// Define the FeedPublisher protocol
protocol FeedPublisher {
func update(with feeds: [Feed])
func finish()
}
// Implement the FeedPublisher protocol
class FeedPublisherImpl: FeedPublisher {
func update(with feeds: [Feed]) {
// Implementation f... | magicoder | swift |
You are tasked with creating a script that processes command-line arguments and performs specific actions based on the input. Your script should accept a variable number of arguments and display the name of the script followed by the provided arguments.
Write a Bash script that accomplishes the following:
- Accepts an... | ```bash
#!/bin/bash
echo $0 "$@"
```
The script `argument_processor.sh` uses the `echo` command to display the name of the script (`$0`) followed by the provided command-line arguments (`"$@"`). When the script is executed with command-line arguments, it will display the script name followed by the provided arguments. | magicoder | shell |
You are tasked with creating a program that simulates a settings management system. The system should allow for the creation, retrieval, and modification of various settings. Each setting can have a name and one of three types of values: string, integer, or text. Additionally, the system should support the ability to s... | ```php
class Setting
{
private $name;
private $defaultValue;
private $value;
public function __construct($name, $defaultValue)
{
$this->name = $name;
$this->defaultValue = $defaultValue;
$this->value = $defaultValue;
}
public function getValue()
{
return... | magicoder | php |
You are tasked with implementing a simple command-line calculator that can perform basic arithmetic operations. The calculator should accept input from the user and evaluate the expression to produce the result.
Your task is to write a program that takes input from the command line and performs the following operation... | ```swift
import Foundation
func calculate(_ expression: String) -> Double? {
let components = expression.components(separatedBy: " ")
guard components.count == 3,
let operand1 = Double(components[0]),
let operand2 = Double(components[2]) else {
return nil
}
let `operator` =... | magicoder | swift |
You are tasked with creating a Python function that processes shader attributes for a 3D model in Autodesk Maya. The function should take in the name of the shader and a list of attributes to process. The function should retrieve and print the values of the specified attributes for the given shader. Additionally, if th... | ```python
from typing import List
import maya.cmds as cmds
def process_shader_attributes(shader_name: str, attributes: List[str]) -> None:
dx11Shader = cmds.listConnections(shader_name + ".outColor")[0]
shader = cmds.listConnections(dx11Shader + ".surfaceShader")[0]
shadows = bool(cmds.getAttr("{0}.{1}".f... | magicoder | python |
You are given a list of items and their corresponding prices in the format of a code snippet. Each item is printed on a separate line, followed by its price on the next line. Your task is to write a program to parse this input and create a dictionary where the items are the keys and their prices are the values.
The in... | ```python
def parse_items(items_list):
items_dict = {}
for i in range(0, len(items_list), 2):
item_name = items_list[i]
item_price = float(items_list[i + 1])
items_dict[item_name] = item_price
return items_dict
# Test the function with the given example
input_items = ['apple', '1.50... | magicoder | python |
You are tasked with creating a C++ program that recursively searches for and deletes all files with a specific extension within a given directory. The program should take the directory path and the file extension as input and then remove all files with the specified extension within the directory and its subdirectories... | ```cpp
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
bool deleteFilesWithExtension(const std::string& directoryPath, const std::string& fileExtension) {
try {
for (const auto& entry : fs::recursive_directory_iterator(directoryPath)) {
if (fs::is_regular_file(entry) ... | magicoder | cpp |
You are tasked with implementing a dependency management system for a Python package manager. The system should allow for registering dependencies and checking if they are installed. You are given a code snippet that partially implements this functionality. Your task is to complete the implementation of the dependency ... | ```python
class Dependency:
def __init__(self, modname, features, required_version, installed_version, optional):
self.modname = modname
self.features = features
self.required_version = required_version
self.installed_version = installed_version
self.optional = optional
DEPE... | magicoder | python |
You are tasked with implementing a Python class that manages a polygon object. The class, named `PolygonManager`, should have the following functionalities:
1. Add a point to the polygon.
2. Remove a point from the polygon.
3. Get the number of points in the polygon.
4. Check if the polygon is closed (i.e., the first ... | ```python
class PolygonManager:
def __init__(self):
self.points = []
def add_point(self, x, y):
# Add a point with coordinates (x, y) to the polygon
self.points.append((x, y))
def remove_point(self, index):
# Remove the point at the specified index from the polygon
... | magicoder | python |
You are tasked with creating a Python script that validates a list of URLs provided as command-line arguments. The script should ensure that each URL is valid, i.e., it should have either the 'http' or 'https' scheme and a non-empty network location. If any URL is found to be invalid, the script should print an error m... | ```python
import sys
from urllib.parse import urlparse
if len(sys.argv) < 3:
print('Usage: ' + sys.argv[0] + ' <target ip> <url>...')
sys.exit(1)
target_ip = sys.argv[1]
for url in sys.argv[2:]:
parsed = urlparse(url)
if not (parsed.scheme in ('http', 'https') and parsed.netloc):
print(url + ... | magicoder | python |
You are tasked with implementing a custom memory management system for a C++ application. The system should support both single-object and array allocations, and it should properly handle aligned memory allocations. Your task is to create a class `CustomAllocator` that provides custom `new`, `new[]`, `delete`, and `del... | ```cpp
#include <iostream>
#include <cstdlib>
#include <new>
template <typename T>
class CustomAllocator {
public:
void* allocate(size_t size, std::align_val_t alignment) {
return ::operator new(size, alignment);
}
void deallocate(void* ptr, size_t size, std::align_val_t alignment) {
::ope... | magicoder | cpp |
You are tasked with creating a program that simulates a simplified version of a file formatting tool similar to `clang-format`. Your program should take a list of file names and apply a specified formatting style to each file. The formatting style is defined by a set of rules, and the program should modify the files in... | ```python
import sys
import os
import subprocess
def apply_formatting_style(style, files):
style_options = {
"Google": "-style=Google",
"LLVM": "-style=LLVM",
"Chromium": "-style=Chromium",
"Mozilla": "-style=Mozilla"
}
if style not in style_options:
print("Invalid ... | magicoder | python |
You are working on a project that involves analyzing and processing time-series data stored in multiple files. Your task is to create a function that will find paths to the relevant files based on the given parameters.
You are given the following function signature:
```python
def find_paths(out_dir: str, files_ID: Lis... | ```python
from typing import List
import datetime
def find_paths(out_dir: str, files_ID: List[str], time_instances: List[str], month_id: int) -> List[str]:
current_year = datetime.datetime.now().year
file_paths = []
for file_id in files_ID:
for time_instance in time_instances:
file_path... | magicoder | python |
You are tasked with creating a command-line tool called "JoinExistingGroup" that allows users to join an existing group by providing the group name as a command-line argument. The tool should validate the group name and then add the user to the specified group. Your task is to implement the logic for the "JoinExistingG... | ```python
import sys
def validate_group(group_name):
# Assume this function checks if the group exists
# and returns True if it exists, False otherwise
pass
def add_user_to_group(user, group_name):
# Assume this function adds the user to the specified group
pass
def main():
if len(sys.argv) !... | magicoder | python |
You are given a dataset representing the populations of three species (Hare, Lynx, and Carrot) over a certain number of years. The dataset is structured as a 2D array where each row represents a year and each column represents a species. Additionally, you are provided with the corresponding years in a 1D array.
Your t... | ```python
import numpy as np
def process_population_data(populations, years):
# Calculate the standard deviation of the populations for each species
std_dev = populations.std(axis=0)
print("Std:", std_dev)
# Determine the year with the maximum population for each species
max_years = np.argmax(popu... | magicoder | python |
You are tasked with implementing a multithreaded program to display real-time data on a screen. The provided code snippet includes a function `fonction_affichage()` that is intended to run in a separate thread for displaying the data. The function has access to global variables `arret_demande`, `affichage_absolu`, `ecr... | ```python
import threading
import time
class RealTimeDisplay:
def __init__(self):
self.arret_demande = False
self.affichage_absolu = ""
self.ecran = None
self.heure_fin = None
def display_thread(self):
while not self.arret_demande:
if self.ecran is not None:... | magicoder | python |
You are tasked with implementing a traffic monitoring system for a network application. The system should track daily and monthly traffic usage, compare it against predefined limits, and trigger a callback function when certain conditions are met.
You are provided with a code snippet that includes the following releva... | ```cpp
#include <iostream>
#include <string>
class TrafficMonitor {
private:
int day_traffic;
int month_traffic;
int day_limit;
int month_limit;
public:
TrafficMonitor(int day_limit, int month_limit) : day_traffic(0), month_traffic(0), day_limit(day_limit), month_limit(month_limit) {}
void up... | magicoder | cpp |
You are tasked with designing a database schema for a book review system. The system should store information about books, authors, and reviews. Each book can have multiple reviews, and each review is associated with a single book. An author can write multiple books, and each book is authored by a single author. Your t... | ```csharp
using Microsoft.EntityFrameworkCore;
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public DateTime PublicationDate { get; set; }
// Other relevant book details
public int AuthorId { get; set; }
public Author Author { get; set; }
public ICol... | magicoder | csharp |
You are tasked with implementing a simple class that tracks the number of instances created and destroyed. Your goal is to create a class `LiveCount` and a map that associates integers with instances of `LiveCount`. The class should increment a static counter `count` each time an instance is created and decrement it ea... | ```cpp
#include <map>
class LiveCount {
public:
static int count;
LiveCount() {
count++;
}
LiveCount(const LiveCount& other) {
count++;
}
~LiveCount() {
count--;
}
};
int LiveCount::count = 0;
int main() {
std::map<int, LiveCount> map;
// Creating an in... | magicoder | cpp |
You are tasked with creating a unit test for a class that dynamically generates tags and their members. The code snippet provided is a part of a unit test written in C# using the FluentAssertions library. The test is for a method that creates a tag with default members and checks if the descriptions of these members ma... | ```csharp
// Tag class to be implemented
public class Tag
{
private Dictionary<string, string> memberDescriptions = new Dictionary<string, string>();
public static Tag Create<T>(string description)
{
// Create a new instance of the Tag class and set the tag description
Tag tag = new Tag();
... | magicoder | csharp |
You are tasked with creating a program that analyzes a given HTML file to extract information about the structure of the document. Specifically, you need to write a function that takes the HTML content as input and returns the count of different HTML tags present in the file.
For example, given the following HTML cont... | ```python
from bs4 import BeautifulSoup
def count_html_tags(html_content):
tag_counts = {}
soup = BeautifulSoup(html_content, 'html.parser')
tags = [tag.name for tag in soup.find_all()]
for tag in tags:
tag_counts[tag] = tag_counts.get(tag, 0) + 1
return tag_counts
```
The `count_html_tags`... | magicoder | python |
You are tasked with implementing a function that updates a window with a buffer in a graphical application. The function `update_with_buffer` takes three parameters: a reference to the buffer, the width of the buffer, and the height of the buffer. The function returns a result, which may contain an error if the update ... | ```rust
use std::error::Error;
// Define the handle_window_update function
fn handle_window_update(
window: &Window,
buffer: &Buffer,
width: u32,
height: u32,
) -> Result<(), Box<dyn Error>> {
window.update_with_buffer(buffer, width, height)?;
Ok(())
}
```
In the solution, the `handle_window_u... | magicoder | rust |
You are tasked with creating a Rust program that utilizes the `anon_params_edition_hygiene` crate to perform anonymous parameter edition hygiene. The `anon_params_edition_hygiene` crate provides functionality for ensuring that anonymous parameters in a function or closure are properly handled to avoid unintended side e... | ```rust
extern crate anon_params_edition_hygiene;
use anon_params_edition_hygiene::anon_params_edition_hygiene;
fn main() {
// Define a closure that takes two parameters
let closure = |x, y| {
// Attempt to modify the first parameter
x += 1; // This should trigger an error due to anonymous par... | magicoder | rust |
You are tasked with implementing a class that simulates a simple memory management system. The class should support allocating and deallocating memory blocks, as well as defragmenting the memory to optimize space usage.
You are given a partially implemented `MemoryManager` class with the following methods:
```swift
cl... | ```swift
class MemoryManager {
var memory: [Bool]
init(size: Int) {
memory = Array(repeating: false, count: size)
}
func allocate(size: Int) -> Int? {
var startIndex = -1
var count = 0
for i in 0..<memory.count {
if memory[i] {
... | magicoder | swift |
You are given a code snippet that calculates the power of a number using the divide and conquer approach. Your task is to implement a function that performs the same operation as the given code snippet. The function should take two integers, `x` and `y`, as input and return the result of raising `x` to the power of `y`... | ```cpp
#include <iostream>
using namespace std;
typedef long long ll;
ll power(ll x, ll y) {
if (y == 0)
return 1;
ll s = power(x, y / 2);
s *= s;
if (y & 1)
s *= x;
return s;
}
int main() {
ll x = 2, y = 5;
cout << "Power of " << x << " raised to " << y << " is: " << powe... | magicoder | cpp |
You are tasked with creating a Python module that interfaces with a C library using SWIG (Simplified Wrapper and Interface Generator). SWIG is a tool that automatically generates the code needed to bind C/C++ libraries with other programming languages such as Python. The given code snippet shows the commands used to ge... | ```python
# Import the generated Python module
import italgos
# Define the Python function to calculate the nth Fibonacci number using the C library
def calculate_fibonacci(n):
return italgos.fibonacci(n)
```
In this solution, the `italgos` module, generated by SWIG, is imported, and a Python function `calculate_... | magicoder | python |
You are tasked with creating a program that simulates a simple file management system. The program should allow users to perform basic file operations such as creating, reading, updating, and deleting files. Additionally, the program should provide a feature to check the contents of a file and prompt the user to confir... | ```python
import os
import time
def display_reminder():
print("Recuerda borrar los codigos de /Codes.txt/ despues de chekearlos (si los chekeaste ya claro esta, si no puedes dejarlos) ")
time.sleep(2)
print("""
Por favor, seleccione una opción:
1. Crear un nuevo archivo
2. Leer el contenido de... | magicoder | python |
You are tasked with implementing a generic class for managing entity properties in a C# application. The class should support properties with change tracking functionality. Your task is to create a generic class `EntityProperty<T>` that encapsulates a property value and provides change tracking functionality using the ... | ```csharp
public class EntityProperty<T>
{
private T _value;
private T _originalValue;
private bool _isDirty;
public EntityProperty(T value)
{
_value = value;
_originalValue = value;
_isDirty = false;
}
public T Value
{
get { return _value; }
set... | magicoder | csharp |
You are tasked with creating a Python function that parses a given text file to extract copyright information. The copyright information is represented by a block of text enclosed within a pair of comment symbols (e.g., # for Python, // for C++, /* */ for C). The function should return a list of unique copyright statem... | ```python
import re
def extract_copyright_statements(file_path):
with open(file_path, 'r') as file:
content = file.read()
# Extract copyright statements enclosed within comment symbols
copyright_statements = re.findall(r'#(.*?)#', content, re.DOTALL)
# Remove leading and trailing whitespace f... | magicoder | python |
You are tasked with implementing a Swift program that processes a given JSON configuration file to extract specific information about terminal strings. The JSON file contains an array of terminal objects, each with a `name` and a `string` property. The `string` property contains the terminal body, which is a sequence o... | ```swift
import Foundation
enum CharacterSetName: String, Decodable {
case letters, uppercaseLetters, lowercaseLetters, alphaNumerics, decimalDigits, whitespacesAndNewlines, whitespaces, newlines, backslash
}
struct Terminal: Decodable {
let name: String
let string: String
}
func countCharacterSets(in te... | magicoder | swift |
You are tasked with creating a program that simulates a simplified version of the `ack` command-line tool. The `ack` tool is used to search for patterns in text files and display the matching lines. Your program should be able to handle both greedy and non-greedy pattern matching.
Your program should take the followin... | ```python
import re
def search_and_display(pattern, filename):
with open(filename, 'r') as file:
content = file.read()
greedy_matches = re.findall(pattern, content)
non_greedy_matches = re.findall(pattern + '?', content)
print("greedy:")
for match in greedy_matches:
print(match)
... | magicoder | python |
You are tasked with creating a Python function that retrieves and processes data from a web API. The function should use the `requests` library to make a GET request to a specific URL, extract relevant information from the API response, and perform some data processing. Additionally, the function should utilize the `re... | ```python
import requests
import re
import datetime
import functools
def retrieve_and_process_data(url: str) -> str:
# Step 1: Make a GET request to the provided URL
response = requests.get(url)
# Step 2: Extract specific data using the re module
pattern = r'Pattern to match in the response'
m... | magicoder | python |
You are tasked with creating a Python class to manage and track the active statistics of virtual machines in a cloud computing environment. The class should be able to retrieve the active statistics, store them in a database, and provide a method to access the stored data.
Your task is to implement the `VMStatistics` ... | ```python
import datetime
from sqlalchemy import create_engine, Column, Integer, DateTime, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class ActiveVCPUS(Base):
__tablename__ = 'active_vcpus'
id = Column(Integer, primary_k... | magicoder | python |
You are working on a project that involves managing digital wallets and creating pairwise connections between different parties. In this scenario, you need to create a programming function that facilitates the creation of pairwise connections between two digital wallet DIDs (Decentralized Identifiers). The function sho... | ```rust
use indy_sys::ErrorCode;
use indy_sys::callbacks::CallbackUtils;
use std::ffi::CString;
pub fn create_pairwise(wallet_handle: i32, their_did: &str, my_did: &str, metadata: Option<&str>) -> Result<(), ErrorCode> {
let (receiver, command_handle, cb) = CallbackUtils::_closure_to_cb_ec();
let their_did = ... | magicoder | rust |
You are tasked with creating a Python function that simulates a simplified version of a web application testing framework. The function should take a list of test cases as input and return a dictionary containing the test results. Each test case is represented as a dictionary with the following keys: "name", "url", and... | ```python
import requests
def run_tests(test_cases):
results = {}
for test_case in test_cases:
url = test_case["url"]
expected_status = test_case["expected_status"]
try:
response = requests.get(url)
actual_status = response.status_code
if actual_statu... | magicoder | python |
You are tasked with writing a script to automate the configuration of a Kubernetes worker node. The script should set specific environment variables and apply labels to the worker node based on certain conditions.
The script should perform the following tasks:
1. Set the environment variables:
- `ISOLATED_CPUS` to ... | ```bash
#!/bin/bash
# Set environment variables
export ISOLATED_CPUS=1
export RESERVED_CPUS=0
export NON_ISOLATED_CPUS=0
export HUGEPAGES_NUMBER=1
# Identify a non-master node in the Kubernetes cluster
NON_MASTER_NODE=$(oc get nodes --no-headers -o name -l '!node-role.kubernetes.io/master' | head -n1)
# Apply label ... | magicoder | shell |
You are tasked with implementing a function to decode HTML-escaped strings back to their original HTML format. HTML-escaping involves replacing special characters with their corresponding HTML entities, such as `<` for `<` and `>` for `>`. Your task is to create a function that takes an HTML-escaped input string ... | ```csharp
public static string HtmlUnescape(string text)
{
return System.Net.WebUtility.HtmlDecode(text);
}
```
The `HtmlUnescape` function can be implemented using the `System.Net.WebUtility.HtmlDecode` method provided by the .NET framework. This method decodes a string that has been HTML-escaped, converting it b... | magicoder | csharp |
You are tasked with creating a Java program to handle asynchronous data retrieval using RxJava. Your program should make use of the RxJava library to fetch data from a remote API and process the response.
Your program should perform the following steps:
1. Create an interface `NewApi` that defines a method `getBanner`... | ```java
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
// Define the response model for the banner data
class BasicResponse<T> {
private T data;
public T getData() {
... | magicoder | java |
You are tasked with implementing a Python function that dynamically loads all immediate child modules of a given package. A module in Python is a file containing Python definitions and statements. A package is a directory containing an `__init__.py` file and can contain other modules or sub-packages. The function shoul... | ```python
import importlib.util
import pkgutil
def get_child_module(name, package):
absolute_name = f"{package}.{name}"
package_loader = importlib.util.find_spec(absolute_name)
if package_loader is not None and package_loader.submodule_search_locations is not None:
modules = []
for loader, ... | magicoder | python |
You are tasked with implementing a unit test for a media management system in a PHP application. The system allows for associating media with characters in a game. The code snippet provided is a part of the unit test suite for the media management system. Your task is to write a unit test for the `makePrimary` method o... | ```php
/**
* @test
* @covers Nova\Media\Media::makePrimary
*/
public function it_can_set_primary_media_for_character()
{
// Create a mock character
$character = $this->getMockBuilder('Nova\Characters\Character')->getMock();
// Create a media instance
$media = new Nova\Media\Media();
// Set up t... | magicoder | php |
You are tasked with creating a Python function that processes geographical data and generates an HTML embed code for displaying the data on a web page. The function should take in a GeoJSON object representing geographical features and return the HTML embed code for displaying the features on a web page using a mapping... | ```python
from xr_embeds.views import geojson_view, embed_html_view
def generate_geojson_embed_code(geojson_object: dict) -> str:
# Generate URL for accessing the geographical data
geojson_url = geojson_view(geojson_object)
# Generate HTML embed code for displaying the geographical features
embed_... | magicoder | python |
You are tasked with creating a program that reads a WAV audio file, performs a specific operation on the audio data, and then saves the modified audio to a new WAV file. The program should be able to handle audio files with different sample rates and multiple channels.
Your task is to implement a function `process_aud... | ```python
import numpy as np
from scipy.io import wavfile
def normalize_audio(audio_data):
max_amplitude = np.max(np.abs(audio_data))
if max_amplitude > 1.0:
normalized_audio = audio_data / max_amplitude
else:
normalized_audio = audio_data
return normalized_audio
def process_audio_file... | magicoder | python |
You are given a list of joint names representing different parts of a robotic hand. Each joint name consists of a combination of words separated by underscores. Your task is to write a function that extracts the unique base names from the joint names and returns them in a sorted order.
Write a function `extract_base_n... | ```python
from typing import List
def extract_base_names(joint_names: List[str]) -> List[str]:
base_names = set()
for joint_name in joint_names:
base_name = joint_name.split('_')[0]
base_names.add(base_name)
return sorted(list(base_names))
```
The `extract_base_names` function iterates thr... | magicoder | python |
You are tasked with creating a Python class to manage the memory configuration of virtual machines (VMs) in a virtualized environment. The class should include a method to update the memory of a VM. The provided code snippet is a part of the class and contains a method that updates the memory of a VM. Your task is to c... | ```python
import requests
class VMManager:
def __init__(self, href, client):
self.href = href
self.client = client
def update_memory(self, vm_id, virtual_quantity):
# Construct the URI for updating the memory of the VM
uri = f"{self.href}/{vm_id}/virtualHardwareSection/memory"
... | magicoder | python |
You are tasked with implementing a Python class that manages a game board and its associated graphical user interface (GUI). The provided code snippet is part of the class definition and contains some initializations and comments. Your task is to complete the implementation of the class by adding methods to handle the ... | ```python
import wx
class GameBoard:
def __init__(self, board_object):
self.board_object = board_object
self.SIZE = self.board_object.BOARD_SIZE
self.__label_list = []
self.__best_score = 0
self.__current_score = 0
self.initialize_board()
def initialize_boar... | magicoder | python |
You are tasked with creating a program that simulates a simple form validation process. The program should prompt the user to input their name and then validate the input according to specific criteria. The validation process should check for the presence of the name and ensure that it contains only alphabetic characte... | ```python
import re
def validate_name_input(name):
if not name:
return "Name is required"
if not re.match("^[a-zA-Z]+$", name):
return "Name should contain only alphabetic characters"
return "Name is valid"
def main():
name = input("Please enter your name: ")
validation_result = va... | magicoder | python |
You are tasked with implementing a function that will parse a given JavaScript/TypeScript file and extract the default export from a React component. The default export should be returned as a string, including any associated code or comments. You should assume that the default export is a React component and is define... | ```javascript
function extractDefaultExport(fileContent) {
const defaultExportRegex = /export default\s*(class|function)?\s*([A-Za-z$_][A-Za-z0-9$_]*)/;
const match = defaultExportRegex.exec(fileContent);
if (match) {
const exportName = match[2];
const exportRegex = new RegExp(`(class|function)?\\s*${exp... | magicoder | javascript |
You are tasked with implementing a parser for a custom programming language that supports a FOR_LOOP construct. The given code snippet is a part of the parser implementation for the FOR_LOOP construct. The parser is responsible for converting the source code into an abstract syntax tree (AST) for further processing.
T... | ```java
// Define the Node class for representing nodes in the abstract syntax tree (AST)
class Node {
// Implementation of the Node class
// ...
}
// Define the Parser class for parsing the custom programming language
class Parser {
// Constants for defining minimum and maximum priorities
static final... | magicoder | java |
You are tasked with implementing a function to generate a login link for a web application. The login link should direct users to the Shibboleth login page for the server. Shibboleth is an open-source project that provides Single Sign-On capabilities and allows websites to make informed authorization decisions for indi... | ```python
def generate_login_link(request) -> str:
# Assuming the Shibboleth login page URL is known
shibboleth_login_url = "https://example.com/shibboleth-login"
# Constructing the login link based on the request
# For example, adding a return URL parameter to redirect users back to the original page ... | magicoder | python |
You are tasked with creating a function that modifies an Android build.gradle file to update the version code and version name. The build.gradle file contains the version code and version name in a specific format. The function should throw an error if the Android build number is missing from the build.gradle file.
Yo... | ```javascript
function writeVersion(buildGradle, version) {
const versionCodeRegex = /versionCode\s+\d+/m;
const versionNameRegex = /versionName\s+".*"/m;
if (!buildGradle.match(versionCodeRegex) || !buildGradle.match(versionNameRegex)) {
throw new Error('Android build number is missing');
}
const updat... | magicoder | javascript |
You are tasked with simulating a Discrete Element Method (DEM) system for particle dynamics. The given code snippet is a part of a larger simulation program and contains some initial setup, printing of statistics, and the actual simulation execution. Your goal is to implement the DEM simulation using the provided param... | ```python
class CriticalStep:
def __init__(self, perparticle):
self.perparticle = perparticle
self.steps = []
def add_step(self, particle_index, circular_frequency, damping_ratio):
self.steps.append((self.perparticle, particle_index, circular_frequency, damping_ratio))
def __str__(... | magicoder | python |
You are tasked with creating a Python function that interacts with the Open Movie Database (OMDb) API to retrieve information about a movie based on its IMDb index. Your function should take the IMDb index as input and return the movie's title, year of release, genre, and plot summary. You will need to handle potential... | ```python
import requests
def generateIMDb(imdb: str) -> dict:
api_key = "your_api_key" # Replace with your actual OMDb API key
url = f"http://www.omdbapi.com/?i={imdb}&apikey={api_key}"
try:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
... | magicoder | python |
You are tasked with creating a Python function that processes a search query string and returns a dictionary containing the frequency of each word in the query. The function should ignore case sensitivity and punctuation, and only consider alphanumeric characters as part of a word. For example, given the query "apple o... | ```python
import re
def process_query(query: str) -> dict:
# Remove punctuation and convert to lowercase
query = re.sub(r'[^\w\s]', '', query).lower()
# Split the query into words
words = query.split()
# Create a dictionary to store word frequencies
word_freq = {}
# Count the frequency of e... | magicoder | python |
You are tasked with implementing a function to parse a JSON configuration file and extract specific information from it. The JSON file contains configuration settings for a software application, and the function should retrieve and return the values of specific configuration parameters.
You are given the following cod... | ```python
import json
def get_config_from_json(json_file):
"""
Get the config from a JSON file
param: json_file
"""
with open(json_file, 'r') as file:
config_data = json.load(file)
extracted_config = {
'app_name': config_data.get('app_name'),
'debug_mode': config_data.g... | magicoder | python |
You are tasked with creating a Python program that simulates a simple task scheduler. The program should read a list of tasks from a file, schedule them to run at specific times, and execute the tasks asynchronously using asyncio.
The input file, `tasks.txt`, contains task descriptions in the following format:
```
tas... | ```python
import asyncio
from datetime import datetime, timedelta
import os
async def run_task(task_name, start_time, duration):
print(f"Task '{task_name}' started at {start_time}")
await asyncio.sleep(duration)
print(f"Task '{task_name}' completed at {datetime.now().strftime('%H:%M:%S')}")
async def sche... | magicoder | python |
You are tasked with implementing a custom time series data writer in Rust. The `TimeseriesWriter` struct is responsible for writing data points to a file in a specific format. The data points consist of a timestamp and a value, and they are written to the file at regular intervals.
The `TimeseriesWriter` struct has th... | ```rust
use std::fs::File;
use std::io::{Result, Write};
use std::time::{Duration, SystemTime};
struct TimeseriesWriter {
file: File,
buffer_size: usize,
start_time: SystemTime,
interval: Duration,
buffer: Vec<(SystemTime, f64)>,
}
impl TimeseriesWriter {
fn create(file: File, buffer_size: usi... | magicoder | rust |
You are tasked with creating a Python class that simulates a simple banking system. The class should be able to create bank accounts, deposit funds, withdraw funds, and provide the account balance. Additionally, the class should keep track of the total amount of money stored in all accounts.
Create a Python class `Ban... | ```python
class Bank:
def __init__(self):
self.accounts = {} # Dictionary to store account_id: balance pairs
self.total_balance = 0.0
def create_account(self, account_id: int, initial_balance: float) -> None:
if account_id not in self.accounts:
self.accounts[account_id] = i... | magicoder | python |
You are working on a software project that uses Git for version control and Maven for build automation. Your task is to create a script that automates the versioning and deployment process. The provided code snippet is a part of this automation script.
The code snippet performs the following tasks:
1. Checks if the Gi... | ```bash
#!/bin/bash
# Check if the Git repository is clean
if [[ -n $(git status -s) ]]; then
echo "Error: Uncommitted changes in the repository"
exit 1
fi
# Construct the version string
VER="5.1.0-`git log --format="%cd-%h" --date=format:%Y%m%d -n 1`"
# Set the Maven project version
mvn versions:set -DnewVersio... | magicoder | shell |
You are working on a bioinformatics project and need to implement a statistical method for evaluating the significance of data. The method involves calculating the false discovery rate (FDR) for a given set of values. The FDR is the expected proportion of false positives among the rejected hypotheses.
You are given a ... | ```python
def calculate_FDR(p_values, mEvalueCutoff, mFDR):
num_rejected = sum(p <= mEvalueCutoff for p in p_values)
total_rejected = max(1, num_rejected)
FDR = (mFDR * num_rejected) / total_rejected
return FDR
# Example usage
p_values = [0.05, 0.1, 0.2, 0.3, 0.05, 0.08]
mEvalueCutoff = 0.1
mFDR = 0.1
... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.