code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" def _A ( lowercase ): """simple docstring""" a =int(lowercase ) if n_element < 1: a =ValueError('''a should be a positive number''' ) raise my_error a =[1] a , a , a =(0, 0, 0) a ...
81
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __A ( _SCREAMING_SNA...
81
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers im...
108
"""simple docstring""" import numpy as np def a__ ( __SCREAMING_SNAKE_CASE ) -> np.array: return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
108
1
from collections.abc import Iterable from typing import Any class UpperCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] , UpperCamelCase__ : int | None = None ) -> List[Any]: """simple docstring""" __...
88
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDi...
88
1
"""simple docstring""" from __future__ import annotations def lowercase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ): '''simple docstring''' return [ord(__UpperCAmelCase ) - 96 for elem in plain] def lowercase ( _SCREAMING_SNAKE_CASE :...
356
"""simple docstring""" import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def ...
326
0
import math snake_case_ = 10 snake_case_ = 7 snake_case_ = BALLS_PER_COLOUR * NUM_COLOURS def lowerCamelCase__ ( snake_case_ : int = 20 ) -> str: __snake_case = math.comb(snake_case_ , snake_case_ ) __snake_case...
24
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTester...
32
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCamelCase__ = { '''configuration_layoutlmv2''': ['''LAYOUTLMV2_PRETRAIN...
359
'''simple docstring''' def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> float: UpperCAmelCase__ : Tuple = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): ...
299
0
import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMix...
274
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import ...
299
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING snake_case__ = logging.get_logger(__name__) snake_case__ = { '''ut/deta''': '''https://huggingface.co/ut/deta/resolve...
367
'''simple docstring''' from __future__ import annotations class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[int] , _lowerCamelCase : int ): """simple docstring""" ...
4
0
'''simple docstring''' __lowerCAmelCase : dict[str, float] ={ "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, } __lowerCAmelCase : dict[str, float] ={ "km/h": 1.0, "m/s": 0.277777778, "mph": 0.621371192, "knot": 0.539956803, } def UpperCamelCas...
237
'''simple docstring''' import functools def UpperCamelCase ( _lowerCamelCase : str , _lowerCamelCase : str ): A__ = len(_lowerCamelCase ) A__ = len(_lowerCamelCase ) @functools.cache def min_distance(_lowerCamelCase :...
237
1
def _a ( SCREAMING_SNAKE_CASE : int ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError('''multiplicative_persistence() only accepts integral values''' ) if num < 0: raise ValueError('''multiplicative_persis...
51
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging __UpperCamelCase : List[Any] = logging.get_logger(__name__) def _a ( SCREAMING_SNAKE_CASE : Union[tf.Tensor, np.ndarray] ): """simple docstring""" if isinst...
51
1
import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class lowerCAmelCase__ ( a): '''simp...
11
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available lowerCAmelCase__ = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvai...
11
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_pegasus import PegasusTokenizer else: __lowerCa...
10
import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCa...
10
1
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import ...
153
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, ...
110
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a ( _SCREAMING_SNAKE_CASE ): _lowerCAmelCase = ["""image_processor""", """tokenizer"""] _lowerCAmelCase = """AutoImageProcessor""" _lowerCAmelCase = """AutoTokenize...
362
'''simple docstring''' import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUE...
104
0
"""simple docstring""" from math import ceil def _a ( _SCREAMING_SNAKE_CASE = 1_001 ) -> Optional[int]: snake_case_ = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): snake_case_ = 2 * i + 1 snake_case_ = 2 * i ...
347
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = int(number**0.5 ) return number == sq * sq def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCa...
299
0
import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor __SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) class lowercase_ ( __snake_case ): def __init__( self , *lowercase_ , **lowercase_ )...
284
import logging from transformers import PretrainedConfig __SCREAMING_SNAKE_CASE : Any = logging.getLogger(__name__) __SCREAMING_SNAKE_CASE : int = { 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/mai...
284
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ : str = logging.get_logger(__name__) snake_case_ : Tuple = {} class lowercase__ ( lowercase ): lowercase__ = """llama""" lowercase__ = ["""pas...
83
'''simple docstring''' import os from datetime import datetime as dt from github import Github snake_case_ : Any = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def A__ ( ): ...
83
1
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class UpperCamelCase : def __init__( self) -> Dict: snake_case_ = {} def a_ ( self, lowerCAmelCase__, lowerCAmelCase_...
312
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, ...
312
1
from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, ...
52
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline __lowerCamelCase : str = logging.get_logger(__name__) # pylint: disable=invalid-name class A__ ( __snake_...
52
1
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : int = 1_0_0_0_0_0_0 ) ->int: A__ : int = set(range(3, UpperCAmelCase__, 2 ) ) primes.add(2 ) for p in range(3, UpperCAmelCase__, 2 ): if p not in primes: ...
353
"""simple docstring""" import os from distutils.util import strtobool def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Optional[Any] ) ->List[str]: for e in env_keys: A__ : List[Any] = int(os.environ.get(UpperCAme...
296
0
import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging fr...
245
import os # Precomputes a list of the 100 first triangular numbers a : Optional[Any] = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def lowerCAmelCase_ (): """simple docstring""" UpperCAmelCase_: Any = os.path.dirname(os.path.real...
147
0
import itertools import random import unittest import numpy as np from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor from transformers.testing_utils import require_torch, slow from ...test_sequence_feature_extraction_common import SequenceFeatu...
213
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _SCREAMING_SNAKE_CASE : int = { "configuration_timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"], } try: if not is_torch_availab...
213
1
"""simple docstring""" def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = [] UpperCAmelCase = [] UpperCAmelCase = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, ...
78
"""simple docstring""" import colorsys from PIL import Image # type: ignore def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ ): UpperCAmelCase = x UpperCAmelCase = y for step in range(lowercase_ ): # noqa: B007 ...
78
1
import cva import numpy as np class A__ : def __init__( self , UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: '''simple docstring''' if k in (0.04, 0.06): A_ = k A_ = window_size else: ...
358
'''simple docstring''' def UpperCAmelCase__ ( UpperCAmelCase__ = 1_00 ) -> int: A_ = n * (n + 1) * (2 * n + 1) / 6 A_ = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
101
0
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='''session''' ) def UpperCamelCase ( ): '''simple docst...
101
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ :Dict = logging.get_logger(__name__) lowercase__ :Optional[int] = { "BAAI/AltCLIP": "https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json", # See a...
101
1
'''simple docstring''' import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import Config...
362
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params i...
199
0
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { """microsoft/unispeech-large-1500h-cv""": ( """https://huggingface.co/microsoft/unispeech-large-1500h-cv...
66
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_i...
248
0
'''simple docstring''' import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modelin...
352
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase = {"""configuration_sew""": ["""SEW_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SEWConfig"""]} try: if not is_torch_available(): raise OptionalDepend...
48
0
from maths.prime_factors import prime_factors def a__ ( A_ ): '''simple docstring''' if not isinstance(A_, A_ ): __magic_name__ = f'''Input value of [number={number}] must be an integer''' raise TypeError(A_ ) if number < 1: raise...
88
import argparse import datetime def lowerCAmelCase__( lowercase : str ) -> str: __snake_case : int = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } __snake_...
326
0
"""simple docstring""" def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = [] UpperCAmelCase = [] UpperCAmelCase = { """^""": 3, """*""": 2, ...
353
"""simple docstring""" from __future__ import annotations def _lowerCAmelCase ( lowerCAmelCase = 4 ): '''simple docstring''' UpperCAmelCase = abs(lowerCAmelCase ) or 4 return [[1 + x + y * row_size for x in range(lowerCAmelCase )] for y in ra...
248
0
import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, ...
50
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return [tuple(a_ )] __A = [] def generate(a_ , a_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , ...
15
0
'''simple docstring''' import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOC...
107
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all file...
107
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __A = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else...
164
'''simple docstring''' import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger(__name__) def _A ( lowercase__ ): lowercase__ ...
164
1
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer ...
355
from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _in...
167
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, ...
309
def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = { '''^''': 3, '''*''': 2, '''/''': 2, '''%''': 2, '''+''': 1, '''-''': 1, } # Priority of each operator SCREAMING_SNAKE_CASE_ ...
299
0
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance lowerCAmelCase_ = 6_3_7_8_1_3_7.0 lowerCAmelCase_ = 6_3_5_6_7_5_2.3_1_4_2_4_5 lowerCAmelCase_ = 6_37_81_37 def snake_case( __magic_name__ , __magic_name__ , __ma...
116
import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFe...
116
1
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, ...
11
import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTokenizerFast from...
36
0
'''simple docstring''' import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import...
174
'''simple docstring''' import os lowerCamelCase_ = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 1_00, '''D''': 5_00, '''M''': 10_00} def __lowercase ( __lowercase ) -> int: '''simple docstring''' _A = 0 _A = 0 whi...
174
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase : str = { 'configuration_git': ['GIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GitConfig', 'GitVisionConfig'], 'processing_git': ['GitPro...
3
def lowercase( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> bool: '''simple docstring''' return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(UpperCamelCase_ ) ) def lowercase( UpperCamelCase_ ,...
343
0
import os def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Tuple ) -> int: UpperCAmelCase_ = len(grid[0] ) UpperCAmelCase_ = len(__UpperCamelCase ) UpperCAmelCase_ = 0 UpperCAmelCase_ = 0 UpperC...
177
from __future__ import annotations _lowerCamelCase = list[list[int]] # assigning initial values to the grid _lowerCamelCase = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0...
177
1
"""simple docstring""" import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager imp...
179
"""simple docstring""" from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_util...
179
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ = { "configuration_mobilenet_v2": [ "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config", "Mob...
371
'''simple docstring''' import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PA...
43
0
'''simple docstring''' from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function snake_case_ : int = 1.0_54_57_18_17e-34 # unit of ℏ : J * s snake_case_ : Optional[int] = 3e8 # unit of c : m * s^-1 ...
83
from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import Config...
257
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenizat...
348
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device ...
348
1
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to tak...
244
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : Any = logging.get_logger(__name__) A_ : Optional[Any] = { 'google/pegasus-large': 'https://huggingface.co/google/pegasus-large/resolve/main/config.json', # See all PEGASUS models at https...
333
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "microsoft/beit-base-patch16-224-pt22k"...
362
_snake_case = 8.3144598 def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' if temperature < 0: raise Exception("Temperature cannot be less than 0 K" ) if molar_mass <= 0: raise Exception("Molar mass cannot be less than ...
300
0
'''simple docstring''' import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __lowercase : Dict = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'te...
27
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVeca...
27
1
import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _A (...
131
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaa...
131
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pi...
120
'''simple docstring''' import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecu...
120
1
'''simple docstring''' from __future__ import annotations import math def _lowerCAmelCase ( __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : Union[str, Any] , __snake_case : Optional[Any] , __snake_case : ...
365
'''simple docstring''' import itertools import math def _lowerCAmelCase ( __snake_case : int ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Ne...
190
0
'''simple docstring''' def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Tuple = [0 for i in range(r + 1 )] # nc0 = 1 UpperCAmelCase__ : Tuple = 1 for i in range(1 , n + 1 ): # to...
163
"""simple docstring""" from __future__ import annotations def __A ( a_ :str , a_ :str) -> bool: __a : Optional[Any] = get_failure_array(a_) # 2) Step through text searching for pattern __a , __a : Union[str, Any] = ...
160
0
import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() _A = logging.get_l...
366
"""simple docstring""" import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore _A = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" _A = [file for file in filepaths i...
205
0
lowerCAmelCase__ = [ 'Audio', 'Array2D', 'Array3D', 'Array4D', 'Array5D', 'ClassLabel', 'Features', 'Sequence', 'Value', 'Image', 'Translation', 'TranslationVariableLanguages', ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ...
11
from argparse import ArgumentParser from .add_new_model import AddNewModelCommand from .add_new_model_like import AddNewModelLikeCommand from .convert import ConvertCommand from .download import DownloadCommand from .env import EnvironmentCommand from .lfs import LfsCommands from .pt_to_tf import PTtoTFCommand from ....
231
0
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .t...
76
"""simple docstring""" def _snake_case ( UpperCamelCase : Tuple , UpperCamelCase : Tuple , UpperCamelCase : Tuple=False ): if isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(UpperCamelCase , UpperCamelCase ): UpperCAmelCase :...
76
1
import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) snake_case : int = loggin...
94
import math lowerCAmelCase__ :Optional[int] = 1_0 lowerCAmelCase__ :Optional[Any] = 7 lowerCAmelCase__ :Union[str, Any] = BALLS_PER_COLOUR * NUM_COLOURS def lowerCAmelCase__ ( a__: int = 2_0 ) -> str: '''simple docstring''' _UpperCAmelCase ...
329
0
import gc import unittest import numpy as np import torch from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params impo...
366
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/confi...
211
0
import operator as op def A ( a_ ) -> List[Any]: __UpperCamelCase : List[str] =[] __UpperCamelCase : Union[str, Any] =lambda a_ ,a_ : int(x / y ) # noqa: E731 integer division operation __UpperCam...
71
a_ = 8.314_4598 def lowerCamelCase__ ( _a , _a): if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_ma...
76
0
from dataclasses import dataclass from typing import Optional import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .modeling_utils import ModelMixin @dataclass class __lowerCAme...
158
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase ( lowerCAmelCase): _a = (DDIMParallelScheduler,) _a = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def SCREAMING_SNAKE_CAS...
158
1
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, ...
48
import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE = None ,_SCREA...
48
1
"""simple docstring""" from argparse import ArgumentParser from .add_new_model import AddNewModelCommand from .add_new_model_like import AddNewModelLikeCommand from .convert import ConvertCommand from .download import DownloadCommand from .env import EnvironmentCommand from .lfs import LfsC...
215
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransfor...
215
1
"""simple docstring""" import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class ...
64
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : list ): """simple docstring""" if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] _snake_case : List[Any] = [] def generate(snake_case__ : int , snake_case__...
64
1
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class UpperCamelCase_ ( __lowercase ): lowerCAmelCase_ = CustomTokenizer pass
352
from cva import destroyAllWindows, imread, imshow, waitKey def lowerCamelCase__ ( UpperCamelCase__ : Dict ) -> Optional[Any]: '''simple docstring''' _snake_case , _snake_case = img.shape[0], img.shape[1] # converting each pixel's colo...
295
0
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTo...
225
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor lowerCamelCase__ : List[str] = logging.get_logger(__name__) class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( sel...
225
1
"""simple docstring""" from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration a :int = HfArgumentParser(InitializationArguments) a :Union[str, Any] = parser.parse_args() # Load codeparrot tokenizer tr...
56
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a :Dict = { "configuration_rag": ["RagConfig"], "retrieval_rag": ["RagRetriever"], "tokenization_rag": ["RagTokenizer"], } try: if no...
56
1
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A_ : Any = logging.get_logger(__nam...
192
"""simple docstring""" def A ( snake_case__ = 50 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in r...
165
0
import warnings from ...utils import logging from .image_processing_owlvit import OwlViTImageProcessor UpperCAmelCase__ = logging.get_logger(__name__) class __lowerCAmelCase ( A ): def __init__( self : int , *A : List[Any] , **A : int) ->...
290
from binascii import hexlify from hashlib import shaaaa from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 UpperCAmelCase__ = { # 1536-bit 5: { "prime": int( "FFFFFFFFFFFF...
290
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # 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 applicab...
6
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def __lowerCAmelCase ( a__ , a__ , a__=1024 , a__=1024 , a__=False , **a__ ) -> Optional[Any]: __...
6
1
"""simple docstring""" def _lowerCamelCase( a , a = False ): if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 1_0 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3_3_1_7_0_4_4_0_6...
268
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case__ ( snake_case_ ...
268
1
import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class a_ ( a__ , a__ ...
313
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''') class a_ : """simple d...
313
1
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf __SCREAMING_SNAKE_CASE : str = logging.get_logge...
284
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __SCREAMING_SNAKE_CASE : Optional[int] = { 'configuration_distilbert': [ 'DISTIL...
284
1
from datetime import datetime import matplotlib.pyplot as plt import torch def UpperCamelCase ( _A ): """simple docstring""" for param in module.parameters(): __magic_name__ : List[Any] = False def UpperCamelCase ( ): ...
342
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __magic_name__: str = logging.get_logger(__name__) __magic_name__: ...
342
1
import sys _lowerCAmelCase : List[str] = ( '''73167176531330624919225119674426574742355349194934''' '''96983520312774506326239578318016984801869478851843''' '''85861560789112949495459501737958331952853208805511''' '''12540698747158523863050715693290963295227443043557''' '''66896648...
364
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCAmelCase : Dict = { '''configuration_blip''': [ '''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', ''...
70
0
from typing import Dict from .base import GenericTensor, Pipeline class _SCREAMING_SNAKE_CASE ( snake_case_ ): def SCREAMING_SNAKE_CASE_( self , lowercase=None , lowercase=None , lowercase=None , **lowercase ) -> str: if tokenize_kwargs is None: ...
19
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.te...
9
0
'''simple docstring''' import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision...
61
'''simple docstring''' import os def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : Any ): '''simple docstring''' UpperCAmelCase__ = len(grid[0] ) UpperCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = 0 UpperCAmelCase__ ...
61
1
"""simple docstring""" def snake_case ( A__ ,A__ ): return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def snake_case ( A__ ,A__=0 ): return sorted(A__ ,key=lambda A__ : x[column] ) def snake_case ( A__ ,A__ ,A__=float("inf" ) ...
268
"""simple docstring""" import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ = lo...
268
1
'''simple docstring''' from __future__ import annotations def __a ( UpperCAmelCase ) ->list[int]: """simple docstring""" return [ord(UpperCAmelCase ) - 96 for elem in plain] def __a ( UpperCAmelCase ) ->str: """simple docstring""" return "".join...
370
'''simple docstring''' import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' ...
337
0
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as Prophet...
176
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = {"""vocab_file""": """vocab.txt"""} __snake_case ...
176
1
def __lowercase ( _UpperCamelCase ) ->int: """simple docstring""" lowercase : list[list[int]] = [[0 for _ in range(_UpperCamelCase )] for _ in range(m + 1 )] for i in range(m + 1 ): lowercase : Union[str, Any] = ...
357
# flake8: noqa # Lint as: python3 __a = [ '''VerificationMode''', '''Version''', '''disable_progress_bar''', '''enable_progress_bar''', '''is_progress_bar_enabled''', '''experimental''', ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progre...
173
0
import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppToken...
50
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, re...
50
1
import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_con...
356
from __future__ import annotations lowerCAmelCase__ = tuple[int, int, int] lowerCAmelCase__ = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase lowerCAmelCase__ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # -------------------------- default selecti...
119
0
"""simple docstring""" import argparse import os import re __lowercase = '''src/transformers/models/auto''' # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict __lowercase = re.com...
40
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return x + 2 class UpperCamelCase_ ( unittest.TestCase): ...
54
0
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor impor...
356
'''simple docstring''' import os def lowerCamelCase (): with open(os.path.dirname(_SCREAMING_SNAKE_CASE ) + '/p022_names.txt' ) as file: __a : List[Any] = str(file.readlines()[0] ) __a : str = names.replace('"' , '' ).split('...
294
0
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_...
2
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklea...
266
0
'''simple docstring''' from collections.abc import Iterable from typing import Any class A_ : def __init__( self : Dict , snake_case_ : int | None = None ): _UpperCAmelCase = value _UpperCAmelCase = None # Added in order to delete...
156
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch...
156
1
'''simple docstring''' import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingf...
97
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase_ = {'configuration_xgl...
243
0
from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ......
352
"""simple docstring""" import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __UpperCamelCase : List[Any] = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets b...
309
0
'''simple docstring''' import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( l...
55
'''simple docstring''' a_ : str = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ a_ : Any...
55
1
from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import Padd...
365
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torc...
165
0
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. _snake_case = 10 def _UpperCamelCase ( snake_case__, snake_case__, snake_case__, snake_case__ ) -...
157
def _UpperCamelCase ( snake_case__ ) -> int: __UpperCAmelCase : Union[str, Any] = abs(snake_case__ ) __UpperCAmelCase : Dict = 0 while n > 0: res += n % 10 n //= 10 return res def _UpperCamelCas...
157
1
"""simple docstring""" import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast _a = datasets.utils.logging.get_logger(__name__) @dataclass class _lowerCAmelCas...
144
"""simple docstring""" import numpy # List of input, output pairs _a = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) _a = (((5_15, 22, 13), 5_55), ((61, 35, 49), 1_50)) _a = [2, 4, 1, 5] _a = len(...
144
1
"""simple docstring""" from __future__ import annotations import bisect def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 0 , _UpperCamelCase = -1 ): if hi < 0: __lowerCAmelCase : Tuple = len(_UpperCamelCase ) while lo < hi: __l...
86
'''simple docstring''' import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class _a ( unittest.TestCase ...
251
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # 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 app...
257
from graphs.minimum_spanning_tree_kruskal import kruskal def A__ ( ): SCREAMING_SNAKE_CASE_ = 9 SCREAMING_SNAKE_CASE_ = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], ...
257
1
"""simple docstring""" from __future__ import annotations a :Optional[int] = "Muhammad Umer Farooq" a :Any = "MIT" a :Optional[int] = "1.0.0" a :Dict = "Muhammad Umer Farooq" a :Dict = "contact@muhammadumerfarooq.me" a :List[str] = "Alpha" import r...
132
"""simple docstring""" import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( Autoencoder...
132
1
from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_...
124
import numpy class UpperCAmelCase : '''simple docstring''' def __init__( self : List[str] ,A : numpy.ndarray ,A : numpy.ndarray ): __A = input_array # Random initial weights are assigned where first argument is the # number of nodes in previou...
124
1
"""simple docstring""" from __future__ import annotations class _UpperCAmelCase: def __init__( self , __a=None) -> List[Any]: '''simple docstring''' _UpperCamelCase = data _UpperCamelCase = None def...
194
# Lint as: python3 import itertools import os import re lowerCamelCase = re.compile(R'([A-Z]+)([A-Z][a-z])') lowerCamelCase = re.compile(R'([a-z\d])([A-Z])') lowerCamelCase = re.compile(R'(?<!_)_(?!_)') lowerCamelCase = re.compile(R'(_{2,})') lowerC...
199
0
from __future__ import annotations def UpperCamelCase ( snake_case__ : Union[str, Any] , snake_case__ : List[str] = None , snake_case__ : Any = None , snake_case__ : str = False , ) -> tuple[int, float, str]: UpperCamelCase : Dict = cipher_alphabet or ...
364
import re def UpperCamelCase ( snake_case__ : str ) -> str: if len(re.findall('[ATCG]' , snake_case__ ) ) != len(snake_case__ ): raise ValueError('Invalid Strand' ) return dna.translate(dna.maketrans('ATCG' , 'TAGC' ) ) if __name__ == "__main...
103
0
import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils...
275
def _lowercase ( lowercase__ , lowercase__ ): if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__":...
275
1
'''simple docstring''' import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers....
357
'''simple docstring''' import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX...
217
0
import argparse UpperCamelCase = """docs/source/_static/js/custom.js""" def __lowerCamelCase ( snake_case__ ) -> Optional[int]: """simple docstring""" with open(UpperCAmelCase_ ,encoding="""utf-8""" ,newline="""\n""" ) as f: ...
306
'''simple docstring''' from __future__ import annotations from typing import Generic, TypeVar a_ : List[str] = TypeVar("""T""") class snake_case ( Generic[T] ): """simple docstring""" def __init__( self , UpperCamelCase ): ...
55
0
"""simple docstring""" import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # C...
64
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise Optiona...
64
1