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""" import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase_ = get_tests_dir('fixtures/test_sentencep...
243
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) __lowerCAmelCase : str = {'openai-gpt': 'https://huggingface.co/openai-gpt/resolve/main/config.json'} class snake_case__ (_Up...
107
0
"""simple docstring""" def __lowerCamelCase ( a_ : int ) -> list: __SCREAMING_SNAKE_CASE :Optional[int] = [0] * len(__UpperCAmelCase ) for i in range(1 , len(__UpperCAmelCase ) ): # use last results for b...
352
"""simple docstring""" import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class _SCREAMING_SNAKE_CASE( unitt...
239
0
"""simple docstring""" import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet i...
266
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extracti...
266
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __snake_case = { '''configuration_layoutlmv2''': ['''LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LayoutLMv2Con...
352
import sys def lowerCAmelCase_ ( __lowerCAmelCase )-> Any: '''simple docstring''' UpperCAmelCase : Optional[Any] =len(__lowerCAmelCase ) UpperCAmelCase : List[str] =[[0 for x in range(__lowerCAmelCase )] for x in range(__lowerCAmelCase )] ...
78
0
A__ = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ A__ ...
82
"""simple docstring""" from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration lowerCamelCase_ : Any = HfArgumentParser(InitializationArguments) lowerCamelCase_ : Union[str, Any] ...
286
0
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, ...
357
from __future__ import annotations import time import numpy as np _lowerCAmelCase : List[str] = [8, 5, 9, 7] _lowerCAmelCase : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] _lowerCAmelCase : List[Any] ...
308
0
from __future__ import annotations __UpperCAmelCase = list[tuple[int, int]] __UpperCAmelCase = [ [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...
29
from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def lowerCamelCase__ ( a = True , *a , **a ) -> Optional[Any]: if not is_tqdm_available(): raise ImportError('''Accelerate\'s `tqdm` modul...
121
0
"""simple docstring""" import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate imp...
320
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_...
320
1
"""simple docstring""" # Copyright 2022 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/lic...
105
"""simple docstring""" import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefm...
105
1
from collections import defaultdict def lowerCAmelCase__ ( _a : str , _a : str ): snake_case_ : Optional[Any] = first_str.lower().strip() snake_case_ : Dict = second_str.lower().strip() # Remove whitespace snake_case_ : Tuple = ...
361
def lowerCAmelCase__ ( _a : float , _a : float ): 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__": ...
36
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase : Any = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_to...
99
'''simple docstring''' def lowerCAmelCase_ ( _lowerCamelCase: int ): assert ( isinstance(_lowerCamelCase , _lowerCamelCase ) and number_of_steps > 0 ), F"number_of_steps needs to be positive integer, your input {number_of_steps}" if number_of_steps == 1: return 1 __S...
112
0
'''simple docstring''' import argparse import json import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( VideoMAEConfig, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEImageProcessor, ) ...
222
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_availabl...
222
1
'''simple docstring''' from typing import Union import fire import torch from tqdm import tqdm def __magic_name__( lowerCamelCase, lowerCamelCase = "cpu", lowerCamelCase = None): __lowerCAmelCase = torch.load(lowerCamelCase, map_location=lowerCamelCase) for k, v in tqdm(...
174
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _UpperCAmelCase : Optional[Any] = { """config...
174
1
"""simple docstring""" import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import Mo...
350
"""simple docstring""" print((lambda quine: quine % quine)("print((lambda quine: quine %% quine)(%r))"))
316
0
from math import factorial class lowerCamelCase__: def __init__( self: List[str] , UpperCamelCase_: str , UpperCamelCase_: int ): __lowerCamelCase = real if isinstance(UpperCamelCase_ , UpperCamelCase_ ): __lowerC...
12
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, resize, to_channel_dim...
62
0
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: lowercase__ :...
367
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __A ( A_ ...
302
0
'''simple docstring''' import math from datetime import datetime, timedelta def lowerCamelCase ( UpperCAmelCase__ : int ) -> datetime: lowercase_ : int = year % 19 lowercase_ : List[Any] = year % 4 lowercase_ : int...
239
'''simple docstring''' def lowerCamelCase ( UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
239
1
from __future__ import annotations from functools import lru_cache from math import ceil UpperCAmelCase__ = 100 UpperCAmelCase__ = set(range(3, NUM_PRIMES, 2)) primes.add(2) UpperCAmelCase__ = 42 for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: cont...
361
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def A ( ) -> tuple[list[int], int]: '''simple docstring''' _UpperCAmelCase = [randint(-1_000 , 1_000 ) for i in range(10 )] _Up...
290
0
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @requ...
294
"""simple docstring""" import os import time import numpy as np import onnxruntime as ort snake_case_ = """1""" snake_case_ = """0""" snake_case_ = """1""" snake_case_ = ort.SessionOptions() snake_case_ = ort.GraphOptimiz...
78
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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __ma...
356
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo __magic_name__: Optional[Any] = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n ...
138
0
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ...
95
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import requir...
308
0
from datetime import datetime import requests def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :str ) -> bytes: __lowerCAmelCase : List[Any] = """https://downloadgram.net/wp-json/wppress/video-downloader/video?url=""" __lowerCAmelCase : Dict = requests.get(b...
232
import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_avail...
232
1
"""simple docstring""" import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate imp...
320
"""simple docstring""" def A_ ( ): """simple docstring""" _a = [] _a = 1 while len(_lowerCAmelCase ) < 1e6: constant.append(str(_lowerCAmelCase ) ) i += 1 _a = ''''''.join(_lowerCAmelCase ) return ( int(...
320
1
"""simple docstring""" import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase ...
234
"""simple docstring""" import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() _UpperCamelCase ...
234
1
def _lowerCAmelCase (_lowerCAmelCase = 50): UpperCamelCase_ = [[0] * 3 for _ in range(length + 1)] for row_length in range(length + 1): for tile_length in range(2 , 5): for tile_start in range(row_length - tile_length + 1): differe...
128
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 )]), ({"num_s...
36
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { "studio-ousia/luke-base": "https://huggingface.co/studio-ousia/luke-base/resolve/mai...
3
'''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 __lowerCamelCase ( __lowerCA...
3
1
import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home _UpperCAmelCase : Optional[int] = HUGGINGFACE_HUB_CACHE _UpperCAmelCase : List[str] = "config.json" _UpperCAmelCase : Union[str, Any] = "diffusion_pytorch_model.bin" _UpperCAmelCase ...
222
def A ( lowercase ) -> list: '''simple docstring''' UpperCamelCase = len(lowercase ) for i in range(1 , lowercase ): UpperCamelCase = collection[i] UpperCamelCase = 0 UpperCamelCase = i - 1 while low <= high: UpperCamelCase = (low + hig...
222
1
'''simple docstring''' UpperCamelCase = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j": "BBBAA", "k": "ABAAB", "l": "ABABA", "m": "ABABB", "n": "ABBAA", "o": "A...
360
'''simple docstring''' from __future__ import annotations import numpy as np def SCREAMING_SNAKE_CASE( __lowercase ) -> Dict: return np.maximum(0 , __lowercase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
334
0
import csv import tweepy # Twitter API credentials __lowerCamelCase = """""" __lowerCamelCase = """""" __lowerCamelCase = """""" __lowerCamelCase = """""" def UpperCamelCase ( __lowerCamelCase : str ): # authorize twitter, initial...
59
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class _a ( snake_case_ , snake_case_ ): """simple docstring""" @register_t...
312
0
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() parser.add_argument('''--dump_path...
369
import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import S...
218
0
"""simple docstring""" # 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/l...
16
from typing import Any, Dict, List, Union 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 ..image_utils import load_image if is_torch_available(): import torch ...
302
0
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ =OrderedDict( [ # ...
325
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ =logging.get_logger(__name__) UpperCamelCase__ ...
325
1
from __future__ import annotations def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[list[int]] ) -> int: '''simple docstring''' for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in r...
68
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_avai...
290
0
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils impo...
368
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, prepare_image_inputs if is_torch_available(): import torch ...
178
0
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness __UpperCamelCase = '''\ @misc{chen2021evaluating, title={Evaluat...
69
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 : Any = datasets.utils.logging.get_logger(__name__) @dataclass class __A ( datasets.Bui...
138
0
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device a__ : Tuple = False class a_ ( unittest.TestCase ): "...
19
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ ...
19
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowercase : str = { 'configuration_llama': ['LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP...
232
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, Pr...
232
1
from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class lowerCAmelCase__: '''simple docstring''' __snake_case = 42 __snake_case = None...
325
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class lowerCAmelCase__( __lowercase , __lowercase ...
325
1
'''simple docstring''' import math import unittest def __lowerCAmelCase (__lowerCAmelCase ): assert isinstance(__lowerCAmelCase , __lowerCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3...
234
'''simple docstring''' # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_nod...
234
1
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed ...
64
"""simple docstring""" import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def lowercase_ ( _lowerCamelCase: str , _lowerCamelCase: Optional[int]=7 ) -> int: '''simple docstring''' __lowerCamelCase : List[st...
64
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Optional[Any] = logging.get_logger(__name__) lowercase : Dict = { 'studio-ousia/luke-base': 'https://huggingface.co/studio-ousia/luke-base/resolve/main/con...
3
'''simple docstring''' import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize('''dataset_size''' , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize('''input_in_memory_max_size''' , ['''default''', 0, 100...
3
1
'''simple docstring''' from math import factorial def __UpperCAmelCase ( a_: int = 100 ): return sum(map(a_, str(factorial(a_ ) ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
358
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, ...
17
0
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, ...
76
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 ...
334
0
"""simple docstring""" from pathlib import Path import fire from tqdm import tqdm def _UpperCAmelCase ( __lowerCamelCase : Optional[int]="ro" , __lowerCamelCase : int="en" , __lowerCamelCase : Optional[int]="wmt16" , __lowerCamelCase : Dict=None ) -> None: try: ...
40
"""simple docstring""" import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase__ = logging.get_logger(__name__) class lowerCAmelCase__ ( A_ ): def __init__( self : str ,...
40
1
"""simple docstring""" def lowercase ( _snake_case : int , _snake_case : int , _snake_case : int ) ->float: """simple docstring""" __snake_case : Optional[int] = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) ...
102
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils impo...
218
0
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE_ ) class snake_case ( SCREAMING_SNAKE_CASE_ ): # `task` is not a ClassVar si...
303
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase_ = { 'configuration_mctct': ['MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MCTCTConfig'], 'feature_extraction_mctct': ['MCTCTFeatureExtractor'], ...
303
1
from __future__ import annotations def _a ( lowerCamelCase, lowerCamelCase ): lowerCamelCase : Optional[Any] = sorted(numsa + numsa ) lowerCamelCase , lowerCamelCase : List[Any] = divmod(len(lowerCamelCase ), 2 ) if mod == 1: return all_number...
287
# Copyright 2021 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...
287
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ ...
183
'''simple docstring''' import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ = logging.get_logger('transformers.models.speecht5') def lowercase...
183
1
"""simple docstring""" from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging __magic_name__ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCamelCase_ ): if isinstance(a_ , np.ndarray ): return list(tenso...
100
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def __UpperCAmelCase ( a_ , a_ , a_ , a_ , a_): snake_case_ = np.array([[...
178
0
import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.te...
370
from torch import nn def UpperCamelCase( lowercase_ ) -> Tuple: '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f'''Unsupported acti...
34
0
def lowerCamelCase_ ( lowerCamelCase__ ): return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
19
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __A ={ '''configuration_bloom''': ['''BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BloomConfig''', '''BloomOnnxConfig'''], } try: if not is_tokenizers_available(): ...
19
1
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() __UpperCamelCase : List[Any] = logging.get_logger('''transformers.models.speecht5''') def _SCREAMING_SNAKE_CASE (_Uppe...
359
"""simple docstring""" import os from collections.abc import Iterator def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : str = "." ): for dir_path, dir_names, filenames in os.walk(_UpperCAmelCase ): lowerCAmelCase = [d for d in dir_names if d != 'scripts' and d[0] not in '._'] for filename in ...
309
0
'''simple docstring''' import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from ....
254
'''simple docstring''' import math import os import sys def lowercase_ ( lowerCAmelCase__ : str ): """simple docstring""" __UpperCAmelCase : Any = """""" try: with open(lowerCAmelCase__ , """rb""" ) as binary_file: _...
254
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface....
302
"""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...
302
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''BridgeTower/bridgetower-base''': '''https://huggingface.co/BridgeTower/brid...
64
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings A_ = r''' [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and can be used to control th...
64
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging,...
304
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from ...
304
1
'''simple docstring''' 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 ( ...
265
"""simple docstring""" from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, Stabl...
17
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCAmelCase ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelC...
350
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator...
319
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __lowercase = { """configuration_encodec""": [ """ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP""", "...
40
"""simple docstring""" __lowercase = { """Pillow""": """Pillow<10.0.0""", """accelerate""": """accelerate>=0.20.3""", """av""": """av==9.2.0""", """beautifulsoup4""": """beautifulsoup4""", """black""": """black~=23.1""", """codecarbon""": """codecarbon==1....
40
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, ) if is_sentencepiece_available(): from ..ta...
350
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase : Optional[Any] = { '''configuration_poolformer''': [ '''POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PoolFormerConfig''', ...
306
0
def a__ ( snake_case ): """simple docstring""" if not isinstance(snake_case , snake_case ) or number < 0: raise ValueError('''Input must be a non-negative integer''' ) __SCREAMING_SNAKE_CASE : Dict = 0 while number: # This way we arrive at next set bit (next 1) i...
303
from heapq import heappop, heappush import numpy as np def a__ ( snake_case , snake_case , snake_case , snake_case , ): """simple docstring""" __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = grid.shape __SCREAMING_SNAKE_CASE : Tuple = ...
303
1
def lowercase( UpperCamelCase_ = 1000000 ) -> int: '''simple docstring''' UpperCamelCase = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , UpperCamelCase_ ): phi[j] -= phi[j] // ...
165
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore _SCREAMING_SNAKE_CASE = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" _SCREAMING_SNAKE_CASE = [file for file in...
165
1
"""simple docstring""" def lowerCamelCase__ ( _lowerCamelCase : int ) -> list: lowerCamelCase_ = int(_lowerCamelCase ) if n_element < 1: lowerCamelCase_ = ValueError('a should be a positive number' ) raise my_error l...
183
"""simple docstring""" from math import pow, sqrt def lowerCamelCase__ ( *_lowerCamelCase : float ) -> bool: lowerCamelCase_ = len(_lowerCamelCase ) > 0 and all(value > 0.0 for value in values ) return result def ...
183
1
"""simple docstring""" import os def lowercase ( a__ : Dict = "matrix.txt" ) -> int: with open(os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ) as in_file: _UpperCamelCase = in_file.read() _Upper...
365
"""simple docstring""" import numpy as np def lowercase ( a__ : Optional[Any] , a__ : str , a__ : Union[str, Any] , a__ : Any , a__ : List[str] ) -> Dict: _UpperCamelCase = int(np.ceil((x_end - xa) / h ) ) _UpperCamelCa...
54
0
# Copyright 2021 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...
19
'''simple docstring''' import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging...
34
0
from __future__ import annotations import typing from collections.abc import Iterable import numpy as np lowercase_ = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 lowercase_ = typing.Union[np.floataa, int, float] # noqa: UP007 def __lowerCAmelCase ( SCRE...
224
def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowercase__ = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): lowercase__ = n - k # Calculate C(n,k) for i in range(SCREAMING_SNAKE_CASE_ ): result *=...
224
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import loggin...
97
'''simple docstring''' import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers im...
309
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A : List[str] = {'configuration_opt': ['OPT_PRETRAINED_CONFIG...
8
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, to...
8
1
from __future__ import annotations def A__ ( __lowerCamelCase ): if not nums: raise ValueError('''List is empty''' ) return sum(__lowerCamelCase ) / len(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
299
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
1
"""simple docstring""" import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging imp...
360
"""simple docstring""" def lowerCAmelCase (__UpperCamelCase : str ): """simple docstring""" __UpperCamelCase =0 # if input_string is "aba" than new_input_string become "a|b|a" __UpperCamelCase ='''''' __UpperCamelCase ='''''' # append eac...
85
0
'''simple docstring''' import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case__ : def __init__( self : Optional[Any] , _A : List[Any]=2 , _A : Tuple=3 ...
304
'''simple docstring''' import logging from transformers.configuration_utils import PretrainedConfig _UpperCamelCase : Any = logging.getLogger(__name__) class snake_case__ ( UpperCamelCase): a_ = "masked_bert" def __init__( self : str , _A : ...
304
1
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__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = args.log_outputs ...
327
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, va...
327
1
from ...configuration_utils import PretrainedConfig from ...utils import logging A__ = logging.get_logger(__name__) A__ = { """facebook/vit-mae-base""": """https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json""", # See all ViT MAE models at https://huggingface.co/...
82
'''simple docstring''' import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing impor...
319
0
'''simple docstring''' from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class _snake_case ( yaml.SafeLoader ): def snake_case__ ( self , _lowerCamelCase): UpperCAmelCase__ : str ...
283
'''simple docstring''' def _UpperCamelCase ( UpperCamelCase__ ): UpperCAmelCase__ : List[str] = len(UpperCamelCase__ ) UpperCAmelCase__ : List[Any] = sum(UpperCamelCase__ ) UpperCAmelCase__ : List[str] = [[Fals...
283
1
"""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.or...
81
from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.m...
310
0
def _a ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str ): """simple docstring""" assert x is not None assert y is not None UpperCamelCase__ : Any = len(SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Dict = len(SCREAMING_SNAKE_CA...
51
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : List[str] = { "configuration_mobilenet_v2": [ "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config", "M...
51
1
"""simple docstring""" import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosit...
165
"""simple docstring""" from collections import defaultdict class lowerCamelCase : def __init__( self : List[str] , __UpperCAmelCase : Dict , __UpperCAmelCase : Any ) -> Any: SCREAMING_SNAKE_CASE__ = total # total no of tasks (N) # DP ...
165
1
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM...
102
from pathlib import Path import fire from tqdm import tqdm def _a ( SCREAMING_SNAKE_CASE_ : Dict="ro" , SCREAMING_SNAKE_CASE_ : Union[str, Any]="en" , SCREAMING_SNAKE_CASE_ : Optional[Any]="wmt16" , SCREAMING_SNAKE_CASE_ : List[str]=None ...
102
1
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int ) ->int: if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError("""Input must be an integer""" ) if input_num <= 0: raise ValueError("""Input must be positive""" ) ...
58
"""simple docstring""" import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import Toke...
54
0
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __snake_case : Union[str, Any] = logging.getLogger() @unittest.skip('''Tempor...
122
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup __snake_case : Any = """https://www.indeed.co.in/jobs?q=mobile+app+development&l=""" def _UpperCamelCase ( UpperCamelCase_ : str = "mumbai" ...
122
1
"""simple docstring""" import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloy...
224
"""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, ) lowercase__ : ...
224
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.''' )
360
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging A_ :Union[str, Any] = logging.get_logger(__name__) A_ :Tuple = { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/config.json''', '''x...
245
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase_ = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', ...
8
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable lowerCAmelCase_ = {'''configuration_dpt''': ['''DPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DPTConfig''']} try:...
8
1
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def UpperCamelCase_( _snake_case : np.ndarray ): """simple docstring""" return input_array.reshape((input_array.size, 1) ) def...
367
import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class __magic_name__ ( nn.Module ): SCREAMING_SNAKE_CASE = 42 SCREAMING_SNAKE_CAS...
308
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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, ...
147
'''simple docstring''' def UpperCamelCase_( snake_case : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = [0 for i in range(r + 1 )] # nc0 = 1 snake_case_ = 1 for i in ...
85
0
import os # Precomputes a list of the 100 first triangular numbers __UpperCAmelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def UpperCamelCase ( ) -> Any: UpperCamelCase : Tuple = os.path.dirname(os.path.realpath(snake_case__ ) ) UpperCamelCase ...
103
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
1
"""simple docstring""" from math import factorial class UpperCamelCase : def __init__( self : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] ) -> List[Any]: _a : List[str] ...
294
"""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_s...
294
1
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 __UpperCAmelCase = logging.get_logger(__name__)...
42
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCAmelCase = {'''configuration_xlnet''': ['''XLNET_PRETRAINED_CONFIG_ARCHIVE_M...
42
1
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Any = input('''Enter image url: ''').strip() print(f"Downloading image from {url} ...") A__: Any = BeautifulSoup(requests.get(url).content, '''html.parser'''...
149
"""simple docstring""" from collections.abc import Sequence def lowercase__ ( _UpperCAmelCase , _UpperCAmelCase = False ) -> float: '''simple docstring''' if not arr: return 0 lowercase : Tuple = 0 if allow_empty_suba...
255
0
from __future__ import annotations def _a ( SCREAMING_SNAKE_CASE__ : list[int] ) -> list[int]: # This function is recursive '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = len(SCREAMING_SNAKE_CASE__ ) # If the ar...
191
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
1
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from ac...
51
from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean snake_case_ : str = 0 snake_case_ : Union[str, Any] = [ [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...
51
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from t...
366
UpperCAmelCase__ = "0.21.0" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import sk...
26
0
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils imp...
102
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_...
102
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { '''vinvino02/glpn-kitti''': '''https://huggingface.co/vinvino02/glpn-kitti/resolve/main/co...
359
'''simple docstring''' import heapq def _lowerCAmelCase ( lowerCamelCase_ : dict ): __lowercase = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue ...
217
0
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxMode...
122
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise Opt...
122
1
'''simple docstring''' # Lint as: python3 import itertools import os import re lowercase : Optional[int] = re.compile(R'([A-Z]+)([A-Z][a-z])') lowercase : Optional[Any] = re.compile(R'([a-z\d])([A-Z])') lowercase : int = re.compile(R'(?<!_)_(?!_)...
311
'''simple docstring''' import unittest from transformers import BertGenerationConfig, 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 ...t...
311
1
from ..utils import DummyObject, requires_backends class lowercase ( metaclass=UpperCamelCase__ ): _a = ["note_seq"] def __init__( self , *_a , **_a ) -> Dict: requires_backends(self , ["""note_seq"""] ) @classmethod ...
26
def __lowercase ( _A ) -> bool: return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print("""Program to check whether a number is a Perfect number or not...""") UpperCAmelCase__ : Optional[int] = int(input("""Ente...
245
0
'''simple docstring''' from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMix...
98
'''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 Threa...
98
1
import itertools import string from collections.abc import Generator, Iterable def lowerCamelCase__ ( a__ : int , a__ : Any ) -> Generator[tuple[str, ...], None, None]: UpperCamelCase_ = iter(a__ ) while True: UpperCamelCase_ = ...
122
import copy from typing import Any, Dict, List, Optional, Union import numpy as np 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 imp...
308
0
def _snake_case ( lowercase__ : int ) -> int: '''simple docstring''' lowerCAmelCase_ :Union[str, Any] = 0 while num > 0: digit_sum += num % 1_0 num //= 1_0 return digit_sum def _snake_case ( lowercase__ : int = 1_0_0 )...
359
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( A__ ): def __init__( self , *__A , ...
1
0