query
stringlengths
22
16.4k
answer
stringlengths
0
11.4k
resource
stringclasses
4 values
lang
stringclasses
148 values
You are tasked with implementing a function that processes and updates user information based on a given set of rules. The function should take in a user object and perform specific operations on it. The user object contains a property called `praiseCount`, which represents the number of praises received by the user. T...
```swift func processAndUpdateUserInfo(user: User, indexPath: IndexPath) { if user.praiseCount < 0 { user.praiseCount = 0 } // Update user information in the model (Assuming UserModel.updateUserInfo() is responsible for this) UserModel.updateUserInfo(user) // Trigger table view rel...
magicoder
swift
You are tasked with implementing a message update service for a Discord bot using C#. The service should handle reactions added and reactions removed events. You are provided with a partial code snippet for the `MessageUpdateService` class, which includes a `DiscordSocketClient` field and two events for reaction added ...
```csharp using Discord.WebSocket; using System; namespace TournamentAssistantShared.Discord.Services { public class MessageUpdateService { private DiscordSocketClient _discordClient; public event Action<SocketReaction> ReactionAdded; public event Action<SocketReaction> ReactionRemoved...
magicoder
csharp
You are tasked with creating a Python function that processes a list of activities and an intent, and then logs the activities to a database. The function should filter out the intent from the list of activities before logging them. The activities are represented as a list of strings, and the intent is a single string....
```python from sqlalchemy import Column, String, Integer, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class ActivityLog(Base): __tablename__ = 'activity_log' id = Column(Integer, primary_key=True) activity = Column...
magicoder
python
You are tasked with implementing a Python class that handles authentication and data retrieval from a REST API. The class should inherit from the `Auth` class and have three private class variables: `_endpoint1`, `_endpoint2`, and `_endpoint3`. The `_endpoint1` variable should be set to the string "user/tokens", the `_...
```python class Auth: # Assume the implementation of the Auth class for handling authentication class Value(Auth): _endpoint1 = "user/tokens" _endpoint2 = "value" _endpoint3 = None def __init__(self, username, password): super().__init__(username, password) # Assuming Auth class requires ...
magicoder
python
You are working on a security system that requires storing and validating user tokens. The tokens are stored in a file named `tokenfile.py` and are encrypted using a simple algorithm. The encrypted token is in the form of a string and is stored in the `token` variable within the file. Your task is to write a Python fun...
```python def validate_token(password: str) -> bool: encrypted_token = "MjM4NDk0NzU2NTIxMzc3Nzky.CunGFQ.wUILz7z6HoJzVeq6pyHPmVgQgV4" decrypted_token = "" shift = len(password) # Use the length of the password as the shift value for char in encrypted_token: if char.isalpha(): if cha...
magicoder
python
You are tasked with creating a simple Line chatbot using the Python programming language. The code snippet provided is a part of the chatbot's event handling logic. The chatbot is designed to respond to different types of events, such as receiving a text message or a postback event. Your task is to implement the funct...
```python from linebot import LineBotApi, WebhookHandler from linebot.models import MessageEvent, TextMessage, PostbackEvent from linebot.exceptions import LineBotApiError from linebot.models import TextSendMessage # Initialize Line bot API and Webhook handler line_bot_api = LineBotApi('YOUR_CHANNEL_ACCESS_TOKEN') han...
magicoder
python
You are given a code snippet that uses a Segment Tree to perform range queries on a given array. Your task is to implement a similar functionality using a Segment Tree to efficiently answer range queries on an array of integers. You need to implement a class `SegmentTree` that supports the following operations: 1. `bu...
```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; template <typename T> class SegmentTree { private: vector<T> tree; int n; void buildTree(const vector<T>& arr, int v, int tl, int tr) { if (tl == tr) { tree[v] = arr[tl]; } else { ...
magicoder
cpp
You are tasked with implementing a function that performs grid search cross-validation for a machine learning model. Grid search cross-validation is a technique used to tune hyperparameters for a model by exhaustively searching through a specified subset of hyperparameter combinations and evaluating each combination us...
```python from sklearn.model_selection import GridSearchCV, cross_val_score def fit_grid(param_grid): # Perform grid search cross-validation grid_search = GridSearchCV(model, param_grid, cv=cv) grid_search.fit(X, y) best_params = grid_search.best_params_ return best_params def calculate_mse(model,...
magicoder
python
You are tasked with creating a Python function that utilizes the `synphot` library to perform photometric calculations on astronomical data. The `synphot` library is used for synthetic photometry, which involves simulating the measurement of the flux of an astronomical object through a set of filters. Your function sho...
```python import synphot def calculate_synthetic_photometry(object_spectrum, filter_bandpass): try: # Perform synthetic photometry using synphot library synthetic_flux = synphot.Observation(object_spectrum, filter_bandpass).effstim('abmag') return synthetic_flux except ImportError: ...
magicoder
python
You are given a database schema for a role-playing game (RPG) with two tables: `character` and `weapon`. The `character` table contains information about different characters in the game, including their unique `character_id`. The `weapon` table contains information about the weapons owned by the characters, with each ...
```sql SELECT character.character_id, COUNT(DISTINCT weapon.item_ptr_id) as weapon_count FROM character LEFT JOIN weapon ON character.character_id = weapon.item_ptr_id GROUP BY character.character_id; ``` In the solution, we use a `LEFT JOIN` to ensure that all characters are included in the result, even i...
magicoder
sql
You are tasked with implementing a data collection system for a weather monitoring device. The device has two modes of operation: `CONT_TEMP` and `CONT_PRESTEMP`. In `CONT_TEMP` mode, the device takes temperature measurements at the current temperature rate, while the pressure is not updated. In `CONT_PRESTEMP` mode, t...
```python class WeatherMonitor: def __init__(self, temperature_rate, pressure_rate): self.temperature_rate = temperature_rate self.pressure_rate = pressure_rate self.mode = None def set_mode(self, mode): if mode == "CONT_TEMP" or mode == "CONT_PRESTEMP": self.mode = ...
magicoder
python
You are tasked with creating a Swift program to manage and analyze weather conditions. The program should include a class `WeatherManager` with a property `weather` that stores an array of `WeatherCondition` objects. The `WeatherCondition` class should have properties to store the date, temperature, and description of ...
```swift class WeatherCondition { var date: String var temperature: Double var description: String init(date: String, temperature: Double, description: String) { self.date = date self.temperature = temperature self.description = description } } class WeatherManager { ...
magicoder
swift
You are tasked with implementing a simplified version of a task processing system. The system is designed to process different types of tasks, such as heartbeats, data updates, and alerts. Your goal is to create a class that can handle the processing of heartbeats and warnings. You are provided with a partial code sni...
```cpp #include <iostream> #include <string> // Define the Task class class Task { public: std::string type; std::string data; Task(std::string type, std::string data) : type(type), data(data) {} }; // Implement the L2MdApi class class L2MdApi { public: void processHeartBeatWarning(Task task) { ...
magicoder
cpp
You are tasked with creating a function that will traverse a directory and return a list of all files with specific file extensions, excluding any subdirectories. You are given a code snippet that includes some relevant logic for handling file extensions and directories. Your task is to complete the function based on t...
```swift func listFiles(withExtensions allowFileTypes: Set<String>, atPath path: String) -> [String] { var files: [String] = [] guard let contents = try? FileManager.default.contentsOfDirectory(atPath: path) else { return files } for file in contents { let filePath = "\(path)/\...
magicoder
swift
You are given a Python program that processes training data for a machine learning model. The program extracts training features and targets from the full dataset and then checks if there is only one feature available for training. Your task is to implement a function that performs the same processing as the given code...
```python def process_training_data(features, targets, i_train): features_train = [features[i] for i in i_train] targets_train = [targets[i] for i in i_train] if len(features_train) == 1: features_train = features_train[0] return features_train, targets_train ``` The `process_training_data` func...
magicoder
python
You are tasked with implementing a function to calculate the total cost of a payment, including shipping and tax, based on the country and shipping type. You are given a class `PhysicalAddress` with a method `getCountryCode()` that returns the country code of the address. The class also has a property `$_countryCostsMa...
```php public function calculateTotalCost($physicalAddress, $shippingType, $paymentTotal) { if (array_key_exists($physicalAddress->getCountryCode(), $this->_countryCostsMatrix)) { $countryData = $this->_countryCostsMatrix[$physicalAddress->getCountryCode()]; if (array_key_exists($shippingType, $coun...
magicoder
php
You are tasked with creating a program to manage the expiration of welcome notifications for a browser extension. The program should handle setting and checking preferences related to the notification expiration. Your task is to implement a class or module that provides methods for setting and retrieving preferences r...
```java public class WelcomeNotificationManager { private Preferences preferences; public WelcomeNotificationManager(Preferences preferences) { this.preferences = preferences; } public void setWelcomeNotificationDismissed(boolean dismissed) { preferences.setBooleanPref("kWelcomeNotific...
magicoder
java
You are given a list of integers as input. For each integer in the list, you need to calculate a new value using the formula (integer / 2) + 1, and then output the result for each integer on a new line. Write a program that takes the input list of integers and applies the given formula to each integer, then outputs th...
```python n = int(input()) integers = list(map(int, input().split())) for i in range(n): result = integers[i] // 2 + 1 print(result) ``` The solution first reads the integer n representing the number of integers in the list. Then, it reads the list of integers. It iterates through the list, applies the formul...
magicoder
python
You are tasked with implementing a module system for managing scientific experiments in a research laboratory. The provided code snippet is a part of the module system for experiment management. The system consists of three modules: `create`, `delete`, and `edit`, each responsible for creating, deleting, and editing ex...
```rust // view.rs pub trait ViewExperiment { fn view_details(&self, experiment_id: u32); } pub struct ExperimentViewer; impl ExperimentViewer { pub fn new() -> Self { ExperimentViewer } } impl ViewExperiment for ExperimentViewer { fn view_details(&self, experiment_id: u32) { // Fetch...
magicoder
rust
You are given a binary tree represented by a Node class. Each node has a value and pointers to its left and right children. The tree is constructed using the following code snippet: ```python class Node: def __init__(self, value): self.value = value self.left = None self.right = None def c...
```python class Node: def __init__(self, value): self.value = value self.left = None self.right = None def calculate_tree_sum(root): if root is None: return 0 return root.value + calculate_tree_sum(root.left) + calculate_tree_sum(root.right) # Construct the tree root = Node...
magicoder
python
You are tasked with implementing a PID (Process Identifier) allocator for a simple operating system. The provided code snippet is part of a PID allocator implementation in Rust. The `get_unique_pid` function is responsible for allocating a unique PID and marking it as used. The `allocator` is an instance of a PID alloc...
```rust /// Represents a Process Identifier (PID). type Pid = u32; /// Represents an error number. type Errno = u32; /// Maximum PID value. const MAX_PID: Pid = 65535; /// Represents a PID allocator. struct PidAllocator { used: Vec<bool>, } impl PidAllocator { /// Creates a new PID allocator with the specif...
magicoder
rust
You are given a directed graph represented as an adjacency list and a starting node. Your task is to implement a depth-first search (DFS) algorithm to find all possible routes from the starting node to all other nodes in the graph. Each route should be represented as a list of nodes visited in sequence. You should imp...
```python def dfs_routes(graph, start_node): def dfs(route, node): if node == start_node and len(route) > 1: # Avoid cycles and self-loops return if len(route) == len(graph): # All nodes visited result.append(route[:]) return for dest in graph[node]: ...
magicoder
python
You are tasked with implementing a function to calculate the division of two floating-point numbers. The function should return a `Result` type, where the successful division result is wrapped in `Ok`, and any division by zero should result in an error of type `Error`. You are given the following code snippet as a sta...
```rust #[derive(Debug, PartialEq)] enum Error { DIVIDE_BY_ZERO, } fn div(x: f32, y: f32) -> Result<f32, Error> { if y == 0.0 { Err(Error::DIVIDE_BY_ZERO) } else { Ok(x / y) } } fn main() { // Test cases assert_eq!(div(10.0, 2.0), Ok(5.0)); assert_eq!(div(5.0, 0.0), Err(Err...
magicoder
rust
You are tasked with implementing a Python class for a linear transformation layer in a neural network. The class, named `Linear`, should inherit from a superclass and have the ability to initialize its weights and biases using various initialization methods. Your task is to complete the implementation of the `Linear` c...
```python import torch def lecun_normal_init_(tensor): # Implementation of the lecun_normal_init_ function pass class Linear: def __init__(self, in_dim, out_dim, bias=True, init_fn=None, init="default"): """ Initializes the Linear layer with input and output dimensions, and initializes wei...
magicoder
python
You are working as a system administrator for a company that uses Nagios for monitoring their IT infrastructure. As part of your responsibilities, you need to write a script to automate the process of updating the Nagios configuration files. The provided code snippet is a part of the script you are working on. It is r...
```bash #!/bin/bash TEMP_DIR="/tmp/" OUTPUT_DIR="/path/to/output/dir/" CONF_ARCHIVE="nagios_conf.tar" NAGIOS_DIR="/etc/nagios/" if [ "${OUTPUT_DIR}${CONF_ARCHIVE}" -nt "${TEMP_DIR}${CONF_ARCHIVE}" ] ; then cp -p "${OUTPUT_DIR}${CONF_ARCHIVE}" "${TEMP_DIR}${CONF_ARCHIVE}" tar -xf "${TEMP_DIR}${CONF_ARCHIVE}" -...
magicoder
shell
You are tasked with implementing a Python class decorator that ensures only one instance of a class is created, regardless of how many times the class is instantiated. The decorator should maintain a dictionary of instances created for each class and return the existing instance if the class has already been instantiat...
```python def singleton(cls): instances = {} def get_instance(*args, **kwargs): key = (cls, args, frozenset(kwargs.items())) if key not in instances: instances[key] = cls(*args, **kwargs) return instances[key] return get_instance @singleton class MyClass: def __ini...
magicoder
python
You are tasked with implementing a logging system for a weather modeling application. The application consists of multiple modules, including `weather_models`, each of which requires its own logger for tracking events and errors. Your goal is to create a logging system that allows each module to have its own logger ins...
```python import logging class WeatherLogger: def __init__(self): self.default_logger = logging.getLogger('weather_models') self.default_logger.setLevel(logging.INFO) # Set default logging level to INFO formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ...
magicoder
python
You are tasked with implementing a class that represents the supported OAuth flows for an OpenAPI specification. The class should allow for the configuration of various OAuth flows and be capable of being encoded into a specific format. Your task is to create the `OpenAPIOAuthFlows` class with the necessary properties ...
```swift import Foundation /// Represents an OAuth 2.0 flow for OpenAPI specification. public class OpenAPIOAuthFlow: Encodable { // Properties representing the OAuth 2.0 flow details // ... public init(/* Initialize properties for the OAuth flow */) { // Initialize the properties } // Im...
magicoder
swift
You are tasked with creating a custom Django form for a search functionality that integrates with Elasticstack, a popular tool for searching and analyzing data in real time. Your form should allow users to input a search query and specify the search index to be used. Additionally, the form should include validation to ...
```python from django import forms from django.test import TestCase from elasticstack.forms import SearchForm class SearchForm(forms.Form): query = forms.CharField(max_length=100, required=True) index = forms.CharField(max_length=100, required=True) class TestSearchForm(TestCase): def test_search_form(sel...
magicoder
python
You are given a 2D list `f1` representing a binary image. Each element in the list is either 0 or 1, where 1 represents a white pixel and 0 represents a black pixel. Your task is to write a function that takes this 2D list as input and returns the coordinates of the bounding box surrounding the white pixels in the imag...
```python def find_bounding_box(f1): rows = len(f1) cols = len(f1[0]) min_row, min_col, max_row, max_col = float('inf'), float('inf'), 0, 0 for i in range(rows): for j in range(cols): if f1[i][j] == 1: min_row = min(min_row, i) min_col = min(min_c...
magicoder
python
You are tasked with creating a custom decorator in TypeScript for Angular applications. The decorator should log a message to the console whenever the decorated component's change detection strategy is set to OnPush. Your task is to implement the `LogOnPush` decorator and apply it to the `BlogHeaderComponent` class pr...
```typescript // Define the LogOnPush decorator function LogOnPush(target: any) { const originalNgOnInit = target.prototype.ngOnInit; target.prototype.ngOnInit = function () { if (this.changeDetection === ChangeDetectionStrategy.OnPush) { console.log('Change detection strategy set to OnPush'); } ...
magicoder
typescript
You are tasked with implementing a custom Ant task that utilizes the Apache Velocity library to perform XML transformations. The task is to create a Java class that can be used within an Ant build script to replace XSLT for XML transformations. Your task is to implement the necessary methods and configurations to achie...
```java import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class VelocityXmlTran...
magicoder
java
You are tasked with implementing a genetic algorithm for optimizing a specific problem. The genetic algorithm involves tournament selection, crossover, and mutation operations. The crossover operation can be one of three types: exponential, binomial, or single. Similarly, the mutation operation can be one of three type...
To solve this problem, you can implement the genetic algorithm using the provided selection, crossover, and mutation operations. Here's a high-level overview of the solution: 1. Tournament Selection: - Implement a tournament selection function that selects individuals for reproduction based on their fitness. The to...
magicoder
python
You are tasked with implementing a function that processes a list of image filters and their corresponding parameters. The function should apply these filters to an input image and return the processed image. The filters can include operations such as blurring, sharpening, edge detection, and color manipulation. Each f...
```python from PIL import Image, ImageFilter, ImageEnhance, ImageOps from typing import List, Dict, Union def apply_filters(image: Image, filters: List[Dict[str, Union[str, int, float, bool]]]) -> Image: processed_image = image for f in filters: filter_type = f["type"] if filter_type == "blur":...
magicoder
python
You are tasked with implementing a class for handling time values in a Python application. The class, named `TimeHandler`, is responsible for storing and manipulating time values in a specific format. The class has a method for setting the time value and a property for retrieving the time value. The `TimeHandler` clas...
```python class TimeHandler: def __init__(self, delta_T_format, delta_T_format_name, name, allowed_units=None): self.delta_T_format = delta_T_format self.delta_T_format_name = delta_T_format_name self.name = name self.allowed_units = allowed_units self._time_value = None ...
magicoder
python
You are tasked with creating a custom decorator in Python that replicates the functionality of the `@method_decorator` used in Django's class-based views. The decorator should be able to apply a specified function decorator to a class method. Write a Python function called `custom_method_decorator` that takes two argu...
```python def custom_method_decorator(decorator_func, name): def decorate_method(cls): method = getattr(cls, name) setattr(cls, name, decorator_func(method)) return cls return decorate_method ``` The `custom_method_decorator` function takes a `decorator_func` and a `name` as input and r...
magicoder
python
You are tasked with implementing a feature for a web application that involves creating a confirmation dialog for deleting items. The application uses PHP and the Yii framework for backend development. The code snippet provided is a part of a view file that renders a delete button for an item. The button is styled with...
```php function generateDeleteButton($itemId) { $html = '<form action="delete-item/' . $itemId . '" method="post">'; $html .= '<button type="submit" class="btn btn-danger" data-confirm="Are you sure you want to delete this item?" data-method="post">Delete</button>'; $html .= '</form>'; return $html; } `...
magicoder
php
You are tasked with implementing a class that manages a collection of data and provides notifications when the data changes. Your task is to complete the implementation of the `DataModel` class by adding the necessary code to support the `INotifyPropertyChanged` interface. Additionally, you need to implement a method t...
```csharp using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Controls; public class DataModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private List<string> data; public List<string> Data { get { return ...
magicoder
csharp
You are tasked with creating a method to validate the correctness of a table's metadata in a database. The table metadata includes the names of the columns and their corresponding data types. You are given a class `TableMetadata` with a method `getColumnNames()` that returns a list of column names in the table. Additio...
```java public boolean validateTableMetadata(TableMetadata tableMetadata) { List<String> expectedColumnNames = Arrays.asList( "COL_NAME1", "COL_NAME2", "COL_NAME3", "COL_NAME4", "COL_NAME5", "COL_NAME6", "COL_NAME7", "COL_NAME8", "COL_NAME9", "COL_NAME10", "COL_NAME11" ); // Validat...
magicoder
java
You are tasked with implementing a Python function that calculates the sum of all even Fibonacci numbers up to a given limit. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. For example, the first few Fibonacci numbers are 0, 1, 1, ...
```python def even_fibonacci_sum(limit): # Initialize the first two Fibonacci numbers fib1, fib2 = 0, 1 even_sum = 0 # Iterate through the Fibonacci sequence and calculate the sum of even numbers while fib2 <= limit: if fib2 % 2 == 0: even_sum += fib2 fib1, fib2 = fi...
magicoder
python
You are tasked with implementing a Python class for warping numerical values using square root transformation. The class should support both regular and inverted square root transformations. Additionally, you need to write a function to perform unit testing for the implemented class using the `pytest` framework. Your ...
```python import pytest from collections import namedtuple class SquareRootWarping: def __init__(self, offset, is_inverted): self.offset = offset self.is_inverted = is_inverted def warp(self, value): if value < 0 and not self.is_inverted: raise ValueError("Cannot perform s...
magicoder
python
You are tasked with implementing a function that copies a specified number of points from a given root in a graph. The graph is represented using an adjacency list, and the function should return a new graph containing the copied points and their connections. You are given the following function signature: ```python d...
```python from typing import Dict, List def copy_points( root: str, n_points_to_copy=50, ) -> Dict[str, List[str]]: """ Copies n_points_to_copy number of points from the given root in the graph and returns the new graph. Args: - root: A string representing the root point from which to start co...
magicoder
python
You are tasked with implementing a simplified version of a URL routing system using Python. Your goal is to create a function that takes a list of URL patterns and a URL as input, and returns the corresponding view function for the given URL. Each URL pattern consists of a path and its associated view function. The UR...
```python from typing import List, Tuple, Callable, Optional def resolve_url(url_patterns: List[Tuple[str, Callable]], url: str) -> Optional[Callable]: for pattern, view_func in url_patterns: pattern_parts = pattern.split('/') url_parts = url.split('/') if len(pattern_parts) != len(url_part...
magicoder
python
You are tasked with creating a Python function that processes a list of integers and returns the sum of all the even numbers in the list. However, there's a catch - you must implement the function without using any conditional statements (if, else, etc.) or the modulo operator (%). Your task is to implement the functi...
```python def sum_even_numbers(nums): # Initialize the sum to 0 total_sum = 0 # Iterate through the list of numbers for num in nums: # Calculate the product of the boolean value of (num % 2) and num # If num is even, (num % 2) will be 0, and the product will be 0 # If num is...
magicoder
python
You are working on a text processing task using Apache Spark and need to implement a feature extraction technique called HashingTF. HashingTF is a method for turning a collection of text documents into numerical feature vectors. In this problem, you will be asked to implement the HashingTF feature extraction using the ...
```python from pyspark import SparkContext from pyspark.mllib.feature import HashingTF from pyspark.mllib.linalg import Vectors # Define the Spark context sc = SparkContext("local", "HashingTFExample") # Define the HashingTF class class HashingTF: def __init__(self, numFeatures=1048576): self.numFeatures ...
magicoder
python
You are tasked with creating a Python function that retrieves the SHA hash of the latest commit in a Git repository using the `gitpython` library. Your function should take the path to the local Git repository as an argument and return the SHA hash of the latest commit. The function signature should be: ```python def ...
```python import git def get_latest_commit_sha(repo_path: str) -> str: repo = git.Repo(repo_path) sha = repo.head.object.hexsha return sha ``` The `gitpython` library is used to interact with the Git repository. We create a `git.Repo` object using the provided `repo_path` and then retrieve the SHA hash of...
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. Additionally, the program should enforce certain security measures, such as requiring a PIN to access an account. Your task is to implem...
```java import java.util.HashMap; class BankAccount { private int accountNumber; private double balance; private String pin; public BankAccount(int accountNumber, double initialBalance, String pin) { this.accountNumber = accountNumber; this.balance = initialBalance; this.pin = ...
magicoder
java
You are tasked with creating a language translation function that takes a language code and a phrase in English as input and returns the translated phrase in the specified language. The translation function should be able to handle variable substitution, where placeholders like `%(user_count)s` or `%d` are replaced wit...
```python def translate(language_code, phrase, variables=None): if language_code in languages: language = languages[language_code] if phrase in language: translated_phrase = language[phrase] if variables: if isinstance(variables, dict): tra...
magicoder
python
You are tasked with implementing a simple key-value store in Python. The key-value store should support setting a key-value pair, getting the value for a given key, and deleting a key-value pair. Additionally, the key-value store should support a feature to write the key-value pairs to a file and assert that the writte...
```python class KeyValueStore: def __init__(self): self.key_value_pairs = {} def set(self, key, value): self.key_value_pairs[key] = value def get(self, key): return self.key_value_pairs.get(key) def delete(self, key): if key in self.key_value_pairs: del sel...
magicoder
python
You are tasked with creating a program that simulates a simple vending machine. The vending machine should be able to dispense items based on user input and maintain an inventory of available items. The items available for purchase will be predefined, and the vending machine should handle invalid inputs gracefully. Yo...
```python class VendingMachine: def __init__(self, initial_inventory): self.inventory = initial_inventory def dispense_item(self, item_name): if item_name in self.inventory and self.inventory[item_name] > 0: self.inventory[item_name] -= 1 return item_name else: ...
magicoder
python
You are tasked with creating a program that simulates a simple banking system. The program should allow users to create accounts, deposit and withdraw funds, and check their balance. The program should also keep track of the account holders' information and account balances. Your task is to implement the Account class...
```python class Account: account_number = 0 def __init__(self, holder_name, initial_balance): self.holder_name = holder_name self.balance = initial_balance Account.account_number += 1 self.account_number = Account.account_number def deposit(self, amount): if amount ...
magicoder
python
You are tasked with creating a Python script that will analyze the performance of a given statement by running it a specified number of times using cProfile. The script should take the statement and the number of times to run it as input, and then output the profiling results. Your task is to implement the `runprofile...
```python import os import subprocess HOME = os.path.dirname(__file__) def runprofile(STATEMENT, TIMES): os.chdir(HOME) command = f"PYTHONPATH=. python -m cProfile -s cumulative neo4j/__main__.py -qx '{TIMES}' '{STATEMENT}'" subprocess.run(command, shell=True) # Example usage runprofile("print('Hello, wo...
magicoder
python
You are tasked with implementing a function to match UUIDs from the `before` and `after` targets/children for continuity. The function should take two input dictionaries, `before` and `after`, and return a mapping of UUID matches between the two. The `before` dictionary contains the following keys: - `uuid`: a UUID re...
```python import typing class Dependency: def __init__(self, kind, package_names): self.kind = kind self.package_names = package_names def get_package_names(self): return self.package_names def match_uuids(before: dict, after: dict) -> dict: after.data["_uuid"] = before.uuid a...
magicoder
python
You are tasked with creating a Python script to automate the minimization of input files for a binary analysis tool. The script will iterate through a directory of vulnerability output files, extract relevant information from the file names, and then use this information to minimize the input files for each binary. Th...
```python import os import glob def run_cmd(command): # Implementation of the run_cmd function is not provided in the given code snippet pass def minimize(binary_id, pov_name): # Implementation of the minimize function is not provided in the given code snippet pass showmap_path = "/home/angr/.virtual...
magicoder
python
You are tasked with implementing a genetic algorithm to solve the classic game of Russian Roulette. In this game, a single bullet is placed in a revolver, the chamber is spun, and players take turns firing the gun at their own head. The chamber rotates after each pull of the trigger, so there is a chance that the bulle...
To solve this problem, you can start by defining the representation of individuals in the population. Each individual can be represented as a binary string, where each bit corresponds to a pull of the trigger in a round of Russian Roulette. A '0' represents a safe pull, and a '1' represents a risky pull. Next, you nee...
magicoder
python
You are tasked with implementing a program that converts strings between UTF-8 and UTF-16 encoding. UTF-8 and UTF-16 are variable-length character encoding formats used to represent Unicode characters. In this problem, you need to create two functions: one to convert a UTF-16 string to a UTF-8 string and another to con...
```cpp #include <string> #include <codecvt> #include <locale> std::string FromWideString(const std::u16string& str) { std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter; return converter.to_bytes(str); } std::u16string ToWideString(const std::string& str) { std::wstring_convert<st...
magicoder
cpp
You are tasked with implementing a file indexing system that processes various types of files and extracts specific information from them. The system should be able to identify and index files with extensions ".html", ".htm", and ".txt". For HTML files, a unique identifier (UID) needs to be constructed for each documen...
```java import java.io.File; public class FileIndexingSystem { private boolean deleting; // Flag to indicate file deletion // Function to index files with specific extensions public void indexDocs(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); if (f...
magicoder
java
You are tasked with implementing a custom view controller transition in an iOS app. The goal is to create a smooth transition from a presenting view controller to an upgraded view controller. The code snippet provided demonstrates the dismissal of the presenting view controller and the subsequent presentation of the up...
To achieve a custom transition between the presenting view controller and the upgraded view controller, you can use the `UIViewControllerAnimatedTransitioning` protocol to define the custom animation. Below is an example of how you can implement the custom transition animation: ```swift class CustomTransitionAnimator:...
magicoder
swift
You are tasked with implementing a chess position parser that can read a Forsyth-Edwards Notation (FEN) string and construct a corresponding chess position object. The FEN string represents a particular board position in a chess game. It contains information about the placement of pieces, the current player's turn, cas...
```java public class Position { private char[][] board; private char activeColor; private boolean[] castlingAvailability; private String enPassantTarget; private int halfmoveClock; private int fullmoveNumber; public Position() { // Initialize the board and other attributes } ...
magicoder
java
You are given a large integer `q = 590872612825179551336102196593`. Your task is to write a program to find the prime factors of this integer and then calculate the sum of all the distinct prime factors. Write a function `sum_of_distinct_prime_factors(q)` that takes the integer `q` as input and returns the sum of all ...
```python def sum_of_distinct_prime_factors(q): factors = set() divisor = 2 while q > 1: while q % divisor == 0: factors.add(divisor) q //= divisor divisor += 1 return sum(factors) q = 590872612825179551336102196593 print(sum_of_distinct_prime_factors(q)) # Outp...
magicoder
python
You are tasked with creating a CMake build system for a project that consists of multiple source files and requires linking with external libraries. Your project structure is as follows: ``` project/ CMakeLists.txt src/ main.cpp utils/ helper.cpp helper.h include/ ...
```cmake cmake_minimum_required(VERSION 3.10) project(MyProject) # Set the source files set(SOURCES src/main.cpp src/utils/helper.cpp ) # Set the include directories include_directories(include) # Set the target executable and link with external library add_executable(MyExecutable ${SOURCES}) target_link_l...
magicoder
cmake
You are working on a testing framework for a data processing application. The code snippet provided is a part of a test case class that involves setting up and tearing down a dataset for testing purposes. The `setUpClass` method is responsible for creating a dataset using a client's method `create_dataset` and the `tea...
```python class Client: @staticmethod def create_dataset(unique_name, dataset_format, content, tags): # Implement the logic to create a dataset using the provided parameters # For example: # dataset = { # 'unique_name': unique_name, # 'format': dataset_format, ...
magicoder
python
You are tasked with implementing a simplified version of the `Future` trait in Rust. The `Future` trait represents a value that may not be available yet, but will be resolved in the future. Your goal is to implement the `poll` method for a custom `Future` type. You are provided with a code snippet that defines a trait...
```rust pub type Poll<T, E> = Result<T, E>; struct CustomFuture { polled: bool, } impl Future for CustomFuture { type Item = i32; type Error = String; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if self.polled { Err("Not ready yet".to_string()) } else { ...
magicoder
rust
You are tasked with implementing a custom sorting algorithm for a list of dictionaries representing products. Each dictionary contains the product's name, price, and creation date. The sorting should be based on the creation date in descending order, meaning the most recently created products should appear first. If tw...
```python def custom_sort_products(products): sorted_products = sorted(products, key=lambda x: (-x['created'], x['price'], id(x))) return sorted_products ``` The `custom_sort_products` function takes the list of products as input and uses the `sorted` function with a custom sorting key. The key function sorts ...
magicoder
python
You are tasked with automating the compilation and execution process for a neural network inference wrapper. The given code snippet demonstrates the compilation and execution steps for a wrapper_nn_2 program, which includes generated convolutional layers using both Halide and Tiramisu libraries. Your task is to create ...
```bash #!/bin/bash # Step 1: Compile Halide-based convolution generator echo "Compiling conv_layer_generator_2 (Halide-based convolution generator)" ./compile_tiramisu_code.sh conv_layer_generator_2_tiramisu.cpp # Step 2: Run Halide-based convolution generator echo "Running conv_layer_generator_2 (Halide-based convo...
magicoder
shell
You are tasked with setting up a basic web application using ASP.NET Core. Your goal is to configure the application to include essential services and middleware for handling HTTP requests, managing database connections, and integrating various web services. Given the provided code snippet, you need to complete the con...
```csharp using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using MyProject.Configuration; using MyProject.Data; using MyProject.Services.DomainServices.Messaging; using MyProject.WebFramework.ServiceConfiguration.Id...
magicoder
csharp
You are tasked with implementing a ShareManager struct in Swift that conforms to two protocols: Configurable and Shareable. The ShareManager struct should have a static property called keys, which is a dictionary of dictionaries used to store registered keys for sharing. Your task is to complete the implementation of ...
```swift // Sample usage of the ShareManager struct ShareManager.registerKey(key: "public", subkey: "message", value: "Hello, World!") // Accessing the registered keys print(ShareManager.keys) // Output: ["public": ["message": "Hello, World!"]] ```
magicoder
swift
You are given a scenario where a mouse is trying to escape from two cats. The positions of the mouse and the cats are represented on a 1-dimensional coordinate system. The positions of the cats are represented by integers `x` and `y`, and the position of the mouse is represented by integer `z`. The distance between the...
```python def mouseEscape(x: int, y: int, z: int) -> str: distCatA = abs(z - x) distCatB = abs(z - y) if distCatA < distCatB: return "Mouse A" elif distCatB < distCatA: return "Mouse B" else: return "Mouse C" ```
magicoder
python
You are given a list of assignments representing the mapping of one scripting language to another. Each assignment takes the form of `language = (script)`, where `language` is the name of the language and `script` is the scripting language it is mapped to. The script can be another language or `None`. Your task is to w...
```python def find_unique_languages(assignments): unique_languages = set() dependencies = {} for assignment in assignments: language, script = assignment.split(' = ') language = language.strip() script = script.strip('()') if script != 'None': dependencies[languag...
magicoder
python
You are tasked with creating a multithreaded program to process a queue of tasks using Python's threading module. The program should create multiple worker threads, each responsible for processing tasks from the queue concurrently. Your task is to implement the WorkerThread class and the main program logic to achieve t...
```python import threading import queue class WorkerThread(threading.Thread): def __init__(self, queue, id): threading.Thread.__init__(self) self.queue = queue self.id = id def run(self): print("WorkerThread %d started" % self.id) while True: task = self.que...
magicoder
python
You are tasked with creating a Python class that simulates a real-time log monitor. The class should allow users to continuously monitor a log file and display new log entries in real-time on the console. The log monitor should be able to handle log files of any size and should not block the main thread while monitorin...
```python import time import os class LogMonitor: def __init__(self, log_file_path): self.log_file_path = log_file_path self.running = False def start_monitoring(self): self.running = True with open(self.log_file_path, 'r') as log_file: log_file.seek(0, os.SEEK_END)...
magicoder
python
You are working on a project that involves processing EEG (electroencephalography) data using the MNE-Python library. Your task is to create a function that takes a file containing raw EEG data, processes it, and returns specific information about the data. You are given the following code snippet as a starting point:...
```python def get_bads(rawf): # Implement the logic to identify bad channels based on the given criteria bad_channels = [] # Criteria 1: Channels with excessive noise levels noise_threshold = 100 # Example threshold for noise level for ch in rawf.info['ch_names']: if any(abs(rawf[ch][0...
magicoder
python
You are tasked with creating a program that processes a list of image URLs and applies a box shadow effect to each image. The program should read the list of image URLs from a file, apply the box shadow effect to each image, and then save the modified images to a specified output directory. Your program should use the...
```python import requests from PIL import Image from io import BytesIO import os # Function to apply box shadow effect to an image def apply_box_shadow(image_path, output_path): img = Image.open(image_path) img_with_shadow = Image.new("RGBA", img.size) img_with_shadow.paste(img, (0, 0), img) shadow = I...
magicoder
python
You are tasked with creating a program to simulate a game where players attempt to add rectangles to a canvas. The program should keep track of the number of attempts made by each player to successfully add a rectangle without overlapping any existing ones. You are given a variable `rectangleAddAttempts` which represe...
```python from typing import List def can_add_rectangle(canvas: List[List[int]], x1: int, y1: int, x2: int, y2: int) -> bool: for i in range(x1, x2): for j in range(y1, y2): if canvas[j][i] == 1: return False for i in range(x1, x2): for j in range(y1, y2): ...
magicoder
python
You are tasked with creating a function that processes a list of strings and a list of patterns to find all non-overlapping matches of the patterns within the strings. A match is considered valid if it contains more than two characters and has not been previously found. The function should return a set of all unique va...
```python import re from typing import List, Set, Pattern def find_unique_matches(strings: List[str], patterns: List[Pattern]) -> Set[str]: found = set() for string in strings: for p in patterns: for match in p.findall(string): if (len(match) > 2) and (match not in found): ...
magicoder
python
You are tasked with implementing a function to train machine learning models using the given options. The function `train_model` takes two dictionaries as input: `agent_opts` and `model_opts`. The `agent_opts` dictionary contains options related to the training agent, while the `model_opts` dictionary contains options ...
```python def train_model(agent_opts, model_opts): # Extract options from dictionaries add_dropout = agent_opts.get('add_dropout', False) add_callbacks = agent_opts.get('add_callbacks', False) nodes_per_layer = model_opts.get('nodes_per_layer', []) filter_size = model_opts.get('filter_size', 3) ...
magicoder
python
You are tasked with creating a program that processes a list of file paths and extracts specific information from each file. Each file contains data related to Unicode character properties. The program should read the content of each file, extract the relevant information, and store it in a structured format for furthe...
```python from typing import List, Dict def extract_unicode_properties(file_paths: List[str]) -> Dict[str, List[str]]: properties_dict = {} for file_path in file_paths: property_name = file_path.split('/')[-1].split('.')[0] # Extract property name from file path with open(file_path, 'r', encod...
magicoder
python
You are tasked with implementing a class for managing connector operators in a data integration system. The class, `ConnectorOperator`, is responsible for handling different types of connector operators such as Marketo and S3. The class includes an overloaded assignment operator to set the values of the connector opera...
```cpp #include <string> #include <iostream> // Define MarketoConnectorOperatorMapper and S3ConnectorOperatorMapper classes for mapping connector operator names to types class MarketoConnectorOperatorMapper { public: static MarketoConnectorOperator GetMarketoConnectorOperatorForName(const std::string& name) { ...
magicoder
cpp
You are tasked with implementing a function that takes a dictionary `dct` and returns a JSON string representation of the dictionary with a specific indentation level. The function should take two parameters: `dct` (the dictionary to be converted to JSON) and `indent` (the number of spaces to use for indentation). The ...
```python import json def convert_to_pretty_json(dct, indent): """ Converts the given dictionary to a JSON string with the specified indentation level. Args: dct: dict - The dictionary to be converted to JSON. indent: int - The number of spaces to use for indentation. Returns: str: The JS...
magicoder
python
You are tasked with implementing a class that represents a decimal number with support for negative values. The class should include methods for basic arithmetic operations and comparison. Create a class `DecimalNumber` with the following specifications: - The class should have a constructor that takes a single parame...
```python class DecimalNumber: def __init__(self, value): self.value = value def add(self, other): return DecimalNumber(self.value + other.value) def subtract(self, other): return DecimalNumber(self.value - other.value) def multiply(self, other): return DecimalNumber(s...
magicoder
python
You are tasked with creating a Python program that sends an email using the `smtplib` library. Your program should prompt the user to input the necessary email details such as sender's email address, recipient's email address, subject, and message content. After gathering this information, the program should construct ...
```python import smtplib from email.mime.text import MIMEText from getpass import getpass def send_email(): # Prompt user for email details sender_email = input("Enter your email address: ") password = getpass("Enter your email password: ") recipient_email = input("Enter recipient's email address: ") ...
magicoder
python
You are tasked with creating a Python function that simulates a simple voting system for a poll. Your function should allow users to vote for a specific option in the poll and keep track of the voting history. You are provided with a partial code snippet that includes a test case for the voting history form. Your task ...
```python from datetime import datetime class Poll: def __init__(self, question, pub_date, options): self.question = question self.pub_date = pub_date self.options = options self.votes = {option: 0 for option in options} def vote(self, option): if option not in self.opt...
magicoder
python
You are tasked with implementing a PID controller for a self-driving car simulation. The PID controller is a control loop feedback mechanism widely used in engineering to control systems, in this case, the steering angle of a self-driving car. The PID controller uses three parameters: proportional (P), integral (I), an...
```cpp #include <iostream> class PID { private: double Kp, Ki, Kd; double p_error, i_error, d_error; public: PID(double Kp, double Ki, double Kd) : Kp(Kp), Ki(Ki), Kd(Kd), p_error(0), i_error(0), d_error(0) {} void UpdateError(double cte) { d_error = cte - p_error; // Calculate the derivativ...
magicoder
cpp
You are tasked with implementing a custom subclass of UITableView in Swift called AnimatableTableView. This subclass should provide additional functionality for animating table view cells in a specific way. The AnimatableTableView class should have the following requirements: 1. It should override the reloadData() met...
```swift import UIKit open class AnimatableTableView: UITableView { override func reloadData() { UIView.transition(with: self, duration: 0.35, options: .transitionCrossDissolve, animations: { super.reloadData() }, completion: nil) } func animateCellSelection(at indexPa...
magicoder
swift
You are tasked with implementing a Python class that manages a set of rules for a query language. The class should support adding rules, checking for duplicate rule names, and generating SQL sources for the rules. Your task is to complete the implementation of the `Rule` class by adding the following methods: 1. `__in...
```python from typing import List, Union, Generator class Rule: names = {} # Class variable to store rule names def __init__(self, name: str, args: List[Union[int, 'Rule']]): self.name = name self.args = args def _sqlsource(self, query: str) -> Generator[str, None, None]: for chi...
magicoder
python
You are tasked with implementing a Python function that retrieves tags associated with a specific project from a version control system. The function will interact with an API to fetch the tags and return them as a list of strings. You are provided with a partial code snippet that includes the method signature for the...
```python from typing import List class VersionControlSystem: def get_tags(self, project: str) -> List[str]: # Assume the existence of a method to make API requests, e.g., self._make_api_request() route_values = {'project': project} response = self._make_api_request( method='GET...
magicoder
python
You are tasked with implementing a function that checks whether a given number is a prime number or not. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your task is to write a function `isPrime` that takes an integer as input and returns `true` if the number is ...
```cpp #include <iostream> bool isPrime(int n) { if (n <= 1) { return false; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } int main() { // Test cases std::cout << isPrime(7) << std::endl; // Output: 1 (true) std::cout << isPrime(4) << std::e...
magicoder
cpp
You are given a list of tuples, where each tuple contains two elements. The first element is a string representing a sequence of movements (e.g., 'lrldrrrllddrrlllrddd'), and the second element is a tuple of strings representing specific movement patterns (e.g., ('ldl', 'rld')). Additionally, each tuple contains a sing...
```python from typing import List, Tuple def apply_movement_patterns(sequence_list: List[Tuple[str, Tuple[str, ...], int]]) -> List[Tuple[int, int]]: def apply_pattern(sequence: str, pattern: str) -> str: return sequence.replace(pattern, '', 1) def apply_patterns(sequence: str, patterns: Tuple[str, .....
magicoder
python
You are working on a data processing system that handles a JSON-like data structure. The system is designed to process and manipulate the data in various ways. One of the tasks involves modifying a nested dictionary within the data structure. The dictionary contains information about questions and subquestions, and you...
```python def update_op_field(data): paragraphs = data['data'][0]['paragraphs'] subquestions = [q['question'] for q in paragraphs[0]['qas'] if q['level'] == 'subquestion'] last_subquestion = subquestions[-1] paragraphs[0]['op'] = last_subquestion.replace(' ', '_').upper() return data ``` When the `...
magicoder
python
You are tasked with creating a Python function that simulates the process of handling payment requests and integration requests. The function should take in a payment request object and return the status of the integration request after processing the payment callback response. The payment request object has the follo...
```python import frappe def process_payment_callback(payment_request): # Step 1: Retrieve integration request IDs integration_req_ids = frappe.get_all("Integration Request", filters={ 'reference_doctype': payment_request.reference_doctype, 'reference_docname': payment_request.reference_docname,...
magicoder
python
You are tasked with implementing a custom deserializer for a specific data format. The deserializer takes a string representation of the data and converts it into a structured object. The data format consists of key-value pairs separated by commas, where the key and value are separated by a colon. The value can be a st...
```python def deserialize(data: str) -> dict: result = {} key = "" value = "" in_nested = False nested_data = "" for char in data: if char == '{': in_nested = True nested_data = "" elif char == '}': in_nested = False result[key] = d...
magicoder
python
You are tasked with implementing a Django model method for the `Post` model. The method should return a summary of the post's content by truncating the `text` field to a specified length and appending an ellipsis if the text exceeds the specified length. The summary should prioritize breaking at the end of a sentence a...
```python class Post(models.Model): pub_date = models.DateTimeField(auto_now=True) text = models.TextField() short = models.TextField(max_length=280) title = models.CharField(max_length=200) def get_summary(self, max_length): if len(self.text) <= max_length: return self.text ...
magicoder
python
You are working on a project that involves analyzing the memory and parameter counts of a deep learning model. As part of this project, you need to create a Python function that calculates the total memory and parameter counts of a given deep learning model. You are given a code snippet that includes some relevant ope...
```python import numpy as np import keras.backend as K def model_analysis(model): shapes_mem_count = 0 trainable_count = 0 non_trainable_count = 0 for layer in model.layers: single_layer_mem = 1 for s in layer.output_shape: if s is None: continue ...
magicoder
python
You are tasked with implementing a class for generating synthetic data for a classification problem. The class should have a method to generate random samples with labels based on the specified number of samples and classes. The generated data should be in the form of feature vectors and corresponding class labels. Yo...
```python import random class SyntheticDataGenerator: def __init__(self, n_samples, n_classes): self.n_samples = n_samples self.n_classes = n_classes def generate_data(self): feature_vectors = [] class_labels = [] samples_per_class = self.n_samples // self.n_classes ...
magicoder
python
You are tasked with implementing a custom correlation model for kriging in Python. Kriging is a statistical method used for interpolation and regression analysis, particularly in geostatistics. The correlation model is a crucial component of kriging, as it defines the spatial correlation structure of the data. In this ...
```python from UQpy.surrogates.kriging.correlation_models.baseclass.Correlation import Correlation import numpy as np class CustomCorrelation(Correlation): def __init__(self, theta): super().__init__() self.theta = theta def __call__(self, h): return np.exp(-self.theta * h) ``` In the...
magicoder
python
You are tasked with creating a Python program that utilizes the `argparse` module to build a command-line interface for testing a Fast R-CNN network pipeline. The program should accept command-line arguments for configuring and running the testing process. Your program should support the following command-line argumen...
```python import argparse import os import cv2 import fast_rcnn # Assuming the Fast R-CNN library is imported def test_fast_rcnn_pipeline(): # Create an ArgumentParser object parser = argparse.ArgumentParser(description='Test a Fast R-CNN network pipeline') # Add command-line arguments parser.add_arg...
magicoder
python
You are tasked with implementing a function to sort a dictionary of banks and their accounts based on specific criteria. Each bank is represented by a key, and its accounts are represented by a nested dictionary where the key is the account name and the value is the account balance. The sorting criteria are as follows:...
```csharp using System; using System.Collections.Generic; using System.Linq; public class BankSorter { public Dictionary<string, Dictionary<string, decimal>> SortBanks(Dictionary<string, Dictionary<string, decimal>> unsortedBanks) { var sortedBanks = unsortedBanks .OrderByDescending(bank =>...
magicoder
csharp
You are tasked with implementing a decision-making algorithm for an AI agent in a game environment. The agent is presented with a set of actions to choose from based on a given key and context. The key identifies the specific interaction, and the context provides relevant information about the agent's current state in ...
```python def choose_action(key, context, actions): if key == "combat": # Example: Choose the action with the highest damage potential in combat context return max(actions, key=lambda action: action.damage) elif key == "exploration": # Example: Choose the action with the highest explorat...
magicoder
python
You are tasked with creating a translation service that converts text from one language to another. The service should support multiple languages and provide an option to detect the source language automatically. Your task is to implement a function that takes a translation query and a completion callback and returns t...
```javascript export function translate(query, completion) { const { text = '', detectFrom, detectTo } = query; const str = formatString(text); const params = { from: detectFrom, to: detectTo, tld: Bob.getOption('tld'), cache: Bob.getOption('cache') }; let res; if (Bob.getOption('version') === 'rpc') { //...
magicoder
javascript
You are tasked with creating a custom Apollo query component in a LitElement-based web application. The application uses Apollo client for GraphQL queries and LitElement for building web components. Your task is to create a new custom element called `LaunchesPastQueryComponent` that extends the `LitElement` class and ...
```typescript import { ApolloQueryController } from '@apollo-elements/core'; import { LitElement, html, css } from 'lit'; import { customElement, property } from 'lit/decorators.js'; import LaunchesPast from '../graphql/LaunchesPast.query.graphql'; import { LaunchesPastQueryVariables } from '../typescript/generated-typ...
magicoder
typescript