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
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects...
11
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __a = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: ...
66
0
'''simple docstring''' from importlib import import_module from .logging import get_logger a : int = get_logger(__name__) class a : def __init__( self : Dict , lowercase_ : Optional[Any] , lowercase_ : Any=None ): snake_case_ ...
357
'''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 @datacl...
72
0
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common imp...
27
import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) _UpperCAmelCase = { """sample_size""": 32, """in_channels""": 3, """out_channels""": 3, """layers_per_block""": 2, """num_cla...
140
0
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transfor...
283
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A ={ 'configuration_table_transformer': [ 'TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TableTransformerConfig', 'Tab...
283
1
'''simple docstring''' def UpperCamelCase_( snake_case : int ): '''simple docstring''' snake_case_ = len(snake_case ) while cur > 1: # Find the maximum number in arr snake_case_ = arr.index(max(arr[0:cur] ...
85
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImagePro...
318
0
'''simple docstring''' import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase): def UpperCAmelCase_ ( self )-> Union[str, Any]: ...
358
'''simple docstring''' # 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...
251
0
'''simple docstring''' import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def lowercase ( __magic_name__ ): '''sim...
311
'''simple docstring''' from jiwer import compute_measures import datasets a : List[Any] = "\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improve...
311
1
'''simple docstring''' import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging lowerCamelCase : List[str] = logging.get_log...
362
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Tuple = { "configuration_blenderbot": [ "BL...
114
0
"""simple docstring""" import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_availab...
77
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig 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 ......
41
0
"""simple docstring""" import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_submodules, ) from accelerat...
291
"""simple docstring""" import math from collections.abc import Iterator from itertools import takewhile def __lowercase ( snake_case_ : int ) ->bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 ...
291
1
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, id...
210
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, id...
210
1
import math import random from typing import Any from .hill_climbing import SearchProblem def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase = True , _UpperCamelCase = math.inf , _UpperCamelCase = -math.inf , _UpperCamelCase = math.inf , _UpperCamelCase = -math.in...
279
def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError('''multiplicative_persistence() only accepts integral values''' ) if num < 0: raise ValueError('''multipl...
279
1
from collections.abc import Sequence from queue import Queue class _lowercase : def __init__( self : str , snake_case : Any , snake_case : Optional[int] , snake_case : Tuple , snake_case : Union[str, Any]=None , snake_case : int=None ...
175
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> int: while second != 0: __lowerCamelCase = first & second first ^= second __lowerCamelCase = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod...
67
0
# using dfs for finding eulerian path traversal def __lowerCAmelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None )-> Dict: """simple docstring""" snake_case_ = (path or []) + [u] for v in graph[u]: ...
350
import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def __lowerCAmelCase (SCREAMING_SNAKE_CASE )-> Tuple: """simple docstring""" if ( (cp >= 0X4E00 and cp <= 0X9FFF) or (cp >= 0X3...
267
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __A = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( _lowercase ): '''simple docstring''' lowercase_ = "upernet" d...
10
"""simple docstring""" from __future__ import annotations def snake_case_ ( A_ : str ): '''simple docstring''' return [ord(A_ ) - 96 for elem in plain] def snake_case_ ( A_ : list[int] ): '''simple docstring''' ...
72
0
import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def __lowerCamelCase ( lower...
370
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class a_ : '''simple docstring''' UpperCAmelCase_ = None UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ ...
119
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) _snake_case = { '''configuration_perceiver''': ['''PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP...
283
# 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 re...
283
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision fro...
255
"""simple docstring""" import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def _lowerCAmelCase ( *UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_=True , UpperCamelCase_=2 ): from .. import __version__ __SCREAMING...
255
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase__ = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tok...
104
'''simple docstring''' import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( 'files' ,[ ['full:README.md', 'dataset_infos.json'], ['empty:README...
251
0
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def a__ ( lowerCAmelCase ) -> Tuple: UpperCAmelCase__ : Any = FileLock(str(tmpdir / """foo.lock""" ) ) UpperCAmelCase__ : List[Any] = FileLock(str(tmpdir / """foo.lock""" ...
359
"""simple docstring""" import sys import turtle def a__ ( lowerCAmelCase , lowerCAmelCase ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ) -> None: ...
166
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimen...
308
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=lowercase__ ) class a ( lowercase__ ): """simple docstring""" a : str ...
114
0
'''simple docstring''' from __future__ import annotations __lowercase: int = 10 def SCREAMING_SNAKE_CASE__( _UpperCamelCase : list[int] ) -> list[int]: '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = max(_Uppe...
31
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE__( _UpperCamelCase : list[int | str] ) -> None: '''simple docstring''' create_state_space_tree(_UpperCamelCase , [] , 0 , [0 for i in rang...
31
1
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCAmelCase_ ( _a): lowerCamelCase__ : List[str] = ["image_processor", "tokenizer"] lowerCamelCase__ : List[str] = "CLIPImageProce...
77
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False ...
276
0
'''simple docstring''' from __future__ import annotations _snake_case = list[tuple[int, int]] _snake_case = [ [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, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0...
370
'''simple docstring''' from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TR...
199
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging loggin...
279
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_...
279
1
'''simple docstring''' from __future__ import annotations from typing import Any def snake_case__ ( lowerCamelCase__ : list ) -> int: if not postfix_notation: return 0 A_ : List[str] = {'''+''', '''-''', '''*''', '''/'''} A_...
4
'''simple docstring''' class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , _lowerCamelCase : Union[str, Any] ): """simple docstring""" A_ : Union[st...
4
1
"""simple docstring""" import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings ...
16
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = n __SCREAMING_SNAKE_CASE = ...
267
0
"""simple docstring""" import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __A = { """User-Agent""": """Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36""" """ (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Ed...
365
"""simple docstring""" 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...
254
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a : Optional[Any] = { '''configura...
105
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu __UpperCAmelCase = get_tests_...
119
0
'''simple docstring''' from typing import List from .keymap import KEYMAP, get_character def _UpperCamelCase ( UpperCamelCase__ ): def decorator(UpperCamelCase__ ): UpperCAmelCase__ : Optional[Any] = getattr(UpperCamelCase__ , """handle_ke...
283
'''simple docstring''' import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available...
283
1
from numpy import exp, pi, sqrt def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0.0 , SCREAMING_SNAKE_CASE__ = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import docte...
8
"""simple docstring""" from scipy.stats import pearsonr import datasets _UpperCamelCase: str = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of ...
255
0
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy UpperCAmelCase_ : str = logging.get_logger(__name__) cla...
371
import string def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str ) -> None: """simple docstring""" for key in range(len(string.ascii_uppercase ) ): UpperCamelCase :List[str] = """""" for symbol in message: if symbol in string.ascii_uppercase: UpperC...
62
0
def __UpperCamelCase ( _lowerCAmelCase ) -> Tuple: """simple docstring""" if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): A : Union[str, Any] = f'''Input value of [number={number}] must be an integer''' raise TypeError(_lowerCAmelCase ) ...
116
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqCon...
166
0
'''simple docstring''' import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import T...
363
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaa...
227
0
'''simple docstring''' def UpperCamelCase_ ( _UpperCAmelCase : list , _UpperCAmelCase : list ) -> float: """simple docstring""" _validate_point(_UpperCAmelCase ) _validate_point(_UpperCAmelCase ) if len(_UpperCAmelCase ) != len(_UpperCA...
31
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE : str = loggin...
31
1
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": lowerCamelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, h...
306
def snake_case_ ( lowerCAmelCase_ : int = 200 ): __lowercase : List[str] = [1, 2, 5, 10, 20, 50, 100, 200] __lowercase : List[str] = [0] * (pence + 1) __lowercase : Optional[Any] = 1 # base case: 1 way to make 0 pence ...
306
1
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __lowerCAmelCase ( lowerCamelCase__ ): __lowe...
82
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( ...
199
0
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging __UpperCAmelCase : Optional[int] = logging.get_logger(__name__) ...
293
from __future__ import annotations import numpy as np def A__ ( SCREAMING_SNAKE_CASE__) -> List[str]: return np.maximum(0 , SCREAMING_SNAKE_CASE__) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
293
1
'''simple docstring''' from __future__ import annotations from typing import Any def a_ ( lowerCamelCase : list ): if not postfix_notation: return 0 lowerCAmelCase = {'+', '-', '*', '/'} lowerCAmelCase = [] for token in postfix_notation: ...
4
'''simple docstring''' import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings __snake...
4
1
"""simple docstring""" import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( snake_case_, unit...
268
"""simple docstring""" import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() SCREAMING_SNAKE_CASE__:Dict = logg...
268
1
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( '''The `image_to_image.py` script is outdated. Please use directly `from diffusers import''' ''' StableDiffusionImg2ImgPipeline` instead.''' )
230
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ = { '''configuration_ctrl''': ['''CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CTRLConfig'''], '''tokenization_ctrl''': ['''CTRLTokenizer'''], } ...
230
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_availa...
366
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def lowerCamelCase__ ( a__ : Dataset , a__ : Dict[str, str] ) -> int: UpperCamelCase_ ...
261
0
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.fea...
283
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 = { ...
283
1
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def SCREAMING_SNAKE_CASE ( lowercase_ ) -> bool: """simple docstring""" A__ = 0 A__ ...
231
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def SCREAMING_SNAKE_CASE ( lowercase_ ) -> str: """simple docstring""" if "cls_token" in name: A__ = na...
231
1
from __future__ import annotations def _a ( lowerCamelCase: list[int] , lowerCamelCase: int ) -> List[Any]: '''simple docstring''' __A = 0 __A = len(SCREAMING_SNAKE_CASE__ ) - 1 while i < j: ...
117
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAm...
62
0
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=snake_case_ ) class UpperCAmelCase ( snake_case_ ): _lowercase:...
368
'''simple docstring''' import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, Ber...
220
0
import math def a( A : list , A : int ) -> int: """simple docstring""" a = len(A ) a = int(math.floor(math.sqrt(A ) ) ) a = 0 while arr[min(A , A ) - 1] < x: a...
227
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase: str = logging.get_logger(__name__) _lowercase: List[str] = { "microsoft/trocr-base-handwritten": ( "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json" ), ...
227
1
from __future__ import annotations import time import numpy as np _UpperCAmelCase = [8, 5, 9, 7] _UpperCAmelCase = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] _UpperCAmelCase = [ [3, 2, 1, 4], [0, 2,...
232
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :list[list[int]] ) -> bool: __lowerCAmelCase : Tuple = len(SCREAMING_SNAKE_CASE ) # We need to create solution object to save path. __lowerCAmelCase : str = [[0 for _ in ra...
232
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ...
306
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling...
306
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : str = logging.get_logger(__name__) lowercase : List[Any] = { """microsoft/unispeech-large-1500h-cv""": ( """https://huggingface.co/microsoft/unispe...
285
from bisect import bisect from itertools import accumulate def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: lowercase : Dict = sorted(zip(SCREAMING_SNAKE_CASE__ , SCREAMIN...
285
1
"""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, ) __A = {"""configuration_xglm""":...
293
"""simple docstring""" from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(...
293
1
from __future__ import annotations import math class __a : def __init__( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" _UpperCAmelCase = size # approximate the overall size of segment tree with given value _UpperCAmelC...
185
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": lowerCAmelCase__ :Dict = pd.read_csv('''sample_data.csv''', header=None) lowerCAmelCa...
185
1
"""simple docstring""" 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_mvp impor...
268
"""simple docstring""" import copy import os import cva import numpy as np from matplotlib import pyplot as plt class UpperCamelCase_ : def __init__( self : str ) -> Dict: UpperCAmelCase_ : List[Any] = "" UpperCAmelCase_ : int = ""...
268
1
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTMode...
174
'''simple docstring''' import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attentio...
174
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : Tuple =logging.get_logger(__name__) _UpperCAmelCase : Union[str, Any] ={ """microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""", """microsoft...
262
from __future__ import annotations import requests def lowerCAmelCase ( lowerCAmelCase_ )-> dict: lowerCAmelCase_ : List[Any] = f"""https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty""" return requests.get(lowerCAmelCase_ ).json() def lo...
262
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_c...
133
"""simple docstring""" import baseaa def a__ ( SCREAMING_SNAKE_CASE : str ): '''simple docstring''' return baseaa.baaencode(string.encode("utf-8" ) ) def a__ ( SCREAMING_SNAKE_CASE : bytes ): '''simple docstring''' return baseaa.baadecode(SCREAMI...
133
1
import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCamelCase__ ( __lowerCAmelCase : Union[dict, list, tuple, torch.Tensor] ): ...
231
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) _A = { "configuration_speech_to_text": ["SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Spee...
231
1
def _a ( lowerCamelCase: str , lowerCamelCase: str ) -> str: '''simple docstring''' __A = len(lowerCamelCase_ ) __A = len(lowerCamelCase_ ) __A = ( first_str_length if first_st...
358
import math def _a ( lowerCamelCase: int ) -> bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negativ...
250
0
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 lowerCamelCase : Tuple =datasets.utils.logging.get_logger(__name__) @dataclass cl...
189
"""simple docstring""" import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def _SCREAMING_SNAKE_CASE ( __snake_case : List[Any] ):...
220
0
'''simple docstring''' A : Dict = '''Alexander Joslin''' import operator as op from .stack import Stack def lowerCAmelCase__ ( lowerCamelCase : str ): _A : Dict = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} _A : St...
227
'''simple docstring''' # This code is adapted from OpenAI's release # https://github.com/openai/human-eval/blob/master/human_eval/execution.py import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile def lowerCAmelCase__ ( low...
227
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...
306
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.nu...
306
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) _lowerCamelCase : Optional[int] = { '''vinvino02/glpn-kitti''': '''https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json'...
356
def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ) -> int: '''simple docstring''' if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): raise ValueError("String lengths must match!" ) ...
191
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase = {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP...
256
'''simple docstring''' import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def __lowerCamelCase ( ) -> Any: raise RuntimeError("""CUDA out of memory.""" ) c...
265
0
import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, ...
360
def __lowerCamelCase ( __magic_name__ : int ): if not isinstance(__magic_name__ , __magic_name__ ): a__: List[str] =F"Input value of [number={number}] must be an integer" raise TypeError(__magic_name__ ) if number < 1: a__: ...
42
0
'''simple docstring''' class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ ) -> Dict: __lowerCamelCase : Union[str, Any] = n __lowerCamelCase : List[Any] = [None] * self.n __lowerCamelCas...
185
'''simple docstring''' from numpy import exp, pi, sqrt def UpperCAmelCase__ ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : float = 1.0 ) -> int: return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 ...
185
1
from __future__ import annotations from collections.abc import Callable __magic_name__ = list[list[float | int]] def _lowerCAmelCase ( A__: Matrix , A__: Matrix ): '''simple docstring''' UpperCAmelCase = len(A__ ) UpperCAmelC...
365
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap __magic_name__ = "Usage of script: script_name <size_of_canvas:int>" __magic_name__ = [0] * 100 + [1] * 10 random.shuffle(choice) def _lowe...
152
0
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, sl...
174
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _UpperCAmelCase : Dict = { """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """Mvp...
174
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase ={"configuration_focalnet": ["FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FocalNetConfig"]} try: ...
351
"""simple docstring""" import pytest UpperCAmelCase ="__dummy_dataset1__" UpperCAmelCase ="\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = \"https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/\"\nURLS = {\"train\": REPO_URL + \"wikiann-bn-train.jsonl\", \...
77
0
from __future__ import annotations lowercase_ : Union[str, Any] = [] def __SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ , snake_case_ ): '''simple docstring''' for i in range(len(snake_case_ ) ): if board[row][i] == 1: retur...
133
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch...
133
1
import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" , [ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10...
357
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that ...
59
0
__lowerCamelCase : Tuple = 2_56 # Modulus to hash a string __lowerCamelCase : int = 1_00_00_03 def _snake_case ( lowerCAmelCase : str , lowerCAmelCase : str ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = len(lowerCAmelCase ) SCREAM...
18
'''simple docstring''' _snake_case = 8.3_1_4_4_5_9_8 def _A ( snake_case , snake_case ) -> float: 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" ...
250
0
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json''' ), # S...
216
import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel snake_case_ = False snake_case_ = True snake_case_ = False if __name__ == "__main__": snake_case_ = argparse.Argument...
216
1
def a( A : list ) -> list: """simple docstring""" a = len(A ) for i in range(1 , A ): a = collection[i] a = 0 a = i - 1 while low <= high: a ...
227
_lowercase: Dict = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def a( A : str ) -> int: """simple docs...
227
1
'''simple docstring''' class __lowerCamelCase : """simple docstring""" def __init__( self : List[str]): _A : Tuple = {} def A ( self : List[str]): print(self.vertex) for i in self.vertex: print...
363
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaa...
227
0
"""simple docstring""" import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate SCREAMING_SNAKE_CASE = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow(""...
247
"""simple docstring""" 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 ...
191
0
"""simple docstring""" from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split UpperCAmelCase = datasets.load_iris() UpperCAmelCase = np.array(data['''data''']) UpperCAmelCase = np.array(data['''target'''...
354
"""simple docstring""" from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transfor...
172
0
"""simple docstring""" import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging a = logging.get_logger(__nam...
315
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transfor...
42
0
lowerCamelCase_ : Tuple = """Input must be a string of 8 numbers plus letter""" lowerCamelCase_ : Tuple = """TRWAGMYFPDXBNJZSQVHLCKE""" def lowerCAmelCase( __lowerCamelCase ): if not isinstance(__lowerCamelCase , __lowerCamelCase ): __a = f'''E...
350
def lowerCAmelCase( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): # Return True if there is node that has not iterated. __a = [False] * len(__lowerCamelCase ) __a = [] queue.append(__lowerCamelCase ) ...
197
0
from __future__ import annotations import time UpperCAmelCase_ : str = list[tuple[int, int]] UpperCAmelCase_ : Dict = [ [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, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1,...
38
'''simple docstring''' import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets a_ = datasets.logging.get_logger(__name__) a_ = '\\n@inproceedings{bleurt,\n title={BLEURT: Learning Robust Metrics for Text Generation},\n...
152
0
_SCREAMING_SNAKE_CASE = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _SCREAMING_SNAKE_CASE = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def snake_case ( snake_case__ :dict[int, list[int]] , snake_case__ :int , snake_case__ ...
81
import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup _SCREAMING_SNAKE_CASE = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.195...
81
1
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.huggingface ...
65
"""simple docstring""" import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def a_ ( _lowerCAmelCase : str ): '''simple docstring''' lowercase__ : int = args.pruning_method ...
77
0
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from tran...
119
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 BatchFeature from ...uti...
119
1
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging imp...
91
import argparse import re from typing import Dict import torch from datasets import Audio, Dataset, load_dataset, load_metric from transformers import AutoFeatureExtractor, pipeline def UpperCamelCase ( __lowerCamelCase : Dataset , __lowerCamelCase : Dict[str, str] ): ...
59
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase = { "configuration_altclip": [ "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "Al...
368
import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) UpperCamelCase = { '''sample_size''': 32, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2...
125
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set...
216
def __UpperCamelCase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ): __a : str = len(lowerCAmelCase__ ) __a : Optional[int] = [] for i in range(len(lowerCAmelCase__ ) - pat_len + 1 ): __a : str = True for j in range(lowerCAmelCase__ ): if s[i + j]...
216
1
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir,...
165
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _SCREAMING_SNAKE_CASE = {"""configuration_yolos""": ["""YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """YolosConfig""", """YolosOnnxConfig"""]} try: if not is_visio...
165
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, ...
144
import random def a( A : Optional[Any] , A : Optional[Any] , A : str ) -> List[Any]: """simple docstring""" a = a[left_index] a = left_index + 1 for j in range(left_index + 1 , A ): if a...
227
0
'''simple docstring''' import os import string import sys __a = 1 << 8 __a = { "tab": ord('\t'), "newline": ord('\r'), "esc": 27, "up": 65 + ARROW_KEY_FLAG, "down": 66 + ARROW_KEY_FLAG, "right": 67 + ARROW_KEY_FLAG, "left": 68 + ARROW_KEY_FLAG, "mod_int": 91, ...
368
'''simple docstring''' import baseaa def __UpperCAmelCase ( a_: str ): return baseaa.baaencode(string.encode("utf-8" ) ) def __UpperCAmelCase ( a_: bytes ): return baseaa.baadecode(a_ ).decode("utf-8" ) if __name__ == "__main__": ...
17
0
'''simple docstring''' def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str: if not (isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ )): raise ValueError('longest_common_substring() takes two strings fo...
89
"""simple docstring""" def __UpperCAmelCase ( ) -> int: '''simple docstring''' return [ a * b * (10_00 - a - b) for a in range(1 , 9_99 ) for b in range(UpperCAmelCase_ , 9_99 ) if (a * a + b * b == (10_00 - a - b) ** 2) ][0] ...
172
0
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Tuple: __lowerCamelCase : Any = { 'en': 'Machine learning is great, isn\'t it?', ...
113
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...
113
1
def _snake_case ( lowerCAmelCase : int = 2_0_0_0_0_0_0 ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = [0 for i in range(n + 1 )] SCREAMING_SNAKE_CASE_ : Optional[Any] = 1 SCREAMING_SNAKE_CASE_ : Tuple = 1 for i in range(2 , int(n**0....
18
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : List[Any] =logging.get_logger(__name__) __lowerCAmelCase : Union[str, Any] ={ """s-JoL/Open-Llama-V1""": """https://huggingface.co/s-J...
197
0
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device _SCREAMING_SNAKE_CASE = False class a ( unittest...
81
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler...
81
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class __A ( metaclass=_SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["torch", "transformers", "onnx"] def __init__( self , *__A , *...
81
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[Tr...
81
1
'''simple docstring''' import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgum...
351
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging lowerCAmelCase__ ...
52
0
def UpperCamelCase ( snake_case__ : int , snake_case__ : int ) -> int: return int((input_a, input_a).count(1 ) != 0 ) def UpperCamelCase ( ) -> None: assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) =...
119
from __future__ import annotations from typing import Any class lowerCAmelCase_ : def __init__( self, SCREAMING_SNAKE_CASE_ ) -> None: UpperCamelCase : Any = num_of_nodes UpperCamelCase : list[list[int]] = [] UpperCamelCase : dict[...
119
1
'''simple docstring''' from abc import ABC, abstractmethod from typing import List, Optional class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self ): """simple docstring""" self.test() def _lowercase ...
358
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", ...
229
0
"""simple docstring""" from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class __A : """simple docstring""" __lowerCAmelCase ...
81
'''simple docstring''' import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax ...
125
0
'''simple docstring''' import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging __lowerCamelCase = logging.get_logger(__name__) def UpperCAmelCase__ ( UpperCAmelCase__ ) -> Optional...
366
'''simple docstring''' import argparse import glob import logging import os import sys import time from collections import defaultdict from pathlib import Path from typing import Dict, List, Tuple import numpy as np import pytorch_lightning as pl import torch from callbacks import SeqaSeqLoggingCallback, get_...
101
0
"""simple docstring""" from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand A_ : List[Any] = logging.get_logger(__name__) # pylint: disable=inv...
165
"""simple docstring""" def A ( snake_case__ ): '''simple docstring''' assert isinstance(snake_case__ , snake_case__ ), f"""The input value of [n={number}] is not an integer""" if number == 1: return 2 elif number < 1: SCREAMING_SNAKE_CASE__ ...
165
1
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py _snake_case = "." if __name__ == "__main__": _snake_case = os.path.join(REPO_PATH, '''utils/documentation_tests.txt''') _snake_case ...
366
import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_devic...
342
0