text
stringlengths
18
19.4k
source
stringclasses
1 value
num_tokens
int64
3
4.34k
id
stringlengths
47
47
import random from typing import List def select_random_word(word_list: List[str]) -> str: """ Selects a random word from the provided list of words. :param word_list: List of words to choose from. :return: A randomly selected word. """ return random.choice(word_list) def create_initial_c...
cranecode
694
cranecode::8eb1ed2f-d260-5ee2-958e-d08860362884
from django.contrib import admin from images.models import Image class ImageAdmin(admin.ModelAdmin): """ Custom admin class for the Image model to enhance the admin interface. This class provides a customized view for managing Image objects in the Django admin site, including list display, search ...
cranecode
239
cranecode::5bb6824c-4a53-596d-ab4d-3028b3b18baf
from django.urls import path from . import views # Define the application namespace app_name = 'polls' def get_polls_urlpatterns() -> list: """ Returns a list of URL patterns for the polls application. This function defines the routing for different views in the polls app, including the index, detail...
cranecode
288
cranecode::c98a5f54-9684-5c2b-9598-afcd9d248141
import tensorflow.compat.v1 as tf tf.disable_v2_behavior() # Constants to define the architecture LAYER_SIZES = [16, 32, 64, 128] NUM_RESIDUAL_UNITS = 3 def batch_normalization_and_leaky_relu(input_tensor: tf.Tensor) -> tf.Tensor: """ Applies batch normalization followed by a leaky ReLU activation function. ...
cranecode
1,940
cranecode::c4873296-5503-545f-9871-eff07e2e3210
from PIL import Image, ImageChops from typing import List, Tuple def read_image_filenames(file_path: str) -> List[str]: """ Reads a file containing a list of image filenames and returns them as a list. :param file_path: Path to the file containing the list of filenames. :return: A list of image filena...
cranecode
673
cranecode::247bd0d8-d216-5b89-8bbe-c0bfbcfb3194
import tensorflow as tf # Define utility functions that were previously assumed to be part of 'util' def lrelu(x: tf.Tensor, alpha: float = 0.2) -> tf.Tensor: """Applies Leaky ReLU activation to the input tensor.""" return tf.maximum(alpha * x, x) def crop_by_pixel(input_tensor: tf.Tensor, num_pixels: int) ->...
cranecode
1,706
cranecode::b2dc7cb9-c9a5-5ed7-ba48-75af7e1a311e
import yfinance as yf import pandas as pd from pathlib import Path def fetch_latest_trading_day_data(ticker: str) -> pd.DataFrame: """ Fetches the latest trading day's data for a given ticker. Parameters: ticker (str): The stock ticker symbol. Returns: pd.DataFrame: A DataFrame containing the...
cranecode
883
cranecode::b16cf3c4-9fb1-532c-9467-ef40e5f7edc9
import flask import pickle import pandas as pd from sklearn.feature_extraction.text import CountVectorizer # Load the training data def load_training_data(file_path: str) -> pd.DataFrame: """ Loads and preprocesses the training data from a CSV file. Parameters: file_path (str): The path to the CSV fil...
cranecode
700
cranecode::e87aae24-75b8-53b2-b0b8-1622a9874d40
#!/usr/bin/env python import rospy from std_msgs.msg import Float32, String def process_yaw_message(yaw_value: float) -> str: """ Processes the yaw value by converting it to a formatted string. Args: yaw_value (float): The yaw angle in radians. Returns: str: A formatted string repres...
cranecode
335
cranecode::688b2da9-ea13-5ac0-9056-d2b03452463f
import json import csv class Base: """ Base class with a private attribute __nb_objects to count instances. Attributes: id (int): Unique identifier for each instance. """ __nb_objects = 0 def __init__(self, object_id: int = None): """ Initialize a new instance of the ...
cranecode
1,699
cranecode::5c1234c8-b220-5e6b-b3d8-79b365eca349
#!/usr/bin/python3 """ This module defines the Rectangle class which inherits from the Base class. """ class Rectangle: """ Represents a rectangle with specified dimensions and position. Attributes: width (int): Width of the rectangle. height (int): Height of the rectangle. x (int)...
cranecode
1,574
cranecode::1993d947-fc3a-59bb-a81a-7d70141d4605
#!/usr/bin/python3 import unittest from typing import List, Optional, Union def find_maximum_value(numbers: List[Union[int, float]]) -> Optional[Union[int, float]]: """ Finds the maximum value in a list of numbers. Parameters: numbers (List[Union[int, float]]): A list of integers or floats. Retur...
cranecode
709
cranecode::4ef64509-edb3-57b7-bd4a-3e51967d45af
import json import re from typing import Dict, Set, List def load_job_data(file_path: str) -> List[Dict]: """ Load job data from a JSON file. :param file_path: Path to the JSON file containing job data. :return: List of job dictionaries. """ try: with open(file_path, 'r') as file: ...
cranecode
1,093
cranecode::fe5d1be3-fde6-5a5f-8a62-607db44530fb
import os from typing import Any, Dict, List class GradingSystem: """ A class to simulate a grading system for educational purposes. """ def __init__(self): self.users: Dict[str, Dict[str, Any]] = {} self.courses: Dict[str, Dict[str, List[Dict[str, str]]]] = {} def load_data(self)...
cranecode
843
cranecode::e4740847-b472-5222-8ca6-13f561cc4b5b
from datetime import datetime, timedelta import pytest # Simulated User class class User: def __init__(self, username: str, password: str): self.username = username self.password = password self.courses = {} def submit_assignment(self, course_name: str, assignment_name: str, submission...
cranecode
824
cranecode::50cce4b6-04b9-5986-8d62-bdd9f8132713
import logging from typing import Optional # Mock implementation of browser_util for demonstration purposes class BrowserUtil: _driver = None @staticmethod def get_driver() -> Optional['WebDriver']: """Retrieve the current WebDriver instance.""" return BrowserUtil._driver @staticmetho...
cranecode
635
cranecode::a9edb759-216a-502f-accc-74adcd0054a9
from behave import given, when, then, register_type import parse from typing import Optional from unittest.mock import Mock # Mocking CalculatorPage and ocr_util for self-containment class CalculatorPageMock: def open_calculator_page(self): """Simulate opening the calculator page.""" print("Calcula...
cranecode
679
cranecode::fb199da1-7098-5fc0-b31c-8de18dcddd45
#!/usr/bin/env python3 """ A script to test distributed SQL queries using dbToaster and K3. """ import os import re import platform import json import subprocess def generate_file_name(file_path: str) -> str: """ Generate a user-friendly name for the file based on its path. :param file_path: Path to th...
cranecode
3,829
cranecode::63b6d30f-6ef2-5d16-ab22-851f380c2ed1
import numpy as np import dataclasses # Mock implementations for the missing functions def define_alphabet(sequence_type: str, allow_ambiguous: bool) -> str: """Define the alphabet based on the sequence type and ambiguity allowance.""" alphabets = { 'dna': 'ACGT', 'rna': 'ACGU', 'protei...
cranecode
851
cranecode::7ec43d6b-48ee-52fb-a685-77ea794a82aa
import argparse import time import os import torch import torch.nn as nn import torch.optim as optim from sklearn.metrics import classification_report # Constants for configuration NUM_EPOCHS = 1000 BATCH_SIZE = 16 PATIENCE = 10 LEARNING_RATE = 1e-3 # Paths and configurations DATA_DIR = 'data/annotations/new_annot.js...
cranecode
1,955
cranecode::f96ead85-b62f-50c1-a0b3-7d07ec3114dd
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, Dataset, TensorDataset import time # Mock implementations for the models class AnchorTextOnlyModel(nn.Module): def __init__(self): super().__init__() self.fc = nn.Linear(100, 2) # Assuming input...
cranecode
2,162
cranecode::e899cefc-ccda-56e6-b956-93e3c2733009
import os import re import json import random import spacy import torch import transformers as ppb import numpy as np import torchvision.models as models from collections import Counter, defaultdict from PIL import Image from torchvision import transforms from torch.utils.data import Dataset, DataLoader from tqdm impor...
cranecode
3,957
cranecode::c8cb4df8-d259-58e7-9998-ea4c5772a344
import logging import tensorflow as tf import numpy as np # Constants VOCAB_SIZE = 1996725 SENTENCE_LENGTH_MAX = 150 DEFAULT_TYPE = tf.float32 class TextClassifier: def __init__(self, embedding_file: str, embedding_size: int, conv_params: list, fc_sizes: list): """ Initializes the TextClassifier w...
cranecode
2,452
cranecode::0df3369d-1cd8-5b72-8bbc-f0113706a89c
import tensorflow as tf class TensorFlowModel: """ A class representing a TensorFlow model with a specific scope name. """ def __init__(self, scope_name: str): """ Initializes the TensorFlowModel with a given scope name. Args: scope_name (str): The name scope for th...
cranecode
305
cranecode::4687ec1a-1679-5041-ab74-ad025fb50746
import numpy as np import pytest from abc import ABC, abstractmethod class BendingState: """Represents the bending state of a system with a default array of zeros.""" def __init__(self, array: np.ndarray = None): self.array = array if array is not None else np.zeros(3) class Metric(ABC): """Abstra...
cranecode
786
cranecode::392d46f1-b433-544f-adc7-be3e93588769
import os import yaml import batoid import numpy as np from aos.telescope import BendingTelescope, ZernikeTelescope, Telescope from aos.state import BendingState, ZernikeState def load_lsst_optic() -> batoid.Optic: """ Load the LSST g optic configuration from a YAML file. Returns: batoid.Optic: Th...
cranecode
1,767
cranecode::237a02f0-d489-566e-9003-ac47837301de
import numpy as np class Survey: """ A class to represent an astronomical survey with a table of observations. Attributes: table (np.ndarray): A structured array containing survey data. """ def __init__(self, filters: list = ['r'], magnitudes: list = [20.0]): """ I...
cranecode
480
cranecode::52697e24-5559-51bd-aa09-16e32f62ed15
import numpy as np class WavefrontEstimator: def evaluate(self, zernike_coefficients: np.ndarray) -> np.ndarray: """ Evaluate the wavefront based on Zernike coefficients. :param zernike_coefficients: Array of Zernike coefficients. :return: Simulated wavefront image. """ ...
cranecode
1,248
cranecode::ed94f8b7-adc9-53ea-bcfa-0e698af05101
import os import yaml import batoid import numpy as np # Mock classes for demonstration purposes class M1M3Residual: def __init__(self, n_modes: int = 5): self.n_modes = n_modes self.x, self.y = np.meshgrid(np.linspace(-1, 1, 100), np.linspace(-1, 1, 100)) self.surf_residual = np.zeros_like...
cranecode
2,560
cranecode::9c0ce3cf-ccdf-5e48-8bcf-a9b4f80de554
from typing import List, Tuple, Union import math def calculate_earliest_bus_product(start_time: int, bus_ids: List[Union[int, str]]) -> int: """ Calculate the product of the earliest bus ID and the waiting time from the start time. :param start_time: The starting time. :param bus_ids: A list of b...
cranecode
987
cranecode::9744ebdb-065b-585c-95ac-dd1e16d945b3
import logging import requests from typing import Callable, List # Configure logging logging.basicConfig(level=logging.INFO) LOG = logging.getLogger(__name__) # Constants SESSION_TOKEN_FILE = '.token' ADVENT_OF_CODE_URL = "https://adventofcode.com" def fetch_advent_of_code_input(day: int, year: int) -> str: """ ...
cranecode
774
cranecode::340eabc1-1362-5a57-a863-44ad50693a37
from typing import Tuple def fetch_exoplanet_coordinates(exoplanet_name: str) -> Tuple[float, float]: """ Fetches the coordinates of a given exoplanet. Args: exoplanet_name (str): The name of the exoplanet. Returns: Tuple[float, float]: A tuple containing the right ascension and decli...
cranecode
420
cranecode::7540eedb-13a7-5671-acd1-7d74abe0cdab
""" Copyright 2021 InfAI (CC SES) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software...
cranecode
656
cranecode::facef03c-e624-5c96-af99-2026fea93b22
import numpy as np def calculate_euclidean_distances(points1: np.ndarray, points2: np.ndarray) -> np.ndarray: """ Calculate the Euclidean distance between each pair of points in two sets of points. Parameters: points1 (np.ndarray): A 2D array where each row represents a point in n-dimensional space. ...
cranecode
784
cranecode::c2026fd2-367c-54a3-af01-6dd4353dcdb8
import numpy as np from scipy.sparse import csr_matrix class BaseSmoothOracle: """ Base class for implementing oracles. """ def func(self, weights: np.ndarray) -> float: """ Calculate the value of the function at the given weights. :param weights: 1D numpy array representing th...
cranecode
907
cranecode::b9346ffd-e39c-5f8c-9ef6-2e85c6bb4e25
class HygieneGuidelines: """ A class to provide comprehensive guidelines for maintaining hygiene during a pandemic. """ def __init__(self, recommended_handwashing_time: int = 20): """ Initialize the HygieneGuidelines with a recommended handwashing time in seconds. :param recomm...
cranecode
582
cranecode::ce4afa5d-b27f-5799-b27e-ec98369e9b4e
import os import unittest from typing import Generator, List, Union class DBEXMetaEncrypter(type): """Metaclass for encrypter classes to ensure proper initialization.""" def __init__(cls, name, bases, dct): super().__init__(name, bases, dct) if cls.gen_encryption: cls.gen_encrypter ...
cranecode
1,609
cranecode::44752312-b133-5923-bcd4-77356598c46d
from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): """ A model representing additional information about a user. Attributes: user (User): The Django User instance this profile belongs to. bio (str): A short biography of the user. ...
cranecode
624
cranecode::e9b25601-017b-5334-9aab-e0157a37acf5
import configparser import logging import hashlib from typing import Optional # Mocking external dependencies for self-containment class DBSession: def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): pass def query(self, model): return Query(model) ...
cranecode
1,785
cranecode::b4df3bc5-d3e3-5626-9a69-a113b81f1f35
from threading import Thread import time import logging from pathlib import Path # Mock implementations for demonstration purposes class DataImporter: @staticmethod def import_data_opcua_call(parent, data_path: str) -> None: logging.info(f"Importing data from {data_path}") class CoatingImporter: @...
cranecode
2,736
cranecode::532f5326-9db3-5196-ac59-3554d293c4bf
import logging from typing import List, Dict, Optional # Mock implementations for DBClient and models to make the code self-contained class Part: def __init__(self, part_number: str, finished_length: float, finished_width: float, finished_thickness: float, status: str): self.part_number = part_number ...
cranecode
1,541
cranecode::884a9af5-dbaf-5d47-94d6-e324bebd3c54
#!/usr/bin/env python3 # (./send.py; cat) | nc biooosless.challenges.ooo 6543 import base64 import os def get_file_size(file_path: str) -> int: """ Returns the size of the file in bytes. Args: file_path (str): The path to the file. Returns: int: The size of the file in bytes. """...
cranecode
506
cranecode::829104cc-ffc4-5430-abdf-22a56dad8dda
# -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui, QtWidgets class NMEAMainWindow(QtWidgets.QMainWindow): """ Main window class for the NMEA sentence processing application. """ def __init__(self): super().__init__() self.setup_ui() def setup_ui(self) -> None: """ ...
cranecode
1,551
cranecode::22bfd51f-abaa-5108-ac92-934832858c67
import pystache # CSS for the Pycco HTML page PYCCO_CSS = """\ /*--------------------- Layout and Typography ----------------------------*/ body { font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; font-size: 16px; line-height: 24px; color: #252519; margin: 0; padding: 0; backgro...
cranecode
3,217
cranecode::db7288d6-6f5a-562c-a4a2-7dfb621882e2
#!/usr/bin/env python import rospy from antenna_msgs.msg import AntennaCommand from std_msgs.msg import Float64 class AntennaController: """ Controls the antenna by subscribing to commands and publishing joint positions. This class initializes ROS publishers and subscribers, processes incoming comma...
cranecode
749
cranecode::22fab64e-32de-5d01-922b-d15eba895801
import random from typing import List, Any def quicksort(array: List[Any]) -> None: """ Sorts a list in-place using the QuickSort algorithm. :param array: The list to be sorted. """ def swap_elements(index1: int, index2: int) -> None: """Swaps elements at two indices in the list.""" ...
cranecode
605
cranecode::9bc46e0a-a4e7-5817-b31b-a15273f02e4f
class QuickUnion: """ A class to implement the Quick Union algorithm for the union-find data structure. """ def __init__(self, number_of_nodes: int): """ Initializes the QuickUnion data structure with the specified number of nodes. :param number_of_nodes: Total number o...
cranecode
807
cranecode::4cff1def-54bb-5240-8d51-9ccce146103d
from typing import List class Digraph: """ A class representing a directed graph. """ def __init__(self, vertices: int): """ Initialize the directed graph with a specified number of vertices. :param vertices: The number of vertices in the graph. """ self._vert...
cranecode
1,498
cranecode::cde5b7de-2233-553f-b8e8-614c6c459ac1
class ListNode: """ A node in a singly linked list. """ def __init__(self, value: int): self.value = value self.next = None class SinglyLinkedList: """ A singly linked list implementation. """ def __init__(self, head: ListNode = None): self.head = head def ...
cranecode
854
cranecode::225b4a0b-837d-551d-851d-629a9b25b701
import random from typing import List, Any def perform_knuth_shuffle(elements: List[Any]) -> None: """ Shuffle the list in place using the Knuth shuffle algorithm. This function implements the Fisher-Yates shuffle, which ensures each permutation of the list is equally likely. Parameters: ...
cranecode
500
cranecode::e9b16b80-0539-5d18-8ee3-6300062e5d8d
import numpy as np def compute_binary_cross_entropy( predicted_probabilities: list[float], true_labels: list[int] ) -> float: """ Compute the binary cross-entropy loss between predicted probabilities and true labels. Parameters: predicted_probabilities (list[float]): A list of predicted proba...
cranecode
538
cranecode::ed88cdb3-9314-51fa-9349-3705594b5a65
import numpy as np def reshape_numpy_array(array_to_reshape: np.ndarray, target_shape: tuple) -> np.ndarray: """ Reshape a given NumPy array into a new specified shape. Parameters: array_to_reshape (np.ndarray): The original NumPy array to be reshaped. target_shape (tuple): The desired new shape o...
cranecode
427
cranecode::7a2bb75a-d9f9-5eec-bb67-074ad895b531
import numpy as np from sklearn.metrics import confusion_matrix, f1_score, precision_recall_curve def compute_confusion_matrix(actual_labels: list, predicted_labels: list) -> np.ndarray: """ Compute the confusion matrix for given actual and predicted binary labels. Parameters: actual_labels (list): Li...
cranecode
727
cranecode::52c19c4d-ad7f-542f-9c14-21f343174359
import numpy as np from sklearn.preprocessing import StandardScaler, MinMaxScaler def apply_standard_scaler(input_data: np.ndarray) -> np.ndarray: """ Apply StandardScaler to the input data and print the transformed data, mean, and standard deviation. Parameters: input_data (np.ndarray): Input data t...
cranecode
582
cranecode::3659a6c6-20d5-5b35-b640-ac7c07c0f467
from collections import Counter, defaultdict from functools import partial import math from typing import Any, Dict, List, Tuple, Union def build_decision_tree(training_data: List[Tuple[Dict[str, Any], bool]], attributes: List[str] = None) -> Union[bool, Tuple[str, Dict[Any, Union[bool, Tuple]]]]: """ Construc...
cranecode
1,819
cranecode::b0332554-3cbb-5032-be56-ce5b54fa61f2
import paho.mqtt.client as mqtt MQTT_BROKER_ADDRESS = 'localhost' STATE_INFO_TOPIC = 'state_info_from_edgex' MQTT_USERNAME = 'link' MQTT_PASSWORD = '0123' def on_mqtt_connect(client: mqtt.Client, userdata, flags, return_code: int) -> None: """ Callback function for when the client receives a CONNACK response...
cranecode
548
cranecode::5c1511f2-fc3a-5c58-8acc-28889474433e
import networkx as nx from typing import Dict, List def calculate_degree_centrality(vertex: str, graph: nx.Graph) -> int: """ Calculate the degree centrality of a vertex in the graph. :param vertex: The vertex for which to calculate degree centrality. :param graph: The graph containing the vertex....
cranecode
1,035
cranecode::0d9d57be-4cea-5084-836f-afec86de61f3
import pickle import numpy as np class PearsonCorrelationCalculator: """ A class to calculate the Pearson correlation coefficient between two datasets. It also provides functionality to save and load data using pickle files. """ def save_data_to_pickle(self, filename: str, data) -> None: "...
cranecode
1,532
cranecode::6d47a63e-6638-5205-aaf5-b4aae4c4f7f5
import gym import readchar from enum import Enum # Define an enumeration for actions class Action(Enum): LEFT = 0 DOWN = 1 RIGHT = 2 UP = 3 # Key mapping for arrow keys ARROW_KEY_MAPPING = { '\x1b[A': Action.UP, '\x1b[B': Action.DOWN, '\x1b[C': Action.RIGHT, '\x1b[D': Action.LEFT } de...
cranecode
519
cranecode::760743f6-6a1f-5c11-8635-1378814910ca
# coding: utf-8 import numpy as np import matplotlib.pyplot as plt from deeplink.custom_image_data import CustomImageData from deep_convnet import DeepConvNet import math def load_image_datasets(dataset_path: str, image_width: int, image_height: int, image_channel: int) -> tuple: """ Load image datasets from t...
cranecode
1,694
cranecode::c0c2233c-a0da-5cf4-8133-23cc73b46548
def calculate_digit_sum(number: int) -> int: """ Calculate the sum of the digits of a positive integer. Args: number (int): A positive integer. Returns: int: The sum of the digits of the input number. """ # Initialize sum to zero digit_sum = 0 # Loop through each d...
cranecode
297
cranecode::18683a3e-6b46-51a0-a8f7-d5390634ca8a
import re from typing import Dict, List, Union class IDParserInfo: """Provides parser metadata (version, author, etc.)""" version = '1.3' description = '`id` command parser' author = 'Kelly Brazil' author_email = 'kellyjonbrazil@gmail.com' compatible_platforms = ['linux', 'darwin', 'aix', 'fre...
cranecode
1,249
cranecode::03523f9b-11e2-5949-9089-eed1957589b8
import os import unittest import json import jc.parsers.ping class PingParserTest(unittest.TestCase): """ A test suite for the jc.parsers.ping module. """ def setUp(self) -> None: """ Load input and output fixtures for testing. """ self.input_data = self._load_fixtures...
cranecode
2,108
cranecode::0c136510-6c9e-5128-a66c-d90a5715ac10
import discord import socket import threading import json import time import requests import subprocess import os import configparser import codecs import webview from urllib.parse import urlparse, parse_qs import traceback # Load configuration config = configparser.ConfigParser() config.read_file(codecs.open('conf.in...
cranecode
2,594
cranecode::fe5dab23-1b0f-52ba-b832-7bc974977581
from django.db import models class WorkRequest(models.Model): """ Model representing a work request in the system. Attributes: id (int): Auto-incrementing primary key. job_number (str): Unique identifier for the job. team_name (str): Name of the team responsible for the job. ...
cranecode
1,295
cranecode::ff4cb9b9-22d2-5e24-9a2b-455693d2608e
from django.urls import path, include from django.contrib import admin # Enable the admin interface admin.autodiscover() def configure_url_patterns() -> list: """ Configure and return the URL patterns for the application. Returns: list: A list of URL patterns for the application. """ urlp...
cranecode
216
cranecode::42661b77-c83f-55d8-99d4-f45495763072
from django.db import models from django.contrib.auth.models import User # Define choices for gender, card type, and group with more descriptive names GENDER_CHOICES = ( ('MALE', 'Male'), ('FEMALE', 'Female'), ) CARD_TYPE_CHOICES = ( ('ANNUAL', 'Annual'), ('SIX_MONTH', 'Six Month'), ('ONE_MONTH', ...
cranecode
1,055
cranecode::3079cf5a-6f77-5796-971d-04c6f26b54c7
import os import sys import pandas as pd # Assuming ch_pen and ch_metaobjects are custom modules that you have control over. # For demonstration purposes, I'll mock these classes. class MockMetaObjectStore: def collect_exhibitions_records(self): """Mock method to simulate collecting exhibitions records."""...
cranecode
691
cranecode::ab1b85ef-7388-58e4-8e91-db819d5fea00
import os import sys import pandas as pd from typing import Any, Dict # Mock class to simulate the behavior of ch_pen.Pen class Pen: def create_temporal_features(self, dataframe: pd.DataFrame) -> pd.DataFrame: """ Creates temporal features from the given DataFrame. :param dataframe: A pand...
cranecode
614
cranecode::7544ebf4-5872-527a-982a-a80e0b857652
from django.test import TestCase from dailyhub.models import Contacto class ContactoModelTestCase(TestCase): """ Test case for the Contacto model. """ @classmethod def setUpTestData(cls): """ Set up non-modified data for all test methods. This method is called once for the ...
cranecode
593
cranecode::4a8f6345-15ba-5b60-9b5b-173d2d59808c
import numpy as np import matplotlib.pyplot as plt import pandas as pd import pandas_datareader as web import datetime as dt from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, LSTM def fetch_stock_data(ticker_symbol: str, st...
cranecode
1,878
cranecode::e026c9e8-284b-59a9-b03a-db297f51ceab
import discord import os import random from dotenv import load_dotenv from datetime import datetime load_dotenv() DISCORD_TOKEN = os.getenv("DISCORD_TOKEN") class GroupShufflerBot(discord.Client): """A Discord bot that shuffles participants into groups of a specified size.""" def __init__(self, *args, **kwa...
cranecode
1,269
cranecode::50bb6b58-88d5-50e2-8b90-a7495a75cea1
import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple # Assuming pyutils and network.resnet38d are part of the project, we will mock them for self-containment class MockPyUtils: @staticmethod def get_indices_of_pairs(radius: int, size: Tuple[int, int]) -> Tuple[torch.Tenso...
cranecode
1,965
cranecode::131c3026-6c11-5b3c-a0d7-c78ff5488ff1
import torch import torchvision import numpy as np import imageio import os import argparse import importlib import torch.nn.functional as F from torch.utils.data import DataLoader import voc12.data import imutils def generate_pixel_indices(height: int, width: int, radius: int) -> np.ndarray: """ Generates ind...
cranecode
2,445
cranecode::fccd83c5-37d1-51a4-acf8-99b06a488cea
from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError import bleach # Define valid HTML tags for content sanitization ALLOWED_HTML_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] class BlogPostForm(forms.ModelForm): """ Form for creating or updatin...
cranecode
1,028
cranecode::c3ba4797-4042-57c6-af6b-3c3b344d8345
from django.test import TestCase, Client from django.shortcuts import reverse import uuid from .models import Blog, User from .forms import BlogForm class BlogFormValidationTest(TestCase): """ Test case for validating the BlogForm fields. """ def setUp(self) -> None: """ Set up the ini...
cranecode
3,381
cranecode::74f320a9-2c9b-5e33-abeb-95f4cd908c08
from typing import List, Dict class DatabaseModel: """ A simple class to simulate a database model with fields. """ def __init__(self, name: str, fields: Dict[str, type]): """ Initialize a new database model with a name and fields. :param name: The name of the model. :p...
cranecode
795
cranecode::6b82f05b-c424-5b36-825b-d36ece2563a8
from typing import List, Dict class Ticket: """ Represents a ticket with user information. Attributes: user_id (int): Unique identifier for the user. event_name (str): Name of the event. seat_number (str): Seat number assigned to the ticket. """ def __init__(self, ...
cranecode
557
cranecode::007c3a9d-e16d-5107-b340-52ecc828f087
def calculate_recursive_value(input_number: int) -> int: """ Recursively calculates a value based on the input number using specific rules. Args: input_number (int): The input integer to calculate the value from. Returns: int: The calculated value. """ if input_number < 3: ...
cranecode
387
cranecode::24b829d5-5fd0-5f1c-b455-3c6468c776f3
def calculate_ways_to_reach_target(start_value: int, target_value: int) -> int: """ Recursively calculates the number of ways to reach the target value starting from the start value by incrementing by 1, doubling, or tripling the current value. :param start_value: The initial integer value. :param ...
cranecode
457
cranecode::5c6e5398-e8ab-5b38-87dd-25dd357dca3d
def count_divisors(number: int, divisors: list[int]) -> int: """ Count how many numbers in the divisors list divide the given number. Args: number (int): The number to be checked. divisors (list[int]): A list of divisors to check against. Returns: int: The count of divisors tha...
cranecode
428
cranecode::5368a40d-83dc-5712-acec-05171cc7045c
def calculate_digit_sum(number: int) -> int: """ Calculate the sum of the digits of a given number. Args: number (int): The number whose digits are to be summed. Returns: int: The sum of the digits of the number. """ total = 0 while number > 0: total += number % 10 ...
cranecode
457
cranecode::dce71dc4-f5e9-5bb6-8eaa-8ac595cdd87a
def calculate_custom_sequence(term_index: int) -> int: """ Calculate the nth term of a custom sequence defined as follows: - S(1) = 1 - S(2) = 2 - S(3) = 3 - S(n) = S(n - 3) * n for n > 3 Parameters: term_index (int): The term of the sequence to calculate. Returns: int: The nth...
cranecode
288
cranecode::37569c81-bd1e-5a88-ac0d-036b041b184f
def transform_and_count_ones(start_length: int, end_length: int) -> None: """ Transforms strings composed entirely of '1's by replacing occurrences of "111" with "2" and "222" with "1". It then prints the count of '1's in the original string if the transformed string equals "22". :param start_lengt...
cranecode
302
cranecode::f3510585-947e-5bcb-b246-66b379f3be87
def is_divisible(number: int, divisor: int) -> bool: """ Check if a number is divisible by a given divisor. Args: number (int): The number to be checked. divisor (int): The divisor. Returns: bool: True if the number is divisible by the divisor, False otherwise. """ retu...
cranecode
509
cranecode::daf901a9-ad6f-5bb1-9934-d29608543144
import investpy import pandas as pd from azure.cosmos import CosmosClient, exceptions from typing import List, Dict, Any def fetch_south_korea_10y_bond_data(start_date: str, end_date: str) -> pd.DataFrame: """ Fetch historical bond data for South Korea 10Y from investpy. Args: start_date (str): Th...
cranecode
950
cranecode::9d1acff8-95f9-57f8-912f-364b68459be1
import json import requests from typing import List, Optional def fetch_meme_image_url(api_url: str = "https://meme-api.herokuapp.com/gimme") -> str: """ Fetches a meme image URL from the specified Meme API. Args: api_url (str): The URL of the Meme API endpoint. Returns: str: The URL ...
cranecode
536
cranecode::4a2a34c5-a415-5125-9bf9-6baa30d27c70
# -*- coding: utf-8 -*- import os import logging import time from typing import Dict, Optional # Simulating the base command class and PlayerError exception class BaseCommand: def __init__(self, args: Dict[str, Optional[object]]): self._args = args self._player = MediaPlayer() def _set_playin...
cranecode
960
cranecode::12e9d58e-0324-534e-892c-b1b8ac0ac4bd
# -*- coding: utf-8 -*- import logging import queue import threading from datetime import datetime from typing import List, Optional, Callable, Tuple # Mocking external dependencies for self-containment class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._...
cranecode
2,582
cranecode::46260644-7d7f-5600-9e2a-ba7c37530378
# -*- coding: utf-8 -*- from base64 import b64encode, b64decode from Crypto.Cipher import AES from Crypto import Random AES_BLOCK_SIZE = AES.block_size def pad_plaintext(plaintext: str) -> bytes: """ Pad the plaintext to ensure it is a multiple of the AES block size. Parameters: ---------- plain...
cranecode
902
cranecode::1115227c-9f99-596d-a4c8-a7e6c0577b65
# -*- coding: utf-8 -*- import logging import os import time import threading # Mocking external dependencies for self-containment class SmartQueue: def __init__(self, maxlen: int, db_params: dict): self.queue = [] self.maxlen = maxlen self.db_params = db_params def enqueue(self, data...
cranecode
1,155
cranecode::45efdd09-cf22-5255-a932-1cb7e320aace
# -*- coding: utf-8 -*- import logging import time # Mocking the hardware and system.status modules for self-containment class HardwarePlatform: @staticmethod def restart_networking(): """Simulates restarting the networking service.""" print("Restarting networking service...") class SystemSta...
cranecode
647
cranecode::8091a2b4-2dc9-5c86-876c-650216b53a67
# -*- coding: utf-8 -*- from bottle import template, run, get, post, auth_basic, abort, request, static_file, TEMPLATE_PATH, redirect import os import logging import webui.models.status import webui.models.password import webui.models.address import webui.models.system # Configure logging logger = logging.getLogger(...
cranecode
1,745
cranecode::4df7e7b5-5cbb-5076-a558-867770f92cbe
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import time import subprocess # Mocking the utils.shell module for demonstration purposes class ShellUtils: @staticmethod def execute(command: str) -> tuple: """Execute a shell command and return the result.""" try: resu...
cranecode
1,277
cranecode::b73fcbb6-427a-529e-86dc-c13c6f0a7591
import numpy as np from typing import List, Any, Dict def create_one_hot_encoding(class_labels: List[Any]) -> np.ndarray: """ Create a one-hot encoded matrix from a list of class labels. Parameters: class_labels (List[Any]): A list of classification labels. Returns: np.ndarray: A 2D numpy arr...
cranecode
299
cranecode::aef5ce43-94d0-5690-b688-b12dbdcf3144
from typing import List def count_number_occurrences(numbers: List[int]) -> List[int]: """ Counts the occurrences of each number in the list, assuming numbers are 1-based indices. Args: numbers (List[int]): A list of integers representing 1-based indices. Returns: List[int...
cranecode
369
cranecode::6c236eba-902b-528f-bbd5-73bd553abc66
import streamlit as st import requests from typing import List, Dict, Any def fetch_mercadolibre_item_status(item_id: str, access_token: str) -> Dict[str, Any]: """ Retrieves the catalog quality status for a specified MercadoLibre item using the provided access token. Args: item_id (str): The uniq...
cranecode
525
cranecode::9bc88fe8-45ce-543a-bdec-d30afcc1469e
from collections import defaultdict from os import listdir from os.path import isfile, join from re import split from typing import List, Dict, Tuple def collect_labeled_documents( parent_directory: str, newsgroup_names: List[str], word_frequencies: Dict[str, int] = None ) -> List[str]: """ Collec...
cranecode
1,033
cranecode::994e50ac-3103-5335-8f62-b56ca152c9b3
import os import io import time import random import string import cherrypy from typing import Tuple, List # Simulating the analytics module for demonstration purposes class AnalyticsModule: def main(self, bucket_name: str, file_name: str, sample_rate: int, offset: int) -> List[Tuple[str, str, str, str]]: ...
cranecode
2,525
cranecode::82052014-8855-53b0-a229-def64618b98f
from rest_framework import viewsets from rest_framework.permissions import AllowAny from rest_framework.authentication import SessionAuthentication, BasicAuthentication from hospital.models import Hospital from hospital.serializers import HospitalSerializer class HospitalViewSet(viewsets.ModelViewSet): """ A v...
cranecode
423
cranecode::7ed77223-172c-5b9d-950b-7993ed904da3