Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
52
7.08k
0000be168220370b3d1c
```swift class HTTPResponse { let status: Int let bodyDescription: String var headers: [String: String] // ... other properties and methods init(status: Int, bodyDescription: String, headers: [String: String]) { self.status = status self.bodyDescription = bodyDescription se...
00014f4971aca6559977
```javascript import isHexadecimal from "./isHexadecimal.ts"; export default function isMongoId(str) { if (typeof str !== 'string' || str.length !== 24) { return false; } return isHexadecimal(str); } ``` In the solution, the `isMongoId` function first checks if the input is a string and has a length of 24 c...
000500d0266fe3924d38
```python def predict_health_condition(hypertension: str, heart_disease: str) -> (int, int): model_hyper = 0 if hypertension == "No" else 1 model_heart = 0 if heart_disease == "No" else 1 return model_hyper, model_heart ``` The `predict_health_condition` function takes in the input variables `hypertension` ...
0005177bee86cb4b3094
```python def _intersect(seq1, seq2): # Using set intersection to find common elements return list(set(seq1) & set(seq2)) ``` The `_intersect` function takes two sequences as input and uses the set intersection operation to find the common elements between the sequences. It then converts the resulting set back...
000531a36659d04391cf
```python from django.conf.urls import url, include from django.views.generic import RedirectView urlpatterns = [ url(r'^event/', include('sedastrela_is.event.urls', namespace='event')), url(r'^$', RedirectView.as_view(url='/admin/')), url(r'^profile/$', ProfileView.as_view(), name='profile'), ] ``` In the...
00072421aad7316e0e6d
```swift import Foundation protocol MLBusinessCrossSellingBoxData { func getIconUrl() -> String func getText() -> String func getButtonTitle() -> String func getButtonDeepLink() -> String } class CrossSellingBoxData: NSObject, MLBusinessCrossSellingBoxData { func getIconUrl() -> String { r...
00099a365a035c703158
```swift @objc static func controller(parent: WelcomePageControllerProtocol) -> WelcomePageController? { guard WelcomePageController.shouldShowWelcome() else { return nil } let transitionStyle: UIPageViewController.TransitionStyle = .scroll // or .pageCurl, or .scroll based on specific requirements...
0009dcd450e1d4e1a7f3
```python from .cbindings import convert_to_problem, convert_from_problem, train, load class MLPipeline: def __init__(self, model_name): self.model_name = model_name def convert_to_problem(self, data): return convert_to_problem(data) def convert_from_problem(self, problem_data): r...
0009e2b11705d3ca955b
```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <time.h> long randomWriteThenRead(int blockSize) { clock_t start, end; double cpu_time_used; int returnVal; char *b; int i, r; // Open file for writing returnVal = open("test.txt", O_CREAT | O_TRUN...
0009fce21f12b0e4b603
```cpp #include <cstddef> #include <stdexcept> #include <memory> template <typename T, size_t N> class RingBuf { public: RingBuf() : buffer(new T[N]), head(0), tail(0), size(0) {} void push_back(const T& value) { if (size == N) { head = (head + 1) % N; // Overwrite the oldest element ...
000a12fbb1bafc8e151a
```swift import SwiftUI import UIKit struct ImagePicker: UIViewControllerRepresentable { @Binding var selectedImage: UIImage? @Environment(\.presentationMode) var presentationMode class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate { var parent: ImagePicker...
000a230e5411644560d1
```python import numpy as np import pandas as pd from datetime import datetime from typing import List def generate_random_timestamps(cal: List[datetime], random_n: int) -> List[pd.Timestamp]: random_timestamps = [] for _ in range(random_n): time = np.random.choice(cal) # Choose a random minute from c...
000df7bc96c5e9ba27fb
```javascript import React, { useState, useEffect } from "react"; import { Login } from "../Login"; import { Entry } from "../Entry"; import { Button, MainWrapper } from "./styles"; export const PopupContent: React.FC = () => { const [loading, setLoading] = useState(false); const [streams, setStreams] = useState<A...
000ed66d85a969328dff
```javascript function resolveModuleImport(importPath, currentFilePath) { const path = require('path'); let resolvedPath; if (importPath.startsWith("./")) { resolvedPath = path.resolve(path.dirname(currentFilePath), importPath); } else if (importPath.startsWith("../")) { resolvedPath = path.resolve(pat...
000fc7c368530deb593c
1. Potential Security Vulnerabilities: a. In the `test` method, the code directly accesses the `request` object without any validation or sanitization. This can lead to potential security vulnerabilities such as injection attacks or unauthorized access. b. The `response.headers.update(_headers)` statement seems t...
001126c45e186670f2af
```rust use std::collections::HashMap; use geojson::Feature; use serde_json::Value; #[derive(Debug, PartialEq, Eq)] enum PropType { String, Long, Double, JsonVal, } fn schema<'a>(features: impl Iterator<Item = &'a Feature>) -> HashMap<String, PropType> { let mut schema = HashMap::<String, PropType...
0012ab90ae09cc6f2737
```python import queue import time class Task: def __init__(self, priority, execution_time): self.priority = priority self.execution_time = execution_time def __lt__(self, other): return self.priority < other.priority class TaskScheduler: def __init__(self): self.high_prio...
00137b8ca89dea720ef3
```python from typing import List, Tuple def analyze_license(license: str) -> Tuple[List[str], List[str]]: permissions = [] conditions = [] in_condition = False current_permission = "" current_condition = "" for char in license: if char == '(': in_condition = True ...
00152b43252fadc36a78
```python import re def validate_email(email): if email == "": print("Email is compulsory!") return False else: # Regular expression for basic email format validation email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' if re.match(email_regex, email): ...
0015f4570511f78ce901
```python import matplotlib.pyplot as plt def plot_hitting_probabilities(t_hist, hit_prob_hist): plt.close('all') # Close all existing plots plt.style.use('../conlab.mplstyle') # Set the plot style plt.step(t_hist, hit_prob_hist) # Create a step plot plt.xlabel('Time') # Set x-axis label plt.yl...
0016bcf75b9ada237033
```python from typing import List, Tuple def latest_migration_version(operations: List[Tuple[str, str]]) -> str: latest_version = '' for operation in operations: _, version = operation if version > latest_version: latest_version = version return latest_version ``` The `latest_m...
00170fef94596cca4db3
```java public class WorldRenderer { public void renderMap(Tile[][] map) { for (int y = 0; y < map.length; y++) { for (int x = 0; x < map[y].length; x++) { Tile tile = map[y][x]; String terrainSymbol = getTerrainSymbol(tile.getTerrainType()); Strin...
00198bc6d4981998b056
```python import requests class SimpleHTTPClient: TEST_REQUEST_BASE = { 'timeout': 5, 'verify': False } def send_request(self, request_type, url, headers=None, data=None): if request_type == 'GET': response = requests.get(url, headers=headers, **self.TEST_REQUEST_BASE) ...
00198d239ad0072fdf03
```bash if [ $stage -le 1 ]; then echo "Initializing training..." # Add code to initialize the training process fi if [ $stage -le 2 ]; then echo "Performing feature engineering..." # Add code to perform feature engineering fi if [ $stage -le 3 ]; then echo "Training the model..." # Add code t...
0019d13cdc56f84f82c4
```php function calculateAverageQuizGrade($quiz): float { $totalGrade = 0.0; $questionCount = 0; // Iterate through each question in the quiz foreach ($quiz->questions as $question) { // Accumulate the grades and count the questions $totalGrade += $question->grade; $questionCoun...
001bc2e9f743187d7ab6
```python from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.helpers import config_validation as cv from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( ATTR_SPEED, DATA_COORDINATOR, DATA_UN...
001c3247377839ffe02e
```python import numpy as np from sklearn.neighbors import KernelDensity class KernelDensityEstimator: def __init__(self, kernel='gaussian', bandwidth=1.0): self._kernel = kernel self._bandwidth = bandwidth self._estimators = [] def fit(self, X): p = X.shape[1] for feat...
001e2d20ac60713c2fbe
```python import re def set_primary_key(table_name: str, primary_key_name: str) -> bool: if not table_name or not primary_key_name: return False # Table name and primary key name cannot be empty if not re.match(r'^[A-Z_][A-Z0-9_]*$', primary_key_name): return False # Primary key name should ...
0020b9099b79a9a60339
```python import time class NetworkDevice: def __init__(self): self.port = 22 def execute(self, command, wait=True, venv=False): print(f"Executing command: {command}, wait: {wait}, venv: {venv}") def set_port(self, new_port): self.port = new_port print(f"Port set to: {self...
0020d17d6c960fec8e73
```swift class MaxStack { private var stack: [(value: Int, max: Int)] = [] func push(_ value: Int) { let currentMax = stack.last.map { max($0.max, value) } ?? value stack.append((value, currentMax)) } func pop() -> Int? { return stack.popLast()?.value } func max() -> I...
0021a19dccda1134d228
```python def calculate_total_stars(repositories): stars_dict = {} for repo in repositories: org, repo_name = repo.split('/') stars = get_stars_from_github_api(org, repo_name) # Assume a function to fetch stars from GitHub API if org in stars_dict: stars_dict[org] += stars ...
0022430a683fca579551
```python class BackgroundTaskManager: def __init__(self): self.__task_queue__ = [] def add_task(self, task): # Add the task to the task queue self.__task_queue__.append(task) def get_next_task(self): # Retrieve and remove the next task from the task queue i...
0023fffec8927dac7d60
```java /** * AuthService * * @author Sunnly * @since 2020/12/11 */ public interface AuthService { boolean authenticate(String username, String password); } public class SimpleAuthService implements AuthService { private static final String PREDEFINED_USERNAME = "admin"; private static final String PR...
002438abbbc787069c41
```rust // account_state.rs pub struct AccountState { account_id: u64, balance: f64, } impl AccountState { pub fn new(account_id: u64, initial_balance: f64) -> AccountState { AccountState { account_id, balance: initial_balance, } } pub fn get_balance(&self)...
0025be427711782a1355
```python def get_input(): # Simulate player input for testing purposes return input("Enter your command: ") def update(game, current, response): if response.startswith("MOVE"): direction = response.split()[1] # Update game state to move the player in the specified direction # Examp...
00269781337116103274
```python class CircularQueue: def __init__(self, size): self.size = size self.queue = [None] * size self.cursor = -1 def enqueue(self, element): self.cursor = (self.cursor + 1) % self.size self.queue[self.cursor] = element def dequeue(self): oldest_element ...
0026aa5d202b3c221e43
```python import threading class UpdateManager: def __init__(self): self.update_thread = None def start_update_thread(self, resource): # Start a background thread to update the given resource self.update_thread = threading.Thread(target=self._update_resource, args=(resource,)) ...
0027290d831c11ca7adf
```swift import Foundation // Define a custom error type for validation failures enum ValidationError: Error { case invalidData } // Extend the Decodable protocol to add the validate method public extension Decodable { func validate() throws -> Self { // Use JSONEncoder and JSONDecoder to convert the ...
0027d4cf93fef52228b8
```php class EntityManager { private $entities = []; private $entityManager; public function __construct($entityManager) { $this->entityManager = $entityManager; } /** * Add an entity to the entity manager. * * @param mixed $entity The entity to add. */ public ...
00280f5aa6cfc24cf612
```python from typing import List def find_correct_g(zcw_g: List[int]) -> int: a, b = zcw_g g = 1 for i in range(1, min(abs(a), abs(b)) + 1): if a % i == 0 and b % i == 0: g = i return g ``` The `find_correct_g` function takes the list `zcw_g` as input and initializes `g` to 1. It ...
00289447b0feafcfec54
```python class VEGGG(CnnModel): def __init__(self, model_name): super().__init__() self.MODEL_NAME = model_name def build_model(self): layers = BasicLayers(relu_version='parametric') input_tensor = Input(shape=self.INPUT_SHAPE) x = input_tensor # Add convoluti...
00293cb2ce6414118707
```python def mock_pv_info(system_id): # Mock information for PV system mock_info = { "system_id": system_id, "location": "Mock Location", "capacity": 100, # in kW "current_output": 50 # in kW } return mock_info def test_pv_tracking(system_id, time_period): # Simul...
002aec6fcff302f279f4
```csharp private void ValidatePhoneNumber() { string phoneNumber = phoneNumberTextBox.Text; if (string.IsNullOrEmpty(phoneNumber)) { phoneNumberErrorLabel.Text = "Phone number is required"; } else if (phoneNumber.Length != 10 || !phoneNumber.All(char.IsDigit)) { phoneNumberError...
002ce1054a43e126f822
```csharp using System; public class GraphQLServerException : Exception { public string Query { get; } public string Field { get; } public string ErrorMessage { get; } public GraphQLServerException(string query, string field, string errorMessage) { Query = query; Field = field; ...
002d1663fe34b203c8ca
```python # quiz_game.py import time def main(): questions = [ ("What is the capital of France?", "Paris"), ("What is the largest planet in our solar system?", "Jupiter"), # Add more questions and answers as needed ] for question, answer in questions: user_answer = input(f"...
002d8341246dc482fee9
```python def get_groups(board): copy = [row.copy() for row in board] groups = [] x_max, y_max = len(copy), len(copy[0]) for x in range(x_max): for y in range(y_max): group = get_group(copy, x, y) if group: groups.append(group) return groups def get_...
002e2abc6e9c3facaa9d
```python import os from argparse import ArgumentParser def process_snps_files(snps_filename, genome_filename): # Your implementation to process .snps_files to VCF format goes here pass if __name__ == "__main__": parser = ArgumentParser("Process one or more .snps_files files from dnadiff to VCF format.") ...
002e6dfe475755fa3415
```python def concatenate_files(fasta_file, tree_file, output_file): try: with open(fasta_file, 'r') as fasta, open(tree_file, 'r') as tree, open(output_file, 'w') as output: fasta_content = fasta.read() tree_content = tree.read() output.write(fasta_content + tree_content...
002fd2f6b474d32d12d2
```python import re from collections import Counter # Read the stop words from the file with open('stopwords.txt', 'r') as stop_words_file: stop_words = set(word.strip() for word in stop_words_file) # Read the text file with open('input.txt', 'r') as text_file: text = text_file.read() # Tokenize the words an...
003055f307d6f9a82edb
```python import colorsys def generate_state_colors(states): state_colors = {} for state, info in states.items(): phase = info['phase'] rgb = colorsys.hsv_to_rgb(phase, 1, 1) # Convert the RGB values from floats in the range [0, 1] to integers in the range [0, 255] rgb_int = tup...
00317051e127c5a56c8e
```javascript function extractTooltipMessage(codeSnippet) { // Regular expression to match the tooltip assignment pattern const tooltipRegex = /tooltip=\{StringResources\.([a-zA-Z0-9.]+)\}/; // Extract the tooltip message using the regular expression const match = codeSnippet.match(tooltipRegex); if (match ...
00324249c1aa18f555be
```python class Node: def __init__(self, node_type, content, refuri=None, children=None): self.node_type = node_type self.content = content self.refuri = refuri self.children = children if children is not None else [] def generate_toc(root_node): toc = [] def process_node(n...
00352a3f7fca33660cf3
```python import pandas as pd def generate_summary(df): summary = pd.DataFrame() for subject in df.columns[2:]: stats = { 'Mean': df[subject].mean(), 'Median': df[subject].median(), 'Std Dev': df[subject].std(), 'Min': df[subject].min(), 'Max'...
00370f986364f0607509
```bash #!/bin/bash # Check if Docker is installed if ! command -v docker &>/dev/null; then echo "Docker is required but not installed, aborting..." >&2 exit 1 fi # Build the Docker image with user-specific build arguments docker build . \ --build-arg USER_NAME="$USER" \ --build-arg USER_ID="$(id -u $...
003877685fbec5aafe7f
```python import tkinter as tk # Create a window win = tk.Tk() win.title("GUI Window") win.geometry("400x300") # Create a label label = tk.Label(win, text="Hello, World!") label.pack() # Display the window win.mainloop() ```
0039f27fd3bd58c01082
```python def get_data_by_name(username, fields=('*',), case_sensitive=False): """Retrieves the data of a user with the given name.""" if not case_sensitive: query = (f'SELECT {",".join(fields)} FROM users WHERE ' 'LOWER(username) = ? LIMIT 1') query_args = [username.lower()] ...
0039f5eec48aa05d031f
```java protected void save(PositionRequest context, PositionProxy entity) { if (isNew()) { entity.setPlan(plan); context.persist().using(entity); } } ``` The solution checks if the entity is new using the isNew() method. If it is new, the plan is set for the entity, and it is persisted using t...
003a56d724204067c538
```php function generateAlert($type, $message) { if ($type == 0) { return '<div class="alert alert-danger">' . $message . '</div>'; } else { return '<div class="alert alert-success">' . $message . '</div>'; } } ``` The `generateAlert` function checks the input message type. If the type is 0...
003b5f48d23cdac50b1a
```cpp #include <optional> // Define the RxEqualizerSettings type struct RxEqualizerSettings { // Define the properties of RxEqualizerSettings // ... }; // Define the cfg namespace and the TransceiverOverrides type namespace cfg { struct TransceiverOverrides { // Define the properties and methods of Transce...
003b76d32f77733f3d89
```java @Override public int hashCode() { int result = super.hashCode(); // Start with the default hash code result = 31 * result + (expression != null ? expression.hashCode() : 0); // Apply the specified rules return result; // Return the calculated hash code } ``` The `hashCode` method first initializes ...
003bd12111b5313af9d3
```python from typing import List class Message: def __init__(self, content: str): self.content = content def normalize(self) -> str: # Implement the normalization logic for the message content pass class MessageList: def __init__(self): self._messages = [] self._u...
003cafc43913e8016057
```python def extract_copyright_info(file_path: str) -> str: try: with open(file_path, 'r') as file: first_line = file.readline().strip() if first_line.startswith("# Copyright"): copyright_info = first_line.split(',')[0].lstrip('#').strip() return f"Co...
003d5b4bb0808707d27c
```python import re def extractCopyrightYear(copyrightText: str) -> str: pattern = r'Copyright \(c\) (\d{4}(?:-\d{4})?)' match = re.search(pattern, copyrightText) if match: return match.group(1) else: return "Year not found" ``` The `extractCopyrightYear` function uses the `re` module ...
003dbde1bd9ae112f9a2
```python class UserAccount: def __init__(self, username, email, created_at): self.username = username self.email = email self.created_at = created_at # Sample database containing user accounts user_accounts = { "title1": UserAccount("user1", "user1@example.com", "2022-01-01"), "tit...
003f17ac3e84e2a84a9a
```python def get_decimal_sum(decimal_digit_words): decimal_words = {'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'} american_number_system = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9} decimal_number_sum = 0...
003ff72dbd4096a0fffe
```python from docutils import nodes from docutils.parsers.rst import Directive from docutils.parsers.rst import directives class helloworld(nodes.Admonition, nodes.Element): pass def visit_helloworld_node(self, node): self.visit_admonition(node) class HelloWorldDirective(Directive): has_content = Tru...
004093b71c676890dfa6
```python class Workspace: def create_complex(self, substructures): atoms = [] bonds = [] for substructure in substructures: atoms.extend(substructure.get_atoms()) bonds.extend(substructure.get_bonds()) complex_molecule = Complex(atoms, bonds) return...
0041b3f64987beac25f8
```csharp using System; using System.Collections.Generic; using System.IO; using System.Xml; using Commons.Xml.Nvdl; public List<string> ProcessValidatedXML(string xmlFilePath, string nvdlSchemaPath, List<string> informationToExtract) { List<string> extractedInformation = new List<string>(); try { ...
004209e3e8fdeb83669f
```java import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class Logger { public static void logInfo(String tag, String message) { log("INFO", tag, message); } public static void logWarning(String tag, String message) { log("WARNING", tag, message); ...
00420c75793287e1432c
```csharp public override void PrintMessage() { Console.WriteLine($"Message: {_text}"); } ``` In the `PrintMessage` method, the provided solution uses `Console.WriteLine` to print the message in the required format. The `_text` field, inherited from the base class `Message`, is accessed to retrieve the message tex...
004260791c0529ba9c1a
```python import os def process_and_execute_batch_file(filename): with open(filename, "rt") as f: batch_content = f.read() modified_content = batch_content.replace("search.cpp", "search_tmp.cpp") with open(filename, "wt") as f: f.write(modified_content) os.system(filename...
004267208b6a1a9a7e5b
```csharp public Color32 GetCellColor(int selectedIndex, int dataIndex) { return selectedIndex == dataIndex ? new Color32(0, 255, 255, 100) : new Color32(255, 255, 255, 77); } ``` The `GetCellColor` function takes the `selectedIndex` and `dataIndex` as input and returns the color for the cell's imag...
00445c86e17148bd4670
```rust // Define the Building struct pub struct Building { name: String, location: String, capacity: u32, } // Implement methods for the Building struct impl Building { // Constructor for the Building struct pub fn new(name: String, location: String, capacity: u32) -> Building { Building {...
0044e381a427c2bc6553
```python from os import path def parse_requirements_and_extensions(requirements_file: str, native_extensions: list) -> dict: parsed_data = {'requirements': [], 'extensions': native_extensions} with open(path.join(path.abspath(path.dirname(__file__)), requirements_file), encoding='utf-8') as f: all_re...
0046075a71269e3b45c4
```python import unittest # Implement the get_itemclass function def get_itemclass(text): class TupleTrans: def __init__(self, text): self.text = text def transform_to_tuple(self): return tuple(self.text) return TupleTrans # Implement the TupleTrans class class TupleT...
00465441dd4fef9460bc
```python import subprocess # Function to generate white noise with frequency band and apply audio effects def generate_white_noise_band(): subprocess.run(['play', '-n', '-c1', 'synth', 'whitenoise', 'band', '100', '20', 'compand', '.3,.8', '-1,-10', 'gain', '+20']) # Function to generate white noise with multipl...
0046f75bb26bde67a30d
```rust use log::warn; use std::io::Error as IoError; // Custom error type for socket address errors pub struct SocketAddressError { error: IoError, } impl SocketAddressError { // Constructor function to create a new instance of SocketAddressError pub fn new(error: IoError) -> Self { SocketAddress...
004991dd5b4c76438fbf
```swift import UIKit class LayoutConstraintManager { private weak var view: UIView? private weak var width: NSLayoutConstraint! private weak var height: NSLayoutConstraint! init(view: UIView) { self.view = view } func setInitialConstraints(width: CGFloat, height: CGFloat) { g...
0049fc7326f7ae884ce9
```python class BatchTask: def __init__(self, job_def_arn, job_name): self.job_def_arn = job_def_arn self.job_name = job_name def run(self): raise NotImplementedError("Subclasses must implement this method") class BatchTaskNoOutput(BatchTask): def __init__(self, job_def, job_name)...
004a0240b69d86122305
```swift import UIKit class CustomView: UIView { private let stackView = UIStackView() private let titleLabel = UILabel() private let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { ...
004aa71c5f56bcb4f636
The register method in the RegistrationController class should be implemented as follows: ```php public function register(RegisterRequest $request) { // Validate the incoming registration data $validatedData = $request->validated(); // Create a new user in the database $user = new User(); $user->n...
004b2a5a261ae27ffa92
```javascript function processDateAndCases() { let mes = (new Date().getMonth() + 1 < 10) ? '0' + (new Date().getMonth() + 1) : (new Date().getMonth() + 1); let date_range = { start: new Date().getFullYear() + '-01-01', end: new Date().getFullYear() + '-' + mes + '-' + new Date().getDate() }; if (localS...
004ed5653a79ea3e356d
```python import re class Domain: def __init__(self, domain): self.domain = domain def validate_domain(self): pattern = r'^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$' if re.match(pattern, self.domain): return True ...
004f81c30e292f2f6461
```python class Person: def __init__(self, name, age): self.name = name self.age = age def get_details(self): return f"Name: {self.name}, Age: {self.age}" class Student(Person): def __init__(self, name, age, student_id, grade): super().__init__(name, age) self.stud...
004fdb36025ccfc74ea5
```python def solution(xk, equation): x, k = map(int, xk.split()) x_value = x ** k result = eval(equation.replace('x', str(x_value))) return result ``` The `solution` function first extracts the value of x and k from the input string `xk` using `split()` and `map(int, ...)`. It then calculates the valu...
004fe8073bd8701ea2d7
```bash #!/bin/bash set -e # Check for the presence of the error message related to microcode if dmesg | grep -q "Firmware Bug.*TSC_DEADLINE disabled due to Errata"; then echo "Error related to microcode detected. Updating microcode..." # Install the "intel-ucode" package without requiring user confirmati...
005051ba75d7158f45a7
```python import requests def retrieve_synset_info(synset): name = synset.name().split(".")[0] offset = synset.offset() wnid = f"n{offset:08d}" print(f"{wnid}.{category}.{name}") geturls = "https://example.com/synset_info?wnid={wnid}" # Replace with the actual URL template r = requests.get(get...
0052701f935e49755fef
```html <h1>Tabel Acc</h1> <br> <br> @foreach($acc as $accs) <div class="card"> <h3><a href="/acc/{{$accs->id_acc}}">{{$accs->id_acc}}</a></h3> <p>Details:</p> <ul> <li>ID: {{$accs->id_acc}}</li> <!-- Add additional details based on the unspecified attributes of the accounting record --> <!...
00541b3a72b94060dc71
```python import math # Prompt the user to input a number num1 = float(input('Enter a number: ')) # Calculate the square root of the input number square_root = math.sqrt(num1) # Round the square root to the nearest integer rounded_square_root = round(square_root) # Print the original number and the rounded square r...
0055039ec3e52830bdcd
```python import os from time import time job_index = 1 chain_ID = 'B1422' out_path = os.getenv('HOME') + '/data/sims/' # Further processing of simulation output files based on the provided parameters # ... # Your additional code for processing simulation output files goes here # ... ``` In the solution, the script s...
00554db8117a46fb3eac
```c // Assuming HKEY_LOOKUP is a global array char HKEY_LOOKUP[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}; char rootToChar(int root) { return HKEY_LOOKUP[root & 0x00000007]; } ``` In the solution, the `rootToChar` function takes an integer `root` as input and returns the corresponding value from `HKEY_LOOKUP` ...
005597d9719f7d7dc57f
```python def extractUniqueExtensions(paths): extensions = set() for path in paths: file_name = path.split("/")[-1] extension = file_name.split(".")[-1].replace("'", "").replace(")", "") extensions.add(extension) return list(extensions) ```
0056fb21e4358a1c3ab7
```python import sys import pymongo import os def import_data_to_mongodb(database, collection, file_path): try: client = pymongo.MongoClient('localhost', 27017) db = client[database] col = db[collection] # Drop the collection if it already exists if collection in db...
0057e6eefab4c7b5d675
```rust mod session; use clap::{App, Arg, ArgMatches}; use error::CustomError; use session::{Session, SessionConfig}; fn parse_config<'a>(matches: &'a ArgMatches) -> Result<SessionConfig<'a>, CustomError> { let device = matches.value_of("device_name") .ok_or("Device name is empty")?; let speed: u32 = ...
0058a0ec89859b369cbc
```rust // Solution for the dependency resolution algorithm let mut deps_to_fetch: Vec<PackageId> = /* initialize with package IDs */; let mut fetched_packages: HashSet<PackageId> = HashSet::new(); while let Some(id) = deps_to_fetch.pop() { if !fetched_packages.insert(id) { // Handle the case when the pack...
005a0877bd2314ced19a
```python def count_workflow_actions(workflow_data): unique_action_types = set(workflow_data.keys()) return len(unique_action_types) ```
005b49a16f187b45316a
```python from collections import deque from typing import List def max_sliding_window(nums: List[int], k: int) -> List[int]: result = [] window = deque() for i, num in enumerate(nums): while window and num >= nums[window[-1]]: window.pop() window.append(i) if ...
00633519f0afdc403d20
```java public class Contact { private String name; private String email; private String observacao; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void ...
0064be9ce96aebf22a47
```python def filter_shopping_carts(shopping_carts: list, min_price: float) -> list: filtered_carts = [] for customer, products in shopping_carts: filtered_products = [(product, price) for product, price in products if price >= min_price] if filtered_products: filtered_carts.append((...
0065dc24c97bd9b101ef
```swift func longestSubstringWithTwoDistinct(_ s: String) -> String { var charMap = [Character: Int]() var start = 0 var end = 0 var maxLength = 0 var maxStart = 0 for (i, char) in s.enumerated() { charMap[char] = i if charMap.count > 2 { let minIndex = charMap....
End of preview. Expand in Data Studio

Magicoder OSS-Instruct — Training, unified schema

A seeded sample of ise-uiuc/Magicoder-OSS-Instruct-75K, made into retrieval training pairs and reshaped into the strict schema shared by every dataset in this collection. One of the 15 domain sources (code, medical, science, finance, legal) added to the collection's general sources.

Source ise-uiuc/Magicoder-OSS-Instruct-75K @ 5f839b1f368a
Task coding problem → solution
Domain · languages code · eng
Queries / documents / qrels 59,997 / 59,999 / 59,997
Qrels per query min 1 · mean 1.0 · max 1
Score values 2 ×59,997 (2: the first positive, 1: any other)
Layout queries · corpus · qrels · hard-negatives · teacher-scores, split train
Splits corpus: train · hard-negatives: train · qrels: train · queries: train · teacher-scores: train
Hard negatives sources: dense · 5,939,734 rows
Teacher scores none yet (0 rows): jinaai/jina-reranker-v3.5 scores come next
Ids sha1(text)[:20]; identical texts collapse to one document / query
License mit

Schema

config columns rules
queries id: string, text: string ids unique and non-empty; every query has ≥ 1 qrel
corpus id: string, title: string, text: string title is always present ("" when the source has none)
qrels query-id: string, corpus-id: string, score: int32 referential integrity to both tables; no duplicate pairs; no floats
hard-negatives query-id: string, corpus-id: string, rank: int32, source: string one row per negative; (query-id, corpus-id, source) unique; never a labelled positive of the same query
teacher-scores query-id: string, corpus-id: string, teacher: string, score: float32 one row per scored pair (positives included); a row means scored — never a placeholder

Files are Parquet, sorted by id, zstd-compressed, sharded at 500 MB. Every rule above is checked before publishing; provenance.json records the source revision, what changed, and the output file hashes.

What changed from the source

  • sampled: a seeded random sample (seed 1) of up to 60,000 pairs
  • reshaped: the coding problem (problem) is the query, its solution (solution) the document
  • decontaminated (exact): a pair was dropped when its normalised query equals any evaluation query, or a positive equals a document of a test or dev corpus; a repeated query keeps its first pair
  • decontaminated (near-duplicates): 1 passages that nearly copy an evaluation document some evaluation query judges relevant, and 2 queries that nearly copy an evaluation query (word 13-grams for passages, 8-grams for queries; at least half shared with one text of the 23 test sets (BEIR, RTEB, LitSearch) or the 6 dev sets) were removed, and with them 3 queries in total; near copies of evaluation-corpus documents that no evaluation query judges relevant were kept
  • text: leading and trailing whitespace stripped; otherwise as converted above
  • ids re-keyed to sha1(text)[:20]: 0 documents and 0 queries collapsed into identical texts
  • added a title column filled with "" (the source has none)

Hard negatives and teacher scores

Filled by the collection's annotation pipeline (annotation=jina35). Interim: the candidates are final, the teacher scores are still to come.

  • Candidates: dense retrieval with jinaai/jina-embeddings-v5-text-small over this corpus to depth 1,000; 100 candidates per query drawn from the rank windows 1–30 (30), 31–100 (30), 101–300 (20), 301–1000 (20), the query's labelled positives excluded. rank is the dense rank; source is dense for a mined row and dataset for a negative the source labels itself.
  • Teacher scores: none yet. teacher-scores holds 0 rows until the jinaai/jina-reranker-v3.5 scores (listwise, as in the other repositories) are filled in; datasets cannot return a 0-example split, so read that file with pyarrow / pandas meanwhile. The candidates stay.
configs queries hard negatives teacher scores
hard-negatives · teacher-scores 59,997 (all) 5,939,734 (5,939,734 dense) 0

Load it

from datasets import load_dataset
queries   = load_dataset("Hyukkyu/train-magicoder", "queries", split="train")
corpus    = load_dataset("Hyukkyu/train-magicoder", "corpus", split="train")
qrels     = load_dataset("Hyukkyu/train-magicoder", "qrels", split="train")
negatives = load_dataset("Hyukkyu/train-magicoder", "hard-negatives", split="train")
scores    = load_dataset("Hyukkyu/train-magicoder", "teacher-scores", split="train")

License and attribution

The data is redistributed under the source's terms — mit. All credit belongs to the original authors; see the source repository (https://huggingface.co/datasets/ise-uiuc/Magicoder-OSS-Instruct-75K). This repository is an independent repackaging.

Downloads last month
51

Collection including Hyukkyu/train-magicoder