uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2b45de9ccd10e396e667f4e5 | train | class | @requireCapability('barn', 'oats')
class Horse(ActorTypeDispatcher):
def receiveMsg_str(self, strmsg, sender):
self.send(sender, 'Neigh: ' + strmsg)
| @requireCapability('barn', 'oats')
class Horse(ActorTypeDispatcher):
| def receiveMsg_str(self, strmsg, sender):
self.send(sender, 'Neigh: ' + strmsg)
| == "Register":
self.preRegisterRemoteSystem(msg[1], msg[2])
if msg[0] == "Deregister":
self.deRegisterRemoteSystem(msg[1])
self.send(sender, "OK")
@requireCapability('barn', 'oats')
class Horse(ActorTypeDispatcher):
| 64 | 64 | 43 | 17 | 47 | dendron2000/Thespian | thespian/test/test_preRegistration.py | Python | Horse | Horse | 24 | 27 | 24 | 25 | d81b546d88dd9ba58121107a215a230fb82112aa | bigcode/the-stack | train |
47b14381f03143234a97a27c | train | class | class PreRegistrationActor(ActorTypeDispatcher):
def receiveMsg_tuple(self, msg, sender):
if msg[0] == "Register":
self.preRegisterRemoteSystem(msg[1], msg[2])
if msg[0] == "Deregister":
self.deRegisterRemoteSystem(msg[1])
self.send(sender, "OK")
| class PreRegistrationActor(ActorTypeDispatcher):
| def receiveMsg_tuple(self, msg, sender):
if msg[0] == "Register":
self.preRegisterRemoteSystem(msg[1], msg[2])
if msg[0] == "Deregister":
self.deRegisterRemoteSystem(msg[1])
self.send(sender, "OK")
| TestLogging
from thespian.actors import *
from thespian.system.messages.status import *
from thespian.system.utilis import fmap
MAX_ASK_DELAY = timedelta(seconds=2)
wait_for_registration = lambda: inTestDelay(timedelta(milliseconds=250))
class PreRegistrationActor(ActorTypeDispatcher):
| 64 | 64 | 73 | 9 | 55 | dendron2000/Thespian | thespian/test/test_preRegistration.py | Python | PreRegistrationActor | PreRegistrationActor | 14 | 21 | 14 | 15 | 08542781b76746c13675c9fb5b457def6447c8b1 | bigcode/the-stack | train |
d396d01c91b1ceff61861870 | train | function | def showAdminStatus(actorSys):
admin = actorSys._systemBase\
.transport\
.getAddressFromString('127.0.0.1:%d'%actorSys.port_num)
print('admin address: %s'%str(admin))
sts = actorSys.ask(admin, Thespian_StatusReq(), 2)
if sts is None:
print('no status from ... | def showAdminStatus(actorSys):
| admin = actorSys._systemBase\
.transport\
.getAddressFromString('127.0.0.1:%d'%actorSys.port_num)
print('admin address: %s'%str(admin))
sts = actorSys.ask(admin, Thespian_StatusReq(), 2)
if sts is None:
print('no status from system 1')
else:
fo... | self.notifyOnSystemRegistrationChanges(boolmsg)
def receiveMsg_ActorSystemConventionUpdate(self, update, sender):
newn = [N for N in self.notifications if N.remoteAdminAddress != update.remoteAdminAddress]
self.notifications = newn + [update]
def showAdminStatus(actorSys):
| 64 | 64 | 98 | 7 | 57 | dendron2000/Thespian | thespian/test/test_preRegistration.py | Python | showAdminStatus | showAdminStatus | 52 | 61 | 52 | 52 | 12f5d4aa44c824b45cd4efe5a38e69edd2eb93c3 | bigcode/the-stack | train |
20be2a7402cf1edfdc05f84d | train | class | class NotificationHandler(ActorTypeDispatcher):
def __init__(self, *args, **kw):
super(NotificationHandler, self).__init__(*args, **kw)
self.notifications = []
def receiveMsg_str(self, strmsg, sender):
self.send(sender, self.notifications)
def receiveMsg_bool(self, boolmsg, sender)... | class NotificationHandler(ActorTypeDispatcher):
| def __init__(self, *args, **kw):
super(NotificationHandler, self).__init__(*args, **kw)
self.notifications = []
def receiveMsg_str(self, strmsg, sender):
self.send(sender, self.notifications)
def receiveMsg_bool(self, boolmsg, sender):
self.notifyOnSystemRegistrationChanges... | , sender):
self.send(sender, 'Neigh: ' + strmsg)
@requireCapability('moo')
class Cow(ActorTypeDispatcher):
def receiveMsg_str(self, strmsg, sender):
self.send(sender, 'Moo: ' + strmsg)
class NotificationHandler(ActorTypeDispatcher):
| 64 | 64 | 129 | 8 | 56 | dendron2000/Thespian | thespian/test/test_preRegistration.py | Python | NotificationHandler | NotificationHandler | 36 | 49 | 36 | 36 | 0c546a277962c9444ac038c8b871779103d5f381 | bigcode/the-stack | train |
c37051b58deafe3f34eb4bc5 | train | class | class TestFuncRegistration(object):
def test_Registration(self, asys, asys2):
unsupported(asys)
asys.updateCapability('dog', 'food')
asys2.updateCapability('barn', 'oats')
regActor = asys.createActor(PreRegistrationActor)
raises(NoCompatibleSystemForActor, asys.createActor,... | class TestFuncRegistration(object):
| def test_Registration(self, asys, asys2):
unsupported(asys)
asys.updateCapability('dog', 'food')
asys2.updateCapability('barn', 'oats')
regActor = asys.createActor(PreRegistrationActor)
raises(NoCompatibleSystemForActor, asys.createActor, Horse)
raises(NoCompatibleSy... | super(NotificationHandler, self).__init__(*args, **kw)
self.notifications = []
def receiveMsg_str(self, strmsg, sender):
self.send(sender, self.notifications)
def receiveMsg_bool(self, boolmsg, sender):
self.notifyOnSystemRegistrationChanges(boolmsg)
def receiveMsg_ActorSystemCon... | 256 | 256 | 2,419 | 6 | 250 | dendron2000/Thespian | thespian/test/test_preRegistration.py | Python | TestFuncRegistration | TestFuncRegistration | 72 | 335 | 72 | 73 | c9cebd144ccfb51955e7a55e036e31e659feebd8 | bigcode/the-stack | train |
04009f8959093147364f8c68 | train | class | @requireCapability('moo')
class Cow(ActorTypeDispatcher):
def receiveMsg_str(self, strmsg, sender):
self.send(sender, 'Moo: ' + strmsg)
| @requireCapability('moo')
class Cow(ActorTypeDispatcher):
| def receiveMsg_str(self, strmsg, sender):
self.send(sender, 'Moo: ' + strmsg)
| self.send(sender, "OK")
@requireCapability('barn', 'oats')
class Horse(ActorTypeDispatcher):
def receiveMsg_str(self, strmsg, sender):
self.send(sender, 'Neigh: ' + strmsg)
@requireCapability('moo')
class Cow(ActorTypeDispatcher):
| 64 | 64 | 39 | 13 | 51 | dendron2000/Thespian | thespian/test/test_preRegistration.py | Python | Cow | Cow | 30 | 33 | 30 | 31 | a847d6d03c8799daa6e96daf2918e0c4438b240b | bigcode/the-stack | train |
609b94fd075ace4027ba89b5 | train | function | async def test_if_action(hass, calls):
"""Test for firing if action."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": [
... | async def test_if_action(hass, calls):
| """Test for firing if action."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": [
{
"con... | .async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 1
hass.states.async_set("test.entity", "home")
await hass.async_block_till_done()
assert len(calls) == 2
async def test_if_action(hass, calls):
| 69 | 69 | 231 | 10 | 58 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_action | test_if_action | 377 | 409 | 377 | 377 | 5d2905c4c4937eeaf337a4116e8bb0d0d020da3a | bigcode/the-stack | train |
94222486373bc39d2dfe0bf6 | train | function | async def test_if_fires_on_change_with_bad_template_2(hass, calls):
"""Test for firing on change with bad template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_fires_on_change_with_bad_template_2(hass, calls):
| """Test for firing on change with bad template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ xyz | round(0) }}",
... | .DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "template", "value_template": "{{ "},
"action": {"service": "test.automation"},
}
},
)
async def test_if_fires_on_change_with_bad_template_2(hass, calls):
| 64 | 64 | 129 | 18 | 46 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_bad_template_2 | test_if_fires_on_change_with_bad_template_2 | 427 | 445 | 427 | 427 | 1aa77d8f53a9e256934f60dc2d14e2a52fa7f75a | bigcode/the-stack | train |
d55f14893db3ea1c70b6acc9 | train | function | async def test_if_fires_on_change_with_template_advanced(hass, calls):
"""Test for firing on change with template advanced."""
context = Context()
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
... | async def test_if_fires_on_change_with_template_advanced(hass, calls):
| """Test for firing on change with template advanced."""
context = Context()
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '... | action": {"service": "test.automation"},
}
},
)
await hass.async_block_till_done()
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async def test_if_fires_on_change_with_template_advanced(hass, calls):
| 73 | 73 | 246 | 17 | 55 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_template_advanced | test_if_fires_on_change_with_template_advanced | 263 | 300 | 263 | 263 | 91ba1fd8c88f90c81f54d9a4e53e381997a76234 | bigcode/the-stack | train |
cdcd7fe11f406dc1fa4aaf75 | train | function | async def test_if_fires_on_no_change_with_template_advanced(hass, calls):
"""Test for firing on no change with template advanced."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform"... | async def test_if_fires_on_no_change_with_template_advanced(hass, calls):
| """Test for firing on no change with template advanced."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": """{%- if is_state("te... | assert len(calls) == 1
assert calls[0].context.parent_id == context.id
assert "template - test.entity - hello - world - None" == calls[0].data["some"]
async def test_if_fires_on_no_change_with_template_advanced(hass, calls):
| 63 | 64 | 201 | 18 | 45 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_no_change_with_template_advanced | test_if_fires_on_no_change_with_template_advanced | 303 | 331 | 303 | 303 | 63932d89ecf9a4d25584089c3f9dcc6095a3b311 | bigcode/the-stack | train |
3f78fd5416b9732f41f15780 | train | function | async def test_if_not_fires_on_change_with_template(hass, calls):
"""Test for not firing on change with template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_not_fires_on_change_with_template(hass, calls):
| """Test for not firing on change with template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ is_state("test.entity", "h... | "action": {"service": "test.automation"},
}
},
)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_not_fires_on_change_with_template(hass, calls):
| 64 | 64 | 139 | 16 | 47 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_not_fires_on_change_with_template | test_if_not_fires_on_change_with_template | 240 | 260 | 240 | 240 | 0cbfaddfbac5c0c49e87fc46458ed96f33bd26cb | bigcode/the-stack | train |
93b126abfb1a52861f91486f | train | function | async def test_if_fires_on_change_with_for(hass, calls):
"""Test for firing on change with for."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_fires_on_change_with_for(hass, calls):
| """Test for firing on change with for."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}... | ("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["some"] == "template - test.entity - hello - world - None"
async def test_if_fires_on_change_with_for(hass, calls):
| 64 | 64 | 175 | 15 | 49 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_for | test_if_fires_on_change_with_for | 496 | 518 | 496 | 496 | b118721a319fdc8f5a6836c924d1ce08c6e9df8c | bigcode/the-stack | train |
f1e0d8cb662d29adcf96177a | train | function | async def test_if_fires_on_time_change(hass, calls):
"""Test for firing on time changes."""
start_time = dt_util.utcnow() + timedelta(hours=24)
time_that_will_not_match_right_away = start_time.replace(minute=1, second=0)
with patch(
"homeassistant.util.dt.utcnow", return_value=time_that_will_not... | async def test_if_fires_on_time_change(hass, calls):
| """Test for firing on time changes."""
start_time = dt_util.utcnow() + timedelta(hours=24)
time_that_will_not_match_right_away = start_time.replace(minute=1, second=0)
with patch(
"homeassistant.util.dt.utcnow", return_value=time_that_will_not_match_right_away
):
assert await async_s... | Test for invalid for template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
... | 146 | 146 | 487 | 14 | 131 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_time_change | test_if_fires_on_time_change | 834 | 886 | 834 | 834 | 696c4741e971c8a321834ab221b7d151bb7fb470 | bigcode/the-stack | train |
9aa7740df08eeacf14670668 | train | function | async def test_if_fires_on_change_with_template_2(hass, calls):
"""Test for firing on change with template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_fires_on_change_with_template_2(hass, calls):
| """Test for firing on change with template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ not is_state("test.entity", "w... | Different state
hass.states.async_set("test.entity", "worldz")
await hass.async_block_till_done()
assert len(calls) == 0
# Different state
hass.states.async_set("test.entity", "hello")
await hass.async_block_till_done()
assert len(calls) == 0
async def test_if_fires_on_change_with_template... | 88 | 88 | 296 | 17 | 70 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_template_2 | test_if_fires_on_change_with_template_2 | 334 | 374 | 334 | 334 | 8934ea9fd0de38330ef520c3f635b1bf75bad812 | bigcode/the-stack | train |
cdf06854a49948c0820679ad | train | function | async def test_if_fires_on_two_change(hass, calls):
"""Test for firing on two changes."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_te... | async def test_if_fires_on_two_change(hass, calls):
| """Test for firing on two changes."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ states.test.entity.state and true }}",
... | },
)
await hass.async_block_till_done()
cur_len = len(calls)
hass.states.async_set("test.entity", "hello")
await hass.async_block_till_done()
assert cur_len == len(calls)
async def test_if_fires_on_two_change(hass, calls):
| 64 | 64 | 164 | 14 | 50 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_two_change | test_if_fires_on_two_change | 192 | 216 | 192 | 192 | 9a5ef2d116578e40dbb6b49ac8de0a1bdc46f2b4 | bigcode/the-stack | train |
ca55660603169e33c9d8482d | train | function | async def test_if_fires_on_change_str(hass, calls):
"""Test for firing on change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_templat... | async def test_if_fires_on_change_str(hass, calls):
| """Test for firing on change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ states.test.entity.state and "true" }}',
... | URN_OFF,
{ATTR_ENTITY_ID: ENTITY_MATCH_ALL},
blocking=True,
)
hass.states.async_set("test.entity", "planet")
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_fires_on_change_str(hass, calls):
| 64 | 64 | 124 | 14 | 49 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_str | test_if_fires_on_change_str | 69 | 87 | 69 | 69 | db610d8871f330b8551d677264a4df6f026ab5f0 | bigcode/the-stack | train |
e24c5e4cc67e3286a73b00b0 | train | function | async def test_if_fires_on_change_with_for_advanced(hass, calls):
"""Test for firing on change with for advanced."""
context = Context()
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"p... | async def test_if_fires_on_change_with_for_advanced(hass, calls):
| """Test for firing on change with for advanced."""
context = Context()
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ is... | },
)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_fires_on_change_with_for_a... | 89 | 89 | 298 | 17 | 71 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_for_advanced | test_if_fires_on_change_with_for_advanced | 521 | 562 | 521 | 521 | f6bb063f6d2b053e0183dfeeaefabd3379125a65 | bigcode/the-stack | train |
fb49fdffc12a139d7361d424 | train | function | async def test_if_fires_on_change_with_for_template_2(hass, calls):
"""Test for firing on change with for template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_fires_on_change_with_for_template_2(hass, calls):
| """Test for firing on change with for template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'w... | assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_fires_on_change_with_for_template_2(hass, calls):
| 64 | 64 | 178 | 18 | 45 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_for_template_2 | test_if_fires_on_change_with_for_template_2 | 761 | 783 | 761 | 761 | 11884092493a663671ad3d540dfac40923cb2a21 | bigcode/the-stack | train |
a3045a22675886b34012ac9a | train | function | async def test_if_not_fires_on_change_with_for(hass, calls):
"""Test for firing on change with for."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_not_fires_on_change_with_for(hass, calls):
| """Test for firing on change with for."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}... | .async_block_till_done()
assert len(calls) == 1
assert calls[0].context.parent_id == context.id
assert calls[0].data["some"] == "template - test.entity - hello - world - 0:00:05"
async def test_if_not_fires_on_change_with_for(hass, calls):
| 73 | 73 | 244 | 16 | 57 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_not_fires_on_change_with_for | test_if_not_fires_on_change_with_for | 670 | 698 | 670 | 670 | b5d113219025762856d3fbc3c1efc1f086e214ba | bigcode/the-stack | train |
8384e24450053664e5416437 | train | function | @pytest.fixture(autouse=True)
def setup_comp(hass):
"""Initialize components."""
mock_component(hass, "group")
hass.states.async_set("test.entity", "hello")
| @pytest.fixture(autouse=True)
def setup_comp(hass):
| """Initialize components."""
mock_component(hass, "group")
hass.states.async_set("test.entity", "hello")
| ,
)
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa
@pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
@pytest.fixture(autouse=True)
def setup_comp(hass):
| 64 | 64 | 39 | 13 | 51 | miccico/core | tests/components/template/test_trigger.py | Python | setup_comp | setup_comp | 30 | 34 | 30 | 31 | b4445ddf3f488c7ff61e77f73c36e915e9b9632d | bigcode/the-stack | train |
965864e4c12d92496028af1c | train | function | async def test_if_fires_on_change_with_for_template_1(hass, calls):
"""Test for firing on change with for template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_fires_on_change_with_for_template_1(hass, calls):
| """Test for firing on change with for template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'w... | assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=6))
await hass.async_block_till_done()
assert len(calls) == 0
async def test_if_fires_on_change_with_for_template_1(hass, calls):
| 64 | 64 | 181 | 18 | 45 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_for_template_1 | test_if_fires_on_change_with_for_template_1 | 736 | 758 | 736 | 736 | 65d1a39962138a5cb97c4d223273d67a9025aec8 | bigcode/the-stack | train |
989dcf4faed27e3bb002d777 | train | function | @pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
| @pytest.fixture
def calls(hass):
| """Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
| _setup_component
import homeassistant.util.dt as dt_util
from tests.common import (
assert_setup_component,
async_fire_time_changed,
async_mock_service,
mock_component,
)
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa
@pytest.fixture
def calls(hass):
| 64 | 64 | 31 | 8 | 55 | miccico/core | tests/components/template/test_trigger.py | Python | calls | calls | 24 | 27 | 24 | 25 | b7f416106e10ac548681ca4dee417a5161181aae | bigcode/the-stack | train |
e68b24f1e18b3de8d2514772 | train | function | async def test_if_fires_on_change_with_template(hass, calls):
"""Test for firing on change with template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_fires_on_change_with_template(hass, calls):
| """Test for firing on change with template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ is_state("test.entity", "world... | ill_done()
assert len(calls) == 1
# Trigger again
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_fires_on_change_with_template(hass, calls):
| 64 | 64 | 128 | 15 | 48 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_template | test_if_fires_on_change_with_template | 219 | 237 | 219 | 219 | da2ec2fb49b36697ee6b03e5758d8a1a991ac4f3 | bigcode/the-stack | train |
db3a5bddcba783a2e1890102 | train | function | async def test_if_fires_on_no_change(hass, calls):
"""Test for firing on no change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "template", "value_template": "{{ true }}"},
"act... | async def test_if_fires_on_no_change(hass, calls):
| """Test for firing on no change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "template", "value_template": "{{ true }}"},
"action": {"service": "test.automation"},
}... | },
"action": {"service": "test.automation"},
}
},
)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async def test_if_fires_on_no_change(hass, calls):
| 64 | 64 | 129 | 14 | 49 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_no_change | test_if_fires_on_no_change | 171 | 189 | 171 | 171 | f8194aa9a3fa50204249f45fc55d63022fa723f8 | bigcode/the-stack | train |
16f907a941530301c8aa9735 | train | function | async def test_if_fires_on_change_with_for_0(hass, calls):
"""Test for firing on change with for: 0."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_fires_on_change_with_for_0(hass, calls):
| """Test for firing on change with for: 0."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world')... | ) == 1
assert calls[0].context.parent_id == context.id
assert "template - test.entity - hello - world - 0:00:05" == calls[0].data["some"]
async def test_if_fires_on_change_with_for_0(hass, calls):
| 63 | 64 | 143 | 17 | 46 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_for_0 | test_if_fires_on_change_with_for_0 | 565 | 584 | 565 | 565 | 09e6a01acb97f4de902638ab9fa57492e06c9fbc | bigcode/the-stack | train |
48305ab102913ace94b2394e | train | function | async def test_if_not_fires_on_change_str_crazy(hass, calls):
"""Test for not firing on string change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_not_fires_on_change_str_crazy(hass, calls):
| """Test for not firing on string change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ "Anything other than true is fals... | ": {"service": "test.automation"},
}
},
)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async def test_if_not_fires_on_change_str_crazy(hass, calls):
| 64 | 64 | 130 | 18 | 45 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_not_fires_on_change_str_crazy | test_if_not_fires_on_change_str_crazy | 150 | 168 | 150 | 150 | 1a0e6ac4b962802084b8511c03fbfa6aade38993 | bigcode/the-stack | train |
13df68d16f317803737775d6 | train | function | async def test_if_fires_on_change_bool(hass, calls):
"""Test for firing on boolean change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"valu... | async def test_if_fires_on_change_bool(hass, calls):
| """Test for firing on boolean change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ states.test.entity.state and true }}... | _mock_service(hass, "test", "automation")
@pytest.fixture(autouse=True)
def setup_comp(hass):
"""Initialize components."""
mock_component(hass, "group")
hass.states.async_set("test.entity", "hello")
async def test_if_fires_on_change_bool(hass, calls):
| 64 | 64 | 188 | 14 | 50 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_bool | test_if_fires_on_change_bool | 37 | 66 | 37 | 37 | 7c2a32b718c7b1f417cf5173ba0f021453a52cb2 | bigcode/the-stack | train |
39ac373d3b77a19e5dfd5f93 | train | function | async def test_if_fires_on_change_with_bad_template(hass, calls):
"""Test for firing on change with bad template."""
with assert_setup_component(0, automation.DOMAIN):
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
... | async def test_if_fires_on_change_with_bad_template(hass, calls):
| """Test for firing on change with bad template."""
with assert_setup_component(0, automation.DOMAIN):
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "template", "value_tem... | assert len(calls) == 0
# Condition is true and event is triggered
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_fires_on_change_with_bad_template(hass, calls):
| 64 | 64 | 97 | 16 | 47 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_bad_template | test_if_fires_on_change_with_bad_template | 412 | 424 | 412 | 412 | 8453557a79a40b2a14a02a9dcdc0de0692cbb71c | bigcode/the-stack | train |
96818f27bfc65b7d804adbb1 | train | function | async def test_invalid_for_template_1(hass, calls):
"""Test for invalid for template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_tem... | async def test_invalid_for_template_1(hass, calls):
| """Test for invalid for template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}",
... | _till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
async def test_invalid_for_template_1(hass, calls):
| 64 | 64 | 147 | 13 | 50 | miccico/core | tests/components/template/test_trigger.py | Python | test_invalid_for_template_1 | test_invalid_for_template_1 | 811 | 831 | 811 | 811 | 6afd010a790fe6b1e4277a9d12d06889ca43b885 | bigcode/the-stack | train |
28e7c4383b8eb49f1dab350b | train | function | async def test_if_not_fires_on_change_bool(hass, calls):
"""Test for not firing on boolean change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_not_fires_on_change_bool(hass, calls):
| """Test for not firing on boolean change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ states.test.entity.state and fal... | "action": {"service": "test.automation"},
}
},
)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_not_fires_on_change_bool(hass, calls):
| 64 | 64 | 125 | 15 | 48 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_not_fires_on_change_bool | test_if_not_fires_on_change_bool | 111 | 129 | 111 | 111 | 4215dfb1ac9834763df0e36bae0481122a4877c5 | bigcode/the-stack | train |
a0fdfe7abcad235b4d5dd1a6 | train | function | async def test_if_not_fires_on_change_str(hass, calls):
"""Test for not firing on string change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "template", "value_template": "true"},
... | async def test_if_not_fires_on_change_str(hass, calls):
| """Test for not firing on string change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "template", "value_template": "true"},
"action": {"service": "test.automation"},
... | "action": {"service": "test.automation"},
}
},
)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 0
async def test_if_not_fires_on_change_str(hass, calls):
| 64 | 64 | 114 | 15 | 48 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_not_fires_on_change_str | test_if_not_fires_on_change_str | 132 | 147 | 132 | 132 | cfa95f24b4c2fb1e53036e86730471006746762c | bigcode/the-stack | train |
d34ce0c34a141df035adda2c | train | function | async def test_if_not_fires_when_turned_off_with_for(hass, calls):
"""Test for firing on change with for."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_not_fires_when_turned_off_with_for(hass, calls):
| """Test for firing on change with for."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'world') }}... | "hello")
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=6))
await hass.async_block_till_done()
assert len(calls) == 0
async def test_if_not_fires_when_turned_off_with_for(hass, calls):
| 77 | 77 | 259 | 18 | 58 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_not_fires_when_turned_off_with_for | test_if_not_fires_when_turned_off_with_for | 701 | 733 | 701 | 701 | b96561a2acdff4af57aa51d1be4a4436e1ae540b | bigcode/the-stack | train |
59eed21da3f5b80f4ab7af5c | train | function | async def test_if_fires_on_change_with_for_template_3(hass, calls):
"""Test for firing on change with for template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_if_fires_on_change_with_for_template_3(hass, calls):
| """Test for firing on change with for template."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('test.entity', 'w... | assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_fires_on_change_with_for_template_3(hass, calls):
| 64 | 64 | 183 | 18 | 45 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_for_template_3 | test_if_fires_on_change_with_for_template_3 | 786 | 808 | 786 | 786 | 581ac879161e99f78678b762f36afbcbdedc2436 | bigcode/the-stack | train |
92253bb036a21f0339e40c15 | train | function | async def test_if_fires_on_change_with_for_2(hass, calls):
"""Test for firing on change with for."""
context = Context()
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "templ... | async def test_if_fires_on_change_with_for_2(hass, calls):
| """Test for firing on change with for."""
context = Context()
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ is_state('t... | .entity", "world", context=context)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].context.parent_id == context.id
assert calls[0].data["some"] == "template - test.entity - hello - world - 0:00:00"
async def test_if_fires_on_change_with_for_2(hass, calls):
| 85 | 85 | 285 | 17 | 68 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_for_2 | test_if_fires_on_change_with_for_2 | 628 | 667 | 628 | 628 | ab3302df814c0abf2c19401ec719fcff4f64eec3 | bigcode/the-stack | train |
6d01884acb0ee974f411edbd | train | function | async def test_if_fires_on_change_with_for_0_advanced(hass, calls):
"""Test for firing on change with for: 0 advanced."""
context = Context()
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
... | async def test_if_fires_on_change_with_for_0_advanced(hass, calls):
| """Test for firing on change with for: 0 advanced."""
context = Context()
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{... | "for": {"seconds": 0},
},
"action": {"service": "test.automation"},
}
},
)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_fires_on_change_with_for_0_advanced(hass, calls):
| 79 | 79 | 266 | 19 | 59 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_with_for_0_advanced | test_if_fires_on_change_with_for_0_advanced | 587 | 625 | 587 | 587 | e37eb73b14a72a75916ea0ef05349ae17fc9596a | bigcode/the-stack | train |
451a19edf2df4e9554025f01 | train | function | async def test_if_fires_on_change_str_crazy(hass, calls):
"""Test for firing on change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_t... | async def test_if_fires_on_change_str_crazy(hass, calls):
| """Test for firing on change."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": '{{ states.test.entity.state and "TrUE" }}',
... | action": {"service": "test.automation"},
}
},
)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert len(calls) == 1
async def test_if_fires_on_change_str_crazy(hass, calls):
| 64 | 64 | 128 | 17 | 46 | miccico/core | tests/components/template/test_trigger.py | Python | test_if_fires_on_change_str_crazy | test_if_fires_on_change_str_crazy | 90 | 108 | 90 | 90 | 89df9f06aabc09196ff571611ba7f9c661297d01 | bigcode/the-stack | train |
82ee7c3710d1202d31a61dc4 | train | function | async def test_wait_template_with_trigger(hass, calls):
"""Test using wait template with 'trigger.entity_id'."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
... | async def test_wait_template_with_trigger(hass, calls):
| """Test using wait template with 'trigger.entity_id'."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "template",
"value_template": "{{ states.test.entity.s... | {
"platform": "template",
"value_template": "{{ xyz | round(0) }}",
},
"action": {"service": "test.automation"},
}
},
)
hass.states.async_set("test.entity", "world")
await hass.async_block_till_done()
assert le... | 85 | 85 | 286 | 12 | 72 | miccico/core | tests/components/template/test_trigger.py | Python | test_wait_template_with_trigger | test_wait_template_with_trigger | 448 | 493 | 448 | 448 | 9e84ba9be10efcd70c09906dc00f82e864d0b424 | bigcode/the-stack | train |
e477fd281bde08cc00190414 | train | function | @pytest.mark.skipif(sys.version_info > (3,), reason="requires python 2.x")
def test_compat_py2():
assert _is_str(unicode(''))
# Python 2.x - 8 bit strings are just regular strings
str_8bit = _bytes_join(['a', 'b', 'c'])
assert str_8bit == 'abc'.encode()
assert "'abc'" == '%r' % str_8bit
| @pytest.mark.skipif(sys.version_info > (3,), reason="requires python 2.x")
def test_compat_py2():
| assert _is_str(unicode(''))
# Python 2.x - 8 bit strings are just regular strings
str_8bit = _bytes_join(['a', 'b', 'c'])
assert str_8bit == 'abc'.encode()
assert "'abc'" == '%r' % str_8bit
| '.encode(), 'c'.encode()])
assert str_8bit == 'abc'.encode()
assert "b'abc'" == '%r' % str_8bit
@pytest.mark.skipif(sys.version_info > (3,), reason="requires python 2.x")
def test_compat_py2():
| 64 | 64 | 97 | 26 | 37 | Rockly/netaddr | netaddr/tests/core/test_compat.py | Python | test_compat_py2 | test_compat_py2 | 22 | 29 | 22 | 23 | 2e02f570c6b04551594f5801cd8a9287fa60e993 | bigcode/the-stack | train |
957e3f21d7e8e81c35163c40 | train | function | def test_compat_range():
l1 = _range(3)
assert isinstance(l1, list)
assert hasattr(l1, 'pop')
assert l1 == [0, 1, 2]
it = _iter_range(3)
assert not isinstance(it, list)
assert hasattr(it, '__iter__')
assert it != [0, 1, 2]
assert list(it) == [0, 1, 2]
| def test_compat_range():
| l1 = _range(3)
assert isinstance(l1, list)
assert hasattr(l1, 'pop')
assert l1 == [0, 1, 2]
it = _iter_range(3)
assert not isinstance(it, list)
assert hasattr(it, '__iter__')
assert it != [0, 1, 2]
assert list(it) == [0, 1, 2]
| ', 0), ('b', 1), ('c', 2)]
def test_compat_zip():
l2 = _zip([0], [1])
assert hasattr(_zip(l2), 'pop')
assert l2 == [(0, 1)]
def test_compat_range():
| 63 | 64 | 100 | 6 | 57 | Rockly/netaddr | netaddr/tests/core/test_compat.py | Python | test_compat_range | test_compat_range | 51 | 61 | 51 | 51 | f139a74769580650b82f8173d8ee7f962c14f8e2 | bigcode/the-stack | train |
a68144013cf31a7b4638eb0e | train | function | def test_compat_callable():
i = 1
def f1():
"""docstring"""
pass
f2 = lambda x: x
assert not _callable(i)
assert _callable(f1)
assert _callable(f2)
| def test_compat_callable():
| i = 1
def f1():
"""docstring"""
pass
f2 = lambda x: x
assert not _callable(i)
assert _callable(f1)
assert _callable(f2)
| , 2]
it = _iter_range(3)
assert not isinstance(it, list)
assert hasattr(it, '__iter__')
assert it != [0, 1, 2]
assert list(it) == [0, 1, 2]
def test_compat_callable():
| 64 | 64 | 58 | 6 | 58 | Rockly/netaddr | netaddr/tests/core/test_compat.py | Python | test_compat_callable | test_compat_callable | 64 | 75 | 64 | 64 | 9423d1e7cde63ce3a38ff8eaf760c5111ea8f76e | bigcode/the-stack | train |
fffb4e3484604a309b710ab4 | train | function | def test_iter_next():
it = iter([42])
assert _iter_next(it) == 42
| def test_iter_next():
| it = iter([42])
assert _iter_next(it) == 42
| ]
def test_compat_callable():
i = 1
def f1():
"""docstring"""
pass
f2 = lambda x: x
assert not _callable(i)
assert _callable(f1)
assert _callable(f2)
def test_iter_next():
| 64 | 64 | 23 | 5 | 59 | Rockly/netaddr | netaddr/tests/core/test_compat.py | Python | test_iter_next | test_iter_next | 78 | 80 | 78 | 78 | 11e91f8a76af7c9c3114e76171b397abd757dec3 | bigcode/the-stack | train |
14c6be9c213d7ee370bcc0b6 | train | function | def test_compat_dict_operations():
d = { 'a' : 0, 'b' : 1, 'c' : 2 }
assert sorted(_dict_keys(d)) == ['a', 'b', 'c']
assert sorted(_dict_items(d)) == [('a', 0), ('b', 1), ('c', 2)]
| def test_compat_dict_operations():
| d = { 'a' : 0, 'b' : 1, 'c' : 2 }
assert sorted(_dict_keys(d)) == ['a', 'b', 'c']
assert sorted(_dict_items(d)) == [('a', 0), ('b', 1), ('c', 2)]
| abc'" == '%r' % str_8bit
def test_compat_string_and_int_detection():
assert _is_int(_sys_maxint)
assert not _is_str(_sys_maxint)
assert _is_str('')
assert _is_str(''.encode())
def test_compat_dict_operations():
| 64 | 64 | 77 | 7 | 57 | Rockly/netaddr | netaddr/tests/core/test_compat.py | Python | test_compat_dict_operations | test_compat_dict_operations | 39 | 42 | 39 | 39 | eb2b7a1c33a3a6392483604019cb8779bff0fe1f | bigcode/the-stack | train |
74815160fbccccb75b05d6a9 | train | function | def test_compat_string_and_int_detection():
assert _is_int(_sys_maxint)
assert not _is_str(_sys_maxint)
assert _is_str('')
assert _is_str(''.encode())
| def test_compat_string_and_int_detection():
| assert _is_int(_sys_maxint)
assert not _is_str(_sys_maxint)
assert _is_str('')
assert _is_str(''.encode())
| - 8 bit strings are just regular strings
str_8bit = _bytes_join(['a', 'b', 'c'])
assert str_8bit == 'abc'.encode()
assert "'abc'" == '%r' % str_8bit
def test_compat_string_and_int_detection():
| 64 | 64 | 45 | 9 | 54 | Rockly/netaddr | netaddr/tests/core/test_compat.py | Python | test_compat_string_and_int_detection | test_compat_string_and_int_detection | 32 | 36 | 32 | 32 | f172adc3d40b3d87414f5076d8bdf221bcf2ba51 | bigcode/the-stack | train |
84f8a5fe4e527203e77057d3 | train | function | @pytest.mark.skipif(sys.version_info < (3,), reason="requires python 3.x")
def test_compat_py3():
assert _is_str(''.encode())
# byte string join tests.
str_8bit = _bytes_join(['a'.encode(), 'b'.encode(), 'c'.encode()])
assert str_8bit == 'abc'.encode()
assert "b'abc'" == '%r' % str_8bit
| @pytest.mark.skipif(sys.version_info < (3,), reason="requires python 3.x")
def test_compat_py3():
| assert _is_str(''.encode())
# byte string join tests.
str_8bit = _bytes_join(['a'.encode(), 'b'.encode(), 'c'.encode()])
assert str_8bit == 'abc'.encode()
assert "b'abc'" == '%r' % str_8bit
|
from netaddr.compat import _dict_keys, _dict_items
from netaddr.compat import _bytes_join, _zip, _range
from netaddr.compat import _iter_range
@pytest.mark.skipif(sys.version_info < (3,), reason="requires python 3.x")
def test_compat_py3():
| 64 | 64 | 97 | 26 | 37 | Rockly/netaddr | netaddr/tests/core/test_compat.py | Python | test_compat_py3 | test_compat_py3 | 11 | 19 | 11 | 12 | 8e3d71fd7af00a77edde253db31991290d861e1b | bigcode/the-stack | train |
2c4103cda661e6c411e1f797 | train | function | def test_compat_zip():
l2 = _zip([0], [1])
assert hasattr(_zip(l2), 'pop')
assert l2 == [(0, 1)]
| def test_compat_zip():
| l2 = _zip([0], [1])
assert hasattr(_zip(l2), 'pop')
assert l2 == [(0, 1)]
| ' : 1, 'c' : 2 }
assert sorted(_dict_keys(d)) == ['a', 'b', 'c']
assert sorted(_dict_items(d)) == [('a', 0), ('b', 1), ('c', 2)]
def test_compat_zip():
| 63 | 64 | 40 | 6 | 57 | Rockly/netaddr | netaddr/tests/core/test_compat.py | Python | test_compat_zip | test_compat_zip | 45 | 48 | 45 | 45 | a4a6024a6cf836b2b84cb6dfa5290b353289467b | bigcode/the-stack | train |
fb0346b5c2d6264a6616cc94 | train | function | def get_av(hotel):
headers = { 'x-OTL-api-key': 'Your own API key for your account' }
params = (
('hotelCodes', hotel),
('rateCodes', 'IGCOR'),
('startDate', '2020-05-10T00:00:00Z'),
('endDate', '2020-06-29T00:00:00Z'),
('lengthOfStay', '1'),
)
r... | def get_av(hotel):
| headers = { 'x-OTL-api-key': 'Your own API key for your account' }
params = (
('hotelCodes', hotel),
('rateCodes', 'IGCOR'),
('startDate', '2020-05-10T00:00:00Z'),
('endDate', '2020-06-29T00:00:00Z'),
('lengthOfStay', '1'),
)
response = requests.g... | import requests
import pprint
import re
import time
def get_av(hotel):
| 18 | 64 | 210 | 6 | 11 | Divulgacheur/room_available | hotel.py | Python | get_av | get_av | 6 | 32 | 6 | 6 | 7c1af283fd26527ce53916f48336fd77bf60fa04 | bigcode/the-stack | train |
d64cd41ca9c13cab1afdcb9c | train | function | def get_hotels(state,city):
url = 'https://www.OTL.com/destinations/fr/fr/'+state+'/'+city+'-hotels'
print(url)
response = requests.get(url)
resultats = re.findall('name: "([^\n]*)",\n[^\n]*\n[^\n]*\n[^\n]*\n[^\n]*\n[^h]*hotelCode: "([^"]*)",', response.text, flags=re.S)
... | def get_hotels(state,city):
| url = 'https://www.OTL.com/destinations/fr/fr/'+state+'/'+city+'-hotels'
print(url)
response = requests.get(url)
resultats = re.findall('name: "([^\n]*)",\n[^\n]*\n[^\n]*\n[^\n]*\n[^\n]*\n[^h]*hotelCode: "([^"]*)",', response.text, flags=re.S)
total = str(len(resultats))
p... | 0]['windows']:
monnaie = response.json()['hotels'][0]['currencyCode']
print(i['startDate'],i['totalAmount'],monnaie )
time.sleep(2)
except:
print('pas dispo\n')
return response
def get_hotels(state,city):
| 64 | 64 | 138 | 9 | 54 | Divulgacheur/room_available | hotel.py | Python | get_hotels | get_hotels | 34 | 46 | 34 | 35 | bf4380d7f726d1bbd0e6d998e90fc36867f8727d | bigcode/the-stack | train |
003a54476ff183b8b187f5a9 | train | class | class PostDao:
def __init__(self, database=None):
self._db = database or db
def search(self) -> typing.List[DBPost]:
"""Search posts from database."""
# TODO: handle search filters, paging and total count
statement = sql.SQL(
"""
SELECT {fields}
... | class PostDao:
| def __init__(self, database=None):
self._db = database or db
def search(self) -> typing.List[DBPost]:
"""Search posts from database."""
# TODO: handle search filters, paging and total count
statement = sql.SQL(
"""
SELECT {fields}
FROM ... | import dataclasses
from psycopg2 import sql
import typing
from src.common.setup import db
from ..types.post import DBPost, Post
DB_POST_FIELDS: sql.SQL = sql.SQL(",").join(
sql.Identifier(f.name) for f in dataclasses.fields(DBPost)
)
class PostDao:
| 65 | 83 | 278 | 4 | 61 | TaitoUnited/full-stack-template | alternatives/server-flask/src/core/daos/post_dao.py | Python | PostDao | PostDao | 13 | 57 | 13 | 13 | 4c3ce9a2c8458f3e37a5071731c7ea79d8e1fd80 | bigcode/the-stack | train |
779dab8a280ded125a037520 | train | class | class myString:
def __init__(self, strcon):
self.stringContent = strcon
def __repr__(self):
return self.stringContent
def test(self):
print("prueba: " + self.stringContent)
def remove_prefix(self, myPrefix):
self.stringContent = self.stringContent[len(myPrefix):]
... | class myString:
| def __init__(self, strcon):
self.stringContent = strcon
def __repr__(self):
return self.stringContent
def test(self):
print("prueba: " + self.stringContent)
def remove_prefix(self, myPrefix):
self.stringContent = self.stringContent[len(myPrefix):]
return self
... | return input_string[: -len(suffix)]
return input_string
def remove_prefix2(input_string: str, prefix: str) -> str:
if prefix and input_string.startswith(prefix):
return input_string[len(prefix):]
return input_string
'''
# New Method using classes
class myString:
| 64 | 64 | 104 | 4 | 59 | artmen1516/Discounted-Udemy-Course-Enroller | CLI/prefixsuffix.py | Python | myString | myString | 18 | 34 | 18 | 18 | 0455c3e61f5c281e354a043cfa5be704441c9cf8 | bigcode/the-stack | train |
56e189a679150a278543b5b8 | train | class | class ZooLock(object):
_LOCK_NAME = '_lock_'
def __init__(self, client, path, contender_name=None):
"""
@type client KazooClient
"""
self.client = client
self.path = path
# some data is written to the node. this can be queries via
# get_contenders() to s... | class ZooLock(object):
| _LOCK_NAME = '_lock_'
def __init__(self, client, path, contender_name=None):
"""
@type client KazooClient
"""
self.client = client
self.path = path
# some data is written to the node. this can be queries via
# get_contenders() to see who is contending fo... | import threading
import uuid
from kazoo.retry import ForceRetryError
from zookeeper import NoNodeException
from kazoo.exceptions import CancelledError
class ZooLock(object):
| 37 | 256 | 1,001 | 5 | 31 | nimbusproject/kazoo | kazoo/recipe/lock.py | Python | ZooLock | ZooLock | 8 | 174 | 8 | 8 | 5d0b75a157e5e987b084082c3e7dab55a7162c87 | bigcode/the-stack | train |
682bca985ea06f3b3b3c786e | train | function | def check_binaries():
sh.ensure('convert')
| def check_binaries():
| sh.ensure('convert')
| import sh
def check_binaries():
| 8 | 64 | 11 | 5 | 2 | Kronika-Polskiej-Demosceny/dvp | imagemagick.py | Python | check_binaries | check_binaries | 3 | 4 | 3 | 3 | 329b458862955f1ffaaa34583bbca1b3c08870f1 | bigcode/the-stack | train |
8df2150ffd4428acdecd4bfc | train | function | def convert(from_path, to_path, filters=[]):
result = sh.execute(['convert', from_path, *filters, to_path])
| def convert(from_path, to_path, filters=[]):
| result = sh.execute(['convert', from_path, *filters, to_path])
| import sh
def check_binaries():
sh.ensure('convert')
def convert(from_path, to_path, filters=[]):
| 25 | 64 | 28 | 11 | 14 | Kronika-Polskiej-Demosceny/dvp | imagemagick.py | Python | convert | convert | 6 | 7 | 6 | 6 | 425996477791dba50ca39d611bc0b9a9ce53218b | bigcode/the-stack | train |
5521483f19d3a5a8529db177 | train | class | class UserCreateResponse(BaseModel):
user_token: str
| class UserCreateResponse(BaseModel):
| user_token: str
| get_user_by_token,
)
app = FastAPI()
# Sample APIs
@app.get("/")
async def root():
return {"message": "Hello World"}
# User APIs
class UserCreateRequest(BaseModel):
user_name: str
leader_card_id: int
class UserCreateResponse(BaseModel):
| 64 | 64 | 13 | 7 | 56 | honehaniwa/gameserver | app/api.py | Python | UserCreateResponse | UserCreateResponse | 37 | 38 | 37 | 37 | 4ef419b798d68a9271cc1a9ee2f0b0115eb5edc1 | bigcode/the-stack | train |
8ce276615d9cf9d4c00a6293 | train | class | class RoomJoinResponse(BaseModel):
join_room_result: JoinRoomResult
| class RoomJoinResponse(BaseModel):
| join_room_result: JoinRoomResult
| room_id: int
class RoomListRequest(BaseModel):
live_id: int
class RoomListResponse(BaseModel):
room_info_list: list[RoomInfo]
class RoomJoinRequest(BaseModel):
room_id: int
select_difficulty: LiveDifficulty
class RoomJoinResponse(BaseModel):
| 64 | 64 | 16 | 7 | 56 | honehaniwa/gameserver | app/api.py | Python | RoomJoinResponse | RoomJoinResponse | 63 | 64 | 63 | 63 | 00fc6405d2395998c13ba1a5fac771ee716a7e0c | bigcode/the-stack | train |
c07004805c2fd1ea831300cd | train | function | @app.post("/user/create", response_model=UserCreateResponse)
def user_create(req: UserCreateRequest):
"""新規ユーザー作成"""
token = model.create_user(req.user_name, req.leader_card_id)
return UserCreateResponse(user_token=token)
| @app.post("/user/create", response_model=UserCreateResponse)
def user_create(req: UserCreateRequest):
| """新規ユーザー作成"""
token = model.create_user(req.user_name, req.leader_card_id)
return UserCreateResponse(user_token=token)
| : JoinRoomResult
class RoomWaitRequest(BaseModel):
room_id: int
class RoomWaitResponse(BaseModel):
status: WaitRoomStatus
room_user_list: list[RoomUser]
@app.post("/user/create", response_model=UserCreateResponse)
def user_create(req: UserCreateRequest):
| 64 | 64 | 57 | 22 | 42 | honehaniwa/gameserver | app/api.py | Python | user_create | user_create | 76 | 80 | 76 | 77 | bc34b117ac83776a4ed2668fa0596eea9299036e | bigcode/the-stack | train |
7503b3b0fb74ac91ecc402f1 | train | class | class RoomListRequest(BaseModel):
live_id: int
| class RoomListRequest(BaseModel):
| live_id: int
| : str
leader_card_id: int
class UserCreateResponse(BaseModel):
user_token: str
class RoomCreateRequest(BaseModel):
live_id: int
select_difficulty: LiveDifficulty
class RoomCreateResponse(BaseModel):
room_id: int
class RoomListRequest(BaseModel):
| 64 | 64 | 13 | 7 | 56 | honehaniwa/gameserver | app/api.py | Python | RoomListRequest | RoomListRequest | 50 | 51 | 50 | 50 | 6fff7c506bf67bb1c8c38fe412fd81e1acc428e4 | bigcode/the-stack | train |
4ecd1ae052f60545f0b81ff6 | train | class | class RoomWaitRequest(BaseModel):
room_id: int
| class RoomWaitRequest(BaseModel):
| room_id: int
| : int
class RoomListResponse(BaseModel):
room_info_list: list[RoomInfo]
class RoomJoinRequest(BaseModel):
room_id: int
select_difficulty: LiveDifficulty
class RoomJoinResponse(BaseModel):
join_room_result: JoinRoomResult
class RoomWaitRequest(BaseModel):
| 64 | 64 | 13 | 7 | 56 | honehaniwa/gameserver | app/api.py | Python | RoomWaitRequest | RoomWaitRequest | 67 | 68 | 67 | 67 | 138cc12a116c838b5fbf0ad0652d4e23e301f948 | bigcode/the-stack | train |
81a4c4a1878813fa0e5f769e | train | function | @app.post("/room/list", response_model=RoomListResponse)
def room_list(req: RoomListRequest, token: str = Depends(get_auth_token)):
# print(req)
room_info_list = model.room_list(req.live_id)
return RoomListResponse(room_info_list=room_info_list)
| @app.post("/room/list", response_model=RoomListResponse)
def room_list(req: RoomListRequest, token: str = Depends(get_auth_token)):
# print(req)
| room_info_list = model.room_list(req.live_id)
return RoomListResponse(room_info_list=room_info_list)
| room_id = model.create_room(user, req.live_id, req.select_difficulty)
return RoomCreateResponse(room_id=room_id)
@app.post("/room/list", response_model=RoomListResponse)
def room_list(req: RoomListRequest, token: str = Depends(get_auth_token)):
# print(req)
| 64 | 64 | 61 | 36 | 28 | honehaniwa/gameserver | app/api.py | Python | room_list | room_list | 124 | 128 | 124 | 126 | f46696ba93eef6ab3a2e69f33228c3d6a666ed40 | bigcode/the-stack | train |
f7ea11aa13e77cf5348781ad | train | class | class RoomJoinRequest(BaseModel):
room_id: int
select_difficulty: LiveDifficulty
| class RoomJoinRequest(BaseModel):
| room_id: int
select_difficulty: LiveDifficulty
| live_id: int
select_difficulty: LiveDifficulty
class RoomCreateResponse(BaseModel):
room_id: int
class RoomListRequest(BaseModel):
live_id: int
class RoomListResponse(BaseModel):
room_info_list: list[RoomInfo]
class RoomJoinRequest(BaseModel):
| 64 | 64 | 21 | 7 | 57 | honehaniwa/gameserver | app/api.py | Python | RoomJoinRequest | RoomJoinRequest | 58 | 60 | 58 | 58 | 88bf361236f5548adb967ca77fdf3fd5421b4195 | bigcode/the-stack | train |
fc51997fce4e42776625640f | train | class | class RoomCreateResponse(BaseModel):
room_id: int
| class RoomCreateResponse(BaseModel):
| room_id: int
| User APIs
class UserCreateRequest(BaseModel):
user_name: str
leader_card_id: int
class UserCreateResponse(BaseModel):
user_token: str
class RoomCreateRequest(BaseModel):
live_id: int
select_difficulty: LiveDifficulty
class RoomCreateResponse(BaseModel):
| 64 | 64 | 13 | 7 | 56 | honehaniwa/gameserver | app/api.py | Python | RoomCreateResponse | RoomCreateResponse | 46 | 47 | 46 | 46 | c358a20fe2ffc47ca39e2fcf2773edeb52fbcb35 | bigcode/the-stack | train |
fa8e8d275da47899d34dcf6b | train | function | @app.post("/room/wait", response_model=RoomWaitResponse)
def room_join(req: RoomWaitRequest, token: str = Depends(get_auth_token)):
# print(req)
user = get_user_by_token(token)
if user is None:
return None
status, room_users = model.wait_room(user, req.room_id)
return RoomWaitResponse(status... | @app.post("/room/wait", response_model=RoomWaitResponse)
def room_join(req: RoomWaitRequest, token: str = Depends(get_auth_token)):
# print(req)
| user = get_user_by_token(token)
if user is None:
return None
status, room_users = model.wait_room(user, req.room_id)
return RoomWaitResponse(status=status, room_user_list=room_users)
| model.join_room(user, req.room_id, req.select_difficulty)
return RoomJoinResponse(join_room_result=join_room_result)
@app.post("/room/wait", response_model=RoomWaitResponse)
def room_join(req: RoomWaitRequest, token: str = Depends(get_auth_token)):
# print(req)
| 64 | 64 | 86 | 37 | 27 | honehaniwa/gameserver | app/api.py | Python | room_join | room_join | 141 | 148 | 141 | 143 | 67ed9abac0f4756b1c0942ff44007fc8bd16dc61 | bigcode/the-stack | train |
3a66d5ae07102adf2e9a1177 | train | class | class RoomCreateRequest(BaseModel):
live_id: int
select_difficulty: LiveDifficulty
| class RoomCreateRequest(BaseModel):
| live_id: int
select_difficulty: LiveDifficulty
| Sample APIs
@app.get("/")
async def root():
return {"message": "Hello World"}
# User APIs
class UserCreateRequest(BaseModel):
user_name: str
leader_card_id: int
class UserCreateResponse(BaseModel):
user_token: str
class RoomCreateRequest(BaseModel):
| 64 | 64 | 21 | 7 | 56 | honehaniwa/gameserver | app/api.py | Python | RoomCreateRequest | RoomCreateRequest | 41 | 43 | 41 | 41 | 0ac919d8ebb8bcd6927736c6449c48d208b51d48 | bigcode/the-stack | train |
983d8e39c346e906ad877383 | train | function | def get_auth_token(cred: HTTPAuthorizationCredentials = Depends(bearer)) -> str:
assert cred is not None
if not cred.credentials:
raise HTTPException(status_code=401, detail="invalid credential")
return cred.credentials
| def get_auth_token(cred: HTTPAuthorizationCredentials = Depends(bearer)) -> str:
| assert cred is not None
if not cred.credentials:
raise HTTPException(status_code=401, detail="invalid credential")
return cred.credentials
| UserCreateRequest):
"""新規ユーザー作成"""
token = model.create_user(req.user_name, req.leader_card_id)
return UserCreateResponse(user_token=token)
bearer = HTTPBearer()
def get_auth_token(cred: HTTPAuthorizationCredentials = Depends(bearer)) -> str:
| 64 | 64 | 51 | 19 | 45 | honehaniwa/gameserver | app/api.py | Python | get_auth_token | get_auth_token | 86 | 90 | 86 | 86 | 865f25a23b29b25a5e2c22cd9733ecb3cef8bf72 | bigcode/the-stack | train |
6a2cf6e5fef2a97bd372ada4 | train | function | @app.post("/room/create", response_model=RoomCreateResponse)
def room_create(req: RoomCreateRequest, token: str = Depends(get_auth_token)):
# print(req)
user = get_user_by_token(token)
if user is None:
return None
room_id = model.create_room(user, req.live_id, req.select_difficulty)
return R... | @app.post("/room/create", response_model=RoomCreateResponse)
def room_create(req: RoomCreateRequest, token: str = Depends(get_auth_token)):
# print(req)
| user = get_user_by_token(token)
if user is None:
return None
room_id = model.create_room(user, req.live_id, req.select_difficulty)
return RoomCreateResponse(room_id=room_id)
| user attributes"""
# print(req)
model.update_user(token, req.user_name, req.leader_card_id)
return {}
@app.post("/room/create", response_model=RoomCreateResponse)
def room_create(req: RoomCreateRequest, token: str = Depends(get_auth_token)):
# print(req)
| 63 | 64 | 84 | 36 | 27 | honehaniwa/gameserver | app/api.py | Python | room_create | room_create | 114 | 121 | 114 | 116 | ceef90aaff7278ea1d474db44fd8e181c7790955 | bigcode/the-stack | train |
a55f4664a3caa9bfdae66d25 | train | function | @app.post("/user/update", response_model=Empty)
def update(req: UserCreateRequest, token: str = Depends(get_auth_token)):
"""Update user attributes"""
# print(req)
model.update_user(token, req.user_name, req.leader_card_id)
return {}
| @app.post("/user/update", response_model=Empty)
def update(req: UserCreateRequest, token: str = Depends(get_auth_token)):
| """Update user attributes"""
# print(req)
model.update_user(token, req.user_name, req.leader_card_id)
return {}
| raise HTTPException(status_code=404)
# print(f"user_me({token=}, {user=})")
return user
class Empty(BaseModel):
pass
@app.post("/user/update", response_model=Empty)
def update(req: UserCreateRequest, token: str = Depends(get_auth_token)):
| 64 | 64 | 58 | 28 | 35 | honehaniwa/gameserver | app/api.py | Python | update | update | 106 | 111 | 106 | 107 | d9631a435a735461ebac5c4a1a519af12102fed3 | bigcode/the-stack | train |
81cca3116ea1eda8820729da | train | function | @app.get("/user/me", response_model=SafeUser)
def user_me(token: str = Depends(get_auth_token)):
user = model.get_user_by_token(token)
if user is None:
raise HTTPException(status_code=404)
# print(f"user_me({token=}, {user=})")
return user
| @app.get("/user/me", response_model=SafeUser)
def user_me(token: str = Depends(get_auth_token)):
| user = model.get_user_by_token(token)
if user is None:
raise HTTPException(status_code=404)
# print(f"user_me({token=}, {user=})")
return user
| Depends(bearer)) -> str:
assert cred is not None
if not cred.credentials:
raise HTTPException(status_code=401, detail="invalid credential")
return cred.credentials
@app.get("/user/me", response_model=SafeUser)
def user_me(token: str = Depends(get_auth_token)):
| 64 | 64 | 68 | 24 | 39 | honehaniwa/gameserver | app/api.py | Python | user_me | user_me | 93 | 99 | 93 | 94 | 057b4c83ccbae0d7af481939e4e98a4f6e066f95 | bigcode/the-stack | train |
2aa855ab9ebf63e47d711219 | train | class | class Empty(BaseModel):
pass
| class Empty(BaseModel):
| pass
| SafeUser)
def user_me(token: str = Depends(get_auth_token)):
user = model.get_user_by_token(token)
if user is None:
raise HTTPException(status_code=404)
# print(f"user_me({token=}, {user=})")
return user
class Empty(BaseModel):
| 64 | 64 | 8 | 5 | 58 | honehaniwa/gameserver | app/api.py | Python | Empty | Empty | 102 | 103 | 102 | 102 | fc683dedbcd0788f0753e579a0393b6db9951c98 | bigcode/the-stack | train |
50993ac4412e07e76604c8e5 | train | class | class RoomWaitResponse(BaseModel):
status: WaitRoomStatus
room_user_list: list[RoomUser]
| class RoomWaitResponse(BaseModel):
| status: WaitRoomStatus
room_user_list: list[RoomUser]
| _list: list[RoomInfo]
class RoomJoinRequest(BaseModel):
room_id: int
select_difficulty: LiveDifficulty
class RoomJoinResponse(BaseModel):
join_room_result: JoinRoomResult
class RoomWaitRequest(BaseModel):
room_id: int
class RoomWaitResponse(BaseModel):
| 64 | 64 | 24 | 7 | 56 | honehaniwa/gameserver | app/api.py | Python | RoomWaitResponse | RoomWaitResponse | 71 | 73 | 71 | 71 | cbc18caed0b2a084fb5cc97b212873f0cf9581fa | bigcode/the-stack | train |
1cdffc8b8e8e287402d89550 | train | function | @app.get("/")
async def root():
return {"message": "Hello World"}
| @app.get("/")
async def root():
| return {"message": "Hello World"}
|
from . import model
from .model import (
JoinRoomResult,
LiveDifficulty,
ResultUser,
RoomInfo,
RoomUser,
SafeUser,
WaitRoomStatus,
get_user_by_token,
)
app = FastAPI()
# Sample APIs
@app.get("/")
async def root():
| 64 | 64 | 16 | 7 | 56 | honehaniwa/gameserver | app/api.py | Python | root | root | 24 | 26 | 24 | 25 | bf861d53063d25c028e8360e31d4460cdb7e3de6 | bigcode/the-stack | train |
29d71e6bf3344155bebe40b4 | train | class | class RoomListResponse(BaseModel):
room_info_list: list[RoomInfo]
| class RoomListResponse(BaseModel):
| room_info_list: list[RoomInfo]
| Response(BaseModel):
user_token: str
class RoomCreateRequest(BaseModel):
live_id: int
select_difficulty: LiveDifficulty
class RoomCreateResponse(BaseModel):
room_id: int
class RoomListRequest(BaseModel):
live_id: int
class RoomListResponse(BaseModel):
| 64 | 64 | 17 | 7 | 56 | honehaniwa/gameserver | app/api.py | Python | RoomListResponse | RoomListResponse | 54 | 55 | 54 | 54 | 5fcbaf63542f3a21d341bbac8f03451afb020f2f | bigcode/the-stack | train |
3f8a8e79ce95e7578874ef39 | train | function | @app.post("/room/join", response_model=RoomJoinResponse)
def room_join(req: RoomJoinRequest, token: str = Depends(get_auth_token)):
# print(req)
user = get_user_by_token(token)
if user is None:
return None
join_room_result = model.join_room(user, req.room_id, req.select_difficulty)
return Ro... | @app.post("/room/join", response_model=RoomJoinResponse)
def room_join(req: RoomJoinRequest, token: str = Depends(get_auth_token)):
# print(req)
| user = get_user_by_token(token)
if user is None:
return None
join_room_result = model.join_room(user, req.room_id, req.select_difficulty)
return RoomJoinResponse(join_room_result=join_room_result)
| (req)
room_info_list = model.room_list(req.live_id)
return RoomListResponse(room_info_list=room_info_list)
@app.post("/room/join", response_model=RoomJoinResponse)
def room_join(req: RoomJoinRequest, token: str = Depends(get_auth_token)):
# print(req)
| 64 | 64 | 88 | 37 | 27 | honehaniwa/gameserver | app/api.py | Python | room_join | room_join | 131 | 138 | 131 | 133 | a22bee87afc9a4d5881eb39155f0d7269c796f96 | bigcode/the-stack | train |
a7eaa1a0e9e804de8593bb56 | train | class | class UserCreateRequest(BaseModel):
user_name: str
leader_card_id: int
| class UserCreateRequest(BaseModel):
| user_name: str
leader_card_id: int
| ResultUser,
RoomInfo,
RoomUser,
SafeUser,
WaitRoomStatus,
get_user_by_token,
)
app = FastAPI()
# Sample APIs
@app.get("/")
async def root():
return {"message": "Hello World"}
# User APIs
class UserCreateRequest(BaseModel):
| 64 | 64 | 20 | 7 | 56 | honehaniwa/gameserver | app/api.py | Python | UserCreateRequest | UserCreateRequest | 32 | 34 | 32 | 32 | f777ef1f9240caa2e2597212680d7b52209f4b45 | bigcode/the-stack | train |
de9c2fe41346172d56bed04c | train | function | @pytest.mark.parametrize('app_class', [App, ASyncApp])
def test_jwt_anon_allowed(app_class) -> None:
secret = 'jwt-secret'
routes = [
Route('/anonymous-allowed', 'GET', anon_allowed),
]
components = [JWT({'JWT_SECRET': secret})]
app = app_class(routes=routes, components=components)
clie... | @pytest.mark.parametrize('app_class', [App, ASyncApp])
def test_jwt_anon_allowed(app_class) -> None:
| secret = 'jwt-secret'
routes = [
Route('/anonymous-allowed', 'GET', anon_allowed),
]
components = [JWT({'JWT_SECRET': secret})]
app = app_class(routes=routes, components=components)
client = TestClient(app)
response = client.get('/anonymous-allowed')
assert response.status_code... | encoded_jwt = jwt.encode(payload, secret, algorithm='HS512').decode(encoding='UTF-8')
response = client.get('/auth-required', headers={
'Authorization': 'Bearer {token}'.format(token=encoded_jwt),
})
assert response.status_code == 401
# empty payload causes auth to fail
encoded_jwt = jwt.e... | 158 | 158 | 529 | 27 | 130 | jgirardet/apistar-jwt | tests/test_apistar_jwt.py | Python | test_jwt_anon_allowed | test_jwt_anon_allowed | 92 | 153 | 92 | 93 | d3b77b10c1887a757f88339b36f7fc7bb8ef5b3f | bigcode/the-stack | train |
9e30bc791d75cba50fc83d81 | train | function | @anonymous_allowed
def anon_allowed(request: http.Request, user: JWTUser):
if user:
return user.__dict__
return None
| @anonymous_allowed
def anon_allowed(request: http.Request, user: JWTUser):
| if user:
return user.__dict__
return None
| istar_jwt.token import JWT, JWTUser
from apistar_jwt.decorators import authentication_required, anonymous_allowed
@authentication_required
def auth_required(request: http.Request, user: JWTUser):
return user.__dict__
@anonymous_allowed
def anon_allowed(request: http.Request, user: JWTUser):
| 63 | 64 | 31 | 17 | 46 | jgirardet/apistar-jwt | tests/test_apistar_jwt.py | Python | anon_allowed | anon_allowed | 20 | 24 | 20 | 21 | 3efd3eb7a90d8b1245a3c14b0867c9539ba495eb | bigcode/the-stack | train |
4bd97e7e19e428745b1c9203 | train | function | @pytest.mark.parametrize('app_class', [App, ASyncApp])
def test_jwt_audience_claim(app_class) -> None:
secret = 'jwt-secret'
routes = [
Route('/auth-required', 'GET', auth_required),
]
components = [
JWT({
'JWT_SECRET': secret,
'JWT_OPTIONS': {
'... | @pytest.mark.parametrize('app_class', [App, ASyncApp])
def test_jwt_audience_claim(app_class) -> None:
| secret = 'jwt-secret'
routes = [
Route('/auth-required', 'GET', auth_required),
]
components = [
JWT({
'JWT_SECRET': secret,
'JWT_OPTIONS': {
'audience': 'urn:foo',
}
})
]
app = app_class(routes=routes, components=com... | _jwt = jwt.encode(payload, secret, algorithm='HS256').decode(encoding='UTF-8')
response = client.get('/auth-required', headers={
'Authorization': 'Bearer {token}'.format(token=encoded_jwt),
})
assert response.status_code == 401
# no iss claim included in jwt
del payload['iss']
encoded_j... | 164 | 164 | 548 | 27 | 136 | jgirardet/apistar-jwt | tests/test_apistar_jwt.py | Python | test_jwt_audience_claim | test_jwt_audience_claim | 202 | 261 | 202 | 203 | ad22a835e71344dc1aba1a550d3253547974e058 | bigcode/the-stack | train |
2bd31c321dbad3921f298a5f | train | function | def test_configuration_error() -> None:
with pytest.raises(exceptions.ConfigurationError):
JWT()
| def test_configuration_error() -> None:
| with pytest.raises(exceptions.ConfigurationError):
JWT()
|
@authentication_required
def auth_required(request: http.Request, user: JWTUser):
return user.__dict__
@anonymous_allowed
def anon_allowed(request: http.Request, user: JWTUser):
if user:
return user.__dict__
return None
def test_configuration_error() -> None:
| 64 | 64 | 20 | 8 | 55 | jgirardet/apistar-jwt | tests/test_apistar_jwt.py | Python | test_configuration_error | test_configuration_error | 27 | 29 | 27 | 27 | e7c1114d412e44950aa56f5708c9dadf708bee63 | bigcode/the-stack | train |
f98625c58c49dce92ba1aa64 | train | function | @pytest.mark.parametrize("app_class", [App, ASyncApp])
def test_jwt_white_list(app_class) -> None:
secret = "jwt-secret"
class IsAuthenticated:
def on_request(self, jwt_user: JWTUser) -> None:
""" just force authentication for each request"""
components = [JWT({"JWT_SECRET": secret})]... | @pytest.mark.parametrize("app_class", [App, ASyncApp])
def test_jwt_white_list(app_class) -> None:
| secret = "jwt-secret"
class IsAuthenticated:
def on_request(self, jwt_user: JWTUser) -> None:
""" just force authentication for each request"""
components = [JWT({"JWT_SECRET": secret})]
app = app_class(routes=[], components=components, event_hooks=[IsAuthenticated()])
client... | response = client.get('/auth-required', headers={
'Authorization': 'Bearer {token}'.format(token=encoded_jwt),
})
assert response.status_code == 200
@pytest.mark.parametrize("app_class", [App, ASyncApp])
def test_jwt_white_list(app_class) -> None:
| 64 | 64 | 190 | 26 | 37 | jgirardet/apistar-jwt | tests/test_apistar_jwt.py | Python | test_jwt_white_list | test_jwt_white_list | 310 | 333 | 310 | 311 | f05c7125dfbc76b2418262bde5546121626e9cd7 | bigcode/the-stack | train |
a2d8a56ed06284ffccea9541 | train | function | @authentication_required
def auth_required(request: http.Request, user: JWTUser):
return user.__dict__
| @authentication_required
def auth_required(request: http.Request, user: JWTUser):
| return user.__dict__
| http
from apistar.test import TestClient
from apistar.server.app import App, ASyncApp
from apistar_jwt.token import JWT, JWTUser
from apistar_jwt.decorators import authentication_required, anonymous_allowed
@authentication_required
def auth_required(request: http.Request, user: JWTUser):
| 64 | 64 | 23 | 17 | 46 | jgirardet/apistar-jwt | tests/test_apistar_jwt.py | Python | auth_required | auth_required | 15 | 17 | 15 | 16 | 8475d62b2d121cc6547a6a693acca2eeb0102db6 | bigcode/the-stack | train |
f48e1dcb568bb950e89aa9f4 | train | function | @pytest.mark.parametrize('app_class', [App, ASyncApp])
def test_jwt_issuer_claim(app_class) -> None:
secret = 'jwt-secret'
routes = [
Route('/auth-required', 'GET', auth_required),
]
components = [
JWT({
'JWT_SECRET': secret,
'JWT_OPTIONS': {
'is... | @pytest.mark.parametrize('app_class', [App, ASyncApp])
def test_jwt_issuer_claim(app_class) -> None:
| secret = 'jwt-secret'
routes = [
Route('/auth-required', 'GET', auth_required),
]
components = [
JWT({
'JWT_SECRET': secret,
'JWT_OPTIONS': {
'issuer': 'urn:foo',
}
})
]
app = app_class(routes=routes, components=compo... | assert response.status_code == 401
# empty payload causes auth to fail
encoded_jwt = jwt.encode({}, secret, algorithm='HS256').decode(encoding='UTF-8')
response = client.get('/anonymous-allowed', headers={
'Authorization': 'Bearer {token}'.format(token=encoded_jwt),
})
assert response.s... | 107 | 107 | 358 | 27 | 79 | jgirardet/apistar-jwt | tests/test_apistar_jwt.py | Python | test_jwt_issuer_claim | test_jwt_issuer_claim | 156 | 199 | 156 | 157 | 68be259990bd259eb1eeb80eccbb8445285ef40e | bigcode/the-stack | train |
94686da96b15533f4935c3b9 | train | function | @pytest.mark.parametrize('app_class', [App, ASyncApp])
def test_jwt_leeway_claim(app_class) -> None:
secret = 'jwt-secret'
routes = [
Route('/auth-required', 'GET', auth_required),
]
components = [
JWT({
'JWT_SECRET': secret,
'JWT_OPTIONS': {
'le... | @pytest.mark.parametrize('app_class', [App, ASyncApp])
def test_jwt_leeway_claim(app_class) -> None:
| secret = 'jwt-secret'
routes = [
Route('/auth-required', 'GET', auth_required),
]
components = [
JWT({
'JWT_SECRET': secret,
'JWT_OPTIONS': {
'leeway': 3,
}
})
]
app = app_class(routes=routes, components=components)
... | })
assert response.status_code == 401
# no aud claim included in jwt
del payload['aud']
encoded_jwt = jwt.encode(payload, secret, algorithm='HS256').decode(encoding='UTF-8')
response = client.get('/auth-required', headers={
'Authorization': 'Bearer {token}'.format(token=encoded_jwt),
}... | 114 | 114 | 380 | 27 | 86 | jgirardet/apistar-jwt | tests/test_apistar_jwt.py | Python | test_jwt_leeway_claim | test_jwt_leeway_claim | 264 | 307 | 264 | 265 | 6389c2b044724d6ac9304afb8349eaca280cce79 | bigcode/the-stack | train |
48043280c553f48bcd77bcee | train | function | @pytest.mark.parametrize('app_class', [App, ASyncApp])
def test_jwt_auth_required(app_class) -> None:
secret = 'jwt-secret'
routes = [
Route('/auth-required', 'GET', auth_required),
]
components = [JWT({'JWT_SECRET': secret})]
app = app_class(routes=routes, components=components)
client... | @pytest.mark.parametrize('app_class', [App, ASyncApp])
def test_jwt_auth_required(app_class) -> None:
| secret = 'jwt-secret'
routes = [
Route('/auth-required', 'GET', auth_required),
]
components = [JWT({'JWT_SECRET': secret})]
app = app_class(routes=routes, components=components)
client = TestClient(app)
response = client.get('/auth-required')
assert response.status_code == 401... | istar.test import TestClient
from apistar.server.app import App, ASyncApp
from apistar_jwt.token import JWT, JWTUser
from apistar_jwt.decorators import authentication_required, anonymous_allowed
@authentication_required
def auth_required(request: http.Request, user: JWTUser):
return user.__dict__
@anonymous_all... | 144 | 144 | 481 | 26 | 118 | jgirardet/apistar-jwt | tests/test_apistar_jwt.py | Python | test_jwt_auth_required | test_jwt_auth_required | 32 | 89 | 32 | 33 | 18cc8a35f662ca99d2f160cfad67a2e1542b22ce | bigcode/the-stack | train |
ea01f689580e6431c749eb8b | train | function | def move_axis(data, label, new_position):
"""Moves a named axis to a new position in an xarray DataArray object.
Args:
data (DataArray): Object with named axes
label (str): Name of the axis to move
new_position (int): Numerical new position of the axis.
Negat... | def move_axis(data, label, new_position):
| """Moves a named axis to a new position in an xarray DataArray object.
Args:
data (DataArray): Object with named axes
label (str): Name of the axis to move
new_position (int): Numerical new position of the axis.
Negative indices are accepted.
Returns:
... | = list(axes_labels)
# check if the required labels are present
if required_labels is not None:
for label in required_labels:
assert label in labels, f'Required label missing: {label}'
return xr.DataArray(data, dims=labels)
def move_axis(data, label, new_position):
| 68 | 68 | 228 | 10 | 58 | dianna-ai/dianna | dianna/utils/misc.py | Python | move_axis | move_axis | 61 | 87 | 61 | 61 | c8f0db5d8c56c45be1bb9d3eaf0153f107745674 | bigcode/the-stack | train |
3c8cdf7d85ab4ead3eefb8b5 | train | function | def get_kwargs_applicable_to_function(function, kwargs):
"""
Returns a dict that is the subset of `kwargs` for which the keys are
keyword arguments of `function`. Note that if `function` has a `**kwargs`
argument, this function should not be necessary (provided the function
handles `**kwargs` robust... | def get_kwargs_applicable_to_function(function, kwargs):
| """
Returns a dict that is the subset of `kwargs` for which the keys are
keyword arguments of `function`. Note that if `function` has a `**kwargs`
argument, this function should not be necessary (provided the function
handles `**kwargs` robustly).
"""
return {key: value for key, value in kwa... | runner = model_or_function
else:
def runner(input_data):
return model_or_function(preprocess_function(input_data))
else:
raise TypeError("model_or_function argument must be string (path to model) or function")
return runner
def get_kwargs_applicable_to_function(funct... | 64 | 64 | 101 | 11 | 52 | dianna-ai/dianna | dianna/utils/misc.py | Python | get_kwargs_applicable_to_function | get_kwargs_applicable_to_function | 26 | 34 | 26 | 26 | b90fe8fc8523c51c7b1a37f359f44f322a4eb9fa | bigcode/the-stack | train |
71c69f3b0438dc9a954cce0c | train | function | def get_function(model_or_function, preprocess_function=None):
"""Converts input to callable function.
Input can be either model path or function.
If input is a function, the function is returned unchanged.
Any keyword arguments are given to the ModelRunner class if the input is a model path.
... | def get_function(model_or_function, preprocess_function=None):
| """Converts input to callable function.
Input can be either model path or function.
If input is a function, the function is returned unchanged.
Any keyword arguments are given to the ModelRunner class if the input is a model path.
"""
if isinstance(model_or_function, str):
runn... |
import xarray as xr
from dianna.utils.onnx_runner import SimpleModelRunner
def get_function(model_or_function, preprocess_function=None):
| 30 | 64 | 158 | 11 | 18 | dianna-ai/dianna | dianna/utils/misc.py | Python | get_function | get_function | 6 | 23 | 6 | 6 | 4abd19c2eabd17abd56ad8fcf6fefbde9cc5bdcf | bigcode/the-stack | train |
16f14edf3c761f751b8ea23b | train | function | def to_xarray(data, axes_labels, required_labels=None):
"""Converts numpy data and axes labels to an xarray object
"""
if isinstance(axes_labels, dict):
# key = axis index, value = label
# not all axes have to be present in the input, but we need to provide
# a name for each axis
... | def to_xarray(data, axes_labels, required_labels=None):
| """Converts numpy data and axes labels to an xarray object
"""
if isinstance(axes_labels, dict):
# key = axis index, value = label
# not all axes have to be present in the input, but we need to provide
# a name for each axis
# first ensure negative indices are converted to po... | `
argument, this function should not be necessary (provided the function
handles `**kwargs` robustly).
"""
return {key: value for key, value in kwargs.items()
if key in function.__code__.co_varnames}
def to_xarray(data, axes_labels, required_labels=None):
| 65 | 65 | 217 | 13 | 52 | dianna-ai/dianna | dianna/utils/misc.py | Python | to_xarray | to_xarray | 37 | 58 | 37 | 37 | 90ced7e95b8812ab50dbc9377ea70314120dbe0a | bigcode/the-stack | train |
881e40a1052a34fcf6b80505 | train | function | def myApp():
if(not os.path.isdir('ResultFile')):
os.mkdir('ResultFile')
if( not os.path.exists('XMLFiles')):
xmlEpmtyFolder = input('''Arquivos nao existentes na pasta XMLFiles!
\n por favor revise e execute o programa novamente!
\n PRESSIONE UMA TECLA PARA ENCERRAR!... | def myApp():
| if(not os.path.isdir('ResultFile')):
os.mkdir('ResultFile')
if( not os.path.exists('XMLFiles')):
xmlEpmtyFolder = input('''Arquivos nao existentes na pasta XMLFiles!
\n por favor revise e execute o programa novamente!
\n PRESSIONE UMA TECLA PARA ENCERRAR! ''')
... | import os
import os.path
from xmlFinder import XMLEncoder, openResultFilesFolder
import xml.etree.ElementTree as ET
def myApp():
| 34 | 111 | 370 | 4 | 29 | ValdeirBarbosa/XMLfinderTag | main.py | Python | myApp | myApp | 12 | 43 | 12 | 12 | 6fd3ee00b8b6f518d7be175c985ec97a7df005a8 | bigcode/the-stack | train |
7e8306acecf112cdbd531a70 | train | class | class FHIRUnitTestRenderer(FHIRRenderer):
""" Write unit tests.
"""
def render(self):
if self.spec.unit_tests is None:
return
# render all unit test collections
for coll in self.spec.unit_tests:
data = {
'info': self.spec.info,
... | class FHIRUnitTestRenderer(FHIRRenderer):
| """ Write unit tests.
"""
def render(self):
if self.spec.unit_tests is None:
return
# render all unit test collections
for coll in self.spec.unit_tests:
data = {
'info': self.spec.info,
'class': coll.klass,
... | = {
'info': self.spec.info,
'systems': sorted(systems, key=lambda x: x.name) if self.settings.sort_resources else systems,
}
target_name = self.settings.tpl_codesystems_target_name
target_path = os.path.join(self.settings.tpl_resource_target, target_name)
self.do... | 89 | 89 | 298 | 10 | 79 | hsolbrig/fhir-parser | fhirparser/fhirrenderer.py | Python | FHIRUnitTestRenderer | FHIRUnitTestRenderer | 188 | 221 | 188 | 188 | 4fdcae05feba2db6cb3c7de2b3d039037fd78f55 | bigcode/the-stack | train |
c2c31c3a793363f3c2374359 | train | class | class FHIRDependencyRenderer(FHIRRenderer):
""" Puts down dependencies for each of the FHIR resources. Per resource
class will grab all class/resource names that are needed for its
properties and add them to the "imports" key. Will also check
classes/resources may appear in references and list those in... | class FHIRDependencyRenderer(FHIRRenderer):
| """ Puts down dependencies for each of the FHIR resources. Per resource
class will grab all class/resource names that are needed for its
properties and add them to the "imports" key. Will also check
classes/resources may appear in references and list those in the
"references" key.
"""
def r... |
data = {
'info': self.spec.info,
'classes': sorted(classes, key=lambda x: x.name) if self.settings.sort_resources else classes,
}
self.do_render(data, self.settings.tpl_factory_source, self.settings.tpl_factory_target)
class FHIRDependencyRenderer(FHIRRenderer):
| 64 | 64 | 182 | 9 | 55 | hsolbrig/fhir-parser | fhirparser/fhirrenderer.py | Python | FHIRDependencyRenderer | FHIRDependencyRenderer | 150 | 167 | 150 | 150 | 03132194ba46c6177da78259d45b34335fe56865 | bigcode/the-stack | train |
b909040b9b6c51ccbb001a03 | train | class | class FHIRRenderer(object):
""" Superclass for all renderer implementations.
"""
def __init__(self, spec, settings):
self.spec = spec
self.settings = settings
self.clean_settings()
self.jinjaenv = Environment(loader=FileSystemLoader(self.settings.tpl_base))
self.... | class FHIRRenderer(object):
| """ Superclass for all renderer implementations.
"""
def __init__(self, spec, settings):
self.spec = spec
self.settings = settings
self.clean_settings()
self.jinjaenv = Environment(loader=FileSystemLoader(self.settings.tpl_base))
self.jinjaenv.filters['wordwrap']... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import re
import shutil
import textwrap
from typing import Optional
from jinja2 import Environment, FileSystemLoader, TemplateNotFound
from jinja2.filters import environmentfilter
from fhirparser.logger import logger
class FHIRRenderer(object):
| 73 | 156 | 520 | 6 | 66 | hsolbrig/fhir-parser | fhirparser/fhirrenderer.py | Python | FHIRRenderer | FHIRRenderer | 17 | 75 | 17 | 17 | d9eaa1e484e1fea52f9b46e905f18b9396a17ff6 | bigcode/the-stack | train |
8baa27983d4b8ac55a54a2bb | train | class | class FHIRValueSetRenderer(FHIRRenderer):
""" Write ValueSet and CodeSystem contained in the FHIR spec.
"""
def render(self):
if not self.settings.tpl_codesystems_source:
logger.info("Not rendering value sets and code systems since `tpl_codesystems_source` is not set")
return... | class FHIRValueSetRenderer(FHIRRenderer):
| """ Write ValueSet and CodeSystem contained in the FHIR spec.
"""
def render(self):
if not self.settings.tpl_codesystems_source:
logger.info("Not rendering value sets and code systems since `tpl_codesystems_source` is not set")
return
systems = [v for k,v in ... | 'references': profile.referenced_classes(),
})
data['resources'] = sorted(resources, key=lambda x: x['name']) if self.settings.sort_resources else resources
self.do_render(data, self.settings.tpl_dependencies_source, self.settings.tpl_dependencies_target)
class FHIRValueSetRe... | 64 | 64 | 163 | 10 | 54 | hsolbrig/fhir-parser | fhirparser/fhirrenderer.py | Python | FHIRValueSetRenderer | FHIRValueSetRenderer | 170 | 185 | 170 | 170 | 853734df07154e116a3a8742905c213a89aa8772 | bigcode/the-stack | train |
88dea218f40b69b5451828d4 | train | function | @environmentfilter
def do_wordwrap(environment, s, width=79, break_long_words=True, wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not... | @environmentfilter
def do_wordwrap(environment, s, width=79, break_long_words=True, wrapstring=None):
| """
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`.
"""
if not s:
return s
... | wrap (inherited from `textwrap`) in that it
# ignores existing linebreaks when applying the wrap:
# https://github.com/mitsuhiko/jinja2/issues/175
# Here's the workaround:
@environmentfilter
def do_wordwrap(environment, s, width=79, break_long_words=True, wrapstring=None):
| 70 | 70 | 235 | 25 | 45 | hsolbrig/fhir-parser | fhirparser/fhirrenderer.py | Python | do_wordwrap | do_wordwrap | 228 | 254 | 228 | 229 | 84276028d3a6a2bc31eeae6a995e97602516962e | bigcode/the-stack | train |
08b4991a5cc37a20f01c5f55 | train | class | class FHIRStructureDefinitionRenderer(FHIRRenderer):
""" Write classes for a profile/structure-definition.
"""
def copy_files(self, target_dir):
""" Copy base resources to the target location, according to settings.
"""
for origpath, module, contains in self.settings.manual_profi... | class FHIRStructureDefinitionRenderer(FHIRRenderer):
| """ Write classes for a profile/structure-definition.
"""
def copy_files(self, target_dir):
""" Copy base resources to the target location, according to settings.
"""
for origpath, module, contains in self.settings.manual_profiles:
if not origpath:
con... | _name))
except TemplateNotFound as e:
logger.error("Template \"{}\" not found in «{}», cannot render"
.format(template_name, self.settings.tpl_base))
return
if not target_path:
raise Exception("No target filepath provided")
dirpath = o... | 146 | 147 | 490 | 10 | 136 | hsolbrig/fhir-parser | fhirparser/fhirrenderer.py | Python | FHIRStructureDefinitionRenderer | FHIRStructureDefinitionRenderer | 79 | 132 | 79 | 79 | 821b8df3489b429dc2737b952790ef92fe83266e | bigcode/the-stack | train |
0b0a52516317bfd3120f646a | train | class | class FHIRFactoryRenderer(FHIRRenderer):
""" Write factories for FHIR classes.
"""
def render(self):
classes = []
for profile in self.spec.writable_profiles():
classes.extend(profile.writable_classes())
data = {
'info': self.spec.info,
'cl... | class FHIRFactoryRenderer(FHIRRenderer):
| """ Write factories for FHIR classes.
"""
def render(self):
classes = []
for profile in self.spec.writable_profiles():
classes.extend(profile.writable_classes())
data = {
'info': self.spec.info,
'classes': sorted(classes, key=lambda x: x.n... | _source
target_name = self.settings.tpl_resource_target_ptrn.format(ptrn)
target_path = os.path.join(self.settings.tpl_resource_target, target_name)
self.do_render(data, source_path, target_path)
self.copy_files(self.settings.tpl_resource_target)
class FHIRFactoryRenderer(FH... | 64 | 64 | 102 | 9 | 55 | hsolbrig/fhir-parser | fhirparser/fhirrenderer.py | Python | FHIRFactoryRenderer | FHIRFactoryRenderer | 135 | 147 | 135 | 135 | b3a95fd6a5bb84dd4e5d813a7cb6f32243c1c00e | bigcode/the-stack | train |
ad1a6152ce691a32758f448b | train | class | @dataclass
class Bar:
class Meta:
name = "bar"
| @dataclass
class Bar:
| class Meta:
name = "bar"
| from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Bar:
| 20 | 64 | 16 | 6 | 13 | tefra/xsdata-w3c-tests | output/models/ms_data/model_groups/mg_z003_xsd/mg_z003.py | Python | Bar | Bar | 5 | 8 | 5 | 6 | f07590aae9db92cb23a9d3c346b4ad363794eb2d | bigcode/the-stack | train |
1722a51eaaf64e5af0c73ce7 | train | class | @dataclass
class Doc(Foo):
class Meta:
name = "doc"
| @dataclass
class Doc(Foo):
| class Meta:
name = "doc"
| = "bar"
@dataclass
class Foo(Bar):
class Meta:
name = "foo"
e1: Optional[object] = field(
default=None,
metadata={
"type": "Element",
"namespace": "",
}
)
@dataclass
class Doc(Foo):
| 64 | 64 | 18 | 8 | 56 | tefra/xsdata-w3c-tests | output/models/ms_data/model_groups/mg_z003_xsd/mg_z003.py | Python | Doc | Doc | 25 | 28 | 25 | 26 | 1e858c861225aa8a1eb40ce7b8e89d14f565ff0d | bigcode/the-stack | train |
29d0aa28c117a64a140f9783 | train | class | @dataclass
class Foo(Bar):
class Meta:
name = "foo"
e1: Optional[object] = field(
default=None,
metadata={
"type": "Element",
"namespace": "",
}
)
| @dataclass
class Foo(Bar):
| class Meta:
name = "foo"
e1: Optional[object] = field(
default=None,
metadata={
"type": "Element",
"namespace": "",
}
)
| from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Bar:
class Meta:
name = "bar"
@dataclass
class Foo(Bar):
| 38 | 64 | 52 | 8 | 30 | tefra/xsdata-w3c-tests | output/models/ms_data/model_groups/mg_z003_xsd/mg_z003.py | Python | Foo | Foo | 11 | 22 | 11 | 12 | 4fea8efc11916bd435720d05631b318ae32bb394 | bigcode/the-stack | train |
ade737eeaefe8cde5f277215 | train | class | class GameClient(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.game = Game()
self.client = None
def Loop(self):
if self.game.isPhase2():
if not self.client: self.client = Client(self.host, self.port, self.game)
i... | class GameClient(object):
| def __init__(self, host, port):
self.host = host
self.port = port
self.game = Game()
self.client = None
def Loop(self):
if self.game.isPhase2():
if not self.client: self.client = Client(self.host, self.port, self.game)
if self.client: self.client... | . (I'm doing it for simplicity's sake)
from _thread import *
from game import Game
from scene.game_scene import GameScene
from scene.draw_scene import DrawScene
from scene.lobby_scene import LobbyScene
from scene.end_game_scene import EndGameScene
class GameClient(object):
| 64 | 64 | 90 | 5 | 58 | InnovAnon-Inc/py-bingo-client | client/client.py | Python | GameClient | GameClient | 22 | 32 | 22 | 22 | 5c4426def28c60b81b5c5f1cf753b082102d9420 | bigcode/the-stack | train |
7d35c2ce65689781744efe8d | train | class | class Client(ConnectionListener):
def __init__(self, host, port, game):
self.Connect((host, port))
print("Chat client started")
print("Ctrl-C to exit")
# get a nickname from the user before starting
name = str(game.active_scene.name)
print("Enter your nickname: %s" % ... | class Client(ConnectionListener):
| def __init__(self, host, port, game):
self.Connect((host, port))
print("Chat client started")
print("Ctrl-C to exit")
# get a nickname from the user before starting
name = str(game.active_scene.name)
print("Enter your nickname: %s" % name)
#connection.Send({"a... | # Don't ever do this - it's slow and ugly. (I'm doing it for simplicity's sake)
from _thread import *
from game import Game
from scene.game_scene import GameScene
from scene.draw_scene import DrawScene
from scene.lobby_scene import LobbyScene
from scene.end_game_scene import EndGameScene
cl... | 164 | 164 | 548 | 5 | 159 | InnovAnon-Inc/py-bingo-client | client/client.py | Python | Client | Client | 34 | 101 | 34 | 34 | 886c20a16dd526b08b8f818f839c6a5c503f6033 | bigcode/the-stack | train |
a902fb8e6849bc029342cd04 | train | class | class Isotope(object):
def __init__(self, master):
self.master = master
self.logger = logging.getLogger(__name__)
self.settings = master.settings
self.process_parameters = master.process_parameters
self.charge = master.charge
self.data_subset = None
self.fract... | class Isotope(object):
| def __init__(self, master):
self.master = master
self.logger = logging.getLogger(__name__)
self.settings = master.settings
self.process_parameters = master.process_parameters
self.charge = master.charge
self.data_subset = None
self.fraction = None
self... | import logging
import numpy as np
from bisect import bisect_left, bisect_right
from scipy.interpolate import InterpolatedUnivariateSpline
from sys import maxsize
class Isotope(object):
| 42 | 143 | 478 | 5 | 36 | Tarskin/MassyTools | MassyTools/bin/isotope.py | Python | Isotope | Isotope | 8 | 56 | 8 | 8 | 9262501f38cbc9785213c7773b5adceed32beaf2 | bigcode/the-stack | train |
57ec7586484843c750617e79 | train | function | @receiver(post_save, sender=OrderDiscount)
def receive_order_discount_save(sender, instance, **kwargs):
# Record the amount of discount against the appropriate offers
# and vouchers
discount = instance
if discount.voucher:
discount.voucher.total_discount += discount.amount
discou... | @receiver(post_save, sender=OrderDiscount)
def receive_order_discount_save(sender, instance, **kwargs):
# Record the amount of discount against the appropriate offers
# and vouchers
| discount = instance
if discount.voucher:
discount.voucher.total_discount += discount.amount
discount.voucher.save()
discount.offer.total_discount += discount.amount
discount.offer.save()
| ._default_manager.get(pk=voucher_id)
voucher.num_basket_additions += 1
voucher.save()
@receiver(post_save, sender=OrderDiscount)
def receive_order_discount_save(sender, instance, **kwargs):
# Record the amount of discount against the appropriate offers
# and vouchers
| 64 | 64 | 81 | 40 | 24 | owad/django-oscar | oscar/apps/offer/receivers.py | Python | receive_order_discount_save | receive_order_discount_save | 16 | 25 | 16 | 19 | dc47093cad5c3d28d74ffd7565f6c41cb8f7c01e | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.