query stringlengths 22 16.4k | answer stringlengths 0 11.4k | resource stringclasses 4
values | lang stringclasses 148
values |
|---|---|---|---|
You are working on a project that involves using Docker containers for development and testing. Your task is to write a script that automates the process of pulling a specific Docker image and running a container with certain configurations.
Given the provided Bash script snippet, your goal is to complete the script b... | ```bash
# detect the root dir
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
ROOT="$(dirname ${ROOT})"
# Pull the Docker image
docker pull keyiz/hgdb:lint
# Run the Docker container
docker run -d --name clang-format --rm -it --mount type=bind,source=${ROOT},target=/hgdb keyiz/hgdb:lint bash
... | magicoder | shell |
You are tasked with creating a custom value converter for a .NET Core Entity Framework application. The application uses Entity Framework Core to interact with a database, and you need to implement a custom value converter to handle a specific data type conversion.
Your task is to create a custom value converter that ... | ```csharp
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System;
using System.Linq.Expressions;
public class CustomTypeValueConverter : ValueConverter<CustomType, string>
{
public CustomTypeValueConverter(ConverterMappingHints mappingHints = null)
: base(
customType => Con... | magicoder | csharp |
You are working on a scientific computing project that involves calculating various physical quantities related to radiation and temperature. The project consists of several modules, each containing functions for specific calculations. The code snippet provided is a part of the project and shows the import statements f... | ```python
# radiation_calc.py
from .hg import calcQ
from .temperature import calcTss
from .blackbody import calcPlanckLambda
__all__ = ["calcFluxLambdaSun",
"calcFluxLambdaAtObs",
"calcFluxLambdaAtObsWithSunlight",
"calcFluxLambdaObs",
"calcTotalFluxLambda"]
def calcFluxLa... | magicoder | python |
You are tasked with implementing a Python class that simulates a simple slot machine game. The slot machine has three reels, each displaying a random symbol from a set of possible symbols. The player can spin the reels and, if the symbols on the reels match, they win a prize.
Your task is to implement the `SlotMachine... | ```python
import random
class SlotMachine:
def __init__(self, symbols):
self.symbols = symbols
def spin(self):
self.reels = [random.choice(self.symbols) for _ in range(3)]
def is_winner(self):
return len(set(self.reels)) == 1
# Test unit
def test_slot_machine():
symbols = ['c... | magicoder | python |
You are given an array of integers `nums` and an integer `target`. Your task is to write a function that finds and returns the indices of the two numbers such that they add up to the `target`. You may assume that each input would have exactly one solution, and you may not use the same element twice.
Write a function `... | ```python
def two_sum(nums, target):
cache = dict()
for index, value in enumerate(nums):
cache[target - value] = index
for index, value in enumerate(nums):
if value in cache and cache[value] != index:
return sorted([cache[value], index])
raise Exception("No two sum solution... | magicoder | python |
You are tasked with creating a custom initializer for a class that inherits from `RLMObject` in a Realm database application. The `RLMObject` class is a part of the Realm Swift framework, which is used for object-oriented database management in iOS applications. Your custom initializer should take in a value of any typ... | ```swift
[Problem Description]
You are tasked with creating a custom initializer for a class that inherits from `RLMObject` in a Realm database application. The `RLMObject` class is a part of the Realm Swift framework, which is used for object-oriented database management in iOS applications. Your custom initializer sh... | magicoder | swift |
You are tasked with implementing a Python class that manages train requests for a transportation system. The class should inherit from three different mixins: `Request`, `DocsPropertyMixin`, and `GroundtruthPropertyMixin`. The `Request` mixin provides basic request functionality, while the `DocsPropertyMixin` and `Grou... | ```python
class Request:
def __init__(self, request_data):
self.request_data = request_data
class DocsPropertyMixin:
def __init__(self, docs_data):
self.docs_data = docs_data
class GroundtruthPropertyMixin:
def __init__(self, groundtruth_data):
self.groundtruth_data = groundtruth_d... | magicoder | python |
You are given a weighted directed graph with N nodes and M edges. The task is to find the shortest path from node 1 to node N. If there is no path from node 1 to node N, return -1.
You need to implement a function `shortestPath` that takes in the following parameters:
- `N`: an integer representing the number of nodes... | ```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
const int INF = std::numeric_limits<int>::max();
int shortestPath(int N, std::vector<std::vector<int>>& edges, int M) {
std::vector<std::vector<std::pair<int, int>>> graph(N);
for (const auto& edge : edges) {
int u = edge[... | magicoder | cpp |
You are tasked with implementing a function to determine the longest common prefix among a set of strings. Given an array of strings, write a function `longestCommonPrefix` to find the longest common prefix string amongst its elements. If there is no common prefix, return an empty string `""`.
For example, given the i... | ```python
from typing import List
def longestCommonPrefix(strs: List[str]) -> str:
if not strs:
return ""
# Sort the input list of strings
strs.sort()
# Find the common prefix between the first and last strings
first = strs[0]
last = strs[-1]
prefix = ""
for i in range(min(len... | magicoder | python |
You are tasked with creating a web application that allows users to edit sub-consultancies. The application uses Laravel framework and Blade templating engine for the front-end. The provided code snippet is a part of the Blade template for editing sub-consultancies.
Your task is to implement the back-end functionality... | ```php
// Route definition in web.php
Route::put('/subconsultorias/{id}', 'SubConsultoriasController@update')->name('subconsultorias.update');
// SubConsultoriasController.php
use App\SubConsultorias;
use Illuminate\Http\Request;
public function update(Request $request, $id)
{
// Validate the form data
$valid... | magicoder | php |
You are given a Python code snippet that processes a string character by character. The code snippet is as follows:
```python
if ch == "\\":
if not bs: bs = True
continue
elif ch == "-" and not bs:
hy = True
```
Here, `ch` represents the current character being processed, `bs` is a boolean variable indica... | ```python
from typing import Tuple
def process_string(s: str) -> Tuple[bool, bool]:
bs = False # Initialize backslash indicator to False
hy = False # Initialize hyphen indicator to False
for ch in s:
if ch == "\\":
if not bs:
bs = True # Set backslash indicator to Tr... | magicoder | python |
You are tasked with implementing a Python function that simulates a test scenario for a software application. The function will take in three lists of integers representing the lengths of different types of data, and an optional parameter for the number of iterations. The function will then perform a series of tests ba... | ```python
import random
def test(firsts, others, pool, iters=1000):
total_iters = 0
for _ in range(iters):
first_len = random.choice(firsts)
other_len = random.choice(others)
pool_len = random.choice(pool)
avg_length = (first_len + other_len + pool_len) / 3
print(avg_len... | magicoder | python |
You are tasked with implementing a function that manages communication channels for a network application. The function is responsible for handling both existing and new connections. The provided code snippet is a part of the function and demonstrates the handling of existing connections and the fallback to establishin... | ```rust
use std::sync::mpsc::{channel, Sender, Receiver};
use std::error::Error;
struct Connection {
// Define the necessary fields for the Connection struct
}
async fn manage_connection(url: String) -> Result<(String, Sender<Connection>, Receiver<Connection>), Box<dyn Error>> {
match maybe_bi.await {
... | magicoder | rust |
You are tasked with implementing a Rust program that involves cryptographic algorithms and data structures. The program includes a module called `CryptoAlgo` that defines different cryptographic algorithms and their corresponding byte lengths. Additionally, there is a conditional compilation module called `haskeyspair`... | ```rust
// Define the CryptoAlgo enum with associated byte lengths
enum CryptoAlgo {
Ed25519,
Ecdsa,
}
impl CryptoAlgo {
fn byte_length(&self) -> usize {
match self {
CryptoAlgo::Ed25519 => 64,
CryptoAlgo::Ecdsa => 65,
}
}
}
// Implement the total_byte_length fu... | magicoder | rust |
You are tasked with implementing a rendering engine that supports different rendering techniques based on the specified rendering type. The rendering engine currently supports Shader Model 2.0 (SM2) for rendering. Your task is to extend the rendering engine to support Shader Model 3.0 (SM3) as well.
You are provided w... | To extend the rendering engine to support Shader Model 3.0 (SM3), you can modify the existing code as follows:
```cpp
switch (renderType) {
case ERT_RENDERER_SM2:
// Existing implementation for Shader Model 2.0
break;
case ERT_RENDERER_SM3:
// New implementation for Shader Model 3.0
... | magicoder | cpp |
You are tasked with implementing a memoization function in JavaScript. Memoization is a technique used to improve the performance of a function by caching its results based on the parameters passed to it. The goal is to avoid redundant computations by returning the cached result if the function is called with the same ... | ```javascript
function memoize(func) {
const cache = new Map();
return function (...args) {
const key = args.join('-');
if (cache.has(key)) {
return cache.get(key);
} else {
const result = func(...args);
cache.set(key, result);
return result;
}
};
}
function toTitleCase(st... | magicoder | javascript |
You are tasked with creating a Python script that utilizes the `bpy` library to automate the process of generating a 3D model of a simple house. The house should consist of a rectangular base with a triangular roof. Your script should create the 3D model in Blender, a popular open-source 3D creation suite.
Your script... | ```python
import bpy
import math
# Clear existing mesh objects
bpy.ops.object.select_all(action='DESELECT')
bpy.ops.object.select_by_type(type='MESH')
bpy.ops.object.delete()
# Define house dimensions
base_length = 4
base_width = 3
base_height = 2
roof_base_length = 4
roof_height = 2
roof_slope = 1.5
house_location =... | magicoder | python |
You are tasked with creating a Java class that simulates a simple SMS message service. The class should be able to send SMS messages to tenants associated with a particular service. You are provided with a partial code snippet for a test class that utilizes Spring's dependency injection. Your task is to complete the te... | ```java
// SMSMessageService.java
public interface SMSMessageService {
void sendSmsToTenant(String tenantId, String message);
}
// SMSMessageServiceImpl.java
@Service
public class SMSMessageServiceImpl implements SMSMessageService {
@Autowired
private TenantRepository tenantRepository;
@Override
p... | magicoder | java |
You are tasked with implementing a Python function that simulates a simplified version of an asynchronous task scheduler. The function will take in a list of tasks, each represented by a dictionary containing task information. The function should execute these tasks based on certain conditions and constraints.
The tas... | ```python
from typing import List, Dict, Union
def execute_tasks(tasks: List[Dict[str, Union[str, List[str]]]]) -> List[str]:
task_map = {task["name"]: task for task in tasks}
executed_tasks = []
def execute_task(task_name):
if task_name not in executed_tasks:
task = task_map[task_name... | magicoder | python |
You are tasked with implementing a transliteration function that converts input text from one writing system to another. Transliteration is the process of converting letters or characters from one script into corresponding characters of another script. Your goal is to create a function that can perform transliteration ... | ```python
def translit(language, input_text):
if language == "he":
transliteration_map = {
'א': 'a', 'ב': 'b', 'ג': 'g', 'ד': 'd', 'ה': 'h', 'ו': 'v', 'ז': 'z', 'ח': 'ch',
'ט': 't', 'י': 'y', 'כ': 'k', 'ל': 'l', 'מ': 'm', 'נ': 'n', 'ס': 's', 'ע': "'",
'פ': 'p', 'צ': 'ts',... | magicoder | python |
You are tasked with implementing a user authentication system for a web application. The system should handle user login and remember me functionality. The code snippet provided is a part of the backend logic for the login process. Your task is to complete the implementation of the login functionality by writing the mi... | ```javascript
_post: async (req, res, next) => {
let rememberMe = req.body.remember;
let listenerUuid = req.body.listener_uuid;
try {
let { user, selector, publicKey } = await loginService(context, req.lang.part("auth"))({
username: req.body.username,
password: req.body.passw... | magicoder | javascript |
You are tasked with creating a function that performs color interpolation between two given colors. The function should take in two UIColor objects representing the starting and ending colors, as well as a percentage value indicating the amount of interpolation to be applied. The interpolation should be performed in th... | ```swift
func interpolateColor(from fromColor: UIColor, to toColor: UIColor, withPercentage percentage: CGFloat) -> UIColor {
var fromRed: CGFloat = 0.0, fromGreen: CGFloat = 0.0, fromBlue: CGFloat = 0.0, fromAlpha: CGFloat = 0.0
var toRed: CGFloat = 0.0, toGreen: CGFloat = 0.0, toBlue: CGFloat = 0.0, toAlpha: ... | magicoder | swift |
You are working on a seismic monitoring system that processes earthquake event data. The system uses the Haversine formula through the `gps2dist_azimuth` function to calculate the distance between the event location and a seismic station. The distance is then converted from meters to kilometers using the `M_TO_KM` cons... | ```python
import numpy as np
class clipNet:
# Define the clipNet class as per the system's requirements
pass
def process_seismic_data(event_lat, event_lon, st):
# Calculate distance between event location and the first seismic station
dist_in_meters = gps2dist_azimuth(
lat1=event_lat,
... | magicoder | python |
You are tasked with implementing a simple dependency injection system in TypeScript. The system should allow for the registration of services and the resolution of dependencies between these services.
You are provided with a basic `Container` class that has two methods: `register` and `resolve`. The `register` method ... | ```typescript
class Container {
private services: Map<string, any> = new Map();
register(name: string, service: any) {
this.services.set(name, service);
}
resolve<T>(name: string): T {
const service = this.services.get(name);
if (!service) {
throw new Error(`Service ${name} not registered`);... | magicoder | typescript |
You are given a class representing a disjoint-set data structure using the union-find algorithm. The class contains a method `union` that merges two disjoint sets by updating their roots and tree sizes. The `array` field represents the disjoint-set data structure, where each element stores the parent of the correspondi... | ```java
public int find(int element) {
if (array[element] < 0) {
return element; // element is the root of its set
} else {
// Perform path compression by making the element point directly to the root
array[element] = find(array[element]);
return array[element];
}
}
```
The... | magicoder | java |
You are tasked with implementing a Python function that validates a dictionary representing a connection configuration against a predefined schema. The schema defines the required and optional connection arguments along with their respective types. Your task is to write a function that checks whether the given connecti... | ```python
def validate_connection_config(config: dict, schema: dict) -> bool:
required_args = schema['required_connection_arguments']
optional_args = schema['optional_connection_arguments']
# Check if all required arguments are present in the config
if not all(arg in config for arg in required_args):
... | magicoder | python |
You are tasked with simulating a simple Brainfuck interpreter. Brainfuck is an esoteric programming language known for its minimalism and extreme simplicity. The language operates on an array of memory cells, each initially set to zero, and a data pointer that points to the current memory cell. The language consists of... | ```cpp
#include <iostream>
#include <vector>
#include <array>
enum class BfOpKind {
MOVE_RIGHT,
MOVE_LEFT,
INCREMENT,
DECREMENT,
LOOP_START,
LOOP_END,
WRITE_STDOUT,
READ_STDIN
};
struct BfOp {
BfOpKind kind;
int argument; // Used for WRITE_STDOUT and LOOP_START
};
void execute(const std::vector<... | magicoder | cpp |
You are tasked with implementing a video player class in Swift. The class should have the ability to control the playback state and mute/unmute the audio. You need to implement the `playbackControl` method and the `bindViewModel` method.
The `playbackControl` method takes a `PlaybackState` enum as input and should per... | ```swift
func playbackControl(_ state: PlaybackState) {
switch state {
case .paused:
self.player.playFromCurrentTime()
default:
if player.isMuted {
player.isMuted = false
} else {
player.isMuted = true
}
}
}
func bindViewModel(_ viewModel: Any) {
... | magicoder | swift |
You are tasked with implementing a performance testing utility for a custom data structure. The data structure is a custom implementation of a priority queue, and you need to measure the time taken for various operations on this data structure. The priority queue is implemented using a binary heap.
Your task is to cre... | ```swift
import XCTest
@testable import YourCustomPriorityQueueModule
class PerformanceTesting: XCTestCase {
func testPriorityQueuePerformance() {
let priorityQueue = CustomPriorityQueue<Int>()
// Measure the time taken for inserting elements into the priority queue
measure {
... | magicoder | swift |
You are tasked with creating a Python program that manages file operations using the `tkinter` library for GUI and file dialog. Your program should allow users to perform various file operations such as opening a file, reading its contents, and displaying a success message upon successful file loading.
Your task is to... | ```python
import tkinter as tk
from tkinter import filedialog
def open_file_dialog():
root = tk.Tk()
root.fileName = filedialog.askopenfilename()
if root.fileName:
try:
with open(root.fileName, 'r') as file:
print("\tLoading...")
content = file.read()
... | magicoder | python |
You are tasked with implementing a priority queue using a min-heap data structure. A min-heap is a complete binary tree where each node's value is less than or equal to its children's values. The priority queue should support the following operations:
1. `heappush(heap, item)`: Add the `item` to the `heap`.
2. `heappop... | To implement the `heappush` operation for the priority queue using the min-heap data structure, we can use the following approach:
```python
def heappush(heap, item):
heap.append(item) # Add the item to the end of the list
_siftup(heap, len(heap) - 1) # Restore the heap invariant
def _siftup(heap, pos):
... | magicoder | python |
You are tasked with implementing a Python class that manages a server instance for a distributed computing framework. The class, named `FrovedisServer`, is responsible for handling server-related operations. The provided code snippet includes a portion of the `FrovedisServer` class, showcasing the `getServerInstance` m... | ```python
class FrovedisServer:
__instance = None
def __init__(self):
self.mnode = rpclib.get_selfNode()
@classmethod
def setWorkerSize(cls, host, port, size):
rpclib.set_worker_size(host, port, size)
excpt = rpclib.check_server_exception()
if excpt["status"]:
... | magicoder | python |
You are tasked with creating a Python function that interacts with a Cisco AMP for Endpoints server to retrieve events and store them in a queue. The function will need to handle rate limiting and error conditions gracefully.
Your function will be part of a larger system and should be designed to work within the Resil... | ```python
import json
import logging
from datetime import datetime
from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError
from fn_cisco_amp4ep.lib.amp_client import Ampclient
from fn_cisco_amp4ep.lib.helpers import validate_opts, validate_params
from fn_cisco_... | magicoder | python |
You are tasked with implementing a calendar application that allows users to schedule and manage events. The application should have a feature to mark certain events as "start events" to signify the beginning of a series of related events. To achieve this, you need to create a class `PostStartCalendar` that extends a b... | ```python
class Model:
pass # Placeholder for the base model class
class PostStartCalendar(Model):
def __init__(self):
self.start_events = []
def mark_as_start_event(self, event_id):
"""
Mark the specified event as a start event.
Args:
event_id: The unique identifi... | magicoder | python |
You are tasked with implementing a function to parse a specific type of Ethereum smart contract function call data. Ethereum smart contracts are self-executing contracts with the terms of the agreement directly written into code. Function calls to these contracts are encoded in a specific way, and your task is to extra... | ```rust
pub fn get_calldata() -> Vec<u8> {
// Assuming the function call data is stored in a variable called calldata
let calldata: Vec<u8> = vec![/* Populate with the actual function call data */];
calldata
}
```
In the solution, the `get_calldata` function is completed by populating the `calldata` vector... | magicoder | rust |
You are tasked with creating a Python function that simulates a simplified version of a process injection technique used in cybersecurity. The function, `inject_script_into_process`, will take in various parameters to replace HTTP calls made by a process with a new URL path and method. Your task is to implement this fu... | ```python
from typing import Union, Dict, Any
def inject_script_into_process(proc_identifier: Union[int, str, Dict[str, Any]],
new_path: str, new_method: str = "GET",
source_path: str = "/", source_method: str = "GET",
script_... | magicoder | python |
You are tasked with implementing a custom subscriber for a Combine framework in Swift. The subscriber will be responsible for tracking and processing integer values received from a publisher. The subscriber should be able to handle the subscription and process the received values according to a specific logic.
Your ta... | ```swift
import Combine
class CustomTrackingSubscriber: Subscriber {
typealias Input = Int
typealias Failure = Never
private var downstreamSubscription: Subscription?
func receive(subscription: Subscription) {
downstreamSubscription = subscription
subscription.request(.max(1))... | magicoder | swift |
You are tasked with implementing a thread-safe singleton class in Java. The class, `RpcServiceDispatcher`, is responsible for managing instances of target objects and providing a dispatcher for remote procedure calls (RPCs). The provided code snippet is a part of the `RpcServiceDispatcher` class, and it shows the `getD... | ```java
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class RpcServiceDispatcher {
private static final Map<Object, RpcServiceDispatcher> s_targetMap = new ConcurrentHashMap<>();
private final Object _targetObject;
private RpcServiceDispatcher(final Object targetObject) {
... | magicoder | java |
You are tasked with implementing a simplified version of a decision engine for a multi-agent system. The decision engine is responsible for managing a group of agents and facilitating their decision-making process. Each agent has a unique character and is associated with a specific action log.
Your task is to implemen... | ```cpp
DecisionEngine::DecisionEngine(std::vector<Agent*> agents, CVC* cvc, Logger* action_log)
: agents_(agents), cvc_(cvc), action_log_(action_log) {
for (Agent* agent : agents_) {
agent_lookup_[agent->GetCharacter()] = agent;
}
}
```
In the solution, the `DecisionEngine` constructor initializes the memb... | magicoder | cpp |
You are tasked with implementing a simplified version of a wire protocol message handler for a PostgreSQL adapter. The `QueryMessage` class is responsible for executing a simple statement received from a client. Your task is to extend this class and implement the logic to handle the query message.
Your implementation ... | ```java
package com.google.cloud.spanner.pgadapter.wireprotocol;
import com.google.cloud.spanner.pgadapter.ConnectionHandler;
import com.google.cloud.spanner.pgadapter.statements.IntermediateStatement;
import com.google.cloud.spanner.pgadapter.statements.PSQLStatement;
import java.io.DataInputStream;
import java.io.Da... | magicoder | java |
You are tasked with creating a Python program that simulates a file copying process. Your program should handle exceptions and provide appropriate error messages in case of failures.
Your program should have the following features:
- Prompt the user to input the source and destination file paths.
- Attempt to copy th... | ```python
import shutil
def copy_file():
source = input("Enter the source file path: ")
destination = input("Enter the destination file path: ")
try:
shutil.copy(source, destination)
except FileNotFoundError:
print("Source file not found.")
except PermissionError:
print("Pe... | magicoder | python |
You are tasked with implementing a Python function that converts a given dictionary's keys from snake_case to camelCase. In snake_case, words are separated by underscores, while in camelCase, the first word is all lowercase and subsequent words have their first letter capitalized and no spaces or underscores between th... | ```python
def snake_to_camel(input_dict: dict) -> dict:
camel_dict = {}
for key, value in input_dict.items():
words = key.split('_')
camel_key = words[0] + ''.join(word.capitalize() for word in words[1:])
camel_dict[camel_key] = value
return camel_dict
``` | magicoder | python |
You are tasked with implementing a class that manages user data, including sensitive information such as passwords. Your goal is to create a method that allows the class to hide specific attributes when they are serialized or converted to an array. To achieve this, you need to implement a mechanism to specify which att... | ```php
class UserData
{
protected $hidden = [
'password', 'remember_token',
];
protected $attributes = [
'username' => 'john_doe',
'password' => 'secretpassword',
'email' => 'john_doe@example.com',
'remember_token' => 'abc123',
];
public function toArray()
... | magicoder | php |
You are tasked with creating a program that generates a fstab (file system table) for a Linux system. The fstab file is used by the operating system to control how disk partitions, various other block devices, or remote file systems are mounted into the file system. The program should take input from the user regarding... | ```python
def generate_fstab():
num_partitions = int(input("Enter the number of disk partitions: "))
fstab_content = ""
for _ in range(num_partitions):
device_name = input("Enter the device name (e.g., /dev/sda1): ")
mount_point = input("Enter the mount point (e.g., /mnt/data): ")
... | magicoder | python |
You are working on a project to simulate the behavior of a physical grid using numerical methods. As part of this project, you need to implement a Laplace equation solver using the boundary element method. The Laplace equation is a second-order partial differential equation and is used to describe the behavior of poten... | ```python
import numpy as np
class Grid:
def __init__(self, x_range, x_num_points, y_range, y_num_points, mask, x_endpoints, y_endpoints):
self.xg, self.yg = np.meshgrid(np.linspace(x_range[0], x_range[1], x_num_points),
np.linspace(y_range[0], y_range[1], y_num_point... | magicoder | python |
You are tasked with creating a Python script that organizes and runs a series of test cases for a software project. The test cases are stored in separate modules, each containing a test class. The code snippet provided shows the import statements for the test classes.
Your task is to implement a function `run_all_test... | ```python
import importlib
def run_all_tests():
test_results = {}
test_modules = [
'args_test', 'arithmetic_test', 'build_dirs_test', 'build_file_test',
'bundle_tags_test', 'caching_test', 'case_test', 'clean_test',
'created_files_test', 'error_handling_test', 'error_test',
'fil... | magicoder | python |
You are tasked with creating a web application that manages products and shopping cart functionality. The given code snippet is from a PHP Laravel controller that handles various actions related to products and shopping cart.
Your task is to implement a feature to display a single product page based on its slug. The p... | ```php
public function onepage($slug){
$product = Product::where('slug', $slug)->where('status', 1)->first();
if($product){
$title = "Sản phẩm - " . Helpers::page_get_option('title');
$keywords = Helpers::page_get_option('keywords');
$description = Helpers::page_get_option('description')... | magicoder | php |
You are tasked with implementing a simplified version of an expression tree parser in Java. An expression tree is a mathematical expression represented in a tree data structure, where each node can be an operator or an operand. The given code snippet is a part of a method that creates an expression tree based on the in... | ```java
import java.util.Stack;
public class ExpressionTreeParser {
/**
* Returns an ExpressionTree based off the input text
* @throws InvalidCommandException
*/
private Command createExpressionTree(CommandParser lang, String[] text) throws InvalidCommandException {
CommandList root = m... | magicoder | java |
You are working on a system that processes data from two different sources, par1 and par2. Each source provides a signal-to-noise ratio (snr) and a confidence probability (conf_prob). Your task is to implement a decision-making algorithm based on the provided conditions. If par1's snr is greater than 0 and par2's snr i... | ```python
def data_picker(par1, par2, conf_thresh):
if (par1['snr'] > 0) and (par2['snr'] <= 0):
if par1['conf_prob'] < conf_thresh:
return 0
else:
return 1
elif (par1['snr'] <= 0) and (par2['snr'] > 0):
if par2['conf_prob'] < conf_thresh:
return 1
... | magicoder | python |
You are working on a project that involves building software using CMake. The project has a specific requirement to support cross-compilation for Xilinx platforms. Your task is to write a script that automates the CMake configuration process based on the existence of a target sysroot directory.
Write a shell script th... | ```bash
#!/bin/bash
if [ -d "$OECORE_TARGET_SYSROOT" ]; then
cmake --verbose=1 -DCMAKE_TOOLCHAIN_FILE=$OECORE_NATIVE_SYSROOT/usr/share/cmake/OEToolchainConfig.cmake -DXILINX_HEADER_DIR=$OECORE_TARGET_SYSROOT/usr/include/xilinx -DCMAKE_INSTALL_PREFIX=$OECORE_TARGET_SYSROOT/usr -DCMAKE_BUILD_TYPE=Release -DBUILD_SH... | magicoder | shell |
You are working on a project to develop a game-playing AI using the Python library for StarCraft II (sc2). As part of the project, you need to implement a class that handles the preprocessing of game screen images. The class has a method to determine the number of channels for preprocessed screen images based on the co... | ```python
def calculate_screen_channels(SCREEN_FEATURES, screen_imgs):
channels = 0
for i, screen_feature in enumerate(SCREEN_FEATURES):
if i not in screen_imgs:
channels += 1
return channels
```
The `calculate_screen_channels` function iterates through the `SCREEN_FEATURES` list and inc... | magicoder | python |
You are tasked with implementing a texture loading and drawing system for a simple 2D game. The game engine provides a set of functions for loading textures and drawing them on the screen. The texture loading function loads an image file and returns a unique identifier for the loaded texture. The drawing function takes... | ```python
# Texture Loading and Drawing Functions
class TextureManager:
def __init__(self):
self.textures = {}
self.next_texture_id = 1
def loadTexture(self, filename):
# Simulate loading texture from file and assigning a unique identifier
texture_id = self.next_texture_id
... | magicoder | python |
You are tasked with creating a Python package called "pylfq" that interfaces with a C library for implementing a lock-free queue. The code snippet provided is a part of the setup configuration for building the Python extension module using the C source files "pylfq.c" and "queue.c". Your task is to write a Python modul... | ```python
# pylfq.py
import ctypes
from ctypes import CDLL, c_void_p, c_int
# Load the C library
lib = CDLL('path_to_your_compiled_library.so')
# Define the necessary C function prototypes
init_queue = lib.init_queue
init_queue.restype = c_void_p
enqueue = lib.enqueue
enqueue.argtypes = [c_void_p, c_int]
dequeue =... | magicoder | python |
You are tasked with implementing a simple file management system in Java. Your task is to create a class `FileManager` that provides methods for managing files and directories. The class should have the following functionalities:
1. `createFile(String fileName)`: A method that creates a new file with the given `fileNa... | ```java
package io.contek.invoker.commons;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FileManager {
private File currentDirectory;
public FileManager(String currentDirectoryPath) {
this.currentDirectory = new File(currentDirec... | magicoder | java |
You are tasked with creating a system simulator for a space exploration program. The system simulator is responsible for processing input data from various sensors and generating appropriate responses. The input data is received through the standard input (stdin) and the responses are printed to the standard output (st... | ```python
import sys
class SystemSimulator:
def process_input_data(self, msg):
if msg == "SENSOR_A":
return "Detected anomaly in sensor A."
elif msg == "SENSOR_B":
return "Sensor B is operating normally."
elif msg == "SENSOR_C":
return "Critical error in ... | magicoder | python |
You are tasked with creating a program that retrieves and displays the features and dependencies for a specific crate in the Rust programming language. The program should take the name of the crate as input and then fetch and print out its features and dependencies.
Your program should interact with the official Rust ... | ```rust
use reqwest;
use serde::Deserialize;
#[derive(Deserialize)]
struct CrateMetadata {
name: String,
versions: Vec<Version>,
}
#[derive(Deserialize)]
struct Version {
num: String,
features: serde_json::Value,
dependencies: Vec<Dependency>,
}
#[derive(Deserialize)]
struct Dependency {
name... | magicoder | rust |
You are given a list of integers representing the daily stock prices of a company. Your task is to write a function to calculate the maximum profit that can be obtained by buying and selling the stock on different days. You can only make one transaction (i.e., buy one and sell one share of the stock), and you must buy ... | ```python
def max_profit(stock_prices):
if not stock_prices:
return 0
min_price = stock_prices[0]
max_profit = 0
for price in stock_prices:
if price < min_price:
min_price = price
else:
max_profit = max(max_profit, price - min_price)
ret... | magicoder | python |
You are tasked with creating a Rust module that interacts with the Bittrex cryptocurrency exchange API. The Bittrex API provides various endpoints for accessing market data, placing orders, and managing account information. Your goal is to implement a Rust module that utilizes the `url` crate to construct and send HTTP... | ```rust
extern crate url;
use std::io::Read;
use url::Url;
use serde::{Deserialize, Serialize};
pub mod bittrex {
#[derive(Debug, Deserialize)]
struct MarketSummary {
symbol: String,
high: f64,
low: f64,
last: f64,
volume: f64,
}
pub fn get_market_summary(tradin... | magicoder | rust |
You are tasked with implementing a non-copyable template class in C++. The non_copyable class is designed to prevent the copying of objects of a specific type. Your task is to complete the implementation of the non_copyable class template by adding a private copy constructor and assignment operator, and then create a c... | ```cpp
#include <iostream>
class non_copyable {
protected:
non_copyable() {}
private:
non_copyable(const non_copyable&);
non_copyable& operator=(const non_copyable&);
};
class MyClass : public non_copyable {
public:
MyClass(int val) : value(val) {}
int getValue() const {
return value;
... | magicoder | cpp |
You are tasked with implementing a function that parses a string representation of a floating-point number and extracts the exponent part if present. The function should handle both lowercase and uppercase 'e' or 'E' as the exponent indicator, and return the exponent value as an integer. If the string does not contain ... | ```rust
fn parse_exponent(input: &str) -> Result<i32, &'static str> {
let mut exp_info: Option<(char, usize)> = None;
for (i, c) in input.chars().enumerate() {
match c {
'e' | 'E' | 'p' | 'P' => {
exp_info = Some((c, i + 1));
break; // start of exponent
... | magicoder | rust |
You are tasked with implementing a simple command-line argument parsing library in Rust. The library should provide functionality for defining and validating command-line arguments.
You need to implement the `Arg` trait, which represents a command-line argument. The trait has the following methods:
1. `get_desc<'a>(&'... | ```rust
struct ArgDesc {
// Fields and methods for describing the argument
}
struct Ident {
desc: ArgDesc,
variants: Vec<Vec<String>>,
}
impl Arg for Ident {
fn get_desc<'a>(&'a self) -> &'a ArgDesc {
&self.desc
}
fn validate_parsed_value(&self, value: &str) -> bool {
self.var... | magicoder | rust |
You are tasked with creating a custom hook in React that manages the scrolling behavior of a given HTML element. The hook should utilize the `useRef` and `useEffect` hooks to ensure that the element is scrolled to the bottom whenever its content changes.
Your task is to implement the `useScrollToBottom` custom hook, w... | ```javascript
import { useEffect, useRef } from 'react';
function useScrollToBottom(ref) {
useEffect(() => {
const element = ref.current;
if (element) {
element.scrollTop = element.scrollHeight;
}
}, [ref]);
}
```
The `useScrollToBottom` custom hook utilizes the `useEffect` hook to listen for ch... | magicoder | javascript |
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. Each account should have a unique account number, and the program should be able to handle multiple accounts.
Your task is to implement ... | ```swift
class Account {
let accountNumber: Int
let accountHolder: String
var balance: Double
init(accountNumber: Int, accountHolder: String) {
self.accountNumber = accountNumber
self.accountHolder = accountHolder
self.balance = 0
}
func deposit(amount: Double) ... | magicoder | swift |
You are tasked with implementing a simplified version of a forking detection system in a blockchain network. The system is responsible for detecting and alerting when a forking event occurs, indicating a potential breach in the network's integrity.
You are given a partial code snippet from the forking detection system... | ```rust
use std::collections::HashMap;
use futures::channel::mpsc::UnboundedSender;
// Define the types used in the forking detection system
type NodeIndex = u64; // Type representing a node index
type ForkProof<H, D, S> = (H, D, S); // Type representing a fork proof
type ForkingNotification<H, D, S> = (H, D, S); // T... | magicoder | rust |
You are tasked with implementing a simulation for a voting system using the provided code snippet as a starting point. The voting system consists of a class with several methods for evaluating derivatives, calculating time steps, and registering the state of the system. Your task is to complete the implementation of th... | ```python
class VotingSystem:
def __init__(self):
Physics.__init__(self)
return
def evaluateDerivatives(self, t, dt, db, state, derivs):
# Implement logic to evaluate derivatives based on the current state and time
# Example:
derivs[0] = state[0] * 0.1 # Calculate deriv... | magicoder | python |
You are tasked with implementing a Python decorator-based function dispatcher. The dispatcher function, `foo`, will take different actions based on the value of its first argument. The dispatcher will call different functions based on the value of the first argument and the annotations provided by the decorator.
Your ... | ```python
class Dispatcher:
def __init__(self):
self.handlers = {}
def dispatch(self, on):
def register_handler(func):
self.handlers[on] = func
return func
return register_handler
def __call__(self, *args):
if len(args) == 1:
if args[0] i... | magicoder | python |
You are tasked with creating a program that simulates a weightlifting routine. The program should take in various parameters and generate a set of weightlifting routines based on the input. The parameters include the type of exercise, the number of steps, the repetition count, the heap pages, and the output file locati... | ```python
def generate_weightlifting_routines(extrinsic, steps, repeat, heap_pages, output_file):
# Generate weightlifting routines based on the input parameters
routines = []
for _ in range(repeat):
routine = f"Perform {steps} steps of {extrinsic} with {heap_pages} heap pages"
routines.appe... | magicoder | python |
You are tasked with creating a Python module that handles web scraping and data processing. The module should contain two main components: `scrape_handler` and `data_handler`. The `scrape_handler` is responsible for extracting data from a website, while the `data_handler` processes and manipulates the extracted data. Y... | ```python
import requests
from bs4 import BeautifulSoup
def scrape_handler(url):
try:
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
# Perform specific scraping operations based on the website structure
... | magicoder | python |
You are tasked with implementing a custom data structure to store and manage a collection of unique strings. The data structure should support adding a new string, removing an existing string, and checking if a given string is present in the collection. Additionally, the data structure should provide a method to retrie... | ```java
import java.util.HashSet;
import java.util.Set;
public class CustomStringCollection {
private Set<String> stringSet;
public CustomStringCollection() {
stringSet = new HashSet<>();
}
public void addString(String str) {
stringSet.add(str);
}
public void removeString(Str... | magicoder | java |
You are tasked with creating a Python function that simulates the execution of a series of commands for a hardware description language (HDL) synthesis and simulation tool. The function will take in a list of files, a top-level module name, and a boolean flag indicating whether waveform debugging is enabled. The functi... | ```python
import sys
from typing import List
def run_command(cmd: str) -> None:
# Placeholder for the run_command function, which executes the given command
pass
def print_banner(message: str) -> None:
# Placeholder for the print_banner function, which prints a banner with the given message
pass
def ... | magicoder | python |
You are tasked with implementing a Python function that processes an image using the MTCNN (Multi-Task Cascaded Convolutional Networks) face detection model and OpenCV library. The function should take an input image, convert it to RGB format, detect faces and facial landmarks using MTCNN, and then visualize the detect... | ```python
import cv2
import numpy as np
from mtcnn import MTCNN
import vision
def process_image(input_image):
# Convert input image from BGR to RGB format
img_rgb = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB)
# Initialize MTCNN detector
mtcnn_detector = MTCNN()
# Detect faces and landmarks using... | magicoder | python |
You are tasked with creating a Python function that parses and extracts information from a given HTTP request and response log. The log is in the form of a dictionary, where the keys represent the type of action (e.g., "connect", "send", "reply", "header"), and the values are the corresponding data for each action. The... | ```python
def parse_http_log(log: dict) -> dict:
parsed_log = {}
# Extract connection information
if 'connect' in log:
parsed_log['connection'] = log['connect']
# Extract request method and path
if 'send' in log:
send_data = log['send'].decode('utf-8')
request_lines = send_... | magicoder | python |
You are tasked with implementing a program to calculate the length of the Collatz sequence for a given range of numbers. The Collatz sequence for a given number n is defined as follows:
- If n is even, the next number in the sequence is n / 2.
- If n is odd, the next number in the sequence is 3n + 1.
The sequence termi... | ```cpp
#include <unordered_map>
int collatzSequenceLength(long long n, std::unordered_map<long long, int>& cache) {
if (n == 1) {
return 1;
}
if (cache.find(n) != cache.end()) {
return cache[n];
}
int length = 1 + collatzSequenceLength((n % 2 == 0) ? n / 2 : 3 * n + 1, cache);
c... | magicoder | cpp |
You are given a code snippet that represents a program's metadata. The code snippet consists of comments indicating the length of the code and the execution time. Your task is to write a program that can parse this code snippet and extract the length of the code and the execution time.
Write a function or program that... | ```python
from typing import Tuple
def parse_code_metadata(code_snippet: str) -> Tuple[int, int]:
code_length = 0
execution_time = 0
lines = code_snippet.split('\n')
for line in lines:
if "コード長" in line:
code_length = int(line.split(":")[1].strip())
elif "実行時間" in line:
... | magicoder | python |
You are working on a project that involves modeling multivariate data using Pyro, a probabilistic programming language built on top of PyTorch. Your task is to write a Pyro model that generates multivariate data based on a given covariance structure.
The provided code snippet is a part of the Pyro model that you are w... | ```python
import torch
import pyro
from pyro.distributions import LKJCorrCholesky, MultivariateNormal
def generate_multivariate_data(T, D, N, device):
# Initialize the correlation Cholesky matrix
corr_chol = torch.zeros(T, D, D, device=device)
# Sample the correlation Cholesky matrix using LKJCorrCholesky... | magicoder | python |
You are tasked with implementing a function that expands the fluid nodes marked in a two-dimensional scene. The scene contains node shape factors for the y and z dimensions, and the function should expand the marked fluid nodes by a specified number of layers.
You are provided with the following code snippet as a refe... | ```cpp
void TwoDScene::expandFluidNodesMarked(int layers)
{
const std::vector< VectorXs >& node_shape_factor_y = getNodeShapeFactorY();
const std::vector< VectorXs >& node_shape_factor_z = getNodeShapeFactorZ();
for (int i = 0; i < layers; i++) {
// Iterate through the marked fluid nodes and expand... | magicoder | cpp |
You are tasked with creating a custom configuration provider for a .NET Core application. The application uses the `Microsoft.Extensions.Options` library to manage configuration settings. Your custom provider should retrieve configuration data from a remote FTP server and make it available to the application.
Your tas... | ```csharp
using Microsoft.Extensions.Options;
using System;
using System.IO;
using System.Net;
namespace CustomConfigurationProvider
{
public class FtpConfigurationProvider : IOptionsMonitor<FtpConfiguration>
{
private readonly FtpConfiguration _options;
private FileSystemWatcher _fileWatcher;
... | magicoder | csharp |
You are tasked with implementing a custom router system for a mobile application. The router is responsible for managing the navigation flow within the app. The provided code snippet shows a method signature for transitioning from one router to another.
You need to implement the `transit` method in the `ARCHRouter` cl... | ```swift
public class ARCHRouter {
// Other properties and methods of ARCHRouter class
func transit(from: ARCHRouter?, options: [ARCHRouterOptions], animated: Bool) {
// Implementation of the transit method
if let sourceRouter = from {
// Perform transition from sourceRouter to this... | magicoder | swift |
You are tasked with implementing a custom Float class that supports various features such as pre-setting values, handling units, and mapping values to specific labels. Your task is to create a Float class with the following functionalities:
1. The class should support pre-setting values using the `pre_set` method. Whe... | ```python
from pint import UnitRegistry
class Float:
def __init__(self, setter=False, values=None, unit=None, mapping=None):
self.setter = setter
self.values = values if values else []
self.unit = unit
self.mapping = mapping if mapping else {}
def pre_set(self, _, value):
... | magicoder | python |
You are tasked with implementing a function that will determine the depth of nested HTML tags in a given string. The depth of a tag is defined as the number of levels it is nested within other tags. For example, a tag directly within the body tag has a depth of 1, while a tag within another tag within the body tag has ... | ```javascript
function calculateTagDepth(htmlString) {
let maxDepth = 0;
let currentDepth = 0;
for (let i = 0; i < htmlString.length; i++) {
if (htmlString[i] === '<' && htmlString[i + 1] !== '/') {
currentDepth++;
if (currentDepth > maxDepth) {
maxDepth = currentDepth;
}
} else... | magicoder | javascript |
You are tasked with creating a Python program to manage a library of books. The program should allow users to add, remove, and display books in the library. Additionally, users should be able to search for books by title and view the details of a specific book.
Your task is to implement the `Library` class with the fo... | ```python
class Library:
def __init__(self):
self.books = {}
def add_book(self, title, author, genre):
self.books[title] = {'author': author, 'genre': genre}
def remove_book(self, title):
if title in self.books:
del self.books[title]
else:
print(f"Th... | magicoder | python |
You are tasked with implementing a simple event handling system in Python. You are given a code snippet that defines three classes: `__init__`, `TaskRemoved`, and `TaskRetrieved`. Your task is to create a class that manages these events and their handlers.
Your task is to implement a class `EventManager` with the foll... | ```python
class EventManager:
def __init__(self):
self.handlers = {}
def register_handler(self, event_type, handler):
if event_type not in self.handlers:
self.handlers[event_type] = []
self.handlers[event_type].append(handler)
def trigger_event(self, event):
eve... | magicoder | python |
You are tasked with optimizing the process of finding the closest node to a given position in a graph. The graph is represented by a class `Graph` containing a collection of nodes, each with a position in 3D space. The goal is to implement an efficient algorithm to find the closest node to a specified position in the g... | To optimize the process of finding the closest node to a given position in the graph, we can use a spatial data structure like a kd-tree. This data structure partitions the space into regions, making it efficient to search for the closest node.
Here's a high-level overview of the solution:
1. Build a kd-tree from the ... | magicoder | cpp |
You are tasked with creating a password validation function that checks whether a given password meets specific criteria. The function should accept a string representing the password and return a boolean value indicating whether the password is valid or not.
The password must satisfy the following criteria:
1. It mus... | ```python
import re
def validate_password(password):
if len(password) < 8:
return False
if re.match(r'^(?=.*\d|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$', password):
return True
else:
return False
# Test the function
print(validate_password("StrongP@ssw0rd")) # Output: Tru... | magicoder | python |
You are tasked with implementing a class that represents a geometric shape. The class should have methods to calculate the area and perimeter of the shape. Additionally, the class should have a method to retrieve the name of the shape. Below is a partial implementation of the class in PHP:
```php
class GeometricShape ... | ```php
class GeometricShape {
const NAME = "Geometric Shape";
public function getArea() : float {
// To be implemented
}
public function getPerimeter() : float {
// To be implemented
}
public function getName() : string {
return self::NAME;
}
}
class Circle extends GeometricShape {
priva... | magicoder | php |
You are tasked with creating a program that simulates a simple text-based game. The game involves a character navigating through a grid-based world, collecting treasures, and avoiding obstacles. The character's movements are controlled by the user's input.
Your task is to implement the movement logic for the character... | ```java
public char[][] moveCharacter(char[][] grid, char direction, int currentRow, int currentCol) {
int newRow = currentRow;
int newCol = currentCol;
if (direction == 'U') {
newRow--;
} else if (direction == 'D') {
newRow++;
} else if (direction == 'L') {
newCol--;
} ... | magicoder | java |
You are working on a computer vision project and need to implement a function to process image data and region of interest (ROI) information. The goal is to sample ROIs from a given set of images and generate corresponding labels for each ROI based on the provided roidb (region of interest database) and the number of c... | ```python
import numpy as np
def sample_rois_and_generate_labels(im_scales, roidb, im_blob, num_classes):
assert len(im_scales) == 1, "Single batch only"
assert len(roidb) == 1, "Single batch only"
blobs = {}
blobs['data'] = im_blob
rois_blob = np.zeros((0, 5), dtype=np.float32)
labels_blob = ... | magicoder | python |
You are tasked with implementing a function that simulates a simplified version of URL redirection. The function should take a list of URLs and their corresponding redirects and return the final destination URL after following all the redirects. Each redirect is represented as a tuple containing the source URL and the ... | ```python
from typing import List, Tuple
def final_destination(urls: List[Tuple[str, str]]) -> str:
redirect_map = {source: dest for source, dest in urls}
current_url = urls[0][0] # Start from the first URL
while current_url in redirect_map:
current_url = redirect_map[current_url] # Follow the re... | magicoder | python |
You are tasked with creating a program that processes and analyzes configuration files for a DirectX 11 graphics engine. The configuration files contain settings for rasterizer states and samplers. Each setting is specified in a section with a unique name enclosed in square brackets, followed by key-value pairs separat... | ```python
import re
def process_configuration_file(file_path):
with open(file_path, 'r') as file:
config_data = file.read()
rasterizer_state = re.search(r'\[RasterizerStateDX11\]\s*CullMode\s*=\s*(\w+)', config_data)
sampler_1 = re.search(r'\[SamplerDX11_1\]', config_data)
sampler_2 = re.searc... | magicoder | python |
You are tasked with creating a Python class that represents a user in a database. The class should have a method to validate the username based on certain criteria. The username should be stored in a database column with a maximum length of 16 characters.
Create a class `User` with the following specifications:
- The ... | ```python
import re
class User:
def __init__(self, username):
self.username = username
def validate_username(self):
if not self.username:
return False # Username is empty
if len(self.username) > 16:
return False # Username exceeds 16 characters
if not ... | magicoder | python |
You are tasked with implementing a function to encrypt a message using the ChaCha20-Poly1305 encryption algorithm. The provided code snippet demonstrates the usage of the encryption function, but the specific implementation details are missing. Your task is to write a function that performs the encryption using the Cha... | ```swift
import CryptoKit
func encryptUsingChaCha20Poly1305(plaintext: inout Data, additional: Data, encryptKey: Data, nonce: [UInt8]) throws -> Data {
var cipher = Data()
let encryptCount = UInt64(0) // Replace with the appropriate value for the encryption count
let nonce = Array(nonce) // Conve... | magicoder | swift |
You are tasked with creating a Python program to process JSON data and generate an Excel file containing statistical information for a given company. The program should read JSON data from a specified URL, extract relevant information, and then save the statistical data in an Excel file.
Your task is to implement the ... | ```python
import requests
import json
import pandas as pd
def process_company_data(url, company_name, output_directory):
response = requests.get(url)
response_json = json.loads(response.text)
company_data = []
for data in response_json["period"]:
if company_name.lower() in data["asof"].low... | magicoder | python |
You are tasked with creating a program to solve a Sudoku puzzle. A Sudoku puzzle is a 9x9 grid, divided into 9 3x3 subgrids, with some digits already filled in. The goal is to fill in the remaining cells such that each row, each column, and each 3x3 subgrid contains all of the digits from 1 to 9.
Your task is to imple... | ```python
from typing import List
def solve_sudoku(board: List[List[int]]) -> List[List[int]]:
def is_valid(board, row, col, num):
for i in range(9):
if board[row][i] == num or board[i][col] == num:
return False
start_row, start_col = 3 * (row // 3), 3 * (col // 3)
... | magicoder | python |
You are tasked with creating a command-line interface for a machine learning model training script. The script should accept various command-line arguments for configuring the training process. Your task is to implement the argument parsing logic using the `argparse` module in Python.
You need to define the following ... | ```python
import argparse
def main():
parser = argparse.ArgumentParser(description='Machine Learning Model Training Script')
parser.add_argument('--learning-rate', type=float, default=0.001,
help='Learning rate for the model optimizer (default: 0.001)')
parser.add_argument('--batch... | magicoder | python |
You are tasked with implementing a program to simulate a simple vending machine. The vending machine has a set of available items, each with a unique code, name, and price. Users can insert coins into the machine and select items to purchase. The program should calculate the total amount inserted, allow the user to mak... | ```python
from typing import List, Tuple
class VendingMachine:
def __init__(self, items: List[Tuple[str, str, float]]):
self.items = {code: (name, price) for code, name, price in items}
self.total_amount_inserted = 0.0
def insert_coin(self, amount: float):
self.total_amount_inserted +=... | magicoder | python |
You are tasked with implementing a custom matrix multiplication operation for a Python class. The class `C` has a method `__matmul__` which should perform the matrix multiplication operation when the `@` operator is used between two instances of class `C`.
The `__matmul__` method should take another instance of class ... | ```python
class C:
def __init__(self, matrix):
self.matrix = matrix
def __matmul__(self, other):
if len(self.matrix[0]) != len(other.matrix):
raise ValueError("Incompatible matrix dimensions for multiplication")
result = []
for i in range(len(self.matrix)):
... | magicoder | python |
You are working for a cybersecurity company and have been tasked with creating a program to detect potentially malicious code. Your program needs to identify if a given C# code snippet writes to a file in a system startup directory. The system startup directory is typically used by malware to ensure its persistence on ... | ```csharp
using System;
using System.IO;
public class MaliciousCodeDetector
{
public bool IsWritingToStartupDirectory(string codeSnippet)
{
string startupDirectory = "C:\\users\\%username%\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\startup\\";
string[] lines = codeSnippet.Spli... | magicoder | csharp |
You are tasked with creating a program that reads a CSV file containing student information and calculates the average score for each student. The CSV file contains the following columns: StudentID, Name, Subject, and Score. Each row represents a student's performance in a specific subject.
Your program should read th... | ```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class StudentPerformance
{
public string StudentID { get; set; }
public string Name { get; set; }
public string Subject { get; set; }
public double Score { get; set; }
public static void CalculateA... | magicoder | csharp |
You are tasked with implementing a command-line utility in Rust for printing a list in a tree format. The utility will take input from the user and display the list in a hierarchical tree structure. The input will consist of a list of items, each with a specified level of indentation to represent the hierarchy.
Your t... | ```rust
fn print_tree(items: Vec<&str>) {
let mut stack: Vec<(usize, &str)> = Vec::new();
for item in items {
let level = item.chars().take_while(|&c| c == ' ').count();
while let Some((top_level, _)) = stack.last() {
if level <= *top_level {
stack.pop();
... | magicoder | rust |
You are tasked with implementing a memory management system for a reinforcement learning agent. The memory module is responsible for storing and retrieving memories and providing rewards based on the stored memories. The memory module has a method `get_reward` that takes a memory tensor as input and returns a reward va... | ```python
import tensorflow as tf
class Memory:
def __init__(self):
self.memory_slots = []
def get_reward(self, mems):
# Calculate reward based on the input memory tensor
# For demonstration purposes, return the sum of all elements in the memory tensor as the reward
return tf.r... | magicoder | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.