code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
from PIL import Image def lowerCamelCase( a__ ,a__): def brightness(a__) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError('''level must be between -255.0 (black) and 255.0 (white)''') return img.point(_lowerCamelCase) if __name...
691
"""simple docstring""" import unittest from typing import Dict, List, Optional, Union 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 ImageProcessingSavingTe...
646
0
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : List[str] =logging.get_l...
700
"""simple docstring""" import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six...
197
0
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint lowerCAme...
39
'''simple docstring''' import numpy as np class lowercase__ : '''simple docstring''' def __init__( self ): _SCREAMING_SNAKE_CASE : List[Any] = (0, 0) _SCREAMING_SNAKE_CASE : List[str] = None _SCREAMING_SNAKE_CASE ...
533
0
'''simple docstring''' import math import unittest def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ): assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: ...
438
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'uw-madison/mra-base-512-4': 'https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json', } class UpperCAm...
438
1
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class __SCREAMING_SNAKE_CASE ( unittest.TestCase): """simple docstring""" def lowercase_ ( self ): __snake_case : Dict = [ 'safety_checker/p...
576
from ....configuration_utils import PretrainedConfig from ....utils import logging __magic_name__ = logging.get_logger(__name__) # TODO: upload to AWS __magic_name__ = { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/reso...
576
1
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( ConditionalDetrConfig, ConditionalDetrForObjectDetection, Conditiona...
569
from cva import destroyAllWindows, imread, imshow, waitKey def __lowerCamelCase ( snake_case__ ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = img.shape[0], img.shape[1] # converting each pixel's c...
569
1
'''simple docstring''' from math import ceil def lowerCAmelCase ( UpperCamelCase__ : int = 1_0_0_1 ): """simple docstring""" __UpperCAmelCase = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): __UpperCAmelCase = 2 *...
262
import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .token...
37
0
import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_co...
129
import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch __lowerCAmelCase = "sshleifer/bart-tiny-random"...
129
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils...
332
from __future__ import annotations from dataclasses import dataclass @dataclass class a : """simple docstring""" UpperCamelCase_ : float UpperCamelCase_ : TreeNode | None = None UpperCamelCase_ : TreeNode | None = None ...
332
1
import os import sys lowerCamelCase : Tuple = os.path.join(os.path.dirname(__file__), '''src''') sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoM...
702
import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Ac...
290
0
import warnings 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__ ( _A): ...
2
'''simple docstring''' 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 lowerCAmelCase__ ( a , a ): """simple docstring""" @register_to_config de...
627
0
"""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 f...
292
"""simple docstring""" from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configura...
292
1
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _a : List[str] = { 'configuration_informer': [ 'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Informer...
447
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from u...
447
1
'''simple docstring''' import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, ...
719
'''simple docstring''' from __future__ import annotations from statistics import mean def __lowerCAmelCase ( a_ , a_ , a_ ) -> list[int]: '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = [0] * no...
179
0
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE ={ """huggingface/informer-tourism-monthly""": ( """https://huggingface.co...
234
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class __magic_name__ ( __UpperCAmelCase): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = "Speech2TextFeatureExtractor" SCREAMIN...
234
1
from ...processing_utils import ProcessorMixin class __magic_name__ ( A__ ): lowercase : List[str] ='''WhisperFeatureExtractor''' lowercase : Any ='''WhisperTokenizer''' def __init__( self : Optional[int] , UpperCamelCase__ ...
703
def lowerCamelCase_(lowerCamelCase_ , lowerCamelCase_ ) -> list[int]: UpperCAmelCase = int(lowerCamelCase_ ) # Initialize Result UpperCAmelCase = [] # Traverse through all denomination for denomination in reversed(lowerCamelCase_ ): ...
457
0
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor _snake_case = logging.get_logger(__name__) class UpperCAmelCase_ ( a): def __init__( self, *__a, **__a): '''simple docstring''' warnings.w...
500
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, D...
500
1
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class lowercase ( ctypes.Structure ): # _fields is a specific attr expected by ctypes lowerCamelCase : Dict = [('''size''', ctypes....
711
from __future__ import annotations a_ :str = 8.988e9 # units = N * m^s * C^-2 def a ( A__ , A__ , A__ , A__ ) -> dict[str, float]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = abs(chargea * chargea ) ...
250
0
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort ...
395
import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging snake_case__ = logging.get_logger(__name__) snake_case__ = r''' Args: input_ids (`torch.LongTensor` of shape `(b...
395
1
"""simple docstring""" import unittest from knapsack import greedy_knapsack as kp class __snake_case ( unittest.TestCase ): def lowerCamelCase_ ( self) -> Union[str, Any]: '''simple docstring''' a__: Optional[Any] = [10, 20, 30, 40, 50, 60...
217
"""simple docstring""" from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 10**-10 ) ->float: a__: int = a while True: a__: ...
217
1
from math import factorial, pi def __lowerCAmelCase ( _UpperCamelCase : float , _UpperCamelCase : int = 30 ) -> float: '''simple docstring''' if not isinstance(_UpperCamelCase , (int, float) ): raise ValueError('maclaurin_sin() requires either an int or float for theta...
439
# 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 applica...
439
1
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, O...
53
import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_commo...
53
1
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 lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''facebook/levit-1...
496
"""simple docstring""" import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class UpperCamelCase__ ( unittest.TestCase ): """simple docstri...
104
0
import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False if __name__ == "__main__": SCRE...
707
from __future__ import annotations import math def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : int ) -> float: __lowercase = u for i in range(1 , SCREAMING_SNAKE_CASE ): __lowercase = temp * (u - i) ret...
688
0
'''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 __SCREAMIN...
578
'''simple docstring''' from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( _lowerCamelCase: str , _lowerCamelCase: float | Decimal , _lowerCamelCase: float = 10**-10 ): __SCREAMING_SNAKE_CASE :...
578
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { '''google/bigbird-roberta-base''': '''https://huggingfa...
712
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 logging.set_verbosity_info() Up...
565
0
"""simple docstring""" import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() clas...
102
'''simple docstring''' 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 tra...
447
0
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def __lowerCAmelCase ( __UpperCa...
21
"""simple docstring""" def __lowerCAmelCase ( __UpperCamelCase : int , __UpperCamelCase : bool = False ): '''simple docstring''' if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n ...
21
1
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask ...
663
'''simple docstring''' import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _A = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( snake_case ): ...
158
0
import numpy as np def A ( _lowercase ): return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
34
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def A ( _lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = analyze_text(_lowercase ) SCREAMING_SNAKE_CASE ...
34
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling...
366
'''simple docstring''' import re import time from typing import Optional import IPython.display as disp from ..trainer_callback import TrainerCallback from ..trainer_utils import IntervalStrategy, has_length def lowerCamelCase( SCREAMING_SNAKE_CASE_ ) -> str: A_ = int(SCREAMING_SNA...
366
1
"""simple docstring""" from torch import nn class __snake_case ( nn.Module ): def __init__( self , lowercase , lowercase) -> List[str]: '''simple docstring''' super().__init__() a__: Optional[Any] = class_size a__: Any ...
217
"""simple docstring""" def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False ) ->str: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): a__: int = F'Expected string as input, found {type(_SCREAMING_SNAKE_CASE )}' raise ValueError(_SCREAMING_SNAK...
217
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''', # See all GPTNeoX m...
91
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_ve...
232
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/...
63
"""simple docstring""" import math import sys import cva import numpy as np def __magic_name__ ( _lowerCamelCase : np.ndarray , _lowerCamelCase : float ): # For applying gaussian function for each element in matrix. __a : int = math....
63
1
def a (lowerCAmelCase__ = 1_000_000 ): __a = 1 __a = 1 __a = {1: 1} for inputa in range(2 , lowerCAmelCase__ ): __a = 0 __a = inputa while True: if number in counters: counter += counters[number] break...
99
# 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...
99
1
'''simple docstring''' # 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. ...
389
'''simple docstring''' def _lowerCamelCase ( lowerCamelCase_ : str , lowerCamelCase_ : int ): """simple docstring""" return [sentence[i : i + ngram_size] for i in range(len(lowerCamelCase_ ) - ngram_size + 1 )] if __name__ == "__main__": from docte...
389
1
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : float ,lowerCAmelCase_ : float ,lowerCAmelCase_ : float ) -> dict[str, float]: """simple docstring""" if (voltage, current, resistance).count(0 ) != 1: ...
220
import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : Tuple ,lowerCAmelCase_ : Optional[int] ,lowerCAmelCase_ : Union[str, Any] ,lowerCAmelCase_ : Optional[Any]=1024 ...
220
1
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import Mo...
712
"""simple docstring""" import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWith...
422
0
"""simple docstring""" from collections import defaultdict class lowerCamelCase : '''simple docstring''' def __init__(self , _lowerCamelCase , _lowerCamelCase ): """simple docstring""" UpperCAmelCase__ : Dict = total # total no of tasks ...
182
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {"""configuration_sew""": ["""SEW_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SEWConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAv...
182
1
import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging snake_case_ : Optional[Any] ...
205
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from tra...
205
1
def _a ( lowerCAmelCase = 10 )-> List[Any]: if not isinstance(UpperCamelCase_ , UpperCamelCase_ ) or n < 0: raise ValueError('Invalid input' ) SCREAMING_SNAKE_CASE_ = 10**n SCREAMING_SNAKE_CASE_ = 28433 * (pow(2 , 7830457 , U...
360
'''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 = logging.get_logger(_...
467
0
'''simple docstring''' import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( ConditionalDetrConfig, ConditionalDetrForObjectDete...
719
'''simple docstring''' import json import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common impo...
324
0
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.sched...
327
def UpperCAmelCase_ (_lowerCAmelCase : int = 60_08_51_47_51_43 ): try: __UpperCamelCase : Optional[Any] = int(_lowerCAmelCase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter...
327
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipe...
551
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_...
551
1
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_ten...
97
from __future__ import annotations def a ( snake_case__: Optional[int] , snake_case__: Optional[int] , snake_case__: Any , snake_case__: Optional[int] ): # noqa: E741 '''simple docstring''' while r - l > 1: lowercase_ = (l + r) // 2 if v[m] >=...
97
1
import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, ...
705
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets _lowerCamelCase : Tuple = datasets.logging.get_logger(__name__) _lowerCamelCase : Any ...
157
0
import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_co...
59
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A = transforms.Compose...
59
1
import argparse import datetime def lowercase_ (A : str ): snake_case__ : int = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', ...
243
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since ...
243
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __snake_case = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_...
472
'''simple docstring''' def _A ( ): '''simple docstring''' A__ = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] A__ = 6 A__ = 1 A__ = 1901 A__ = 0 while year < 2001: day += 7 if (year % 4 == 0 and...
531
0
'''simple docstring''' import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate _snake_case = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerro...
701
from math import factorial, pi def __lowerCamelCase ( _lowercase , _lowercase = 30 ) -> float: if not isinstance(_lowercase , (int, float) ): raise ValueError('maclaurin_sin() requires either an int or float for theta' ) if not isinstance(_lowercase , _lowercase ) ...
170
0
from typing import Any class lowerCamelCase_ : '''simple docstring''' def __init__( self , __lowercase) -> List[str]: __UpperCamelCase :List[str] = data __UpperCamelCase :Optional[Any] = None def __repr__( self) ...
167
"""simple docstring""" from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance __A = 637_8137.0 __A = 635_6752.31_4245 __A = 6_3_7_8_1_3_7 def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAme...
586
0
def UpperCAmelCase_ ( UpperCAmelCase__ ): if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError("""Input value must be an 'int' type""" ) lowercase_ = 0 while number: position += 1 number >>= 1 return position i...
717
# 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/licenses/LICENSE-2.0 # # Unless required by applic...
650
0
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class lowercase ( pl.LightningModule): """simple docstring""" def __init__( self : List[str] , __UpperCAmelCase :...
593
'''simple docstring''' def lowerCamelCase__ ( __lowerCamelCase : str ): '''simple docstring''' _UpperCAmelCase : Dict ='' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def lowerCame...
446
0
class _a : """simple docstring""" def __init__( self: Dict , __lowerCamelCase: Union[str, Any] = "" , __lowerCamelCase: Any = False ): '''simple docstring''' UpperCamelCase__: dict[str, RadixNode] = {} # A node will be a leaf if...
721
def lowerCAmelCase_ ( ): for n in range(1 ,1_00_00_00): yield n * (n + 1) // 2 def lowerCAmelCase_ ( A_): UpperCamelCase__: int = 1 UpperCamelCase__: Dict = 2 while i * i <= n: UpperCamelCase__: Any ...
221
0
import requests from bsa import BeautifulSoup def __magic_name__ ( SCREAMING_SNAKE_CASE = "https://www.worldometers.info/coronavirus" ) -> dict: _lowercase : Optional[Any] = BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE ).text , 'html.parser' ) ...
66
from __future__ import annotations import string from itertools import cycle, product from pathlib import Path UpperCAmelCase : str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) UpperCAmelCase : list[int] = [ord(letter) for letter in string.ascii_low...
239
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType...
481
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_TRUE_VALUES, FEAT...
481
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer a_ = logging.get_logger(__name__) a_ = {"""vocab_file""": ""...
175
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class __a ( ctypes.Structure ): # _fields is a specific attr expected by ctypes __snake_case : Optional[Any] = [("""size""", ctypes.c_int),...
600
0
"""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...
645
"""simple docstring""" import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from tr...
645
1
import datasets from .evaluate import evaluate SCREAMING_SNAKE_CASE = "\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.0...
579
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableU...
413
0
'''simple docstring''' import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCA...
312
'''simple docstring''' def a__ ( lowerCAmelCase__ ) -> bool: UpperCAmelCase__ : List[Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
312
1
def __lowercase ( lowerCamelCase : int ): if num <= 0: raise ValueError('Input must be a positive integer' ) UpperCamelCase_ : int = [True] * (num + 1) UpperCamelCase_ : str = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , lowerCamelCas...
417
'''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 Threaded...
664
0
'''simple docstring''' import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate lowerCAmelCase : str = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow(''''''...
718
'''simple docstring''' import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def __lowerCAmelCase ( lowerCamelCase : bytes , lowerCamelCase : int ): '''simple docstring''' __lowerCAmelCase = f''...
39
0
from queue import PriorityQueue from typing import Any import numpy as np def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , S...
39
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 HfArgumentParser, Tr...
39
1
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Tuple = [randint(-1000, 1000 ) for i in range(10 )] _SCREAMING_SNAKE_CASE : int ...
381
from __future__ import annotations UpperCamelCase__ =[True] * 100_0001 UpperCamelCase__ =2 while i * i <= 100_0000: if seive[i]: for j in range(i * i, 100_0001, i): UpperCamelCase__ =False i += 1 def lowerCamelCase__ (__lowerCamelCase ):...
381
1
"""simple docstring""" import heapq as hq import math from collections.abc import Iterator class A_ : def __init__( self: Optional[Any] ,__lowerCAmelCase: Optional[Any] ): '''simple docstring''' _lowerCamelCase : Any = str(id_ )...
46
'''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_...
577
0
import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params...
583
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class...
583
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : str =logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Union[str, Any] ={ 'bigcode/gpt_bigcode-santacoder': 'https://huggingface.co/bigcode/gpt_bi...
434
"""simple docstring""" def UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ->Tuple: if height >= 1: move_tower(height - 1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CA...
434
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCamelCase__ : List[Any] = {'configuration_yolos': ['YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'YolosConfig', 'YolosOnnxConfig']} try: if not ...
496
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase__ : int = logging.get_logger(__name__) UpperCamelCase__ : Optional[Any] = {'vocab_file': 'vocab.json'} UpperCamelCase_...
496
1
'''simple docstring''' import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline lowerCAmelCase_ : List[Any] = { 'n_samples': 64, 'horizon': 32, 'num_inference_steps': 20, 'n_guide_steps': 2, # can set to 0 for f...
527
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffu...
527
1
'''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...
331
'''simple docstring''' import os # Precomputes a list of the 100 first triangular numbers lowercase =[int(0.5 * n * (n + 1)) for n in range(1, 101)] def lowerCamelCase__ ( ): '''simple docstring''' _UpperCAmelCase : int =os.path.dirname(os.path.realpath(__low...
331
1
def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any]=False ) -> Dict: if isinstance(lowercase, lowercase ) and isinstance(lowercase, lowercase ): A : int =len(set_a.intersection(lowercase ) ) if alternati...
305
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 _lowercase : Any =get_tests_dir('''fixtures/test_sentencepiece_with_bytefallb...
305
1
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = ["image_proce...
85
"""simple docstring""" a : List[Any] = """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/""" def lowercase__(A ) ->bytes: """simple docstring""" if not isinstance(A , A ): lowercase__ ...
85
1
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.util...
175
import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logg...
647
0
'''simple docstring''' import os from datetime import datetime as dt from github import Github A = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def ...
449
'''simple docstring''' def UpperCAmelCase ( UpperCAmelCase__ : list[int]): if not nums: # Makes sure that the list is not empty raise ValueError('List is empty') lowerCamelCase : int = sum(UpperCAmelCase__) / len(UpperCAmelCase__) # Calculate the...
449
1
'''simple docstring''' def __lowercase ( __lowercase , __lowercase , __lowercase , __lowercase ) -> Optional[Any]: '''simple docstring''' global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: _A = mf_...
330
'''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/LIC...
143
0
"""simple docstring""" 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, ...
718
"""simple docstring""" import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class lowerCamelCase__ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowerCamelCase = (DDPMParallelScheduler,) ...
255
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __A : str = logging.get_logger(__name__) __A : List[Any] = { 'google/switch-base-8': 'https://huggingface.co/google/switch-base-8/blob/main/config.json', } class __UpperCam...
334
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowercase ( SCREAMING_SNAKE_CASE__ : Any ) -> str: return getitem, k def lowercase ( SCREAMING_SNAKE_CASE__ : List[Any] , ...
477
0
import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundf...
720
import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppToken...
381
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_at...
244
'''simple docstring''' import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class lowerCamelCase_ (snake_case__ ): '''simple docstring''' __UpperCamelCase: Union[str, Any] = (DDPMScheduler,) def _A ( self : ...
244
1
def _snake_case ( __snake_case , __snake_case ): return abs(__snake_case ) if a == 0 else greatest_common_divisor(b % a , __snake_case ) def _snake_case ( __snake_case , __snake_case ): while y: # --> when y=0 then loop will terminate and return x as final GCD. ...
718
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase ...
71
0
import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str,...
144
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ...
144
1
import math import sys def lowerCamelCase( a__): if number != int(a__): raise ValueError('''the value of input must be a natural number''') if number < 0: raise ValueError('''the value of input must not be a negative number''') if number == 0: return 1 _SCREAMIN...
191
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_u...
191
1
def UpperCamelCase ( snake_case__ : int ,snake_case__ : int ,snake_case__ : int ): '''simple docstring''' if exponent == 1: return base if exponent % 2 == 0: __snake_case :int = _modexpt(snake_case__ ,expon...
455
import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, ...
455
1
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def __snake_case ( ): __a = ArgumentParser( description=( '''PyTorch TPU distributed training launch helper utility...
711
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING...
60
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : List[str] = { "fa...
197
'''simple docstring''' import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : List[Any]=None ) -> Union[str, Any]: ''...
38
0
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_available, logging from .benchma...
527
import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class lowerCamelCase_ : '''simple docstring''' def __init__( self , snake_case_=2 , snake_case_=3 , snake_case_=6_4 , snake_case_=Non...
527
1
'''simple docstring''' from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) _lowercase ...
5
def lowerCAmelCase_ ( __UpperCAmelCase: str ) -> bool: return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') ) def lowerCAmelCase_ ( __UpperCAmelCase: str ) -> bool: UpperCamelCase__ : Tuple ...
253
0
from __future__ import annotations def _lowerCAmelCase ( _a : list[int] ) -> list[int]: # This function is recursive lowerCAmelCase_ : List[Any] = len(_a ) # If the array contains only one element, we return it (it's the stop condition of # recursion) i...
440
UpperCAmelCase_ : str = """Alexander Joslin""" import operator as op from .stack import Stack def _lowerCAmelCase ( _a : str ) -> int: lowerCAmelCase_ : Any = {"""*""": op.mul, """/""": op.truediv, """+""": op.add, """-""": op.sub} lowerCAmelCas...
440
1
"""simple docstring""" import math import unittest def snake_case_ ( A_ : int ): '''simple docstring''' assert isinstance(A_, A_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 ...
83
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _UpperCAmelCase : Optional[int] = logging.get_logger(__name__) _UpperCAmelCase : str = { "vocab_file": "vocab.json"...
668
0
'''simple docstring''' import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import g...
223
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( __A , __A , __A , __A ) -> None: '''simple docstring''' if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ...
223
1
"""simple docstring""" 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 ...
118
"""simple docstring""" import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers i...
118
1
'''simple docstring''' 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 t...
415
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE_: Dict ={ 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Au...
415
1
'''simple docstring''' import warnings 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 __SCREAMING_SN...
692
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _lowerC...
692
1
# 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 appli...
711
from __future__ import annotations def __a ( __UpperCAmelCase , __UpperCAmelCase ): a__ = get_failure_array(__UpperCAmelCase ) # 2) Step through text searching for pattern a__ , a__ = 0, 0 # index into text, pattern while i < len(__UpperCAmelCase...
148
0
"""simple docstring""" import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from f...
7
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase ={ "configuration_informer": [ "INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "...
617
0
from math import factorial def UpperCAmelCase ( lowercase__ : int = 100 ): '''simple docstring''' return sum(map(lowercase__ , str(factorial(lowercase__ ) ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
712
def UpperCAmelCase ( lowercase__ : float , lowercase__ : float ): '''simple docstring''' if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / de...
412
0
"""simple docstring""" import logging from transformers import PretrainedConfig lowerCamelCase__ : Optional[int] = logging.getLogger(__name__) lowerCamelCase__ : str = { '''bertabs-finetuned-cnndm''': '''https://huggingface.co/remi/bertabs-finetuned-cnndm-extract...
238
"""simple docstring""" import argparse import datetime def UpperCamelCase ( _lowerCAmelCase : str ) -> str: _UpperCAmelCase : List[str] = { """0""": """Sunday""", """1""": """Monday""", """2""": """Tuesday""", """3""": """We...
238
1
"""simple docstring""" from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 9, 14 # noqa: F841 SCREAM...
538
"""simple docstring""" # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def SCREAMING_SNAKE_CASE ( __UpperCAmelCase ) -> List[str...
538
1
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_avai...
657
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" try: _UpperCAmelCase = float(UpperCamelCase__ ) except ValueError: raise ValueError("Please enter a valid number" ) _UpperCAmelCase = decimal - int(UpperCamelCase__ ) if fractional_part == ...
657
1
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversat...
695
'''simple docstring''' 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 lowerca...
695
1