uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c7183a932a431416aa5d0df6 | train | class | class FakeDriver(log_driver_base.DriverBase):
@staticmethod
def create():
return FakeDriver(
name='fake_driver',
vif_types=[],
vnic_types=[],
supported_logging_types=['security_group'],
requires_rpc=True
)
| class FakeDriver(log_driver_base.DriverBase):
@staticmethod
| def create():
return FakeDriver(
name='fake_driver',
vif_types=[],
vnic_types=[],
supported_logging_types=['security_group'],
requires_rpc=True
)
| resources
from neutron.services.logapi.common import sg_callback
from neutron.services.logapi.drivers import base as log_driver_base
from neutron.services.logapi.drivers import manager as driver_mgr
from neutron.tests import base
FAKE_DRIVER = None
class FakeDriver(log_driver_base.DriverBase):
@staticmethod
| 64 | 64 | 54 | 13 | 50 | congnt95/neutron | neutron/tests/unit/services/logapi/common/test_sg_callback.py | Python | FakeDriver | FakeDriver | 30 | 40 | 30 | 32 | 449232f753acc54ea1c1fe619e4d36a2d99c7fa5 | bigcode/the-stack | train |
0cc48661c407ab0595bbb6f3 | train | class | class TestSecurityGroupRuleCallback(base.BaseTestCase):
def setUp(self):
super(TestSecurityGroupRuleCallback, self).setUp()
self.driver_manager = driver_mgr.LoggingServiceDriverManager()
@mock.patch.object(sg_callback.SecurityGroupRuleCallBack, 'handle_event')
def test_handle_event(self, m... | class TestSecurityGroupRuleCallback(base.BaseTestCase):
| def setUp(self):
super(TestSecurityGroupRuleCallback, self).setUp()
self.driver_manager = driver_mgr.LoggingServiceDriverManager()
@mock.patch.object(sg_callback.SecurityGroupRuleCallBack, 'handle_event')
def test_handle_event(self, mock_sg_cb):
fake_register()
self.driver_m... | '],
requires_rpc=True
)
def fake_register():
global FAKE_DRIVER
if not FAKE_DRIVER:
FAKE_DRIVER = FakeDriver.create()
driver_mgr.register(resources.SECURITY_GROUP_RULE,
sg_callback.SecurityGroupRuleCallBack)
class TestSecurityGroupRuleCallback(base.BaseT... | 64 | 64 | 210 | 11 | 53 | congnt95/neutron | neutron/tests/unit/services/logapi/common/test_sg_callback.py | Python | TestSecurityGroupRuleCallback | TestSecurityGroupRuleCallback | 51 | 72 | 51 | 52 | 9a81d52be4fe80290df7de4b8f7b243e66cea47a | bigcode/the-stack | train |
d4f4b62d3518c1e2cffd46d8 | train | function | def fake_register():
global FAKE_DRIVER
if not FAKE_DRIVER:
FAKE_DRIVER = FakeDriver.create()
driver_mgr.register(resources.SECURITY_GROUP_RULE,
sg_callback.SecurityGroupRuleCallBack)
| def fake_register():
| global FAKE_DRIVER
if not FAKE_DRIVER:
FAKE_DRIVER = FakeDriver.create()
driver_mgr.register(resources.SECURITY_GROUP_RULE,
sg_callback.SecurityGroupRuleCallBack)
| FAKE_DRIVER = None
class FakeDriver(log_driver_base.DriverBase):
@staticmethod
def create():
return FakeDriver(
name='fake_driver',
vif_types=[],
vnic_types=[],
supported_logging_types=['security_group'],
requires_rpc=True
)
def fake... | 64 | 64 | 45 | 4 | 60 | congnt95/neutron | neutron/tests/unit/services/logapi/common/test_sg_callback.py | Python | fake_register | fake_register | 43 | 48 | 43 | 43 | b92837861a4a6b7fad7ff59a63c71307ee45ad1a | bigcode/the-stack | train |
672a8b5362b9a1913107606c | train | class | class KoubeiMarketingCampaignItemMerchantactivityModifyRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
... | class KoubeiMarketingCampaignItemMerchantactivityModifyRequest(object):
| def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
self._notify_url = None
self._return_url = None
self._ud... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.KoubeiMarketingCampaignItemMerchantactivityModifyModel import KoubeiMarketingCampaignItemMerchantactivityModifyModel
class KoubeiMarket... | 80 | 255 | 851 | 12 | 67 | snowxmas/alipay-sdk-python-all | alipay/aop/api/request/KoubeiMarketingCampaignItemMerchantactivityModifyRequest.py | Python | KoubeiMarketingCampaignItemMerchantactivityModifyRequest | KoubeiMarketingCampaignItemMerchantactivityModifyRequest | 12 | 144 | 12 | 13 | d43177f1dded56ca909b1c7c85dcef1a963934a9 | bigcode/the-stack | train |
e15d9e07ffd3a0de225ef61a | train | class | class ZeroRobotFactory(JSConfigBase):
def __init__(self):
self.__jslocation__ = "j.servers.zrobot"
JSConfigBase.__init__(self, ZeroRobotServer)
| class ZeroRobotFactory(JSConfigBase):
| def __init__(self):
self.__jslocation__ = "j.servers.zrobot"
JSConfigBase.__init__(self, ZeroRobotServer)
| from js9 import j
from .ZeroRobotServer import ZeroRobotServer
JSConfigBase = j.tools.configmanager.base_class_configs
class ZeroRobotFactory(JSConfigBase):
| 36 | 64 | 42 | 8 | 27 | PeterNashaat/0-robot | JumpScale9Zrobot/servers/zerorobot/ZeroRobotFactory.py | Python | ZeroRobotFactory | ZeroRobotFactory | 8 | 12 | 8 | 9 | 4593d273f5427913deffdfae028ae48e6d737d06 | bigcode/the-stack | train |
e64038a76670ab66d4959619 | train | function | def edit_pipeline(full_dataset_path, laz_path, tif_path, output_epsg, bound, polygon_input):
fetch_json = open_json("./pipeline.json")
fetch_json['pipeline'][0]['filename'] = full_dataset_path
fetch_json['pipeline'][0]['bounds'] = bound
fetch_json['pipeline'][1]['polygon'] = polygon_input
fetch_json... | def edit_pipeline(full_dataset_path, laz_path, tif_path, output_epsg, bound, polygon_input):
| fetch_json = open_json("./pipeline.json")
fetch_json['pipeline'][0]['filename'] = full_dataset_path
fetch_json['pipeline'][0]['bounds'] = bound
fetch_json['pipeline'][1]['polygon'] = polygon_input
fetch_json['pipeline'][3]['out_srs'] = f'EPSG:{output_epsg}'
fetch_json['pipeline'][4]['filename'] ... | import json
def open_json(path):
with open(path, 'r')as json_file:
dict_ob = json.load(json_file)
return dict_ob
def edit_pipeline(full_dataset_path, laz_path, tif_path, output_epsg, bound, polygon_input):
| 56 | 64 | 137 | 22 | 33 | Bethelsis/AgriTech-USGS-LIDAR-Challenge | scripts/edit_pipeline.py | Python | edit_pipeline | edit_pipeline | 8 | 18 | 8 | 8 | 642efbc4ae6611ddf2cd8e45a49144b900c01568 | bigcode/the-stack | train |
f6d7ef29acda709b13ded2c1 | train | function | def open_json(path):
with open(path, 'r')as json_file:
dict_ob = json.load(json_file)
return dict_ob
| def open_json(path):
| with open(path, 'r')as json_file:
dict_ob = json.load(json_file)
return dict_ob
| import json
def open_json(path):
| 8 | 64 | 31 | 5 | 2 | Bethelsis/AgriTech-USGS-LIDAR-Challenge | scripts/edit_pipeline.py | Python | open_json | open_json | 3 | 6 | 3 | 3 | a10112c653964921fcf5c5c89cdeb808e98189bb | bigcode/the-stack | train |
906ed902324ba134fcb362af | train | function | def test_dynamic_sidecar_env_vars(monkeypatch: MonkeyPatch) -> None:
for key, value in MOCKED_BASE_REGISTRY_ENV_VARS.items():
monkeypatch.setenv(key, value)
registry_settings = RegistrySettings()
dynamic_sidecar_env_vars = get_dynamic_sidecar_env_vars(registry_settings)
print("dynamic_sidecar_... | def test_dynamic_sidecar_env_vars(monkeypatch: MonkeyPatch) -> None:
| for key, value in MOCKED_BASE_REGISTRY_ENV_VARS.items():
monkeypatch.setenv(key, value)
registry_settings = RegistrySettings()
dynamic_sidecar_env_vars = get_dynamic_sidecar_env_vars(registry_settings)
print("dynamic_sidecar_env_vars:", dynamic_sidecar_env_vars)
assert len(dynamic_sidecar... | _USER": "usr",
"REGISTRY_PW": MOCKED_PASSWORD,
"REGISTRY_SSL": "False",
}
EXPECTED_DYNAMIC_SIDECAR_ENV_VAR_NAMES = {
"REGISTRY_AUTH",
"REGISTRY_PATH",
"REGISTRY_URL",
"REGISTRY_USER",
"REGISTRY_PW",
"REGISTRY_SSL",
}
def test_dynamic_sidecar_env_vars(monkeypatch: MonkeyPatch) -> None:
| 92 | 92 | 307 | 17 | 75 | colinRawlings/osparc-simcore | services/director-v2/tests/unit/test_utils_registry.py | Python | test_dynamic_sidecar_env_vars | test_dynamic_sidecar_env_vars | 26 | 58 | 26 | 26 | d54cad9f6ea15bbff36abe9889a32a97515c3bc5 | bigcode/the-stack | train |
9f346370a32a905b62dacf3f | train | class | class clean_versions(AppCommand):
"""Delete old version directories.
Warning:
This command will result in the destruction of the following files:
1) Table data for previous versions of the app.
"""
async def run(self) -> None:
"""Execute command."""
self.remove_old... | class clean_versions(AppCommand):
| """Delete old version directories.
Warning:
This command will result in the destruction of the following files:
1) Table data for previous versions of the app.
"""
async def run(self) -> None:
"""Execute command."""
self.remove_old_versiondirs()
def remove_old... | """Program ``faust reset`` used to delete local table state."""
from shutil import rmtree
from .base import AppCommand
__all__ = ['clean_versions']
class clean_versions(AppCommand):
| 41 | 64 | 119 | 6 | 35 | spencerpomme/Public-Transit-Status-with-Apache-Kafka | consumers/venv/lib/python3.7/site-packages/faust/cli/clean_versions.py | Python | clean_versions | clean_versions | 8 | 25 | 8 | 8 | cf9c1eb8e8f128942889db4afb0ad149a7229e3e | bigcode/the-stack | train |
891606af602f3c400845a078 | train | class | class read_writeTest(unittest.TestCase):
filename = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "test_file.nc"
)
broken_bounds = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "broken_bounds.cdl"
)
string_filename = os.path.join(
os.path.dirname(os.... | class read_writeTest(unittest.TestCase):
| filename = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "test_file.nc"
)
broken_bounds = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "broken_bounds.cdl"
)
string_filename = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "string_char.nc"... | import atexit
import datetime
import faulthandler
import inspect
import os
import shutil
import subprocess
import tempfile
import unittest
import numpy
faulthandler.enable() # to debug seg faults and timeouts
import cf
n_tmpfiles = 8
tmpfiles = [
tempfile.mkstemp("_test_read_write.nc", dir=os.getcwd())[1]
... | 197 | 256 | 7,239 | 8 | 189 | sadielbartholomew/cf-python | cf/test/test_read_write.py | Python | read_writeTest | read_writeTest | 46 | 880 | 46 | 46 | dd9b7bf0883c947cc34c7fc645af07eb94869e59 | bigcode/the-stack | train |
48b0359be12c2be18730f21e | train | function | def _remove_tmpfiles():
"""Try to remove defined temporary files by deleting their paths."""
for f in tmpfiles:
try:
os.remove(f)
except OSError:
pass
| def _remove_tmpfiles():
| """Try to remove defined temporary files by deleting their paths."""
for f in tmpfiles:
try:
os.remove(f)
except OSError:
pass
| ]
for i in range(n_tmpfiles)
]
(
tmpfile,
tmpfileh,
tmpfileh2,
tmpfilec,
tmpfilec2,
tmpfile0,
tmpfile1,
tmpfile2,
) = tmpfiles
def _remove_tmpfiles():
| 64 | 64 | 42 | 6 | 57 | sadielbartholomew/cf-python | cf/test/test_read_write.py | Python | _remove_tmpfiles | _remove_tmpfiles | 34 | 40 | 34 | 34 | 210576a2a02df2443b5751ef1c2d02f113b24e19 | bigcode/the-stack | train |
88d5845dfe7641ca5c8c189d | train | class | class Cert_9_2_19_PendingDatasetGet(thread_cert.TestCase):
SUPPORT_NCP = False
TOPOLOGY = {
COMMISSIONER: {
'name': 'COMMISSIONER',
'mode': 'rdn',
'allowlist': [LEADER]
},
LEADER: {
'name': 'LEADER',
'mode': 'rdn',
... | class Cert_9_2_19_PendingDatasetGet(thread_cert.TestCase):
| SUPPORT_NCP = False
TOPOLOGY = {
COMMISSIONER: {
'name': 'COMMISSIONER',
'mode': 'rdn',
'allowlist': [LEADER]
},
LEADER: {
'name': 'LEADER',
'mode': 'rdn',
'allowlist': [COMMISSIONER]
},
}
def test(... | USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import unittest
import config
import mesh_cop
import thread_cert
from pktverify.consts import MGMT_PENDING_GET_URI, MGMT_PENDING_SET_URI, NM_CHANNEL_TLV, NM_PAN_ID_TLV, NM_NETWORK_NAME_TLV, NM_NETWORK_MESH_LOCAL_PREFIX_TLV, NM_PSKC_TLV, NM... | 256 | 256 | 2,201 | 17 | 238 | sarah-iot/openthread | tests/scripts/thread-cert/Cert_9_2_19_PendingDatasetGet.py | Python | Cert_9_2_19_PendingDatasetGet | Cert_9_2_19_PendingDatasetGet | 59 | 289 | 59 | 59 | eaf1fd414d21478dde6e31edd5ff9a489b211f51 | bigcode/the-stack | train |
203cdfc09a85c2a956e5ec19 | train | function | def smart_divide(func):
def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return inner
| def smart_divide(func):
| def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return inner
| decorator's arg func..!!****")
# print(num + 1)
# my_decorator(test_in)
@my_decorator # this is exactly similar to: my_decorator(test_in)
def test_in():
print("***I m decorator's arg func..!!****")
def smart_divide(func):
| 64 | 64 | 59 | 6 | 58 | PranaliRPatil/Python_OOP_Basics | decorators_test.py | Python | smart_divide | smart_divide | 17 | 25 | 17 | 17 | 4584ce0226f3227d821ba5f5941b10ea282b3488 | bigcode/the-stack | train |
a9011d59fc6f85e06b4af0e4 | train | function | def my_decorator(func):
print("Inside decorator")
func()
print("End decorator\n*******###*********")
| def my_decorator(func):
| print("Inside decorator")
func()
print("End decorator\n*******###*********")
| #https://www.programiz.com/python-programming/decorator
#https://realpython.com/primer-on-python-decorators/
def my_decorator(func):
| 33 | 64 | 26 | 6 | 27 | PranaliRPatil/Python_OOP_Basics | decorators_test.py | Python | my_decorator | my_decorator | 3 | 6 | 3 | 3 | c74833b8703fbbb5a38a20d7bf7b8c544f8b86df | bigcode/the-stack | train |
988999e8887e0129f9aeda8e | train | function | @my_decorator # this is exactly similar to: my_decorator(test_in)
def test_in():
print("***I m decorator's arg func..!!****")
| @my_decorator # this is exactly similar to: my_decorator(test_in)
def test_in():
| print("***I m decorator's arg func..!!****")
| print("End decorator\n*******###*********")
def test_in():
print("***I m decorator's arg func..!!****")
# print(num + 1)
# my_decorator(test_in)
@my_decorator # this is exactly similar to: my_decorator(test_in)
def test_in():
| 64 | 64 | 35 | 22 | 42 | PranaliRPatil/Python_OOP_Basics | decorators_test.py | Python | test_in | test_in | 13 | 15 | 13 | 14 | cf834679d00d7475b32019af94d3d809caa84296 | bigcode/the-stack | train |
bd28bac8f37b1fc1ceceaab5 | train | function | @smart_divide
def divide(a, b):
print(a/b)
| @smart_divide
def divide(a, b):
| print(a/b)
| def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return inner
@smart_divide
def divide(a, b):
| 64 | 64 | 16 | 11 | 52 | PranaliRPatil/Python_OOP_Basics | decorators_test.py | Python | divide | divide | 27 | 29 | 27 | 28 | 4b06f8312c9a22bfc7446f3a3b3d8b38774022a8 | bigcode/the-stack | train |
85df27105305de8deead856d | train | function | def test_in():
print("***I m decorator's arg func..!!****")
| def test_in():
| print("***I m decorator's arg func..!!****")
| #https://www.programiz.com/python-programming/decorator
#https://realpython.com/primer-on-python-decorators/
def my_decorator(func):
print("Inside decorator")
func()
print("End decorator\n*******###*********")
def test_in():
| 57 | 64 | 17 | 4 | 53 | PranaliRPatil/Python_OOP_Basics | decorators_test.py | Python | test_in | test_in | 8 | 9 | 8 | 8 | ebb7f168ef587e1fbc6d7e49e4ce6a96f53ba193 | bigcode/the-stack | train |
92db5ecf77e50fd36452954c | train | class | class CustomObjectReference(Reference):
"Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectReferenceSchema`."
#: Optional :class:`commercetools.types.CustomObject`
obj: typing.Optional["CustomObject"]
def __init__(
self,
*,
type_id: typing.Optional["R... | class CustomObjectReference(Reference):
| "Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectReferenceSchema`."
#: Optional :class:`commercetools.types.CustomObject`
obj: typing.Optional["CustomObject"]
def __init__(
self,
*,
type_id: typing.Optional["ReferenceTypeId"] = None,
id: typ... | super().__init__()
def __repr__(self) -> str:
return (
"CustomObjectPagedQueryResponse(count=%r, total=%r, offset=%r, results=%r)"
% (self.count, self.total, self.offset, self.results)
)
class CustomObjectReference(Reference):
| 64 | 64 | 173 | 7 | 57 | mbarga/commercetools-python-sdk | src/commercetools/types/_custom_object.py | Python | CustomObjectReference | CustomObjectReference | 128 | 148 | 128 | 128 | 813d14344e928eb8510aacfd40770791f03d33bc | bigcode/the-stack | train |
38de8e39e987e4963b446536 | train | class | class CustomObjectPagedQueryResponse(_BaseType):
"Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectPagedQueryResponseSchema`."
#: :class:`int`
count: typing.Optional[int]
#: Optional :class:`int`
total: typing.Optional[int]
#: :class:`int`
offset: typing.Optional... | class CustomObjectPagedQueryResponse(_BaseType):
| "Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectPagedQueryResponseSchema`."
#: :class:`int`
count: typing.Optional[int]
#: Optional :class:`int`
total: typing.Optional[int]
#: :class:`int`
offset: typing.Optional[int]
#: List of :class:`commercetools.types.... |
self.version = version
super().__init__()
def __repr__(self) -> str:
return "CustomObjectDraft(container=%r, key=%r, value=%r, version=%r)" % (
self.container,
self.key,
self.value,
self.version,
)
class CustomObjectPagedQueryResponse... | 74 | 74 | 247 | 10 | 64 | mbarga/commercetools-python-sdk | src/commercetools/types/_custom_object.py | Python | CustomObjectPagedQueryResponse | CustomObjectPagedQueryResponse | 96 | 125 | 96 | 96 | dc335f00b3a13aa9078cc2e66f33a947cd40615f | bigcode/the-stack | train |
2fd2bc707b5f305238274e8d | train | class | class CustomObject(BaseResource):
"Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectSchema`."
#: :class:`str`
container: typing.Optional[str]
#: :class:`str`
key: typing.Optional[str]
#: :class:`typing.Any`
value: typing.Optional[typing.Any]
def __init__(
... | class CustomObject(BaseResource):
| "Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectSchema`."
#: :class:`str`
container: typing.Optional[str]
#: :class:`str`
key: typing.Optional[str]
#: :class:`typing.Any`
value: typing.Optional[typing.Any]
def __init__(
self,
*,
id:... | # DO NOT EDIT! This file is automatically generated
import datetime
import typing
from commercetools.types._abstract import _BaseType
from commercetools.types._common import BaseResource, Reference, ReferenceTypeId
__all__ = [
"CustomObject",
"CustomObjectDraft",
"CustomObjectPagedQueryResponse",
"Cu... | 83 | 90 | 302 | 6 | 77 | mbarga/commercetools-python-sdk | src/commercetools/types/_custom_object.py | Python | CustomObject | CustomObject | 17 | 59 | 17 | 17 | aed84af0826e5cece6e1ed81243e6ff42dc91c45 | bigcode/the-stack | train |
6237f3f1baa62866a70c392c | train | class | class CustomObjectDraft(_BaseType):
"Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectDraftSchema`."
#: :class:`str`
container: typing.Optional[str]
#: :class:`str`
key: typing.Optional[str]
#: :class:`typing.Any`
value: typing.Optional[typing.Any]
#: Optiona... | class CustomObjectDraft(_BaseType):
| "Corresponding marshmallow schema is :class:`commercetools.schemas.CustomObjectDraftSchema`."
#: :class:`str`
container: typing.Optional[str]
#: :class:`str`
key: typing.Optional[str]
#: :class:`typing.Any`
value: typing.Optional[typing.Any]
#: Optional :class:`int`
version: typing.O... | _at=%r, last_modified_at=%r, container=%r, key=%r, value=%r)"
% (
self.id,
self.version,
self.created_at,
self.last_modified_at,
self.container,
self.key,
self.value,
)
)
class... | 68 | 68 | 228 | 8 | 60 | mbarga/commercetools-python-sdk | src/commercetools/types/_custom_object.py | Python | CustomObjectDraft | CustomObjectDraft | 62 | 93 | 62 | 62 | 5518241639ba5d7934bf67a93a570e2238138aed | bigcode/the-stack | train |
713c277a58726b0028b71be0 | train | class | class MathguideConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'mathguide'
| class MathguideConfig(AppConfig):
| default_auto_field = 'django.db.models.BigAutoField'
name = 'mathguide'
| from django.apps import AppConfig
class MathguideConfig(AppConfig):
| 14 | 64 | 27 | 7 | 6 | LHY-42/matholympiadguide | mathguide/apps.py | Python | MathguideConfig | MathguideConfig | 4 | 6 | 4 | 4 | e570e7403525b68f466cf955d2ecd7b25e128f57 | bigcode/the-stack | train |
abcc56f695aa2c9784e172c4 | train | function | def requires_backends(obj, backends):
if not isinstance(backends, (list, tuple)):
backends = [backends]
name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
if not all(BACKENDS_MAPPING[backend][0]() for backend in backends):
raise ImportError("".join([BACKENDS_MAPPING... | def requires_backends(obj, backends):
| if not isinstance(backends, (list, tuple)):
backends = [backends]
name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
if not all(BACKENDS_MAPPING[backend][0]() for backend in backends):
raise ImportError("".join([BACKENDS_MAPPING[backend][1].format(name) for backend ... | ERS_IMPORT_ERROR)),
("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
("vision", (is_vision_available, VISION_IMPORT_ERROR)),
("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)),
]
)
def requires_backends(obj, backends):
| 64 | 64 | 95 | 9 | 55 | MichalPitr/transformers | src/transformers/file_utils.py | Python | requires_backends | requires_backends | 606 | 612 | 606 | 606 | 88d69d1aa3b100daffa968f95914fc5d9933c3ac | bigcode/the-stack | train |
c0dc29117101bd5011b8ce72 | train | function | def is_py3nvml_available():
return importlib.util.find_spec("py3nvml") is not None
| def is_py3nvml_available():
| return importlib.util.find_spec("py3nvml") is not None
| return False
return importlib.util.find_spec("torch_xla.core.xla_model") is not None
def is_datasets_available():
return _datasets_available
def is_psutil_available():
return importlib.util.find_spec("psutil") is not None
def is_py3nvml_available():
| 64 | 64 | 25 | 8 | 55 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_py3nvml_available | is_py3nvml_available | 322 | 323 | 322 | 322 | 733e4e4957712a033378e6e79e3a4753555fd362 | bigcode/the-stack | train |
95553f892e5f558acb030445 | train | function | def is_vision_available():
return importlib.util.find_spec("PIL") is not None
| def is_vision_available():
| return importlib.util.find_spec("PIL") is not None
| is_protobuf_available():
if importlib.util.find_spec("google") is None:
return False
return importlib.util.find_spec("google.protobuf") is not None
def is_tokenizers_available():
return importlib.util.find_spec("tokenizers") is not None
def is_vision_available():
| 64 | 64 | 21 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_vision_available | is_vision_available | 358 | 359 | 358 | 358 | 0a480f980adf3eed65c4fa7d63937c44b12383ec | bigcode/the-stack | train |
354221589fb308c21d68e553 | train | function | def is_pandas_available():
return importlib.util.find_spec("pandas") is not None
| def is_pandas_available():
| return importlib.util.find_spec("pandas") is not None
| ODE_PID" in os.environ:
raise ImportError("vscode")
return importlib.util.find_spec("IPython") is not None
except (AttributeError, ImportError, KeyError):
return False
def is_scatter_available():
return _scatter_available
def is_pandas_available():
| 64 | 64 | 21 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_pandas_available | is_pandas_available | 380 | 381 | 380 | 380 | 9a4b7708f8a9a86d73b803805fbbd3df3624fd85 | bigcode/the-stack | train |
7131ea6b7951f9c68abed206 | train | function | def is_remote_url(url_or_filename):
parsed = urlparse(url_or_filename)
return parsed.scheme in ("http", "https")
| def is_remote_url(url_or_filename):
| parsed = urlparse(url_or_filename)
return parsed.scheme in ("http", "https")
| f"The function {fn} should have an empty 'Return:' or 'Returns:' in its docstring as placeholder, current docstring is:\n{docstrings}"
)
fn.__doc__ = docstrings
return fn
return docstring_decorator
def is_remote_url(url_or_filename):
| 64 | 64 | 28 | 8 | 55 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_remote_url | is_remote_url | 1,162 | 1,164 | 1,162 | 1,162 | f3d38666696ad6c7d2f2f7ee2862f92d0868be91 | bigcode/the-stack | train |
1909346ac296c20976e0627c | train | function | def is_offline_mode():
return _is_offline_mode
| def is_offline_mode():
| return _is_offline_mode
| This is the version of torch required to run torch.fx features.
TORCH_FX_REQUIRED_VERSION = version.parse("1.8")
_is_offline_mode = True if os.environ.get("TRANSFORMERS_OFFLINE", "0").upper() in ENV_VARS_TRUE_VALUES else False
def is_offline_mode():
| 64 | 64 | 14 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_offline_mode | is_offline_mode | 261 | 262 | 261 | 261 | ccae0a114ab4dd2827891bc2eb5fca9d5eac4877 | bigcode/the-stack | train |
4a6cfa1e4d02cef39d51bc09 | train | function | def is_scipy_available():
return importlib.util.find_spec("scipy") is not None
| def is_scipy_available():
| return importlib.util.find_spec("scipy") is not None
| 3nvml_available():
return importlib.util.find_spec("py3nvml") is not None
def is_apex_available():
return importlib.util.find_spec("apex") is not None
def is_faiss_available():
return _faiss_available
def is_scipy_available():
| 64 | 64 | 22 | 7 | 56 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_scipy_available | is_scipy_available | 334 | 335 | 334 | 334 | 1678d3a35d7f95019f92512779ed6f806d996ff7 | bigcode/the-stack | train |
031286ad73bff9f7b09cc568 | train | class | class PaddingStrategy(ExplicitEnum):
"""
Possible values for the ``padding`` argument in :meth:`PreTrainedTokenizerBase.__call__`. Useful for tab-completion
in an IDE.
"""
LONGEST = "longest"
MAX_LENGTH = "max_length"
DO_NOT_PAD = "do_not_pad"
| class PaddingStrategy(ExplicitEnum):
| """
Possible values for the ``padding`` argument in :meth:`PreTrainedTokenizerBase.__call__`. Useful for tab-completion
in an IDE.
"""
LONGEST = "longest"
MAX_LENGTH = "max_length"
DO_NOT_PAD = "do_not_pad"
| for missing values.
"""
@classmethod
def _missing_(cls, value):
raise ValueError(
f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
)
class PaddingStrategy(ExplicitEnum):
| 64 | 64 | 70 | 7 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | PaddingStrategy | PaddingStrategy | 1,841 | 1,849 | 1,841 | 1,841 | 0571de3418fbc68866dfa7038d5f664080d7b80c | bigcode/the-stack | train |
77fdd81937ee922d78bd1fe9 | train | function | def torch_only_method(fn):
def wrapper(*args, **kwargs):
if not _torch_available:
raise ImportError(
"You need to install pytorch to use this method or class, "
"or activate it with environment variables USE_TORCH=1 and USE_TF=0."
)
else:
... | def torch_only_method(fn):
| def wrapper(*args, **kwargs):
if not _torch_available:
raise ImportError(
"You need to install pytorch to use this method or class, "
"or activate it with environment variables USE_TORCH=1 and USE_TF=0."
)
else:
return fn(*args, **k... | ():
return _timm_available
def is_torchaudio_available():
return _torchaudio_available
def is_speech_available():
# For now this depends on torchaudio but the exact dependency might evolve in the future.
return _torchaudio_available
def torch_only_method(fn):
| 64 | 64 | 82 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | torch_only_method | torch_only_method | 443 | 453 | 443 | 443 | 580dab927089513f2cea7476bd29b1c570244d39 | bigcode/the-stack | train |
50905e2d449fbff3c27dce72 | train | class | class TensorType(ExplicitEnum):
"""
Possible values for the ``return_tensors`` argument in :meth:`PreTrainedTokenizerBase.__call__`. Useful for
tab-completion in an IDE.
"""
PYTORCH = "pt"
TENSORFLOW = "tf"
NUMPY = "np"
JAX = "jax"
| class TensorType(ExplicitEnum):
| """
Possible values for the ``return_tensors`` argument in :meth:`PreTrainedTokenizerBase.__call__`. Useful for
tab-completion in an IDE.
"""
PYTORCH = "pt"
TENSORFLOW = "tf"
NUMPY = "np"
JAX = "jax"
| the ``padding`` argument in :meth:`PreTrainedTokenizerBase.__call__`. Useful for tab-completion
in an IDE.
"""
LONGEST = "longest"
MAX_LENGTH = "max_length"
DO_NOT_PAD = "do_not_pad"
class TensorType(ExplicitEnum):
| 64 | 64 | 76 | 7 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | TensorType | TensorType | 1,852 | 1,861 | 1,852 | 1,852 | 440fd0142ee6e97a41834a048921f5792191e8b5 | bigcode/the-stack | train |
ccebc3ba9765725823169245 | train | function | def is_torch_cuda_available():
if is_torch_available():
import torch
return torch.cuda.is_available()
else:
return False
| def is_torch_cuda_available():
| if is_torch_available():
import torch
return torch.cuda.is_available()
else:
return False
| _is_offline_mode = True if os.environ.get("TRANSFORMERS_OFFLINE", "0").upper() in ENV_VARS_TRUE_VALUES else False
def is_offline_mode():
return _is_offline_mode
def is_torch_available():
return _torch_available
def is_torch_cuda_available():
| 64 | 64 | 32 | 7 | 56 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_torch_cuda_available | is_torch_cuda_available | 269 | 275 | 269 | 269 | 8d8d803792bd336bd8570b4b79c7544ac5c4231d | bigcode/the-stack | train |
17b33f290e3402b90f4f8cc0 | train | function | def add_start_docstrings_to_model_forward(*docstr):
def docstring_decorator(fn):
class_name = f":class:`~transformers.{fn.__qualname__.split('.')[0]}`"
intro = f" The {class_name} forward method, overrides the :func:`__call__` special method."
note = r"""
.. note::
Although th... | def add_start_docstrings_to_model_forward(*docstr):
| def docstring_decorator(fn):
class_name = f":class:`~transformers.{fn.__qualname__.split('.')[0]}`"
intro = f" The {class_name} forward method, overrides the :func:`__call__` special method."
note = r"""
.. note::
Although the recipe for forward pass needs to be defined within... | _docstrings(*docstr):
def docstring_decorator(fn):
fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
return fn
return docstring_decorator
def add_start_docstrings_to_model_forward(*docstr):
| 64 | 64 | 175 | 12 | 51 | MichalPitr/transformers | src/transformers/file_utils.py | Python | add_start_docstrings_to_model_forward | add_start_docstrings_to_model_forward | 623 | 637 | 623 | 623 | 37029ffbb65332e71ad3d6f67df1f56ff56306cd | bigcode/the-stack | train |
130bf754440381a3e00a1778 | train | function | def is_training_run_on_sagemaker():
return "SAGEMAKER_JOB_NAME" in os.environ
| def is_training_run_on_sagemaker():
| return "SAGEMAKER_JOB_NAME" in os.environ
| _mpi_enabled", False):
return False
except json.JSONDecodeError:
return False
# Lastly, check if the `smdistributed` module is present.
return importlib.util.find_spec("smdistributed") is not None
def is_training_run_on_sagemaker():
| 64 | 64 | 22 | 9 | 54 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_training_run_on_sagemaker | is_training_run_on_sagemaker | 422 | 423 | 422 | 422 | 8746f77794007988a9cda868d1ecd680d29ef352 | bigcode/the-stack | train |
3d674ed696f538aece200322 | train | function | def is_local_clone(repo_path, repo_url):
"""
Checks if the folder in `repo_path` is a local clone of `repo_url`.
"""
# First double-check that `repo_path` is a git repo
if not os.path.exists(os.path.join(repo_path, ".git")):
return False
test_git = subprocess.run("git branch".split(), cw... | def is_local_clone(repo_path, repo_url):
| """
Checks if the folder in `repo_path` is a local clone of `repo_url`.
"""
# First double-check that `repo_path` is a git repo
if not os.path.exists(os.path.join(repo_path, ".git")):
return False
test_git = subprocess.run("git branch".split(), cwd=repo_path)
if test_git.returncode !... | = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
def is_local_clone(repo_path, repo_url):
| 64 | 64 | 164 | 10 | 53 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_local_clone | is_local_clone | 1,910 | 1,931 | 1,910 | 1,910 | 8210980e76df9c226f0dbb374c8d33a35e107088 | bigcode/the-stack | train |
e169eaab5624d010e0b2f5f8 | train | function | def url_to_filename(url: str, etag: Optional[str] = None) -> str:
"""
Convert `url` into a hashed filename in a repeatable way. If `etag` is specified, append its hash to the url's,
delimited by a period. If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the name so that TF 2.0 can
identify it... | def url_to_filename(url: str, etag: Optional[str] = None) -> str:
| """
Convert `url` into a hashed filename in a repeatable way. If `etag` is specified, append its hash to the url's,
delimited by a period. If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the name so that TF 2.0 can
identify it as a HDF5 file (see
https://github.com/tensorflow/tensorflow/... | else:
return f"{endpoint}/{model_id}/{filename}"
if revision is None:
revision = "main"
return HUGGINGFACE_CO_PREFIX.format(model_id=model_id, revision=revision, filename=filename)
def url_to_filename(url: str, etag: Optional[str] = None) -> str:
| 68 | 68 | 228 | 20 | 48 | MichalPitr/transformers | src/transformers/file_utils.py | Python | url_to_filename | url_to_filename | 1,202 | 1,219 | 1,202 | 1,202 | 7131a09d9632574cb72a52f510651ba31d0de858 | bigcode/the-stack | train |
3aebf2f4d53d8a4c7a995a03 | train | function | def hf_bucket_url(
model_id: str, filename: str, subfolder: Optional[str] = None, revision: Optional[str] = None, mirror=None
) -> str:
"""
Resolve a model identifier, a file name, and an optional revision id, to a huggingface.co-hosted url, redirecting
to Cloudfront (a Content Delivery Network, or CDN)... | def hf_bucket_url(
model_id: str, filename: str, subfolder: Optional[str] = None, revision: Optional[str] = None, mirror=None
) -> str:
| """
Resolve a model identifier, a file name, and an optional revision id, to a huggingface.co-hosted url, redirecting
to Cloudfront (a Content Delivery Network, or CDN) for large files.
Cloudfront is replicated over the globe so downloads are way faster for the end user (and it also lowers our
band... | fn} should have an empty 'Return:' or 'Returns:' in its docstring as placeholder, current docstring is:\n{docstrings}"
)
fn.__doc__ = docstrings
return fn
return docstring_decorator
def is_remote_url(url_or_filename):
parsed = urlparse(url_or_filename)
return parsed.scheme in ... | 119 | 119 | 398 | 39 | 80 | MichalPitr/transformers | src/transformers/file_utils.py | Python | hf_bucket_url | hf_bucket_url | 1,167 | 1,199 | 1,167 | 1,169 | 827271e1c7ae4159b8c569e5e2d2998c8312ec8e | bigcode/the-stack | train |
f53baf9aef8e89059fbb37cf | train | function | def replace_return_docstrings(output_type=None, config_class=None):
def docstring_decorator(fn):
docstrings = fn.__doc__
lines = docstrings.split("\n")
i = 0
while i < len(lines) and re.search(r"^\s*Returns?:\s*$", lines[i]) is None:
i += 1
if i < len(lines):
... | def replace_return_docstrings(output_type=None, config_class=None):
| def docstring_decorator(fn):
docstrings = fn.__doc__
lines = docstrings.split("\n")
i = 0
while i < len(lines) and re.search(r"^\s*Returns?:\s*$", lines[i]) is None:
i += 1
if i < len(lines):
lines[i] = _prepare_output_docstrings(output_type, config_cl... | None else ""
built_doc = code_sample.format(**doc_kwargs)
fn.__doc__ = (fn.__doc__ or "") + "".join(docstr) + output_doc + built_doc
return fn
return docstring_decorator
def replace_return_docstrings(output_type=None, config_class=None):
| 64 | 64 | 175 | 13 | 50 | MichalPitr/transformers | src/transformers/file_utils.py | Python | replace_return_docstrings | replace_return_docstrings | 1,142 | 1,159 | 1,142 | 1,142 | c2b64c48cd5623797a030ba3c6ca5e3316d0a5c2 | bigcode/the-stack | train |
d85b2b0bde97505bfb67e440 | train | function | def is_sentencepiece_available():
return importlib.util.find_spec("sentencepiece") is not None
| def is_sentencepiece_available():
| return importlib.util.find_spec("sentencepiece") is not None
| return importlib.util.find_spec("scipy") is not None
def is_sklearn_available():
if importlib.util.find_spec("sklearn") is None:
return False
return is_scipy_available() and importlib.util.find_spec("sklearn.metrics")
def is_sentencepiece_available():
| 64 | 64 | 21 | 6 | 58 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_sentencepiece_available | is_sentencepiece_available | 344 | 345 | 344 | 344 | 39d75ce2c2893fa209351b0e474035f05b935977 | bigcode/the-stack | train |
d9ad2c822d02b1309cf3ce3c | train | function | def is_tf_available():
return _tf_available
| def is_tf_available():
| return _tf_available
| lib_metadata.version("torch"))
_torch_fx_available = (torch_version.major, torch_version.minor) == (
TORCH_FX_REQUIRED_VERSION.major,
TORCH_FX_REQUIRED_VERSION.minor,
)
def is_torch_fx_available():
return _torch_fx_available
def is_tf_available():
| 64 | 64 | 11 | 5 | 58 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_tf_available | is_tf_available | 291 | 292 | 291 | 291 | b26f8e8e3187e91dfb6aebaf4b4bac49cb792332 | bigcode/the-stack | train |
2a1dcdae6c1462617be8d608 | train | function | def is_faiss_available():
return _faiss_available
| def is_faiss_available():
| return _faiss_available
| .util.find_spec("psutil") is not None
def is_py3nvml_available():
return importlib.util.find_spec("py3nvml") is not None
def is_apex_available():
return importlib.util.find_spec("apex") is not None
def is_faiss_available():
| 64 | 64 | 14 | 7 | 56 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_faiss_available | is_faiss_available | 330 | 331 | 330 | 330 | 39ac0eb3d413850a67aa53e601115725829b49b4 | bigcode/the-stack | train |
875d025d95a9b13baeeb634d | train | class | class PushToHubMixin:
"""
A Mixin containing the functionality to push a model or tokenizer to the hub.
"""
def push_to_hub(
self,
repo_path_or_name: Optional[str] = None,
repo_url: Optional[str] = None,
use_temp_dir: bool = False,
commit_message: Optional[str] =... | class PushToHubMixin:
| """
A Mixin containing the functionality to push a model or tokenizer to the hub.
"""
def push_to_hub(
self,
repo_path_or_name: Optional[str] = None,
repo_url: Optional[str] = None,
use_temp_dir: bool = False,
commit_message: Optional[str] = None,
organiz... | Returns a copy of a function f."""
# Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
... | 256 | 256 | 1,710 | 6 | 250 | MichalPitr/transformers | src/transformers/file_utils.py | Python | PushToHubMixin | PushToHubMixin | 1,934 | 2,107 | 1,934 | 1,934 | 398445593a3cb822410223285f100309d7adcc0d | bigcode/the-stack | train |
0e39dfd11810ab12692f1fac | train | function | def is_in_notebook():
try:
# Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
get_ipython = sys.modules["IPython"].get_ipython
if "IPKernelApp" not in get_ipython().config:
raise ImportError("console")
if "VSCODE_PID" in o... | def is_in_notebook():
| try:
# Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
get_ipython = sys.modules["IPython"].get_ipython
if "IPKernelApp" not in get_ipython().config:
raise ImportError("console")
if "VSCODE_PID" in os.environ:
... |
return importlib.util.find_spec("google.protobuf") is not None
def is_tokenizers_available():
return importlib.util.find_spec("tokenizers") is not None
def is_vision_available():
return importlib.util.find_spec("PIL") is not None
def is_in_notebook():
| 64 | 64 | 129 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_in_notebook | is_in_notebook | 362 | 373 | 362 | 362 | 8bffd1a5f7c87c343973803c1d57b3d47f4ea148 | bigcode/the-stack | train |
a98c4c378ff033d45806d1a4 | train | function | def is_soundfile_availble():
return _soundfile_available
| def is_soundfile_availble():
| return _soundfile_available
| # Lastly, check if the `smdistributed` module is present.
return importlib.util.find_spec("smdistributed") is not None
def is_training_run_on_sagemaker():
return "SAGEMAKER_JOB_NAME" in os.environ
def is_soundfile_availble():
| 64 | 64 | 15 | 8 | 55 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_soundfile_availble | is_soundfile_availble | 426 | 427 | 426 | 426 | 2a9269df79dadda8e9c1ff4622a5d361d3bf218b | bigcode/the-stack | train |
5f58c1a6c56b5daf4fae0420 | train | function | def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str:
"""
Formats a user-agent string with basic info about a request.
"""
ua = f"transformers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}"
if is_torch_available():
ua += f"; torch/{_torch_version}"
... | def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str:
| """
Formats a user-agent string with basic info about a request.
"""
ua = f"transformers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}"
if is_torch_available():
ua += f"; torch/{_torch_version}"
if is_tf_available():
ua += f"; tensorflow/{_tf_version}"
... | sm_distributed_training": runs_distributed_training,
"sm_deep_learning_container": dlc_container_used,
"sm_deep_learning_container_tag": dlc_tag,
"sm_account_id": account_id,
}
return sagemaker_object
def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str:
| 75 | 75 | 250 | 21 | 53 | MichalPitr/transformers | src/transformers/file_utils.py | Python | http_user_agent | http_user_agent | 1,409 | 1,429 | 1,409 | 1,409 | d54dd3a06aea76865f046203880dbd165e8c9749 | bigcode/the-stack | train |
eae3d4d3c5ff399270521e3c | train | function | def is_timm_available():
return _timm_available
| def is_timm_available():
| return _timm_available
| module is present.
return importlib.util.find_spec("smdistributed") is not None
def is_training_run_on_sagemaker():
return "SAGEMAKER_JOB_NAME" in os.environ
def is_soundfile_availble():
return _soundfile_available
def is_timm_available():
| 64 | 64 | 13 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_timm_available | is_timm_available | 430 | 431 | 430 | 430 | 1fb8d68e94d097a99f1d5d85739ca687387508d8 | bigcode/the-stack | train |
ce4d74c9b6bad4164ad19fc4 | train | function | def _get_indent(t):
"""Returns the indentation in the first line of t"""
search = re.search(r"^(\s*)\S", t)
return "" if search is None else search.groups()[0]
| def _get_indent(t):
| """Returns the indentation in the first line of t"""
search = re.search(r"^(\s*)\S", t)
return "" if search is None else search.groups()[0]
| full_output_type}` or a tuple of
:obj:`tf.Tensor` (if ``return_dict=False`` is passed or when ``config.return_dict=False``) comprising various
elements depending on the configuration (:class:`~transformers.{config_class}`) and inputs.
"""
def _get_indent(t):
| 64 | 64 | 47 | 6 | 58 | MichalPitr/transformers | src/transformers/file_utils.py | Python | _get_indent | _get_indent | 666 | 669 | 666 | 666 | 6dddb0600b5fad3f5a5d327c4be89fb717bc5b88 | bigcode/the-stack | train |
4616a685f4604b33500ff5cd | train | function | def define_sagemaker_information():
try:
instance_data = requests.get(os.environ["ECS_CONTAINER_METADATA_URI"]).json()
dlc_container_used = instance_data["Image"]
dlc_tag = instance_data["Image"].split(":")[1]
except Exception:
dlc_container_used = None
dlc_tag = None
... | def define_sagemaker_information():
| try:
instance_data = requests.get(os.environ["ECS_CONTAINER_METADATA_URI"]).json()
dlc_container_used = instance_data["Image"]
dlc_tag = instance_data["Image"].split(":")[1]
except Exception:
dlc_container_used = None
dlc_tag = None
sagemaker_params = json.loads(os.g... | tracted)
zip_file.close()
elif tarfile.is_tarfile(output_path):
tar_file = tarfile.open(output_path)
tar_file.extractall(output_path_extracted)
tar_file.close()
else:
raise EnvironmentError(f"Archive format of {o... | 82 | 82 | 274 | 7 | 74 | MichalPitr/transformers | src/transformers/file_utils.py | Python | define_sagemaker_information | define_sagemaker_information | 1,383 | 1,406 | 1,383 | 1,383 | 2f1bd4e925b907e024d25a05ac053067be394934 | bigcode/the-stack | train |
02e98f9566049dd57213105d | train | function | def get_cached_models(cache_dir: Union[str, Path] = None) -> List[Tuple]:
"""
Returns a list of tuples representing model binaries that are cached locally. Each tuple has shape
:obj:`(model_url, etag, size_MB)`. Filenames in :obj:`cache_dir` are use to get the metadata for each model, only
urls ending w... | def get_cached_models(cache_dir: Union[str, Path] = None) -> List[Tuple]:
| """
Returns a list of tuples representing model binaries that are cached locally. Each tuple has shape
:obj:`(model_url, etag, size_MB)`. Filenames in :obj:`cache_dir` are use to get the metadata for each model, only
urls ending with `.bin` are added.
Args:
cache_dir (:obj:`Union[str, Path]... | "
if not os.path.exists(meta_path):
raise EnvironmentError(f"file {meta_path} not found")
with open(meta_path, encoding="utf-8") as meta_file:
metadata = json.load(meta_file)
url = metadata["url"]
etag = metadata["etag"]
return url, etag
def get_cached_models(cache_dir: Union[str, ... | 90 | 90 | 303 | 20 | 69 | MichalPitr/transformers | src/transformers/file_utils.py | Python | get_cached_models | get_cached_models | 1,248 | 1,278 | 1,248 | 1,248 | 85a425aac141a06d4f2592b302cac18483572e21 | bigcode/the-stack | train |
43cdae2150a3f1fa5e72b4c5 | train | function | def to_py_obj(obj):
"""
Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list.
"""
if isinstance(obj, (dict, UserDict)):
return {k: to_py_obj(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple)):
return [to_py_obj(o) for o in obj]
eli... | def to_py_obj(obj):
| """
Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list.
"""
if isinstance(obj, (dict, UserDict)):
return {k: to_py_obj(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple)):
return [to_py_obj(o) for o in obj]
elif is_tf_available() ... | isinstance(x, torch.device)
def _is_tensorflow(x):
import tensorflow as tf
return isinstance(x, tf.Tensor)
def _is_jax(x):
import jax.numpy as jnp # noqa: F811
return isinstance(x, jnp.ndarray)
def to_py_obj(obj):
| 64 | 64 | 147 | 6 | 58 | MichalPitr/transformers | src/transformers/file_utils.py | Python | to_py_obj | to_py_obj | 1,722 | 1,737 | 1,722 | 1,722 | dc3f83d83b969841b81ed2a47546f1bd70bc85fe | bigcode/the-stack | train |
b03996bb3a24187f2f03982e | train | function | def is_flax_available():
return _flax_available
| def is_flax_available():
| return _flax_available
| CH_FX_REQUIRED_VERSION.major,
TORCH_FX_REQUIRED_VERSION.minor,
)
def is_torch_fx_available():
return _torch_fx_available
def is_tf_available():
return _tf_available
def is_onnx_available():
return _onnx_available
def is_flax_available():
| 64 | 64 | 13 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_flax_available | is_flax_available | 299 | 300 | 299 | 299 | 33ed288a4f1e37b4abefc21a6647ffdc409ff9eb | bigcode/the-stack | train |
341b9e600c2ecc6c008f3816 | train | class | class ModelOutput(OrderedDict):
"""
Base class for all model outputs as dataclass. Has a ``__getitem__`` that allows indexing by integer or slice (like
a tuple) or strings (like a dictionary) that will ignore the ``None`` attributes. Otherwise behaves like a regular
python dictionary.
.. warning::
... | class ModelOutput(OrderedDict):
| """
Base class for all model outputs as dataclass. Has a ``__getitem__`` that allows indexing by integer or slice (like
a tuple) or strings (like a dictionary) that will ignore the ``None`` attributes. Otherwise behaves like a regular
python dictionary.
.. warning::
You can't unpack a :obj:... | torch
return isinstance(x, torch.Tensor)
def _is_torch_device(x):
import torch
return isinstance(x, torch.device)
def _is_tensorflow(x):
import tensorflow as tf
return isinstance(x, tf.Tensor)
def _is_jax(x):
import jax.numpy as jnp # noqa: F811
return isinstance(x, jnp.ndarray)
... | 236 | 236 | 788 | 7 | 228 | MichalPitr/transformers | src/transformers/file_utils.py | Python | ModelOutput | ModelOutput | 1,740 | 1,826 | 1,740 | 1,740 | d9497f8b96dfe5d3908c903c8ea45676dde65e53 | bigcode/the-stack | train |
b6916b62102df3a459cf0916 | train | function | def is_apex_available():
return importlib.util.find_spec("apex") is not None
| def is_apex_available():
| return importlib.util.find_spec("apex") is not None
| def is_datasets_available():
return _datasets_available
def is_psutil_available():
return importlib.util.find_spec("psutil") is not None
def is_py3nvml_available():
return importlib.util.find_spec("py3nvml") is not None
def is_apex_available():
| 64 | 64 | 21 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_apex_available | is_apex_available | 326 | 327 | 326 | 326 | b60ce3a0d220dcc979538a79bd45dbfaa5cc3709 | bigcode/the-stack | train |
eace067f09cf2d5c0477c602 | train | function | def add_end_docstrings(*docstr):
def docstring_decorator(fn):
fn.__doc__ = fn.__doc__ + "".join(docstr)
return fn
return docstring_decorator
| def add_end_docstrings(*docstr):
| def docstring_decorator(fn):
fn.__doc__ = fn.__doc__ + "".join(docstr)
return fn
return docstring_decorator
|
processing steps while the latter silently ignores them.
"""
fn.__doc__ = intro + note + "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
return fn
return docstring_decorator
def add_end_docstrings(*docstr):
| 64 | 64 | 44 | 9 | 54 | MichalPitr/transformers | src/transformers/file_utils.py | Python | add_end_docstrings | add_end_docstrings | 640 | 645 | 640 | 640 | 24d7a20bbf4cc21aee0b240663bebe06b1d3657f | bigcode/the-stack | train |
1fa060f9ce61513419e36ac9 | train | function | def cached_path(
url_or_filename,
cache_dir=None,
force_download=False,
proxies=None,
resume_download=False,
user_agent: Union[Dict, str, None] = None,
extract_compressed_file=False,
force_extract=False,
use_auth_token: Union[bool, str, None] = None,
local_files_only=False,
) -> ... | def cached_path(
url_or_filename,
cache_dir=None,
force_download=False,
proxies=None,
resume_download=False,
user_agent: Union[Dict, str, None] = None,
extract_compressed_file=False,
force_extract=False,
use_auth_token: Union[bool, str, None] = None,
local_files_only=False,
) -> ... | """
Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file
and cache it, and return the path to the cached file. If it's already a local path, make sure the file exists and
then return the path
Args:
cache_dir: specify a cache direc... | List[Tuple]: List of tuples each with shape :obj:`(model_url, etag, size_MB)`
"""
if cache_dir is None:
cache_dir = TRANSFORMERS_CACHE
elif isinstance(cache_dir, Path):
cache_dir = str(cache_dir)
cached_models = []
for file in os.listdir(cache_dir):
if file.endswith(".json"... | 256 | 256 | 941 | 82 | 173 | MichalPitr/transformers | src/transformers/file_utils.py | Python | cached_path | cached_path | 1,281 | 1,380 | 1,281 | 1,292 | d81e9863a6c346836df45670db8a5575173f0dbb | bigcode/the-stack | train |
fd9bc5ca156139375d21fcca | train | class | class cached_property(property):
"""
Descriptor that mimics @property but caches output in member variable.
From tensorflow_datasets
Built-in in functools from Python 3.8.
"""
def __get__(self, obj, objtype=None):
# See docs.python.org/3/howto/descriptor.html#properties
if obj... | class cached_property(property):
| """
Descriptor that mimics @property but caches output in member variable.
From tensorflow_datasets
Built-in in functools from Python 3.8.
"""
def __get__(self, obj, objtype=None):
# See docs.python.org/3/howto/descriptor.html#properties
if obj is None:
return self... | "creating metadata file for {cache_path}")
meta = {"url": url, "etag": etag}
meta_path = cache_path + ".json"
with open(meta_path, "w") as meta_file:
json.dump(meta, meta_file)
return cache_path
class cached_property(property):
| 64 | 64 | 147 | 5 | 58 | MichalPitr/transformers | src/transformers/file_utils.py | Python | cached_property | cached_property | 1,611 | 1,631 | 1,611 | 1,611 | ced42b4faab1cacde0341391df6d61cca04204f6 | bigcode/the-stack | train |
55df9da53319cbd6180ce00b | train | class | class ExplicitEnum(Enum):
"""
Enum with more explicit error message for missing values.
"""
@classmethod
def _missing_(cls, value):
raise ValueError(
f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
)
| class ExplicitEnum(Enum):
| """
Enum with more explicit error message for missing values.
"""
@classmethod
def _missing_(cls, value):
raise ValueError(
f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
)
| avoid recursion errors
super().__setattr__(key, value)
def to_tuple(self) -> Tuple[Any]:
"""
Convert self to a tuple containing all the attributes/keys that are not ``None``.
"""
return tuple(self[k] for k in self.keys())
class ExplicitEnum(Enum):
| 64 | 64 | 71 | 5 | 59 | MichalPitr/transformers | src/transformers/file_utils.py | Python | ExplicitEnum | ExplicitEnum | 1,829 | 1,838 | 1,829 | 1,829 | dd50e5c718a451fd8ca6b62399f629ab762d0bec | bigcode/the-stack | train |
02c2ed2e32b25ec8c61037ef | train | function | def get_from_cache(
url: str,
cache_dir=None,
force_download=False,
proxies=None,
etag_timeout=10,
resume_download=False,
user_agent: Union[Dict, str, None] = None,
use_auth_token: Union[bool, str, None] = None,
local_files_only=False,
) -> Optional[str]:
"""
Given a URL, loo... | def get_from_cache(
url: str,
cache_dir=None,
force_download=False,
proxies=None,
etag_timeout=10,
resume_download=False,
user_agent: Union[Dict, str, None] = None,
use_auth_token: Union[bool, str, None] = None,
local_files_only=False,
) -> Optional[str]:
| """
Given a URL, look for the corresponding file in the local cache. If it's not there, download it. Then return the
path to the cached file.
Return:
Local path (string) of file or if networking is off, last version of file cached on disk.
Raises:
In case of non-recoverable file (n... | ble up errors.
"""
headers = copy.deepcopy(headers)
if resume_size > 0:
headers["Range"] = f"bytes={resume_size}-"
r = requests.get(url, stream=True, proxies=proxies, headers=headers)
r.raise_for_status()
content_length = r.headers.get("Content-Length")
total = resume_size + int(cont... | 256 | 256 | 1,350 | 78 | 178 | MichalPitr/transformers | src/transformers/file_utils.py | Python | get_from_cache | get_from_cache | 1,458 | 1,608 | 1,458 | 1,468 | 449e85d2e49fa341cbd292509fa00eeddc7faba4 | bigcode/the-stack | train |
0d01c2f42aaee0b63eed8bb1 | train | function | def _is_jax(x):
import jax.numpy as jnp # noqa: F811
return isinstance(x, jnp.ndarray)
| def _is_jax(x):
| import jax.numpy as jnp # noqa: F811
return isinstance(x, jnp.ndarray)
| _torch(x):
import torch
return isinstance(x, torch.Tensor)
def _is_torch_device(x):
import torch
return isinstance(x, torch.device)
def _is_tensorflow(x):
import tensorflow as tf
return isinstance(x, tf.Tensor)
def _is_jax(x):
| 64 | 64 | 31 | 7 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | _is_jax | _is_jax | 1,716 | 1,719 | 1,716 | 1,716 | 60dfd089ef63293cffb8ca0a636f6473e9714d06 | bigcode/the-stack | train |
5d1b8a3849217bc6e8034ebd | train | function | def is_torch_tpu_available():
if not _torch_available:
return False
# This test is probably enough, but just in case, we unpack a bit.
if importlib.util.find_spec("torch_xla") is None:
return False
if importlib.util.find_spec("torch_xla.core") is None:
return False
return imp... | def is_torch_tpu_available():
| if not _torch_available:
return False
# This test is probably enough, but just in case, we unpack a bit.
if importlib.util.find_spec("torch_xla") is None:
return False
if importlib.util.find_spec("torch_xla.core") is None:
return False
return importlib.util.find_spec("torch_x... | or,
)
def is_torch_fx_available():
return _torch_fx_available
def is_tf_available():
return _tf_available
def is_onnx_available():
return _onnx_available
def is_flax_available():
return _flax_available
def is_torch_tpu_available():
| 64 | 64 | 96 | 8 | 55 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_torch_tpu_available | is_torch_tpu_available | 303 | 311 | 303 | 303 | eac46398fa5f1f4a62dfa479ed62de523a04b863 | bigcode/the-stack | train |
d6c925dd692cddc7dbbee58d | train | function | def is_scatter_available():
return _scatter_available
| def is_scatter_available():
| return _scatter_available
| raise ImportError("console")
if "VSCODE_PID" in os.environ:
raise ImportError("vscode")
return importlib.util.find_spec("IPython") is not None
except (AttributeError, ImportError, KeyError):
return False
def is_scatter_available():
| 64 | 64 | 12 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_scatter_available | is_scatter_available | 376 | 377 | 376 | 376 | dee8744d96c715395c6dff844f3ed14bcc5b8ba8 | bigcode/the-stack | train |
92cd82a9a652a66fd38576fa | train | function | def filename_to_url(filename, cache_dir=None):
"""
Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or
its stored metadata do not exist.
"""
if cache_dir is None:
cache_dir = TRANSFORMERS_CACHE
if isinstance(cache_dir, Path):... | def filename_to_url(filename, cache_dir=None):
| """
Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or
its stored metadata do not exist.
"""
if cache_dir is None:
cache_dir = TRANSFORMERS_CACHE
if isinstance(cache_dir, Path):
cache_dir = str(cache_dir)
cache_... | hexdigest()
if etag:
etag_bytes = etag.encode("utf-8")
filename += "." + sha256(etag_bytes).hexdigest()
if url.endswith(".h5"):
filename += ".h5"
return filename
def filename_to_url(filename, cache_dir=None):
| 64 | 64 | 199 | 10 | 53 | MichalPitr/transformers | src/transformers/file_utils.py | Python | filename_to_url | filename_to_url | 1,222 | 1,245 | 1,222 | 1,222 | 91e7d810147dd1092460bcabb14e0564d36fc4a6 | bigcode/the-stack | train |
c6716c7b04d97436ae89b761 | train | function | def is_sagemaker_mp_enabled():
# Get the sagemaker specific mp parameters from smp_options variable.
smp_options = os.getenv("SM_HP_MP_PARAMETERS", "{}")
try:
# Parse it and check the field "partitions" is included, it is required for model parallel.
smp_options = json.loads(smp_options)
... | def is_sagemaker_mp_enabled():
# Get the sagemaker specific mp parameters from smp_options variable.
| smp_options = os.getenv("SM_HP_MP_PARAMETERS", "{}")
try:
# Parse it and check the field "partitions" is included, it is required for model parallel.
smp_options = json.loads(smp_options)
if "partitions" not in smp_options:
return False
except json.JSONDecodeError:
... | except json.JSONDecodeError:
return False
# Lastly, check if the `smdistributed` module is present.
return importlib.util.find_spec("smdistributed") is not None
def is_sagemaker_mp_enabled():
# Get the sagemaker specific mp parameters from smp_options variable.
| 68 | 68 | 228 | 24 | 43 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_sagemaker_mp_enabled | is_sagemaker_mp_enabled | 398 | 419 | 398 | 399 | 14ce3b66acfc9a1f8ef2c1765994fe19b61adf8d | bigcode/the-stack | train |
66a2017494d4ae00da5dea1e | train | function | def _is_tensorflow(x):
import tensorflow as tf
return isinstance(x, tf.Tensor)
| def _is_tensorflow(x):
| import tensorflow as tf
return isinstance(x, tf.Tensor)
| , np.ndarray)
def _is_numpy(x):
return isinstance(x, np.ndarray)
def _is_torch(x):
import torch
return isinstance(x, torch.Tensor)
def _is_torch_device(x):
import torch
return isinstance(x, torch.device)
def _is_tensorflow(x):
| 64 | 64 | 21 | 7 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | _is_tensorflow | _is_tensorflow | 1,710 | 1,713 | 1,710 | 1,710 | 5b8498fa90f672fc516c60b2f1010665d9f56006 | bigcode/the-stack | train |
f8dd7ac242235497c4a5ec71 | train | function | def _prepare_output_docstrings(output_type, config_class):
"""
Prepares the return part of the docstring using `output_type`.
"""
docstrings = output_type.__doc__
# Remove the head of the docstring to keep the list of args only
lines = docstrings.split("\n")
i = 0
while i < len(lines) a... | def _prepare_output_docstrings(output_type, config_class):
| """
Prepares the return part of the docstring using `output_type`.
"""
docstrings = output_type.__doc__
# Remove the head of the docstring to keep the list of args only
lines = docstrings.split("\n")
i = 0
while i < len(lines) and re.search(r"^\s*(Args|Parameters):\s*$", lines[i]) is No... | s+)", r"\1- **\2**\3", blocks[i])
blocks[i] = re.sub(r":\s*\n\s*(\S)", r" -- \1", blocks[i])
return "\n".join(blocks)
def _prepare_output_docstrings(output_type, config_class):
| 65 | 65 | 219 | 12 | 53 | MichalPitr/transformers | src/transformers/file_utils.py | Python | _prepare_output_docstrings | _prepare_output_docstrings | 698 | 717 | 698 | 698 | ae4f97d6b5f9f65317ff58fe28b23edb8753db67 | bigcode/the-stack | train |
0f64868cef5dccfe7a7d8845 | train | function | def _convert_output_args_doc(output_args_doc):
"""Convert output_args_doc to display properly."""
# Split output_arg_doc in blocks argument/description
indent = _get_indent(output_args_doc)
blocks = []
current_block = ""
for line in output_args_doc.split("\n"):
# If the indent is the sam... | def _convert_output_args_doc(output_args_doc):
| """Convert output_args_doc to display properly."""
# Split output_arg_doc in blocks argument/description
indent = _get_indent(output_args_doc)
blocks = []
current_block = ""
for line in output_args_doc.split("\n"):
# If the indent is the same as the beginning, the line is the name of new... | elements depending on the configuration (:class:`~transformers.{config_class}`) and inputs.
"""
def _get_indent(t):
"""Returns the indentation in the first line of t"""
search = re.search(r"^(\s*)\S", t)
return "" if search is None else search.groups()[0]
def _convert_output_args_doc(output_args_... | 78 | 78 | 261 | 10 | 68 | MichalPitr/transformers | src/transformers/file_utils.py | Python | _convert_output_args_doc | _convert_output_args_doc | 672 | 695 | 672 | 672 | 2b385806f2e30d4249dd7d40b7473a35e0ea6723 | bigcode/the-stack | train |
773525ddd921c7642d67b3fb | train | function | def add_start_docstrings(*docstr):
def docstring_decorator(fn):
fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
return fn
return docstring_decorator
| def add_start_docstrings(*docstr):
| def docstring_decorator(fn):
fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
return fn
return docstring_decorator
| name__") else obj.__class__.__name__
if not all(BACKENDS_MAPPING[backend][0]() for backend in backends):
raise ImportError("".join([BACKENDS_MAPPING[backend][1].format(name) for backend in backends]))
def add_start_docstrings(*docstr):
| 63 | 64 | 55 | 9 | 54 | MichalPitr/transformers | src/transformers/file_utils.py | Python | add_start_docstrings | add_start_docstrings | 615 | 620 | 615 | 615 | 1ca77726606ffcec8b9ddbac293ee54c145c9401 | bigcode/the-stack | train |
bb1c9d8f98ab3776f47d80fa | train | function | def is_sklearn_available():
if importlib.util.find_spec("sklearn") is None:
return False
return is_scipy_available() and importlib.util.find_spec("sklearn.metrics")
| def is_sklearn_available():
| if importlib.util.find_spec("sklearn") is None:
return False
return is_scipy_available() and importlib.util.find_spec("sklearn.metrics")
| def is_apex_available():
return importlib.util.find_spec("apex") is not None
def is_faiss_available():
return _faiss_available
def is_scipy_available():
return importlib.util.find_spec("scipy") is not None
def is_sklearn_available():
| 64 | 64 | 44 | 7 | 56 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_sklearn_available | is_sklearn_available | 338 | 341 | 338 | 338 | 71da3e4733b16aa7e735934808a0bfa1c7f25953 | bigcode/the-stack | train |
68dab40336760d2fcebdc197 | train | function | def is_sagemaker_dp_enabled():
# Get the sagemaker specific env variable.
sagemaker_params = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
try:
# Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
sagemaker_params = json.loads(sagemaker_params)
if not sagemaker_param... | def is_sagemaker_dp_enabled():
# Get the sagemaker specific env variable.
| sagemaker_params = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
try:
# Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
sagemaker_params = json.loads(sagemaker_params)
if not sagemaker_params.get("sagemaker_distributed_dataparallel_enabled", False):
return... | Error, ImportError, KeyError):
return False
def is_scatter_available():
return _scatter_available
def is_pandas_available():
return importlib.util.find_spec("pandas") is not None
def is_sagemaker_dp_enabled():
# Get the sagemaker specific env variable.
| 64 | 64 | 140 | 19 | 44 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_sagemaker_dp_enabled | is_sagemaker_dp_enabled | 384 | 395 | 384 | 385 | 373d31106f3e2f7ca20e8c2b951a73e64efe0938 | bigcode/the-stack | train |
e866a74af3d8a6dce5a7964d | train | function | def _is_numpy(x):
return isinstance(x, np.ndarray)
| def _is_numpy(x):
| return isinstance(x, np.ndarray)
|
if is_flax_available():
import jaxlib.xla_extension as jax_xla
from jax.core import Tracer
if isinstance(x, (jax_xla.DeviceArray, Tracer)):
return True
return isinstance(x, np.ndarray)
def _is_numpy(x):
| 64 | 64 | 14 | 6 | 58 | MichalPitr/transformers | src/transformers/file_utils.py | Python | _is_numpy | _is_numpy | 1,694 | 1,695 | 1,694 | 1,694 | f2bd2a54d220ab239277cd70277f30d0d17c17f6 | bigcode/the-stack | train |
0aa78d49193abf4711a4eb0e | train | function | def is_datasets_available():
return _datasets_available
| def is_datasets_available():
| return _datasets_available
| if importlib.util.find_spec("torch_xla") is None:
return False
if importlib.util.find_spec("torch_xla.core") is None:
return False
return importlib.util.find_spec("torch_xla.core.xla_model") is not None
def is_datasets_available():
| 64 | 64 | 12 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_datasets_available | is_datasets_available | 314 | 315 | 314 | 314 | 8634cbff6934260affa7c900ed19492fb76ea5d0 | bigcode/the-stack | train |
4fa1f9c19511061b730c3920 | train | function | def is_torchaudio_available():
return _torchaudio_available
| def is_torchaudio_available():
| return _torchaudio_available
| tributed") is not None
def is_training_run_on_sagemaker():
return "SAGEMAKER_JOB_NAME" in os.environ
def is_soundfile_availble():
return _soundfile_available
def is_timm_available():
return _timm_available
def is_torchaudio_available():
| 64 | 64 | 16 | 8 | 55 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_torchaudio_available | is_torchaudio_available | 434 | 435 | 434 | 434 | 1584491412a480662e48acd2315d4b4a48507110 | bigcode/the-stack | train |
23bbca0fed2001d27b487462 | train | function | def http_get(url: str, temp_file: BinaryIO, proxies=None, resume_size=0, headers: Optional[Dict[str, str]] = None):
"""
Download remote file. Do not gobble up errors.
"""
headers = copy.deepcopy(headers)
if resume_size > 0:
headers["Range"] = f"bytes={resume_size}-"
r = requests.get(url,... | def http_get(url: str, temp_file: BinaryIO, proxies=None, resume_size=0, headers: Optional[Dict[str, str]] = None):
| """
Download remote file. Do not gobble up errors.
"""
headers = copy.deepcopy(headers)
if resume_size > 0:
headers["Range"] = f"bytes={resume_size}-"
r = requests.get(url, stream=True, proxies=proxies, headers=headers)
r.raise_for_status()
content_length = r.headers.get("Content... | }/{v}" for k, v in user_agent.items())
elif isinstance(user_agent, str):
ua += "; " + user_agent
return ua
def http_get(url: str, temp_file: BinaryIO, proxies=None, resume_size=0, headers: Optional[Dict[str, str]] = None):
| 66 | 66 | 221 | 33 | 32 | MichalPitr/transformers | src/transformers/file_utils.py | Python | http_get | http_get | 1,432 | 1,455 | 1,432 | 1,432 | 4bc71f569647fca00ca3cd048ab6889eeb182137 | bigcode/the-stack | train |
b494cfd4c7e4f7a4d98b6628 | train | function | def is_speech_available():
# For now this depends on torchaudio but the exact dependency might evolve in the future.
return _torchaudio_available
| def is_speech_available():
# For now this depends on torchaudio but the exact dependency might evolve in the future.
| return _torchaudio_available
| ble():
return _soundfile_available
def is_timm_available():
return _timm_available
def is_torchaudio_available():
return _torchaudio_available
def is_speech_available():
# For now this depends on torchaudio but the exact dependency might evolve in the future.
| 64 | 64 | 34 | 26 | 37 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_speech_available | is_speech_available | 438 | 440 | 438 | 439 | bb0ee2a355dd9bc85561b6dd14968b2ee3fd53b9 | bigcode/the-stack | train |
ef132535ae41522c9277f16d | train | function | def is_torch_fx_proxy(x):
if is_torch_fx_available():
import torch.fx
return isinstance(x, torch.fx.Proxy)
return False
| def is_torch_fx_proxy(x):
| if is_torch_fx_available():
import torch.fx
return isinstance(x, torch.fx.Proxy)
return False
| the same.
@wraps(func)
def wrapper(*args, **kwargs):
if is_tf_available():
return func(*args, **kwargs)
else:
raise ImportError(f"Method `{func.__name__}` requires TF.")
return wrapper
def is_torch_fx_proxy(x):
| 64 | 64 | 34 | 8 | 55 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_torch_fx_proxy | is_torch_fx_proxy | 1,658 | 1,663 | 1,658 | 1,658 | 1c44402d4f72abd39df0e815c3b42ef417843b93 | bigcode/the-stack | train |
724e0a27ffab39463d8616f9 | train | class | class _BaseLazyModule(ModuleType):
"""
Module class that surfaces all objects but only performs associated imports when the objects are requested.
"""
# Very heavily inspired by optuna.integration._IntegrationModule
# https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
d... | class _BaseLazyModule(ModuleType):
| """
Module class that surfaces all objects but only performs associated imports when the objects are requested.
"""
# Very heavily inspired by optuna.integration._IntegrationModule
# https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
def __init__(self, name, import_stru... | DO_NOT_PAD = "do_not_pad"
class TensorType(ExplicitEnum):
"""
Possible values for the ``return_tensors`` argument in :meth:`PreTrainedTokenizerBase.__call__`. Useful for
tab-completion in an IDE.
"""
PYTORCH = "pt"
TENSORFLOW = "tf"
NUMPY = "np"
JAX = "jax"
class _BaseLazyModule(Modu... | 93 | 93 | 311 | 8 | 85 | MichalPitr/transformers | src/transformers/file_utils.py | Python | _BaseLazyModule | _BaseLazyModule | 1,864 | 1,898 | 1,864 | 1,864 | 03a1acffd015b6485fc012a28cbb51d3e058dbd4 | bigcode/the-stack | train |
108b8eebb2b983789ccd6eb9 | train | function | def _is_torch_device(x):
import torch
return isinstance(x, torch.device)
| def _is_torch_device(x):
| import torch
return isinstance(x, torch.device)
| , (jax_xla.DeviceArray, Tracer)):
return True
return isinstance(x, np.ndarray)
def _is_numpy(x):
return isinstance(x, np.ndarray)
def _is_torch(x):
import torch
return isinstance(x, torch.Tensor)
def _is_torch_device(x):
| 64 | 64 | 20 | 8 | 56 | MichalPitr/transformers | src/transformers/file_utils.py | Python | _is_torch_device | _is_torch_device | 1,704 | 1,707 | 1,704 | 1,704 | eca37fd2f419a05f70f6ab40e1af835af70dcd1f | bigcode/the-stack | train |
bc44bb5c8ad262741693fca6 | train | function | def tf_required(func):
# Chose a different decorator name than in tests so it's clear they are not the same.
@wraps(func)
def wrapper(*args, **kwargs):
if is_tf_available():
return func(*args, **kwargs)
else:
raise ImportError(f"Method `{func.__name__}` requires TF.")... | def tf_required(func):
# Chose a different decorator name than in tests so it's clear they are not the same.
@wraps(func)
| def wrapper(*args, **kwargs):
if is_tf_available():
return func(*args, **kwargs)
else:
raise ImportError(f"Method `{func.__name__}` requires TF.")
return wrapper
| return func(*args, **kwargs)
else:
raise ImportError(f"Method `{func.__name__}` requires PyTorch.")
return wrapper
def tf_required(func):
# Chose a different decorator name than in tests so it's clear they are not the same.
@wraps(func)
| 64 | 64 | 78 | 31 | 32 | MichalPitr/transformers | src/transformers/file_utils.py | Python | tf_required | tf_required | 1,646 | 1,655 | 1,646 | 1,648 | fbfe5d688a632d74432d368a4f06e47af18ce179 | bigcode/the-stack | train |
c429fc4b68bdd60e0feb6a8b | train | function | def torch_required(func):
# Chose a different decorator name than in tests so it's clear they are not the same.
@wraps(func)
def wrapper(*args, **kwargs):
if is_torch_available():
return func(*args, **kwargs)
else:
raise ImportError(f"Method `{func.__name__}` requires... | def torch_required(func):
# Chose a different decorator name than in tests so it's clear they are not the same.
@wraps(func)
| def wrapper(*args, **kwargs):
if is_torch_available():
return func(*args, **kwargs)
else:
raise ImportError(f"Method `{func.__name__}` requires PyTorch.")
return wrapper
| getattr(obj, attr, None)
if cached is None:
cached = self.fget(obj)
setattr(obj, attr, cached)
return cached
def torch_required(func):
# Chose a different decorator name than in tests so it's clear they are not the same.
@wraps(func)
| 64 | 64 | 80 | 31 | 32 | MichalPitr/transformers | src/transformers/file_utils.py | Python | torch_required | torch_required | 1,634 | 1,643 | 1,634 | 1,636 | 8684acc8ef2488b6ba9cd6325cf90fc5fefab191 | bigcode/the-stack | train |
10265e8c2c85f9ed39ce5085 | train | function | def copy_func(f):
"""Returns a copy of a function f."""
# Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwd... | def copy_func(f):
| """Returns a copy of a function f."""
# Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
retu... | , name)
else:
raise AttributeError(f"module {self.__name__} has no attribute {name}")
setattr(self, name, value)
return value
def _get_module(self, module_name: str) -> ModuleType:
raise NotImplementedError
def copy_func(f):
| 64 | 64 | 93 | 5 | 58 | MichalPitr/transformers | src/transformers/file_utils.py | Python | copy_func | copy_func | 1,901 | 1,907 | 1,901 | 1,901 | 8b92c8e8c763f2668cd86f141cd0fbc9b931a50c | bigcode/the-stack | train |
d49dfcb314d2352095e94c95 | train | function | def is_onnx_available():
return _onnx_available
| def is_onnx_available():
| return _onnx_available
| torch_version.major, torch_version.minor) == (
TORCH_FX_REQUIRED_VERSION.major,
TORCH_FX_REQUIRED_VERSION.minor,
)
def is_torch_fx_available():
return _torch_fx_available
def is_tf_available():
return _tf_available
def is_onnx_available():
| 64 | 64 | 14 | 7 | 56 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_onnx_available | is_onnx_available | 295 | 296 | 295 | 295 | 30256b8c7207e21d8692fa18855ea18e99dea7d8 | bigcode/the-stack | train |
08d97f0d07313c435ebe774e | train | function | def is_psutil_available():
return importlib.util.find_spec("psutil") is not None
| def is_psutil_available():
| return importlib.util.find_spec("psutil") is not None
| None:
return False
if importlib.util.find_spec("torch_xla.core") is None:
return False
return importlib.util.find_spec("torch_xla.core.xla_model") is not None
def is_datasets_available():
return _datasets_available
def is_psutil_available():
| 64 | 64 | 21 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_psutil_available | is_psutil_available | 318 | 319 | 318 | 318 | 2bae8410dcb427dfe1d69c9be3231888b9cd14ed | bigcode/the-stack | train |
caec0c86016916fdd7a37d8c | train | function | def is_tensor(x):
"""
Tests if ``x`` is a :obj:`torch.Tensor`, :obj:`tf.Tensor`, obj:`jaxlib.xla_extension.DeviceArray` or
:obj:`np.ndarray`.
"""
if is_torch_fx_proxy(x):
return True
if is_torch_available():
import torch
if isinstance(x, torch.Tensor):
return... | def is_tensor(x):
| """
Tests if ``x`` is a :obj:`torch.Tensor`, :obj:`tf.Tensor`, obj:`jaxlib.xla_extension.DeviceArray` or
:obj:`np.ndarray`.
"""
if is_torch_fx_proxy(x):
return True
if is_torch_available():
import torch
if isinstance(x, torch.Tensor):
return True
if is_tf... | kwargs)
else:
raise ImportError(f"Method `{func.__name__}` requires TF.")
return wrapper
def is_torch_fx_proxy(x):
if is_torch_fx_available():
import torch.fx
return isinstance(x, torch.fx.Proxy)
return False
def is_tensor(x):
| 64 | 64 | 165 | 5 | 58 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_tensor | is_tensor | 1,666 | 1,691 | 1,666 | 1,666 | 08b7ba9cc5f86002087cf2e70150e29ae5247a5c | bigcode/the-stack | train |
407c4cece1914959e7c0c9e9 | train | function | def is_tokenizers_available():
return importlib.util.find_spec("tokenizers") is not None
| def is_tokenizers_available():
| return importlib.util.find_spec("tokenizers") is not None
| is_sentencepiece_available():
return importlib.util.find_spec("sentencepiece") is not None
def is_protobuf_available():
if importlib.util.find_spec("google") is None:
return False
return importlib.util.find_spec("google.protobuf") is not None
def is_tokenizers_available():
| 64 | 64 | 21 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_tokenizers_available | is_tokenizers_available | 354 | 355 | 354 | 354 | 6fbf0982860471b011cd9998a36bbdd0b9eac789 | bigcode/the-stack | train |
a1a4edfac79cf2bc71ad9faf | train | function | def is_torch_available():
return _torch_available
| def is_torch_available():
| return _torch_available
| CH_FX_REQUIRED_VERSION = version.parse("1.8")
_is_offline_mode = True if os.environ.get("TRANSFORMERS_OFFLINE", "0").upper() in ENV_VARS_TRUE_VALUES else False
def is_offline_mode():
return _is_offline_mode
def is_torch_available():
| 64 | 64 | 12 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_torch_available | is_torch_available | 265 | 266 | 265 | 265 | 4f6cdaae7555bc24b8466869b62da1f946ad4d14 | bigcode/the-stack | train |
8ba436d72bc7289ad2f44d05 | train | function | def is_protobuf_available():
if importlib.util.find_spec("google") is None:
return False
return importlib.util.find_spec("google.protobuf") is not None
| def is_protobuf_available():
| if importlib.util.find_spec("google") is None:
return False
return importlib.util.find_spec("google.protobuf") is not None
| if importlib.util.find_spec("sklearn") is None:
return False
return is_scipy_available() and importlib.util.find_spec("sklearn.metrics")
def is_sentencepiece_available():
return importlib.util.find_spec("sentencepiece") is not None
def is_protobuf_available():
| 64 | 64 | 38 | 6 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_protobuf_available | is_protobuf_available | 348 | 351 | 348 | 348 | 81412f62f720814e1b27e743a54d27a831a3e8de | bigcode/the-stack | train |
1f78d776794ea5c1e1827252 | train | function | def _is_torch(x):
import torch
return isinstance(x, torch.Tensor)
| def _is_torch(x):
| import torch
return isinstance(x, torch.Tensor)
| _extension as jax_xla
from jax.core import Tracer
if isinstance(x, (jax_xla.DeviceArray, Tracer)):
return True
return isinstance(x, np.ndarray)
def _is_numpy(x):
return isinstance(x, np.ndarray)
def _is_torch(x):
| 64 | 64 | 19 | 7 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | _is_torch | _is_torch | 1,698 | 1,701 | 1,698 | 1,698 | 41f083da969f054e298313ca452760fa0ee5ffa7 | bigcode/the-stack | train |
ccdf14352fb7604d16910742 | train | function | def is_torch_fx_available():
return _torch_fx_available
| def is_torch_fx_available():
| return _torch_fx_available
| if _torch_available:
torch_version = version.parse(importlib_metadata.version("torch"))
_torch_fx_available = (torch_version.major, torch_version.minor) == (
TORCH_FX_REQUIRED_VERSION.major,
TORCH_FX_REQUIRED_VERSION.minor,
)
def is_torch_fx_available():
| 64 | 64 | 14 | 7 | 57 | MichalPitr/transformers | src/transformers/file_utils.py | Python | is_torch_fx_available | is_torch_fx_available | 287 | 288 | 287 | 287 | 03f488d20e76e64a937789b5db3196ba7b7b6b45 | bigcode/the-stack | train |
c7e7c60eeef815030b46088a | train | function | def add_code_sample_docstrings(
*docstr, tokenizer_class=None, checkpoint=None, output_type=None, config_class=None, mask=None, model_cls=None
):
def docstring_decorator(fn):
# model_class defaults to function's class if not specified otherwise
model_class = fn.__qualname__.split(".")[0] if mode... | def add_code_sample_docstrings(
*docstr, tokenizer_class=None, checkpoint=None, output_type=None, config_class=None, mask=None, model_cls=None
):
| def docstring_decorator(fn):
# model_class defaults to function's class if not specified otherwise
model_class = fn.__qualname__.split(".")[0] if model_cls is None else model_cls
if model_class[:2] == "TF":
sample_docstrings = TF_SAMPLE_DOCSTRINGS
elif model_class[:4] ==... | """
FLAX_SAMPLE_DOCSTRINGS = {
"SequenceClassification": FLAX_SEQUENCE_CLASSIFICATION_SAMPLE,
"QuestionAnswering": FLAX_QUESTION_ANSWERING_SAMPLE,
"TokenClassification": FLAX_TOKEN_CLASSIFICATION_SAMPLE,
"MultipleChoice": FLAX_MULTIPLE_CHOICE_SAMPLE,
"MaskedLM": FLAX_MASKED_LM_SAMPLE,
"BaseMode... | 135 | 135 | 453 | 35 | 100 | MichalPitr/transformers | src/transformers/file_utils.py | Python | add_code_sample_docstrings | add_code_sample_docstrings | 1,100 | 1,139 | 1,100 | 1,102 | 6fc61af66006fdc697d363af4394cea6488815a8 | bigcode/the-stack | train |
3c4031e0940b18b218e31250 | train | function | def test_find_complement():
s = module.Solution()
assert s.findComplement(5) == 2
assert s.findComplement(2) == 1
assert s.findComplement(1) == 0
assert s.findComplement(0) == 0
| def test_find_complement():
| s = module.Solution()
assert s.findComplement(5) == 2
assert s.findComplement(2) == 1
assert s.findComplement(1) == 0
assert s.findComplement(0) == 0
| import importlib
module = importlib.import_module("algorithms.0476_number_complement")
def test_find_complement():
| 26 | 64 | 61 | 6 | 20 | paulo-erichsen/leetcode | tests/0476_number_complement_test.py | Python | test_find_complement | test_find_complement | 6 | 11 | 6 | 6 | 2b5972edee2a58c7675ddabff1f57825a1a9098b | bigcode/the-stack | train |
36ba28d735b0d8b49f80b7dc | train | class | class LaserScan:
"""Class that contains LaserScan with x,y,z,r"""
EXTENSIONS_SCAN = [".bin"]
def __init__(
self,
project=False,
H=64,
W=1024,
fov_up=3.0,
fov_down=-
25.0):
self.project = project
self.proj_H... | class LaserScan:
| """Class that contains LaserScan with x,y,z,r"""
EXTENSIONS_SCAN = [".bin"]
def __init__(
self,
project=False,
H=64,
W=1024,
fov_up=3.0,
fov_down=-
25.0):
self.project = project
self.proj_H = H
self... | #!/usr/bin/env python3
# This file is covered by the LICENSE file in the root of this project.
import numpy as np
import time
class LaserScan:
| 35 | 256 | 1,683 | 4 | 30 | rayonnant14/PointCloudSegmentation | visualization/laserscan.py | Python | LaserScan | LaserScan | 7 | 180 | 7 | 7 | 25f16ba55acd8a96dbac597477ac753ed4bb6851 | bigcode/the-stack | train |
642c49d5f6e815efe7a27321 | train | class | class SemLaserScan(LaserScan):
"""Class that contains LaserScan with x,y,z,r,sem_label,sem_color_label,inst_label,inst_color_label"""
EXTENSIONS_LABEL = [".label"]
def __init__(
self,
sem_color_dict=None,
sem_labels_dict=None,
project=False,
H=64,
W=1024,
... | class SemLaserScan(LaserScan):
| """Class that contains LaserScan with x,y,z,r,sem_label,sem_color_label,inst_label,inst_color_label"""
EXTENSIONS_LABEL = [".label"]
def __init__(
self,
sem_color_dict=None,
sem_labels_dict=None,
project=False,
H=64,
W=1024,
fov_up=3.0,
fov_d... | proj_y = np.minimum(self.proj_H - 1, proj_y)
proj_y = np.maximum(0, proj_y).astype(np.int32) # in [0,H-1]
self.proj_y = np.copy(proj_y) # stope a copy in original order
# copy of depth in original order
self.unproj_range = np.copy(depth)
# order in decreasing depth
i... | 256 | 256 | 1,979 | 8 | 248 | rayonnant14/PointCloudSegmentation | visualization/laserscan.py | Python | SemLaserScan | SemLaserScan | 183 | 408 | 183 | 183 | eb9e8e70d9105c8aaa656582be35e76e0ff27c81 | bigcode/the-stack | train |
90b1d1948681256e4b2664a5 | train | class | class ArcFace(Layer):
def __init__(
self, n_classes=10, enhance=64.0, penalty=0.50, regularizer=None, **kwargs
):
super(ArcFace, self).__init__(**kwargs)
self.n_classes = n_classes
self.s = enhance
self.m = penalty
self.regularizer = get(regularizer)
def buil... | class ArcFace(Layer):
| def __init__(
self, n_classes=10, enhance=64.0, penalty=0.50, regularizer=None, **kwargs
):
super(ArcFace, self).__init__(**kwargs)
self.n_classes = n_classes
self.s = enhance
self.m = penalty
self.regularizer = get(regularizer)
def build(self, input_shape):
... | import tensorflow as tf
from tensorflow.keras.layers import BatchNormalization, Dropout, Flatten, Dense, Layer
from tensorflow.keras.backend import l2_normalize, clip, epsilon, softmax
from tensorflow.keras.regularizers import l2, get
from tensorflow.keras.applications import VGG16, ResNet50
import os
class ArcFace(Lay... | 74 | 87 | 290 | 6 | 67 | note-nota/ML_models | ArcFace/model/archs.py | Python | ArcFace | ArcFace | 9 | 43 | 9 | 9 | ab70962f76ea8af6ba43c09f72436f7cacb746c8 | bigcode/the-stack | train |
4b523c79b2a360171c4b9030 | train | function | def arcface_main(args):
n_classes = args.n_classes
penalty = args.penalty
enhance = args.enhance
dropout_rate = args.dropout
decay = args.decay
backbone = VGG16 if args.backbone == "VGG16" else ResNet50
backbone = backbone(include_top=False, input_shape=(100, 100, 3), classes=n_classes)
... | def arcface_main(args):
| n_classes = args.n_classes
penalty = args.penalty
enhance = args.enhance
dropout_rate = args.dropout
decay = args.decay
backbone = VGG16 if args.backbone == "VGG16" else ResNet50
backbone = backbone(include_top=False, input_shape=(100, 100, 3), classes=n_classes)
for layer in backbone.... | .0 + epsilon(), 1.0 - epsilon()))
target_logits = tf.math.cos(theta + self.m)
logits = logits * (1 - y) + target_logits * y
logits *= self.s
out = softmax(logits)
return out
def compute_output_shape(self, input_shape):
return (None, self.n_classes)
def arcface_main(... | 83 | 83 | 277 | 6 | 77 | note-nota/ML_models | ArcFace/model/archs.py | Python | arcface_main | arcface_main | 46 | 79 | 46 | 46 | 95ebd95a4b9bf91ffc0c6a5d20198cafa1526b2e | bigcode/the-stack | train |
00087f24b21f8d28f9261388 | train | function | def reset() -> None:
"""Resets all factories in this package."""
individual_factory.IndividualFactory.reset()
ctf.ClassTypeFactory.reset()
ltf.LiteralTypeFactory.reset()
rtf.RelationTypeFactory.reset()
| def reset() -> None:
| """Resets all factories in this package."""
individual_factory.IndividualFactory.reset()
ctf.ClassTypeFactory.reset()
ltf.LiteralTypeFactory.reset()
rtf.RelationTypeFactory.reset()
| BSD-2-Clause"
__version__ = "2017.1"
__date__ = "Nov 12, 2017"
__maintainer__ = "Patrick Hohenecker"
__email__ = "mail@paho.at"
__status__ = "Development"
def reset() -> None:
| 64 | 64 | 50 | 6 | 58 | phohenecker/rel-data | src/main/python/reldata/__init__.py | Python | reset | reset | 46 | 51 | 46 | 46 | 68c03612d022202898b89faf6a5fa32d2352753f | bigcode/the-stack | train |
013f8aa95b3179fae2c4d7e8 | train | function | def merge_emails(contact):
return "\n".join(filter(lambda x: x != "", filter(lambda x: x is not None,
[contact.email1, contact.email2, contact.email3])))
| def merge_emails(contact):
| return "\n".join(filter(lambda x: x != "", filter(lambda x: x is not None,
[contact.email1, contact.email2, contact.email3])))
| "", string)
def merge_phones(contact):
return "\n".join(filter(lambda x: x != "", map(lambda x: clear(x),
filter(lambda x: x is not None, [contact.homephone, contact.mobile,
contact.wo... | 64 | 64 | 42 | 6 | 58 | chameleoneyes/python_tr | Tests/test_compare_contact_views.py | Python | merge_emails | merge_emails | 25 | 27 | 25 | 25 | 5edbb47a7d295ba698eb58d5791a940c92947b3a | bigcode/the-stack | train |
418cb812a195757fcef6c738 | train | function | def clear(string):
return re.sub("[]() -]", "", string)
| def clear(string):
| return re.sub("[]() -]", "", string)
| _hp.lastname == contact_from_ep.lastname
assert contact_from_hp.addr == contact_from_ep.addr
assert contact_from_hp.all_phones == merge_phones(contact_from_ep)
assert contact_from_hp.all_emails == merge_emails(contact_from_ep)
# Clear special symbols from phone nums
def clear(string):
| 64 | 64 | 16 | 4 | 59 | chameleoneyes/python_tr | Tests/test_compare_contact_views.py | Python | clear | clear | 15 | 16 | 15 | 15 | ded580f7f4b4677c029bd9a6971e08cec62c62d1 | bigcode/the-stack | train |
286be08a46302ab318a83dff | train | function | def test_compare_contact_views(app, index=4):
contact_from_hp = app.contact.get_contact_list()[index]
contact_from_ep = app.contact.get_contact_from_edit_page(index)
assert contact_from_hp.firstname == contact_from_ep.firstname
assert contact_from_hp.lastname == contact_from_ep.lastname
assert conta... | def test_compare_contact_views(app, index=4):
| contact_from_hp = app.contact.get_contact_list()[index]
contact_from_ep = app.contact.get_contact_from_edit_page(index)
assert contact_from_hp.firstname == contact_from_ep.firstname
assert contact_from_hp.lastname == contact_from_ep.lastname
assert contact_from_hp.addr == contact_from_ep.addr
as... | import re
def test_compare_contact_views(app, index=4):
| 14 | 64 | 106 | 11 | 2 | chameleoneyes/python_tr | Tests/test_compare_contact_views.py | Python | test_compare_contact_views | test_compare_contact_views | 4 | 11 | 4 | 4 | 4f01b8a12fdb64771c4556e763e318a6540ac8a8 | bigcode/the-stack | train |
5fef0e05a37962856e2338f8 | train | function | def merge_phones(contact):
return "\n".join(filter(lambda x: x != "", map(lambda x: clear(x),
filter(lambda x: x is not None, [contact.homephone, contact.mobile,
contact.workphone, contac... | def merge_phones(contact):
| return "\n".join(filter(lambda x: x != "", map(lambda x: clear(x),
filter(lambda x: x is not None, [contact.homephone, contact.mobile,
contact.workphone, contact.phone2]))))
| .addr
assert contact_from_hp.all_phones == merge_phones(contact_from_ep)
assert contact_from_hp.all_emails == merge_emails(contact_from_ep)
# Clear special symbols from phone nums
def clear(string):
return re.sub("[]() -]", "", string)
def merge_phones(contact):
| 64 | 64 | 55 | 6 | 58 | chameleoneyes/python_tr | Tests/test_compare_contact_views.py | Python | merge_phones | merge_phones | 19 | 22 | 19 | 19 | e063f66e52869a19ae6e52f3e9b9206a127ef7af | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.