← 목록

Synth · Magicoder-OSS일부

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

[lang] | python [raw_index] | 134135 [index] | 9527 [seed] | data.append(tuple(parameters)) [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a Python class that manages a collection of data points. The class should provide methods for adding new data points, calculating the average of a specific attribute across all data points, and finding the data point with the highest value for a given attribute. You [solution] | ```python class DataManager: def __init__(self): self.data = [] def add_data_point(self, parameters): self.data.append(parameters) def average(self, attribute_index): total = sum(data[attribute_index] for data in self.data) return total / len(self.data)

[lang] | php [raw_index] | 44283 [index] | 3826 [seed] | }).then(function (response) { return response.text(); [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a function that retrieves data from a remote server and processes it to extract specific information. The function will take a URL as input and should return a promise that resolves with the extracted information. The provided code snippet is a part of the asynchronous p [solution] | ```javascript function extractInformationFromServer(url) { return fetch(url) // Assuming fetch API is available .then(function (response) { if (!response.ok) { throw new Error('Network response was not ok'); } return response.text();

[lang] | python [raw_index] | 114946 [index] | 19335 [seed] | from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for, current_app, session ) from werkzeug.security import check_password_hash, generate_password_hash from .document import User bp = Blueprint('auth', __name__, url_prefix='/auth') @bp.route('/registe [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Flask web application that allows users to register and log in. The application should include functionality for user registration, password hashing, and authentication. Your task is to implement the registration and login functionality using Flask and Werkzeug. Your [solution] | ```python from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for, current_app ) from werkzeug.security import check_password_hash, generate_password_hash from .document import User bp = Blueprint('auth', __name__, url_prefix='/auth') @bp.route('/register

[lang] | csharp [raw_index] | 110650 [index] | 170 [seed] | } public static bool GetIsDragOver(DependencyObject element) { return (bool) element.GetValue(IsDragOverProperty); } } } [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a simple drag-and-drop functionality in a WPF (Windows Presentation Foundation) application. The provided code snippet is a part of a custom attached property implementation for handling drag-over events in WPF. Your task is to create a custom attached property call [solution] | ```csharp using System.Windows; public static class DragDropHelper { public static readonly DependencyProperty IsDragOverProperty = DependencyProperty.RegisterAttached("IsDragOver", typeof(bool), typeof(DragDropHelper)); public static void SetIsDragOver(DependencyObject element, bo

[lang] | csharp [raw_index] | 139086 [index] | 891 [seed] | this.btnCancelRD.Click += new System.EventHandler(this.btnCancelRD_Click); // // tbName [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a simple event handling system in C#. Your goal is to create a class that manages event subscriptions and triggers the corresponding event handlers. You need to implement a class called `EventDispatcher` with the following requirements: - It should have a method `A [solution] | ```csharp using System; using System.Collections.Generic; public class EventDispatcher { private Dictionary<string, List<Delegate>> eventListeners; public EventDispatcher() { eventListeners = new Dictionary<string, List<Delegate>>(); } public void AddListener(string ev

[lang] | python [raw_index] | 55510 [index] | 5939 [seed] | def build_train_set(trajectories): """ Args: trajectories: trajectories after processing by add_disc_sum_rew(), [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function to process trajectories from a reinforcement learning environment. The function `build_train_set` takes in a list of trajectories and returns a processed training set. Each trajectory is a list of tuples, where each tuple represents a step in the trajector [solution] | ```python from typing import List, Tuple, Any def build_train_set(trajectories: List[List[Tuple[Any, Any, float, Any]]]) -> Tuple[List[Any], List[Any], List[float], List[Any]: states = [] actions = [] discounted_rewards = [] next_states = [] for trajectory in trajectories:

[lang] | python [raw_index] | 5289 [index] | 23004 [seed] | result.append(retval) if max_num_results is not None and len(result) >= max_num_results: return result return result [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function that processes a list of values and returns a subset of the list based on certain conditions. The function should take in a list of values, a maximum number of results, and a condition for filtering the values. The function should return a subset of the in [solution] | ```python from typing import List, Callable, Optional def process_list(input_list: List[int], condition: Callable[[int], bool], max_num_results: Optional[int]) -> List[int]: result = [] for value in input_list: if condition(value): result.append(value) if max

[lang] | shell [raw_index] | 29850 [index] | 1533 [seed] | echo "Deploying documentation" else success "Not building master branch. Skipping deploy." exit 0 fi if [ -z "$GITHUB_TOKEN" ]; then error "Environment variable GITHUB_TOKEN does not exist. Stopping deploy." exit 1 fi npm run gh-pages [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a deployment script for a documentation website. The script should check if it is being run on the master branch of a Git repository and if the environment variable `GITHUB_TOKEN` is set. If both conditions are met, the script should execute the command `npm run gh-pages [solution] | ```bash #!/bin/bash # Check if the script is being run on the master branch if [ "$(git rev-parse --abbrev-ref HEAD)" != "master" ]; then echo "Not building master branch. Skipping deploy." exit 0 fi # Check if the GITHUB_TOKEN environment variable is set if [ -z "$GITHUB_TOKEN" ]; then echo

[lang] | python [raw_index] | 145880 [index] | 13306 [seed] | class EastLiteralWidthTestCase(unittest.TestCase): def test_get_east_asian_width_count_1(self): text = "你好,世界!" expect = 11 result = text_lib.get_east_asian_width_count(text) self.assertEqual(expect, result) def test_get_east_asian_width_count_ [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function to count the number of East Asian wide characters in a given text string. East Asian wide characters are those that occupy two columns in a fixed-width text display, such as Chinese, Japanese, and Korean characters. You are provided with a code snippet th [solution] | ```python def get_east_asian_width_count(text: str) -> int: count = 0 for char in text: if is_east_asian_wide(char): count += 1 return count def is_east_asian_wide(char: str) -> bool: # Check if the character is East Asian wide # Implement the logic to identi

[lang] | python [raw_index] | 44535 [index] | 35414 [seed] | register = template.Library() [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a custom template tag in a Django web application. The tag should take a list of strings as input and return a modified version of the list. The modification involves reversing the order of characters in each string and then sorting the list of strings in descending [solution] | ```python from django import template register = template.Library() @register.filter def reverse_string(value): return value[::-1] @register.simple_tag def reverse_and_sort_strings(input_list): modified_list = [reverse_string(s) for s in input_list] modified_list.sort(reverse=True)

[lang] | typescript [raw_index] | 32626 [index] | 3680 [seed] | import {Style} from './Style'; const pointStyles = new Style({ stroked: false, filled: true, getFillColor: [238, 77, 90], getRadius: 3, pointRadiusMinPixels: 2, pointRadiusMaxPixels: 4 [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a class that represents a style for rendering points on a map. The class should allow for customization of various visual properties such as stroke, fill, color, and size of the points. You are given a code snippet that initializes a `Style` object with certain prop [solution] | ```javascript import {Style} from './Style'; class PointStyle extends Style { constructor(options) { super(options); } getStrokeColor() { // Implement logic to return the RGB color values for the stroke color // Example: return this.stroked ? [0, 0, 0] : [255, 255, 255]; } s

[lang] | python [raw_index] | 143845 [index] | 32834 [seed] | self.TextComment = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_MULTILINE) self.LabelStatus = wx.StaticText(self, wx.ID_ANY, "Welcome") self.LabelOkCancelPlaceholder = wx.StaticText(self, wx.ID_ANY, "LabelOkCancelPlaceholder", style=wx.ALIGN_RIGHT) self.__set_propert [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python GUI application using the wxPython library. Your application should have a dialog window with several widgets, including a multiline text control, static text labels, and a choice control. Additionally, you need to bind an event to the choice control to handle u [solution] | The provided solution completes the implementation of the `MyDialog` class by adding the necessary code to set properties and layout for the widgets, as well as to bind an event to the choice control. The `__set_properties` method sets the title of the dialog window and the initial selection of the

[lang] | typescript [raw_index] | 142278 [index] | 2071 [seed] | .send(urlBody) }) [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function that sends an HTTP POST request to a given URL with a specified body. Your function should take two parameters: `url` (a string representing the URL to which the request will be sent) and `body` (a string representing the body of the request). The function [solution] | ```javascript async function sendPostRequest(url, body) { try { const response = await fetch(url, { method: 'POST', body: body, headers: { 'Content-Type': 'application/json' } }); if (!response.ok) { throw new Error('Failed to send POST request');

[lang] | python [raw_index] | 34344 [index] | 33096 [seed] | swap2ijs[swap] = [(i, j), (i+1, j)] ij2swaps[(i, j)].append(swap) ij2swaps[(i+1, j)].append(swap) [openai_fingerprint] | fp_eeff13170a [problem] | You are given a grid of size N x M, where each cell contains a non-negative integer. Your task is to implement a function that swaps the values of two adjacent cells in the grid and updates the grid accordingly. The function should also keep track of the swaps made and the cells involved in each swa [solution] | ```python from typing import List, Dict, Tuple def swap_cells(grid: List[List[int]], i1: int, j1: int, i2: int, j2: int) -> None: # Swap the values in the grid grid[i1][j1], grid[i2][j2] = grid[i2][j2], grid[i1][j1] # Update the swap tracking data structures swap = len(swap2ijs

[lang] | python [raw_index] | 90815 [index] | 34244 [seed] | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a program that analyzes a given text file to count the occurrences of each unique word. The program should ignore punctuation and be case-insensitive when counting words. Additionally, the program should output the top N most frequently occurring words in the file, where [solution] | ```python from typing import List, Tuple import re from collections import Counter def top_n_words(file_path: str, n: int) -> List[Tuple[str, int]]: with open(file_path, 'r') as file: text = file.read().lower() words = re.findall(r'\b\w+\b', text) word_count = Counter(wo

[lang] | python [raw_index] | 98814 [index] | 2495 [seed] | <filename>objects/CSCG/_2d/mesh/do/find.py from screws.freeze.main import FrozenOnly from root.config.main import sIze import numpy as np class _2dCSCG_Mesh_DO_FIND(FrozenOnly): """A wrapper of all find methods for mesh.do.""" def __init__(self, meshDO): self._DO_ = meshDO [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a class method for finding specific elements in a 2D mesh. The given code snippet provides the beginning of a Python class `_2dCSCG_Mesh_DO_FIND` that is a wrapper for find methods for mesh.do. Your task is to complete the implementation of a method `find_elements` w [solution] | ```python class _2dCSCG_Mesh_DO_FIND(FrozenOnly): """A wrapper of all find methods for mesh.do.""" def __init__(self, meshDO): self._DO_ = meshDO self._mesh_ = meshDO._mesh_ self._freeze_self_() def find_elements(self, element_type): if element_type == "t

[lang] | rust [raw_index] | 22136 [index] | 2280 [seed] | extern "C" { pub fn pam_open_session( pamh: *mut pam_handle_t, flags: ::std::os::raw::c_int, ) -> ::std::os::raw::c_int; } [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Rust FFI (Foreign Function Interface) binding for the `pam_open_session` function from the PAM (Pluggable Authentication Modules) library. The `pam_open_session` function is used to initiate a user session within the PAM framework. Your goal is to create a Rust functio [solution] | ```rust use std::os::raw::c_int; use std::os::raw::c_void; // Define the pam_handle_t type if it's not already defined in the Rust code #[repr(C)] pub struct pam_handle_t { // Define the fields of pam_handle_t if known // For example: // pub data: *mut c_void, // pub some_field: c_i

[lang] | php [raw_index] | 47783 [index] | 2584 [seed] | 5 => '', 6 => '', 7 => '', ]; public static $exelHeader = [ 1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a class that represents a spreadsheet. The class should have a method to convert a given column number into its corresponding column label, similar to how columns are labeled in Excel. You are provided with a code snippet that includes a partial implementation of th [solution] | ```php class Spreadsheet { public static $exelHeader = [ 1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', // ... more mappings ]; public static function getColumnLabel($columnNumber) { $label =

[lang] | java [raw_index] | 3550 [index] | 4676 [seed] | @ParameterizedTest @MethodSource("provideTestDataForPart1") public void testPart1(List<String> input, Object expected, IOHelper io) { testPart1(this.day, input, expected, io); } @ParameterizedTest @MethodSource("provideTestDataForPart2") public void testPart2(Lis [openai_fingerprint] | fp_eeff13170a [problem] | You are given a Java test class that uses JUnit 5's ParameterizedTest to test two parts of a day's code. The test methods testPart1 and testPart2 take a list of strings as input, an expected object, and an IOHelper object. The testPart1 and testPart2 methods are expected to test the day's code for p [solution] | ```java import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import java.util.List; import java.util.Arrays; public class DayTest { static Stream<Arguments> provideTestDataForPart1() { return Stream.o

[lang] | cpp [raw_index] | 124233 [index] | 4185 [seed] | /***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 <NAME> * * This library is free software; you can redistribute it and/or [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a program that reads a C++ source file and extracts the copyright holder's name from the file header. The file header is defined as the comment block at the beginning of the file, which typically contains copyright information and licensing details. Your program should [solution] | ```python import re def extract_copyright_holder(file_path): with open(file_path, 'r') as file: content = file.read() # Define regular expressions to match different styles of copyright comments single_line_comment_pattern = r'\/\/.*Copyright.*\n' multi_line_comment_pattern

[lang] | python [raw_index] | 37388 [index] | 1965 [seed] | if (lc>1024): dt=dt[dt.index(b"\n")+1:] if (time.time()>lt): lt=time.time()+30 fs.write("log.log",dt) [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a log file management system. The provided code snippet is a part of a Python script responsible for managing a log file. The script continuously reads data from a source and writes it to a log file. However, it has a couple of issues that need to be addressed. The [solution] | ```python import time class FileSystem: def write(self, file_name, data): # Implementation of the write method to write data to the log file pass def manage_log_file(dt: bytes, fs: FileSystem): if len(dt) > 1024: dt = dt[dt.index(b"\n") + 1:] # Remove data up to th

[lang] | python [raw_index] | 74658 [index] | 5870 [seed] | for line in f: files.append(line.split('\n')[0]) # 得到每行的文件名,然后append return files class PointNetDataset(Dataset): # 继承父类Dataset def __init__(self, root_dir, train): super(PointNetDataset, self).__init__() # 执行父类的构造函数,使得我们能够调用父类的属性。 self._train = train # 0是训练文件,1是测试文件 sel [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a custom dataset class for a machine learning project using Python and PyTorch. The dataset class, named `PointNetDataset`, is designed to handle loading and processing of data for a point cloud classification task. The dataset is expected to be split into training a [solution] | ```python import torch from torch.utils.data import Dataset class PointNetDataset(Dataset): def __init__(self, root_dir, train): super(PointNetDataset, self).__init__() self._train = train self._classes = [] self._file_names = [] self._labels = []

[lang] | python [raw_index] | 39296 [index] | 22299 [seed] | # 获得py文件名 def get_pyname(): global FileNum return 'test_%d' % FileNum # 接收代码写入文件 def write_file(pyname, code): fpath = os.path.join(TempFile, '%s.py' % pyname) with open(fpath, 'w', encoding='utf-8') as f: [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python program that manages the storage and retrieval of code snippets. The program should provide functionality to generate unique file names for the code snippets and write the code to corresponding files. You are provided with a code snippet that contains two funct [solution] | ```python import os # Directory for storing the code snippets TempFile = '/path/to/temporary/directory' # Global variable to track the file number FileNum = 0 # Get unique file name for the code snippet def get_pyname(): global FileNum FileNum += 1 return 'test_%d' % FileNum # Write

[lang] | rust [raw_index] | 129897 [index] | 1910 [seed] | #![recursion_limit = "1024"] extern crate proc_macro; #[macro_use] extern crate quote; extern crate syn; [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Rust macro that generates a custom implementation for a trait based on the input struct. The macro should take a struct definition as input and generate an implementation for a specified trait. Your task is to write a macro that accomplishes this functionality. Your m [solution] | ```rust #![recursion_limit = "1024"] extern crate proc_macro; #[macro_use] extern crate quote; extern crate syn; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, Data, DeriveInput, Fields}; #[proc_macro_derive(MyTraitMacro)] pub fn my_trait_macro(input: TokenStream) ->

[lang] | rust [raw_index] | 128427 [index] | 3383 [seed] | let mut s = "".to_string(); [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a function that takes a string as input and returns a modified version of the string based on specific rules. The function should perform the following operations: 1. Convert all lowercase letters to uppercase. 2. Remove any whitespace characters from the string. 3. [solution] | ```rust fn modify_string(input: &str) -> String { let modified_string: String = input .to_uppercase() // Convert all lowercase letters to uppercase .chars() .filter(|c| !c.is_whitespace()) // Remove whitespace characters .rev() // Reverse the order of the characte

[lang] | python [raw_index] | 143759 [index] | 18240 [seed] | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python script to automate the process of downloading files from wetransfer.com. The script should be able to handle the download of files from wetransfer.com using the `transferwee` module. The `transferwee` module exposes a `download` subcommand, which is used to down [solution] | ```python import subprocess def download_from_wetransfer(url: str, destination: str) -> bool: try: # Use subprocess to call the transferwee download subcommand process = subprocess.run(['transferwee', 'download', url, '-d', destination], check=True, capture_output=True, text=Tru

[lang] | java [raw_index] | 102202 [index] | 3962 [seed] | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package spark.kmedoids.eval.synthetic; [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with implementing a program to calculate the Levenshtein distance between two strings. The Levenshtein distance is a measure of the similarity between two strings, which is defined as the minimum number of single-character edits (insertions, deletions, or substitutions) required to ch [solution] | ```python def levenshtein_distance(str1: str, str2: str) -> int: m, n = len(str1), len(str2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): dp[i][0] = i for j in range(n + 1): dp[0][j] = j for i in range(1, m + 1): for j in range(1, n

[lang] | python [raw_index] | 72774 [index] | 12310 [seed] | from .feature_extraction import word, vocabulary from .feature_extraction import normalizer [openai_fingerprint] | fp_eeff13170a [problem] | You are working on a natural language processing (NLP) project and need to implement a custom feature extraction module for text data. The module should include functionality for word extraction, vocabulary creation, and text normalization. Your task is to create a Python class that encapsulates th [solution] | ```python # feature_extraction.py class TextFeatureExtractor: @staticmethod def extract_words(text): return text.split() @staticmethod def create_vocabulary(words): return set(words) @staticmethod def normalize_text(text): return ''.join(e for e in

[lang] | python [raw_index] | 110137 [index] | 10567 [seed] | urlpatterns = [ path('', TemplateView.as_view(template_name='index.html'), name='index'), path('formulario/', TemplateView.as_view(template_name='index.html'), name='formulario'), ] [openai_fingerprint] | fp_eeff13170a [problem] | You are tasked with creating a Python function that processes a list of URL patterns and returns a dictionary mapping each URL path to its corresponding template name. The URL patterns are represented as a list of tuples, where each tuple contains the path, view, and name of the URL. You need to im [solution] | ```python from django.views.generic import TemplateView def extract_template_mapping(urlpatterns): template_mapping = {} for path, view, name in urlpatterns: if isinstance(view, TemplateView): template_mapping[path] = view.template_name return template_mapping ``` T

[lang] | python [raw_index] | 106945 [index] | 85 [seed] | twos += two threes += three checksum = twos * threes [openai_fingerprint] | fp_eeff13170a [problem] | You are given a list of strings, each containing only lowercase English letters. Your task is to find the checksum of the list, which is calculated as the product of the count of strings containing exactly two of any letter and the count of strings containing exactly three of any letter. For exampl [solution] | ```python from typing import List def calculate_checksum(strings: List[str]) -> int: twos = 0 threes = 0 for string in strings: counts = {} for char in string: counts[char] = counts.get(char, 0) + 1 if 2 in counts.values(): twos += 1