← 목록

Synth · Magicoder-OSS일부

총 5,000개 · 페이지 1/167
🔀 랜덤 처음으로
불러오는 중…

[lang] | cpp [raw_index] | 84792 [index] | 2771 [seed] | BOOST_REQUIRE(error == 0); SMO_close(&p_handle); } BOOST_AUTO_TEST_SUITE_END() struct Fixture{ Fixture() { [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a simple stack data structure using C++. The stack should support the following operations: push, pop, and top. Additionally, you need to implement a function that returns the minimum element in the stack at any given time. You are not allowed to use any built-in sta [solution] | ```cpp #include <iostream> #include <cassert> struct Node { int val; int min; Node* next; Node(int x, int m, Node* n) : val(x), min(m), next(n) {} }; class MinStack { private: Node* topNode; public: MinStack() { topNode = nullptr; } void push(int x) {

[lang] | python [raw_index] | 68333 [index] | 23304 [seed] | from caffe.proto import caffe_pb2 from google.protobuf import text_format # Global variables bn_maps = {} def make_parser(): parser = argparse.ArgumentParser() parser.add_argument('--model', type=str, required=True, [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a Python script that processes a configuration file for a deep learning model and extracts specific information from it. The configuration file is in the Protobuf format and contains information about the layers and their parameters. Your goal is to extract the names [solution] | ```python import argparse from caffe.proto import caffe_pb2 from google.protobuf import text_format # Global variables bn_maps = {} def make_parser(): parser = argparse.ArgumentParser() parser.add_argument('--config', type=str, required=True, help='Path to the inp

[lang] | cpp [raw_index] | 38790 [index] | 4994 [seed] | #include "adc.h" // First define the Adc. [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a simple ADC (Analog-to-Digital Converter) library for a microcontroller. The ADC library should provide functions for initializing the ADC, reading analog values from specific channels, and performing basic operations on the acquired data. The ADC library should su [solution] | ```c // adc.c #include "adc.h" // Define the ADC structure to hold configuration settings typedef struct { // Add necessary fields for configuration settings // e.g., reference voltage, clock source, resolution } AdcConfig; // Initialize the ADC with the given configuration settings void

[lang] | python [raw_index] | 13010 [index] | 39439 [seed] | catalogDict[label]={} if 'saveDS9Regions' in f['params'] and f['params']['saveDS9Regions'] == True: DS9RegionsPath=config.filteredMapsDir+os.path.sep+tileName+os.path.sep+"%s_filteredMap.reg" % (label) [openai_fingerprint] | fp_eeff13170a [problem] | You are working on a data processing pipeline for astronomical observations. The pipeline processes images of the sky captured by a telescope and extracts various features from the images. Your task is to write a function that generates DS9 region files for the extracted features based on the provid [solution] | ```python import os def generate_DS9_regions(catalogDict: dict, tileName: str, config: dict) -> None: if 'saveDS9Regions' in config and config['saveDS9Regions'] == True: regions_dir = config.get('filteredMapsDir', '') if regions_dir: for label, feature_info in catalo

[lang] | php [raw_index] | 74854 [index] | 3459 [seed] | <p class="float-right"><?php echo $pesan['no_telepon']?></p> </div> <div class="col-lg-2"> <p class="float-right"><?php echo $pesan['email']?></p> </div> </div> [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a PHP function that takes an array of messages and generates an HTML table to display the messages' details. Each message is represented as an associative array with the following keys: 'name', 'no_telepon', and 'email'. The function should generate an HTML table with th [solution] | ```php function generateMessageTable($messages) { $html = '<table>'; $html .= '<tr><th>Name</th><th>Phone Number</th><th>Email</th></tr>'; foreach ($messages as $message) { $html .= '<tr>'; $html .= '<td>' . $message['name'] . '</td>'; $html .= '<td>' . $mess

[lang] | python [raw_index] | 78619 [index] | 22692 [seed] | flux_median_window = np.median(flux[:,window], axis=1) flux_norm = np.zeros(flux.shape) cont_norm = np.zeros(cont.shape) for i in range(len(flux)): flux_norm[i,:] = flux[i,:]/flux_median_window[i] [openai_fingerprint] | fp_eeff13170a [problem] | You are given a Python code snippet that processes astronomical data using the NumPy library. The code snippet calculates the median of a specific window of data and then normalizes the flux data based on this median. Your task is to implement a function that achieves the same result as the given co [solution] | ```python import numpy as np def normalize_flux(flux, cont, window): flux_median_window = np.median(flux[:, :window], axis=1) # Calculate median within the specified window flux_norm = np.zeros(flux.shape) # Initialize an array for normalized flux data for i in range(len(flux)):

[lang] | python [raw_index] | 12046 [index] | 28857 [seed] | now = date.today() print('The date today is', now, now.strftime("%A")) [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python program that simulates a simple library management system. The program should allow users to add new books to the library, display the list of available books, and search for a book by its title. The program should also keep track of the date when a book is adde [solution] | ```python from datetime import date class Library: def __init__(self): self.books = [] self.current_date = date.today() def add_book(self, title): self.books.append((title, self.current_date)) def display_books(self): print("Available books:") f

[lang] | php [raw_index] | 133324 [index] | 3325 [seed] | // Préparation de la requête et envoi des data à la BDD $create_new_collect = $bdd->prepare( 'INSERT INTO collects(collect_site, collect_source, object_type, object_sub_type, object_weight, collect_date) VALUES(:collect_site, :collect_source, :object_type, :object_sub_type, :object_weight, n [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a PHP function that interacts with a MySQL database to insert a new record into the "collects" table. The function should take input parameters for the collect site, collect source, object type, object sub type, and object weight. The collect date should be automatically [solution] | ```php function createNewCollect($collectSite, $collectSource, $objectType, $objectSubType, $objectWeight, $bdd) { // Prepare the SQL statement with placeholders $createNewCollect = $bdd->prepare('INSERT INTO collects(collect_site, collect_source, object_type, object_sub_type, object_weight,

[lang] | swift [raw_index] | 68383 [index] | 4085 [seed] | #endif } } [openai_fingerprint] | fp_eeff13170a [problem] | You are given a C++ function that is intended to reverse a string in place. However, the function contains some errors and is not functioning as expected. Your task is to identify the issues in the given code and correct them to make the function work as intended. ```cpp #include <iostream> #includ [solution] | The given `reverseString` function has a logical error in the swapping process. The correct approach to reverse the string in place is to iterate only up to half the length of the string and swap the characters at the corresponding positions from the beginning and end of the string. Here's the corr

[lang] | typescript [raw_index] | 106192 [index] | 4791 [seed] | //# sourceMappingURL=TSpanElement.d.ts.map [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a program that extracts the filename from a given sourceMappingURL comment in a JavaScript file. The sourceMappingURL comment is a special comment used to specify the location of the source map file associated with the JavaScript file. The filename is the part of the sou [solution] | ```javascript function extractSourceMapFilename(sourceMappingURL) { const match = sourceMappingURL.match(/=(.*).map/); if (match) { return match[1]; } else { return "Invalid sourceMappingURL format"; } } // Test the function const sourceMappingURL = "//# sourceMappingURL=TSpanElemen

[lang] | python [raw_index] | 123926 [index] | 3610 [seed] | from django.contrib import admin admin.site.register(Cart) [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a custom Django admin action to process and update multiple instances of a model in the Django admin interface. Your task is to implement a custom admin action that calculates the total price of all selected Cart instances and updates a new field called "total_price" in [solution] | ```python from django.contrib import admin from .models import Cart def calculate_total_price(modeladmin, request, queryset): for cart in queryset: total_price = cart.quantity * cart.price cart.total_price = total_price cart.save() calculate_total_price.short_descriptio

[lang] | csharp [raw_index] | 78491 [index] | 2296 [seed] | namespace HandGestureRecord.GestureInput { /// <summary> /// 指の識別子. /// </summary> public enum FingerId : int { [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a gesture recognition system for a hand gesture input application. The system needs to identify different fingers based on their unique identifiers. The provided code snippet includes the definition of an enum `FingerId` within the `HandGestureRecord.GestureInput` na [solution] | ```csharp using System; namespace HandGestureRecord.GestureInput { public class GestureRecognizer { public string IdentifyFinger(FingerId fingerId) { switch (fingerId) { case FingerId.Thumb: return "Thumb";

[lang] | python [raw_index] | 76097 [index] | 24744 [seed] | class UnitedKingdomStores(Stores): """ Base class for united kingdom marketplaces. """ [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a Python class that represents a marketplace in the United Kingdom. The class should inherit from a base class called `Stores`. Your task is to complete the implementation of the `UnitedKingdomStores` class by adding specific attributes and methods that are relevant [solution] | ```python class UnitedKingdomStores(Stores): """ Base class for united kingdom marketplaces. """ currency = "GBP" def calculate_vat(self, price): return price * 0.2 # VAT rate in the UK is 20% def apply_discount(self, price, discount_percentage): return pr

[lang] | python [raw_index] | 109988 [index] | 12962 [seed] | index2label_map[i] = label print("index2label_map:", index2label_map) real_label_dict = get_real_label(real_file) [openai_fingerprint] | fp_eeff13170a [problem] | You are working on a machine learning project and need to implement a function to map index values to corresponding labels. The index-to-label mapping is stored in a dictionary called `index2label_map`. After creating the mapping, the program prints the contents of the `index2label_map` dictionary. [solution] | ```python def generate_intersection_mapping(index2label_map, real_label_dict): intersection_mapping = {key: index2label_map[key] for key in index2label_map if key in real_label_dict and real_label_dict[key] == index2label_map[key]} return intersection_mapping # Test the function with the gi

[lang] | swift [raw_index] | 28618 [index] | 3478 [seed] | See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import GMLImageUtils import XCTest @testable import TFLImageClassifier [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Swift function that processes an image using the GMLImageUtils library and then tests the functionality using XCTest. The GMLImageUtils library provides image processing capabilities, and the TFLImageClassifier module contains the image classification functionality. Yo [solution] | ```swift import XCTest import GMLImageUtils import TFLImageClassifier // Function to process and classify the image func processAndClassifyImage(inputImage: UIImage) -> String? { // Process the input image using GMLImageUtils let processedImage = GMLImageUtils.processImage(inputImage)

[lang] | java [raw_index] | 9507 [index] | 912 [seed] | public interface BackdropActions { void showBackview(); void closeBackview(); } [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a class that utilizes the `BackdropActions` interface to manage the display of a backview in a user interface. The `BackdropActions` interface contains two methods: `showBackview()` and `closeBackview()`, which are responsible for showing and closing the backview, re [solution] | ```java public class BackdropManager implements BackdropActions { private boolean isBackviewDisplayed; public BackdropManager() { this.isBackviewDisplayed = false; } @Override public void showBackview() { if (!isBackviewDisplayed) { // Code to displa

[lang] | swift [raw_index] | 10387 [index] | 3864 [seed] | self.countStyle = countStyle } public func stringValue() -> String { switch bytes { case 0..<countStyle: return "\(bytes) " + "bytes".locale(AppSd.translateUnits) case countStyle..<(countStyle * countStyle): [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a file size formatting utility in Swift. The utility should take a file size in bytes and convert it to a human-readable string representation. The string representation should include the appropriate unit (bytes, kilobytes, megabytes, etc.) based on the magnitude of [solution] | ```swift class FileSizeFormatter { var countStyle: Int init(countStyle: Int) { self.countStyle = countStyle } func stringValue(bytes: Int) -> String { let units = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] var fileSize = Double(bytes)

[lang] | php [raw_index] | 44823 [index] | 4706 [seed] | @for ($i = 1; $i <= $secteurs->lastPage(); $i++) <li class="{{ ($secteurs->currentPage() == $i) ? ' active' : '' }} page-item"> <a href="{{ $secteurs->url($i) }}" class="page-link">{{ $i }}</a> [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a pagination feature for a web application. The code snippet provided is a part of a web page that displays a list of sectors and their corresponding page numbers. The code uses a loop to generate a list of page numbers and a placeholder for skipped pages represented [solution] | ```python from typing import List, Union def generate_pagination(current_page: int, total_pages: int, max_visible_pages: int) -> List[Union[int, str]]: if total_pages <= max_visible_pages: return list(range(1, total_pages + 1)) half_visible = max_visible_pages // 2 if curre

[lang] | rust [raw_index] | 35200 [index] | 4227 [seed] | #[doc = "Checks if the value of the field is `YES`"] [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a custom assertion macro for a testing framework. The macro should check if a given field in a struct has a specific value. The macro should take in the field name, the expected value, and the actual struct instance. If the field value matches the expected value, the [solution] | ```rust macro_rules! assert_field_value { ($field:ident, $expected:expr, $actual:expr) => { assert_eq!($expected, $actual.$field, "Field '{}' does not have the expected value", stringify!($field)); }; } struct TestStruct { value: &'static str, } fn main() { let test_instanc

[lang] | csharp [raw_index] | 85931 [index] | 2156 [seed] | private bool MessageArrived(CurrentMessageInformation arg) { if (NestedTransactionScope == null) { NestedTransactionScope = new TransactionScope(TransactionScopeOption.Suppress); } return fal [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a message processing system that involves handling message arrival and transaction management. The provided code snippet is a part of the message processing system and contains a method `MessageArrived` which is called when a new message arrives. The method is respon [solution] | ```csharp private bool MessageArrived(CurrentMessageInformation arg) { using (var transactionScope = new TransactionScope(TransactionScopeOption.Required)) { try { // Process the arrived message based on the information in 'arg' // Implement the necess

[lang] | python [raw_index] | 75282 [index] | 5936 [seed] | def contact_form(request: HttpRequest, user_id: int): try: user = User.objects.get(id=user_id) except User.DoesNotExist: return db_error(_('Requested user does not exist.')) assert isinstance(user, User) if request.method == 'POST': form = ContactForm(request [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python function that processes a contact form submission and sends an email to a user. The function `contact_form` takes two parameters: `request`, which is an instance of `HttpRequest`, and `user_id`, an integer representing the ID of the user to whom the email will b [solution] | ```python from django.core.mail import send_mail from django.http import HttpRequest from django.contrib.auth.models import User from .forms import ContactForm # Assuming the ContactForm is defined in a separate file CONTACT_FOOTER = "Thank you for contacting us. We will get back to you shortly.\n

[lang] | python [raw_index] | 147177 [index] | 22862 [seed] | print('error: command {cmd} does not exist' .format(cmd=self.args[0])) return 1 except KeyboardInterrupt: print('\nOk, bye') return 1 [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a command-line tool that processes user input and performs various operations. Your program should handle different types of errors and interruptions gracefully. You have been provided with a partial code snippet from the error handling section of the program. Your task [solution] | ```python class CommandLineTool: def __init__(self, args): self.args = args def process_command(self): try: # Process the user input and perform the corresponding operation # ... return 0 # Return 0 to indicate successful execution

[lang] | python [raw_index] | 106442 [index] | 32456 [seed] | try: post_logout_url = reverse('helusers:auth_logout_complete') except NoReverseMatch: post_logout_url = None if post_logout_url: params['post_logout_redirect_uri'] = request.build_absolute_uri(post_logout_url) try: # A [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function that manipulates URLs based on certain conditions. The function should take in a URL and a dictionary of parameters, and then modify the URL based on the following rules: 1. If the URL can be reversed using the 'helusers:auth_logout_complete' pattern, the [solution] | ```python import urllib.parse def modify_url(url, params): try: post_logout_url = reverse('helusers:auth_logout_complete') except NoReverseMatch: post_logout_url = None if post_logout_url: params['post_logout_redirect_uri'] = request.build_absolute_uri(post_logou

[lang] | python [raw_index] | 95304 [index] | 26802 [seed] | ''' Function to find alternate spellings for names. Recursively finds alts of alts. ''' for group in ALT_GROUPS: for unit in group: sub = '(' + '|'.join([ u for u in group if u != unit ]) + ')' alt = re.sub(sub, unit, name) if (alt != nam [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function to find alternate spellings for names. The function should recursively find alternate spellings of alternate spellings. The function will take a name as input and return a list of all the alternate spellings found. The function will iterate through each g [solution] | ```python import re def find_alternate_spellings(name, ALT_GROUPS, lower_names, checked=None, alts=None): if checked is None: checked = [] if alts is None: alts = [] for group in ALT_GROUPS: for unit in group: sub = '(' + '|'.join([u for u in group i

[lang] | python [raw_index] | 13883 [index] | 33645 [seed] | prepare_command = chaosblade_prepare_script(chaosblade_prepare, prepare_args) prepare_msg, stderr = executor_command_inside_namespaced_pod(api_instance, namespace, pod, prepare_command) print(prepare_msg, stderr) agent_uid = jsonpath.jsonpath(json.loads(prepare_msg), 'result') re [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python function that checks for the existence of the Chaosblade tool inside a Kubernetes pod and retrieves the agent UID if the tool is found. The Chaosblade tool is used for chaos engineering and testing in Kubernetes environments. You are provided with a code snippet [solution] | ```python import json import jsonpath def chaosblade_prepare_script(script, args): # Implementation of the chaosblade_prepare_script function is not provided def executor_command_inside_namespaced_pod(api_instance, namespace, pod, command): # Implementation of the executor_command_inside_n

[lang] | java [raw_index] | 148082 [index] | 1539 [seed] | @Test public void getAllFilesTest() { String webSiteSrcDir = this.workingDir.resolve("website/timeless/").toString(); Map<String, Path> allFiles = IOUtils.getAllFiles(webSiteSrcDir); allFiles.forEach((rel, abs) -> LOG.info("{} , {}", rel, abs.toString())); [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a method to retrieve all files within a specified directory and its subdirectories. The method should return a map where the keys are the relative paths of the files within the directory, and the values are the absolute paths of the corresponding files. You are prov [solution] | ```java import java.io.IOException; import java.nio.file.*; import java.util.HashMap; import java.util.Map; public class IOUtils { public static Map<String, Path> getAllFiles(String directoryPath) { Map<String, Path> allFiles = new HashMap<>(); try { Files.walk(Paths

[lang] | python [raw_index] | 48631 [index] | 15750 [seed] | from uio import Uio from argsort_axi import ArgSort_AXI if __name__ == '__main__': uio = Uio('uio_argsort') argsort_axi = ArgSort_AXI(uio.regs()) argsort_axi.print_info() argsort_axi.print_debug() [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a Python class to perform an in-place sorting algorithm on a list of integers. The algorithm should be a variation of the quicksort algorithm, but with a twist. Instead of choosing the last element as the pivot, the algorithm should choose the median of the first, mi [solution] | ```python class QuickSort: def __init__(self, data): self.data = data def sort(self): def partition(left, right): mid = (left + right) // 2 pivot = sorted([(self.data[left], left), (self.data[mid], mid), (self.data[right], right)])[1][1] s

[lang] | cpp [raw_index] | 60164 [index] | 4991 [seed] | if (m_pSuites[dwSuite].aiTests) delete [] m_pSuites[dwSuite].aiTests; } if (m_lpMachineName) delete [] m_lpMachineName; } DWORD CTSTestData::GetSuiteCount () const [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a class for managing test data in a testing framework. The provided code snippet is part of the implementation of the `CTSTestData` class. The class is responsible for managing test suites and their associated tests. The code snippet shows a part of the destructor f [solution] | ```cpp #include <iostream> class CTSTestData { private: struct TestSuite { int* aiTests; int testCount; }; TestSuite* m_pSuites; char* m_lpMachineName; int m_suiteCount; public: CTSTestData() : m_pSuites(nullptr), m_lpMachineName(nullptr), m_suiteCount(0) {

[lang] | python [raw_index] | 90852 [index] | 17978 [seed] | class ApikeysProjectsLocationsKeysPatchRequest(_messages.Message): r"""A ApikeysProjectsLocationsKeysPatchRequest object. Fields: name: Output only. The resource name of the key. The `name` has the form: `projects//locations/global/keys/`. For example: `projects/123456867718/ l [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a Python class that represents an API request for updating API keys. The class should have specific fields and properties as described in the code snippet below. Your task is to create a Python class `ApikeysProjectsLocationsKeysPatchRequest` with the following fiel [solution] | ```python class ApikeysProjectsLocationsKeysPatchRequest: """ A class representing an API request for updating API keys. """ def __init__(self, name, updateMask): """ Initializes the ApikeysProjectsLocationsKeysPatchRequest object with the given parameters. A

[lang] | python [raw_index] | 33296 [index] | 12428 [seed] | class Owner(BaseModelCardField): """The information about owners of a model. Attributes: name: The name of the model owner. contact: The contact information for the model owner or owners. These could be individual email addresses, a team mailing list expressly, or a monitore [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python class that represents a deck of playing cards. The class should have methods for shuffling the deck, dealing a specified number of cards, and returning the number of cards remaining in the deck. Additionally, the class should have attributes to store the cards i [solution] | ```python import random class Deck: def __init__(self): suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] self.cards = [{'suit': suit, 'rank': rank} for suit in suits for rank in ranks