uid
stringlengths
24
24
category
stringclasses
2 values
granularity
stringclasses
3 values
prefix
stringlengths
189
2.17k
suffix
stringlengths
25
21.2k
content
stringlengths
48
21.3k
repo
stringlengths
9
41
path
stringlengths
8
82
c7183a932a431416aa5d0df6
class
simple
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
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 )
congnt95/neutron
neutron/tests/unit/services/logapi/common/test_sg_callback.py
0cc48661c407ab0595bbb6f3
class
simple
'], 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.Bas...
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...
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...
congnt95/neutron
neutron/tests/unit/services/logapi/common/test_sg_callback.py
d4f4b62d3518c1e2cffd46d8
function
simple
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 fa...
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)
congnt95/neutron
neutron/tests/unit/services/logapi/common/test_sg_callback.py
672a8b5362b9a1913107606c
class
simple
#!/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 KoubeiMar...
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...
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 ...
snowxmas/alipay-sdk-python-all
alipay/aop/api/request/KoubeiMarketingCampaignItemMerchantactivityModifyRequest.py
906ed902324ba134fcb362af
function
moderate
_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:...
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...
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_...
colinRawlings/osparc-simcore
services/director-v2/tests/unit/test_utils_registry.py
48b0359be12c2be18730f21e
function
simple
] for i in range(n_tmpfiles) ] ( tmpfile, tmpfileh, tmpfileh2, tmpfilec, tmpfilec2, tmpfile0, tmpfile1, tmpfile2, ) = tmpfiles 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
sadielbartholomew/cf-python
cf/test/test_read_write.py
88d5845dfe7641ca5c8c189d
class
simple
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...
SUPPORT_NCP = False TOPOLOGY = { COMMISSIONER: { 'name': 'COMMISSIONER', 'mode': 'rdn', 'allowlist': [LEADER] }, LEADER: { 'name': 'LEADER', 'mode': 'rdn', 'allowlist': [COMMISSIONER] }, } def test(...
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', ...
sarah-iot/openthread
tests/scripts/thread-cert/Cert_9_2_19_PendingDatasetGet.py
203cdfc09a85c2a956e5ec19
function
simple
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):
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
PranaliRPatil/Python_OOP_Basics
decorators_test.py
988999e8887e0129f9aeda8e
function
simple
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():
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..!!****")
PranaliRPatil/Python_OOP_Basics
decorators_test.py
92db5ecf77e50fd36452954c
class
simple
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):
"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...
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...
mbarga/commercetools-python-sdk
src/commercetools/types/_custom_object.py
38de8e39e987e4963b446536
class
simple
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 CustomObjectPagedQueryRespon...
"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....
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...
mbarga/commercetools-python-sdk
src/commercetools/types/_custom_object.py
2fd2bc707b5f305238274e8d
class
simple
# 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...
"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:...
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__( ...
mbarga/commercetools-python-sdk
src/commercetools/types/_custom_object.py
6237f3f1baa62866a70c392c
class
simple
_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, ) ) cla...
"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...
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...
mbarga/commercetools-python-sdk
src/commercetools/types/_custom_object.py
abcc56f695aa2c9784e172c4
function
simple
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):
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 ...
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...
MichalPitr/transformers
src/transformers/file_utils.py
c0dc29117101bd5011b8ce72
function
simple
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():
return importlib.util.find_spec("py3nvml") is not None
def is_py3nvml_available(): return importlib.util.find_spec("py3nvml") is not None
MichalPitr/transformers
src/transformers/file_utils.py
95553f892e5f558acb030445
function
simple
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():
return importlib.util.find_spec("PIL") is not None
def is_vision_available(): return importlib.util.find_spec("PIL") is not None
MichalPitr/transformers
src/transformers/file_utils.py
354221589fb308c21d68e553
function
simple
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():
return importlib.util.find_spec("pandas") is not None
def is_pandas_available(): return importlib.util.find_spec("pandas") is not None
MichalPitr/transformers
src/transformers/file_utils.py
7131ea6b7951f9c68abed206
function
simple
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):
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")
MichalPitr/transformers
src/transformers/file_utils.py
1909346ac296c20976e0627c
function
simple
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():
return _is_offline_mode
def is_offline_mode(): return _is_offline_mode
MichalPitr/transformers
src/transformers/file_utils.py
4a6cfa1e4d02cef39d51bc09
function
simple
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():
return importlib.util.find_spec("scipy") is not None
def is_scipy_available(): return importlib.util.find_spec("scipy") is not None
MichalPitr/transformers
src/transformers/file_utils.py
77fdd81937ee922d78bd1fe9
function
simple
(): 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):
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...
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: ...
MichalPitr/transformers
src/transformers/file_utils.py
ccebc3ba9765725823169245
function
simple
_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():
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
MichalPitr/transformers
src/transformers/file_utils.py
17b33f290e3402b90f4f8cc0
function
simple
_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):
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...
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...
MichalPitr/transformers
src/transformers/file_utils.py
130bf754440381a3e00a1778
function
simple
_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():
return "SAGEMAKER_JOB_NAME" in os.environ
def is_training_run_on_sagemaker(): return "SAGEMAKER_JOB_NAME" in os.environ
MichalPitr/transformers
src/transformers/file_utils.py
3d674ed696f538aece200322
function
simple
= 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):
""" 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 !...
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...
MichalPitr/transformers
src/transformers/file_utils.py
e169eaab5624d010e0b2f5f8
function
simple
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:
""" 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/...
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...
MichalPitr/transformers
src/transformers/file_utils.py
f53baf9aef8e89059fbb37cf
function
simple
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):
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...
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): ...
MichalPitr/transformers
src/transformers/file_utils.py
d85b2b0bde97505bfb67e440
function
simple
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():
return importlib.util.find_spec("sentencepiece") is not None
def is_sentencepiece_available(): return importlib.util.find_spec("sentencepiece") is not None
MichalPitr/transformers
src/transformers/file_utils.py
d9ad2c822d02b1309cf3ce3c
function
simple
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():
return _tf_available
def is_tf_available(): return _tf_available
MichalPitr/transformers
src/transformers/file_utils.py
2a1dcdae6c1462617be8d608
function
simple
.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():
return _faiss_available
def is_faiss_available(): return _faiss_available
MichalPitr/transformers
src/transformers/file_utils.py
875d025d95a9b13baeeb634d
class
simple
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 ...
""" 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...
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] =...
MichalPitr/transformers
src/transformers/file_utils.py
0e39dfd11810ab12692f1fac
function
simple
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():
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: ...
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...
MichalPitr/transformers
src/transformers/file_utils.py
5f58c1a6c56b5daf4fae0420
function
simple
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:
""" 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}" ...
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}" ...
MichalPitr/transformers
src/transformers/file_utils.py
eae3d4d3c5ff399270521e3c
function
simple
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():
return _timm_available
def is_timm_available(): return _timm_available
MichalPitr/transformers
src/transformers/file_utils.py
ce4d74c9b6bad4164ad19fc4
function
simple
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):
"""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]
MichalPitr/transformers
src/transformers/file_utils.py
4616a685f4604b33500ff5cd
function
simple
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...
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...
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 ...
MichalPitr/transformers
src/transformers/file_utils.py
02e98f9566049dd57213105d
function
simple
json" 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...
""" 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]...
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...
MichalPitr/transformers
src/transformers/file_utils.py
43cdae2150a3f1fa5e72b4c5
function
simple
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):
""" 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() ...
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...
MichalPitr/transformers
src/transformers/file_utils.py
b03996bb3a24187f2f03982e
function
simple
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():
return _flax_available
def is_flax_available(): return _flax_available
MichalPitr/transformers
src/transformers/file_utils.py
341b9e600c2ecc6c008f3816
class
simple
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) ...
""" 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:...
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:: ...
MichalPitr/transformers
src/transformers/file_utils.py
b6916b62102df3a459cf0916
function
simple
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():
return importlib.util.find_spec("apex") is not None
def is_apex_available(): return importlib.util.find_spec("apex") is not None
MichalPitr/transformers
src/transformers/file_utils.py
eace067f09cf2d5c0477c602
function
simple
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):
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
MichalPitr/transformers
src/transformers/file_utils.py
1fa060f9ce61513419e36ac9
function
moderate
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"...
""" 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...
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, ) -> ...
MichalPitr/transformers
src/transformers/file_utils.py
fd9bc5ca156139375d21fcca
class
simple
"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):
""" 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...
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...
MichalPitr/transformers
src/transformers/file_utils.py
55df9da53319cbd6180ce00b
class
simple
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):
""" 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())}" )
MichalPitr/transformers
src/transformers/file_utils.py
02c2ed2e32b25ec8c61037ef
function
complex
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...
""" 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...
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...
MichalPitr/transformers
src/transformers/file_utils.py
0d01c2f42aaee0b63eed8bb1
function
simple
_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):
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)
MichalPitr/transformers
src/transformers/file_utils.py
5d1b8a3849217bc6e8034ebd
function
simple
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():
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...
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...
MichalPitr/transformers
src/transformers/file_utils.py
92cd82a9a652a66fd38576fa
function
simple
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):
""" 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_...
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):...
MichalPitr/transformers
src/transformers/file_utils.py
724e0a27ffab39463d8616f9
class
simple
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(Mo...
""" 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...
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...
MichalPitr/transformers
src/transformers/file_utils.py
642c49d5f6e815efe7a27321
class
simple
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...
"""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...
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, ...
rayonnant14/PointCloudSegmentation
visualization/laserscan.py
90b1d1948681256e4b2664a5
class
simple
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(L...
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): ...
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...
note-nota/ML_models
ArcFace/model/archs.py
0706fa6e1b9921559a7ac3bf
class
simple
# coding: utf-8 """ ThingsBoard REST API ThingsBoard Professional Edition IoT platform REST API documentation. # noqa: E501 OpenAPI spec version: 3.3.3PAAS-RC1 Contact: info@thingsboard.io Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F40...
"""NOTE: This class is auto generated by the swagger code generator program. from tb_rest_client.api_client import ApiClient Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. at...
class AdminSettings(object): """NOTE: This class is auto generated by the swagger code generator program. from tb_rest_client.api_client import ApiClient Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the valu...
samson0v/python_tb_rest_client
tb_rest_client/models/models_pe/admin_settings.py
73a80134234f6c7c896d156c
class
simple
', on_delete=models.CASCADE) def __str__(self): return self.tweet.text class Comment(Tweet): parent = models.ForeignKey('Tweet', related_name='comments', on_delete=models.CASCADE) def __str__(s...
user = models.ForeignKey('auth.User', related_name='friends', on_delete=models.CASCADE) target = models.ForeignKey('auth.User', related_name='followers', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user)+"->"+str(self.t...
class Follow(models.Model): user = models.ForeignKey('auth.User', related_name='friends', on_delete=models.CASCADE) target = models.ForeignKey('auth.User', related_name='followers', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return s...
abhishekzgithub/tweet-django
tweetme/core/models.py
3085da516fceea8d7eec50a5
class
simple
.Model): tweet = models.ForeignKey('Tweet', related_name='like', on_delete=models.CASCADE) author = models.ForeignKey('auth.User', related_name='author', on_delete=models.CASCADE) ...
parent = models.ForeignKey('Tweet', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.text
class Comment(Tweet): parent = models.ForeignKey('Tweet', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.text
abhishekzgithub/tweet-django
tweetme/core/models.py
636676a7f74632b11893d152
class
simple
, blank=False, editable=False) likes_count = models.IntegerField(default=0, null=False, blank=False, editable=False) comments_count = models.IntegerField(default=0, null=False, blank=False, editable=False) def __str__(self): return self.text class Like(models.Model):
tweet = models.ForeignKey('Tweet', related_name='like', on_delete=models.CASCADE) author = models.ForeignKey('auth.User', related_name='author', on_delete=models.CASCADE) def __s...
class Like(models.Model): tweet = models.ForeignKey('Tweet', related_name='like', on_delete=models.CASCADE) author = models.ForeignKey('auth.User', related_name='author', on_delete=mod...
abhishekzgithub/tweet-django
tweetme/core/models.py
ae5426bd9e8fcbd37d11f2df
class
simple
# class PublicTimeLine(models.Model): # username=models.ForeignKey('auth.User',related_name='public_timeline',on_delete=models.CASCADE) # public_tweet = models.ForeignKey('Tweet', # related_name='public_tweet', # on_delete=models.CASCADE) class ...
username=models.ForeignKey('auth.User',related_name='user_follower',on_delete=models.CASCADE) followers = models.ManyToManyField('auth.User', related_name='followed_by') date=models.DateTimeField(auto_now_add=True) count=models.IntegerField(default=1) def __str__(self): return str(self....
class UserFollower(models.Model): username=models.ForeignKey('auth.User',related_name='user_follower',on_delete=models.CASCADE) followers = models.ManyToManyField('auth.User', related_name='followed_by') date=models.DateTimeField(auto_now_add=True) count=models.IntegerField(default=1) def __str...
abhishekzgithub/tweet-django
tweetme/core/models.py
b7cd9ea75bde465a7c4701f1
class
simple
='followed_by') date=models.DateTimeField(auto_now_add=True) count=models.IntegerField(default=1) def __str__(self): return str(self.username)+"->"+str(self.followers) class Meta: db_table='user_follower' class HashTag(Tweet):
name=models.CharField(max_length=10,unique=True) tweet=models.ManyToManyField(Tweet,related_name='hastag') def __str__(self): return self.name class Meta: db_table='hashtag'
class HashTag(Tweet): name=models.CharField(max_length=10,unique=True) tweet=models.ManyToManyField(Tweet,related_name='hastag') def __str__(self): return self.name class Meta: db_table='hashtag'
abhishekzgithub/tweet-django
tweetme/core/models.py
2001d5980fdaab195b1a65d7
class
simple
# coding: utf-8 """ Lightly API Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@lightly...
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = ap...
class SamplingsApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() ...
Tekrific/lightly
lightly/openapi_generated/swagger_client/api/samplings_api.py
f6757eda7b6c374d8ca1cf7b
class
simple
.exceptions.request_exception import RequestError from pyopenproject.api_connection.requests.get_request import GetRequest from pyopenproject.business.exception.business_error import BusinessError from pyopenproject.business.services.command.relation.relation_command import RelationCommand from pyopenproject.model impo...
def __init__(self, connection, relation): super().__init__(connection) self.relation = relation def execute(self): try: json_obj = GetRequest(self.connection, f"{self.CONTEXT}/{self.relation.id}").execute() return rel.Relation(json_obj) except RequestErro...
class Find(RelationCommand): def __init__(self, connection, relation): super().__init__(connection) self.relation = relation def execute(self): try: json_obj = GetRequest(self.connection, f"{self.CONTEXT}/{self.relation.id}").execute() return rel.Relation(json_o...
webu/pyopenproject
pyopenproject/business/services/command/relation/find.py
ecd2b4088f3c3489d120c29f
class
simple
from aiokafka.structs import TopicPartition from aiokafka.abc import ConsumerRebalanceListener # All test coroutines will be treated as marked. pytestmark = pytest.mark.asyncio @pytest.fixture async def subscription_state(): return SubscriptionState() class MockListener(ConsumerRebalanceListener):
def on_partitions_revoked(self, revoked): pass def on_partitions_assigned(self, assigned): pass
class MockListener(ConsumerRebalanceListener): def on_partitions_revoked(self, revoked): pass def on_partitions_assigned(self, assigned): pass
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
0559eb9e78cd12c8e069b0bf
function
moderate
_listener) assert subscription_state.subscription is None assert subscription_state.subscribed_pattern == pattern # After subscription to a pattern we can't change the subscription until # `unsubscribe` called with pytest.raises(IllegalStateError): subscription_state.subscribe( ...
topic_partitions = { TopicPartition("topic1", 0), TopicPartition("topic1", 1), TopicPartition("topic2", 0) } subscription_state.assign_from_user(topic_partitions) assert subscription_state.subscription is not None assert subscription_state.subscription.topics == {"topic1", "t...
async def test_user_assignment(subscription_state): topic_partitions = { TopicPartition("topic1", 0), TopicPartition("topic1", 1), TopicPartition("topic2", 0) } subscription_state.assign_from_user(topic_partitions) assert subscription_state.subscription is not None assert sub...
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
1099ca84a861c74cdd4a0f25
function
moderate
ConsumerRebalanceListener # All test coroutines will be treated as marked. pytestmark = pytest.mark.asyncio @pytest.fixture async def subscription_state(): return SubscriptionState() class MockListener(ConsumerRebalanceListener): def on_partitions_revoked(self, revoked): pass def on_partitio...
mock_listener = MockListener() subscription_state.subscribe({"tp1", "tp2"}, listener=mock_listener) assert subscription_state.subscription is not None assert subscription_state.subscription.topics == {"tp1", "tp2"} assert subscription_state.subscription.assignment is None assert subscription_sta...
async def test_subscribe_topic(subscription_state): mock_listener = MockListener() subscription_state.subscribe({"tp1", "tp2"}, listener=mock_listener) assert subscription_state.subscription is not None assert subscription_state.subscription.topics == {"tp1", "tp2"} assert subscription_state.subscri...
hirnimeshrampuresoftware/aiokafka
tests/test_subscription_state.py
d8bbec4304ce1c7bed94c311
class
simple
but print to stdout. """ printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length) printer.pretty(obj) printer.flush() sys.stdout.write(newline) sys.stdout.flush() class _PrettyPrinterBase(object): @contextlib.contextmanager
def indent(self, indent): """with statement support for indenting/dedenting.""" self.indentation += indent try: yield finally: self.indentation -= indent @contextlib.contextmanager def group(self, indent=0, open='', close=''): """like begin_gr...
class _PrettyPrinterBase(object): @contextlib.contextmanager def indent(self, indent): """with statement support for indenting/dedenting.""" self.indentation += indent try: yield finally: self.indentation -= indent @contextlib.contextmanager def ...
Granitosaurus/xonsh
xonsh/pretty.py
5b8192d702e9ed416719d796
class
simple
: # Move the printer over to the regular registry. printer = self.deferred_pprinters.pop(key) self.type_pprinters[cls] = printer return printer class Printable(object): def output(self, stream, output_width): return output_width class Text(Printable):
def __init__(self): self.objs = [] self.width = 0 def output(self, stream, output_width): for obj in self.objs: stream.write(obj) return output_width + self.width def add(self, obj, width): self.objs.append(obj) self.width += width
class Text(Printable): def __init__(self): self.objs = [] self.width = 0 def output(self, stream, output_width): for obj in self.objs: stream.write(obj) return output_width + self.width def add(self, obj, width): self.objs.append(obj) self.width...
Granitosaurus/xonsh
xonsh/pretty.py
7f4941c50530321ee6ac4fb4
class
simple
self.pretty.group_queue.remove(self.group) stream.write(self.obj) return output_width + self.width class Group(Printable): def __init__(self, depth): self.depth = depth self.breakables = collections.deque() self.want_break = False class GroupQueue(object):
def __init__(self, *groups): self.queue = [] for group in groups: self.enq(group) def enq(self, group): depth = group.depth while depth > len(self.queue) - 1: self.queue.append([]) self.queue[depth].append(group) def deq(self): for st...
class GroupQueue(object): def __init__(self, *groups): self.queue = [] for group in groups: self.enq(group) def enq(self, group): depth = group.depth while depth > len(self.queue) - 1: self.queue.append([]) self.queue[depth].append(group) de...
Granitosaurus/xonsh
xonsh/pretty.py
5246b868b3d53dab4c0c054d
class
simple
_stack.pop() if not group.breakables: self.group_queue.remove(group) if close: self.text(close) def flush(self): """Flush data that is left in the buffer.""" for data in self.buffer: self.output_width += data.output(self.output, self.output_width)...
""" Special pretty printer that has a `pretty` method that calls the pretty printer for a python object. This class stores processing data on `self` so you must *never* use this class in a threaded environment. Always lock it or reinstanciate it. Instances also have a verbose flag callbac...
class RepresentationPrinter(PrettyPrinter): """ Special pretty printer that has a `pretty` method that calls the pretty printer for a python object. This class stores processing data on `self` so you must *never* use this class in a threaded environment. Always lock it or reinstanciate it. ...
Granitosaurus/xonsh
xonsh/pretty.py
b1ab7c87ee98dafbb3e84c77
class
simple
.width = 0 def output(self, stream, output_width): for obj in self.objs: stream.write(obj) return output_width + self.width def add(self, obj, width): self.objs.append(obj) self.width += width class Breakable(Printable):
def __init__(self, seq, width, pretty): self.obj = seq self.width = width self.pretty = pretty self.indentation = pretty.indentation self.group = pretty.group_stack[-1] self.group.breakables.append(self) def output(self, stream, output_width): self.group....
class Breakable(Printable): def __init__(self, seq, width, pretty): self.obj = seq self.width = width self.pretty = pretty self.indentation = pretty.indentation self.group = pretty.group_stack[-1] self.group.breakables.append(self) def output(self, stream, outpu...
Granitosaurus/xonsh
xonsh/pretty.py
4865e470c67762e5a5deee19
class
simple
Pretty print the object's representation. """ stream = CUnicodeIO() printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length) printer.pretty(obj) printer.flush() return stream.getvalue() def pprint(obj, verbose=False, max_width=79, newline='\n', max_s...
""" Baseclass for the `RepresentationPrinter` prettyprinter that is used to generate pretty reprs of objects. Contrary to the `RepresentationPrinter` this printer knows nothing about the default pprinters or the `_repr_pretty_` callback method. """ def __init__(self, output, max_width=79, ...
class PrettyPrinter(_PrettyPrinterBase): """ Baseclass for the `RepresentationPrinter` prettyprinter that is used to generate pretty reprs of objects. Contrary to the `RepresentationPrinter` this printer knows nothing about the default pprinters or the `_repr_pretty_` callback method. """ ...
Granitosaurus/xonsh
xonsh/pretty.py
28857e35d41a6a9daa51d28b
class
simple
.group.want_break: stream.write(self.pretty.newline) stream.write(' ' * self.indentation) return self.indentation if not self.group.breakables: self.pretty.group_queue.remove(self.group) stream.write(self.obj) return output_width + self.width cla...
def __init__(self, depth): self.depth = depth self.breakables = collections.deque() self.want_break = False
class Group(Printable): def __init__(self, depth): self.depth = depth self.breakables = collections.deque() self.want_break = False
Granitosaurus/xonsh
xonsh/pretty.py
6915d3e40e203b92734cc0aa
class
moderate
# [X] Improve the search filter, we have to specify we don't want machine accounts in the answer # (play with userAccountControl) # from __future__ import division from __future__ import print_function import argparse import logging import os import sys from datetime import datetime from binascii import hexlify, ...
def printTable(items, header): colLen = [] for i, col in enumerate(header): rowMaxLen = max([len(row[i]) for row in items]) colLen.append(max(rowMaxLen, len(col))) outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width in enumerate(colLen)]) # Pr...
class GetUserSPNs: @staticmethod def printTable(items, header): colLen = [] for i, col in enumerate(header): rowMaxLen = max([len(row[i]) for row in items]) colLen.append(max(rowMaxLen, len(col))) outputFormat = ' '.join(['{%d:%ds} ' % (num, width) for num, width...
jsherwood0/impacket
examples/GetUserSPNs.py
49a53101917b961559977564
class
simple
.exists(upload_path): os.makedirs(upload_path, exist_ok=True) destination_file = os.path.join(upload_path, f.name) with open(destination_file, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) destination.close() class InformationPackageDetail(DetailView)...
""" Information Package Detail View """ model = InformationPackage context_object_name = 'ip' template_name = 'management/detail.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(InformationPackageDetail, self).dispatch(*args, **kwargs) ...
class InformationPackageDetail(DetailView): """ Information Package Detail View """ model = InformationPackage context_object_name = 'ip' template_name = 'management/detail.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(InformationPacka...
eark-project/access_dipcreator
management/views.py
37e192f77169bac16e602fcc
class
simple
= "%s: %s" % (err_msg, json_err["message"]) except JSONDecodeError: pass return render(request, 'earkweb/error.html', { 'header': 'Checkout error', 'message': err_msg }) resp_json = json.loads(response.text) context = { 'msg_checkout_confirm': resp_json['...
from django_tables2.utils import A area = "management" identifier = tables.LinkColumn('%s:storage_area' % area, kwargs={'section': area, 'identifier': A('identifier')}, verbose_name=_("Archived Information Package"), attrs={'a': {'data-t...
class InformationPackageTable(tables.Table): from django_tables2.utils import A area = "management" identifier = tables.LinkColumn('%s:storage_area' % area, kwargs={'section': area, 'identifier': A('identifier')}, verbose_name=_("Archived Information Package"), ...
eark-project/access_dipcreator
management/views.py
4cda72a7346386dee7e1d679
class
simple
on-salient, hard-salient and hard-non-salient) using the update function. The final LCA and HCA can be obtained at a single fold-level using the fold_lca() and fold_hca() functions. Average LCA and HCA across the folds can be obtained using the mean_lca() and mean_hca() functions. Example: -------- ``` tsq = Tes...
""" Weighted mean iou computation for the query complexity tier of TSS Attributes ----------- fold_mious : [ [float] ] mean intersection over union values for each fold, for each partition Methods ------- update( fold_number, part_type, mean_iou...
class TestSetQCS: """ Weighted mean iou computation for the query complexity tier of TSS Attributes ----------- fold_mious : [ [float] ] mean intersection over union values for each fold, for each partition Methods ------- update( fold_number, p...
fewshotseg/toss
src/filescores2ics.py
2dd5628faa17858be1d6fa56
function
moderate
((num_samples,)).numpy() assert np.isfinite(samples).all() emp_cdf, edges = empirical_cdf(samples) calc_cdf = distr.cdf(torch.Tensor(edges)).numpy() assert np.allclose(calc_cdf[1:, :], emp_cdf, atol=1e-2) @pytest.mark.parametrize( "batch_shape, num_pieces, num_samples", [((3, 4, 5), 10, 100),...
gamma = torch.ones(size=(*batch_shape,)) slopes = torch.ones(size=(*batch_shape, num_pieces)) # all positive knot_spacings = ( torch.ones(size=(*batch_shape, num_pieces)) / num_pieces ) # positive and sum to 1 target = torch.ones(size=batch_shape) # shape of gamma distr = PiecewiseLi...
@pytest.mark.parametrize( "batch_shape, num_pieces, num_samples", [((3, 4, 5), 10, 100), ((1,), 2, 1), ((10,), 10, 10), ((10, 5), 2, 1)], ) def test_shapes(batch_shape: Tuple, num_pieces: int, num_samples: int): gamma = torch.ones(size=(*batch_shape,)) slopes = torch.ones(size=(*batch_shape, num_pieces)...
nitinthedreamer/pytorch-ts
test/distributions/test_piecewise_linear.py
e457c115950a63ba68678853
class
moderate
check if # the parameter type name starts with the routine type name routine_type_name = '_'.join(self.name.split('_')[0:2]) # Object parameter is either first or last, it is last if this # is a Create or CreateStart routine, otherwise it is first if self.par...
"""Information on a subroutine parameter""" # Parameter types enum: (INTEGER, FLOAT, DOUBLE, CHARACTER, LOGICAL, CUSTOM_TYPE) = range(6) def __init__(self, name, routine, param_type, type_params, extra_stuff, array, comment): """Initialise a parameter A...
class Parameter(object): """Information on a subroutine parameter""" # Parameter types enum: (INTEGER, FLOAT, DOUBLE, CHARACTER, LOGICAL, CUSTOM_TYPE) = range(6) def __init__(self, name, routine, param_type, type_params, extra_stuff, array, comment): """Initiali...
tsalemink/opencmiss.utils
src/opencmiss/utils/iron/bindings/generate_bindings/parse.py
95ab1ca0431eb0ac650084dd
function
moderate
(",")] # Remove empty strings return list(filter(None, l)) def create_project_card(github_repo, project_name, project_column_name, pull_request): # Locate the project by name project = None for project_item in github_repo.get_projects("all"): if project_item.name == project_name: ...
commit_message = os.getenv( "COMMIT_MESSAGE", "Auto-committed changes by create-pull-request action" ) title = os.getenv( "PULL_REQUEST_TITLE", "Auto-generated by create-pull-request action" ) body = os.getenv( "PULL_REQUEST_BODY", "Auto-generated pull request by " ...
def process_event(github_token, github_repository, repo, branch, base): # Fetch optional environment variables with default values commit_message = os.getenv( "COMMIT_MESSAGE", "Auto-committed changes by create-pull-request action" ) title = os.getenv( "PULL_REQUEST_TITLE", "Auto-generat...
azarakovskiy/create-pull-request
dist/src/create-pull-request.py
7fd0781cec2dea78392cd6a0
function
complex
+ ' does not contains a control file!') @staticmethod def _xzcat_decompress(data): """Decompresses the xz-encrypted bytes in data by piping to xz.""" if subprocess.call('which xz', shell=True, stdout=subprocess.PIPE): raise RuntimeError('Cannot handle .xz compression: xz not found.') xz_proc = ...
default_mode = None if FLAGS.mode: # Convert from octal default_mode = int(FLAGS.mode, 8) mode_map = {} if FLAGS.modes: for filemode in FLAGS.modes: (f, mode) = filemode.split('=', 1) if f[0] == '/': f = f[1:] mode_map[f] = int(mode, 8) default_ownername = ('', '') if...
def main(unused_argv): # Parse modes arguments default_mode = None if FLAGS.mode: # Convert from octal default_mode = int(FLAGS.mode, 8) mode_map = {} if FLAGS.modes: for filemode in FLAGS.modes: (f, mode) = filemode.split('=', 1) if f[0] == '/': f = f[1:] mode_map[f] = ...
wix-playground/rules_docker
container/build_tar.py
5cca3eb366380228f46f5166
function
moderate
is None: raise FreezeError("cannot stat {}".format(path)) return default def get_timestamp_newest(path): ts_newest = 0 for dirpath, dirnames, filenames in os.walk(path, followlinks=True): for f in filenames: ts_newest = max(ts_newest, get_timestamp(os.path.join(dirpath...
path = convert_path(path) if not os.path.isdir(path): raise FreezeError("freeze path must be a directory") if script is None and kind == KIND_AS_STR: if any(f[0] == KIND_AS_STR for f in manifest_list): raise FreezeError("can only freeze one str directory") manifest_list.a...
def freeze_internal(kind, path, script, opt): path = convert_path(path) if not os.path.isdir(path): raise FreezeError("freeze path must be a directory") if script is None and kind == KIND_AS_STR: if any(f[0] == KIND_AS_STR for f in manifest_list): raise FreezeError("can only free...
ljk53/micropython
tools/makemanifest.py
f8c2d19c9c1c5c489faddb89
function
moderate
subdir = "" else: subdir = "/" + script for dirpath, dirnames, filenames in os.walk(path + subdir, followlinks=True): for f in filenames: freeze_internal(kind, path, (dirpath + "/" + f)[len(path) + 1 :], opt) elif not isinstance(script, str): # `scrip...
import argparse cmd_parser = argparse.ArgumentParser( description="A tool to generate frozen content in MicroPython firmware images." ) cmd_parser.add_argument("-o", "--output", help="output path") cmd_parser.add_argument("-b", "--build-dir", help="output path") cmd_parser.add_argument(...
def main(): # Parse arguments import argparse cmd_parser = argparse.ArgumentParser( description="A tool to generate frozen content in MicroPython firmware images." ) cmd_parser.add_argument("-o", "--output", help="output path") cmd_parser.add_argument("-b", "--build-dir", help="output p...
ljk53/micropython
tools/makemanifest.py
88b340fa155ce311bf04ea9c
function
moderate
return True def build_image(args): """Build docker image.""" if args.pull and args.no_pull: print('Incompatible arguments --pull and --no-pull.') return 1 if args.pull: pull = True elif args.no_pull: pull = False else: y_or_n = raw_input('Pull latest base images (compiler/runtime)? (y/...
"""Build fuzzers.""" if not build_image_impl(project_name, no_cache=no_cache): return 1 project_out_dir = _get_output_dir(project_name) project_work_dir = _get_work_dir(project_name) project_language = _get_project_language(project_name) if not project_language: print('WARNING: language not specifi...
def build_fuzzers_impl( # pylint: disable=too-many-arguments,too-many-locals,too-many-branches project_name, clean, engine, sanitizer, architecture, env_to_add, source_path, no_cache=False, mount_location=None): """Build fuzzers.""" if not build_image_impl(project_name, no_cache...
devtty1er/oss-fuzz
infra/helper.py
65daa41d51078937b85afc58
function
moderate
/oss-fuzz-base/base-clang', 'gcr.io/oss-fuzz-base/base-builder', 'gcr.io/oss-fuzz-base/base-runner', 'gcr.io/oss-fuzz-base/base-runner-debug', 'gcr.io/oss-fuzz-base/base-msan-builder', 'gcr.io/oss-fuzz-base/msan-builder', ] VALID_PROJECT_NAME_REGEX = re.compile(r'^[a-zA-Z0-9_-]+$') MAX_PROJECT_NAME...
"""Get subcommand from program arguments and do it.""" os.chdir(OSS_FUZZ_DIR) if not os.path.exists(BUILD_DIR): os.mkdir(BUILD_DIR) parser = argparse.ArgumentParser('helper.py', description='oss-fuzz helpers') subparsers = parser.add_subparsers(dest='command') generate_parser = subparsers.add_parser( ...
def main(): # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements """Get subcommand from program arguments and do it.""" os.chdir(OSS_FUZZ_DIR) if not os.path.exists(BUILD_DIR): os.mkdir(BUILD_DIR) parser = argparse.ArgumentParser('helper.py', description='oss-fuzz helpers') ...
devtty1er/oss-fuzz
infra/helper.py
43bc1d3f4fe4cfa4fe40dea0
function
moderate
_single_target(fuzz_target): try: _get_latest_corpus(args.project_name, fuzz_target, corpus_dir) return True except Exception as error: # pylint:disable=broad-except print('ERROR: corpus download for %s failed: %s' % (fuzz_target, str(error)), file=sys.stderr) re...
"""Generate code coverage using clang source based code coverage.""" if args.corpus_dir and not args.fuzz_target: print( 'ERROR: --corpus-dir requires specifying a particular fuzz target ' 'using --fuzz-target', file=sys.stderr) return 1 if not check_project_exists(args.project_na...
def coverage(args): """Generate code coverage using clang source based code coverage.""" if args.corpus_dir and not args.fuzz_target: print( 'ERROR: --corpus-dir requires specifying a particular fuzz target ' 'using --fuzz-target', file=sys.stderr) return 1 if not check_project_ex...
devtty1er/oss-fuzz
infra/helper.py
911749472a5ed68d70b2d143
function
moderate
, Michal Ernst' __copyright__ = 'Copyright (C) 2018-2019, Nokia' __email__ = 'michal.plichta@nokia.com, michal.ernst@nokia.com' cmd_dir_under_test = 'moler/cmd/' repo_path = abspath(join(dirname(__file__), '..')) # --------------- helper functions --------------- def _list_in_path(listing_type):
""" Quick and dirty function to return list of strings depends on parameter: - allfiles - list all file without path - fullpath - list only py files with path - only_py - list only py file without path :param listing_type: :return: list of files :rtype: list(str) """ abs_test_...
def _list_in_path(listing_type): """ Quick and dirty function to return list of strings depends on parameter: - allfiles - list all file without path - fullpath - list only py files with path - only_py - list only py file without path :param listing_type: :return: list of files :rtype...
carr-elagheb/moler
test/test_cmds_events_doc.py
bb9220cec62e916b195bfaa7
function
moderate
ftest') test_data = {'_ver_execute': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}} assert _validate_documentation_existence(fake_cmd, test_data, "COMMAND") == '' missing = _validate_docu...
from moler.util.cmds_events_doc import _validate_documentation_consistency fake_cmd = import_module('conftest') test_data = {'_ver_test1': {'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test2': {'COMMAND_OUTPUT': '', 'COMMAND_RESULT': {}}, '_ver_test3': {'COMMAND_OUTP...
def test_validate_documentation_consistency(): from moler.util.cmds_events_doc import _validate_documentation_consistency fake_cmd = import_module('conftest') test_data = {'_ver_test1': {'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test2': {'COMMAND_OUTPUT': '', 'COMMAND_RESULT': {}}...
carr-elagheb/moler
test/test_cmds_events_doc.py
a81979e06d5b427ae376ca49
function
moderate
")) global_min.append(float("inf")) return global_max,global_min def collect_stats(all_global_max,all_global_min,max_x, min_x): all_global_max.append(max_x) all_global_min.append(min_x) return all_global_max, all_global_min def get_final_max_and_min(all_global_max, all_global_m...
if method == 'absolute': global_max, global_min = [], [] d_max = np.array([float("-inf") for i in all_global_max[0]]) d_min = np.array([float("inf") for i in all_global_min[0]]) for j in range(len(all_global_max[0])): for i in range(len(all_global_max)): ...
def get_final_max_and_min(all_global_max, all_global_min, method= 'absolute'): if method == 'absolute': global_max, global_min = [], [] d_max = np.array([float("-inf") for i in all_global_max[0]]) d_min = np.array([float("inf") for i in all_global_min[0]]) for j in range(len(...
krishnateja95/Quantization-Test_bed
Vgg16.py
26b334e5c68b7ad3d47eba31
function
moderate
clock_edge_event = RisingEdge(self.clock) while True: await clock_edge_event # read handshake signals ready_sample = self.ready is None or self.ready.value valid_sample = self.valid is None or self.valid.value if ready_sample and valid_sampl...
all_signals = signals.copy() if optional_signals is None: optional_signals = [] else: all_signals += optional_signals if valid_signal is None: for s in all_signals: if s.lower().endswith('valid'): valid_signal = s if valid_signal not in all_signa...
def define_stream(name, signals, optional_signals=None, valid_signal=None, ready_signal=None, signal_widths=None): all_signals = signals.copy() if optional_signals is None: optional_signals = [] else: all_signals += optional_signals if valid_signal is None: for s in all_signals...
andreaskuster/cocotbext-axi
cocotbext/axi/stream.py
d798ac0cd4aac2e0e8e2ba30
function
moderate
: scale = ulimit / t elif t * scale < dlimit: scale = dlimit / t if aim: scale = aim / t for k, v in d.items(): d[k] = v * scale return d def _float(n):
try: n = n.replace(",", "") if n.endswith("K") or n.endswith("k"): n = float(n[:-1]) * 1000 elif n.endswith("M") or n.endswith("m"): n = float(n[:-1]) * 1000 * 1000 elif n.endswith("G") or n.endswith("g") or n.endswith("B") or n.endswith("b"): n = ...
def _float(n): try: n = n.replace(",", "") if n.endswith("K") or n.endswith("k"): n = float(n[:-1]) * 1000 elif n.endswith("M") or n.endswith("m"): n = float(n[:-1]) * 1000 * 1000 elif n.endswith("G") or n.endswith("g") or n.endswith("B") or n.endswith("b"): ...
Rico358097990/xalpha
xalpha/cons.py
43e66ccdf0fae12418cc660d
function
moderate
"2.0")) copy_tree(os.path.join(mono_etc_dir, "4.0"), os.path.join(target_mono_config_dir, "4.0")) copy_tree(os.path.join(mono_etc_dir, "4.5"), os.path.join(target_mono_config_dir, "4.5")) if os.path.isdir(os.path.join(mono_etc_dir, "mconfig")): copy_tree(os.path.join(mono_etc_dir, "mconfig"), os.pa...
from shutil import copy def copy_if_exists(src, dst): if os.path.isfile(src): copy(src, dst) platform = env["platform"] if platform == "windows": src_mono_bin_dir = os.path.join(mono_root, "bin") target_mono_bin_dir = os.path.join(target_mono_root_dir, "bin") ...
def copy_mono_shared_libs(env, mono_root, target_mono_root_dir): from shutil import copy def copy_if_exists(src, dst): if os.path.isfile(src): copy(src, dst) platform = env["platform"] if platform == "windows": src_mono_bin_dir = os.path.join(mono_root, "bin") targ...
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
5c9c2416240f6959df728a27
function
moderate
ono_framework_dir): os.makedirs(editor_mono_framework_dir) if not os.path.isdir(editor_mono_framework_facades_dir): os.makedirs(editor_mono_framework_facades_dir) for assembly in glob(os.path.join(mono_framework_dir, "*.dll")): copy(assembly, editor_mono_framework_dir) for assembly ...
from distutils.dir_util import copy_tree from glob import glob from shutil import copy if not os.path.isdir(target_mono_config_dir): os.makedirs(target_mono_config_dir) mono_etc_dir = os.path.join(mono_root, "etc", "mono") if not os.path.isdir(mono_etc_dir): mono_etc_dir = "" ...
def copy_mono_etc_dir(mono_root, target_mono_config_dir, platform): from distutils.dir_util import copy_tree from glob import glob from shutil import copy if not os.path.isdir(target_mono_config_dir): os.makedirs(target_mono_config_dir) mono_etc_dir = os.path.join(mono_root, "etc", "mono")...
LinuxUserGD/godot-opengl-4
modules/mono/build_scripts/mono_configure.py
c40187b8da9434bcbb8e391c
function
moderate
0), ("PARM_10", "ADJ_LANE_LEFT_2", 0), ] checks = [ ("CUR_LANE_LEFT_1", 15), ("CUR_LANE_LEFT_2", 15), ("CUR_LANE_RIGHT_1", 15), ("CUR_LANE_RIGHT_2", 15), ("CUR_LANE_LEFT_1", 15), ("CUR_LANE_LEFT_2", 15), ("CUR_LANE_RIGHT_1", 15), ("CUR_LANE_RIGHT_2", 15), ...
signals = [ ("XMISSION_SPEED", "ENGINE_DATA", 0), ("WHEEL_SPEED_FL", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_FR", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_RL", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_RR", "WHEEL_SPEEDS", 0), ("STEER_ANGLE", "STEERING_SENSORS", 0), ("STEER_ANGLE_RATE", "STEERING...
def get_can_signals(CP): # this function generates lists for signal, messages and initial values signals = [ ("XMISSION_SPEED", "ENGINE_DATA", 0), ("WHEEL_SPEED_FL", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_FR", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_RL", "WHEEL_SPEEDS", 0), ("WHEEL_SPEED_RR", "WHEE...
Shorrts/raspberry-pilot
selfdrive/car/honda/carstate.py
fc95b5f1873ef9a64c6a9ac3
function
moderate
import json import datetime import isodate import boto3 # Create clients sns = boto3.client('sns') dynamodb = boto3.resource('dynamodb', region_name='eu-west-1') roomTable = dynamodb.Table('myrecords') # Check if is there any booking fot that day def isTimeAvailable(_order):
bookingData = roomTable.scan()["Items"] _order["isAvailable"] = True _order["alternative"] = [] for _bookingData in bookingData: for _slot in _bookingData["slots"]: if _slot["date"] == _order["date"]: __stime = _stime = datetime.datetime.strptime( ...
def isTimeAvailable(_order): bookingData = roomTable.scan()["Items"] _order["isAvailable"] = True _order["alternative"] = [] for _bookingData in bookingData: for _slot in _bookingData["slots"]: if _slot["date"] == _order["date"]: __stime = _stime = datetime.datetime.s...
p-sk/AlexaMeetingRoomBooking
main-back.py
4c38efa9777795533b624637
function
moderate
if value is None or value == '': return None if isinstance(value, str) and value.upper() in FALSE_STRINGS: return False return bool(value) URL_QUERY_ARGUMENT_PARSERS = { 'db': int, 'socket_timeout': float, 'socket_connect_timeout': float, 'socket_keepalive': to_bool, 'r...
url = urlparse(url) kwargs = {} for name, value in parse_qs(url.query).items(): if value and len(value) > 0: value = unquote(value[0]) parser = URL_QUERY_ARGUMENT_PARSERS.get(name) if parser: try: kwargs[name] = parser(value) ...
def parse_url(url): url = urlparse(url) kwargs = {} for name, value in parse_qs(url.query).items(): if value and len(value) > 0: value = unquote(value[0]) parser = URL_QUERY_ARGUMENT_PARSERS.get(name) if parser: try: kwargs[nam...
Pigrenok/redis-py
redis/connection.py
92a5efcf482bd59cfaa5e0a3
function
moderate
data, perioddata=mawperioddata, pname="MAW-1", ) opth = "{}.maw.obs".format(gwfname) obsdata = { "{}.maw.obs.csv".format(gwfname): [ ("whead", "head", (0,)), ] } maw.obs.initialize( filename=opth, digits=20, print_input=True, continuous=obsdata ...
print("evaluating results...") # calculate volume of water and make sure it is conserved name = ex[sim.idxsim] gwfname = "gwf_" + name fname = gwfname + ".maw.bin" fname = os.path.join(sim.simpath, fname) assert os.path.isfile(fname) bobj = flopy.utils.HeadFile(fname, text="HEAD") s...
def eval_results(sim): print("evaluating results...") # calculate volume of water and make sure it is conserved name = ex[sim.idxsim] gwfname = "gwf_" + name fname = gwfname + ".maw.bin" fname = os.path.join(sim.simpath, fname) assert os.path.isfile(fname) bobj = flopy.utils.HeadFile(fn...
kzeiler/modflow6
autotest/test_gwf_maw06.py
8d0111d4ab70b555845eb7f4
function
moderate
(fmt%(d_min, cc), file = log) def assert_same_gridding(map_1, map_2, Sorry_message = "Maps have different gridding."): f1 = map_1.focus() == map_2.focus() f2 = map_1.origin() == map_2.origin() f3 = map_1.all() == map_2.all() if([f1, f2, f3].count(True)!= 3): raise Sorry(Sorry_messa...
if not map_data: assert origin_grid_units and n_xyz shift_needed = True else: # usual shift_needed = not \ (map_data.focus_size_1d() > 0 and map_data.nd() == 3 and map_data.is_0_based()) shift_frac = None shift_cart = None if(shift_needed): if map_data: N = map_data.all() ...
def shift_origin_if_needed(map_data = None, sites_cart = None, crystal_symmetry = None, ncs_object = None, origin_grid_units = None, n_xyz = None, ): if not map_data: assert origin_grid_units and n_xyz shift_needed = True else: # usual shift_needed = not \ (map_data.focus_s...
dperl-sol/cctbx_project
cctbx/maptbx/__init__.py
3582ba45504f2bc733c12b25
function
moderate
.1): ''' Determine if this map is bounded on all sides by values that are zero or a constant, within relative tolerance of relative_sd_tol to the SD of the map as a whole Returns True if map boundary values are nearly constant, and False if they vary Requires that map is at or...
''' Determine relative SD of values on edges to the map as a whole Requires that map is at origin (0,0,0) ''' assert tuple(map_data.origin()) == (0,0,0) sd_overall = map_data.as_1d().standard_deviation_of_the_sample() all = list(map_data.all()) boundary_data = flex.double() rel...
def relative_sd_on_edges(map_data, skip_if_greater_than = None, use_maximum = None): ''' Determine relative SD of values on edges to the map as a whole Requires that map is at origin (0,0,0) ''' assert tuple(map_data.origin()) == (0,0,0) sd_overall = map_data.as_1d().standard_devia...
dperl-sol/cctbx_project
cctbx/maptbx/__init__.py
d82b8965c4d045c359983cbd
function
moderate
# High-frequency filter at this resolution filtered_ma = ma.resolution_filter(d_min = d_min_value) filtered_map = map_coefficients_to_map( map_coeffs = filtered_ma, crystal_symmetry = cs, n_real = map_data.all()) # Make a difference map to look at only high_freq...
''' Measure of whether facing edges have correlated data with correlation similar to that found for adjacent planes and different than randomly chosen points If use_minimum is set, take minimum of values on all pairs of faces ''' all = list(map_data.all()) one_data = flex.double(...
def get_edge_score_towards_periodic(map_data, use_minimum = True): ''' Measure of whether facing edges have correlated data with correlation similar to that found for adjacent planes and different than randomly chosen points If use_minimum is set, take minimum of values on all pairs of faces...
dperl-sol/cctbx_project
cctbx/maptbx/__init__.py
516e58757fc0020a62a34edd
function
moderate
ray_structure = xray_structure, n_real = map_data.all(), rad_smooth = 2.0) map_data = map_data * mask_object.mask_smooth # from iotbx import mrcfile mrcfile.write_ccp4_map( file_name = "%s.ccp4"%file_name_prefix, unit_cell = cg.unit_cell(), space_group = cg.space_group(), #gr...
assert method in ["fsc", "rscc", "rscc_d_min_b"] from cctbx import maptbx from cctbx import miller import mmtbx.utils from iotbx.map_model_manager import map_model_manager mmm = map.as_1d().min_max_mean().as_tuple() map = map-mmm[2] map = map/map.sample_standard_deviation() cg = maptbx.crystal_gridd...
def loc_res(map, model, #pdb_hierarchy, crystal_symmetry, chunk_size = 10, soft_mask_radius = 3., method = "fsc", hard_d_min = 1.5, b_range_low = -200, b_range_high = 500, fsc_cutoff = 0.143, wrappin...
dperl-sol/cctbx_project
cctbx/maptbx/__init__.py
7f3b0f7760b304883a25e77f
function
moderate
# Copyright (c) 2017 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
rate_limiter = RateLimiter(2, 2) # stop time by overwriting timestamp() function to always return # the same time ts = time.time() rate_limiter.last_tick = ts with mock.patch('jaeger_client.rate_limiter.RateLimiter.timestamp') \ as mock_time: mock_time.side_effect = lambda: t...
def test_rate_limiting_sampler(): rate_limiter = RateLimiter(2, 2) # stop time by overwriting timestamp() function to always return # the same time ts = time.time() rate_limiter.last_tick = ts with mock.patch('jaeger_client.rate_limiter.RateLimiter.timestamp') \ as mock_time: ...
rbtcollins/jaeger-client-python
tests/test_rate_limiter.py
f4a97c7ae9137d23e2a8a6c7
function
moderate
associated to individual keys in S3, but # having it listed here should cause no problems because # GET bucket?storageClass is not part of the S3 API.) 'storageClass', # websiteConfig is a QSA for buckets in Google Cloud # S...
""" Generates the aws canonical string for the given parameters """ if not provider: provider = boto.provider.get_default() interesting_headers = {} for key in headers: lk = key.lower() if headers[key] is not None and \ (lk in ['content-md5', 'content-type...
def canonical_string(method, path, headers, expires=None, provider=None): """ Generates the aws canonical string for the given parameters """ if not provider: provider = boto.provider.get_default() interesting_headers = {} for key in headers: lk = key.lower()...
ContextLogic/boto
boto/provider_util.py