source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_instruct_75k | 61,463 | Write a Python function to remove all occurrences of the number 3 from a given list of integers and return the modified list. If the input list is empty or does not contain the number 3, the function should return the original list. The function should be efficient and handle edge cases appropriately.
The code should ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def remove_threes(input_list: List[int]) -> List[int]:
"""
Removes all occurrences of the number 3 from the given list of integers and returns the modified list.
Args:
input_list (List[int])... |
magic_instruct_75k | 61,487 | Write a Python function `calculate_input_size(v)` that takes a list `v` of integers as input and returns the value of `input_size` based on the given code snippet. The `input_size` is calculated as twice the value at index 1 of the list `v`.
The code should start with:
```python
from typing import List
def calculate_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_input_size(v: List[int]) -> int:
"""
Calculate the input size based on the value at index 1 of the list `v`.
Args:
v (List[int]): A list of integers.
Returns:
int:... |
magic_instruct_75k | 61,537 | Write a Python function to process a list of software dependencies and their associated patches. The function should extract and organize the information from the given input and return a structured representation of the dependencies and patches.
The input will consist of a list of strings, where each string represent... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
from typing import List, Dict
def process_dependencies(input_list: List[str]) -> Dict:
"""
Processes a list of software dependencies and their associated patches.
Args:
input_list (List[str]): A list of s... |
magic_instruct_75k | 61,561 | Write a Python function to calculate the average tax amount, standard error of the tax, and the total care cost based on the results of multiple simulations. Each simulation is represented by the `Sim` class, which takes a parameter `p`. The `Sim` class has a method `run()` that returns the tax amount, seed, and care c... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
import math
def calculate_statistics(reps: int, p: float) -> tuple:
"""
Calculate the average tax amount, standard error of the tax, and the total care cost
based on the results of multiple simulations.
... |
magic_instruct_75k | 61,572 | Write a Python function to count the frequency of each course name in a given list, ignoring case sensitivity. The function should return a dictionary where the keys are the lowercase course names and the values are the counts of each course.
The code should start with:
```python
from typing import List, Dict
def cou... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_course_frequency(courses: List[str]) -> Dict[str, int]:
"""
Counts the frequency of each course name in a given list, ignoring case sensitivity.
Args:
courses (List[str]): A ... |
magic_instruct_75k | 61,578 | Write a Python function to process withdrawal requests for a banking system that handles different types of accounts. The function should apply specific rules based on the account type:
- For a `Checking` account, the withdrawal amount should not exceed the current balance.
- For a `Savings` account, the withdrawal amo... | Here is the Python code to solve the given problem in the markdown block:
```python
from enum import Enum
class AccountType(Enum):
Checking = 1
Savings = 2
def withdraw(account_type: AccountType, balance: float, amount: float) -> bool:
"""
Processes a withdrawal request based on the account type and c... |
magic_instruct_75k | 61,598 | Create a Python function to manage and display different UI panels in a mobile game. The function should handle button events to show specific panels based on the event type. The UI panel system should be extensible, allowing for the addition of new panel components and button events in the future.
The code should sta... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Callable
# Hypothetical method to get a UI view for a specific panel component type
def GetUiView(panel_type: str):
# Implementation details are abstracted away
return f"UI View for {panel_type}"
# Hyp... |
magic_instruct_75k | 61,653 | Write a Python function to simulate rolling two dice `n` times and return a dictionary containing the frequency of each possible sum from 2 to 12. The function should start with:
```python
from typing import Dict
def simulate_dice_rolls(n: int) -> Dict[int, int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
import random
def simulate_dice_rolls(n: int) -> Dict[int, int]:
"""
Simulate rolling two dice n times and return a dictionary containing the frequency of each possible sum from 2 to 12.
Args:
... |
magic_instruct_75k | 61,665 | Write a Python function to extract additional endpoints from a given SPARQL query. The function should identify and return a list of URIs that appear in the `FROM` or `FROM NAMED` clauses of the SPARQL query. The code should start with:
```python
from typing import List
import re
def extract_endpoints(sparql_query: st... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_endpoints(sparql_query: str) -> List[str]:
"""
Extracts additional endpoints from a given SPARQL query.
The function identifies and returns a list of URIs that appear in the `F... |
magic_instruct_75k | 61,668 | Write a Python function to identify and return a list of palindromic strings from a given list of strings. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization.
The function should start with:
```python
from t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import string
def find_palindromes(strings: List[str]) -> List[str]:
"""
Returns a list of palindromes from the input list of strings.
Args:
strings: A list of strings.
Returns:
... |
magic_instruct_75k | 61,670 | Write a Python function to find the list of good cities, which are the cities not present in the bad cities list. Each city is represented by a unique identifier. The function should take two parameters:
- `cities`: a set containing unique identifiers of all cities
- `bad_cities`: a set containing unique identifiers of... | Here is the Python code to solve the given problem in the markdown block:
```python
def find_good_cities(cities: set, bad_cities: set) -> set:
"""
Find the list of good cities, which are the cities not present in the bad cities list.
Args:
cities (set): A set containing unique identifiers of all ci... |
magic_instruct_75k | 61,672 | Write a Python function to parse and extract timestamps from a given log file. The log file contains entries with timestamps in the format "YYYY-MM-DD HH:MM:SS". The function should take the log file as input and return a list of timestamps extracted from the log file.
The code should start with:
```python
from typing... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_timestamps(log_file: str) -> List[str]:
"""
Extracts timestamps from a log file containing entries with timestamps in the format "YYYY-MM-DD HH:MM:SS".
Args:
log_file (... |
magic_instruct_75k | 61,714 | Write a Python function to parse a given code snippet and extract information about Rust modules and their associated file paths. The code snippet contains comments that specify the Rust module names and the corresponding file paths. The function should return a dictionary where the keys are the module names and the va... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def extract_module_info(code_snippet: str) -> dict:
"""
Extracts Rust module names and their associated file paths from a given code snippet.
Args:
code_snippet (str): The code snippet containing Rust mod... |
magic_instruct_75k | 61,737 | Create a Python class `DateTime` that can parse and validate date and time strings. The class should handle date and time strings in the format "YYYY-MM-DD HH:MM:SS". The class should raise specific exceptions for invalid inputs:
1. **DateParsingException**: Raised if the input string does not match the expected format... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
from datetime import datetime
class DateParsingException(Exception):
"""Exception raised for errors in the input parsing."""
pass
class DateValidationException(Exception):
"""Exception raised for errors in the da... |
magic_instruct_75k | 61,745 | Write a Python function to filter a list of patient records based on specific criteria. Each patient record is represented as a dictionary with keys "name", "age", "gender", and "diagnosis". The function should filter the patient records according to the following conditions:
1. Patients under the age of 18 should be e... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def filter_patients(patients: List[Dict[str, any]]) -> List[Dict[str, any]]:
"""
Filters a list of patient records based on specific criteria.
Args:
patients (List[Dict[str, any]]): A ... |
magic_instruct_75k | 61,754 | Write a Python function to construct a dictionary based on the given input parameters. The function should take in two parameters: `model` (a string representing a model name) and `description` (an optional string representing a description of the model). If a description is provided, it should be included in the dicti... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_model_dict(model: str, description: str = None) -> dict:
"""
Constructs a dictionary based on the given model name and an optional description.
Args:
model (str): The name of the model.
descrip... |
magic_instruct_75k | 61,768 | Write a Python function to manipulate a given string representing a variable name according to the following operations:
1. Remove any leading or trailing whitespace from the variable name.
2. Convert the variable name to lowercase.
3. Replace any occurrences of a period ('.') with an underscore ('_').
The function sh... | Here is the Python code to solve the given problem in the markdown block:
```python
def manipulate_variable_name(name: str) -> str:
"""
Manipulates a given variable name string by performing the following operations:
1. Removes any leading or trailing whitespace.
2. Converts the string to lowercase.
... |
magic_instruct_75k | 61,787 | Write a Python function to process a list of employee data and return a dictionary containing the first names, last names, and email addresses of the employees. The input data is a list of lists, where each inner list contains the employee's first name, last name, and email address in that order. The function should it... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_employee_data(data: List[List[str]]) -> Dict[str, List[str]]:
"""
Processes a list of employee data and returns a dictionary containing the first names, last names, and email addresses ... |
magic_instruct_75k | 61,789 | Write a Python function to process an input dictionary based on the parameters of an action retrieved using a given reference. The function should update the input dictionary with the parameters from the retrieved action and return the modified dictionary. The function should start with:
```python
def process_action_pa... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_action_parameters(action_ref: str, input_dict: dict) -> dict:
"""
Process the input dictionary based on the parameters of the action retrieved using the given reference.
Args:
action_ref (str): Reference... |
magic_instruct_75k | 61,814 | Write a Python function to generate an SSH command string based on the provided instance information. The instance information is a dictionary containing the IP address, username, and port number of the target host. The SSH command should include options to disable strict host key checking and to write the known hosts ... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_ssh_command(instance_info: dict) -> str:
"""
Generates an SSH command string based on the provided instance information.
Args:
instance_info (dict): A dictionary containing the instance information with... |
magic_instruct_75k | 61,828 | Write a Python function `process_ad_settings(settings: dict) -> dict` that processes a dictionary containing various settings for an advertising platform. The function should modify the dictionary by adding a new key-value pair for each setting, where the key is the original setting name prefixed with "AD_SETTING_" and... | Here is the Python code to solve the given problem in the markdown block:
```python
def process_ad_settings(settings: dict) -> dict:
"""
Processes the input dictionary by modifying the keys and values according to the specified rules.
Args:
settings (dict): The original dictionary containing the ad... |
magic_instruct_75k | 61,838 | Write a Python function to process a given text by splitting it into individual terms and further processing each term by splitting out any colons present within them. The function should return a list of processed terms.
The code should start with:
```python
from typing import List
def process_text(text: str) -> Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_text(text: str) -> List[str]:
"""
Processes a given text by splitting it into individual terms and further processing each term by splitting out any colons present within them.
Args:
... |
magic_instruct_75k | 61,840 | Write a Python function to compare two dictionaries representing order books in a financial trading system. The dictionaries contain price levels as keys and order quantities as values. Your goal is to identify the differences between the two order books in terms of both bid (buy) and ask (sell) orders. The function sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Tuple
def DictDiff(book1: Dict[float, int], book2: Dict[float, int]) -> Dict[float, int]:
"""
Compare two dictionaries representing order books and return the differences.
Args:
book1 (Dict... |
magic_instruct_75k | 61,847 | Write a Python function to monitor the status of a remote job using a simulated job status string. The function should take two parameters: the job status string and a keyword to search for in the job status. The function should then check if the keyword is present in the job status. If the keyword is found, the functi... | Here is the Python code to solve the given problem in the markdown block:
```python
def monitor_job_status(job_status: str, keyword: str) -> str:
"""
Monitors the status of a remote job by checking if a specified keyword is present in the job status string.
Args:
job_status (str): The string repres... |
magic_instruct_75k | 61,852 | Write a Python function to update the configuration settings of a project based on the provided inputs. The function should handle updating settings for both Python 2 and Python 3, as well as updating a specific setting with system library paths. The function should return 0 upon successful completion.
The function sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def get_system_lib_paths() -> List[str]:
"""
Simulated function to get system library paths.
In a real-world scenario, this function would fetch the actual system library paths.
"""
ret... |
magic_instruct_75k | 61,859 | Write a Python function to find the "hubs" in a given graph. A hub is defined as a node with the highest degree in the graph. The degree of a node is the number of connections (edges) it has to other nodes. The graph is represented as an adjacency list, where each key is a node and the value is a list of adjacent nodes... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def getHubs(graph: dict) -> List[str]:
"""
Find and return a list of nodes that qualify as hubs in the given graph.
A hub is a node with the highest degree in the graph.
Args:
graph (dic... |
magic_instruct_75k | 61,878 | Write a Python function `construct_build_options` that constructs the build options string for an OpenCL program named "Concat" based on the given conditions. The function should take three inputs:
- A string `source` representing the source code of the program.
- An integer `outC` representing the number of output cha... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_build_options(source: str, outC: int, registry_data_type: str) -> str:
"""
Constructs the build options string for the "Concat" OpenCL program based on the given conditions.
Args:
source (str): The sou... |
magic_instruct_75k | 61,887 | Write a Python function to extract the app label and module name from a given string. The input string will always be in the format "app_label.module_name", where the app label is the first part of the string before the first dot ('.'), and the module name is the rest of the string after the first dot. The function sho... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_app_module(input_string: str) -> tuple:
"""
Extracts the app label and module name from a given string.
The input string is expected to be in the format "app_label.module_name",
where the app label is the fi... |
magic_instruct_75k | 61,897 | Write a Python function to parse and organize a dictionary of media files. Each key in the dictionary represents a unique media file, and the corresponding value is a tuple containing the file's specifications. The specifications include the resolution (for videos) or bitrate (for audio), the file format, the media typ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple
def parse_media_files(media_dict: Dict[str, Tuple[str, str, str, str]]) -> List[Tuple[str, str, str, str]]:
"""
Parses and organizes a dictionary of media files into a list of tuples.
A... |
magic_instruct_75k | 61,907 | Write a Python function to transform a given string by converting all vowels to uppercase and all consonants to lowercase. The function should accept a single parameter, `input_string`, which is a string containing only alphabetic characters (both uppercase and lowercase). The function should return the modified string... | Here is the Python code to solve the given problem in the markdown block:
```python
def transform_string(input_string: str) -> str:
"""
Transforms the input string by converting all vowels to uppercase and all consonants to lowercase.
Args:
input_string (str): The input string containing only alpha... |
magic_instruct_75k | 61,916 | Write a Python function to generate metrics based on the statuses of tasks in a given list. Each task is represented as a dictionary with keys "status" and "status_details". The "status" key holds the current status of the task, which can be either "success" or "failure". The "status_details" key holds additional detai... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def generate_task_metrics(task_list: List[Dict[str, Dict[str, str]]]) -> Dict[str, int]:
"""
Generate metrics based on the statuses of tasks in a given list.
Args:
task_list (List[Dict... |
magic_instruct_75k | 61,918 | Write a Python function to find the maximum profit that can be obtained by buying and selling a stock at most once, given an array of integers representing the daily stock prices. The maximum profit is the maximum difference between any two numbers in the array, where the larger number appears after the smaller number.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_profit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be obtained by buying and selling a stock at most once.
Args:
prices (List[int]): A list of integers repre... |
magic_instruct_75k | 61,932 | Write a Python function to filter and square all even numbers from a given list of integers. The function should return a new list containing the squares of all the even numbers in the input list. If the input list is empty or does not contain any even numbers, the function should return an empty list.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def square_even_numbers(input_list: List[int]) -> List[int]:
"""
Returns a new list containing the squares of all even numbers from the input list.
Args:
input_list (List[int]): The list of ... |
magic_instruct_75k | 61,950 | Write a Python function to compute the normalizing constants for a set of cached queries. The function should take a list of cached queries as input and calculate the totals for memory, duration, and bytes processed to normalize the summary chart. Each cached query is represented as a dictionary with the keys "Memory",... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def normalizing_constants(cached_queries: List[Dict[str, float]]) -> Dict[str, float]:
"""
Compute the normalizing constants for a set of cached queries.
Args:
cached_queries (List[Dic... |
magic_instruct_75k | 61,959 | Write a Python function `set_item` that takes three parameters: `index` (an integer representing the index of the item to be localized), `localized_string` (a dictionary representing the localized string for different languages), and `this` (a reference to the current object). The function should update the localized s... | Here is the Python code to solve the given problem in the markdown block:
```python
def set_item(index: int, localized_string: dict, this: object) -> None:
"""
Updates the localized string for a specific item at the given index in the current object.
Args:
index (int): The index of the item to be l... |
magic_instruct_75k | 61,963 | Write a Python function to calculate the sum of the squares of a given array of numbers. The function should take an array of numbers as input and return the sum of the squares of those numbers. The code should start with:
```python
from typing import List
def sum_of_squares(arr: List[float]) -> float:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_squares(arr: List[float]) -> float:
"""
Calculate the sum of the squares of the given array of numbers.
Args:
arr (List[float]): A list of numbers for which the sum of squares is ... |
magic_instruct_75k | 61,975 | Write a Python function to find the longest word in a given list of strings. If there are multiple words with the same maximum length, return the first one encountered in the list. The function should start with:
```python
from typing import List
def find_longest_word(words: List[str]) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_longest_word(words: List[str]) -> str:
"""
Finds the longest word in a given list of strings.
Args:
words (List[str]): A list of strings from which to find the longest word.
Re... |
magic_instruct_75k | 61,992 | Write a Python function to calculate the Green's function for both spherical and cylindrical scatterers given the frequency of the electromagnetic wave, the radius of the scatterer, the distances between the source and the scatterer, a constant \( M \), and the speed of light \( c \). The function should return the Gre... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def calculate_greens_function(freq: np.ndarray, r: float, d_ij: np.ndarray, M: float, c: float) -> tuple:
"""
Calculate the Green's function for both spherical and cylindrical scatterers.
Args:
f... |
magic_instruct_75k | 61,998 | Write a Python function to simulate a simple game-saving system. The function should be able to save the current game state to a file and load the game state from a file. The game state is represented as a dictionary containing key-value pairs where keys are strings and values are integers. The function should handle f... | Here is the Python code to solve the given problem in the markdown block:
```python
import json
from typing import Dict
def save_game_state(game_state: Dict[str, int], file_path: str) -> None:
"""
Save the current game state to a file.
Args:
game_state (Dict[str, int]): The current game state repr... |
magic_instruct_75k | 62,010 | Write a Python function to calculate the new position of a dinosaur after it jumps in a simple game simulation. The dinosaur's position is represented by its x and y coordinates on a grid. The dinosaur can jump a fixed distance to avoid obstacles. The function should take the current x and y coordinates of the dinosaur... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculateJumpPosition(x: int, y: int) -> tuple:
"""
Calculate the new position of the dinosaur after it jumps.
The dinosaur jumps a fixed distance of 50 units in the x direction, while the y coordinate remains unchanged... |
magic_instruct_75k | 62,016 | Write a Python function to count the number of holiday events for each month from a given list of holiday events. Each holiday event is represented as a dictionary with keys: 'date' (in the format 'YYYY-MM-DD'), 'description', 'locale', 'notes', 'region', and 'type'. The function should ignore events with an empty 'dat... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
from collections import defaultdict
def count_holidays_by_month(holiday_events: List[Dict[str, str]]) -> Dict[str, int]:
"""
Counts the number of holiday events for each month from a given list of ... |
magic_instruct_75k | 62,050 | Write a Python function to convert a given tone string to its corresponding hexadecimal color code. The tone string can be one of the following: "primary", "secondary", "success", "danger", "warning", or "info". The color codes for these tones are as follows:
- primary: #007bff
- secondary: #6c757d
- success: #28a745
-... | Here is the Python code to solve the given problem in the markdown block:
```python
def tone_to_hex_code(tone: str) -> str:
"""
Converts a given tone string to its corresponding hexadecimal color code.
Args:
tone (str): The tone string to convert. Valid tones are "primary", "secondary", "success", ... |
magic_instruct_75k | 62,062 | Write a Python function to format a given C# code snippet by removing all `#region` and `#endregion` directives, as well as any leading or trailing whitespace from each line. The function should ensure that there is only a single newline character at the end of the formatted code.
The code should start with:
```python... | Here is the Python code to solve the given problem in the markdown block:
```python
def format_code(code: str) -> str:
"""
Formats a given C# code snippet by removing all `#region` and `#endregion` directives,
and ensuring that each line is stripped of leading and trailing whitespace.
The formatted code... |
magic_instruct_75k | 62,068 | Write a Python function to map a given color code to its corresponding color name. If the color code does not match any known color, the function should return "UNKNOWN". The color codes and their corresponding color names are predefined.
The code should start with:
```python
def get_color_name(color_code: int) -> str... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_color_name(color_code: int) -> str:
"""
Maps a given color code to its corresponding color name. If the color code does not match any known color, returns "UNKNOWN".
Args:
color_code (int): The color code to... |
magic_instruct_75k | 62,086 | Write a Python function to generate a Tree Connect Request packet for a network communication protocol. The Tree Connect Request packet is used to request the connection of a client to a share on a server in the context of the Common Internet File System (CIFS) protocol.
The structure of the Tree Connect Request packe... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_tree_connect_request(structure_size: bytes, flags: bytes, path_offset: bytes) -> bytes:
"""
Generates a Tree Connect Request packet for a network communication protocol.
The Tree Connect Request packet is used ... |
magic_instruct_75k | 62,123 | Write a Python function to simulate a simple URL routing system. The function should take a URL path and return the corresponding view function name based on the provided path. The URL paths are unique and do not contain any parameters or query strings. The view function names are also unique. If the provided path does... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def get_view_function(url_path: str, url_patterns: List[Tuple[str, str, str]]) -> str:
"""
Simulates a simple URL routing system by mapping a URL path to its corresponding view function name.
... |
magic_instruct_75k | 62,136 | Create a Python class `EntityStorage` that manages an entity storage system. The class should provide methods to erase entities based on their IDs and to flush the erase queue. The class should be designed to be inherited from and extended by derived classes.
The class should have the following methods:
1. `erase_equa... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
class EntityStorage:
"""
A class to manage an entity storage system.
Attributes:
entities (Dict[int, List[Any]]): A dictionary to store entities, where the key is the entity ID an... |
magic_instruct_75k | 62,146 | Write a Python function to process a given directory structure and perform specific operations on the files and subdirectories within it. The function should accomplish the following tasks:
1. Create a new directory named "data" within the current working directory.
2. Traverse through the contents of the current direc... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import re
def process_directory(directory: str) -> None:
"""
Processes a given directory structure and performs specific operations on the files and subdirectories within it.
Args:
directory (str): The pa... |
magic_instruct_75k | 62,149 | Write a Python function to find the n-th node from the end of a singly linked list. The linked list is represented by a `Node` class, where each node contains data and a reference to the next node. If the list does not contain `n` nodes, the function should return `None`.
The function should start with:
```python
clas... | Here is the Python code to solve the given problem in the markdown block:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
def find_nth_from_end(head: Node, n: int) -> int:
"""
Finds the n-th node from the end of a singly linked list.
Args:
head... |
magic_instruct_75k | 62,150 | Write a Python function to calculate the sum of even-valued terms in the Fibonacci sequence 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 terms of the Fibonacci sequence are 0, 1, 1,... | Here is the Python code to solve the given problem in the markdown block:
```python
def fib_even_sum(limit: int) -> int:
"""
Calculate the sum of even-valued terms in the Fibonacci sequence up to a given limit.
Args:
limit (int): The upper limit for the Fibonacci sequence terms.
Returns:
... |
magic_instruct_75k | 62,162 | Write a Python function to find the length of the longest consecutive sequence of 1s in a given binary string. The binary string consists of only '0's and '1's and can be of any length. The function should return the count of the longest sequence of consecutive '1's.
The code should start with:
```python
def longest_c... | Here is the Python code to solve the given problem in the markdown block:
```python
def longest_consecutive_ones(s: str) -> int:
"""
Find the length of the longest consecutive sequence of '1's in a given binary string.
Args:
s (str): A binary string consisting of '0's and '1's.
Returns:
... |
magic_instruct_75k | 62,165 | Write a Python function to count the number of voxels for each object in a 3D segmentation volume, excluding the object with a specified label. The function should take three parameters:
- `in_out`: a 3D numpy array representing the volume (shape: (n, m, p))
- `labels`: a 3D numpy array representing the segmentation la... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def count_voxels_per_object(in_out: np.ndarray, labels: np.ndarray, label_corner: int) -> dict:
"""
Counts the number of voxels for each object in a 3D segmentation volume, excluding the object with a specifi... |
magic_instruct_75k | 62,175 | Write a Python function to serialize a custom text data type. The function should take a string representing the text data as input and return a serialized string according to the specified format. The serialization format for non-empty text data should be as follows:
- If the text data contains whitespace characters, ... | Here is the Python code to solve the given problem in the markdown block:
```python
def serialize_text(data: str) -> str:
"""
Serialize the given text data according to the specified format.
Args:
data (str): The text data to be serialized.
Returns:
str: The serialized text data.
"... |
magic_instruct_75k | 62,188 | Write a Python function to parse a given code snippet and extract relevant information about the actions performed. Each line in the code snippet represents an action, and the format of each line is as follows:
```
<line_number> <action_type> <action_name> <action_details>
```
Where:
- `<line_number>` is the line num... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def parse_code_snippet(code_snippet: str) -> List[Tuple[int, str, str, str]]:
"""
Parses a given code snippet and extracts relevant information about the actions performed.
Args:
code... |
magic_instruct_75k | 62,203 | Write a Python function to classify monthly rainfall measurements into three categories: "PLENTY RAINFALL", "MODERATE RAINFALL", and "LIGHT RAINFALL". The function should take a list of floating-point numbers representing the monthly rainfall measurements and return a list of strings indicating the classification for e... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def classify_rainfall(rainfall: List[float]) -> List[str]:
"""
Classify each month's rainfall measurement into one of three categories:
"PLENTY RAINFALL", "MODERATE RAINFALL", or "LIGHT RAINFALL".
... |
magic_instruct_75k | 62,210 | Write a Python function to find the maximum value in a given list of integers using a generator expression. The function should iterate through the elements of the list and return the maximum value. The code should start with:
```python
from typing import List
def find_max_value(A: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_max_value(A: List[int]) -> int:
"""
Find the maximum value in a given list of integers using a generator expression.
Args:
A (List[int]): The list of integers from which to find the... |
magic_instruct_75k | 62,215 | Write a Python function `generate_endpoint_dict` that takes an instance of the `APIEndpointHandler` class as input and returns a dictionary where the keys are the names of the properties (`seal` and `secret`) and the values are the corresponding endpoint classes (`v1.SealEndpoint` and `v1.SecretEndpoint`). The function... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_endpoint_dict(api_handler):
"""
Dynamically generates and returns a dictionary containing the names of the properties
and their corresponding endpoint classes from the APIEndpointHandler instance.
Args:
... |
magic_instruct_75k | 62,221 | Write a Python function to analyze the metadata of a software package and extract specific information. The metadata is represented as a list of strings, where each string contains details about the package, such as its license, natural language, operating system compatibility, programming language, and topic. The func... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Union
def extract_metadata(metadata: List[str]) -> Dict[str, Union[str, List[str]]]:
"""
Extracts the programming language and required dependencies from the given metadata list.
Args:
... |
magic_instruct_75k | 62,231 | Write a Python function to filter and sort a list of dictionaries containing weather data. Each dictionary represents a specific weather parameter and contains keys such as 'abbr', 'code', 'title', and 'units'. The function should filter the list to include only those dictionaries where the 'title' key contains the wor... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def filter_and_sort_weather_data(weather_data: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""
Filters and sorts a list of dictionaries containing weather data.
The function filters the lis... |
magic_instruct_75k | 62,253 | Write a Python function to process data from a machine learning model. The function should take in two input arrays, `Xm` and `Xmg`, and a one-dimensional array `dims`. The function should calculate and return the total number of features and the number of dimensions based on the given input arrays and dimensions array... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import numpy as np
def process_data(Xm: np.ndarray, Xmg: np.ndarray, dims: np.ndarray) -> Tuple[int, int]:
"""
Processes data from a machine learning model to calculate the total number of features and ... |
magic_instruct_75k | 62,271 | Write a Python function to process and analyze histograms generated by a search-related functionality in a web application. The histograms are used to track user interactions with related search suggestions and provide insights into user behavior. The function should take in a list of histogram entries and return the t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Union
def processHistogramEntries(entries: List[str]) -> Dict[str, Union[int, List[int]]]:
"""
Processes a list of histogram entries to count the total number of suggestions clicked
and to ext... |
magic_instruct_75k | 62,276 | Write a Python function to increment each element of a given list of integers by 1 and then print the modified list. The function should return the modified list as well. The code should start with:
```python
from typing import List
def increment_and_print(numbers: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def increment_and_print(numbers: List[int]) -> List[int]:
"""
Increments each element of the given list of integers by 1 and prints the modified list.
Args:
numbers (List[int]): The list of ... |
magic_instruct_75k | 62,295 | Write a Python function to find the k closest points to a given reference point in a 2D plane. The function should take in a list of 2D points, the reference point, and the value of k, and return a list of the k closest points to the reference point. The function should be efficient and handle edge cases such as when k... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import math
def k_closest_points(points: List[Tuple[int, int]], reference: Tuple[int, int], k: int) -> List[Tuple[int, int]]:
"""
Find the k closest points to a given reference point in a 2D plane... |
magic_instruct_75k | 62,296 | Write a Python function to create a mapping between abbreviated channel names and their corresponding full channel names with the 'ar' reference for EEG data analysis. The function should take two lists as input: `short_ch_names` containing abbreviated channel names and `ar_ch_names` containing the corresponding full c... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def create_channel_mapping(short_ch_names: List[str], ar_ch_names: List[str]) -> Dict[str, str]:
"""
Creates a mapping between abbreviated channel names and their corresponding full channel names w... |
magic_instruct_75k | 62,308 | Write a Python function to sort the keys of an HTTP headers dictionary in alphabetical order. If two headers have the same key, they should appear in the same order as in the original dictionary. The function should return a new dictionary with the sorted keys.
The code should start with:
```python
from typing import ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def sort_headers(headers: Dict[str, str]) -> Dict[str, str]:
"""
Sorts the keys of an HTTP headers dictionary in alphabetical order.
Args:
headers (Dict[str, str]): A dictionary representing... |
magic_instruct_75k | 62,313 | Write a Python function to initialize a dictionary `b_set_easy_to_read` with sets of words grouped by their lengths. The dictionary should contain the following sets of words:
- Words of length 3: {'cat', 'dog', 'bat'}
- Words of length 4: {'fish', 'bird', 'frog'}
- Words of length 5: {'snake', 'horse', 'zebra'}
The f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Set
def initialize_word_dictionary() -> Dict[int, Set[str]]:
"""
Initializes a dictionary with sets of words grouped by their lengths.
Returns:
Dict[int, Set[str]]: A dictionary where keys ... |
magic_instruct_75k | 62,314 | Write a Python function to handle OpenCL error codes and return the corresponding error message. The function should take an integer error code as input and return the corresponding error message as a string. The error messages are defined as follows:
- `CL_SUCCESS`: "Success"
- `CL_INVALID_VALUE`: "Invalid value"
- `C... | Here is the Python code to solve the given problem in the markdown block:
```python
def getErrorMsg(error_code: int) -> str:
"""
Returns the corresponding error message for a given OpenCL error code.
Args:
error_code (int): The OpenCL error code.
Returns:
str: The corresponding error m... |
magic_instruct_75k | 62,323 | Write a Python function to generate Verilog code for declaring signals as registers and wiring them to output pins. The function should take a dictionary where the keys are signal names and the values are their corresponding widths. The function should return a string containing the Verilog code.
The code should start... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def generate_verilog_code(signals: Dict[str, int]) -> str:
"""
Generates Verilog code for declaring signals as registers and wiring them to output pins.
Args:
signals (Dict[str, int]): A dic... |
magic_instruct_75k | 62,324 | Write a Python function to simulate a simplified version of a Thrift communication system. The function should handle two main tasks:
1. **Extract Peer Identity**: Given an address, extract the peer identity associated with that address. The function should return a tuple containing an extraction result (as an enum) an... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Tuple, List, Any
class Sender:
class ExtractPeerIdentityResult:
SUCCESS = "SUCCESS"
FAILURE = "FAILURE"
def __init__(self):
self.sessions = []
def extractPeerIdentity(self,... |
magic_instruct_75k | 62,334 | Write a Python function to convert a given binary string into its decimal representation. The function should take a binary string as input and return its decimal equivalent. The code should start with:
```python
def binary_to_decimal(binary: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def binary_to_decimal(binary: str) -> int:
"""
Converts a given binary string into its decimal representation.
Args:
binary (str): The binary string to be converted.
Returns:
int: The decimal equivalent... |
magic_instruct_75k | 62,337 | Write a Python function to derive time intervals from a given Pandas DataFrame containing latitude, longitude, and timestamp information. The DataFrame has columns `latitudeE7`, `longitudeE7`, and `timestampMs`. The function should calculate the time difference between consecutive timestamps in milliseconds, convert th... | Here is the Python code to solve the given problem in the markdown block:
```python
import pandas as pd
def derive_time_intervals(json_df: pd.DataFrame) -> pd.DataFrame:
"""
Derive time intervals from a given Pandas DataFrame containing latitude, longitude, and timestamp information.
Args:
json_df... |
magic_instruct_75k | 62,364 | Write a Python function to retrieve the Ubisoft-assigned game ID for a given platform. The function should take a platform name as input and return the corresponding Ubisoft-assigned game ID. If the input platform is not one of the specified platforms, the function should return `None`.
The platform names and their as... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_game_id(platform: str) -> str:
"""
Retrieves the Ubisoft-assigned game ID for a given platform.
Args:
platform (str): The name of the platform for which to retrieve the game ID.
Returns:
str: Th... |
magic_instruct_75k | 62,380 | Implement a Python class that replicates the behavior of the given C++ code snippet. The class should have the following functionalities:
1. A constructor that initializes a shared pointer `token` with the value 129.
2. A method `doIter` that takes no arguments and increments a variable `iter` by 1. It should also inc... | Here is the Python code to solve the given problem in the markdown block:
```python
class DataManager:
def __init__(self):
"""
Initialize the DataManager class with a shared pointer `token`,
a variable `iter`, and two data containers `data1` and `data2`.
"""
self.token = 129 ... |
magic_instruct_75k | 62,398 | Write a Python function to allocate images for training and testing based on the given conditions and print the statistics for each set. The function should handle the following variables:
- `train_idx`: An integer representing the index of the training set.
- `train_n_images`: An integer representing the number of ima... | Here is the Python code to solve the given problem in the markdown block:
```python
def allocate_images(train_idx: int, train_n_images: int, test_idx: int, test_n_images: int) -> None:
"""
Allocates images for training and testing based on the given conditions and prints the statistics for each set.
Args:
... |
magic_instruct_75k | 62,400 | Write a Python function to parse a comment string that specifies tab settings for the vi text editor and return the settings in a dictionary format. The comment string will be in the format `# vi: tabstop=<value> expandtab shiftwidth=<value> softtabstop=<value>`, where `<value>` represents an integer. The function shou... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_vi_comment(comment: str) -> dict:
"""
Parses a comment string specifying vi tab settings and returns them in a dictionary format.
Args:
comment (str): The comment string in the format `# vi: tabstop=<value... |
magic_instruct_75k | 62,440 | Create a Python function that simulates a Discord bot command to redirect users to a specified URL. The function should take a URL as input and then simulate sending a message to the user with the provided URL and also simulate redirecting the user to that URL. The function should not actually interact with Discord but... | Here is the Python code to solve the given problem in the markdown block:
```python
def redirect(url: str) -> None:
"""
Simulates a Discord bot command that redirects users to a specified URL.
Args:
url (str): The URL to which the user should be redirected.
Returns:
None: The function ... |
magic_instruct_75k | 62,447 | Write a Python function to simulate a simple music player with the ability to change and retrieve its mode. The music player can be in one of three modes: "normal", "shuffle", or "repeat". The function should allow setting the mode to any of these three values and retrieving the current mode. If an invalid mode is atte... | Here is the Python code to solve the given problem in the markdown block:
```python
def music_player_mode(initial_mode: str, mode_changes: list) -> list:
"""
Simulate a simple music player with the ability to change and retrieve its mode.
Args:
initial_mode (str): The initial mode of the music play... |
magic_instruct_75k | 62,457 | Write a Python function to translate a list of English words into their corresponding translated words using a provided dictionary of word pairs. The function should handle cases where a translation is not found by returning a default message.
The code should start with:
```python
from typing import List, Dict
def tr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def translateWords(englishWords: List[str], wordPairs: Dict[str, str]) -> List[str]:
"""
Translates a list of English words into their corresponding translated words using a provided dictionary of ... |
magic_instruct_75k | 62,491 | Write a Python function to generate a FizzBuzz sequence up to a given number `n`. The FizzBuzz sequence follows these rules:
- For multiples of 3, "fizz" is printed instead of the number.
- For multiples of 5, "buzz" is printed instead of the number.
- For numbers that are multiples of both 3 and 5, "fizzbuzz" is print... | Here is the Python code to solve the given problem in the markdown block:
```python
def fizz_buzz(n: int) -> str:
"""
Generate a FizzBuzz sequence up to a given number `n`.
Args:
n (int): The upper limit of the sequence (inclusive).
Returns:
str: A string representing the FizzBuzz sequ... |
magic_instruct_75k | 62,494 | Write a Python function to dynamically set the paths for various dependencies based on the environment. The function should take in the `home` directory and set the paths for the dependencies based on the environment variables. Specifically, the function should set the `charm_path` by concatenating the `home` directory... | Here is the Python code to solve the given problem in the markdown block:
```python
def set_dependency_paths(home: str) -> tuple:
"""
Dynamically sets the paths for various dependencies based on the environment.
Args:
home (str): The home directory from which to set the charm_path.
Returns:
... |
magic_instruct_75k | 62,495 | Write a Python function to extract the author's name, email, license, and copyright information from a given code snippet. The code snippet will always contain the author's information in a specific format. The function should return a dictionary with the extracted information.
The code should start with:
```python
im... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def extract_author_info(code_snippet: str) -> dict:
"""
Extracts the author's name, email, license, and copyright information from a given code snippet.
Args:
code_snippet (str): The code snippet containi... |
magic_instruct_75k | 62,503 | Write a Python function `update_leaks_data` that updates the missed leaks count and the corresponding time series data in a water distribution network monitoring system. The function should handle cases where the `site_dict` or `timeseries` may be initially empty. The function should take the following parameters:
- `s... | Here is the Python code to solve the given problem in the markdown block:
```python
def update_leaks_data(site_dict, missed_leaks_str, n_leaks, site, timeseries, current_timestep):
"""
Updates the missed leaks count and the corresponding time series data in a water distribution network monitoring system.
A... |
magic_instruct_75k | 62,507 | Write a Python function to calculate the nth Fibonacci number using an iterative approach. The function should be efficient and avoid the pitfalls of a recursive solution, such as stack overflow for large values of n. The code should start with:
```python
def fibonacci(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def fibonacci(n: int) -> int:
"""
Calculate the nth Fibonacci number using an iterative approach.
Args:
n (int): The position in the Fibonacci sequence to calculate.
Returns:
int: The nth Fibonacci numb... |
magic_instruct_75k | 62,605 | Write a Python function to automate the testing process for a software project by executing a specific version of the NUnit console runner to run the unit tests for the project. The function should take the path to the NUnit console runner executable and the path to the test assembly DLL file as parameters. The functio... | Here is the Python code to solve the given problem in the markdown block:
```python
import subprocess
import os
def run_nunit_tests(nunit_runner: str, test_assembly: str) -> None:
"""
Automates the testing process by executing the NUnit console runner with the provided test assembly DLL file.
Args:
... |
magic_instruct_75k | 62,607 | Write a Python function to simulate the creation and manipulation of 3D scene nodes and entities based on the given code snippet. The function should perform the following operations:
1. Create a scene node named "peen_node" and attach an entity named "peen_entity" with the mesh "peen.mesh" to it.
2. Set the position o... | Here is the Python code to solve the given problem in the markdown block:
```python
def create_and_manipulate_entities():
"""
Simulates the creation and manipulation of 3D scene nodes and entities.
This function performs the following operations:
1. Creates a scene node named "peen_node" and attaches a... |
magic_instruct_75k | 62,614 | Implement a Python function to encode a batch of events using a custom encoder. The function should take a list of event objects and return the encoded string. Each event object has an `encode` method that returns its encoded representation as a string. The encoded string for the batch should be a concatenation of the ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class Event:
def encode(self) -> str:
"""
Encodes the event into a string representation.
"""
raise NotImplementedError("Subclasses must implement the encode method")
class A... |
magic_instruct_75k | 62,634 | Write a Python function to parse a GitHub repository URL and extract the username and repository name. The URL will always be in the format "https://github.com/username/repository". The function should return a tuple containing the username and repository name.
The code should start with:
```python
def parse_github_ur... | Here is the Python code to solve the given problem in the markdown block:
```python
def parse_github_url(url: str) -> tuple:
"""
Parses a GitHub repository URL and extracts the username and repository name.
Args:
url (str): The GitHub repository URL in the format "https://github.com/username/reposi... |
magic_instruct_75k | 62,645 | Write a Python function to parse and process data received over a TCP socket. The function should read a 4-byte size value from the socket, allocate memory to store the data, and then read the specified amount of data into the allocated memory. The function should handle potential errors during the process, such as fai... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Optional, Tuple
def import_data_from_socket(socket_data: bytes) -> Optional[Tuple[int, bytes]]:
"""
Parses and processes data received over a TCP socket.
Args:
socket_data (bytes): The data recei... |
magic_instruct_75k | 62,656 | Write a Python function to process a list of commands and perform specific actions on a dictionary based on the command type. Each command is represented as a string in the format "command_name:arguments", where "command_name" is the name of the command and "arguments" is a comma-separated list of arguments. The functi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def process_commands(commands: List[str]) -> Dict[str, str]:
"""
Processes a list of commands and performs specific actions on a dictionary.
Args:
commands (List[str]): A list of comma... |
magic_instruct_75k | 62,661 | Write a Python function to determine the maximum profit that can be achieved from a list of stock prices over a period of time, given the constraint that only one transaction (buy one unit of stock and sell one unit of stock) is allowed, and you must buy before you sell. The function should take a list of stock prices ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_profit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be achieved from a list of stock prices
with the constraint of a single buy and sell transaction.
Args:
... |
magic_instruct_75k | 62,671 | Write a Python function to determine whether a given Unicode code point falls within any of the specified ranges. The function should return `True` if the code point is within any of the specified ranges and `False` otherwise. The specified ranges are:
- 0x1F240 to 0x1F248
- 0x1F250 to 0x1F251
- 0x20000 to 0x2F73F
- 0x... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_within_unicode_range(code_point: int) -> bool:
"""
Determines whether a given Unicode code point falls within any of the specified ranges.
Args:
code_point (int): The Unicode code point to check.
Returns... |
magic_instruct_75k | 62,673 | Write a Python function to generate a Makefile for a simple C program that uses the SDL2 library for graphics and image loading. The Makefile should compile the program using the GCC compiler and link it with the necessary SDL2 libraries. The function should take the name of the C program as input and generate a Makefi... | Here is the Python code to solve the given problem in the markdown block:
```python
def generate_makefile(program_name: str) -> str:
"""
Generates a Makefile for a C program that uses the SDL2 library for graphics and image loading.
Args:
program_name (str): The name of the C program (without the .... |
magic_instruct_75k | 62,677 | Write a Python function to modify a list of integers based on specific rules. The function should take a list of integers as input and return a modified list where:
1. Each even integer is multiplied by 2.
2. Each odd integer is squared.
The function should start with:
```python
from typing import List
def modify_lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def modify_list(input_list: List[int]) -> List[int]:
"""
Modify a list of integers based on the following rules:
- Each even integer is multiplied by 2.
- Each odd integer is squared.
Args:
... |
magic_instruct_75k | 62,685 | Write a Python function to convert a 2D list (tensor) to a 1D list (vector) in row-major order. The function should take the dimensions of the tensor and the tensor data as input and return a list containing the elements of the tensor in row-major order.
The code should start with:
```python
from typing import List, T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def tensor_to_vector(dimensions: Tuple[int, int], tensor_data: List[List[int]]) -> List[int]:
"""
Converts a 2D tensor (list of lists) to a 1D vector (list) in row-major order.
Args:
... |
magic_instruct_75k | 62,694 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling a stock on different days. You are only allowed to complete at most one transaction (i.e., buy one and sell one share of the stock). The function should take a list of integers `prices` representing the stock prices on di... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def maxProfit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be obtained by buying and selling a stock on different days.
Args:
prices (List[int]): A list of integers r... |
magic_instruct_75k | 62,717 | Write a Python function to extract and count the number of URLs from a given text string. The function should take a string as input and return the count of URLs found within the input string. A URL is defined as any valid web address that starts with "http://" or "https://" and ends with a top-level domain such as ".c... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def count_urls(text: str) -> int:
"""
Counts the number of URLs in a given text string.
Args:
text (str): The input text string to search for URLs.
Returns:
int: The number of URLs found in t... |
magic_instruct_75k | 62,765 | Write a Python function to process metadata from a file named `GS_METADATA` and confirm the completion of the Speech Recognition Toolkit (SCTK) build. The function should read the content of the `GS_METADATA` file, search for specific information related to the SCTK build completion, and return a message indicating whe... | Here is the Python code to solve the given problem in the markdown block:
```python
def confirm_sctk_build_completion(metadata_file: str) -> str:
"""
Confirms the completion of the SCTK build by reading the content of the GS_METADATA file.
Args:
metadata_file (str): The path to the metadata file.
... |
magic_instruct_75k | 62,788 | Write a Python function to generate all possible pairings of dice names such that each pair consists of two distinct dice names. The function should take a list of unique dice names and an integer representing the number of pairs to be formed. The output should be a list of tuples, where each tuple represents a valid p... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
from itertools import permutations
def generate_dice_pairings(dice_names: List[str], num_pairs: int) -> List[Tuple[str, str]]:
"""
Generate all possible pairings of dice names such that each pair ... |
magic_instruct_75k | 62,815 | Write a Python script to automate the build process for a software project on both macOS and Linux operating systems. The script should create a directory named "build," switch to a specific branch named "concat" for testing purposes, set up dependencies, compile the code, and install the built artifacts. The script sh... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import subprocess
def build_project(prefix: str):
"""
Automates the build process for a software project on macOS and Linux.
Args:
prefix (str): The prefix path for the dependencies and installation.
... |
magic_instruct_75k | 62,817 | Write a Python function to split a given string into multiple parts based on a specified delimiter. The function should return a list of the parts and update a global variable to reflect the number of parts created.
The code should start with:
```python
from typing import List
# Global variable to store the number of... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
# Global variable to store the number of parts
part_num = 0
def split_string(input_str: str, delimiter: str) -> List[str]:
"""
Splits the input string into multiple parts based on the specified delimite... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.