uid stringlengths 24 24 | category stringclasses 2
values | granularity stringclasses 1
value | prefix stringlengths 178 1.53k | suffix stringlengths 23 60.4k | content stringlengths 48 60.4k | repo stringlengths 10 54 | path stringlengths 8 67 |
|---|---|---|---|---|---|---|---|
23bbca0fed2001d27b487462 | function | simple | }/{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):
| """
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... | 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,... | MichalPitr/transformers | src/transformers/file_utils.py |
b494cfd4c7e4f7a4d98b6628 | function | simple | 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.
| 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
| MichalPitr/transformers | src/transformers/file_utils.py |
ef132535ae41522c9277f16d | function | simple | 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):
| 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
| MichalPitr/transformers | src/transformers/file_utils.py |
108b8eebb2b983789ccd6eb9 | function | simple | , (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):
| import torch
return isinstance(x, torch.device)
| def _is_torch_device(x):
import torch
return isinstance(x, torch.device)
| MichalPitr/transformers | src/transformers/file_utils.py |
bc44bb5c8ad262741693fca6 | function | simple | 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)
| def wrapper(*args, **kwargs):
if is_tf_available():
return func(*args, **kwargs)
else:
raise ImportError(f"Method `{func.__name__}` requires TF.")
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)
def wrapper(*args, **kwargs):
if is_tf_available():
return func(*args, **kwargs)
else:
raise ImportError(f"Method `{func.__name__}` requires TF.")... | MichalPitr/transformers | src/transformers/file_utils.py |
c429fc4b68bdd60e0feb6a8b | function | simple | 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)
| def wrapper(*args, **kwargs):
if is_torch_available():
return func(*args, **kwargs)
else:
raise ImportError(f"Method `{func.__name__}` requires PyTorch.")
return wrapper
| 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... | MichalPitr/transformers | src/transformers/file_utils.py |
10265e8c2c85f9ed39ce5085 | function | simple | , 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):
| """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... | 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... | MichalPitr/transformers | src/transformers/file_utils.py |
d49dfcb314d2352095e94c95 | function | simple | 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():
| return _onnx_available
| def is_onnx_available():
return _onnx_available
| MichalPitr/transformers | src/transformers/file_utils.py |
08d97f0d07313c435ebe774e | function | simple | 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():
| return importlib.util.find_spec("psutil") is not None
| def is_psutil_available():
return importlib.util.find_spec("psutil") is not None
| MichalPitr/transformers | src/transformers/file_utils.py |
caec0c86016916fdd7a37d8c | function | simple | 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):
| """
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... | 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... | MichalPitr/transformers | src/transformers/file_utils.py |
407c4cece1914959e7c0c9e9 | function | simple | 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():
| return importlib.util.find_spec("tokenizers") is not None
| def is_tokenizers_available():
return importlib.util.find_spec("tokenizers") is not None
| MichalPitr/transformers | src/transformers/file_utils.py |
a1a4edfac79cf2bc71ad9faf | function | simple | 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():
| return _torch_available
| def is_torch_available():
return _torch_available
| MichalPitr/transformers | src/transformers/file_utils.py |
8ba436d72bc7289ad2f44d05 | function | simple | 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():
| 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
| MichalPitr/transformers | src/transformers/file_utils.py |
1f78d776794ea5c1e1827252 | function | simple | _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):
| import torch
return isinstance(x, torch.Tensor)
| def _is_torch(x):
import torch
return isinstance(x, torch.Tensor)
| MichalPitr/transformers | src/transformers/file_utils.py |
ccdf14352fb7604d16910742 | function | simple | 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():
| return _torch_fx_available
| def is_torch_fx_available():
return _torch_fx_available
| MichalPitr/transformers | src/transformers/file_utils.py |
c7e7c60eeef815030b46088a | function | simple |
"""
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,
"BaseMod... | 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] ==... | 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... | MichalPitr/transformers | src/transformers/file_utils.py |
4b523c79b2a360171c4b9030 | function | simple | .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_mai... | 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.... | 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)
... | note-nota/ML_models | ArcFace/model/archs.py |
00087f24b21f8d28f9261388 | function | simple | BSD-2-Clause"
__version__ = "2017.1"
__date__ = "Nov 12, 2017"
__maintainer__ = "Patrick Hohenecker"
__email__ = "mail@paho.at"
__status__ = "Development"
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()
| phohenecker/rel-data | src/main/python/reldata/__init__.py |
013f8aa95b3179fae2c4d7e8 | function | simple | "", 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... | 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])))
| chameleoneyes/python_tr | Tests/test_compare_contact_views.py |
418cb812a195757fcef6c738 | function | simple | _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):
| return re.sub("[]() -]", "", string)
| def clear(string):
return re.sub("[]() -]", "", string)
| chameleoneyes/python_tr | Tests/test_compare_contact_views.py |
5fef0e05a37962856e2338f8 | function | simple | .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):
| 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]))))
| 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... | chameleoneyes/python_tr | Tests/test_compare_contact_views.py |
56989e12cef7a1edcabff513 | function | simple | names:
acc |= names
return acc
def names(category=None):
if not category:
category = default()
if category == ':all':
return list(all())
category = category.replace('/', ' ')
return list(data['names'][category])
def random(n=1, category=None):
| got = names(category)
if got:
shuffle(got)
if n == 1:
return choice(got)
return got[:n]
| def random(n=1, category=None):
got = names(category)
if got:
shuffle(got)
if n == 1:
return choice(got)
return got[:n]
| ask/metasyntactic | metasyntactic/themes/discworld.py |
20e863c92526819ebdd2d702 | function | simple | parse_data
from random import choice, shuffle
from six import iteritems
data = parse_data(DATA)
def default():
try:
if 'default' in data:
return data['default'][0]
except (KeyError, IndexError):
pass
return 'en'
def all():
| acc = set()
for category, names in iteritems(data['names']):
if names:
acc |= names
return acc
| def all():
acc = set()
for category, names in iteritems(data['names']):
if names:
acc |= names
return acc
| ask/metasyntactic | metasyntactic/themes/discworld.py |
0357ec6c5b76b22ecebfd916 | function | simple | sto_helit klatch quirm
ramtops uberwald djelibeybi ephebe genua llamedos agatean_empire xxxx\
'''
from metasyntactic.base import parse_data
from random import choice, shuffle
from six import iteritems
data = parse_data(DATA)
def default():
| try:
if 'default' in data:
return data['default'][0]
except (KeyError, IndexError):
pass
return 'en'
| def default():
try:
if 'default' in data:
return data['default'][0]
except (KeyError, IndexError):
pass
return 'en'
| ask/metasyntactic | metasyntactic/themes/discworld.py |
844b83d8aea3a5182e2ad549 | function | simple | ())
category = category.replace('/', ' ')
return list(data['names'][category])
def random(n=1, category=None):
got = names(category)
if got:
shuffle(got)
if n == 1:
return choice(got)
return got[:n]
def categories():
| return set(data['names'])
| def categories():
return set(data['names'])
| ask/metasyntactic | metasyntactic/themes/discworld.py |
6f82874cc6c5a13f63597253 | function | simple | :
return data['default'][0]
except (KeyError, IndexError):
pass
return 'en'
def all():
acc = set()
for category, names in iteritems(data['names']):
if names:
acc |= names
return acc
def names(category=None):
| if not category:
category = default()
if category == ':all':
return list(all())
category = category.replace('/', ' ')
return list(data['names'][category])
| def names(category=None):
if not category:
category = default()
if category == ':all':
return list(all())
category = category.replace('/', ' ')
return list(data['names'][category])
| ask/metasyntactic | metasyntactic/themes/discworld.py |
0d714000c3e36164b00b99f7 | function | simple | python_act('db_1', test_script_1, substitutions=substitutions_1)
expected_stdout_1 = """
2019-03-01 00:00:00
"""
@pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
| pytest.fail("Test not IMPLEMENTED")
| @pytest.mark.version('>=2.5')
@pytest.mark.xfail
def test_1(db_1):
pytest.fail("Test not IMPLEMENTED")
| reevespaul/firebird-qa | tests/bugs/core_6108_test.py |
acd73caa221bdd9fc22cc843 | function | simple | encrypt", help="Encodethe message")
enc.add_argument("--message", "-m", help="The Message")
# Decoding
dec = sp.add_parser("decrypt", help="Decode the message")
dec.add_argument("--message", "-m", help="The Message")
def load_cipher(parser):
| obj = b64(parser)
return obj
| def load_cipher(parser):
obj = b64(parser)
return obj
| fossbrandon/Crypto | crypto/ciphers/base64/__init__.py |
42523274ddb3f14edc043dd1 | function | simple | assigned_state(tp2)
tp_state = subscription_state._assigned_state(tp1)
assert tp_state is not None
assert repr(tp_state) == (
"TopicPartitionState<Status=PartitionStatus.AWAITING_RESET"
" position=None>"
)
async def test_begin_reassignment(subscription_state):
| subscription_state.subscribe({"tp1", "tp2"})
subscription_state.unsubscribe()
# After unsubscribe we should not fail begin_reassignment, just ignore it
subscription_state.begin_reassignment()
| async def test_begin_reassignment(subscription_state):
subscription_state.subscribe({"tp1", "tp2"})
subscription_state.unsubscribe()
# After unsubscribe we should not fail begin_reassignment, just ignore it
subscription_state.begin_reassignment()
| hirnimeshrampuresoftware/aiokafka | tests/test_subscription_state.py |
e8a505f200d2080d47041248 | function | simple | .state_value(tp) is not None
assert not assignment.state_value(tp).has_valid_position
assert assignment.state_value(tp)._position is None
subscription_state.seek(tp, 1000)
assert assignment.state_value(tp).position == 1000
async def test_assigned_partitions(subscription_state):
| assert subscription_state.assigned_partitions() == set()
subscription_state.subscribe(topics={"tp1"})
assert subscription_state.assigned_partitions() == set()
assignment = {TopicPartition("tp1", 0)}
subscription_state.assign_from_subscribed(assignment)
assert subscription_state.assigned_partitio... | async def test_assigned_partitions(subscription_state):
assert subscription_state.assigned_partitions() == set()
subscription_state.subscribe(topics={"tp1"})
assert subscription_state.assigned_partitions() == set()
assignment = {TopicPartition("tp1", 0)}
subscription_state.assign_from_subscribed(ass... | hirnimeshrampuresoftware/aiokafka | tests/test_subscription_state.py |
f3b8f674de0ce7a7344ba970 | function | simple |
subscription_state.unsubscribe()
assert subscription_state.subscription is None
# After unsubscribe you can change the type to say pattern.
subscription_state.subscribe_pattern(re.compile("pattern"))
subscription_state.subscribe_from_pattern({"tp33"})
assert subscription_state.subscription i... | tp = TopicPartition("topic1", 0)
tp2 = TopicPartition("topic2", 0)
subscription_state.assign_from_user({tp, tp2})
assignment = subscription_state.subscription.assignment
assert assignment.state_value(tp) is not None
assert not assignment.state_value(tp).has_valid_position
assert assignment.... | async def test_seek(subscription_state):
tp = TopicPartition("topic1", 0)
tp2 = TopicPartition("topic2", 0)
subscription_state.assign_from_user({tp, tp2})
assignment = subscription_state.subscription.assignment
assert assignment.state_value(tp) is not None
assert not assignment.state_value(tp).... | hirnimeshrampuresoftware/aiokafka | tests/test_subscription_state.py |
3f5163498764556207c2b015 | function | simple | ics == {"topic3", "topic4"}
new_assignment = subscription_state.subscription.assignment
assert new_assignment.tps == new_tps
assert assignment is not new_assignment
assert assignment.active is False
assert assignment.unassign_future.done() is True
async def test_unsubscribe(subscription_state):
| subscription_state.subscribe({"tp1", "tp2"})
assert subscription_state.subscription is not None
subscription_state.unsubscribe()
assert subscription_state.subscription is None
# After unsubscribe you can change the type to say pattern.
subscription_state.subscribe_pattern(re.compile("pattern")... | async def test_unsubscribe(subscription_state):
subscription_state.subscribe({"tp1", "tp2"})
assert subscription_state.subscription is not None
subscription_state.unsubscribe()
assert subscription_state.subscription is None
# After unsubscribe you can change the type to say pattern.
subscripti... | hirnimeshrampuresoftware/aiokafka | tests/test_subscription_state.py |
55731bdb519a45c820798deb | function | simple | _state.subscribe(topics={"tp1"})
assert subscription_state.assigned_partitions() == set()
assignment = {TopicPartition("tp1", 0)}
subscription_state.assign_from_subscribed(assignment)
assert subscription_state.assigned_partitions() == assignment
async def test_is_assigned(subscription_state):
| tp1 = TopicPartition("topic", 0)
tp2 = TopicPartition("topic", 1)
assert not subscription_state.is_assigned(tp1)
subscription_state.subscribe({"topic"})
assert not subscription_state.is_assigned(tp1)
subscription_state.assign_from_subscribed({tp1})
assert subscription_state.is_assigned(tp1)
... | async def test_is_assigned(subscription_state):
tp1 = TopicPartition("topic", 0)
tp2 = TopicPartition("topic", 1)
assert not subscription_state.is_assigned(tp1)
subscription_state.subscribe({"topic"})
assert not subscription_state.is_assigned(tp1)
subscription_state.assign_from_subscribed({tp1})... | hirnimeshrampuresoftware/aiokafka | tests/test_subscription_state.py |
8820704ac8eaca242416a270 | function | simple | _state import SubscriptionState
from aiokafka.errors import IllegalStateError
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()
| @pytest.fixture
async def subscription_state():
return SubscriptionState()
| hirnimeshrampuresoftware/aiokafka | tests/test_subscription_state.py |
88f56f3f9003319e1d5df2f6 | function | simple | _assigned(tp1)
subscription_state.subscribe({"topic"})
assert not subscription_state.is_assigned(tp1)
subscription_state.assign_from_subscribed({tp1})
assert subscription_state.is_assigned(tp1)
assert not subscription_state.is_assigned(tp2)
async def test_assigned_state(subscription_state):
| tp1 = TopicPartition("topic", 0)
tp2 = TopicPartition("topic", 1)
subscription_state.assign_from_user({tp1})
with pytest.raises(IllegalStateError):
subscription_state._assigned_state(tp2)
tp_state = subscription_state._assigned_state(tp1)
assert tp_state is not None
assert repr(tp... | async def test_assigned_state(subscription_state):
tp1 = TopicPartition("topic", 0)
tp2 = TopicPartition("topic", 1)
subscription_state.assign_from_user({tp1})
with pytest.raises(IllegalStateError):
subscription_state._assigned_state(tp2)
tp_state = subscription_state._assigned_state(tp1)
... | hirnimeshrampuresoftware/aiokafka | tests/test_subscription_state.py |
bf1253cc292b6b681d8d15ba | function | simple | _state.subscription.topics == {"tp1", "tp2", "tp3"}
assert old_subsciption is not subscription_state.subscription
assert old_subsciption.active is False
assert old_subsciption.unsubscribe_future.done() is True
async def test_subscribe_pattern(subscription_state):
| mock_listener = MockListener()
pattern = re.compile("^tests-.*$")
subscription_state.subscribe_pattern(
pattern=pattern, listener=mock_listener)
assert subscription_state.subscription is None
assert subscription_state.subscribed_pattern == pattern
# After subscription to a pattern we c... | async def test_subscribe_pattern(subscription_state):
mock_listener = MockListener()
pattern = re.compile("^tests-.*$")
subscription_state.subscribe_pattern(
pattern=pattern, listener=mock_listener)
assert subscription_state.subscription is None
assert subscription_state.subscribed_pattern ... | hirnimeshrampuresoftware/aiokafka | tests/test_subscription_state.py |
c1a2d25d5b25a1f7e5c5e52c | function | simple | REINFORCE
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
STATE_DIM = dialog_config.STATE_DIM
NUM_ACTIONS = dialog_config.SYS_ACTION_CARDINALITY
def load_policy_model(model_dir="model/test_nlg_no_warm_up_with_nlu.pkl"):
| model = torch.load(model_dir)
net = Net(state_dim=dialog_config.STATE_DIM, num_actions=dialog_config.SYS_ACTION_CARDINALITY).to(device)
net.load_state_dict(model)
net.eval()
return net
| def load_policy_model(model_dir="model/test_nlg_no_warm_up_with_nlu.pkl"):
model = torch.load(model_dir)
net = Net(state_dim=dialog_config.STATE_DIM, num_actions=dialog_config.SYS_ACTION_CARDINALITY).to(device)
net.load_state_dict(model)
net.eval()
return net
| qbetterk/user-simulator | simulator/policy/test_rule-base-simulator_RL_policy.py |
bd44754f8f40978650a28024 | function | simple | import aws_cdk as cdk
CDK_VERSION = 2
except ImportError:
pytestmark = pytest.mark.skip(
"aws_cdk package needed to run CDK tests.")
@pytest.fixture
def runner():
return CliRunner()
def verify_code_asset_exists_v1(uri_props):
| bucket_ref = uri_props['Bucket']['Ref']
assert bucket_ref.startswith('AssetParameters')
| def verify_code_asset_exists_v1(uri_props):
bucket_ref = uri_props['Bucket']['Ref']
assert bucket_ref.startswith('AssetParameters')
| hannes-ucsc/chalice | tests/functional/cdk/test_construct.py |
82e4b0bdc3e3c55fc8e4dfc9 | function | simple | 'testcdk')
api_handler = chalice_app.get_function('APIHandler')
assert api_handler == chalice_app.get_function('APIHandler')
role = chalice_app.get_role('DefaultRole')
assert hasattr(role, 'role_name')
def test_can_package_as_cdk_app(runner, verify_code_asset_exists):
# The CDK lo... | with runner.isolated_filesystem():
newproj.create_new_project_skeleton(
'testcdkpackage', project_type='cdk-ddb')
dirname = os.path.abspath(os.path.join('testcdkpackage',
'infrastructure'))
os.chdir(dirname)
cdk_app, chalice_... | def test_can_package_as_cdk_app(runner, verify_code_asset_exists):
# The CDK loading/synth can take a while so we're testing the
# various APIs out in one test to cut down on test time.
with runner.isolated_filesystem():
newproj.create_new_project_skeleton(
'testcdkpackage', project_type... | hannes-ucsc/chalice | tests/functional/cdk/test_construct.py |
fd525c04541bf2e038e1afb7 | function | simple | also need to verify that we've replaces the CodUri with the
# CDK specific assets.
functions = filter_resources(
cfn_template, 'AWS::Serverless::Function')[0]
verify_code_asset_exists(functions[1]['Properties']['CodeUri'])
def test_can_package_managed_layer(runner, verify_code_ass... | with runner.isolated_filesystem():
newproj.create_new_project_skeleton(
'testcdklayers', project_type='cdk-ddb')
project_dir = os.path.abspath('testcdklayers')
config_file = os.path.join(project_dir, 'runtime',
'.chalice', 'config.json')
... | def test_can_package_managed_layer(runner, verify_code_asset_exists):
with runner.isolated_filesystem():
newproj.create_new_project_skeleton(
'testcdklayers', project_type='cdk-ddb')
project_dir = os.path.abspath('testcdklayers')
config_file = os.path.join(project_dir, 'runtime',... | hannes-ucsc/chalice | tests/functional/cdk/test_construct.py |
d3e4cde4e1b9ffcdbf7ed376 | function | simple | CDK_VERSION = 1
except ImportError:
try:
import aws_cdk as cdk
CDK_VERSION = 2
except ImportError:
pytestmark = pytest.mark.skip(
"aws_cdk package needed to run CDK tests.")
@pytest.fixture
def runner():
| return CliRunner()
| @pytest.fixture
def runner():
return CliRunner()
| hannes-ucsc/chalice | tests/functional/cdk/test_construct.py |
4341942b6a880a05e643dbac | function | simple | ('cdk-')
@pytest.fixture
def verify_code_asset_exists():
if CDK_VERSION == 1:
return verify_code_asset_exists_v1
elif CDK_VERSION == 2:
return verify_code_asset_exists_v2
def load_chalice_construct(dirname, stack_name='testcdk'):
| try:
sys.path.append(dirname)
sys.modules.pop('stacks.chaliceapp', None)
sys.modules.pop('stacks', None)
import stacks.chaliceapp
app = cdk.App()
chalice_app = stacks.chaliceapp.ChaliceApp(app, stack_name)
return app, chalice_app.chalice
finally:
s... | def load_chalice_construct(dirname, stack_name='testcdk'):
try:
sys.path.append(dirname)
sys.modules.pop('stacks.chaliceapp', None)
sys.modules.pop('stacks', None)
import stacks.chaliceapp
app = cdk.App()
chalice_app = stacks.chaliceapp.ChaliceApp(app, stack_name)
... | hannes-ucsc/chalice | tests/functional/cdk/test_construct.py |
05aab2445d82ff1b292edbd9 | function | simple | .chaliceapp.ChaliceApp(app, stack_name)
return app, chalice_app.chalice
finally:
sys.modules.pop('app', None)
sys.modules.pop('stacks', None)
sys.path.pop()
sys.path_importer_cache.clear()
def filter_resources(template, resource_type):
| return [(name, props) for name, props in template['Resources'].items()
if props['Type'] == resource_type]
| def filter_resources(template, resource_type):
return [(name, props) for name, props in template['Resources'].items()
if props['Type'] == resource_type]
| hannes-ucsc/chalice | tests/functional/cdk/test_construct.py |
6374167c54d4fa431c5709d1 | function | simple | props) for name, props in template['Resources'].items()
if props['Type'] == resource_type]
def test_cdk_construct_api(runner):
# The CDK loading/synth can take a while so we're testing the
# various APIs out in one test to cut down on test time.
| with runner.isolated_filesystem():
newproj.create_new_project_skeleton(
'testcdk', project_type='cdk-ddb')
dirname = os.path.abspath(os.path.join('testcdk', 'infrastructure'))
os.chdir(dirname)
cdk_app, chalice_app = load_chalice_construct(dirname, 'testcdk')
api_... | def test_cdk_construct_api(runner):
# The CDK loading/synth can take a while so we're testing the
# various APIs out in one test to cut down on test time.
with runner.isolated_filesystem():
newproj.create_new_project_skeleton(
'testcdk', project_type='cdk-ddb')
dirname = os.path.... | hannes-ucsc/chalice | tests/functional/cdk/test_construct.py |
d89455ec5ea0855d68b56439 | function | simple | "aws_cdk package needed to run CDK tests.")
@pytest.fixture
def runner():
return CliRunner()
def verify_code_asset_exists_v1(uri_props):
bucket_ref = uri_props['Bucket']['Ref']
assert bucket_ref.startswith('AssetParameters')
def verify_code_asset_exists_v2(uri_props):
| bucket_ref = uri_props['Bucket']['Fn::Sub']
# Actual sub value will look something like this:
# 'cdk-abcdefghi-assets-${AWS::AccountId}-${AWS::Region}'},
assert bucket_ref.startswith('cdk-')
| def verify_code_asset_exists_v2(uri_props):
bucket_ref = uri_props['Bucket']['Fn::Sub']
# Actual sub value will look something like this:
# 'cdk-abcdefghi-assets-${AWS::AccountId}-${AWS::Region}'},
assert bucket_ref.startswith('cdk-')
| hannes-ucsc/chalice | tests/functional/cdk/test_construct.py |
0bf57fc30ebae70a54cfebe9 | function | simple | ):
bucket_ref = uri_props['Bucket']['Fn::Sub']
# Actual sub value will look something like this:
# 'cdk-abcdefghi-assets-${AWS::AccountId}-${AWS::Region}'},
assert bucket_ref.startswith('cdk-')
@pytest.fixture
def verify_code_asset_exists():
| if CDK_VERSION == 1:
return verify_code_asset_exists_v1
elif CDK_VERSION == 2:
return verify_code_asset_exists_v2
| @pytest.fixture
def verify_code_asset_exists():
if CDK_VERSION == 1:
return verify_code_asset_exists_v1
elif CDK_VERSION == 2:
return verify_code_asset_exists_v2
| hannes-ucsc/chalice | tests/functional/cdk/test_construct.py |
4f5e4fa1d7b0e7000b74f301 | function | simple | :
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)
self.buffer.clear()
self.buffer_width = 0
def _get_mro(obj_class):
| """ Get a reasonable method resolution order of a class and its superclasses
for both old-style and new-style classes.
"""
if not hasattr(obj_class, '__mro__'):
# Old-style class. Mix in object to make a fake new-style class.
try:
obj_class = type(obj_class.__name__, (obj_cla... | def _get_mro(obj_class):
""" Get a reasonable method resolution order of a class and its superclasses
for both old-style and new-style classes.
"""
if not hasattr(obj_class, '__mro__'):
# Old-style class. Mix in object to make a fake new-style class.
try:
obj_class = type(obj... | Granitosaurus/xonsh | xonsh/pretty.py |
6b19c7125c8b4adf2622e197 | function | simple | , p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
elif len(obj):
p.pretty(list(obj.items()))
def _deque_pprint(obj, p, cycle):
| name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
else:
p.pretty(list(obj))
| def _deque_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
else:
p.pretty(list(obj))
| Granitosaurus/xonsh | xonsh/pretty.py |
c21559505d2fe6882f54ed66 | function | simple |
tp[unicode] = _repr_pprint
except NameError:
tp[range] = _repr_pprint
tp[bytes] = _repr_pprint
return tp
#: printers for types specified by name
@lazyobject
def _deferred_type_pprinters():
| dtp = {}
for_type_by_name('collections', 'defaultdict', _defaultdict_pprint, dtp=dtp)
for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint, dtp=dtp)
for_type_by_name('collections', 'deque', _deque_pprint, dtp=dtp)
for_type_by_name('collections', 'Counter', _counter_pprint, dtp=dtp)
... | @lazyobject
def _deferred_type_pprinters():
dtp = {}
for_type_by_name('collections', 'defaultdict', _defaultdict_pprint, dtp=dtp)
for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint, dtp=dtp)
for_type_by_name('collections', 'deque', _deque_pprint, dtp=dtp)
for_type_by_name('collection... | Granitosaurus/xonsh | xonsh/pretty.py |
11938332aa68e7122a024d9f | function | simple | for the default singletons
_singleton_pprinters = LazyObject(lambda: dict.fromkeys(
map(id, [None, True, False, Ellipsis,
NotImplemented]), _repr_pprint),
globals(), '_singleton_pprinters')
def _default... | name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
else:
p.pretty(obj.default_factory)
p.text(',')
p.breakable()
p.pretty(dict(obj))
| def _defaultdict_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
else:
p.pretty(obj.default_factory)
p.text(',')
p.breakable()
p.pretty(dict(obj))
| Granitosaurus/xonsh | xonsh/pretty.py |
8cd2faa1a14ae6267b65dd54 | function | simple | redirects to the normal repr function."""
# Find newlines and replace them with p.break_()
output = repr(obj)
for idx,output_line in enumerate(output.splitlines()):
if idx:
p.break_()
p.text(output_line)
def _function_pprint(obj, p, cycle):
| """Base pprint for all functions and builtin functions."""
name = _safe_getattr(obj, '__qualname__', obj.__name__)
mod = obj.__module__
if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
name = mod + '.' + name
p.text('<function %s>' % name)
| def _function_pprint(obj, p, cycle):
"""Base pprint for all functions and builtin functions."""
name = _safe_getattr(obj, '__qualname__', obj.__name__)
mod = obj.__module__
if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
name = mod + '.' + name
p.text('<function %s>' % name)... | Granitosaurus/xonsh | xonsh/pretty.py |
dd2b1b6c6f971cf3f919c7d7 | function | simple | with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
else:
p.pretty(obj.default_factory)
p.text(',')
p.breakable()
p.pretty(dict(obj))
def _ordereddict_pprint(obj, p, cycle):
| name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
elif len(obj):
p.pretty(list(obj.items()))
| def _ordereddict_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
elif len(obj):
p.pretty(list(obj.items()))
| Granitosaurus/xonsh | xonsh/pretty.py |
d15d03ef26b9ef4ff0cda4b0 | function | simple | in p._enumerate(obj):
if idx:
p.text(',')
p.breakable()
p.pretty(x)
if len(obj) == 1 and type(obj) is tuple:
# Special case for 1-item tuples.
p.text(',')
p.end_group(step, end)
return inner
def _set_pprinter_factory(... | """
Factory that returns a pprint function useful for sets and frozensets.
"""
def inner(obj, p, cycle):
typ = type(obj)
if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
# If the subclass provides its own repr, use it instead.
... | def _set_pprinter_factory(start, end, basetype):
"""
Factory that returns a pprint function useful for sets and frozensets.
"""
def inner(obj, p, cycle):
typ = type(obj)
if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
# If the subclass p... | Granitosaurus/xonsh | xonsh/pretty.py |
b61fb693cca2d9a8634347f3 | function | simple | _break = True
return group
for group in stack:
group.want_break = True
del stack[:]
def remove(self, group):
try:
self.queue[group.depth].remove(group)
except ValueError:
pass
@lazyobject
def _baseclass_reprs():
| try:
br = (object.__repr__, types.InstanceType.__repr__)
except AttributeError: # Python 3
br = (object.__repr__,)
return br
| @lazyobject
def _baseclass_reprs():
try:
br = (object.__repr__, types.InstanceType.__repr__)
except AttributeError: # Python 3
br = (object.__repr__,)
return br
| Granitosaurus/xonsh | xonsh/pretty.py |
5ee265340efc76f8a16f4be5 | function | simple | The pprint for the super type."""
p.begin_group(8, '<super: ')
p.pretty(obj.__thisclass__)
p.text(',')
p.breakable()
p.pretty(obj.__self__)
p.end_group(8, '>')
def _re_pattern_pprint(obj, p, cycle):
| """The pprint function for regular expression patterns."""
p.text('re.compile(')
pattern = repr(obj.pattern)
if pattern[:1] in 'uU':
pattern = pattern[1:]
prefix = 'ur'
else:
prefix = 'r'
pattern = prefix + pattern.replace('\\\\', '\\')
p.text(pattern)
if obj.flag... | def _re_pattern_pprint(obj, p, cycle):
"""The pprint function for regular expression patterns."""
p.text('re.compile(')
pattern = repr(obj.pattern)
if pattern[:1] in 'uU':
pattern = pattern[1:]
prefix = 'ur'
else:
prefix = 'r'
pattern = prefix + pattern.replace('\\\\', '\... | Granitosaurus/xonsh | xonsh/pretty.py |
7adb12e967f4c612184e7199 | function | simple | .__class__.__name__)
if obj.__class__.__module__ not in ('exceptions', 'builtins'):
name = '%s.%s' % (obj.__class__.__module__, name)
step = len(name) + 1
p.begin_group(step, name + '(')
for idx, arg in enumerate(getattr(obj, 'args', ())):
if idx:
p.text(',')
p.br... | tp = {
int: _repr_pprint,
float: _repr_pprint,
str: _repr_pprint,
tuple: _seq_pprinter_factory('(', ')', tuple),
list: _seq_pprinter_factory('[', ']', list),
... | @lazyobject
def _type_pprinters():
#: printers for builtin types
tp = {
int: _repr_pprint,
float: _repr_pprint,
str: _repr_pprint,
tuple: _seq_pprinter_factory('(', ')', tuple),
list: ... | Granitosaurus/xonsh | xonsh/pretty.py |
70d43987040d71b6d3906dd3 | function | simple |
from xonsh.lazyasd import LazyObject, lazyobject
__all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
'for_type', 'for_type_by_name']
MAX_SEQ_LENGTH = 1000
def _safe_getattr(obj, attr, default=None):
| """Safe version of getattr.
Same as getattr, but will return ``default`` on any Exception,
rather than raising.
"""
try:
return getattr(obj, attr, default)
except Exception:
return default
| def _safe_getattr(obj, attr, default=None):
"""Safe version of getattr.
Same as getattr, but will return ``default`` on any Exception,
rather than raising.
"""
try:
return getattr(obj, attr, default)
except Exception:
return default
| Granitosaurus/xonsh | xonsh/pretty.py |
a3d5fd5d9029c93e99ae2207 | function | simple | (obj)
except Exception:
# Sometimes the items don't sort.
pass
for idx, x in p._enumerate(items):
if idx:
p.text(',')
p.breakable()
p.pretty(x)
p.end_group(step, end)
... | """
Factory that returns a pprint function used by the default pprint of
dicts and dict proxies.
"""
def inner(obj, p, cycle):
typ = type(obj)
if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
# If the subclass provides its own repr, u... | def _dict_pprinter_factory(start, end, basetype=None):
"""
Factory that returns a pprint function used by the default pprint of
dicts and dict proxies.
"""
def inner(obj, p, cycle):
typ = type(obj)
if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:... | Granitosaurus/xonsh | xonsh/pretty.py |
b7bafc252dddc818ba1c334c | function | simple | deque_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
else:
p.pretty(list(obj))
def _counter_pprint(obj, p, cycle):
| name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
elif len(obj):
p.pretty(dict(obj))
| def _counter_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
elif len(obj):
p.pretty(dict(obj))
| Granitosaurus/xonsh | xonsh/pretty.py |
b3fe8483e62e03dbfa75635c | function | simple | (key)
p.text('=')
step = len(key) + 1
p.indentation += step
p.pretty(value)
p.indentation -= step
first = False
p.end_group(1, '>')
def _seq_pprinter_factory(start, end, basetype):
| """
Factory that returns a pprint function useful for sequences. Used by
the default pprint for tuples, dicts, and lists.
"""
def inner(obj, p, cycle):
typ = type(obj)
if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
# If the subclas... | def _seq_pprinter_factory(start, end, basetype):
"""
Factory that returns a pprint function useful for sequences. Used by
the default pprint for tuples, dicts, and lists.
"""
def inner(obj, p, cycle):
typ = type(obj)
if basetype is not None and typ is not basetype and typ.__repr__ !... | Granitosaurus/xonsh | xonsh/pretty.py |
bcd722894a124f9b4564ec23 | function | simple | `` on any Exception,
rather than raising.
"""
try:
return getattr(obj, attr, default)
except Exception:
return default
CUnicodeIO = io.StringIO
def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
| """
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 pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
"""
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.f... | Granitosaurus/xonsh | xonsh/pretty.py |
b717ce601e419c573c1c191f | function | simple | name__', obj.__name__)
mod = obj.__module__
if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
name = mod + '.' + name
p.text('<function %s>' % name)
def _exception_pprint(obj, p, cycle):
| """Base pprint for all exceptions."""
name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
if obj.__class__.__module__ not in ('exceptions', 'builtins'):
name = '%s.%s' % (obj.__class__.__module__, name)
step = len(name) + 1
p.begin_group(step, name + '(')
for idx, arg i... | def _exception_pprint(obj, p, cycle):
"""Base pprint for all exceptions."""
name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
if obj.__class__.__module__ not in ('exceptions', 'builtins'):
name = '%s.%s' % (obj.__class__.__module__, name)
step = len(name) + 1
p.begin_grou... | Granitosaurus/xonsh | xonsh/pretty.py |
2dd72e82deefe97ebf5f3827 | function | simple | typ, None)
if func is not None:
# To support easy restoration of old pprinters, we need to ignore Nones.
_type_pprinters[typ] = func
return oldfunc
def for_type_by_name(type_module, type_name, func, dtp=None):
| """
Add a pretty printer for a type specified by the module and name of a type
rather than the type object itself.
"""
if dtp is None:
dtp = _deferred_type_pprinters
key = (type_module, type_name)
oldfunc = dtp.get(key, None)
if func is not None:
# To support easy restora... | def for_type_by_name(type_module, type_name, func, dtp=None):
"""
Add a pretty printer for a type specified by the module and name of a type
rather than the type object itself.
"""
if dtp is None:
dtp = _deferred_type_pprinters
key = (type_module, type_name)
oldfunc = dtp.get(key, No... | Granitosaurus/xonsh | xonsh/pretty.py |
81277114a92dd67f5abd218c | function | simple | , dtp=dtp)
for_type_by_name('collections', 'deque', _deque_pprint, dtp=dtp)
for_type_by_name('collections', 'Counter', _counter_pprint, dtp=dtp)
return dtp
def for_type(typ, func):
| """
Add a pretty printer for a given type.
"""
oldfunc = _type_pprinters.get(typ, None)
if func is not None:
# To support easy restoration of old pprinters, we need to ignore Nones.
_type_pprinters[typ] = func
return oldfunc
| def for_type(typ, func):
"""
Add a pretty printer for a given type.
"""
oldfunc = _type_pprinters.get(typ, None)
if func is not None:
# To support easy restoration of old pprinters, we need to ignore Nones.
_type_pprinters[typ] = func
return oldfunc
| Granitosaurus/xonsh | xonsh/pretty.py |
981b6aea86c5a49e21d82e82 | function | simple | for idx, key in p._enumerate(keys):
if idx:
p.text(',')
p.breakable()
p.pretty(key)
p.text(': ')
p.pretty(obj[key])
p.end_group(1, end)
return inner
def _super_pprint(obj, p, cycle):
| """The pprint for the super type."""
p.begin_group(8, '<super: ')
p.pretty(obj.__thisclass__)
p.text(',')
p.breakable()
p.pretty(obj.__self__)
p.end_group(8, '>')
| def _super_pprint(obj, p, cycle):
"""The pprint for the super type."""
p.begin_group(8, '<super: ')
p.pretty(obj.__thisclass__)
p.text(',')
p.breakable()
p.pretty(obj.__self__)
p.end_group(8, '>')
| Granitosaurus/xonsh | xonsh/pretty.py |
bf4662c68798f92a4cff4b50 | function | simple | ',
'UNICODE', 'VERBOSE', 'DEBUG'):
if obj.flags & getattr(re, flag):
if done_one:
p.text('|')
p.text('re.' + flag)
done_one = True
p.text(')')
def _type_pprint(obj, p, cycle):
| """The pprint for classes and types."""
# Heap allocated types might not have the module attribute,
# and others may set it to None.
# Checks for a __repr__ override in the metaclass
if type(obj).__repr__ is not type.__repr__:
_repr_pprint(obj, p, cycle)
return
mod = _safe_geta... | def _type_pprint(obj, p, cycle):
"""The pprint for classes and types."""
# Heap allocated types might not have the module attribute,
# and others may set it to None.
# Checks for a __repr__ override in the metaclass
if type(obj).__repr__ is not type.__repr__:
_repr_pprint(obj, p, cycle)
... | Granitosaurus/xonsh | xonsh/pretty.py |
9c4584567c4c92ff5cda2d7b | function | simple | name__
if not isinstance(name, str):
name = '<unknown type>'
if mod in (None, '__builtin__', 'builtins', 'exceptions'):
p.text(name)
else:
p.text(mod + '.' + name)
def _repr_pprint(obj, p, cycle):
| """A pprint that just redirects to the normal repr function."""
# Find newlines and replace them with p.break_()
output = repr(obj)
for idx,output_line in enumerate(output.splitlines()):
if idx:
p.break_()
p.text(output_line)
| def _repr_pprint(obj, p, cycle):
"""A pprint that just redirects to the normal repr function."""
# Find newlines and replace them with p.break_()
output = repr(obj)
for idx,output_line in enumerate(output.splitlines()):
if idx:
p.break_()
p.text(output_line)
| Granitosaurus/xonsh | xonsh/pretty.py |
43c252e1c80cc241d8391da6 | function | simple | try:
self.queue[group.depth].remove(group)
except ValueError:
pass
@lazyobject
def _baseclass_reprs():
try:
br = (object.__repr__, types.InstanceType.__repr__)
except AttributeError: # Python 3
br = (object.__repr__,)
return br
def _default_pprint... | """
The default print function. Used if an object does not provide one and
it's none of the builtin objects.
"""
klass = _safe_getattr(obj, '__class__', None) or type(obj)
if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
# A user-provided repr. Find newlines and replac... | def _default_pprint(obj, p, cycle):
"""
The default print function. Used if an object does not provide one and
it's none of the builtin objects.
"""
klass = _safe_getattr(obj, '__class__', None) or type(obj)
if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
# A user-pro... | Granitosaurus/xonsh | xonsh/pretty.py |
f7537024c61defc222d6d517 | function | simple | 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_seq_length=MAX_SEQ_LENGTH):
| """
Like `pretty` 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()
| def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
"""
Like `pretty` 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(n... | Granitosaurus/xonsh | xonsh/pretty.py |
6044ab827837adcb2a0ace9b | function | simple | _work
}
return render(request, 'management/iptable.html', context=context)
@login_required
def index(request):
template = loader.get_template('management/index.html')
context = {
}
return HttpResponse(template.render(context=context, request=request))
@login_required
def sip_detail(request,... | ip = InformationPackage.objects.get(pk=pk)
if not ip.uid:
context = {"ip": ip}
return render(request, 'management/checkout.html', context=context)
return upload_step1(request, pk)
| @login_required
def sip_detail(request, pk):
ip = InformationPackage.objects.get(pk=pk)
if not ip.uid:
context = {"ip": ip}
return render(request, 'management/checkout.html', context=context)
return upload_step1(request, pk)
| eark-project/access_dipcreator | management/views.py |
67c55ccf7551ff0677770580 | function | simple | , pk):
ip = InformationPackage.objects.get(pk=pk)
if not ip.uid:
context = {"ip": ip}
return render(request, 'management/checkout.html', context=context)
return upload_step1(request, pk)
def upload_aip(ip_work_dir, upload_path, f):
| print("Upload file '%s' to working directory: %s" % (f, upload_path))
if not os.path.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():
d... | def upload_aip(ip_work_dir, upload_path, f):
print("Upload file '%s' to working directory: %s" % (f, upload_path))
if not os.path.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:
... | eark-project/access_dipcreator | management/views.py |
4bd87b4f7f3e4bbae9bcdaa3 | function | simple | render
from django_tables2 import RequestConfig
from uuid import uuid4
import logging
from submission.views import upload_step1
from util.djangoutils import get_user_api_token
logger = logging.getLogger(__name__)
from django.utils.translation import ugettext_lazy as _
@login_required
def index(request):
| template = loader.get_template('management/index.html')
context = {
}
return HttpResponse(template.render(context=context, request=request))
| @login_required
def index(request):
template = loader.get_template('management/index.html')
context = {
}
return HttpResponse(template.render(context=context, request=request))
| eark-project/access_dipcreator | management/views.py |
e4a2b1fdf9d4f8a1c362bafc | function | simple | def delete(request, pk):
ip = InformationPackage.objects.get(pk=pk)
template = loader.get_template('management/deleted.html')
if ip.uid:
path = os.path.join(config_path_work, ip.uid)
if os.path.exists(path):
rmtree(path)
context = {
'uid': ip.uid,
}
ip.uid = "... | ip = InformationPackage.objects.get(identifier=identifier)
uid = None
if not ip.uid:
uid = str(uuid4())
ip.uid = uid
ip.work_dir = os.path.join(config_path_work, uid)
template = loader.get_template('management/checkout_confirm.html')
from config.configuration import django_ba... | @login_required
def checkout(request, identifier):
ip = InformationPackage.objects.get(identifier=identifier)
uid = None
if not ip.uid:
uid = str(uuid4())
ip.uid = uid
ip.work_dir = os.path.join(config_path_work, uid)
template = loader.get_template('management/checkout_confirm.ht... | eark-project/access_dipcreator | management/views.py |
bcef4bd4e3ec1a658237146f | function | simple | _file, upload_path,
os.path.join(ip_work_dir, 'metadata/sip_creation.log'))
print("Package extraction task '%s' to extract package '%s' to working directory: %s" % (
async_res.id, f.name, upload_path))
@login_required
def delete(request, pk):
| ip = InformationPackage.objects.get(pk=pk)
template = loader.get_template('management/deleted.html')
if ip.uid:
path = os.path.join(config_path_work, ip.uid)
if os.path.exists(path):
rmtree(path)
context = {
'uid': ip.uid,
}
ip.uid = ""
ip.work_dir = ""
... | @login_required
def delete(request, pk):
ip = InformationPackage.objects.get(pk=pk)
template = loader.get_template('management/deleted.html')
if ip.uid:
path = os.path.join(config_path_work, ip.uid)
if os.path.exists(path):
rmtree(path)
context = {
'uid': ip.uid,
... | eark-project/access_dipcreator | management/views.py |
9cd56c3d570a2314f605ca83 | function | simple | (__name__)
from django.utils.translation import ugettext_lazy as _
@login_required
def index(request):
template = loader.get_template('management/index.html')
context = {
}
return HttpResponse(template.render(context=context, request=request))
@login_required
@csrf_exempt
def ip_detail_table(reques... | logger.info("Updating ip table ...")
pkg_id = request.POST['pkg_id']
ip = InformationPackage.objects.get(pk=pkg_id)
logger.info("- version: %s" % ip.version)
context = {
"ip": ip,
"config_path_work": config_path_work
}
return render(request, 'management/iptable.html', context... | @login_required
@csrf_exempt
def ip_detail_table(request):
logger.info("Updating ip table ...")
pkg_id = request.POST['pkg_id']
ip = InformationPackage.objects.get(pk=pkg_id)
logger.info("- version: %s" % ip.version)
context = {
"ip": ip,
"config_path_work": config_path_work
}
... | eark-project/access_dipcreator | management/views.py |
ec433a04575dbb92279ea03d | function | simple | render(request, '%s/overview.html' % area, {'informationpackage': table})
@login_required
def render_network(request):
template = loader.get_template('management/render_network.html')
context = {
}
return HttpResponse(template.render(context=context, request=request))
def upload_file(upload_path, ... | print("Upload file '%s' to working directory: %s" % (f.name, upload_path))
if not os.path.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():
... | def upload_file(upload_path, f):
print("Upload file '%s' to working directory: %s" % (f.name, upload_path))
if not os.path.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:
... | eark-project/access_dipcreator | management/views.py |
1a53904d855eff798c5fed84 | function | simple | 'informationpackage': table,
}
if request.method == "POST":
return render(request, 'earkweb/ipstable.html', context=context)
else:
return render(request, '%s/overview.html' % area, {'informationpackage': table})
@login_required
def render_network(request):
| template = loader.get_template('management/render_network.html')
context = {
}
return HttpResponse(template.render(context=context, request=request))
| @login_required
def render_network(request):
template = loader.get_template('management/render_network.html')
context = {
}
return HttpResponse(template.render(context=context, request=request))
| eark-project/access_dipcreator | management/views.py |
6f1e45c8967d1482a627c3cd | function | simple | glyphicon glyphicon-ok-sign" aria-hidden="true" style="color:green"/>'
)
elif value == "Error":
return mark_safe(
'Error <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true" style="color:#91170A"/>'
)
elif value == "Warning":
... | area = "management"
areacode = "2"
filterword = request.POST['filterword'] if 'filterword' in request.POST.keys() else ""
sql_query = """
select ip.id as id, ip.work_dir as path, ip.uid as uid, ip.package_name as package_name,
CONCAT('<a href="/earkweb/management/modify/',ip.id,'/" data-toggle="... | @login_required
@csrf_exempt
def informationpackages_overview(request):
area = "management"
areacode = "2"
filterword = request.POST['filterword'] if 'filterword' in request.POST.keys() else ""
sql_query = """
select ip.id as id, ip.work_dir as path, ip.uid as uid, ip.package_name as package_name,
... | eark-project/access_dipcreator | management/views.py |
98237e74609e00ef4efe2607 | function | simple | Package.objects.get(pk=pkg_id)
logger.info("- version: %s" % ip.version)
context = {
"ip": ip,
"config_path_work": config_path_work
}
return render(request, 'management/iptable.html', context=context)
@login_required
def index(request):
| template = loader.get_template('management/index.html')
context = {
}
return HttpResponse(template.render(context=context, request=request))
| @login_required
def index(request):
template = loader.get_template('management/index.html')
context = {
}
return HttpResponse(template.render(context=context, request=request))
| eark-project/access_dipcreator | management/views.py |
6f65b3fb8e204fa0d7997c09 | function | simple | import numpy as np
import os
import matplotlib.pyplot as plt
# ==============================================================================
# POINT_CLOUD_2_BIRDSEYE
# ==============================================================================
def point_clo... | """ Creates an birds eye view representation of the point cloud data for MV3D.
Args:
points: (numpy array)
N rows of points data
Each point should be specified by at least 3 elements x,y,z
res: (float)
Desired resolution in ... | def point_cloud_2_top(points,
res=0.1,
zres=0.3,
side_range=(-10., 10.), # left-most to right-most
fwd_range=(-10., 10.), # back-most to forward-most
height_range=(-2., 2.), # bottom-most to upper-most
... | klockeph/MV3D_TF | tools/read_lidar.py |
7bf7279cc00ec1765613b26b | function | simple | =validation_errors, invalid=True)
return execute(self.schema, ast)
@classmethod
def format_error(cls, error: Exception) -> dict:
if isinstance(error, GraphQLSyntaxError):
return format_error(error)
return {'message': str(error)}
def get_ast(query: str):
| return parse(Source(query))
| def get_ast(query: str):
return parse(Source(query))
| karol-gruszczyk/sloth-gql | slothql/query.py |
d85fa77db75d811af092e001 | function | simple | _error(cls, error: Exception) -> dict:
if isinstance(error, GraphQLSyntaxError):
return format_error(error)
return {'message': str(error)}
def get_ast(query: str):
return parse(Source(query))
def gql(schema: slothql.Schema, query: str) -> dict:
| return QueryExecutor(schema).query(query)
| def gql(schema: slothql.Schema, query: str) -> dict:
return QueryExecutor(schema).query(query)
| karol-gruszczyk/sloth-gql | slothql/query.py |
23c77945ccc7713f15fc7ab6 | function | simple | )
@app.route("/api/cache/update")
def force_update():
val = requests.get(api_address + "/e/diseases").json()
update_cache(val)
print(Cache.storage)
return "Success"
@app.route("/api/cache")
def get_cache():
return jsonify(Cache.storage)
def update_cache(val):
| Cache.storage.clear()
Cache.storage = val
regenerate_file()
| def update_cache(val):
Cache.storage.clear()
Cache.storage = val
regenerate_file()
| TriedAngle/diseaster | services/matcher.py |
02443943322693e10da80966 | function | simple | _name + " first"
}
return jsonify(response)
@app.route("/api/cache/update")
def force_update():
val = requests.get(api_address + "/e/diseases").json()
update_cache(val)
print(Cache.storage)
return "Success"
@app.route("/api/cache")
def get_cache():
| return jsonify(Cache.storage)
| @app.route("/api/cache")
def get_cache():
return jsonify(Cache.storage)
| TriedAngle/diseaster | services/matcher.py |
5e849c8e73fa134253e0b259 | function | simple | "/e/diseases").json()
update_cache(val)
print(Cache.storage)
return "Success"
@app.route("/api/cache")
def get_cache():
return jsonify(Cache.storage)
def update_cache(val):
Cache.storage.clear()
Cache.storage = val
regenerate_file()
def extract(text) -> List[str]:
| response = openai.Completion.create(
engine="davinci",
prompt="Read this patient phone call:\n\"\"\"\n {} \n\"\"\"\nAnswer the following questions:\n\n1. What is the patients name?\n2. What symptoms is he mentioning?\n3. Return the symptoms as a Python list object\n4. What disease could he have?\n5.... | def extract(text) -> List[str]:
response = openai.Completion.create(
engine="davinci",
prompt="Read this patient phone call:\n\"\"\"\n {} \n\"\"\"\nAnswer the following questions:\n\n1. What is the patients name?\n2. What symptoms is he mentioning?\n3. Return the symptoms as a Python list object\n4.... | TriedAngle/diseaster | services/matcher.py |
5fd97b0a6ef504971fdf0d80 | function | simple | load_dotenv()
key = os.environ.get("OPENAI_KEY")
address = os.environ.get("MATCH_SERVICE_ADDRESS")
api_address = os.environ.get("BACKEND_REACH_ADDRESS")
openai.api_key = key
app = Flask(__name__)
class Cache:
storage = {}
@app.route("/")
def index():
| return "hello world!"
| @app.route("/")
def index():
return "hello world!"
| TriedAngle/diseaster | services/matcher.py |
49c2704e676f3fb47675ec86 | function | simple | dep['name']
print(dep_name)
response = {
"text": "you are likely to have: " + max_val + "\nwe recommend going to the Department of " + dep_name + " first"
}
return jsonify(response)
@app.route("/api/cache/update")
def force_update():
| val = requests.get(api_address + "/e/diseases").json()
update_cache(val)
print(Cache.storage)
return "Success"
| @app.route("/api/cache/update")
def force_update():
val = requests.get(api_address + "/e/diseases").json()
update_cache(val)
print(Cache.storage)
return "Success"
| TriedAngle/diseaster | services/matcher.py |
efecdeebb3cd6e30e5a8428c | function | simple | =0,
stop=["7."]
)
text_output = response["choices"][0]["text"]
b = "234567."
for char in b:
text_output = text_output.replace(char, "")
result = text_output.splitlines()
return result[2]
def regenerate_file():
| temp = []
for val in Cache.storage:
symptoms = ""
metadata = val["name"]
for symptom in val["symptoms"]:
symptoms += symptom["name"] + ", "
size = len(symptoms)
mod_string = symptoms[:size - 2]
symptoms = mod_string
temp.append({'text': symp... | def regenerate_file():
temp = []
for val in Cache.storage:
symptoms = ""
metadata = val["name"]
for symptom in val["symptoms"]:
symptoms += symptom["name"] + ", "
size = len(symptoms)
mod_string = symptoms[:size - 2]
symptoms = mod_string
te... | TriedAngle/diseaster | services/matcher.py |
05ad05bef5e0e7af6f92a509 | function | simple | jsonlines
load_dotenv()
key = os.environ.get("OPENAI_KEY")
address = os.environ.get("MATCH_SERVICE_ADDRESS")
api_address = os.environ.get("BACKEND_REACH_ADDRESS")
openai.api_key = key
app = Flask(__name__)
class Cache:
storage = {}
@app.route("/")
def index():
return "hello world!"
@app.route("/api/matc... | content = request.form
text = content['text']
print(text)
query_as_list = extract(text)
query = str(query_as_list).replace("[", "").replace("]", "").replace("'", "")
result = openai.Engine("davinci").search(
file="file-cEbtzr5OPbMfgHXroCUm5hT4",
query=query,
return_meta... | @app.route("/api/matcher", methods=['GET', 'POST'])
def get_matching():
content = request.form
text = content['text']
print(text)
query_as_list = extract(text)
query = str(query_as_list).replace("[", "").replace("]", "").replace("'", "")
result = openai.Engine("davinci").search(
file="... | TriedAngle/diseaster | services/matcher.py |
faea31882b37ca2aef00d50c | function | simple | list(shape)
assert shape.count(-1) <= 1
if -1 in shape:
shape[shape.index(-1)] = int(x.size(-1) / -np.prod(shape))
return x.view(*x.size()[:-1], *shape)
def merge_last(x, n_dims):
| """
merge the last n_dims to a dimension
"""
s = x.size()
assert n_dims > 1 and n_dims < len(s)
return x.view(*s[:-n_dims], -1)
| def merge_last(x, n_dims):
"""
merge the last n_dims to a dimension
"""
s = x.size()
assert n_dims > 1 and n_dims < len(s)
return x.view(*s[:-n_dims], -1)
| riteshkumarumassedu/BERT-with-SOP | utils.py |
4cfbe26cddc572f10ac5257c | function | simple | break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def get_random_word(vocab_words):
i = random.randint(0, len(vocab_words)-1)
return vocab_words[i]
def tensorboard_logger(name, log_path):
| """
logger for tensorboard
"""
logger = logging.getLogger(name)
fomatter = logging.Formatter(
'[ %(levelname)s|%(filename)s:%(lineno)s] %(asctime)s > %(message)s')
if not os.path.isfile(log_path):
f = open(log_path, "w+")
fileHandler = logging.FileHandler(log_path)
... | def tensorboard_logger(name, log_path):
"""
logger for tensorboard
"""
logger = logging.getLogger(name)
fomatter = logging.Formatter(
'[ %(levelname)s|%(filename)s:%(lineno)s] %(asctime)s > %(message)s')
if not os.path.isfile(log_path):
f = open(log_path, "w+")
fileHand... | riteshkumarumassedu/BERT-with-SOP | utils.py |
8bd9d5423664490e43d9b6ec | function | simple | ("%s (%d GPUs)" % (device, n_gpu))
return device
def set_random_seed(seed):
"""
set random seeds
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def split_last(x, shape):
| """
split the last dimension to given shape
"""
shape = list(shape)
assert shape.count(-1) <= 1
if -1 in shape:
shape[shape.index(-1)] = int(x.size(-1) / -np.prod(shape))
return x.view(*x.size()[:-1], *shape)
| def split_last(x, shape):
"""
split the last dimension to given shape
"""
shape = list(shape)
assert shape.count(-1) <= 1
if -1 in shape:
shape[shape.index(-1)] = int(x.size(-1) / -np.prod(shape))
return x.view(*x.size()[:-1], *shape)
| riteshkumarumassedu/BERT-with-SOP | utils.py |
b17763d46fdcf55fd557a4ec | function | simple | merge_last(x, n_dims):
"""
merge the last n_dims to a dimension
"""
s = x.size()
assert n_dims > 1 and n_dims < len(s)
return x.view(*s[:-n_dims], -1)
def find_sublist(haystack, needle):
| h = len(haystack)
n = len(needle)
skip = {needle[i]: n - i - 1 for i in range(n - 1)}
i = n - 1
while i < h:
for j in range(n):
if haystack[i - j] != needle[-j - 1]:
i += skip.get(haystack[i], n)
break
else:
return i - n + 1
... | def find_sublist(haystack, needle):
h = len(haystack)
n = len(needle)
skip = {needle[i]: n - i - 1 for i in range(n - 1)}
i = n - 1
while i < h:
for j in range(n):
if haystack[i - j] != needle[-j - 1]:
i += skip.get(haystack[i], n)
break
el... | riteshkumarumassedu/BERT-with-SOP | utils.py |
560beb9e46acb852748f1c1a | function | simple | """
get device (CPU or GPU)
"""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
n_gpu = torch.cuda.device_count()
print("%s (%d GPUs)" % (device, n_gpu))
return device
def set_random_seed(seed):
| """
set random seeds
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
| def set_random_seed(seed):
"""
set random seeds
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
| riteshkumarumassedu/BERT-with-SOP | utils.py |
07d4b409da57a9a64f5bed6d | function | simple | _pair(tokens_a, tokens_b, max_len):
while True:
if len(tokens_a) + len(tokens_b) <= max_len:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def get_random_word(vocab_words):
| i = random.randint(0, len(vocab_words)-1)
return vocab_words[i]
| def get_random_word(vocab_words):
i = random.randint(0, len(vocab_words)-1)
return vocab_words[i]
| riteshkumarumassedu/BERT-with-SOP | utils.py |
00b6c9d5607943df8d408f57 | function | simple | range(n):
if haystack[i - j] != needle[-j - 1]:
i += skip.get(haystack[i], n)
break
else:
return i - n + 1
return -1
def truncate_tokens_pair(tokens_a, tokens_b, max_len):
| while True:
if len(tokens_a) + len(tokens_b) <= max_len:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
| def truncate_tokens_pair(tokens_a, tokens_b, max_len):
while True:
if len(tokens_a) + len(tokens_b) <= max_len:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
| riteshkumarumassedu/BERT-with-SOP | utils.py |
9807271da798b076dc82dc85 | function | simple | "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 in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WA... | """Parses all arguments and assigns default values when missing.
Convert argument strings to objects and assign them as attributes of the
namespace.
Returns:
An object containing all the parsed arguments for script to use.
"""
args_parser = argparse.ArgumentParser()
args_parser.add... | def initialise_params():
"""Parses all arguments and assigns default values when missing.
Convert argument strings to objects and assign them as attributes of the
namespace.
Returns:
An object containing all the parsed arguments for script to use.
"""
args_parser = argparse.ArgumentPar... | ruchirjain86/professional-services | examples/cloudml-energy-price-forecasting/trainer/task.py |
6e00d28cbac88dc6532d3a67 | function | simple | .get_train_spec(
parameters.training_path,
parameters.batch_size,
parameters.max_steps)
eval_spec = inputs.get_eval_spec(
parameters.validation_path,
parameters.eval_batch_size)
tf.estimator.train_and_evaluate(
estimator,
train_spec,
eval_spec
... | """Main function to be run when executing job.
Orchestrates the script
"""
parameters = initialise_params()
tf.logging.set_verbosity(tf.logging.INFO)
model_dir = os.path.join(parameters.job_dir, json.loads(
os.environ.get('TF_CONFIG', '{}')).get('task', {}).get('trial', ''))
run_co... | def main():
"""Main function to be run when executing job.
Orchestrates the script
"""
parameters = initialise_params()
tf.logging.set_verbosity(tf.logging.INFO)
model_dir = os.path.join(parameters.job_dir, json.loads(
os.environ.get('TF_CONFIG', '{}')).get('task', {}).get('trial', ''))... | ruchirjain86/professional-services | examples/cloudml-energy-price-forecasting/trainer/task.py |
bb88056e783c7e57a709b998 | function | simple | help='Evaluation batch size.',
default=168,
type=int
)
args_parser.add_argument(
'--max_steps',
help='Maximum steps for training.',
default=5000,
type=int
)
return args_parser.parse_args()
def run_experiment(run_config, parameters):
| """Runs TensorFlow experiment.
Creates the model, trains it, and evaluates it.
Args:
run_config: Configuration for experiment.
parameters: Parameters passed to the job.
"""
estimator = model.create_regressor(
config=run_config, parameters=parameters)
train_spec = inputs... | def run_experiment(run_config, parameters):
"""Runs TensorFlow experiment.
Creates the model, trains it, and evaluates it.
Args:
run_config: Configuration for experiment.
parameters: Parameters passed to the job.
"""
estimator = model.create_regressor(
config=run_config, pa... | ruchirjain86/professional-services | examples/cloudml-energy-price-forecasting/trainer/task.py |
046200f01b7a5842180d27aa | function | simple | , tmp_image
from mapproxy.test.http import mock_httpd
from mapproxy.test.system.test_wms import is_111_capa, is_130_capa, ns130
@pytest.fixture(scope="module")
def config_file():
return "scalehints.yaml"
def diagonal_res_to_pixel_res(res):
| """
>>> '%.2f' % round(diagonal_res_to_pixel_res(14.14214), 4)
'10.00'
"""
return math.sqrt((float(res) ** 2) / 2)
| def diagonal_res_to_pixel_res(res):
"""
>>> '%.2f' % round(diagonal_res_to_pixel_res(14.14214), 4)
'10.00'
"""
return math.sqrt((float(res) ** 2) / 2)
| cunha17/mapproxy | mapproxy/test/system/test_scalehints.py |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 7