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
bfdc09730347e7b9172a8007
train
class
class StateSaverRNNTest(test.TestCase): def setUp(self): self._seed = 23489 np.random.seed(self._seed) def _testScope(self, factory, prefix="prefix", use_outer_scope=True): with self.test_session(use_gpu=True, graph=ops_lib.Graph()): if use_outer_scope: with variable_scope.variable_scope...
class StateSaverRNNTest(test.TestCase):
def setUp(self): self._seed = 23489 np.random.seed(self._seed) def _testScope(self, factory, prefix="prefix", use_outer_scope=True): with self.test_session(use_gpu=True, graph=ops_lib.Graph()): if use_outer_scope: with variable_scope.variable_scope(prefix) as scope: factory(scop...
_dict={ single_input_using_dim: input_value }) state_sav_v = sess.run( state_sav, feed_dict={ single_input_using_dim: input_value }) self.assertAllEqual(np.hstack(state_static_v), np.hstack(state_dynamic_v)) self.assertAllEqual(np.hstack(state_...
130
130
434
10
120
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
StateSaverRNNTest
StateSaverRNNTest
1,774
1,827
1,774
1,775
83fb2e7ea59be041f9b023c1fe3c431011e11c39
bigcode/the-stack
train
13e531221407ad1af930c106
train
class
class RawRNNTest(test.TestCase): def setUp(self): self._seed = 23489 np.random.seed(self._seed) def _testRawRNN(self, max_time): with self.test_session(graph=ops_lib.Graph()) as sess: batch_size = 16 input_depth = 4 num_units = 3 inputs = array_ops.placeholder( shape...
class RawRNNTest(test.TestCase):
def setUp(self): self._seed = 23489 np.random.seed(self._seed) def _testRawRNN(self, max_time): with self.test_session(graph=ops_lib.Graph()) as sess: batch_size = 16 input_depth = 4 num_units = 3 inputs = array_ops.placeholder( shape=(max_time, batch_size, input_dept...
v for v in all_vars if v.name.startswith(prefix + "/")] tf_logging.info("RNN with scope: %s (%s)" % (prefix, "scope" if use_outer_scope else "str")) for v in scope_vars: tf_logging.info(v.name) self.assertEqual(len(scope_vars), len(all_vars)) def testDynamicScope(self)...
256
256
2,865
9
247
mohammadzainabbas/tensorflow
tensorflow/contrib/rnn/python/kernel_tests/core_rnn_test.py
Python
RawRNNTest
RawRNNTest
1,911
2,210
1,911
1,912
4e99d0b6ed9546f23df286d2451c7509b1230a78
bigcode/the-stack
train
66398c38be3ac3658ab4980f
train
class
class EncoderDecoderWPointerTest(unittest.TestCase): def setUp(self): self.output_dir = next(tempfile._get_candidate_names()) def tearDown(self): if os.path.exists(self.output_dir): shutil.rmtree(self.output_dir) if os.path.exists("runs"): shutil.rmtree("runs") ...
class EncoderDecoderWPointerTest(unittest.TestCase):
def setUp(self): self.output_dir = next(tempfile._get_candidate_names()) def tearDown(self): if os.path.exists(self.output_dir): shutil.rmtree(self.output_dir) if os.path.exists("runs"): shutil.rmtree("runs") def test_shape_on_random_data(self): set_...
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
197
256
4,697
10
187
nikhilgoel1997/new-semantic-parsing
tests/test_model.py
Python
EncoderDecoderWPointerTest
EncoderDecoderWPointerTest
31
620
31
31
a7f9b4482505c9a2f58425993ba5310a68bd1420
bigcode/the-stack
train
c75ae12a729eac10803e4049
train
class
class ScriptAddress2Test(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 3 self.setup_clean_chain = False def setup_network(self): self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, [])) self.nodes.append(start_nod...
class ScriptAddress2Test(BitcoinTestFramework):
def __init__(self): super().__init__() self.num_nodes = 3 self.setup_clean_chain = False def setup_network(self): self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, [])) self.nodes.append(start_node(1, self.options.tmpdir, [])) self.node...
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test new Condorcoin multisig prefix functionality. # from test_framework.test_framework import Bitco...
92
256
1,067
10
81
pcjdev/condorcoin
qa/rpc-tests/test_script_address2.py
Python
ScriptAddress2Test
ScriptAddress2Test
14
95
14
14
87b596d3aecaf292712cc1e8c9236060fc42306f
bigcode/the-stack
train
43c55c42d6aa5c42b73b9bc0
train
class
class FairnessModule(PerformanceModule): """ Fairness module for Credo AI. Handles any metric that can be calculated on a set of ground truth labels and predictions, e.g., binary classification, multiclass classification, regression. This module takes in a set of metrics and provides functionalit...
class FairnessModule(PerformanceModule):
""" Fairness module for Credo AI. Handles any metric that can be calculated on a set of ground truth labels and predictions, e.g., binary classification, multiclass classification, regression. This module takes in a set of metrics and provides functionality to: - calculate the metrics - c...
from dis import dis from absl import logging from credoai.utils.common import to_array, NotRunError, ValidationError from credoai.metrics import Metric, find_metrics, MODEL_METRIC_CATEGORIES from credoai.modules.credo_module import CredoModule from fairlearn.metrics import MetricFrame from scipy.stats import norm from...
110
256
1,799
8
101
credo-ai/credoai_lens
credoai/modules/model_modules/fairness_base.py
Python
FairnessModule
FairnessModule
13
250
13
13
3b8533cd5944d83f0afc445177fc914065eee0e1
bigcode/the-stack
train
77adaae2a9a388f2dbeffac7
train
function
def test_to_obj(): parameter_dict = { "type": "boolean", "key": "supportDocumentWrite", "value": "false", } parameter = GTMParameter(parameter_dict) assert parameter_dict == parameter.to_obj() parameter_dict = { "type": "list", "key": "fieldsToSet", ...
def test_to_obj():
parameter_dict = { "type": "boolean", "key": "supportDocumentWrite", "value": "false", } parameter = GTMParameter(parameter_dict) assert parameter_dict == parameter.to_obj() parameter_dict = { "type": "list", "key": "fieldsToSet", "list": [{"type": ...
assert parameter.value == parameter_dict.get("value") assert parameter.key == parameter_dict.get("key") assert parameter.type == parameter_dict.get("type") assert len(parameter.list) == len(parameter_dict.get("list")) assert isinstance(parameter.list[0], GTMParameter) def test_to_obj():
64
64
120
5
59
trakken/gtm_manager
tests/test_parameter.py
Python
test_to_obj
test_to_obj
38
58
38
39
590e87163911eb7fd69313cd9fac467dbbe45220
bigcode/the-stack
train
1f58601f564de9b02f651c31
train
function
def test_init(): parameter_dict = { "type": "boolean", "key": "supportDocumentWrite", "value": "false", } parameter = GTMParameter(parameter_dict) assert parameter.map == parameter_dict.get("map") assert parameter.value == parameter_dict.get("value") assert parameter.ke...
def test_init():
parameter_dict = { "type": "boolean", "key": "supportDocumentWrite", "value": "false", } parameter = GTMParameter(parameter_dict) assert parameter.map == parameter_dict.get("map") assert parameter.value == parameter_dict.get("value") assert parameter.key == parameter_di...
# pylint: disable=missing-docstring from gtm_manager.parameter import GTMParameter def test_init():
23
67
226
4
18
trakken/gtm_manager
tests/test_parameter.py
Python
test_init
test_init
5
35
5
5
3df8f86ae3a62214477d7eea7b367b25933d4260
bigcode/the-stack
train
46da99723f189901449f20e6
train
function
def test_copy(): parameter_dict = { "type": "boolean", "key": "supportDocumentWrite", "value": "false", } parameter = GTMParameter(parameter_dict) assert parameter_dict == parameter.copy().to_obj() parameter_dict = { "type": "list", "key": "fieldsToSet", ...
def test_copy():
parameter_dict = { "type": "boolean", "key": "supportDocumentWrite", "value": "false", } parameter = GTMParameter(parameter_dict) assert parameter_dict == parameter.copy().to_obj() parameter_dict = { "type": "list", "key": "fieldsToSet", "list": [{"...
type": "list", "key": "fieldsToSet", "list": [{"type": "map", "key": "anonymizeIp", "value": "true"}], } parameter = GTMParameter(parameter_dict) assert parameter_dict == parameter.to_obj() def test_copy():
64
64
123
4
60
trakken/gtm_manager
tests/test_parameter.py
Python
test_copy
test_copy
61
80
61
61
4b17b63d16d8c74406dee723183c241bc52801b2
bigcode/the-stack
train
bea4f0e9215fa0c10d3d5518
train
function
async def test_call_context_user_not_exist(hass): """Check we don't allow deleted users to do things.""" with pytest.raises(exceptions.UnknownUser) as err: await service.entity_service_call( hass, [], Mock(), ha.ServiceCall( "test_domain", ...
async def test_call_context_user_not_exist(hass):
"""Check we don't allow deleted users to do things.""" with pytest.raises(exceptions.UnknownUser) as err: await service.entity_service_call( hass, [], Mock(), ha.ServiceCall( "test_domain", "test_service", co...
_service", {"entity_id": "all"}), required_features=[1], ) assert len(mock_entities) == 2 # Called once because only one of the entities had the required features assert test_service_mock.call_count == 1 async def test_call_context_user_not_exist(hass):
64
64
92
11
52
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_call_context_user_not_exist
test_call_context_user_not_exist
303
317
303
303
2ce94e048eb0abd10e879762cd25dc70d97cc58d
bigcode/the-stack
train
2dabede6ba6644a13f0037f1
train
function
async def test_call_with_omit_entity_id( hass, mock_service_platform_call, mock_entities, caplog ): """Check we only target allowed entities if targetting all.""" await service.entity_service_call( hass, [Mock(entities=mock_entities)], Mock(), ha.ServiceCall("test_domain", "t...
async def test_call_with_omit_entity_id( hass, mock_service_platform_call, mock_entities, caplog ):
"""Check we only target allowed entities if targetting all.""" await service.entity_service_call( hass, [Mock(entities=mock_entities)], Mock(), ha.ServiceCall("test_domain", "test_service"), ) assert len(mock_service_platform_call.mock_calls) == 1 entities = mock_ser...
_entities["light.living_room"], ] assert ( "Not passing an entity ID to a service to target " "all entities is deprecated" ) not in caplog.text async def test_call_with_omit_entity_id( hass, mock_service_platform_call, mock_entities, caplog ):
64
64
157
25
38
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_call_with_omit_entity_id
test_call_with_omit_entity_id
460
479
460
462
4a362e2312224fcd0295845124e55f1c13b0363f
bigcode/the-stack
train
cd68005cba980fc47cb9a8f2
train
function
async def test_call_context_target_specific_no_auth( hass, mock_service_platform_call, mock_entities ): """Check targeting specific entities without auth.""" with pytest.raises(exceptions.Unauthorized) as err: with patch( "homeassistant.auth.AuthManager.async_get_user", retur...
async def test_call_context_target_specific_no_auth( hass, mock_service_platform_call, mock_entities ):
"""Check targeting specific entities without auth.""" with pytest.raises(exceptions.Unauthorized) as err: with patch( "homeassistant.auth.AuthManager.async_get_user", return_value=mock_coro(Mock(permissions=PolicyPermissions({}, None))), ): await service.entit...
assert len(mock_service_platform_call.mock_calls) == 1 entities = mock_service_platform_call.mock_calls[0][1][2] assert entities == [mock_entities["light.kitchen"]] async def test_call_context_target_specific_no_auth( hass, mock_service_platform_call, mock_entities ):
64
64
163
22
41
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_call_context_target_specific_no_auth
test_call_context_target_specific_no_auth
377
399
377
379
cc3705b4e3ab034eaadb79874262f6364b32da82
bigcode/the-stack
train
0207073676b61daf0c76d082
train
function
async def test_call_no_context_target_all( hass, mock_service_platform_call, mock_entities ): """Check we target all if no user context given.""" await service.entity_service_call( hass, [Mock(entities=mock_entities)], Mock(), ha.ServiceCall("test_domain", "test_service"), ...
async def test_call_no_context_target_all( hass, mock_service_platform_call, mock_entities ):
"""Check we target all if no user context given.""" await service.entity_service_call( hass, [Mock(entities=mock_entities)], Mock(), ha.ServiceCall("test_domain", "test_service"), ) assert len(mock_service_platform_call.mock_calls) == 1 entities = mock_service_platfo...
light.kitchen"}, context=ha.Context(user_id="mock-id"), ), ) assert err.value.context.user_id == "mock-id" assert err.value.entity_id == "light.kitchen" async def test_call_no_context_target_all( hass, mock_service_platform_call, mock_entities ):
64
64
108
21
43
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_call_no_context_target_all
test_call_no_context_target_all
402
415
402
404
2003b17dbb5f8dc8cc62708c8228e14aed727da7
bigcode/the-stack
train
7043399880be12d82d0ca7e7
train
function
async def test_extract_entity_ids(hass): """Test extract_entity_ids method.""" hass.states.async_set("light.Bowl", STATE_ON) hass.states.async_set("light.Ceiling", STATE_OFF) hass.states.async_set("light.Kitchen", STATE_OFF) await hass.components.group.Group.async_create_group( hass, "test"...
async def test_extract_entity_ids(hass):
"""Test extract_entity_ids method.""" hass.states.async_set("light.Bowl", STATE_ON) hass.states.async_set("light.Ceiling", STATE_OFF) hass.states.async_set("light.Kitchen", STATE_OFF) await hass.components.group.Group.async_create_group( hass, "test", ["light.Ceiling", "light.Kitchen"] ...
assert 1 == mock_log.call_count service.call_from_config(self.hass, {}) assert 2 == mock_log.call_count service.call_from_config(self.hass, {"service": "invalid"}) assert 3 == mock_log.call_count async def test_extract_entity_ids(hass):
64
64
204
9
54
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_extract_entity_ids
test_extract_entity_ids
181
203
181
181
8ac67db6c48cbe2deb6eabf81774692bcddf5a06
bigcode/the-stack
train
b9fa2d00bc219c800e3a4cfd
train
class
class TestServiceHelpers(unittest.TestCase): """Test the Home Assistant service helpers.""" def setUp(self): # pylint: disable=invalid-name """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.calls = mock_service(self.hass, "test_domain", "t...
class TestServiceHelpers(unittest.TestCase):
"""Test the Home Assistant service helpers.""" def setUp(self): # pylint: disable=invalid-name """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.calls = mock_service(self.hass, "test_domain", "test_service") def tearDown(self): # pyl...
from homeassistant.auth.permissions import PolicyPermissions from homeassistant.helpers import ( service, template, device_registry as dev_reg, entity_registry as ent_reg, ) from tests.common import ( get_test_home_assistant, mock_service, mock_coro, mock_registry, mock_device_regis...
253
253
846
8
244
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
TestServiceHelpers
TestServiceHelpers
66
178
66
66
77e7220967ae36fcaf582a30f065ae2284b61ae0
bigcode/the-stack
train
db13b449007571528b34adab
train
function
async def test_domain_control_admin(hass, hass_admin_user, mock_entities): """Test domain verification in a service call with an admin user.""" calls = [] async def mock_service_log(call): """Define a protected service.""" calls.append(call) with patch( "homeassistant.helpers.e...
async def test_domain_control_admin(hass, hass_admin_user, mock_entities):
"""Test domain verification in a service call with an admin user.""" calls = [] async def mock_service_log(call): """Define a protected service.""" calls.append(call) with patch( "homeassistant.helpers.entity_registry.async_get_registry", return_value=mock_coro(Mock(ent...
with pytest.raises(exceptions.Unauthorized): await hass.services.async_call( "test_domain", "test_service", {}, blocking=True, context=ha.Context(user_id=hass_read_only_user.id), ) async def test_domain_control_admi...
64
64
180
16
48
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_domain_control_admin
test_domain_control_admin
621
649
621
621
2dde31e3fe621e2ac686da49c8d35aefaa77c4ac
bigcode/the-stack
train
91b90e054f70fea5a8a051dc
train
function
async def test_call_context_target_specific( hass, mock_service_platform_call, mock_entities ): """Check targeting specific entities.""" with patch( "homeassistant.auth.AuthManager.async_get_user", return_value=mock_coro( Mock( permissions=PolicyPermissions( ...
async def test_call_context_target_specific( hass, mock_service_platform_call, mock_entities ):
"""Check targeting specific entities.""" with patch( "homeassistant.auth.AuthManager.async_get_user", return_value=mock_coro( Mock( permissions=PolicyPermissions( {"entities": {"entity_ids": {"light.kitchen": True}}}, None ) ...
) assert len(mock_service_platform_call.mock_calls) == 1 entities = mock_service_platform_call.mock_calls[0][1][2] assert entities == [mock_entities["light.kitchen"]] async def test_call_context_target_specific( hass, mock_service_platform_call, mock_entities ):
64
64
190
20
43
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_call_context_target_specific
test_call_context_target_specific
346
374
346
348
e49b6458da98b9014a44149619d893123a6088de
bigcode/the-stack
train
50f830b59d4cc548c7b610b7
train
function
async def test_register_admin_service(hass, hass_read_only_user, hass_admin_user): """Test the register admin service.""" calls = [] async def mock_service(call): calls.append(call) hass.helpers.service.async_register_admin_service("test", "test", mock_service) hass.helpers.service.async_r...
async def test_register_admin_service(hass, hass_read_only_user, hass_admin_user):
"""Test the register admin service.""" calls = [] async def mock_service(call): calls.append(call) hass.helpers.service.async_register_admin_service("test", "test", mock_service) hass.helpers.service.async_register_admin_service( "test", "test2", mock_service, ...
ha.ServiceCall("test_domain", "test_service"), ) assert len(mock_service_platform_call.mock_calls) == 1 entities = mock_service_platform_call.mock_calls[0][1][2] assert entities == [ mock_entities["light.kitchen"], mock_entities["light.living_room"], ] assert ( "Not pas...
114
114
382
18
95
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_register_admin_service
test_register_admin_service
482
545
482
482
e71d3f51a905781a5d1eed4187d0e42704e39215
bigcode/the-stack
train
eeeba6f417bc759eaacecebb
train
function
async def test_domain_control_unknown(hass, mock_entities): """Test domain verification in a service call with an unknown user.""" calls = [] async def mock_service_log(call): """Define a protected service.""" calls.append(call) with patch( "homeassistant.helpers.entity_registr...
async def test_domain_control_unknown(hass, mock_entities):
"""Test domain verification in a service call with an unknown user.""" calls = [] async def mock_service_log(call): """Define a protected service.""" calls.append(call) with patch( "homeassistant.helpers.entity_registry.async_get_registry", return_value=mock_coro(Mock(e...
an unknown user.""" calls = [] def mock_service_log(call): """Define a protected service.""" calls.append(call) with pytest.raises(exceptions.HomeAssistantError): hass.helpers.service.verify_domain_control("test_domain")(mock_service_log) async def test_domain_control_unknown(hass...
64
64
184
12
52
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_domain_control_unknown
test_domain_control_unknown
560
588
560
560
432e478b054b60f1eb2ccadd37de6c31a84da777
bigcode/the-stack
train
3f1d52aec93a2da79717b518
train
function
@pytest.fixture def mock_entities(): """Return mock entities in an ordered dict.""" kitchen = Mock( entity_id="light.kitchen", available=True, should_poll=False, supported_features=1, platform="test_domain", ) living_room = Mock( entity_id="light.living_ro...
@pytest.fixture def mock_entities():
"""Return mock entities in an ordered dict.""" kitchen = Mock( entity_id="light.kitchen", available=True, should_poll=False, supported_features=1, platform="test_domain", ) living_room = Mock( entity_id="light.living_room", available=True, ...
_registry, ) @pytest.fixture def mock_service_platform_call(): """Mock service platform call.""" with patch( "homeassistant.helpers.service._handle_service_platform_call", side_effect=lambda *args: mock_coro(), ) as mock_call: yield mock_call @pytest.fixture def mock_entities():
64
64
123
7
56
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
mock_entities
mock_entities
43
63
43
44
ab86a607d5b490c36317e732d7dc095bbb7a5db3
bigcode/the-stack
train
6d3b32974a9774edd5893b36
train
function
async def test_domain_control_not_async(hass, mock_entities): """Test domain verification in a service call with an unknown user.""" calls = [] def mock_service_log(call): """Define a protected service.""" calls.append(call) with pytest.raises(exceptions.HomeAssistantError): ha...
async def test_domain_control_not_async(hass, mock_entities):
"""Test domain verification in a service call with an unknown user.""" calls = [] def mock_service_log(call): """Define a protected service.""" calls.append(call) with pytest.raises(exceptions.HomeAssistantError): hass.helpers.service.verify_domain_control("test_domain")(mock_s...
", {"required": True}, blocking=True, context=ha.Context(user_id=hass_admin_user.id), ) assert len(calls) == 1 assert calls[0].context.user_id == hass_admin_user.id async def test_domain_control_not_async(hass, mock_entities):
64
64
75
13
50
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_domain_control_not_async
test_domain_control_not_async
548
557
548
548
2dd076b4907a031d67435f421e25f8fb0f098ef5
bigcode/the-stack
train
f5ea808a2c0e8dab2c439ef1
train
function
async def test_call_no_context_target_specific( hass, mock_service_platform_call, mock_entities ): """Check we can target specified entities.""" await service.entity_service_call( hass, [Mock(entities=mock_entities)], Mock(), ha.ServiceCall( "test_domain", ...
async def test_call_no_context_target_specific( hass, mock_service_platform_call, mock_entities ):
"""Check we can target specified entities.""" await service.entity_service_call( hass, [Mock(entities=mock_entities)], Mock(), ha.ServiceCall( "test_domain", "test_service", {"entity_id": ["light.kitchen", "light.non-existing"]}, ), ...
_service"), ) assert len(mock_service_platform_call.mock_calls) == 1 entities = mock_service_platform_call.mock_calls[0][1][2] assert entities == list(mock_entities.values()) async def test_call_no_context_target_specific( hass, mock_service_platform_call, mock_entities ):
64
64
130
21
43
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_call_no_context_target_specific
test_call_no_context_target_specific
418
435
418
420
9ac677cc8be8cdcbf6315aa090746e5fbab5bfae
bigcode/the-stack
train
41140abbc29cfdd2917c1ff2
train
function
async def test_domain_control_no_user(hass, mock_entities): """Test domain verification in a service call with no user.""" calls = [] async def mock_service_log(call): """Define a protected service.""" calls.append(call) with patch( "homeassistant.helpers.entity_registry.async_...
async def test_domain_control_no_user(hass, mock_entities):
"""Test domain verification in a service call with no user.""" calls = [] async def mock_service_log(call): """Define a protected service.""" calls.append(call) with patch( "homeassistant.helpers.entity_registry.async_get_registry", return_value=mock_coro(Mock(entities=...
) await hass.services.async_call( "test_domain", "test_service", {}, blocking=True, context=ha.Context(user_id=hass_admin_user.id), ) assert len(calls) == 1 async def test_domain_control_no_user(hass, mock_entities):
64
64
172
13
50
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_domain_control_no_user
test_domain_control_no_user
652
680
652
652
422cfdff7ee8c43d301b88f7571c6d9cbe1bcb4a
bigcode/the-stack
train
56d44038628ab0c20a765865
train
function
async def test_extract_entity_ids_from_area(hass): """Test extract_entity_ids method with areas.""" hass.states.async_set("light.Bowl", STATE_ON) hass.states.async_set("light.Ceiling", STATE_OFF) hass.states.async_set("light.Kitchen", STATE_OFF) device_in_area = dev_reg.DeviceEntry(area_id="test-ar...
async def test_extract_entity_ids_from_area(hass):
"""Test extract_entity_ids method with areas.""" hass.states.async_set("light.Bowl", STATE_ON) hass.states.async_set("light.Ceiling", STATE_OFF) hass.states.async_set("light.Kitchen", STATE_OFF) device_in_area = dev_reg.DeviceEntry(area_id="test-area") device_no_area = dev_reg.DeviceEntry() ...
("light", "turn_on", {ATTR_ENTITY_ID: "light.Bowl"}) assert {"light.bowl"} == await service.async_extract_entity_ids(hass, call) call = ha.ServiceCall("light", "turn_on", {ATTR_ENTITY_ID: "group.test"}) assert {"light.ceiling", "light.kitchen"} == await service.async_extract_entity_ids( hass, cal...
123
123
410
11
112
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_extract_entity_ids_from_area
test_extract_entity_ids_from_area
206
261
206
206
84313a7968bc46b261fd7264f71197c5ab70154c
bigcode/the-stack
train
ea913bcb3c24eb14e04f2e0e
train
function
@asyncio.coroutine def test_async_get_all_descriptions(hass): """Test async_get_all_descriptions.""" group = hass.components.group group_config = {group.DOMAIN: {}} yield from async_setup_component(hass, group.DOMAIN, group_config) descriptions = yield from service.async_get_all_descriptions(hass) ...
@asyncio.coroutine def test_async_get_all_descriptions(hass):
"""Test async_get_all_descriptions.""" group = hass.components.group group_config = {group.DOMAIN: {}} yield from async_setup_component(hass, group.DOMAIN, group_config) descriptions = yield from service.async_get_all_descriptions(hass) assert len(descriptions) == 1 assert "description" in...
light", "turn_on", {"area_id": ["test-area", "diff-area"]}) assert { "light.in_area", "light.diff_area", } == await service.async_extract_entity_ids(hass, call) @asyncio.coroutine def test_async_get_all_descriptions(hass):
64
64
195
16
48
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_async_get_all_descriptions
test_async_get_all_descriptions
264
285
264
265
804c50e9c4598b918609d6b75930a2da51359a68
bigcode/the-stack
train
89db0f5498ebd5e691d1625f
train
function
async def test_domain_control_unauthorized(hass, hass_read_only_user, mock_entities): """Test domain verification in a service call with an unauthorized user.""" calls = [] async def mock_service_log(call): """Define a protected service.""" calls.append(call) with patch( "homea...
async def test_domain_control_unauthorized(hass, hass_read_only_user, mock_entities):
"""Test domain verification in a service call with an unauthorized user.""" calls = [] async def mock_service_log(call): """Define a protected service.""" calls.append(call) with patch( "homeassistant.helpers.entity_registry.async_get_registry", return_value=mock_coro(M...
hass.services.async_call( "test_domain", "test_service", {}, blocking=True, context=ha.Context(user_id="fake_user_id"), ) assert len(calls) == 0 async def test_domain_control_unauthorized(hass, hass_read_only_user, mock...
64
64
184
19
44
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_domain_control_unauthorized
test_domain_control_unauthorized
591
618
591
591
a6a8628589d3a972e0cbab821cb702b63e4d5958
bigcode/the-stack
train
5e539f93744e16e3dca8bfa9
train
function
async def test_call_context_target_all(hass, mock_service_platform_call, mock_entities): """Check we only target allowed entities if targetting all.""" with patch( "homeassistant.auth.AuthManager.async_get_user", return_value=mock_coro( Mock( permissions=PolicyPermiss...
async def test_call_context_target_all(hass, mock_service_platform_call, mock_entities):
"""Check we only target allowed entities if targetting all.""" with patch( "homeassistant.auth.AuthManager.async_get_user", return_value=mock_coro( Mock( permissions=PolicyPermissions( {"entities": {"entity_ids": {"light.kitchen": True}}}, None ...
[], Mock(), ha.ServiceCall( "test_domain", "test_service", context=ha.Context(user_id="non-existing"), ), ) assert err.value.context.user_id == "non-existing" async def test_call_context_target_all(hass, mock_service_platf...
64
64
182
18
46
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_call_context_target_all
test_call_context_target_all
320
343
320
320
882ebf406b2c2f0a3f97cc5daf5073d823a82a32
bigcode/the-stack
train
862574f2d8356509fbbe6133
train
function
@pytest.fixture def mock_service_platform_call(): """Mock service platform call.""" with patch( "homeassistant.helpers.service._handle_service_platform_call", side_effect=lambda *args: mock_coro(), ) as mock_call: yield mock_call
@pytest.fixture def mock_service_platform_call():
"""Mock service platform call.""" with patch( "homeassistant.helpers.service._handle_service_platform_call", side_effect=lambda *args: mock_coro(), ) as mock_call: yield mock_call
.helpers import ( service, template, device_registry as dev_reg, entity_registry as ent_reg, ) from tests.common import ( get_test_home_assistant, mock_service, mock_coro, mock_registry, mock_device_registry, ) @pytest.fixture def mock_service_platform_call():
64
64
54
9
55
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
mock_service_platform_call
mock_service_platform_call
33
40
33
34
63c6f2557e6768ea9229f8fa86c3f42f3c4cbfa0
bigcode/the-stack
train
f6943b76c34e64422827a95d
train
function
async def test_call_with_match_all( hass, mock_service_platform_call, mock_entities, caplog ): """Check we only target allowed entities if targetting all.""" await service.entity_service_call( hass, [Mock(entities=mock_entities)], Mock(), ha.ServiceCall("test_domain", "test_s...
async def test_call_with_match_all( hass, mock_service_platform_call, mock_entities, caplog ):
"""Check we only target allowed entities if targetting all.""" await service.entity_service_call( hass, [Mock(entities=mock_entities)], Mock(), ha.ServiceCall("test_domain", "test_service", {"entity_id": "all"}), ) assert len(mock_service_platform_call.mock_calls) == 1 ...
len(mock_service_platform_call.mock_calls) == 1 entities = mock_service_platform_call.mock_calls[0][1][2] assert entities == [mock_entities["light.kitchen"]] async def test_call_with_match_all( hass, mock_service_platform_call, mock_entities, caplog ):
64
64
163
23
40
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_call_with_match_all
test_call_with_match_all
438
457
438
440
278ee3ab1d4e11a5b96b659039ebb9aa7d33b65f
bigcode/the-stack
train
e3ea38a77017b5fdcf57170d
train
function
async def test_call_with_required_features(hass, mock_entities): """Test service calls invoked only if entity has required feautres.""" test_service_mock = Mock(return_value=mock_coro()) await service.entity_service_call( hass, [Mock(entities=mock_entities)], test_service_mock, ...
async def test_call_with_required_features(hass, mock_entities):
"""Test service calls invoked only if entity has required feautres.""" test_service_mock = Mock(return_value=mock_coro()) await service.entity_service_call( hass, [Mock(entities=mock_entities)], test_service_mock, ha.ServiceCall("test_domain", "test_service", {"entity_id": "a...
from service.async_get_all_descriptions(hass) assert len(descriptions) == 2 assert "description" in descriptions[logger.DOMAIN]["set_level"] assert "fields" in descriptions[logger.DOMAIN]["set_level"] async def test_call_with_required_features(hass, mock_entities):
63
64
128
13
50
m2hofi94/home-assistant
tests/helpers/test_service.py
Python
test_call_with_required_features
test_call_with_required_features
288
300
288
288
e7ddc6eec09d2fd8de358620faeb76fd6c225565
bigcode/the-stack
train
16759d680850cbed262b4ce4
train
function
def test_pdb_set_trace(): """Using pdb.set_trace from a doctest. You can use pdb.set_trace from a doctest. To do so, you must retrieve the set_trace function from the pdb module at the time you use it. The doctest module changes sys.stdout so that it can capture program output. It also temporari...
def test_pdb_set_trace():
"""Using pdb.set_trace from a doctest. You can use pdb.set_trace from a doctest. To do so, you must retrieve the set_trace function from the pdb module at the time you use it. The doctest module changes sys.stdout so that it can capture program output. It also temporarily replaces pdb.set_trace ...
.SampleClass.a_classmethod' >>> print(doctest.testsource(test.test_doctest, name)) print(SampleClass.a_classmethod(10)) # Expected: ## 12 print(SampleClass(0).a_classmethod(10)) # Expected: ## 12 <BLANKLINE> """ def test_debug(): r""" Create a docstring that we want to debug: >>> ...
256
256
1,109
7
249
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_pdb_set_trace
test_pdb_set_trace
1,615
1,745
1,615
1,615
b306d6fb3507a082827d3b79a2acbf15522b4917
bigcode/the-stack
train
2f8f460d9a167b1685431500
train
class
class test_DocTestRunner: def basics(): r""" Unit tests for the `DocTestRunner` class. DocTestRunner is used to run DocTest test cases, and to accumulate statistics. Here's a simple DocTest case we can use: >>> def f(x): ... ''' ... >>> x = 12 ... >>> print(x) ... 12 ... ...
class test_DocTestRunner:
def basics(): r""" Unit tests for the `DocTestRunner` class. DocTestRunner is used to run DocTest test cases, and to accumulate statistics. Here's a simple DocTest case we can use: >>> def f(x): ... ''' ... >>> x = 12 ... >>> print(x) ... 12 ... >>> x//2 ... 6 ...
_examples` method returns just the examples: >>> for piece in parser.get_examples(s): ... print((piece.source, piece.want, piece.lineno)) ('x, y = 2, 3 # no output expected\n', '', 1) ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2) ('x+y\n', '5\n', 9) The `get_doctest` method creates a T...
256
256
7,600
7
249
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_DocTestRunner
test_DocTestRunner
641
1,543
641
641
39f8eb77d7604d4624db7c519501f7dfa6f458c4
bigcode/the-stack
train
a9e0055b56a0db2a7fc70544
train
function
def test_trailing_space_in_test(): """ Trailing spaces in expected output are significant: >>> x, y = 'foo', '' >>> print(x, y) foo \n """
def test_trailing_space_in_test():
""" Trailing spaces in expected output are significant: >>> x, y = 'foo', '' >>> print(x, y) foo \n """
... 'test_doctest2.txt', ... 'test_doctest4.txt', ... encoding='utf-8') >>> suite.run(unittest.TestResult()) <unittest.TestResult run=3 errors=0 failures=2> """ def test_trailing_space_in_...
64
64
44
8
56
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_trailing_space_in_test
test_trailing_space_in_test
2,088
2,095
2,088
2,088
fbf991bd5f754fd560618c52f272deeb217ac40c
bigcode/the-stack
train
3fd64ea4011c574343242aa2
train
function
def test_testfile(): r""" Tests for the `testfile()` function. This function runs all the doctest examples in a given file. In its simple invokation, it is called with the name of a file, which is taken to be relative to the calling module. The return value is (#failures, #tests). We don't want `-v` in sys.argv for...
def test_testfile():
r""" Tests for the `testfile()` function. This function runs all the doctest examples in a given file. In its simple invokation, it is called with the name of a file, which is taken to be relative to the calling module. The return value is (#failures, #tests). We don't want `-v` in sys.argv for these tests. >>...
Traceback ... Failed example: favorite_color Exception raised: ... NameError: name 'favorite_color' is not defined <BLANKLINE> <BLANKLINE> We get only the first failure. If we give any reporting options when we set up the tests, however: >...
256
256
1,406
6
250
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_testfile
test_testfile
2,173
2,347
2,173
2,173
165fe259ea2f2411ce5c7428958faf495dfd34d9
bigcode/the-stack
train
19930cae005fd937cbeed3db
train
function
def test_Example(): r""" Unit tests for the `Example` class. Example is a simple container class that holds: - `source`: A source string. - `want`: An expected output string. - `exc_msg`: An expected exception message string (or None if no exception is expected). - `lineno`: A line number (within the docst...
def test_Example():
r""" Unit tests for the `Example` class. Example is a simple container class that holds: - `source`: A source string. - `want`: An expected output string. - `exc_msg`: An expected exception message string (or None if no exception is expected). - `lineno`: A line number (within the docstring). - `indent`:...
2 3 """ def __init__(self, val): """ >>> print(SampleNewStyleClass(12).get()) 12 """ self.val = val def double(self): """ >>> print(SampleNewStyleClass(12).double().get()) 24 """ return SampleNewStyleClass(self.val + se...
256
256
1,037
6
249
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_Example
test_Example
156
260
156
156
5de0c25a659647d85928101cfb522449bda8ad97
bigcode/the-stack
train
566ef8bea6dc3a5bf043f1a6
train
function
def test_DocTest(): r""" Unit tests for the `DocTest` class. DocTest is a collection of examples, extracted from a docstring, along with information about where the docstring comes from (a name, filename, and line number). The docstring is parsed by the `DocTest` constructor: >>> docstring = ''' ... >>> ...
def test_DocTest():
r""" Unit tests for the `DocTest` class. DocTest is a collection of examples, extracted from a docstring, along with information about where the docstring comes from (a name, filename, and line number). The docstring is parsed by the `DocTest` constructor: >>> docstring = ''' ... >>> print(12) ... ...
'IndexError: pop from an empty list\n' >>> exc_msg = 'IndexError: pop from an empty list\n' >>> e = doctest.Example('[].pop()', '', exc_msg) >>> e.exc_msg 'IndexError: pop from an empty list\n' Message spans multiple lines >>> exc_msg = 'ValueError: 1\n 2' >>> e = doctest.Example('raise ...
247
247
826
7
240
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_DocTest
test_DocTest
262
349
262
262
7b308c29d8848b150d983f5e14e7b61dca1dfcf0
bigcode/the-stack
train
2c735d527b20c4d32f913f29
train
function
def test_DocTestSuite(): """DocTestSuite creates a unittest test suite from a doctest. We create a Suite by providing a module. A module can be provided by passing a module object: >>> import unittest >>> import test.sample_doctest >>> suite = doctest.DocTestSuite(test.sa...
def test_DocTestSuite():
"""DocTestSuite creates a unittest test suite from a doctest. We create a Suite by providing a module. A module can be provided by passing a module object: >>> import unittest >>> import test.sample_doctest >>> suite = doctest.DocTestSuite(test.sample_doctest) >>...
Pdb) step > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2() -> z = 2 (Pdb) print(z) 1 (Pdb) up > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1() -> self.f2() (Pdb) print(x) 1 (Pdb) up > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(...
233
233
778
7
226
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_DocTestSuite
test_DocTestSuite
1,833
1,920
1,833
1,833
20cbf7d0268a06702f252df7462e424ae1b91c83
bigcode/the-stack
train
b5f3fd390bb88ffe09dfce1c
train
function
def test_coverage(coverdir): tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) tracer.run('test_main()') r = tracer.results() print('Writing coverage results...') r.write_results(show_missing=True, summary=True, coverdir=co...
def test_coverage(coverdir):
tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) tracer.run('test_main()') r = tracer.results() print('Writing coverage results...') r.write_results(show_missing=True, summary=True, coverdir=coverdir)
: support.run_doctest(doctest, verbosity=True) # Check the doctest cases defined here: from test import test_doctest support.run_doctest(test_doctest, verbosity=True) import trace, sys, re, io def test_coverage(coverdir):
64
64
73
8
55
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_coverage
test_coverage
2,372
2,379
2,372
2,372
d5019e83ddf73b14285d88973e20eed582e81b3b
bigcode/the-stack
train
832cc5c4bb3f8ce4a616a4fb
train
function
def test_testsource(): r""" Unit tests for `testsource()`. The testsource() function takes a module and a name, finds the (first) test with that name in that module, and converts it to a script. The example code is converted to regular Python code. The surrounding words and expected output are converted to comments: ...
def test_testsource():
r""" Unit tests for `testsource()`. The testsource() function takes a module and a name, finds the (first) test with that name in that module, and converts it to a script. The example code is converted to regular Python code. The surrounding words and expected output are converted to comments: >>> import test.te...
'>>> # doctest: +ELLIPSIS' >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0) Traceback (most recent call last): ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS' """ def test_testsource():
87
87
293
6
81
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_testsource
test_testsource
1,545
1,583
1,545
1,545
d0b4c91e0108e763128375f3c1283b2c09c6bc21
bigcode/the-stack
train
06743cb824cda005e9d21e29
train
function
def test_unittest_reportflags(): """Default unittest reporting flags can be set to control reporting Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see only the first failure of each test. First, we'll look at the output without the flag. The file test_doctest.txt file has two tests. ...
def test_unittest_reportflags():
"""Default unittest reporting flags can be set to control reporting Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see only the first failure of each test. First, we'll look at the output without the flag. The file test_doctest.txt file has two tests. They both fail if blank lines are...
specify which encoding the file is encoded with. We do so by using the `encoding` parameter: >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2.txt', ... 'test_doctest4.txt', ... ...
147
148
495
7
140
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_unittest_reportflags
test_unittest_reportflags
2,098
2,171
2,098
2,098
3fd5e204a15e805ca1ab08966fc001f14c29ee6c
bigcode/the-stack
train
d40d3f474628ccb75ced7ef7
train
function
def sample_func(v): """ Blah blah >>> print(sample_func(22)) 44 Yee ha! """ return v+v
def sample_func(v):
""" Blah blah >>> print(sample_func(22)) 44 Yee ha! """ return v+v
script for doctest. """ from test import support import doctest import warnings # NOTE: There are some additional tests relating to interaction with # zipimport in the test_zipimport_support test module. ###################################################################### ## Sample Objects (used by test cas...
64
64
36
5
58
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
sample_func
sample_func
16
25
16
16
189f4fe80bb4ec17fee35c80bcbf83e140b71ba7
bigcode/the-stack
train
c0eaef9b614a9dcbb8c6f5ae
train
function
def test_main(): # Check the doctest cases in doctest itself: support.run_doctest(doctest, verbosity=True) # Check the doctest cases defined here: from test import test_doctest support.run_doctest(test_doctest, verbosity=True)
def test_main(): # Check the doctest cases in doctest itself:
support.run_doctest(doctest, verbosity=True) # Check the doctest cases defined here: from test import test_doctest support.run_doctest(test_doctest, verbosity=True)
of the binary module. >>> import unicodedata >>> doctest.testmod(unicodedata, verbose=False) TestResults(failed=0, attempted=0) """ ###################################################################### ## Main ###################################################################### def test_main(): # ...
64
64
62
16
47
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_main
test_main
2,364
2,369
2,364
2,365
af62f1f2548fbc0bd245f78c3ad069d9fc88f262
bigcode/the-stack
train
fac74be7367efdf42de563ce
train
class
class SampleClass: """ >>> print(1) 1 >>> # comments get ignored. so are empty PS1 and PS2 prompts: >>> ... Multiline example: >>> sc = SampleClass(3) >>> for i in range(10): ... sc = sc.double() ... print(' ', sc.get(), sep='', end='') 6 12 24 48 96 192 384 7...
class SampleClass:
""" >>> print(1) 1 >>> # comments get ignored. so are empty PS1 and PS2 prompts: >>> ... Multiline example: >>> sc = SampleClass(3) >>> for i in range(10): ... sc = sc.double() ... print(' ', sc.get(), sep='', end='') 6 12 24 48 96 192 384 768 1536 3072 ""...
""" Test script for doctest. """ from test import support import doctest import warnings # NOTE: There are some additional tests relating to interaction with # zipimport in the test_zipimport_support test module. ###################################################################### ## Sample Objects (used by ...
101
134
448
4
96
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
SampleClass
SampleClass
27
103
27
27
d82583ead9dd0f475506bb4d178e469879f4106f
bigcode/the-stack
train
b6030f44d23275ff045b72bc
train
class
class _FakeInput: """ A fake input stream for pdb's interactive debugger. Whenever a line is read, print it (to simulate the user typing it), and then return it. The set of lines to return is specified in the constructor; they should not have trailing newlines. """ def __init__(self, lines...
class _FakeInput:
""" A fake input stream for pdb's interactive debugger. Whenever a line is read, print it (to simulate the user typing it), and then return it. The set of lines to return is specified in the constructor; they should not have trailing newlines. """ def __init__(self, lines): self.li...
""" return SampleNewStyleClass(self.val + self.val) def get(self): """ >>> print(SampleNewStyleClass(-5).get()) -5 """ return self.val ###################################################################### ## Fake stdin (for testing interactive debugging) #########...
64
64
108
5
58
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
_FakeInput
_FakeInput
137
150
137
137
b327d50e3a62d7d3f8e5e2a7c30e944db0b05b99
bigcode/the-stack
train
a1f44a48f53f36797dd8d1c3
train
class
class SampleNewStyleClass(object): r""" >>> print('1\n2\n3') 1 2 3 """ def __init__(self, val): """ >>> print(SampleNewStyleClass(12).get()) 12 """ self.val = val def double(self): """ >>> print(SampleNewStyleClass(12).double().get...
class SampleNewStyleClass(object):
r""" >>> print('1\n2\n3') 1 2 3 """ def __init__(self, val): """ >>> print(SampleNewStyleClass(12).get()) 12 """ self.val = val def double(self): """ >>> print(SampleNewStyleClass(12).double().get()) 24 """ ...
val=0): """ >>> print(SampleClass.NestedClass().get()) 0 """ self.val = val def square(self): return SampleClass.NestedClass(self.val*self.val) def get(self): return self.val class SampleNewStyleClass(object):
64
64
141
7
56
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
SampleNewStyleClass
SampleNewStyleClass
105
131
105
105
d995cfbc1bfa8105e7067f1c596e04d716beeb0a
bigcode/the-stack
train
cdbd11384579eb7f0f042ed7
train
function
def test_DocTestParser(): r""" Unit tests for the `DocTestParser` class. DocTestParser is used to parse docstrings containing doctest examples. The `parse` method divides a docstring into examples and intervening text: >>> s = ''' ... >>> x, y = 2, 3 # no output expected ... >>> if 1: ... ...
def test_DocTestParser():
r""" Unit tests for the `DocTestParser` class. DocTestParser is used to parse docstrings containing doctest examples. The `parse` method divides a docstring into examples and intervening text: >>> s = ''' ... >>> x, y = 2, 3 # no output expected ... >>> if 1: ... ... print(x) ......
def f(x): ... ''' ... >>> x = 12 ... ... some text ... ... >>> # examples are not created for comments & bare prompts. ... >>> ... ... ... ... >>> for x in range(10): ... ... print(x, end=' ') ... 0 1 2 3 4 5 6 7 8 9 ... >>...
163
163
545
8
155
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_DocTestParser
test_DocTestParser
586
639
586
586
56d20f60df3279002a7cf349c66cb9cbb6c41074
bigcode/the-stack
train
ac522691579763a2e06b7cac
train
function
def test_pdb_set_trace_nested(): """This illustrates more-demanding use of set_trace with nested functions. >>> class C(object): ... def calls_set_trace(self): ... y = 1 ... import pdb; pdb.set_trace() ... self.f1() ... y = 2 ... def f1(self): ...
def test_pdb_set_trace_nested():
"""This illustrates more-demanding use of set_trace with nested functions. >>> class C(object): ... def calls_set_trace(self): ... y = 1 ... import pdb; pdb.set_trace() ... self.f1() ... y = 2 ... def f1(self): ... x = 1 ... ...
ctest foo[1]>(3)g()->None -> import pdb; pdb.set_trace() (Pdb) list 1 def g(x): 2 print(x+3) 3 -> import pdb; pdb.set_trace() [EOF] (Pdb) next --Return-- > <doctest foo[0]>(2)f()->None -> g(x*2) (Pdb) list 1 def f(x): ...
248
248
827
8
240
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_pdb_set_trace_nested
test_pdb_set_trace_nested
1,747
1,831
1,747
1,747
a68c3b7137c51b511ff1fbd99b4dae52a5ce1567
bigcode/the-stack
train
d7e4d4eadbc51d846d2d9f75
train
function
def test_debug(): r""" Create a docstring that we want to debug: >>> s = ''' ... >>> x = 12 ... >>> print(x) ... 12 ... ''' Create some fake stdin input, to feed to the debugger: >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue']) Run ...
def test_debug():
r""" Create a docstring that we want to debug: >>> s = ''' ... >>> x = 12 ... >>> print(x) ... 12 ... ''' Create some fake stdin input, to feed to the debugger: >>> real_stdin = sys.stdin >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue']) Run the debugger on th...
source(test.test_doctest, name)) print(SampleClass.a_classmethod(10)) # Expected: ## 12 print(SampleClass(0).a_classmethod(10)) # Expected: ## 12 <BLANKLINE> """ def test_debug():
64
64
177
5
59
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_debug
test_debug
1,585
1,613
1,585
1,585
3a18822ebf5dcab36aeb9c7a12297ced91785d20
bigcode/the-stack
train
3fa9f3d309fa5790001f2b3a
train
function
def test_DocTestFinder(): r""" Unit tests for the `DocTestFinder` class. DocTestFinder is used to extract DocTests from an object's docstring and the docstrings of its contained objects. It can be used with modules, functions, classes, methods, staticmethods, classmethods, and properties. Finding Tests in Functions ...
def test_DocTestFinder():
r""" Unit tests for the `DocTestFinder` class. DocTestFinder is used to extract DocTests from an object's docstring and the docstrings of its contained objects. It can be used with modules, functions, classes, methods, staticmethods, classmethods, and properties. Finding Tests in Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~...
, globs, 'some_test', 'filename', 0) Traceback (most recent call last): ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))' If there's no blank space after a PS1 prompt ('>>>'), then `DocTest` will raise a ValueError: >>> docstring = '>>>print(1)\n1' ...
256
256
2,000
8
248
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_DocTestFinder
test_DocTestFinder
351
584
351
351
2b1f995d428ee038a2b46624ea0f8297ee4ee968
bigcode/the-stack
train
8c47b966cb029c863f648767
train
function
def test_testmod(): r""" Tests for the testmod function. More might be useful, but for now we're just testing the case raised by Issue 6195, where trying to doctest a C module would fail with a UnicodeDecodeError because doctest tried to read the "source" lines out of the binary module. >>> import unicodedata ...
def test_testmod():
r""" Tests for the testmod function. More might be useful, but for now we're just testing the case raised by Issue 6195, where trying to doctest a C module would fail with a UnicodeDecodeError because doctest tried to read the "source" lines out of the binary module. >>> import unicodedata >>> doctest.testmod...
.txt 2 tests in 1 items. 2 passed and 0 failed. Test passed. TestResults(failed=0, attempted=2) >>> doctest.master = None # Reset master. >>> sys.argv = save_argv """ def test_testmod():
64
64
104
6
58
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_testmod
test_testmod
2,349
2,358
2,349
2,349
387b01a1204d4305f52ffcc1442ac951221a1a45
bigcode/the-stack
train
cc2a9a53ae408de1fc717779
train
function
def test_DocFileSuite(): """We can test tests found in text files using a DocFileSuite. We create a suite by providing the names of one or more text files that include examples: >>> import unittest >>> suite = doctest.DocFileSuite('test_doctest.txt', ... ...
def test_DocFileSuite():
"""We can test tests found in text files using a DocFileSuite. We create a suite by providing the names of one or more text files that include examples: >>> import unittest >>> suite = doctest.DocFileSuite('test_doctest.txt', ... 'test_doctest2...
('test.sample_doctest', ... setUp=setUp, tearDown=tearDown) >>> suite.run(unittest.TestResult()) <unittest.TestResult run=9 errors=0 failures=3> But the tearDown restores sanity: >>> import test.test_doctest >>> test.test_doctest.sillySetup Traceback (...
256
256
1,509
7
249
deadsnakes/python3.1
Lib/test/test_doctest.py
Python
test_DocFileSuite
test_DocFileSuite
1,922
2,086
1,922
1,922
0159cda7d7fb36692c39899430d85fb541c30170
bigcode/the-stack
train
b5782b22ac27a004f9caa685
train
class
class AdServiceClient(object): """Service to manage ads.""" SERVICE_ADDRESS = 'googleads.googleapis.com:443' """The default address of the service.""" # The name of the interface for this client. This is the key used to # find the method configuration in the client_config dictionary. _INTERFAC...
class AdServiceClient(object):
"""Service to manage ads.""" SERVICE_ADDRESS = 'googleads.googleapis.com:443' """The default address of the service.""" # The name of the interface for this client. This is the key used to # find the method configuration in the client_config dictionary. _INTERFACE_NAME = 'google.ads.googleads....
in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, eithe...
256
256
2,107
6
249
arammaliachi/google-ads-python
google/ads/google_ads/v4/services/ad_service_client.py
Python
AdServiceClient
AdServiceClient
41
288
41
41
2cc2e06d2b91f4fac1238a1cf86fad1e095c894a
bigcode/the-stack
train
cee61848aa899dca03fdb685
train
class
class Application(wx.Frame): def __init__(self, parent, title): super(Application, self).__init__(parent, title=title, size=(600, 500)) self.init_menu() self.init_panel() self.Centre() self.Show() def init_menu(self): menu_bar = wx.MenuBar() # icon = wx.I...
class Application(wx.Frame):
def __init__(self, parent, title): super(Application, self).__init__(parent, title=title, size=(600, 500)) self.init_menu() self.init_panel() self.Centre() self.Show() def init_menu(self): menu_bar = wx.MenuBar() # icon = wx.Icon("./bitmaps/zip.ico", wx.B...
#!/usr/bin/env python # -*- encoding=utf-8 -*- import errno __author__ = "Ricky" from pack import * import wx import platform import os import subprocess class Application(wx.Frame):
45
256
1,396
5
39
lxy3372/pack-code
wxrun.py
Python
Application
Application
13
154
13
13
bf27c22908ba6eb54fc77ace9301951ef25dc568
bigcode/the-stack
train
f50c28e442bdcbe10f76604a
train
class
class CenteredUnitX(Transform): """Map X to [-1, 1]^d for RangeParameter of type float and not log scale. Currently does not support linear constraints, but could in the future be adjusted to transform them too, since this is a linear operation. Transform is done in-place. """ def __init__( ...
class CenteredUnitX(Transform):
"""Map X to [-1, 1]^d for RangeParameter of type float and not log scale. Currently does not support linear constraints, but could in the future be adjusted to transform them too, since this is a linear operation. Transform is done in-place. """ def __init__( self, search_spac...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Dict, List, Optional, Tuple from ax.core.observation import ObservationData, ObservationFeatures fr...
125
201
671
8
116
viotemp1/Ax
ax/modelbridge/transforms/centered_unit_x.py
Python
CenteredUnitX
CenteredUnitX
17
81
17
17
70381c7709c1e07362b40741052c117e235950fe
bigcode/the-stack
train
98d957ce864fe993022afbe5
train
class
class BirdBrain(Brain): def __init__(self): pass def decideFlap(self,params): #print(params) return params['playerClick']
class BirdBrain(Brain):
def __init__(self): pass def decideFlap(self,params): #print(params) return params['playerClick']
284 * 2 # BG image size: 284x512 px; tiled twice WIN_HEIGHT = 512 BIRD_X = 350 class Brain(metaclass=ABCMeta): @abstractmethod def decideFlap(self,params):pass class BirdBrain(Brain):
64
64
37
6
57
youngstudent2/flappy-bird-for-learn
flappybird.py
Python
BirdBrain
BirdBrain
23
28
23
23
c316d913c84725115ede37af8a8595f34fa3d546
bigcode/the-stack
train
bac139f2e480a7ecb3b27f72
train
function
def frames_to_msec(frames, fps=FPS): """Convert frames to milliseconds at the specified framerate. Arguments: frames: How many frames to convert to milliseconds. fps: The framerate to use for conversion. Default: FPS. """ return 1000.0 * frames / fps
def frames_to_msec(frames, fps=FPS):
"""Convert frames to milliseconds at the specified framerate. Arguments: frames: How many frames to convert to milliseconds. fps: The framerate to use for conversion. Default: FPS. """ return 1000.0 * frames / fps
images for animating the flapping bird -- animated GIFs are # not supported in pygame 'bird-wingup': load_image('bird_wing_up.png'), 'bird-wingdown': load_image('bird_wing_down.png')} def frames_to_msec(frames, fps=FPS):
63
64
68
12
51
youngstudent2/flappy-bird-for-learn
flappybird.py
Python
frames_to_msec
frames_to_msec
371
378
371
371
a23665eb58f9f20e631b720b35c11d0d1b84711b
bigcode/the-stack
train
302bf6ad05a7dac09effeeb2
train
function
def load_images(): """Load all images required by the game and return a dict of them. The returned dict has the following keys: background: The game's background image. bird-wingup: An image of the bird with its wing pointing upward. Use this and bird-wingdown to create a flapping bird. bir...
def load_images():
"""Load all images required by the game and return a dict of them. The returned dict has the following keys: background: The game's background image. bird-wingup: An image of the bird with its wing pointing upward. Use this and bird-wingdown to create a flapping bird. bird-wingdown: An imag...
, p.rect) for bird in birds: self.display_surface.blit(bird.image, bird.rect) score_surface = self.score_font.render(str(score), True, (255, 255, 255)) score_x = WIN_WIDTH/2 - score_surface.get_width()/2 self.display_surface.blit(score_surface, (score_x, PipePair.PI...
107
109
364
4
103
youngstudent2/flappy-bird-for-learn
flappybird.py
Python
load_images
load_images
331
368
331
331
70beb8e3a654fed44cdf74997dd1a43e4d96e028
bigcode/the-stack
train
b513f3ec385aa7eae0652126
train
class
class FlappyBirdGame(): def __init__(self,fps,birdNum,birdBrains): FPS = fps self.view = GameView() # the bird stays in the same x position, so bird.x is a constant # center bird on screen self.birds = [] for i in range(birdNum): bird = Bird(BIRD_...
class FlappyBirdGame():
def __init__(self,fps,birdNum,birdBrains): FPS = fps self.view = GameView() # the bird stays in the same x position, so bird.x is a constant # center bird on screen self.birds = [] for i in range(birdNum): bird = Bird(BIRD_X, int(WIN_HEIGHT/2 - Bi...
.join('.', 'images', img_file_name) img = pygame.image.load(file_name) img.convert() return img return {'background': load_image('background.png'), 'pipe-end': load_image('pipe_end.png'), 'pipe-body': load_image('pipe_body.png'), # images for animating th...
256
256
1,016
6
249
youngstudent2/flappy-bird-for-learn
flappybird.py
Python
FlappyBirdGame
FlappyBirdGame
392
518
392
392
dc189426b5737359356c25c2a42a61a6b537e3b8
bigcode/the-stack
train
8054579c94b74b1a005ddfde
train
class
class GameView(): def __init__(self): pygame.init() self.display_surface = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) pygame.display.set_caption('Pygame Flappy Bird') self.clock = pygame.time.Clock() self.score_font = pygame.font.SysFont(None, 32, bold=True) # defaul...
class GameView():
def __init__(self): pygame.init() self.display_surface = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) pygame.display.set_caption('Pygame Flappy Bird') self.clock = pygame.time.Clock() self.score_font = pygame.font.SysFont(None, 32, bold=True) # default font sel...
with a pipe in this PipePair. Arguments: bird: The Bird which should be tested for collision with this PipePair. """ return pygame.sprite.collide_mask(self, bird) def in_front_of(self,bird): if bird.X > self.x + PipePair.WIDTH: return False r...
76
76
256
4
71
youngstudent2/flappy-bird-for-learn
flappybird.py
Python
GameView
GameView
297
328
297
297
d26b317ef2b3cd79681fee9f40f0952de9264aad
bigcode/the-stack
train
0eb4136d18579a4152070533
train
function
def msec_to_frames(milliseconds, fps=FPS): """Convert milliseconds to frames at the specified framerate. Arguments: milliseconds: How many milliseconds to convert to frames. fps: The framerate to use for conversion. Default: FPS. """ return fps * milliseconds / 1000.0
def msec_to_frames(milliseconds, fps=FPS):
"""Convert milliseconds to frames at the specified framerate. Arguments: milliseconds: How many milliseconds to convert to frames. fps: The framerate to use for conversion. Default: FPS. """ return fps * milliseconds / 1000.0
frames to milliseconds at the specified framerate. Arguments: frames: How many frames to convert to milliseconds. fps: The framerate to use for conversion. Default: FPS. """ return 1000.0 * frames / fps def msec_to_frames(milliseconds, fps=FPS):
64
64
67
11
52
youngstudent2/flappy-bird-for-learn
flappybird.py
Python
msec_to_frames
msec_to_frames
381
388
381
381
f08d583b16ab1f4cdf116b183b413dbeb26c861d
bigcode/the-stack
train
77f6df113ea164f231bec84a
train
class
class PipePair(pygame.sprite.Sprite): """Represents an obstacle. A PipePair has a top and a bottom pipe, and only between them can the bird pass -- if it collides with either part, the game is over. Attributes: x: The PipePair's X position. This is a float, to make movement smoother. Not...
class PipePair(pygame.sprite.Sprite):
"""Represents an obstacle. A PipePair has a top and a bottom pipe, and only between them can the bird pass -- if it collides with either part, the game is over. Attributes: x: The PipePair's X position. This is a float, to make movement smoother. Note that there is no y attribute, as it ...
or where it is pointing downward based on pygame.time.get_ticks(). This will animate the flapping bird, even though pygame doesn't support animated GIFs. """ if pygame.time.get_ticks() % 500 >= 250: img = self._img_wingup else: img = self._img_w...
256
256
1,094
9
246
youngstudent2/flappy-bird-for-learn
flappybird.py
Python
PipePair
PipePair
174
296
174
174
2b92273d2ddcd0a714fc7cf9c406537277ebc98f
bigcode/the-stack
train
1b220fcef99eb8b05c915a0a
train
class
class Brain(metaclass=ABCMeta): @abstractmethod def decideFlap(self,params):pass
class Brain(metaclass=ABCMeta): @abstractmethod
def decideFlap(self,params):pass
IMATION_SPEED = 0.18 # pixels per millisecond WIN_WIDTH = 284 * 2 # BG image size: 284x512 px; tiled twice WIN_HEIGHT = 512 BIRD_X = 350 class Brain(metaclass=ABCMeta): @abstractmethod
64
64
25
14
49
youngstudent2/flappy-bird-for-learn
flappybird.py
Python
Brain
Brain
20
22
20
21
da5ef821d3a2ab5d80e3fb9a45103292eb1040ab
bigcode/the-stack
train
2696c4ffd6d0a8721a1931d8
train
class
class Bird(pygame.sprite.Sprite): """Represents the bird controlled by the player. The bird is the 'hero' of this game. The player can make it climb (ascend quickly), otherwise it sinks (descends more slowly). It must pass through the space in between pipes (for every pipe passed, one point is sc...
class Bird(pygame.sprite.Sprite):
"""Represents the bird controlled by the player. The bird is the 'hero' of this game. The player can make it climb (ascend quickly), otherwise it sinks (descends more slowly). It must pass through the space in between pipes (for every pipe passed, one point is scored); if it crashes into a pipe, ...
#! /usr/bin/env python3 """Flappy Bird, implemented using Pygame.""" import math import os from random import randint from collections import deque import pygame from pygame.locals import * from abc import ABCMeta,abstractmethod FPS = 60 ANIMATION_SPEED = 0.18 # pixels per millisecond WIN_WIDTH = 284 * 2 # BG ...
178
256
1,273
8
170
youngstudent2/flappy-bird-for-learn
flappybird.py
Python
Bird
Bird
29
172
29
29
86344378cfebe63b5f7167b63130c9b8bed4ca88
bigcode/the-stack
train
d26c01e7c10a2cfa372a13ab
train
class
class ListLiveStreamsOnlineRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensiti...
class ListLiveStreamsOnlineRequest:
""" Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { ...
# coding: utf-8 import pprint import re import six class ListLiveStreamsOnlineRequest:
23
256
1,279
7
15
wuchen-huawei/huaweicloud-sdk-python-v3
huaweicloud-sdk-live/huaweicloudsdklive/v1/model/list_live_streams_online_request.py
Python
ListLiveStreamsOnlineRequest
ListLiveStreamsOnlineRequest
12
217
12
14
a8f19f34529c0b82966f1da4470b24a36c4f9f73
bigcode/the-stack
train
b601b6ebe864b6c9b04e8f11
train
function
def bar(): pass
def bar():
pass
under the License. # ============================================================================== """Tests for tensorflow.ops.registry.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized from tensorflow...
64
64
6
3
60
uve/tensorflow
tensorflow/python/framework/registry_test.py
Python
bar
bar
28
29
28
28
e08b89a4f1b2bc8ca2cfa4637b016949340a9859
bigcode/the-stack
train
199ceb2a8c62d62923bf1c86
train
class
class RegistryTest(test.TestCase, parameterized.TestCase): class Foo(object): pass # Test the registry basics on both classes (Foo) and functions (bar). @parameterized.parameters([Foo, bar]) def testRegistryBasics(self, candidate): myreg = registry.Registry('testRegistry') with self.asser...
class RegistryTest(test.TestCase, parameterized.TestCase):
class Foo(object): pass # Test the registry basics on both classes (Foo) and functions (bar). @parameterized.parameters([Foo, bar]) def testRegistryBasics(self, candidate): myreg = registry.Registry('testRegistry') with self.assertRaises(LookupError): myreg.lookup('testKey') myre...
for tensorflow.ops.registry.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized from tensorflow.python.framework import registry from tensorflow.python.platform import test def bar(): pass class Regi...
69
69
230
12
56
uve/tensorflow
tensorflow/python/framework/registry_test.py
Python
RegistryTest
RegistryTest
32
56
32
33
385652aaa486f9537a458820a199f15c5fdb1525
bigcode/the-stack
train
3a37dc207b877de81b209414
train
class
class GlobalOrderProportion: """Helper used to generate order proportion at specified tick range """ def parse(self, conf: dict, total_container: int, max_tick: int, start_tick: int = 0) -> np.ndarray: """Parse specified configuration, and generate order proportion Args: ...
class GlobalOrderProportion:
"""Helper used to generate order proportion at specified tick range """ def parse(self, conf: dict, total_container: int, max_tick: int, start_tick: int = 0) -> np.ndarray: """Parse specified configuration, and generate order proportion Args: conf (dict): configuration...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import numpy as np from math import floor, ceil from typing import List, Union from .utils import apply_noise, order_init_rand, clip class GlobalOrderProportion:
53
143
477
6
46
zhawan/maro
maro/data_lib/ecr/global_order_proportion.py
Python
GlobalOrderProportion
GlobalOrderProportion
12
68
12
12
d5aee55026cf35155e2d4c1d67d59d200667aa5a
bigcode/the-stack
train
8403d121228ff226d78df150
train
class
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
class TreeNode:
def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
# Support code class TreeNode:
9
64
39
4
4
Voley/AlgorithmicProblemsV2
Trees/search/Solution.py
Python
TreeNode
TreeNode
3
7
3
3
f4cae1903f6ca58676b99dd066098002b526a6e2
bigcode/the-stack
train
2394556cc292228d26f26058
train
function
def searchBST(root): return search(root, val)
def searchBST(root):
return search(root, val)
# Support code class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Problem code def searchBST(root):
53
64
12
5
47
Voley/AlgorithmicProblemsV2
Trees/search/Solution.py
Python
searchBST
searchBST
10
11
10
10
ddf815dcffea6823956c6b3916bf883492ab65f2
bigcode/the-stack
train
8f1bd8870cec17c4cfecdaca
train
function
def search(root, target): if not root: return None if root.val == target: return root if root.val > target: return search(root.left, target) if root.val < target: return search(root.right, target)
def search(root, target):
if not root: return None if root.val == target: return root if root.val > target: return search(root.left, target) if root.val < target: return search(root.right, target)
Support code class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Problem code def searchBST(root): return search(root, val) def search(root, target):
64
64
56
6
58
Voley/AlgorithmicProblemsV2
Trees/search/Solution.py
Python
search
search
13
24
13
13
0514bf3cab79470f8638d43d1596736ec8c58474
bigcode/the-stack
train
8b53c4e5ac4cbe82d672a5e9
train
class
class PyMon: def __init__(self): self.kiwoom = Kiwoom.Kiwoom() self.kiwoom.comm_connect() self.get_code_list() def get_code_list(self): self.kospi_codes = self.kiwoom.get_code_list_by_market(MARKET_KOSPI) self.kosdaq_codes = self.kiwoom.get_code_list_by_market(MARKET_KOS...
class PyMon:
def __init__(self): self.kiwoom = Kiwoom.Kiwoom() self.kiwoom.comm_connect() self.get_code_list() def get_code_list(self): self.kospi_codes = self.kiwoom.get_code_list_by_market(MARKET_KOSPI) self.kosdaq_codes = self.kiwoom.get_code_list_by_market(MARKET_KOSDAQ) def...
import sys from PyQt5.QtWidgets import * import Kiwoom import time from pandas import DataFrame import datetime MARKET_KOSPI = 0 MARKET_KOSDAQ = 10 class PyMon:
52
164
549
4
47
hnccho/book
ch19/day05/03.py
Python
PyMon
PyMon
11
72
11
11
b589fc56cb50cd58dba5289c2ab966ca978b2386
bigcode/the-stack
train
4826b73348814ffd21c338fc
train
class
class InformationAdmin(admin.ModelAdmin): pass
class InformationAdmin(admin.ModelAdmin):
pass
, null=True) content = models.TextField(max_length=65535) status = models.CharField(max_length=10, choices=InformationStatus.choices, default=InformationStatus.ANALYSIS) references = models.TextField(max_length=1024, null=True) class InformationAdmin(admin.ModelAdmin):
64
64
10
7
57
ferdn4ndo/infotrem
backend/api/models/information_model.py
Python
InformationAdmin
InformationAdmin
30
31
30
30
245ec1f4e56db7126ab40b3dd789577fb7eba92c
bigcode/the-stack
train
d5bd3f2431ae1a5344f15775
train
class
class Information(GenericAuditedModel): class InformationStatus(models.TextChoices): DISCUSSION = 'DISCUSSION', _("Information is still under discussion") ANALYSIS = 'ANALYSIS', _("Information is under analysis by a moderator") APPROVED = 'APPROVED', _("Information was approved by a moderat...
class Information(GenericAuditedModel):
class InformationStatus(models.TextChoices): DISCUSSION = 'DISCUSSION', _("Information is still under discussion") ANALYSIS = 'ANALYSIS', _("Information is under analysis by a moderator") APPROVED = 'APPROVED', _("Information was approved by a moderator") REJECTED = 'REJECTED', _("In...
from django.contrib import admin from django.db import models from django.utils.translation import gettext_lazy as _ from .generic_audited_model import GenericAuditedModel from .user_model import User class Information(GenericAuditedModel):
49
77
257
7
41
ferdn4ndo/infotrem
backend/api/models/information_model.py
Python
Information
Information
9
27
9
10
736e5848be6d3771a1bc3902cafa72dcc405a1b8
bigcode/the-stack
train
26dfce5fd2dcec7039f7d0cf
train
class
class AbstractMetaLearner(nn.Module): """ Abstract class providing methods usable by all few-shot classification algorithms """ def __init__(self, backbone: nn.Module): super().__init__() self.backbone = backbone self.backbone_output_shape = compute_backbone_output_shape(backbo...
class AbstractMetaLearner(nn.Module):
""" Abstract class providing methods usable by all few-shot classification algorithms """ def __init__(self, backbone: nn.Module): super().__init__() self.backbone = backbone self.backbone_output_shape = compute_backbone_output_shape(backbone) self.feature_dimension = s...
from abc import abstractmethod from pathlib import Path from typing import Union import torch from torch import nn, optim from torch.utils.data import DataLoader from tqdm import tqdm from easyfsl.utils import sliding_average, compute_backbone_output_shape class AbstractMetaLearner(nn.Module):
62
256
1,739
8
53
irmaps/easy-few-shot-learning
easyfsl/methods/abstract_meta_learner.py
Python
AbstractMetaLearner
AbstractMetaLearner
13
272
13
13
77be148b7e5fb3f0420e17d1260e5d680d1be13a
bigcode/the-stack
train
ccc9785e25f8385a9ef622e3
train
function
def main(argv): test_lib.main(argv)
def main(argv):
test_lib.main(argv)
_utils.CustomInetNtoP(socket.AF_INET6, expected_packed), expected_unpacked) for address in test_dict["bad_ipv6_addresses"]: with self.assertRaises(socket.error, message=address): ipv6_utils.CustomInetPtoN(socket.AF_INET6, address) def main(argv):
64
64
10
4
60
dekoder/grr
grr/core/grr_response_core/lib/ipv6_utils_test.py
Python
main
main
50
51
50
50
ecd94fc80a33de9e929d8f215b77bba11a49aa84
bigcode/the-stack
train
be51a42b2a9bdc0a78fb88eb
train
class
class Ipv6UtilsTest(test_lib.GRRBaseTest): """Test IPv6 utilities functions. Test addresses inspired by: http://download.dartware.com/thirdparty/test-ipv6-regex.pl We test for equivalence with linux's implementation of socket.inet_pton and socket.inet_ntop but not reversibility since the addresses are outpu...
class Ipv6UtilsTest(test_lib.GRRBaseTest):
"""Test IPv6 utilities functions. Test addresses inspired by: http://download.dartware.com/thirdparty/test-ipv6-regex.pl We test for equivalence with linux's implementation of socket.inet_pton and socket.inet_ntop but not reversibility since the addresses are output to best practice standard and the input...
#!/usr/bin/env python """Tests for grr.lib.ipv6_utils.""" from __future__ import unicode_literals import os import socket import yaml from grr_response_core import config from grr_response_core.lib import flags from grr_response_core.lib import ipv6_utils from grr.test_lib import test_lib class Ipv6UtilsTest(test_li...
84
100
334
13
70
dekoder/grr
grr/core/grr_response_core/lib/ipv6_utils_test.py
Python
Ipv6UtilsTest
Ipv6UtilsTest
16
47
16
16
93798d48fcebf6bfd7ed3ea068ac0a5f18662355
bigcode/the-stack
train
ad48a7a33b2cb88315df9b63
train
class
class ResourceTasks(ResourceAbstract): __endpoint: str = "/tasks" __client: Client def __init__(self, client: Client) -> None: super().__init__() self.__client = client def get_resource_endpoint(self): return self.__endpoint def get_tasks(self, params: dict = None) -> dict...
class ResourceTasks(ResourceAbstract):
__endpoint: str = "/tasks" __client: Client def __init__(self, client: Client) -> None: super().__init__() self.__client = client def get_resource_endpoint(self): return self.__endpoint def get_tasks(self, params: dict = None) -> dict: """get_tasks returns a dict w...
from __future__ import annotations from typing import TYPE_CHECKING from easybill_rest.helper import Helper from easybill_rest.resources.resource_abstract import ResourceAbstract if TYPE_CHECKING: from easybill_rest import Client class ResourceTasks(ResourceAbstract):
53
121
404
6
46
soerenbe/py-ebrest
easybill_rest/resources/resource_tasks.py
Python
ResourceTasks
ResourceTasks
12
65
12
12
a24c10b1c2e43e96e98220bff281ad8fcea76d6a
bigcode/the-stack
train
e2a2bfb61b545d75bef2423f
train
class
class AddrTest(unittest.TestCase): """Test the Addr class.""" def setUp(self): from certbot_nginx._internal.obj import Addr self.addr1 = Addr.fromstring("192.168.1.1") self.addr2 = Addr.fromstring("192.168.1.1:* ssl") self.addr3 = Addr.fromstring("192.168.1.1:80") self.ad...
class AddrTest(unittest.TestCase):
"""Test the Addr class.""" def setUp(self): from certbot_nginx._internal.obj import Addr self.addr1 = Addr.fromstring("192.168.1.1") self.addr2 = Addr.fromstring("192.168.1.1:* ssl") self.addr3 = Addr.fromstring("192.168.1.1:80") self.addr4 = Addr.fromstring("*:80 default...
"""Test the helper objects in certbot_nginx._internal.obj.""" import itertools import unittest class AddrTest(unittest.TestCase):
27
256
1,106
7
19
vivithemage/certbot
certbot-nginx/tests/obj_test.py
Python
AddrTest
AddrTest
6
106
6
6
0fe66398f9b30bc8f39d9bba016c939b07878c98
bigcode/the-stack
train
a604bd22c14815b438160670
train
class
class VirtualHostTest(unittest.TestCase): """Test the VirtualHost class.""" def setUp(self): from certbot_nginx._internal.obj import VirtualHost from certbot_nginx._internal.obj import Addr raw1 = [ ['listen', '69.50.225.155:9000'], [['if', '($scheme', '!=', '"htt...
class VirtualHostTest(unittest.TestCase):
"""Test the VirtualHost class.""" def setUp(self): from certbot_nginx._internal.obj import VirtualHost from certbot_nginx._internal.obj import Addr raw1 = [ ['listen', '69.50.225.155:9000'], [['if', '($scheme', '!=', '"https") '], [['return', '301'...
0.0.0.0:80 default_server ssl", "80 default_server ssl", "*:80 default_server ssl", "80 default ssl") for first, second in itertools.combinations(any_addresses, 2): self.assertEqual(Addr.fromstring(first), Addr.fromstring(sec...
256
256
1,285
8
248
vivithemage/certbot
certbot-nginx/tests/obj_test.py
Python
VirtualHostTest
VirtualHostTest
109
225
109
109
6abbf832867273ead60027b4dd57ad4f7f2e1b8a
bigcode/the-stack
train
69312564e5bad96a44f9fcf2
train
function
@click.command() @click.pass_context @click.option("--run-id", type=int, required=True) @click.argument( "filenames", type=click.Path(exists=True, readable=True, resolve_path=True), nargs=-1, required=True, ) def lint(click_ctx: click.Context, run_id: int, filenames: List[str]) -> None: """Output DB...
@click.command() @click.pass_context @click.option("--run-id", type=int, required=True) @click.argument( "filenames", type=click.Path(exists=True, readable=True, resolve_path=True), nargs=-1, required=True, ) def lint(click_ctx: click.Context, run_id: int, filenames: List[str]) -> None:
"""Output DB models in a lint-friendly format""" ctx = click_ctx.obj require_option(click_ctx, "repository") paths = [Path(p).resolve() for p in filenames] root = Path(ctx.repository).resolve() relative = [str(Path(f).relative_to(root)) for f in paths] with ctx.database.make_session() as s...
found in the # LICENSE file in the root directory of this source tree. import json from operator import itemgetter from pathlib import Path from typing import List import click from sqlalchemy.orm import aliased from .cli_lib import require_option from .models import Issue, IssueInstance, SharedText, TraceFrame F...
170
170
569
74
96
s-pace/pyre-check
tools/sapp/sapp/lint.py
Python
lint
lint
23
98
23
32
eb304f102abd2e5d7dbc406ffb7af06b5c657ba1
bigcode/the-stack
train
ee821dc483c86b5c279344f7
train
function
@app.route('/') def redirect_to_swagger(): return flask.redirect('/apidocs')
@app.route('/') def redirect_to_swagger():
return flask.redirect('/apidocs')
r') as f_in: template = yaml.load(f_in, Loader=yaml.Loader) template['info']['version'] = __version__ app.config['SWAGGER'] = {'openapi': '3.0.2'} Swagger(app, template=template) @app.route('/') def redirect_to_swagger():
64
64
17
9
55
piotrmaslanka/yandex-conqueror
conqueror/app.py
Python
redirect_to_swagger
redirect_to_swagger
35
37
35
36
cf99014a38dd0bd0d221bc5d664e27b93c16fae0
bigcode/the-stack
train
7b15fee26cd3621c863755cb
train
class
class TaskAPI(generics.RetrieveUpdateDestroyAPIView): """ get: Get task by ID Get task data, metadata, annotations and other attributes for a specific labeling task. patch: Update task Update the attributes of an existing labeling task. delete: Delete task Delete a task in L...
class TaskAPI(generics.RetrieveUpdateDestroyAPIView):
""" get: Get task by ID Get task data, metadata, annotations and other attributes for a specific labeling task. patch: Update task Update the attributes of an existing labeling task. delete: Delete task Delete a task in Label Studio. This action cannot be undone! """ ...
get(self, request, *args, **kwargs): return super(TaskListAPI, self).get(request, *args, **kwargs) def get_serializer_context(self): context = super(TaskListAPI, self).get_serializer_context() project_id = self.request.data.get('project') if project_id: context['project...
156
156
522
12
144
mp-pinheiro/label-studio
label_studio/tasks/api.py
Python
TaskAPI
TaskAPI
70
133
70
70
93471592f34092eee7a5dfacefba0d9cc4569382
bigcode/the-stack
train
5dd4b97987862a817986a8ac
train
class
class AnnotationsListAPI(RequestDebugLogMixin, generics.ListCreateAPIView): """ get: Get all task annotations List all annotations for a task. post: Create new annotation Add annotations to a task like an annotator does. """ parser_classes = (JSONParser, FormParser, MultiPartParse...
class AnnotationsListAPI(RequestDebugLogMixin, generics.ListCreateAPIView):
""" get: Get all task annotations List all annotations for a task. post: Create new annotation Add annotations to a task like an annotator does. """ parser_classes = (JSONParser, FormParser, MultiPartParser) # Be careful: order of Permission Classes is important! It's lazy cal...
task = annotation.task task.save() # refresh task metrics return super(AnnotationAPI, self).update(request, *args, **kwargs) @swagger_auto_schema(tags=['Annotations']) def get(self, request, *args, **kwargs): return super(AnnotationAPI, self).get(request, *args, **kwargs) ...
220
221
739
16
204
mp-pinheiro/label-studio
label_studio/tasks/api.py
Python
AnnotationsListAPI
AnnotationsListAPI
225
303
225
225
f04a9d78f8da4ccde012d1df2426d0c695396ce9
bigcode/the-stack
train
0ced1cba7792fc2bc94fae75
train
class
class TaskAPIViewTaskPermission(BaseRulesPermission): perm = 'tasks.view_task'
class TaskAPIViewTaskPermission(BaseRulesPermission):
perm = 'tasks.view_task'
import bool_from_request from tasks.serializers import ( TaskSerializer, AnnotationSerializer, TaskSimpleSerializer, PredictionSerializer, TaskWithAnnotationsAndPredictionsAndDraftsSerializer, AnnotationDraftSerializer) from projects.models import Project logger = logging.getLogger(__name__) class TaskAPIView...
64
64
17
9
55
mp-pinheiro/label-studio
label_studio/tasks/api.py
Python
TaskAPIViewTaskPermission
TaskAPIViewTaskPermission
33
34
33
33
5e7f1418a656c4bc2cff1b20f9805f86efe43fe0
bigcode/the-stack
train
1264700628ae2f2cb4a99571
train
class
class AnnotationAPI(RequestDebugLogMixin, generics.RetrieveUpdateDestroyAPIView): """ get: Get annotation by its ID Retrieve a specific annotation for a task. patch: Update annotation Update existing attributes on an annotation. delete: Delete annotation Delete an annotatio...
class AnnotationAPI(RequestDebugLogMixin, generics.RetrieveUpdateDestroyAPIView):
""" get: Get annotation by its ID Retrieve a specific annotation for a task. patch: Update annotation Update existing attributes on an annotation. delete: Delete annotation Delete an annotation. This action can't be undone! """ parser_classes = (JSONParser, FormPar...
.kwargs['pk'], 'tasks.change_task') # validate data from annotation annotation = AnnotationSerializer(data=request.data) annotation.is_valid(raise_exception=True) # set annotator last activity user = request.user user.activity_at = timezone.now() user.save() ...
129
129
430
16
113
mp-pinheiro/label-studio
label_studio/tasks/api.py
Python
AnnotationAPI
AnnotationAPI
168
222
168
168
57feda5de0009747db8e832b80e338c0d403ad73
bigcode/the-stack
train
d475de9071f291b2677607a8
train
class
class TaskAPIChangeProjectPermission(BaseRulesPermission): perm = 'projects.change_project'
class TaskAPIChangeProjectPermission(BaseRulesPermission):
perm = 'projects.change_project'
TaskSimpleSerializer, PredictionSerializer, TaskWithAnnotationsAndPredictionsAndDraftsSerializer, AnnotationDraftSerializer) from projects.models import Project logger = logging.getLogger(__name__) class TaskAPIViewTaskPermission(BaseRulesPermission): perm = 'tasks.view_task' class TaskAPIChangeProjectPermi...
64
64
18
10
54
mp-pinheiro/label-studio
label_studio/tasks/api.py
Python
TaskAPIChangeProjectPermission
TaskAPIChangeProjectPermission
37
38
37
37
8866dca0d54e09807390bb624e614e3f5baabf4a
bigcode/the-stack
train
1ba0d374d0848571e8d12ace
train
class
class TaskListAPI(generics.ListCreateAPIView): """ post: Create task Create a new labeling task in Label Studio. """ parser_classes = (JSONParser, FormParser, MultiPartParser) permission_classes = (IsAuthenticated, ) queryset = Task.objects.all() serializer_class = TaskSerializer ...
class TaskListAPI(generics.ListCreateAPIView):
""" post: Create task Create a new labeling task in Label Studio. """ parser_classes = (JSONParser, FormParser, MultiPartParser) permission_classes = (IsAuthenticated, ) queryset = Task.objects.all() serializer_class = TaskSerializer @swagger_auto_schema(auto_schema=None) d...
sSerializer, AnnotationDraftSerializer) from projects.models import Project logger = logging.getLogger(__name__) class TaskAPIViewTaskPermission(BaseRulesPermission): perm = 'tasks.view_task' class TaskAPIChangeProjectPermission(BaseRulesPermission): perm = 'projects.change_project' class TaskListAPI(gener...
67
67
225
11
56
mp-pinheiro/label-studio
label_studio/tasks/api.py
Python
TaskListAPI
TaskListAPI
41
67
41
41
a9f0220ab1e71934173676513dbb77e05d77714e
bigcode/the-stack
train
e5b0d72ad047087d194ebc76
train
class
class TaskCancelAPI(APIView): """ post: Cancel Task Set a labeling task as cancelled or skipped. """ swagger_schema = None parser_classes = (JSONParser, FormParser, MultiPartParser) permission_classes = (IsAuthenticated,) serializer_class = TaskSerializer def post(self, reques...
class TaskCancelAPI(APIView):
""" post: Cancel Task Set a labeling task as cancelled or skipped. """ swagger_schema = None parser_classes = (JSONParser, FormParser, MultiPartParser) permission_classes = (IsAuthenticated,) serializer_class = TaskSerializer def post(self, request, *args, **kwargs): #...
): return super(TaskAPI, self).delete(request, *args, **kwargs) @swagger_auto_schema(auto_schema=None) def put(self, request, *args, **kwargs): return super(TaskAPI, self).put(request, *args, **kwargs) class TaskCancelAPI(APIView):
64
64
211
7
57
mp-pinheiro/label-studio
label_studio/tasks/api.py
Python
TaskCancelAPI
TaskCancelAPI
136
165
136
136
4cb8136c0b507ae58558a0d646f95cca34bb1939
bigcode/the-stack
train
ac8b9610abc6ae500b5a65ab
train
class
class AnnotationDraftAPI(RequestDebugLogMixin, generics.RetrieveUpdateDestroyAPIView): parser_classes = (JSONParser, MultiPartParser, FormParser) permission_classes = (TaskAPIViewTaskPermission, ) serializer_class = AnnotationDraftSerializer queryset = AnnotationDraft.objects.all() swagger_schema =...
class AnnotationDraftAPI(RequestDebugLogMixin, generics.RetrieveUpdateDestroyAPIView):
parser_classes = (JSONParser, MultiPartParser, FormParser) permission_classes = (TaskAPIViewTaskPermission, ) serializer_class = AnnotationDraftSerializer queryset = AnnotationDraft.objects.all() swagger_schema = None
{user} is going to create draft for task={task_id}, annotation={annotation_id}') serializer.save( task_id=self.kwargs['pk'], annotation_id=annotation_id, user=self.request.user ) class AnnotationDraftAPI(RequestDebugLogMixin, generics.RetrieveUpdateDestroyAPIView):
64
64
65
17
47
mp-pinheiro/label-studio
label_studio/tasks/api.py
Python
AnnotationDraftAPI
AnnotationDraftAPI
326
332
326
327
f5585814fe8d12bf96a0954168aa43ebe7973583
bigcode/the-stack
train
e863c5fa07e37151de11c2a1
train
class
class AnnotationDraftListAPI(RequestDebugLogMixin, generics.ListCreateAPIView): parser_classes = (JSONParser, MultiPartParser, FormParser) permission_classes = (TaskAPIViewTaskPermission, ) serializer_class = AnnotationDraftSerializer queryset = AnnotationDraft.objects.all() swagger_schema = None ...
class AnnotationDraftListAPI(RequestDebugLogMixin, generics.ListCreateAPIView):
parser_classes = (JSONParser, MultiPartParser, FormParser) permission_classes = (TaskAPIViewTaskPermission, ) serializer_class = AnnotationDraftSerializer queryset = AnnotationDraft.objects.all() swagger_schema = None def perform_create(self, serializer): task_id = self.kwargs['pk'] ...
.data.get('draft_id') if draft_id is not None: logger.debug(f'Remove draft {draft_id} after creating annotation {annotation.id}') AnnotationDraft.objects.filter(id=draft_id).delete() return annotation class AnnotationDraftListAPI(RequestDebugLogMixin, generics.ListCreateAPIView)...
64
64
154
16
47
mp-pinheiro/label-studio
label_studio/tasks/api.py
Python
AnnotationDraftListAPI
AnnotationDraftListAPI
306
323
306
307
71587d8b0530ca5a952987251a717de8d3eea1df
bigcode/the-stack
train
97a8667785eb34ee9a53a6f1
train
class
class Transcoder(CommonAudioProcessor): """ Transcoding processing steps for processed audio """ name = 'transcode' description = 'Re-transcode audio' @classmethod def media_is_eligible(cls, entry=None, state=None): if not state: state = entry.state return state ...
class Transcoder(CommonAudioProcessor):
""" Transcoding processing steps for processed audio """ name = 'transcode' description = 'Re-transcode audio' @classmethod def media_is_eligible(cls, entry=None, state=None): if not state: state = entry.state return state in 'processed' @classmethod def...
, fft_size=None, medium_width=None): self.common_setup() if file == 'thumb': self.generate_thumb(size=thumb_size) elif file == 'spectrogram': self.create_spectrogram(max_width=medium_width, fft_size=fft_size) class Transcoder(CommonAudioProcessor):
64
64
178
7
57
paulproteus/mediagoblin-fork
mediagoblin/media_types/audio/processing.py
Python
Transcoder
Transcoder
336
368
336
336
e16dd80aababbab28a76b474c436a4472893b7e9
bigcode/the-stack
train
472ca9ada3e74eb9ea349470
train
function
def sniff_handler(media_file, filename): _log.info('Sniffing {0}'.format(MEDIA_TYPE)) try: transcoder = AudioTranscoder() data = transcoder.discover(media_file.name) except BadMediaFail: _log.debug('Audio discovery raised BadMediaFail') return None if data.is_audio is Tr...
def sniff_handler(media_file, filename):
_log.info('Sniffing {0}'.format(MEDIA_TYPE)) try: transcoder = AudioTranscoder() data = transcoder.discover(media_file.name) except BadMediaFail: _log.debug('Audio discovery raised BadMediaFail') return None if data.is_audio is True and data.is_video is False: re...
_from_args, get_process_filename, store_public, copy_original) from mediagoblin.media_types.audio.transcoders import ( AudioTranscoder, AudioThumbnailer) _log = logging.getLogger(__name__) MEDIA_TYPE = 'mediagoblin.media_types.audio' def sniff_handler(media_file, filename):
64
64
91
8
56
paulproteus/mediagoblin-fork
mediagoblin/media_types/audio/processing.py
Python
sniff_handler
sniff_handler
36
48
36
36
5856728e7f6b1d58ea67a302a64623e4cb562372
bigcode/the-stack
train
62eeee12abde57ce721dc203
train
class
class Resizer(CommonAudioProcessor): """ Thumbnail and spectogram resizing process steps for processed audio """ name = 'resize' description = 'Resize thumbnail or spectogram' thumb_size = 'thumb_size' @classmethod def media_is_eligible(cls, entry=None, state=None): """ ...
class Resizer(CommonAudioProcessor):
""" Thumbnail and spectogram resizing process steps for processed audio """ name = 'resize' description = 'Resize thumbnail or spectogram' thumb_size = 'thumb_size' @classmethod def media_is_eligible(cls, entry=None, state=None): """ Determine if this media entry is elig...
_from_args( args, ['quality', 'fft_size', 'thumb_size', 'medium_width']) def process(self, quality=None, fft_size=None, thumb_size=None, medium_width=None): self.common_setup() self.transcode(quality=quality) self.copy_original() self...
102
102
340
7
95
paulproteus/mediagoblin-fork
mediagoblin/media_types/audio/processing.py
Python
Resizer
Resizer
275
333
275
275
3233453d02c4462cd0d1a14dd88a3ec155619db7
bigcode/the-stack
train
21169e1a5b766fe5eba2dbce
train
class
class CommonAudioProcessor(MediaProcessor): """ Provides a base for various audio processing steps """ acceptable_files = ['original', 'best_quality', 'webm_audio'] def common_setup(self): """ Setup the workbench directory and pull down the original file, add the audio_confi...
class CommonAudioProcessor(MediaProcessor):
""" Provides a base for various audio processing steps """ acceptable_files = ['original', 'best_quality', 'webm_audio'] def common_setup(self): """ Setup the workbench directory and pull down the original file, add the audio_config, transcoder, thumbnailer and spectrogram_t...
A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import argparse import logging import os from mediagoblin import mg_globals as mgg ...
256
256
1,144
7
248
paulproteus/mediagoblin-fork
mediagoblin/media_types/audio/processing.py
Python
CommonAudioProcessor
CommonAudioProcessor
51
206
51
51
51f05dfaeb73bc1bb10366ba05ce8c612d5745df
bigcode/the-stack
train
6e80c5f4071ec222c00fa242
train
class
class InitialProcessor(CommonAudioProcessor): """ Initial processing steps for new audio """ name = "initial" description = "Initial processing" @classmethod def media_is_eligible(cls, entry=None, state=None): """ Determine if this media type is eligible for processing ...
class InitialProcessor(CommonAudioProcessor):
""" Initial processing steps for new audio """ name = "initial" description = "Initial processing" @classmethod def media_is_eligible(cls, entry=None, state=None): """ Determine if this media type is eligible for processing """ if not state: state...
create one.') self.create_spectrogram() spectrogram = self.entry.media_files['spectrogram'] spectrogram_filepath = mgg.public_store.get_local_path(spectrogram) self.thumbnailer.thumbnail_spectrogram( spectrogram_filepath, thumb_tmp, tuple(si...
105
105
350
7
98
paulproteus/mediagoblin-fork
mediagoblin/media_types/audio/processing.py
Python
InitialProcessor
InitialProcessor
209
272
209
209
352a8c281433fbdc77656bd609b1bf900aa2980c
bigcode/the-stack
train
7ba87cbfd9e7a530fdbfd65f
train
class
class AudioProcessingManager(ProcessingManager): def __init__(self): super(AudioProcessingManager, self).__init__() self.add_processor(InitialProcessor) self.add_processor(Resizer) self.add_processor(Transcoder)
class AudioProcessingManager(ProcessingManager):
def __init__(self): super(AudioProcessingManager, self).__init__() self.add_processor(InitialProcessor) self.add_processor(Resizer) self.add_processor(Transcoder)
.1..1') return parser @classmethod def args_to_request(cls, args): return request_from_args( args, ['quality']) def process(self, quality=None): self.common_setup() self.transcode(quality=quality) class AudioProcessingManager(ProcessingManager):
64
64
49
8
56
paulproteus/mediagoblin-fork
mediagoblin/media_types/audio/processing.py
Python
AudioProcessingManager
AudioProcessingManager
371
376
371
371
bb8dcb6f1823f34dfd1eed849b377192313fd24a
bigcode/the-stack
train
0d46a61b56f29071954b1c19
train
function
def gsp( nodes: set, ci_tester: CI_Tester, depth: Optional[int] = 4, nruns: int = 5, verbose: bool = False, initial_undirected: Optional[Union[str, UndirectedGraph]] = 'threshold', initial_permutations: Optional[List] = None, fixed_orders=set(), fi...
def gsp( nodes: set, ci_tester: CI_Tester, depth: Optional[int] = 4, nruns: int = 5, verbose: bool = False, initial_undirected: Optional[Union[str, UndirectedGraph]] = 'threshold', initial_permutations: Optional[List] = None, fixed_orders=set(), fi...
""" Estimate the Markov equivalence class of a DAG using the Greedy Sparsest Permutations (GSP) algorithm. Parameters ---------- nodes: Labels of nodes in the graph. ci_tester: A conditional independence tester, which has a method is_ci taking two sets A and B, and a conditionin...
) # === PROCESS OUTPUT learned_intervention_targets = { int(node[1:]): {child for child in est_meta_dag.children_of(node) if not isinstance(child, str)} for node in est_meta_dag.nodes if isinstance(node, str) } learned_intervention_targets = [learned_intervention_targets[i] for...
256
256
1,879
132
123
uhlerlab/graphical_model_learning
graphical_model_learning/algorithms/dag/gsp.py
Python
gsp
gsp
360
538
360
376
8dcc87e1e5fc9990c0d46c62752ab5dc624c93b9
bigcode/the-stack
train
b9f4688b497e6d526f445160
train
function
def min_degree_alg_amat(amat, rnd=True): """ TODO Parameters ---------- TODO Examples -------- TODO """ amat = amat.copy() remaining_nodes = list(range(amat.shape[0])) permutation = [] while remaining_nodes: # === PICK A NODE OF MINIMUM DEGREE curr_a...
def min_degree_alg_amat(amat, rnd=True):
""" TODO Parameters ---------- TODO Examples -------- TODO """ amat = amat.copy() remaining_nodes = list(range(amat.shape[0])) permutation = [] while remaining_nodes: # === PICK A NODE OF MINIMUM DEGREE curr_amat = amat[np.ix_(remaining_nodes, remain...
nbr2, curr_undirected_graph._nodes - {nbr1, nbr2, k}): # # curr_undirected_graph.delete_edge(nbr1, nbr2) # # permutation.append(k) # # return list(reversed(permutation)) def min_degree_alg_amat(amat, rnd=True):
68
68
228
12
56
uhlerlab/graphical_model_learning
graphical_model_learning/algorithms/dag/gsp.py
Python
min_degree_alg_amat
min_degree_alg_amat
226
258
226
226
2baa4156eb141d0515a3ecad6e7e807b0059d82e
bigcode/the-stack
train
dabf2f24749009c7f28bed0f
train
function
def is_icovered( setting_list: List[Dict], i: int, j: int, dag: DAG, invariance_tester: InvarianceTester, ): """ Tell if an edge i->j is I-covered with respect to the invariance tests. True if, for all I s.t. i \in I, the distribution of j given its parents varies be...
def is_icovered( setting_list: List[Dict], i: int, j: int, dag: DAG, invariance_tester: InvarianceTester, ):
""" Tell if an edge i->j is I-covered with respect to the invariance tests. True if, for all I s.t. i \in I, the distribution of j given its parents varies between the observational and interventional data. setting_list: A list of dictionaries that provide meta-information about each setti...
), len(dag_n[1]))) # print(min_dag) return min_dag[0] def is_icovered( setting_list: List[Dict], i: int, j: int, dag: DAG, invariance_tester: InvarianceTester, ):
64
64
205
41
23
uhlerlab/graphical_model_learning
graphical_model_learning/algorithms/dag/gsp.py
Python
is_icovered
is_icovered
739
767
739
745
9dcc3235b55ce334c7150994b94e58f9a74854d0
bigcode/the-stack
train
67b055bcd4308eaf0e3f4027
train
function
def igsp( setting_list: List[Dict], nodes: set, ci_tester: CI_Tester, invariance_tester: InvarianceTester, depth: Optional[int] = 4, nruns: int = 5, initial_undirected: Optional[Union[str, UndirectedGraph]] = 'threshold', initial_permutations: Optional[Lis...
def igsp( setting_list: List[Dict], nodes: set, ci_tester: CI_Tester, invariance_tester: InvarianceTester, depth: Optional[int] = 4, nruns: int = 5, initial_undirected: Optional[Union[str, UndirectedGraph]] = 'threshold', initial_permutations: Optional[Lis...
""" TODO Parameters ---------- TODO Examples -------- TODO """ only_single_node = all(len(setting['interventions']) <= 1 for setting in setting_list) interventions2setting_nums = { frozenset(setting['interventions']): setting_num for setting_num, setting in ...
in covered_arcs2removed_arcs if current_arcs - {(i, j)} | {(j, i)} - rem_arcs not in all_visited_dags ] else: if len(trace) == 0: # reached minimum within search depth break else: # backtrack curre...
256
256
2,113
94
161
uhlerlab/graphical_model_learning
graphical_model_learning/algorithms/dag/gsp.py
Python
igsp
igsp
541
736
541
551
878a0f7093d0eb0d6f75338e1050172c994c83da
bigcode/the-stack
train
73e5307bd741007c9a1b3121
train
function
def perm2dag_subsets(perm, ci_tester, max_subset_size=None): """ Not recommended unless max_subset_size set very small. Not thoroughly tested. """ arcs = set() nodes = set(perm) for i, pi_i in enumerate(perm): for candidate_parent_set in powerset(perm[:i], r_max=max_subset_size): ...
def perm2dag_subsets(perm, ci_tester, max_subset_size=None):
""" Not recommended unless max_subset_size set very small. Not thoroughly tested. """ arcs = set() nodes = set(perm) for i, pi_i in enumerate(perm): for candidate_parent_set in powerset(perm[:i], r_max=max_subset_size): print(candidate_parent_set) if all(ci_tester...
permutation2dag(list(perm), ci_tester) if dag.num_arcs < min_num_arcs: min_dag, min_num_arcs = dag, dag.num_arcs return min_dag def perm2dag_subsets(perm, ci_tester, max_subset_size=None):
64
64
169
18
45
uhlerlab/graphical_model_learning
graphical_model_learning/algorithms/dag/gsp.py
Python
perm2dag_subsets
perm2dag_subsets
152
165
152
152
41fcd06f9e8657a0d04478085adf232d84482858
bigcode/the-stack
train