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
45ecd418241dcee7767375e3
train
class
@mock.patch.object(conductor_utils, 'node_power_action') class ManagerDoSyncPowerStateTestCase(db_base.DbTestCase): def setUp(self): super(ManagerDoSyncPowerStateTestCase, self).setUp() self.service = manager.ConductorManager('hostname', 'test-topic') self.driver = mock.Mock(spec_set=drivers...
@mock.patch.object(conductor_utils, 'node_power_action') class ManagerDoSyncPowerStateTestCase(db_base.DbTestCase):
def setUp(self): super(ManagerDoSyncPowerStateTestCase, self).setUp() self.service = manager.ConductorManager('hostname', 'test-topic') self.driver = mock.Mock(spec_set=drivers_base.BareDriver) self.power = self.driver.power self.node = obj_utils.create_test_node( ...
def test_set_target_raid_config_iface_not_supported(self): # NOTE(jroll): it's impossible for a dynamic driver to have a null # interface (e.g. node.driver.raid), so this instead tests that # if validation fails, we blow up properly. # need a different raid interface and a hardware...
255
256
2,980
27
228
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
ManagerDoSyncPowerStateTestCase
ManagerDoSyncPowerStateTestCase
6,497
6,796
6,497
6,498
3e07e370191a46533eb4d4af1e55bac4be357842
bigcode/the-stack
train
22b07572b86ed55e5e7de224
train
class
@mgr_utils.mock_record_keepalive class MiscTestCase(mgr_utils.ServiceSetUpMixin, mgr_utils.CommonMixIn, db_base.DbTestCase): def test__mapped_to_this_conductor(self): self._start_service() n = db_utils.get_test_node() self.assertTrue(self.service._mapped_to_this_conductor(...
@mgr_utils.mock_record_keepalive class MiscTestCase(mgr_utils.ServiceSetUpMixin, mgr_utils.CommonMixIn, db_base.DbTestCase):
def test__mapped_to_this_conductor(self): self._start_service() n = db_utils.get_test_node() self.assertTrue(self.service._mapped_to_this_conductor( n['uuid'], 'fake-hardware', '')) self.assertFalse(self.service._mapped_to_this_conductor( n['uuid'], 'fake-hard...
) self.assertFalse(mock_get_power_state.called) @mock.patch('ironic.drivers.modules.fake.FakePower.get_power_state') @mock.patch('ironic.drivers.modules.fake.FakePower.validate') def test__do_node_verify_get_state_fails(self, mock_validate, mock_get_powe...
256
256
1,474
33
223
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
MiscTestCase
MiscTestCase
5,015
5,164
5,015
5,017
8811d26352172ca1d1d28c5a6865d76481e82997
bigcode/the-stack
train
92b7f5f2a87e2104ef739869
train
class
@mgr_utils.mock_record_keepalive @mock.patch.object(n_flat.FlatNetwork, 'validate', autospec=True) class VifTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): def setUp(self): super(VifTestCase, self).setUp() self.vif = {'id': 'fake'} @mock.patch.object(n_flat.FlatNetwork, 'vif_list', ...
@mgr_utils.mock_record_keepalive @mock.patch.object(n_flat.FlatNetwork, 'validate', autospec=True) class VifTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def setUp(self): super(VifTestCase, self).setUp() self.vif = {'id': 'fake'} @mock.patch.object(n_flat.FlatNetwork, 'vif_list', autospec=True) def test_vif_list(self, mock_list, mock_valid): mock_list.return_value = ['VIF_ID'] node = obj_utils.create_test_node(self.context, d...
ParameterValue, exc.exc_info[0]) @mock.patch.object(fake.FakeManagement, 'validate', autospec=True) def test_inject_nmi_validate_missing_param(self, mock_val): node = obj_utils.create_test_node(self.context, driver='fake-hardware') mock_val.side_effect = exception.MissingParameterValue('error')...
256
256
1,642
43
213
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
VifTestCase
VifTestCase
6,095
6,230
6,095
6,098
c932214cd6240d6258da9f6f95db75933c3c5807
bigcode/the-stack
train
8e1880d790f3d49f23993f72
train
class
@mgr_utils.mock_record_keepalive class CheckTimeoutsTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): @mock.patch('ironic.drivers.modules.fake.FakeDeploy.clean_up') def test__check_deploy_timeouts(self, mock_cleanup): self._start_service() CONF.set_override('deploy_callback_timeout', 1,...
@mgr_utils.mock_record_keepalive class CheckTimeoutsTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): @mock.patch('ironic.drivers.modules.fake.FakeDeploy.clean_up')
def test__check_deploy_timeouts(self, mock_cleanup): self._start_service() CONF.set_override('deploy_callback_timeout', 1, group='conductor') node = obj_utils.create_test_node( self.context, driver='fake-hardware', provision_state=states.DEPLOYWAIT, target...
get_node_next_deploy_steps(skip=False) def test__get_node_next_deploy_steps_unset_deploy_step(self): driver_internal_info = {'deploy_steps': self.deploy_steps, 'deploy_step_index': None} node = obj_utils.create_test_node( self.context, driver='fake-hardwa...
246
246
820
45
201
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
CheckTimeoutsTestCase
CheckTimeoutsTestCase
2,841
2,919
2,841
2,843
b14d584f8c6322b538bd78ed7e1efb3bf6e18f0d
bigcode/the-stack
train
64c3ff003219084128fbff19
train
class
@mock.patch.object(task_manager, 'acquire') @mock.patch.object(manager.ConductorManager, '_mapped_to_this_conductor') @mock.patch.object(dbapi.IMPL, 'get_nodeinfo_list') class ManagerPowerRecoveryTestCase(mgr_utils.CommonMixIn, db_base.DbTestCase): def setUp(self): super(M...
@mock.patch.object(task_manager, 'acquire') @mock.patch.object(manager.ConductorManager, '_mapped_to_this_conductor') @mock.patch.object(dbapi.IMPL, 'get_nodeinfo_list') class ManagerPowerRecoveryTestCase(mgr_utils.CommonMixIn, db_base.DbTestCase):
def setUp(self): super(ManagerPowerRecoveryTestCase, self).setUp() self.service = manager.ConductorManager('hostname', 'test-topic') self.service.dbapi = self.dbapi self.driver = mock.Mock(spec_set=drivers_base.BareDriver) self.power = self.driver.power self.task = mo...
, except for node # not mapped to this conductor self.assertEqual(len(nodes) - 1, sleep_mock.call_count) get_nodeinfo_mock.assert_called_once_with( columns=self.columns, filters=self.filters) mapped_calls = [mock.call(x.uuid, x.driver, ...
256
256
1,482
62
194
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
ManagerPowerRecoveryTestCase
ManagerPowerRecoveryTestCase
7,043
7,201
7,043
7,047
d3972b06f734858f1147435e76af2f479284731f
bigcode/the-stack
train
2b8d051bf7d7a04fd4bb2ed1
train
class
@mgr_utils.mock_record_keepalive class DoNodeCleanTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): def setUp(self): super(DoNodeCleanTestCase, self).setUp() self.config(automated_clean=True, group='conductor') self.power_update = { 'step': 'update_firmware', 'priority':...
@mgr_utils.mock_record_keepalive class DoNodeCleanTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def setUp(self): super(DoNodeCleanTestCase, self).setUp() self.config(automated_clean=True, group='conductor') self.power_update = { 'step': 'update_firmware', 'priority': 10, 'interface': 'power'} self.deploy_update = { 'step': 'update_firmware', 'priority': ...
test__do_node_clean_abort(self): self._test__do_node_clean_abort(None) def test__do_node_clean_abort_with_step_name(self): self._test__do_node_clean_abort('foo') @mock.patch.object(fake.FakeDeploy, 'tear_down_cleaning', autospec=True) def test__do_node_clean_abort_tear_down_fail(self, tea...
256
256
11,802
28
228
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
DoNodeCleanTestCase
DoNodeCleanTestCase
3,356
4,606
3,356
3,357
d2fc19db56e5a4c1154f9e194c21f1dcf2989369
bigcode/the-stack
train
38613065e2017a0083e5dc72
train
class
@mgr_utils.mock_record_keepalive class ContinueNodeDeployTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): def setUp(self): super(ContinueNodeDeployTestCase, self).setUp() self.deploy_start = { 'step': 'deploy_start', 'priority': 50, 'interface':...
@mgr_utils.mock_record_keepalive class ContinueNodeDeployTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def setUp(self): super(ContinueNodeDeployTestCase, self).setUp() self.deploy_start = { 'step': 'deploy_start', 'priority': 50, 'interface': 'deploy'} self.deploy_end = { 'step': 'deploy_end', 'priority': 20, 'interface': 'deploy'} self.deploy_steps = [self.dep...
target_provision_state=tgt_prv_state, last_error=None, driver='fake-hardware') self._start_service() with mock.patch.object(self.service, '_spawn_worker', autospec=True) as mock_spawn: ...
255
256
2,167
29
226
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
ContinueNodeDeployTestCase
ContinueNodeDeployTestCase
1,755
1,982
1,755
1,757
44af957d2d90152191aecabe9398baede4b4404f
bigcode/the-stack
train
a86be66dd3ceddf3c3058eee
train
class
@mgr_utils.mock_record_keepalive class DoNodeTearDownTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): def test_do_node_tear_down_invalid_state(self): self._start_service() # test node.provision_state is incorrect for tear_down node = obj_utils.create_test_node(self.context, driver=...
@mgr_utils.mock_record_keepalive class DoNodeTearDownTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def test_do_node_tear_down_invalid_state(self): self._start_service() # test node.provision_state is incorrect for tear_down node = obj_utils.create_test_node(self.context, driver='fake-hardware', provision_state=states.AVAILABLE) exc = self....
mock_clean_up): self._start_service() CONF.set_override('rescue_callback_timeout', 1, group='conductor') tgt_prov_state = states.RESCUE node = obj_utils.create_test_node( self.context, driver='fake-hardware', rescue_interface...
256
256
2,444
30
226
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
DoNodeTearDownTestCase
DoNodeTearDownTestCase
2,922
3,159
2,922
2,923
6806d1dae28d5d2b3332bab2a93c029babb04156
bigcode/the-stack
train
a99d0182929849f0b1d1af0f
train
class
@mgr_utils.mock_record_keepalive class NodeTraitsTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): def setUp(self): super(NodeTraitsTestCase, self).setUp() self.traits = ['trait1', 'trait2'] self.node = obj_utils.create_test_node(self.context, ...
@mgr_utils.mock_record_keepalive class NodeTraitsTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def setUp(self): super(NodeTraitsTestCase, self).setUp() self.traits = ['trait1', 'trait2'] self.node = obj_utils.create_test_node(self.context, driver='fake-hardware') def test_add_node_traits(self): self.service.add_node_traits(se...
('Boo') exc = self.assertRaises(messaging.rpc.ExpectedException, self.service.update_volume_target, self.context, volume_target) # Compare true exception hidden by @messaging.expected_exceptions self.assertEqual(...
256
256
1,014
27
229
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
NodeTraitsTestCase
NodeTraitsTestCase
9,262
9,356
9,262
9,264
04f0930efe59675a5486e30d6439b780bada62d8
bigcode/the-stack
train
21a4c36d4e3285dea06fb232
train
class
@mgr_utils.mock_record_keepalive @mock.patch.object(images, 'is_whole_disk_image') class ServiceDoNodeDeployTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): def test_do_node_deploy_invalid_state(self, mock_iwdi): mock_iwdi.return_value = False self._start_...
@mgr_utils.mock_record_keepalive @mock.patch.object(images, 'is_whole_disk_image') class ServiceDoNodeDeployTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def test_do_node_deploy_invalid_state(self, mock_iwdi): mock_iwdi.return_value = False self._start_service() # test that node deploy fails if the node is already provisioned node = obj_utils.create_test_node( self.context, driver='fake-hardware', provision_sta...
.assert_called_once_with(mock.ANY, 'vendor', driver_name='fake-hardware') # Compare true exception hidden by @messaging.expected_exceptions self.assertEqual(exception.NoValidDefaultForInterface, exc.exc_info[0]) @mock.patch.obj...
256
256
5,277
43
213
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
ServiceDoNodeDeployTestCase
ServiceDoNodeDeployTestCase
1,265
1,752
1,265
1,268
be184c48f2f997623345836c838714fe42e4c028
bigcode/the-stack
train
53023eb0f9b5e1a669f530f9
train
class
@mock.patch.object(waiters, 'wait_for_all') @mock.patch.object(manager.ConductorManager, '_spawn_worker') @mock.patch.object(manager.ConductorManager, '_sync_power_state_nodes_task') class ParallelPowerSyncTestCase(mgr_utils.CommonMixIn, db_base.DbTestCase): def setUp(self): super(ParallelPowerSyncTestCase...
@mock.patch.object(waiters, 'wait_for_all') @mock.patch.object(manager.ConductorManager, '_spawn_worker') @mock.patch.object(manager.ConductorManager, '_sync_power_state_nodes_task') class ParallelPowerSyncTestCase(mgr_utils.CommonMixIn, db_base.DbTestCase):
def setUp(self): super(ParallelPowerSyncTestCase, self).setUp() self.service = manager.ConductorManager('hostname', 'test-topic') def test__sync_power_states_9_nodes_8_workers( self, sync_mock, spawn_mock, waiter_mock): CONF.set_override('sync_power_state_workers', 8, group...
_utils.mock_record_keepalive class ManagerTestHardwareTypeProperties(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): def _check_hardware_type_properties(self, hardware_type, expected): self.config(enabled_hardware_types=[hardware_type]) self.hardware_type =...
225
225
750
60
165
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
ParallelPowerSyncTestCase
ParallelPowerSyncTestCase
7,531
7,614
7,531
7,535
1ccb4cfcae2b5eddac90ebc8f44c9681d5f3dd83
bigcode/the-stack
train
9795890d6deaf2605628f6d1
train
class
@mgr_utils.mock_record_keepalive class DoProvisioningActionTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): @mock.patch('ironic.conductor.manager.ConductorManager._spawn_worker', autospec=True) def test_do_provisioning_action_worker_pool_full(self, mo...
@mgr_utils.mock_record_keepalive class DoProvisioningActionTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): @mock.patch('ironic.conductor.manager.ConductorManager._spawn_worker', autospec=True)
def test_do_provisioning_action_worker_pool_full(self, mock_spawn): prv_state = states.MANAGEABLE tgt_prv_state = states.NOSTATE node = obj_utils.create_test_node(self.context, driver='fake-hardware', provision_state=prv_state, ...
driver_internal_info=driver_internal_info, last_error=None) self._start_service() mock_spawn.side_effect = exception.NoFreeConductorWorker() exc = self.assertRaises(messaging.rpc.ExpectedException, self.service.do_node_tear_down, ...
256
256
1,326
52
204
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
DoProvisioningActionTestCase
DoProvisioningActionTestCase
3,162
3,295
3,162
3,166
43622f6593a58f1410e6d3751b18bcee51ecd9ba
bigcode/the-stack
train
b932eb9b902aac524d2c6184
train
class
@mock.patch.object(task_manager, 'acquire') @mock.patch.object(manager.ConductorManager, '_mapped_to_this_conductor') @mock.patch.object(dbapi.IMPL, 'get_nodeinfo_list') class ManagerCheckDeployTimeoutsTestCase(mgr_utils.CommonMixIn, db_base.DbTestCase): def setUp(self): ...
@mock.patch.object(task_manager, 'acquire') @mock.patch.object(manager.ConductorManager, '_mapped_to_this_conductor') @mock.patch.object(dbapi.IMPL, 'get_nodeinfo_list') class ManagerCheckDeployTimeoutsTestCase(mgr_utils.CommonMixIn, db_base.DbTestCase):
def setUp(self): super(ManagerCheckDeployTimeoutsTestCase, self).setUp() self.config(deploy_callback_timeout=300, group='conductor') self.service = manager.ConductorManager('hostname', 'test-topic') self.service.dbapi = self.dbapi self.node = self._create_node(provision_stat...
_nodeinfo_list_response() mapped_mock.return_value = True acquire_mock.side_effect = self._get_acquire_side_effect(self.task) self.power.get_power_state.return_value = states.ERROR self.service._power_failure_recovery(self.context) get_nodeinfo_mock.assert_called_once_with( ...
256
256
2,129
64
192
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
ManagerCheckDeployTimeoutsTestCase
ManagerCheckDeployTimeoutsTestCase
7,204
7,435
7,204
7,208
22810b58f2961f90fddba35dab9795a99697c96a
bigcode/the-stack
train
ee8247a78f206a5d84bb65e2
train
class
@mgr_utils.mock_record_keepalive class DoNodeCleanAbortTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): @mock.patch.object(fake.FakeDeploy, 'tear_down_cleaning', autospec=True) def _test__do_node_clean_abort(self, step_name, tear_mock): node = obj_utils.create_te...
@mgr_utils.mock_record_keepalive class DoNodeCleanAbortTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): @mock.patch.object(fake.FakeDeploy, 'tear_down_cleaning', autospec=True)
def _test__do_node_clean_abort(self, step_name, tear_mock): node = obj_utils.create_test_node( self.context, driver='fake-hardware', provision_state=states.CLEANFAIL, target_provision_state=states.AVAILABLE, clean_step={'step': 'foo', 'abortable': True}, ...
_step={'step': 'foo', 'abortable': False}) self._start_service() self.service.do_provisioning_action(self.context, node.uuid, 'abort') node.refresh() # Assert the current clean step was marked to be aborted later self.assertIn('abort_after', node.clean_step) self.assertT...
167
167
557
50
117
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
DoNodeCleanAbortTestCase
DoNodeCleanAbortTestCase
3,298
3,353
3,298
3,301
5768eaaaa9e78b69c2cc1cd5c79dc9fe1b1a3b2e
bigcode/the-stack
train
34ee7c4aa90ff26df2f00a94
train
class
@mgr_utils.mock_record_keepalive class UpdateNodeTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): def test_update_node(self): node = obj_utils.create_test_node(self.context, driver='fake-hardware', extra={'test': 'one'}) # check that ManagerServic...
@mgr_utils.mock_record_keepalive class UpdateNodeTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def test_update_node(self): node = obj_utils.create_test_node(self.context, driver='fake-hardware', extra={'test': 'one'}) # check that ManagerService.update_node actually updates the node node.extra = {'test': 'two'} res = self.service.upda...
, driver='fake-hardware', extra={'test': 'one'}) res = self.service.create_node(self.context, node) self.assertEqual({'test': 'one'}, res['extra']) res = objects.Node.get_by_uuid(self.context, node['uuid']) self.assertEqual({'test': 'one'}, res['e...
255
256
3,660
27
228
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
UpdateNodeTestCase
UpdateNodeTestCase
473
895
473
474
f5aa8677cd80f0dfdf21ed6415d505477af61141
bigcode/the-stack
train
4aa669cb74e02b1ff00549c3
train
class
@mgr_utils.mock_record_keepalive class DoNodeInspectAbortTestCase(mgr_utils.CommonMixIn, mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): @mock.patch.object(manager, 'LOG') @mock.patch('ironic.drivers.modules.fake.FakeInspect.abort') @mock.p...
@mgr_utils.mock_record_keepalive class DoNodeInspectAbortTestCase(mgr_utils.CommonMixIn, mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): @mock.patch.object(manager, 'LOG') @mock.patch('ironic.drivers.modules.fake.FakeInspect.abort') @mock.p...
def test_do_inspect_abort_interface_not_support(self, mock_acquire, mock_abort, mock_log): node = obj_utils.create_test_node(self.context, driver='fake-hardware', provision...
raitList.get_by_node_id(self.context, self.node.id) self.assertEqual(self.traits, [trait.trait for trait in traits]) def test_remove_node_traits_node_locked(self): self._test_remove_node_traits_exception(exception.NodeLocked) def test_remove_node_traits_node_not_found(self): self._test...
182
182
608
80
102
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
DoNodeInspectAbortTestCase
DoNodeInspectAbortTestCase
9,359
9,417
9,359
9,365
f559f8c354cdb03b67f384f87d605a538434d470
bigcode/the-stack
train
4b24a732d53c4f1ebb6410c5
train
class
@mgr_utils.mock_record_keepalive class DestroyPortTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase): def test_destroy_port(self): node = obj_utils.create_test_node(self.context, driver='fake-hardware') port = obj_utils.create_test_port(self.context, ...
@mgr_utils.mock_record_keepalive class DestroyPortTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def test_destroy_port(self): node = obj_utils.create_test_node(self.context, driver='fake-hardware') port = obj_utils.create_test_port(self.context, node_id=node.id) self.service.destroy_port(self.context, port) self.assertRaises(exception.P...
') # Use the same nodes/tasks to make life easier in the tests # here get_nodeinfo_mock.return_value = ( self._get_nodeinfo_list_response([self.node] * 3)) mapped_mock.return_value = True acquire_mock.side_effect = ( self._get_acquire_side_effect([self.t...
226
226
754
27
199
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
DestroyPortTestCase
DestroyPortTestCase
8,283
8,368
8,283
8,284
dff714cf47e14a06b20623442a041e604ee83a16
bigcode/the-stack
train
4f23cb7eeeb75b942d6ee223
train
class
@mgr_utils.mock_record_keepalive class RaidHardwareTypeTestCases(RaidTestCases): driver_name = 'fake-hardware' raid_interface = 'fake' def test_get_raid_logical_disk_properties_iface_not_supported(self): # NOTE(jroll) we don't run this test as get_logical_disk_properties # is supported on ...
@mgr_utils.mock_record_keepalive class RaidHardwareTypeTestCases(RaidTestCases):
driver_name = 'fake-hardware' raid_interface = 'fake' def test_get_raid_logical_disk_properties_iface_not_supported(self): # NOTE(jroll) we don't run this test as get_logical_disk_properties # is supported on all RAID implementations, and we cannot have a # null interface for a hard...
bar'} self.node.save() exc = self.assertRaises( messaging.rpc.ExpectedException, self.service.set_target_raid_config, self.context, self.node.uuid, raid_config) self.node.refresh() self.assertEqual({'foo': 'bar'}, self.node.target_raid_config) ...
96
96
322
19
77
DhuldevValekar3/ironic
ironic/tests/unit/conductor/test_manager.py
Python
RaidHardwareTypeTestCases
RaidHardwareTypeTestCases
6,463
6,494
6,463
6,465
b56befa5c1e11c8203792e447ed2bb6dc6900b14
bigcode/the-stack
train
8232301ffc95e4cda6934d07
train
class
class BaseDualPseudoIntegrator(BaseCommon): formulation = 'dual' aux_nregs = 0 def __init__(self, backend, systemcls, rallocs, mesh, initsoln, cfg, stepper_coeffs, dt): self.backend = backend self.rallocs = rallocs self.isrestart = initsoln is not None self....
class BaseDualPseudoIntegrator(BaseCommon):
formulation = 'dual' aux_nregs = 0 def __init__(self, backend, systemcls, rallocs, mesh, initsoln, cfg, stepper_coeffs, dt): self.backend = backend self.rallocs = rallocs self.isrestart = initsoln is not None self.cfg = cfg self._dt = dt sec...
# -*- coding: utf-8 -*- from collections import defaultdict from configparser import NoOptionError from pyfr.integrators.base import BaseCommon from pyfr.util import proxylist class BaseDualPseudoIntegrator(BaseCommon):
47
256
855
8
38
YuWangTAMU/PyFR
pyfr/integrators/dual/pseudo/base.py
Python
BaseDualPseudoIntegrator
BaseDualPseudoIntegrator
10
102
10
10
3bafc271720003d77af1210e53ee2db461061495
bigcode/the-stack
train
dcaffadd22b3b1ec4c1b4a23
train
class
class EventHandler: def __init__(self, fname, suffix = '_events'): # Removing extension and suffix (if present) fname = re.sub( r'\.tsv$', '', fname ) fname = re.sub( suffix + '$', '', fname ) self.__filename = '{}{}.tsv'.format(fname, suffix) self.trials = [] # First line sh...
class EventHandler:
def __init__(self, fname, suffix = '_events'): # Removing extension and suffix (if present) fname = re.sub( r'\.tsv$', '', fname ) fname = re.sub( suffix + '$', '', fname ) self.__filename = '{}{}.tsv'.format(fname, suffix) self.trials = [] # First line should be the header ...
import os import re class EventHandler:
10
64
196
4
5
InstitutoDOr/bids_events
bids_events/Events.py
Python
EventHandler
EventHandler
3
26
3
3
f7a1881ca385e213e8ec56bb6e11ace71752f35d
bigcode/the-stack
train
f8eaaffbea4ccb1578efa06d
train
class
class EnabledStatus(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("enabled", 1), ("disabled", 2))
class EnabledStatus(TextualConvention, Integer32):
status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("enabled", 1), ("disabled", 2))
-22 00:00',)) if mibBuilder.loadTexts: hh3cMpm.setLastUpdated('200503220000Z') if mibBuilder.loadTexts: hh3cMpm.setOrganization('Hangzhou H3C Tech. Co., Ltd.') class EnabledStatus(TextualConvention, Integer32):
64
64
56
10
54
agustinhenze/mibs.snmplabs.com
pysnmp/HH3C-MPM-MIB.py
Python
EnabledStatus
EnabledStatus
21
24
21
21
64cdc4c22d199acc3237114fe30c691c618fd0b9
bigcode/the-stack
train
5088c7c104b18d8f0018041c
train
class
@mock.patch.object(nova_client, "Client") class TestNovaClient(SampleData): def __init__(self, *args, **kwargs): super(TestNovaClient, self).__init__(*args, **kwargs) self.nova_obj = openstack_driver.NovaClient(cfg.CONF) @mock.patch.object(identity_client, "Client") def test_get_image_id(s...
@mock.patch.object(nova_client, "Client") class TestNovaClient(SampleData):
def __init__(self, *args, **kwargs): super(TestNovaClient, self).__init__(*args, **kwargs) self.nova_obj = openstack_driver.NovaClient(cfg.CONF) @mock.patch.object(identity_client, "Client") def test_get_image_id(self, key_obj, mock_obj): instance = mock_obj.return_value key...
_admin_token() self.assertTrue(retval) mock_obj.assert_called_once_with(auth_url=self.AUTH_URL, password='neutron_pass', tenant_id=None, tenant_name='service', ...
256
256
1,103
19
237
ashutosh-mishra/my-test
gbpservice/neutron/tests/unit/nfp/orchestrator/test_openstack_driver.py
Python
TestNovaClient
TestNovaClient
100
229
100
102
3349c9a1bac9488fc2145539a2eb0051278b7e75
bigcode/the-stack
train
fc13f07dca21e7a87d49234b
train
class
@mock.patch.object(identity_client, "Client") class TestKeystoneClient(SampleData): def __init__(self, *args, **kwargs): super(TestKeystoneClient, self).__init__(*args, **kwargs) self.keystone_obj = openstack_driver.KeystoneClient(cfg.CONF) def setUp(self): cfg.CONF.set_override('admin...
@mock.patch.object(identity_client, "Client") class TestKeystoneClient(SampleData):
def __init__(self, *args, **kwargs): super(TestKeystoneClient, self).__init__(*args, **kwargs) self.keystone_obj = openstack_driver.KeystoneClient(cfg.CONF) def setUp(self): cfg.CONF.set_override('admin_user', 'neutron', group=...
= '60c7ebc4-aa70-4ee6-aad6-41e99d27ceec' self.PASSWORD = 'admin_pass' self.PORT_ID = '16fa0e95-3c7a-4dd6-87bd-c76b14f9eac2' self.TENANT_ID = '384757095ca4495683c7f34ae077f8c0' self.TENANT_NAME = 'admin' self.USERNAME = 'admin' @mock.patch.object(identity_client, "Client") class ...
131
131
439
19
112
ashutosh-mishra/my-test
gbpservice/neutron/tests/unit/nfp/orchestrator/test_openstack_driver.py
Python
TestKeystoneClient
TestKeystoneClient
44
97
44
46
60b91161b1d3f97431be55cc54a29d11a6d984d8
bigcode/the-stack
train
47a46a9f95302e4a3e98aee2
train
class
@mock.patch.object(neutron_client, "Client") class TestNeutronClient(SampleData): def __init__(self, *args, **kwargs): super(TestNeutronClient, self).__init__(*args, **kwargs) self.neutron_obj = openstack_driver.NeutronClient(cfg.CONF) def test_get_floating_ip(self, mock_obj): instance...
@mock.patch.object(neutron_client, "Client") class TestNeutronClient(SampleData):
def __init__(self, *args, **kwargs): super(TestNeutronClient, self).__init__(*args, **kwargs) self.neutron_obj = openstack_driver.NeutronClient(cfg.CONF) def test_get_floating_ip(self, mock_obj): instance = mock_obj.return_value obj = instance.show_floatingip('floatingip_id')['f...
IsNotNone(retval) mock_obj.assert_called_once_with('2', auth_token=self.AUTH_TOKEN, tenant_id=self.TENANT_ID, auth_url=self.AUTH_URL) def test_create_instance(self, mock_obj): instance = mock_obj.return_value ...
256
256
1,453
20
236
ashutosh-mishra/my-test
gbpservice/neutron/tests/unit/nfp/orchestrator/test_openstack_driver.py
Python
TestNeutronClient
TestNeutronClient
232
392
232
234
56811e3d274592cc654665a558c7cdc25fc43023
bigcode/the-stack
train
318342a6ede6c75066a47bd5
train
class
@mock.patch.object(gbp_client, "Client") class TestGBPClient(SampleData): def __init__(self, *args, **kwargs): super(TestGBPClient, self).__init__(*args, **kwargs) self.gbp_obj = openstack_driver.GBPClient(cfg.CONF) def test_get_policy_target_groups(self, mock_obj): instance = mock_obj...
@mock.patch.object(gbp_client, "Client") class TestGBPClient(SampleData):
def __init__(self, *args, **kwargs): super(TestGBPClient, self).__init__(*args, **kwargs) self.gbp_obj = openstack_driver.GBPClient(cfg.CONF) def test_get_policy_target_groups(self, mock_obj): instance = mock_obj.return_value obj = instance.list_policy_target_groups()['policy_ta...
): instance = mock_obj.return_value obj = instance.list_subnets(id='subnet_ids').get('subnets', []) retval = self.neutron_obj.list_subnets(self.AUTH_TOKEN, 'subnet_ids=[]') self.assertEqual(retval, obj) mock_obj.assert_called_once_wi...
256
256
2,452
19
237
ashutosh-mishra/my-test
gbpservice/neutron/tests/unit/nfp/orchestrator/test_openstack_driver.py
Python
TestGBPClient
TestGBPClient
395
672
395
397
5174b24cf095ae118e1832c46d16937bb53a1c32
bigcode/the-stack
train
9308053533b04acc03254676
train
class
class SampleData(unittest.TestCase): def __init__(self, *args, **kwargs): super(SampleData, self).__init__(*args, **kwargs) self.AUTH_TOKEN = '6db9dfa4d29d442eb2b23811ad4b3a6d' self.AUTH_URL = 'https://127.0.0.1:35357/None/' self.ENDPOINT_URL = 'https://127.0.0.1:9696/' self...
class SampleData(unittest.TestCase):
def __init__(self, *args, **kwargs): super(SampleData, self).__init__(*args, **kwargs) self.AUTH_TOKEN = '6db9dfa4d29d442eb2b23811ad4b3a6d' self.AUTH_URL = 'https://127.0.0.1:35357/None/' self.ENDPOINT_URL = 'https://127.0.0.1:9696/' self.FLAVOR_NAME = 'm1.tiny' self....
client as gbp_client from gbpservice.nfp.orchestrator.openstack import openstack_driver from keystoneclient.v2_0 import client as identity_client from neutronclient.v2_0 import client as neutron_client from novaclient import client as nova_client cfg.CONF.import_group('keystone_authtoken', 'keystonemiddleware.auth_to...
87
87
291
7
80
ashutosh-mishra/my-test
gbpservice/neutron/tests/unit/nfp/orchestrator/test_openstack_driver.py
Python
SampleData
SampleData
26
41
26
27
8375d2ff8064cc76b9e7c3b30c38ce2804de3634
bigcode/the-stack
train
800b00150669f1f23b9698b6
train
class
class EWAHConnection(Connection): """Extension of airflow's native Connection.""" @classmethod def get_connection_from_secrets(cls, conn_id): """Save the calling hook class as provided when called.""" conn = super().get_connection_from_secrets(conn_id) # conn is returned as airflow....
class EWAHConnection(Connection):
"""Extension of airflow's native Connection.""" @classmethod def get_connection_from_secrets(cls, conn_id): """Save the calling hook class as provided when called.""" conn = super().get_connection_from_secrets(conn_id) # conn is returned as airflow.hooks.base.BaseHook, return as cls...
from airflow.hooks.base import BaseHook from airflow.models.connection import Connection from airflow.providers_manager import ProvidersManager from airflow.utils.module_loading import import_string from typing import Type, Optional class EWAHConnection(Connection):
47
165
551
7
39
Gemma-Analytics/ewah
ewah/hooks/base.py
Python
EWAHConnection
EWAHConnection
9
74
9
9
7dc8a6e9b5fe9c019266c16648079cbe6dd08aa7
bigcode/the-stack
train
1e2b3f56c6949eaaf493d3a2
train
class
class EWAHBaseHook(BaseHook): """Extension of airflow's native Base Hook.""" # Overwrite in child class to relabel attributes # e.g. {"api_key": "password"} to get self.password for self.api_key _ATTR_RELABEL = {} def __init__( self, conn: Optional[EWAHConnection] = None, c...
class EWAHBaseHook(BaseHook):
"""Extension of airflow's native Base Hook.""" # Overwrite in child class to relabel attributes # e.g. {"api_key": "password"} to get self.password for self.api_key _ATTR_RELABEL = {} def __init__( self, conn: Optional[EWAHConnection] = None, conn_id: Optional[str] = None, ...
= "{0} is not an attribute of {1}!" _msg += " conn_id: {2}, conn_type: {3}, hook class: {4}" raise AttributeError( _msg.format( name, self.__class__.__name__, # If accessed directly, attributes would cause infinite loop self.__...
111
111
372
9
102
Gemma-Analytics/ewah
ewah/hooks/base.py
Python
EWAHBaseHook
EWAHBaseHook
77
124
77
77
442c016d48acd5c6c0a3116b857d29b2178b3d2b
bigcode/the-stack
train
c84e975a6ca2fa8ec2d2553d
train
class
class RS485_Mgr(): def __init__( self ): pass def open( self, interface_parameters ): try: print( "interface_parameters",interface_parameters) self.instrument = Instrument(interface_parameters["interface"],40 ) # 10 is instrument address print( "timeout", interface...
class RS485_Mgr():
def __init__( self ): pass def open( self, interface_parameters ): try: print( "interface_parameters",interface_parameters) self.instrument = Instrument(interface_parameters["interface"],40 ) # 10 is instrument address print( "timeout", interface_parameters["timeou...
# # File: rs485_mgr.py # This file handles low level rs485 communication # # # # # import os import time import struct from .myModbus_py3 import * class RS485_Mgr():
49
244
815
6
43
bopopescu/local_controller_3
modbus_redis_server_py3/rs485_mgr_py3.py
Python
RS485_Mgr
RS485_Mgr
15
130
15
15
a61dbb2f123b4f3f53251d64593e98bd90512bb4
bigcode/the-stack
train
ec7f7e79ad4db9a8596fcfcb
train
function
@app.get("/", include_in_schema=False) async def root(): return FileResponse("../index.html")
@app.get("/", include_in_schema=False) async def root():
return FileResponse("../index.html")
def calculate_pressure_altitude(pressure, p0=101_325): altitude = 0.3048 * 145_366.45 * (1 - pow(pressure / p0, 0.190_284)) return altitude @app.get("/", include_in_schema=False) async def root():
64
64
20
12
51
jaluebbe/GPSTracker
gps_tracker/backend_fastapi.py
Python
root
root
20
22
20
21
339e8915ac5629ab479879c421ac6b2a4ee5ed3b
bigcode/the-stack
train
8f7280f25a2636a14a314f41
train
function
@app.get("/api/dataset/{id}.geojson") def get_geojson_dataset( id: str = Query(..., regex="^tracking_[a-z0-9]*_[0-9]{8}$"), show_pressure_altitude: bool = True, show_gps_altitude: bool = False, ref_pressure_mbar: float = 1013.25, ): data = ",\n".join( redis_connection.lrange(id.replace("_", ...
@app.get("/api/dataset/{id}.geojson") def get_geojson_dataset( id: str = Query(..., regex="^tracking_[a-z0-9]*_[0-9]{8}$"), show_pressure_altitude: bool = True, show_gps_altitude: bool = False, ref_pressure_mbar: float = 1013.25, ):
data = ",\n".join( redis_connection.lrange(id.replace("_", ":"), 0, -1)[::-1] ) height_data = [] tracking_data = json.loads(f"[{data}]") if show_gps_altitude: _coords = [ [row["lon"], row["lat"], row["alt"]] for row in tracking_data if row.get("alt...
".join( redis_connection.lrange(id.replace("_", ":"), 0, -1)[::-1] ) return json.loads(f"[{data}]") @app.get("/api/dataset/{id}.geojson") def get_geojson_dataset( id: str = Query(..., regex="^tracking_[a-z0-9]*_[0-9]{8}$"), show_pressure_altitude: bool = True, show_gps_altitude: bool = False...
116
117
392
81
35
jaluebbe/GPSTracker
gps_tracker/backend_fastapi.py
Python
get_geojson_dataset
get_geojson_dataset
52
99
52
58
49be7ee2ef7da9b8a9a170e402149a891d36ce84
bigcode/the-stack
train
b203dc11f1ed6a63229cf62f
train
function
@app.get("/api/current_pressure") def get_current_pressure(): pressure_data = redis_connection.get("current_pressure") if pressure_data is None: raise HTTPException(status_code=404, detail="no data available") return json.loads(pressure_data)
@app.get("/api/current_pressure") def get_current_pressure():
pressure_data = redis_connection.get("current_pressure") if pressure_data is None: raise HTTPException(status_code=404, detail="no data available") return json.loads(pressure_data)
.3048 * 145_366.45 * (1 - pow(pressure / p0, 0.190_284)) return altitude @app.get("/", include_in_schema=False) async def root(): return FileResponse("../index.html") @app.get("/api/current_pressure") def get_current_pressure():
64
64
53
12
52
jaluebbe/GPSTracker
gps_tracker/backend_fastapi.py
Python
get_current_pressure
get_current_pressure
25
30
25
26
c65a42a74b7cbd51e8116ddf33dcb972d691427e
bigcode/the-stack
train
2367633817c474d222887a4e
train
function
@app.get("/api/available_datasets") def get_available_datasets( category: str = Query("*", regex="^[*a-z0-9]*$"), date: str = Query("*", max_length=8, regex="^[*0-9]*$"), ): return [ key.replace(":", "_") for key in redis_connection.scan_iter(f"{category}:*:{date}") ]
@app.get("/api/available_datasets") def get_available_datasets( category: str = Query("*", regex="^[*a-z0-9]*$"), date: str = Query("*", max_length=8, regex="^[*0-9]*$"), ):
return [ key.replace(":", "_") for key in redis_connection.scan_iter(f"{category}:*:{date}") ]
.loads(pressure_data) @app.get("/api/available_datasets") def get_available_datasets( category: str = Query("*", regex="^[*a-z0-9]*$"), date: str = Query("*", max_length=8, regex="^[*0-9]*$"), ):
64
64
87
59
5
jaluebbe/GPSTracker
gps_tracker/backend_fastapi.py
Python
get_available_datasets
get_available_datasets
33
41
33
37
b8e30f3698c01b791a4ca52f73c154cec211ba86
bigcode/the-stack
train
dd9d5e7e39e108cfa1a5866d
train
function
def calculate_pressure_altitude(pressure, p0=101_325): altitude = 0.3048 * 145_366.45 * (1 - pow(pressure / p0, 0.190_284)) return altitude
def calculate_pressure_altitude(pressure, p0=101_325):
altitude = 0.3048 * 145_366.45 * (1 - pow(pressure / p0, 0.190_284)) return altitude
app = FastAPI() app.mount("/static", StaticFiles(directory="../static"), name="static") # calculate barometric altitude based on the following formula: # https://www.weather.gov/media/epz/wxcalc/pressureAltitude.pdf def calculate_pressure_altitude(pressure, p0=101_325):
64
64
52
15
48
jaluebbe/GPSTracker
gps_tracker/backend_fastapi.py
Python
calculate_pressure_altitude
calculate_pressure_altitude
15
17
15
15
e173c981c9982c1ce2b4c78d92607a68a1894368
bigcode/the-stack
train
4df5450e70330f433fa8f26d
train
function
@app.get("/api/dataset/{id}.json") def get_dataset(id): data = ",\n".join( redis_connection.lrange(id.replace("_", ":"), 0, -1)[::-1] ) return json.loads(f"[{data}]")
@app.get("/api/dataset/{id}.json") def get_dataset(id):
data = ",\n".join( redis_connection.lrange(id.replace("_", ":"), 0, -1)[::-1] ) return json.loads(f"[{data}]")
Query("*", max_length=8, regex="^[*0-9]*$"), ): return [ key.replace(":", "_") for key in redis_connection.scan_iter(f"{category}:*:{date}") ] @app.get("/api/dataset/{id}.json") def get_dataset(id):
63
64
57
16
47
jaluebbe/GPSTracker
gps_tracker/backend_fastapi.py
Python
get_dataset
get_dataset
44
49
44
45
dbb374281acfa70839797a78b59b5a7cd0aa1a18
bigcode/the-stack
train
0c3b801419237bffcf80ec91
train
function
@app.callback( [Output("submit-status", "children"), Output("wod-log-df", "children")], [Input("submit-entry-button", "n_clicks")], [State("new-date", "value"), State("new-name", "value"), State("new-sets", "value"), State("new-reps", "value"), State("new-weight", "value"), St...
@app.callback( [Output("submit-status", "children"), Output("wod-log-df", "children")], [Input("submit-entry-button", "n_clicks")], [State("new-date", "value"), State("new-name", "value"), State("new-sets", "value"), State("new-reps", "value"), State("new-weight", "value"), St...
if n_clicks is None: return ( "Press button to submit workout", refresh_aws_table(wod_log)[1] ) else: wod_log.put_item( Item={ 'name': clean_text(name), 'date': date, 'sets': sets, 'reps': reps, '...
@app.callback( [Output("submit-status", "children"), Output("wod-log-df", "children")], [Input("submit-entry-button", "n_clicks")], [State("new-date", "value"), State("new-name", "value"), State("new-sets", "value"), State("new-reps", "value"), State("new-weight", "value"), St...
119
74
249
119
0
SamEdwardes/wod-tracker
app.py
Python
submit_new_entry
submit_new_entry
180
210
180
190
36573e5db7b367ba02c1c60cd2e8d780fca51289
bigcode/the-stack
train
cb8543a904e4dae15037bc5d
train
function
def key_split(s): """ >>> key_split('x') 'x' >>> key_split('x-1') 'x' >>> key_split('x-1-2-3') 'x' >>> key_split(('x-2', 1)) 'x' >>> key_split("('x-2', 1)") 'x' >>> key_split("('x', 1)") 'x' >>> key_split('hello-world-1') 'hello-world' >>> key_split(b'hell...
def key_split(s):
""" >>> key_split('x') 'x' >>> key_split('x-1') 'x' >>> key_split('x-1-2-3') 'x' >>> key_split(('x-2', 1)) 'x' >>> key_split("('x-2', 1)") 'x' >>> key_split("('x', 1)") 'x' >>> key_split('hello-world-1') 'hello-world' >>> key_split(b'hello-world-1') 'h...
running within an IPython kernel >>> is_kernel() False """ # http://stackoverflow.com/questions/34091701/determine-if-were-in-an-ipython-notebook-session if 'IPython' not in sys.modules: # IPython hasn't been imported return False from IPython import get_ipython # check for `kerne...
119
120
401
5
114
tjb900/distributed
distributed/utils.py
Python
key_split
key_split
472
522
472
472
63c3e44871456b00ae49ac5bff24df80e31c6113
bigcode/the-stack
train
f2c0988a54d71704ffee1d19
train
function
def get_ipv6(host='2001:4860:4860::8888', port=80): """ The same as get_ip(), but for IPv6. """ return _get_ip(host, port, family=socket.AF_INET6, default='::1')
def get_ipv6(host='2001:4860:4860::8888', port=80):
""" The same as get_ip(), but for IPv6. """ return _get_ip(host, port, family=socket.AF_INET6, default='::1')
a well-known Internet host (one of Google's public DNS servers). """ return _get_ip(host, port, family=socket.AF_INET, default='127.0.0.1') def get_ipv6(host='2001:4860:4860::8888', port=80):
64
64
59
22
42
tjb900/distributed
distributed/utils.py
Python
get_ipv6
get_ipv6
144
148
144
144
d2e4f0dd493254271e4cefb31749bebae3c846a2
bigcode/the-stack
train
b0f49db04f74f5ee5783a7ad
train
function
def truncate_exception(e, n=10000): """ Truncate exception to be about a certain length """ if len(str(e)) > n: try: return type(e)("Long error message", str(e)[:n]) except Exception: return Exception("Long error message", ...
def truncate_exception(e, n=10000):
""" Truncate exception to be about a certain length """ if len(str(e)) > n: try: return type(e)("Long error message", str(e)[:n]) except Exception: return Exception("Long error message", type(e), ...
os.path.join('concurrent', 'futures')] while exc_traceback and any(b in exc_traceback.tb_frame.f_code.co_filename for b in bad): exc_traceback = exc_traceback.tb_next return exc_traceback def truncate_exception(e, n=10000):
64
64
80
10
53
tjb900/distributed
distributed/utils.py
Python
truncate_exception
truncate_exception
695
706
695
695
a57e8c90acc2a083ca8ca903dded91d61b3c189f
bigcode/the-stack
train
f3f71194ee5549acbfa0f901
train
function
def str_graph(dsk, extra_values=()): def convert(task): if type(task) is list: return [convert(v) for v in task] if type(task) is dict: return valmap(convert, task) if istask(task): return (task[0],) + tuple(map(convert, task[1:])) try: ...
def str_graph(dsk, extra_values=()):
def convert(task): if type(task) is list: return [convert(v) for v in task] if type(task) is dict: return valmap(convert, task) if istask(task): return (task[0],) + tuple(map(convert, task[1:])) try: if task in dsk or task in extra_valu...
_complex(task): """ Possibly contains a nested task """ return (istask(task) or type(task) is list and any(map(_maybe_complex, task)) or type(task) is dict and any(map(_maybe_complex, task.values()))) def str_graph(dsk, extra_values=()):
63
64
126
10
53
tjb900/distributed
distributed/utils.py
Python
str_graph
str_graph
779
794
779
779
d1e5c9786a45e2b6fa5cbba623e5241b0049fd67
bigcode/the-stack
train
61d60d89f42b7975a7748279
train
function
@gen.coroutine def ignore_exceptions(coroutines, *exceptions): """ Process list of coroutines, ignoring certain exceptions >>> coroutines = [cor(...) for ...] # doctest: +SKIP >>> x = yield ignore_exceptions(coroutines, TypeError) # doctest: +SKIP """ wait_iterator = gen.WaitIterator(*coroutines)...
@gen.coroutine def ignore_exceptions(coroutines, *exceptions):
""" Process list of coroutines, ignoring certain exceptions >>> coroutines = [cor(...) for ...] # doctest: +SKIP >>> x = yield ignore_exceptions(coroutines, TypeError) # doctest: +SKIP """ wait_iterator = gen.WaitIterator(*coroutines) results = [] while not wait_iterator.done(): w...
info.address raise ValueError("interface %r doesn't have an IPv4 address" % (ifname,)) @contextmanager def ignoring(*exceptions): try: yield except exceptions as e: pass @gen.coroutine def ignore_exceptions(coroutines, *exceptions):
64
64
121
16
47
tjb900/distributed
distributed/utils.py
Python
ignore_exceptions
ignore_exceptions
174
187
174
175
2fab5cd5b92b43809707546bc563c8f67b434954
bigcode/the-stack
train
bb35a409dc45e8d5e40a692a
train
function
@contextmanager def log_errors(pdb=False): from .comm import CommClosedError try: yield except (CommClosedError, gen.Return): raise except Exception as e: try: logger.exception(e) except TypeError: # logger becomes None during process cleanup pass...
@contextmanager def log_errors(pdb=False):
from .comm import CommClosedError try: yield except (CommClosedError, gen.Return): raise except Exception as e: try: logger.exception(e) except TypeError: # logger becomes None during process cleanup pass if pdb: import pdb ...
-f0-9]{32}', x): return 'data' elif x[0] == '<': return x.strip('<>').split()[0].split('.')[-1] else: return x else: return 'Other' @contextmanager def log_errors(pdb=False):
64
64
86
11
53
tjb900/distributed
distributed/utils.py
Python
log_errors
log_errors
618
633
618
619
678e34f1b924cf357033b0fd90b265a1be57fee3
bigcode/the-stack
train
fb514f2ddc61769d45242c9a
train
function
def mean(seq): seq = list(seq) return sum(seq) / len(seq)
def mean(seq):
seq = list(seq) return sum(seq) / len(seq)
""" total = sum(bins) acc = 0.0 out = [] for b in bins: now = n / total * b + acc now, acc = divmod(now, 1) out.append(int(now)) return out def mean(seq):
64
64
19
4
59
tjb900/distributed
distributed/utils.py
Python
mean
mean
945
947
945
945
e6967c3400af4ee30f791c4930fd806fc18dfcca
bigcode/the-stack
train
2f8f517dd3ca6bce6501b63c
train
function
def json_load_robust(fn, load=json.load): """ Reads a JSON file from disk that may be being written as we read """ while not os.path.exists(fn): sleep(0.01) for i in range(10): try: with open(fn) as f: cfg = load(f) if cfg: return cfg ...
def json_load_robust(fn, load=json.load):
""" Reads a JSON file from disk that may be being written as we read """ while not os.path.exists(fn): sleep(0.01) for i in range(10): try: with open(fn) as f: cfg = load(f) if cfg: return cfg except (ValueError, KeyError): # r...
(callback, callback_time, io_loop) @contextmanager def time_warn(duration, text): start = time() yield end = time() if end - start > duration: print('TIME WARNING', text, end - start) def json_load_robust(fn, load=json.load):
64
64
103
12
52
tjb900/distributed
distributed/utils.py
Python
json_load_robust
json_load_robust
1,264
1,276
1,264
1,264
23ee8fb05af8a7d1f0d0730d4579ca5ca4f592e8
bigcode/the-stack
train
1c6a82639daaa039bc60e211
train
class
class itemgetter(object): """A picklable itemgetter. Examples -------- >>> data = [0, 1, 2] >>> get_1 = itemgetter(1) >>> get_1(data) 1 """ __slots__ = ('index',) def __init__(self, index): self.index = index def __call__(self, x): return x[self.index] ...
class itemgetter(object):
"""A picklable itemgetter. Examples -------- >>> data = [0, 1, 2] >>> get_1 = itemgetter(1) >>> get_1(data) 1 """ __slots__ = ('index',) def __init__(self, index): self.index = index def __call__(self, x): return x[self.index] def __reduce__(self): ...
: for name in names_to_import: logger.info("Reload module %s from %s file", name, ext) loaded.append(reload(import_module(name))) finally: if tmp_python_path is not None: sys.path.remove(tmp_python_path) return loaded class itemgetter(o...
64
64
113
5
58
tjb900/distributed
distributed/utils.py
Python
itemgetter
itemgetter
1,032
1,051
1,032
1,032
4a5e1a8f4c97b4c1b3308059e7c6ce565cce7a7a
bigcode/the-stack
train
ce580b0eff402d3ff3363e9d
train
function
def fix_asyncio_event_loop_policy(asyncio): """ Work around https://github.com/tornadoweb/tornado/issues/2183 """ class PatchedDefaultEventLoopPolicy(asyncio.DefaultEventLoopPolicy): def get_event_loop(self): """Get the event loop. This may be None or an instance of Eve...
def fix_asyncio_event_loop_policy(asyncio):
""" Work around https://github.com/tornadoweb/tornado/issues/2183 """ class PatchedDefaultEventLoopPolicy(asyncio.DefaultEventLoopPolicy): def get_event_loop(self): """Get the event loop. This may be None or an instance of EventLoop. """ try: ...
""" Clear internal storage. """ self.deque.clear() @classmethod def clear_all_instances(cls): """ Clear the internal storage of all live DequeHandlers. """ for inst in list(cls._instances): inst.clear() def fix_asyncio_event_loop_policy(async...
64
64
135
10
54
tjb900/distributed
distributed/utils.py
Python
fix_asyncio_event_loop_policy
fix_asyncio_event_loop_policy
1,326
1,345
1,326
1,326
34ddc54cadbc5a9db5835d3d673737d4b9b047ab
bigcode/the-stack
train
be0dd837e9e30a2a04bd7765
train
function
def divide_n_among_bins(n, bins): """ >>> divide_n_among_bins(12, [1, 1]) [6, 6] >>> divide_n_among_bins(12, [1, 2]) [4, 8] >>> divide_n_among_bins(12, [1, 2, 1]) [3, 6, 3] >>> divide_n_among_bins(11, [1, 2, 1]) [2, 6, 3] >>> divide_n_among_bins(11, [.1, .2, .1]) [2, 6, 3] ...
def divide_n_among_bins(n, bins):
""" >>> divide_n_among_bins(12, [1, 1]) [6, 6] >>> divide_n_among_bins(12, [1, 2]) [4, 8] >>> divide_n_among_bins(12, [1, 2, 1]) [3, 6, 3] >>> divide_n_among_bins(11, [1, 2, 1]) [2, 6, 3] >>> divide_n_among_bins(11, [.1, .2, .1]) [2, 6, 3] """ total = sum(bins) a...
isinstance(s, buffer): # noqa: F821 return bytes(s) if hasattr(s, 'encode'): return s.encode() raise TypeError( "Object %s is neither a bytes object nor has an encode method" % s) def divide_n_among_bins(n, bins):
64
64
205
10
54
tjb900/distributed
distributed/utils.py
Python
divide_n_among_bins
divide_n_among_bins
921
942
921
921
6317f6bc3eae34699bd1249aaf537fc2474f8781
bigcode/the-stack
train
44aa620bc9d604e7fb82eeb3
train
function
@contextmanager def tmp_text(filename, text): fn = os.path.join(tempfile.gettempdir(), filename) with open(fn, 'w') as f: f.write(text) try: yield fn finally: if os.path.exists(fn): os.remove(fn)
@contextmanager def tmp_text(filename, text):
fn = os.path.join(tempfile.gettempdir(), filename) with open(fn, 'w') as f: f.write(text) try: yield fn finally: if os.path.exists(fn): os.remove(fn)
k, v) try: yield finally: for k in kwargs: try: v = old[k] except KeyError: delattr(thread_state, k) else: setattr(thread_state, k, v) @contextmanager def tmp_text(filename, text):
64
64
63
11
53
tjb900/distributed
distributed/utils.py
Python
tmp_text
tmp_text
437
447
437
438
5b7c2457a011dc84900fcf1f570765f62ca25443
bigcode/the-stack
train
afa545dda60d63a74cf84488
train
function
@contextmanager def set_thread_state(**kwargs): old = {} for k in kwargs: try: old[k] = getattr(thread_state, k) except AttributeError: pass for k, v in kwargs.items(): setattr(thread_state, k, v) try: yield finally: for k in kwargs: ...
@contextmanager def set_thread_state(**kwargs):
old = {} for k in kwargs: try: old[k] = getattr(thread_state, k) except AttributeError: pass for k, v in kwargs.items(): setattr(thread_state, k, v) try: yield finally: for k in kwargs: try: v = old[k] ...
, *args, **kwargs) else: self.start() try: return sync(self.loop, func, *args, **kwargs) finally: self.stop() @property def loop(self): return self._loop @contextmanager def set_thread_state(**kwargs):
64
64
110
11
52
tjb900/distributed
distributed/utils.py
Python
set_thread_state
set_thread_state
415
434
415
416
04525cdcfb62d5894d22fd0c4685149c06acb4a9
bigcode/the-stack
train
3e13e03d9df0501d41d3e0a1
train
function
def reset_logger_locks(): """ Python 2's logger's locks don't survive a fork event https://github.com/dask/distributed/issues/1491 """ for name in logging.Logger.manager.loggerDict.keys(): for handler in logging.getLogger(name).handlers: handler.createLock()
def reset_logger_locks():
""" Python 2's logger's locks don't survive a fork event https://github.com/dask/distributed/issues/1491 """ for name in logging.Logger.manager.loggerDict.keys(): for handler in logging.getLogger(name).handlers: handler.createLock()
: return super().get_event_loop() except RuntimeError: # "There is no current event loop in thread" loop = self.new_event_loop() self.set_event_loop(loop) return loop asyncio.set_event_loop_policy(PatchedDefaultEventLoopPol...
64
64
64
6
58
tjb900/distributed
distributed/utils.py
Python
reset_logger_locks
reset_logger_locks
1,348
1,355
1,348
1,348
68943589d0af45a7cbd7140ab7a9c63d73e348b8
bigcode/the-stack
train
ee113535582a17c0cdf2e179
train
function
def import_file(path): """ Loads modules for a file (.py, .zip, .egg) """ directory, filename = os.path.split(path) name, ext = os.path.splitext(filename) names_to_import = [] tmp_python_path = None if ext in ('.py'): # , '.pyc'): if directory not in sys.path: tmp_python_pa...
def import_file(path):
""" Loads modules for a file (.py, .zip, .egg) """ directory, filename = os.path.split(path) name, ext = os.path.splitext(filename) names_to_import = [] tmp_python_path = None if ext in ('.py'): # , '.pyc'): if directory not in sys.path: tmp_python_path = directory ...
There is a chance that this port will be taken by the operating system soon after returning from this function. """ # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, 0)) s.listen(1) port = s.gets...
98
98
327
5
92
tjb900/distributed
distributed/utils.py
Python
import_file
import_file
989
1,029
989
989
b6265dc81be97812e1839ef296f7c9c84c10afc5
bigcode/the-stack
train
6e385aa048e4ec0779764394
train
function
@contextmanager def tmpfile(extension=''): extension = '.' + extension.lstrip('.') handle, filename = tempfile.mkstemp(extension) os.close(handle) os.remove(filename) yield filename if os.path.exists(filename): if os.path.isdir(filename): shutil.rmtree(filename) els...
@contextmanager def tmpfile(extension=''):
extension = '.' + extension.lstrip('.') handle, filename = tempfile.mkstemp(extension) os.close(handle) os.remove(filename) yield filename if os.path.exists(filename): if os.path.isdir(filename): shutil.rmtree(filename) else: try: os.remo...
f.seek(start + length) seek_delimiter(f, delimiter, 2**16) end = f.tell() offset = start length = end - start f.seek(offset) bytes = f.read(length) return bytes @contextmanager def tmpfile(extension=''):
64
64
95
10
53
tjb900/distributed
distributed/utils.py
Python
tmpfile
tmpfile
882
898
882
883
2e6767742d9dbc1bba6f12ab3766c3b89bdb77c5
bigcode/the-stack
train
1b72ffb3c28b574f62bd67f5
train
function
def tokey(o): """ Convert an object to a string. Examples -------- >>> tokey(b'x') 'x' >>> tokey('x') 'x' >>> tokey(1) '1' """ typ = type(o) if typ is unicode or typ is bytes: return o else: return str(o)
def tokey(o):
""" Convert an object to a string. Examples -------- >>> tokey(b'x') 'x' >>> tokey('x') 'x' >>> tokey(1) '1' """ typ = type(o) if typ is unicode or typ is bytes: return o else: return str(o)
seq: q.put(item) def iterator_to_queue(seq, maxsize=0): q = Queue(maxsize=maxsize) t = threading.Thread(target=_dump_to_queue, args=(seq, q)) t.daemon = True t.start() return q def tokey(o):
64
64
83
5
58
tjb900/distributed
distributed/utils.py
Python
tokey
tokey
743
760
743
743
2ebbc5885f5567f7d73d2bd2565321ee9c9439bb
bigcode/the-stack
train
7167652d5e740795e1023627
train
function
@memoize def ensure_ip(hostname): """ Ensure that address is an IP address Examples -------- >>> ensure_ip('localhost') '127.0.0.1' >>> ensure_ip('123.123.123.123') # pass through IP addresses '123.123.123.123' """ # Prefer IPv4 over IPv6, for compatibility families = [socket.A...
@memoize def ensure_ip(hostname):
""" Ensure that address is an IP address Examples -------- >>> ensure_ip('localhost') '127.0.0.1' >>> ensure_ip('123.123.123.123') # pass through IP addresses '123.123.123.123' """ # Prefer IPv4 over IPv6, for compatibility families = [socket.AF_INET, socket.AF_INET6] for f...
level = getattr(logging, level.upper()) old = None logger = logging.getLogger(root) for handler in logger.handlers: if isinstance(handler, logging.StreamHandler): old = handler.level handler.setLevel(level) return old @memoize def ensure_ip(hostname):
64
64
169
10
53
tjb900/distributed
distributed/utils.py
Python
ensure_ip
ensure_ip
654
677
654
655
45ec99fdf9e0e1ea5cf452212bc87d193f05d670
bigcode/the-stack
train
4787dfdf03443d10d08c8fb4
train
function
def clear_queue(q): while not q.empty(): q.get_nowait()
def clear_queue(q):
while not q.empty(): q.get_nowait()
def tmp_text(filename, text): fn = os.path.join(tempfile.gettempdir(), filename) with open(fn, 'w') as f: f.write(text) try: yield fn finally: if os.path.exists(fn): os.remove(fn) def clear_queue(q):
64
64
17
5
59
tjb900/distributed
distributed/utils.py
Python
clear_queue
clear_queue
450
452
450
450
f5166a604096a08100a78a465f64cfa2c417f52c
bigcode/the-stack
train
cb242e690178ebbc52ce608b
train
function
def seek_delimiter(file, delimiter, blocksize): """ Seek current file to next byte after a delimiter bytestring This seeks the file to the next byte following the delimiter. It does not return anything. Use ``file.tell()`` to see location afterwards. Parameters ---------- file: a file de...
def seek_delimiter(file, delimiter, blocksize):
""" Seek current file to next byte after a delimiter bytestring This seeks the file to the next byte following the delimiter. It does not return anything. Use ``file.tell()`` to see location afterwards. Parameters ---------- file: a file delimiter: bytes a delimiter like ``b'\n'`...
try: if task in dsk or task in extra_values: return tokey(task) except TypeError: pass return task return {tokey(k): convert(v) for k, v in dsk.items()} def seek_delimiter(file, delimiter, blocksize):
63
64
204
11
52
tjb900/distributed
distributed/utils.py
Python
seek_delimiter
seek_delimiter
797
827
797
797
af6fdd0813b9e328ce68e9e1cf483c278258e455
bigcode/the-stack
train
642efde3153973017dd046e9
train
function
def is_kernel(): """ Determine if we're running within an IPython kernel >>> is_kernel() False """ # http://stackoverflow.com/questions/34091701/determine-if-were-in-an-ipython-notebook-session if 'IPython' not in sys.modules: # IPython hasn't been imported return False from IPytho...
def is_kernel():
""" Determine if we're running within an IPython kernel >>> is_kernel() False """ # http://stackoverflow.com/questions/34091701/determine-if-were-in-an-ipython-notebook-session if 'IPython' not in sys.modules: # IPython hasn't been imported return False from IPython import get_ipyt...
tempdir(), filename) with open(fn, 'w') as f: f.write(text) try: yield fn finally: if os.path.exists(fn): os.remove(fn) def clear_queue(q): while not q.empty(): q.get_nowait() def is_kernel():
64
64
113
4
60
tjb900/distributed
distributed/utils.py
Python
is_kernel
is_kernel
455
466
455
455
91436aaa5e80ffec2767c5296682b4cd260b8296
bigcode/the-stack
train
3a59eb720736e089b0706fa4
train
function
@gen.coroutine def All(*args): """ Wait on many tasks at the same time Err once any of the tasks err. See https://github.com/tornadoweb/tornado/issues/1546 """ if len(args) == 1 and isinstance(args[0], Iterable): args = args[0] tasks = gen.WaitIterator(*args) results = [None for _ ...
@gen.coroutine def All(*args):
""" Wait on many tasks at the same time Err once any of the tasks err. See https://github.com/tornadoweb/tornado/issues/1546 """ if len(args) == 1 and isinstance(args[0], Iterable): args = args[0] tasks = gen.WaitIterator(*args) results = [None for _ in args] while not tasks.do...
: +SKIP """ wait_iterator = gen.WaitIterator(*coroutines) results = [] while not wait_iterator.done(): with ignoring(*exceptions): result = yield wait_iterator.next() results.append(result) raise gen.Return(results) @gen.coroutine def All(*args):
64
64
120
10
54
tjb900/distributed
distributed/utils.py
Python
All
All
190
205
190
191
5daf1cfa680bff58885d63cdb527cb3ba2821e0a
bigcode/the-stack
train
ee1c85c15b5cf7d617661cf9
train
function
def format_bytes(n): """ Format bytes as text >>> format_bytes(1) '1 B' >>> format_bytes(1234) '1.23 kB' >>> format_bytes(12345678) '12.35 MB' >>> format_bytes(1234567890) '1.23 GB' """ if n > 1e9: return '%0.2f GB' % (n / 1e9) if n > 1e6: return '%0.2f M...
def format_bytes(n):
""" Format bytes as text >>> format_bytes(1) '1 B' >>> format_bytes(1234) '1.23 kB' >>> format_bytes(12345678) '12.35 MB' >>> format_bytes(1234567890) '1.23 GB' """ if n > 1e9: return '%0.2f GB' % (n / 1e9) if n > 1e6: return '%0.2f MB' % (n / 1e6) if...
""" __slots__ = ('index',) def __init__(self, index): self.index = index def __call__(self, x): return x[self.index] def __reduce__(self): return (itemgetter, (self.index,)) def format_bytes(n):
63
64
165
5
59
tjb900/distributed
distributed/utils.py
Python
format_bytes
format_bytes
1,054
1,072
1,054
1,054
7cccec1c0308691091a0c70c4e5bc7aba5b03a6d
bigcode/the-stack
train
a133cd3e20965c2701997aa5
train
function
@memoize def _get_ip(host, port, family, default): # By using a UDP socket, we don't actually try to connect but # simply select the local address through which *host* is reachable. sock = socket.socket(family, socket.SOCK_DGRAM) try: sock.connect((host, port)) ip = sock.getsockname()[0]...
@memoize def _get_ip(host, port, family, default): # By using a UDP socket, we don't actually try to connect but # simply select the local address through which *host* is reachable.
sock = socket.socket(family, socket.SOCK_DGRAM) try: sock.connect((host, port)) ip = sock.getsockname()[0] return ip except EnvironmentError as e: # XXX Should first try getaddrinfo() on socket.gethostname() and getfqdn() warnings.warn("Couldn't detect a suitable IP a...
# is settable using _setmaxstdio(). return 512 @memoize def _get_ip(host, port, family, default): # By using a UDP socket, we don't actually try to connect but # simply select the local address through which *host* is reachable.
64
64
164
47
16
tjb900/distributed
distributed/utils.py
Python
_get_ip
_get_ip
115
131
115
118
63bcd5517a62c2ccb3e63229acbf84fe461da9b3
bigcode/the-stack
train
0b3f42e3ee8c8f2149910d7a
train
class
class DequeHandler(logging.Handler): """ A logging.Handler that records records into a deque """ _instances = weakref.WeakSet() def __init__(self, *args, **kwargs): n = kwargs.pop('n', 10000) self.deque = deque(maxlen=n) super(DequeHandler, self).__init__(*args, **kwargs) se...
class DequeHandler(logging.Handler):
""" A logging.Handler that records records into a deque """ _instances = weakref.WeakSet() def __init__(self, *args, **kwargs): n = kwargs.pop('n', 10000) self.deque = deque(maxlen=n) super(DequeHandler, self).__init__(*args, **kwargs) self._instances.add(self) def emit...
1: return '%.2f s' % n if n >= 1e-3: return '%.2f ms' % (n * 1e3) return '%.2f us' % (n * 1e6) class DequeHandler(logging.Handler):
64
64
160
7
57
tjb900/distributed
distributed/utils.py
Python
DequeHandler
DequeHandler
1,298
1,323
1,298
1,298
0eee26d9f3cb554a9a0341d1e89cbc5bac49039e
bigcode/the-stack
train
72a638a7d224024e79eb09a8
train
function
def get_ip_interface(ifname): """ Get the local IPv4 address of a network interface. KeyError is raised if the interface doesn't exist. ValueError is raised if the interface does no have an IPv4 address associated with it. """ import psutil for info in psutil.net_if_addrs()[ifname]: ...
def get_ip_interface(ifname):
""" Get the local IPv4 address of a network interface. KeyError is raised if the interface doesn't exist. ValueError is raised if the interface does no have an IPv4 address associated with it. """ import psutil for info in psutil.net_if_addrs()[ifname]: if info.family == socket....
_ipv6(host='2001:4860:4860::8888', port=80): """ The same as get_ip(), but for IPv6. """ return _get_ip(host, port, family=socket.AF_INET6, default='::1') def get_ip_interface(ifname):
64
64
108
7
57
tjb900/distributed
distributed/utils.py
Python
get_ip_interface
get_ip_interface
151
163
151
151
b5128c1ba16b29c48d328950ca98a11343c76210
bigcode/the-stack
train
e16cc77316d8649400d860ce
train
function
def read_block(f, offset, length, delimiter=None): """ Read a block of bytes from a file Parameters ---------- f: file File-like object supporting seek, read, tell, etc.. offset: int Byte offset to start read length: int Number of bytes to read delimiter: bytes (opti...
def read_block(f, offset, length, delimiter=None):
""" Read a block of bytes from a file Parameters ---------- f: file File-like object supporting seek, read, tell, etc.. offset: int Byte offset to start read length: int Number of bytes to read delimiter: bytes (optional) Ensure reading starts and stops at de...
size: int Number of bytes to read from the file at once. """ if file.tell() == 0: return last = b'' while True: current = file.read(blocksize) if not current: return full = last + current try: i = full.index(delimiter) ...
125
125
419
12
113
tjb900/distributed
distributed/utils.py
Python
read_block
read_block
830
879
830
830
037123806d41c5aad739be8d3569584d278b6182
bigcode/the-stack
train
ac74e81c9a745fbe82a68701
train
function
def funcname(func): """Get the name of a function.""" while hasattr(func, 'func'): func = func.func try: return func.__name__ except AttributeError: return str(func)
def funcname(func):
"""Get the name of a function.""" while hasattr(func, 'func'): func = func.func try: return func.__name__ except AttributeError: return str(func)
test suite much faster preload = ['distributed'] if 'pkg_resources' in sys.modules: preload.append('pkg_resources') ctx.set_forkserver_preload(preload) else: ctx = multiprocessing return ctx mp_context = _initialize_mp_context() def funcname(func):
64
64
47
5
59
tjb900/distributed
distributed/utils.py
Python
funcname
funcname
75
82
75
75
b853f5f8f05a33aa2416dd87812e36f157094f45
bigcode/the-stack
train
b91980ce405fef98671e80f5
train
function
@contextmanager def time_warn(duration, text): start = time() yield end = time() if end - start > duration: print('TIME WARNING', text, end - start)
@contextmanager def time_warn(duration, text):
start = time() yield end = time() if end - start > duration: print('TIME WARNING', text, end - start)
5.0. """ if tornado.version_info >= (5,): return tornado.ioloop.PeriodicCallback(callback, callback_time) else: return tornado.ioloop.PeriodicCallback(callback, callback_time, io_loop) @contextmanager def time_warn(duration, text):
64
64
44
11
53
tjb900/distributed
distributed/utils.py
Python
time_warn
time_warn
1,255
1,261
1,255
1,256
98f6b386a4c78f682ed8639ac9ce3349d6b5b999
bigcode/the-stack
train
1b71bd131bcba14c2bdefa8a
train
function
def parse_timedelta(s, default='seconds'): """ Parse timedelta string to number of seconds Examples -------- >>> parse_timedelta('3s') 3 >>> parse_timedelta('3.5 seconds') 3.5 >>> parse_timedelta('300ms') 0.3 >>> parse_timedelta(timedelta(seconds=3)) # also supports timedeltas ...
def parse_timedelta(s, default='seconds'):
""" Parse timedelta string to number of seconds Examples -------- >>> parse_timedelta('3s') 3 >>> parse_timedelta('3.5 seconds') 3.5 >>> parse_timedelta('300ms') 0.3 >>> parse_timedelta(timedelta(seconds=3)) # also supports timedeltas 3 """ if isinstance(s, timedelt...
nanosecond': 1e-9, } tds2.update({k + 's': v for k, v in tds2.items()}) timedelta_sizes.update(tds2) timedelta_sizes.update({k.upper(): v for k, v in timedelta_sizes.items()}) def parse_timedelta(s, default='seconds'):
72
72
242
10
62
tjb900/distributed
distributed/utils.py
Python
parse_timedelta
parse_timedelta
1,160
1,197
1,160
1,160
292153b2bc7e17f7727ad591cb0f98d2a61bea13
bigcode/the-stack
train
8944ef3dcd49e3ef0cf4cb08
train
function
def parse_bytes(s): """ Parse byte string to numbers >>> parse_bytes('100') 100 >>> parse_bytes('100 MB') 100000000 >>> parse_bytes('100M') 100000000 >>> parse_bytes('5kB') 5000 >>> parse_bytes('5.4 kB') 5400 >>> parse_bytes('1kiB') 1024 >>> parse_bytes('1e6') ...
def parse_bytes(s):
""" Parse byte string to numbers >>> parse_bytes('100') 100 >>> parse_bytes('100 MB') 100000000 >>> parse_bytes('100M') 100000000 >>> parse_bytes('5kB') 5000 >>> parse_bytes('5.4 kB') 5400 >>> parse_bytes('1kiB') 1024 >>> parse_bytes('1e6') 1000000 >>> pa...
{k.lower(): v for k, v in byte_sizes.items()} byte_sizes.update({k[0]: v for k, v in byte_sizes.items() if k and 'i' not in k}) byte_sizes.update({k[:-1]: v for k, v in byte_sizes.items() if k and 'i' in k}) def parse_bytes(s):
74
74
249
5
69
tjb900/distributed
distributed/utils.py
Python
parse_bytes
parse_bytes
1,094
1,133
1,094
1,094
9d136cb886ec75fb9b0a93d025c246c3f2ffab68
bigcode/the-stack
train
dfbce99e0b652c5423a378bf
train
function
def ensure_bytes(s): """ Turn string or bytes to bytes >>> ensure_bytes('123') b'123' >>> ensure_bytes(b'123') b'123' """ if isinstance(s, bytes): return s if isinstance(s, memoryview): return s.tobytes() if isinstance(s, bytearray) or PY2 and isinstance(s, buffer): ...
def ensure_bytes(s):
""" Turn string or bytes to bytes >>> ensure_bytes('123') b'123' >>> ensure_bytes(b'123') b'123' """ if isinstance(s, bytes): return s if isinstance(s, memoryview): return s.tobytes() if isinstance(s, bytearray) or PY2 and isinstance(s, buffer): # noqa: F821 ...
os.remove(filename) yield filename if os.path.exists(filename): if os.path.isdir(filename): shutil.rmtree(filename) else: try: os.remove(filename) except OSError: # sometimes we can't remove a generated temp file pass def...
64
64
133
5
58
tjb900/distributed
distributed/utils.py
Python
ensure_bytes
ensure_bytes
901
918
901
901
959a8e76452e913305d0dd4ea8fe067e06eaa1f7
bigcode/the-stack
train
5209456a3f6a1c593c783d3b
train
function
def _dump_to_queue(seq, q): for item in seq: q.put(item)
def _dump_to_queue(seq, q):
for item in seq: q.put(item)
""") else: # Returning non-None from generator is a syntax error in 2.x def queue_to_iterator(q): while True: result = q.get() if isinstance(result, StopIteration): raise result yield result def _dump_to_queue(seq, q):
64
64
20
9
54
tjb900/distributed
distributed/utils.py
Python
_dump_to_queue
_dump_to_queue
728
730
728
728
32d28a178e6c3053030b22f854ef4002e1b1ca26
bigcode/the-stack
train
033ca63f3caf4ccddabeeb0a
train
function
def has_arg(func, argname): """ Whether the function takes an argument with the given name. """ while True: try: if argname in getargspec(func).args: return True except TypeError: break try: # For Tornado coroutines and other de...
def has_arg(func, argname):
""" Whether the function takes an argument with the given name. """ while True: try: if argname in getargspec(func).args: return True except TypeError: break try: # For Tornado coroutines and other decorated functions ...
mp_context = _initialize_mp_context() def funcname(func): """Get the name of a function.""" while hasattr(func, 'func'): func = func.func try: return func.__name__ except AttributeError: return str(func) def has_arg(func, argname):
64
64
89
8
56
tjb900/distributed
distributed/utils.py
Python
has_arg
has_arg
85
100
85
85
78394d41e546e753a732b3d0e32a6ade902f093f
bigcode/the-stack
train
d923c2b8cd57400c18bff556
train
function
def get_fileno_limit(): """ Get the maximum number of open files per process. """ if resource is not None: return resource.getrlimit(resource.RLIMIT_NOFILE)[0] else: # Default ceiling for Windows when using the CRT, though it # is settable using _setmaxstdio(). return...
def get_fileno_limit():
""" Get the maximum number of open files per process. """ if resource is not None: return resource.getrlimit(resource.RLIMIT_NOFILE)[0] else: # Default ceiling for Windows when using the CRT, though it # is settable using _setmaxstdio(). return 512
if argname in getargspec(func).args: return True except TypeError: break try: # For Tornado coroutines and other decorated functions func = func.__wrapped__ except AttributeError: break return False def get_fileno_li...
64
64
75
6
57
tjb900/distributed
distributed/utils.py
Python
get_fileno_limit
get_fileno_limit
103
112
103
103
6653122ab1a86ad09ac8c2dd3cc008495a1fddf4
bigcode/the-stack
train
baee56153bf9ff233db44972
train
function
def validate_key(k): """Validate a key as received on a stream. """ typ = type(k) if typ is not unicode and typ is not bytes: raise TypeError("Unexpected key type %s (value: %r)" % (typ, k))
def validate_key(k):
"""Validate a key as received on a stream. """ typ = type(k) if typ is not unicode and typ is not bytes: raise TypeError("Unexpected key type %s (value: %r)" % (typ, k))
(b'x') 'x' >>> tokey('x') 'x' >>> tokey(1) '1' """ typ = type(o) if typ is unicode or typ is bytes: return o else: return str(o) def validate_key(k):
64
64
59
5
59
tjb900/distributed
distributed/utils.py
Python
validate_key
validate_key
763
769
763
763
a7253f12b78e18386617af036cdfb5e542aceef2
bigcode/the-stack
train
ffee5f21ec2e42a92bc97674
train
function
def iterator_to_queue(seq, maxsize=0): q = Queue(maxsize=maxsize) t = threading.Thread(target=_dump_to_queue, args=(seq, q)) t.daemon = True t.start() return q
def iterator_to_queue(seq, maxsize=0):
q = Queue(maxsize=maxsize) t = threading.Thread(target=_dump_to_queue, args=(seq, q)) t.daemon = True t.start() return q
def queue_to_iterator(q): while True: result = q.get() if isinstance(result, StopIteration): raise result yield result def _dump_to_queue(seq, q): for item in seq: q.put(item) def iterator_to_queue(seq, maxsize=0):
64
64
52
11
53
tjb900/distributed
distributed/utils.py
Python
iterator_to_queue
iterator_to_queue
733
740
733
733
f995243d1e2cd5aafb883769d2c3a32cab497238
bigcode/the-stack
train
a6d9f60b91930b196058008a
train
function
def sync(loop, func, *args, **kwargs): """ Run coroutine in loop running in separate thread. """ # Tornado's PollIOLoop doesn't raise when using closed, do it ourselves if ((isinstance(loop, PollIOLoop) and getattr(loop, '_closing', False)) or (hasattr(loop, 'asyncio_loop') and loop.asyncio_...
def sync(loop, func, *args, **kwargs):
""" Run coroutine in loop running in separate thread. """ # Tornado's PollIOLoop doesn't raise when using closed, do it ourselves if ((isinstance(loop, PollIOLoop) and getattr(loop, '_closing', False)) or (hasattr(loop, 'asyncio_loop') and loop.asyncio_loop._closed)): raise RuntimeEr...
tasks err. See https://github.com/tornadoweb/tornado/issues/1546 """ if len(args) == 1 and isinstance(args[0], Iterable): args = args[0] tasks = gen.WaitIterator(*args) results = [None for _ in args] while not tasks.done(): result = yield tasks.next() results[tasks.curr...
105
105
352
12
93
tjb900/distributed
distributed/utils.py
Python
sync
sync
208
255
208
208
5ecf00fc702a428029b693650bae52caefca4e30
bigcode/the-stack
train
ef4dbe8d81a8d296ae26dc13
train
function
def _initialize_mp_context(): if PY3 and not sys.platform.startswith('win') and 'PyPy' not in sys.version: method = dask.config.get('distributed.worker.multiprocessing-method') ctx = multiprocessing.get_context(method) # Makes the test suite much faster preload = ['distributed'] ...
def _initialize_mp_context():
if PY3 and not sys.platform.startswith('win') and 'PyPy' not in sys.version: method = dask.config.get('distributed.worker.multiprocessing-method') ctx = multiprocessing.get_context(method) # Makes the test suite much faster preload = ['distributed'] if 'pkg_resources' in sys....
3, PY2, get_thread_identity, unicode from .metrics import time try: from dask.context import thread_state except ImportError: thread_state = threading.local() logger = _logger = logging.getLogger(__name__) no_default = '__no_default__' def _initialize_mp_context():
64
64
106
6
58
tjb900/distributed
distributed/utils.py
Python
_initialize_mp_context
_initialize_mp_context
57
69
57
57
256768b16d1cc31503aa09cf24d33e5bee04014c
bigcode/the-stack
train
d57552aab8138dd0ecfb35a3
train
function
def _maybe_complex(task): """ Possibly contains a nested task """ return (istask(task) or type(task) is list and any(map(_maybe_complex, task)) or type(task) is dict and any(map(_maybe_complex, task.values())))
def _maybe_complex(task):
""" Possibly contains a nested task """ return (istask(task) or type(task) is list and any(map(_maybe_complex, task)) or type(task) is dict and any(map(_maybe_complex, task.values())))
validate_key(k): """Validate a key as received on a stream. """ typ = type(k) if typ is not unicode and typ is not bytes: raise TypeError("Unexpected key type %s (value: %r)" % (typ, k)) def _maybe_complex(task):
64
64
56
6
58
tjb900/distributed
distributed/utils.py
Python
_maybe_complex
_maybe_complex
772
776
772
772
45ff4d5f04073cbfb2e8f8b4792756f8d9afd6fb
bigcode/the-stack
train
a5dc2481b13f454bec590a0a
train
function
def silence_logging(level, root='distributed'): """ Force all existing loggers below *root* to the given level at least (or keep the existing level if less verbose). """ if isinstance(level, str): level = getattr(logging, level.upper()) old = None logger = logging.getLogger(root) ...
def silence_logging(level, root='distributed'):
""" Force all existing loggers below *root* to the given level at least (or keep the existing level if less verbose). """ if isinstance(level, str): level = getattr(logging, level.upper()) old = None logger = logging.getLogger(root) for handler in logger.handlers: if isi...
Error, gen.Return): raise except Exception as e: try: logger.exception(e) except TypeError: # logger becomes None during process cleanup pass if pdb: import pdb pdb.set_trace() raise def silence_logging(level, root='distributed...
64
64
102
9
54
tjb900/distributed
distributed/utils.py
Python
silence_logging
silence_logging
636
651
636
636
005cb5b6c33f11fb057e1b93b2fd513abcd0c78f
bigcode/the-stack
train
47bdfd85bd108bb5c91f8f52
train
function
def open_port(host=''): """ Return a probably-open port There is a chance that this port will be taken by the operating system soon after returning from this function. """ # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python s = socket.socket(socket.AF_INET, socket.SOCK_STRE...
def open_port(host=''):
""" Return a probably-open port There is a chance that this port will be taken by the operating system soon after returning from this function. """ # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, 0)...
= """ Whether the interpreter is currently shutting down. For use in finalizers, __del__ methods, and similar; it is advised to early bind this function rather than look it up when calling it, since at shutdown module globals may be cleared. """ def open_port(host=''):
63
64
106
6
57
tjb900/distributed
distributed/utils.py
Python
open_port
open_port
974
986
974
974
9445b50d0f8ad67121fb0823a80d68dbdf5a4e46
bigcode/the-stack
train
a9951bbbbe8ffff98d806fd8
train
function
def get_traceback(): exc_type, exc_value, exc_traceback = sys.exc_info() bad = [os.path.join('distributed', 'worker'), os.path.join('distributed', 'scheduler'), os.path.join('tornado', 'gen.py'), os.path.join('concurrent', 'futures')] while exc_traceback and any(b in exc_tra...
def get_traceback():
exc_type, exc_value, exc_traceback = sys.exc_info() bad = [os.path.join('distributed', 'worker'), os.path.join('distributed', 'scheduler'), os.path.join('tornado', 'gen.py'), os.path.join('concurrent', 'futures')] while exc_traceback and any(b in exc_traceback.tb_frame.f_cod...
name, 1234, # dummy port number fam, socket.SOCK_STREAM) except socket.gaierror as e: exc = e else: return results[0][4][0] raise exc tblib.pickling_support.install() def get_traceback():
64
64
109
5
59
tjb900/distributed
distributed/utils.py
Python
get_traceback
get_traceback
683
692
683
683
ae31fbe7e688e2063232e1b533341e0bc5e5ee48
bigcode/the-stack
train
0af1e5cfc6a2c3d47a38a0da
train
function
def format_time(n): """ format integers as time >>> format_time(1) '1.00 s' >>> format_time(0.001234) '1.23 ms' >>> format_time(0.00012345) '123.45 us' >>> format_time(123.456) '123.46 s' """ if n >= 1: return '%.2f s' % n if n >= 1e-3: return '%.2f ms' %...
def format_time(n):
""" format integers as time >>> format_time(1) '1.00 s' >>> format_time(0.001234) '1.23 ms' >>> format_time(0.00012345) '123.45 us' >>> format_time(123.456) '123.46 s' """ if n >= 1: return '%.2f s' % n if n >= 1e-3: return '%.2f ms' % (n * 1e3) retur...
for i in range(10): try: with open(fn) as f: cfg = load(f) if cfg: return cfg except (ValueError, KeyError): # race with writing process pass sleep(0.1) def format_time(n):
64
64
141
5
59
tjb900/distributed
distributed/utils.py
Python
format_time
format_time
1,279
1,295
1,279
1,279
4646a0bb21b22d8bdfb415b98cb0571467f0195b
bigcode/the-stack
train
5bb0d547eb6bcfedbb2be8a9
train
function
def asciitable(columns, rows): """Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i i...
def asciitable(columns, rows):
"""Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i in r) for r in rows] columns...
prefix = s[:index] suffix = s[index:] or default n = float(prefix) multiplier = timedelta_sizes[suffix.lower()] result = n * multiplier if int(result) == result: result = int(result) return result def asciitable(columns, rows):
64
64
208
7
56
tjb900/distributed
distributed/utils.py
Python
asciitable
asciitable
1,200
1,219
1,200
1,200
ee29055fa0d42ccd56f03dad435a00cbf71be52b
bigcode/the-stack
train
797306dd3df34edd1d00f4c6
train
function
@contextmanager def ignoring(*exceptions): try: yield except exceptions as e: pass
@contextmanager def ignoring(*exceptions):
try: yield except exceptions as e: pass
""" import psutil for info in psutil.net_if_addrs()[ifname]: if info.family == socket.AF_INET: return info.address raise ValueError("interface %r doesn't have an IPv4 address" % (ifname,)) @contextmanager def ignoring(*exceptions):
63
64
24
9
55
tjb900/distributed
distributed/utils.py
Python
ignoring
ignoring
166
171
166
167
8f6e684b7bf6e14edb324755fd4ef075412230d7
bigcode/the-stack
train
6cc3ae7ecaa8a14eb3bb5e3b
train
class
class LoopRunner(object): """ A helper to start and stop an IO loop in a controlled way. Several loop runners can associate safely to the same IO loop. Parameters ---------- loop: IOLoop (optional) If given, this loop will be re-used, otherwise an appropriate one will be looked ...
class LoopRunner(object):
""" A helper to start and stop an IO loop in a controlled way. Several loop runners can associate safely to the same IO loop. Parameters ---------- loop: IOLoop (optional) If given, this loop will be re-used, otherwise an appropriate one will be looked up or created. asynchr...
kwargs.pop('callback_timeout', None) def make_coro(): coro = gen.maybe_future(func(*args, **kwargs)) if timeout is None: return coro else: return gen.with_timeout(timedelta(seconds=timeout), coro) e = threading.Event() main_tid = get_thread_identity() r...
256
256
1,086
5
251
tjb900/distributed
distributed/utils.py
Python
LoopRunner
LoopRunner
258
412
258
258
c1934e8a82c3422555072f4e73d5130e0a496b11
bigcode/the-stack
train
2bd870c5ff95bf9b61707e78
train
function
def PeriodicCallback(callback, callback_time, io_loop=None): """ Wrapper around tornado.IOLoop.PeriodicCallback, for compatibility with removal of the `io_loop` parameter in Tornado 5.0. """ if tornado.version_info >= (5,): return tornado.ioloop.PeriodicCallback(callback, callback_time) ...
def PeriodicCallback(callback, callback_time, io_loop=None):
""" Wrapper around tornado.IOLoop.PeriodicCallback, for compatibility with removal of the `io_loop` parameter in Tornado 5.0. """ if tornado.version_info >= (5,): return tornado.ioloop.PeriodicCallback(callback, callback_time) else: return tornado.ioloop.PeriodicCallback(callback...
: def nbytes(frame, _bytes_like=(bytes, bytearray)): """ Number of bytes of a frame or memoryview """ if isinstance(frame, _bytes_like): return len(frame) else: return frame.nbytes def PeriodicCallback(callback, callback_time, io_loop=None):
64
64
96
13
50
tjb900/distributed
distributed/utils.py
Python
PeriodicCallback
PeriodicCallback
1,244
1,252
1,244
1,244
8a2e993dc69f5676d22e21c324eb93d5ac35d811
bigcode/the-stack
train
6b4a6e89bfc220966f3022db
train
function
def get_ip(host='8.8.8.8', port=80): """ Get the local IP address through which the *host* is reachable. *host* defaults to a well-known Internet host (one of Google's public DNS servers). """ return _get_ip(host, port, family=socket.AF_INET, default='127.0.0.1')
def get_ip(host='8.8.8.8', port=80):
""" Get the local IP address through which the *host* is reachable. *host* defaults to a well-known Internet host (one of Google's public DNS servers). """ return _get_ip(host, port, family=socket.AF_INET, default='127.0.0.1')
Couldn't detect a suitable IP address for " "reaching %r, defaulting to %r: %s" % (host, default, e), RuntimeWarning) return default finally: sock.close() def get_ip(host='8.8.8.8', port=80):
64
64
82
17
47
tjb900/distributed
distributed/utils.py
Python
get_ip
get_ip
134
141
134
134
8125ab72fe9705a2badcc046efafdabcb7534165
bigcode/the-stack
train
d1ed2f1bcf25382828f2a3d0
train
class
class AnacondaProject(object): """Class containing a consolidated public API for convenience.""" def __init__(self): """Construct an API instance.""" pass def load_project(self, directory_path, frontend): """Load a project from the given directory. If there's a problem, th...
class AnacondaProject(object):
"""Class containing a consolidated public API for convenience.""" def __init__(self): """Construct an API instance.""" pass def load_project(self, directory_path, frontend): """Load a project from the given directory. If there's a problem, the returned Project instance wil...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2016, Anaconda, Inc. All rights reserved. # # Licensed under the terms of the BSD 3-Clause License. # The full license is in the file LICENSE.txt, distributed with this software. # -------------------...
201
256
6,005
6
194
AlbertDeFusco/anaconda-project
anaconda_project/api.py
Python
AnacondaProject
AnacondaProject
27
758
27
27
e11cef273287afa19331757ff2e291ba1f821f10
bigcode/the-stack
train
d21535ec1ceb9f3c1f553e82
train
class
class KrgBased(SurrogateModel): _regression_types = {"constant": constant, "linear": linear, "quadratic": quadratic} _correlation_types = { "abs_exp": abs_exp, "squar_exp": squar_exp, "act_exp": act_exp, "matern52": matern52, "matern32": matern32, "gower": gower...
class KrgBased(SurrogateModel):
_regression_types = {"constant": constant, "linear": linear, "quadratic": quadratic} _correlation_types = { "abs_exp": abs_exp, "squar_exp": squar_exp, "act_exp": act_exp, "matern52": matern52, "matern32": matern32, "gower": gower_corr, } name = "Kriging...
""" Author: Dr. Mohamed Amine Bouhlel <mbouhlel@umich.edu> Some functions are copied from gaussian_process submodule (Scikit-learn 0.14) This package is distributed under New BSD license. """ import numpy as np from scipy import linalg, optimize from copy import deepcopy from smt.surrogate_models.surrogate_model impo...
194
256
11,008
9
184
RobinGRAPIN/smt
smt/surrogate_models/krg_based.py
Python
KrgBased
KrgBased
30
1,313
30
31
b61646df35197f4c38302b11dd90b95f6ce958c7
bigcode/the-stack
train
d2fd593419c8307b54797e87
train
class
class LibpqConan(ConanFile): name = "libpq" description = "The library used by all the standard PostgreSQL tools." topics = ("conan", "libpq", "postgresql", "database", "db") url = "https://github.com/conan-io/conan-center-index" homepage = "https://www.postgresql.org/docs/current/static/libpq.html"...
class LibpqConan(ConanFile):
name = "libpq" description = "The library used by all the standard PostgreSQL tools." topics = ("conan", "libpq", "postgresql", "database", "db") url = "https://github.com/conan-io/conan-center-index" homepage = "https://www.postgresql.org/docs/current/static/libpq.html" license = "PostgreSQL" ...
from conans import ConanFile, AutoToolsBuildEnvironment, tools from conans.tools import os_info import os class LibpqConan(ConanFile):
35
256
2,317
10
24
Arenoros/conan-libpq
conanfile.py
Python
LibpqConan
LibpqConan
6
176
6
6
e34c990828f05146c030db9ad0bbf2f9c9bdc58a
bigcode/the-stack
train
92399d29e11b2c9dbd50cdfe
train
class
class TrialTestCase(TestCase): def setUp(self): self._trial_params = { 'msg': 'hi', 'x': 123, 'dict': { 'key': 'value', 'y': None } } nni.trial._params = { 'parameter_id': 'test_param', 'parameters': self._trial_params } def test_get_parameters(self): self.assertEqual(nni.get_parameters...
class TrialTestCase(TestCase):
def setUp(self): self._trial_params = { 'msg': 'hi', 'x': 123, 'dict': { 'key': 'value', 'y': None } } nni.trial._params = { 'parameter_id': 'test_param', 'parameters': self._trial_params } def test_get_parameters(self): self.assertEqual(nni.get_parameters(), self._trial_params) de...
all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE L...
152
152
508
7
144
kant/nni
src/sdk/pynni/tests/test_trial.py
Python
TrialTestCase
TrialTestCase
30
80
30
30
5209c8b248044727ce0db73c5656324da0695378
bigcode/the-stack
train
cc69eb3ab5bab63d3482f7aa
train
class
class Info: """ Base class for encapsulating nodal metadata for filesystem entries """ # meta methods def __init__(self, uri, **kwds): # chain up super().__init__(**kwds) # save the node uri self.uri = uri # all done return
class Info:
""" Base class for encapsulating nodal metadata for filesystem entries """ # meta methods def __init__(self, uri, **kwds): # chain up super().__init__(**kwds) # save the node uri self.uri = uri # all done return
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2019 all rights reserved # # declaration class Info:
46
64
74
3
42
lijun99/pyre
packages/pyre/filesystem/Info.py
Python
Info
Info
10
23
10
10
91c021d35689ba0e21a81afbf26499e51820ab31
bigcode/the-stack
train
354c4d401e836df203fddf19
train
function
def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, "interview_pairs", type_="foreignkey") op.drop_column("interview_pairs", "chat_id")
def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, "interview_pairs", type_="foreignkey") op.drop_column("interview_pairs", "chat_id")
) op.create_foreign_key( None, "interview_pairs", "chats", ["chat_id"], ["id"], ondelete="CASCADE" ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
63
64
48
18
45
sivayogasubramanian/coding-questions-telegram-bot
alembic/versions/20210503_001825_add_chat_id_to_interviewpairs_table.py
Python
downgrade
downgrade
31
34
31
32
6ff44b1c20abf84aba25c92582c6d56f2bad4824
bigcode/the-stack
train
37f8bf63c5b395e3b02eec87
train
function
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "interview_pairs", sa.Column("chat_id", postgresql.UUID(), nullable=False) ) op.create_foreign_key( None, "interview_pairs", "chats", ["chat_id"], ["id"], ondelete="CASCADE" )
def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.add_column( "interview_pairs", sa.Column("chat_id", postgresql.UUID(), nullable=False) ) op.create_foreign_key( None, "interview_pairs", "chats", ["chat_id"], ["id"], ondelete="CASCADE" )
mbic import op # revision identifiers, used by Alembic. revision = "a8271c222460" down_revision = "60fa87b77866" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
64
64
78
18
45
sivayogasubramanian/coding-questions-telegram-bot
alembic/versions/20210503_001825_add_chat_id_to_interviewpairs_table.py
Python
upgrade
upgrade
20
27
20
21
c6922696a7b4efb5ec09f24995d0f570237bdbbd
bigcode/the-stack
train
98ead6184db3130e60904425
train
class
class TestTEFuser(JitTestCase): def setUp(self): self.old_cpu_fuser_state = torch._C._jit_can_fuse_on_cpu() self.old_must_use_cpu_state = torch._C._jit_get_te_must_use_llvm_cpu() self.old_gpu_fuser_state = torch._C._jit_can_fuse_on_gpu() torch._C._jit_override_can_fuse_on_cpu(True) ...
class TestTEFuser(JitTestCase):
def setUp(self): self.old_cpu_fuser_state = torch._C._jit_can_fuse_on_cpu() self.old_must_use_cpu_state = torch._C._jit_get_te_must_use_llvm_cpu() self.old_gpu_fuser_state = torch._C._jit_can_fuse_on_gpu() torch._C._jit_override_can_fuse_on_cpu(True) # TODO: force LLVM. need...
'prim::BailOut']) return [n for n in nodes if n.kind() not in profiling_opcodes] def warmup_forward(f, *args, profiling_count=2): for i in range(profiling_count): results = f(*args) return results @contextlib.contextmanager def texpr_reductions_enabled(): old = torch._C._jit_set_texpr_reduct...
256
256
19,663
10
246
vitaut/pytorch
test/test_jit_fuser_te.py
Python
TestTEFuser
TestTEFuser
78
2,156
78
78
56916edda9f578240d90938a5de991b2f5a8cc05
bigcode/the-stack
train
c4f92206dff59cc0f3fd0dd9
train
class
class TestLoopnestRandomization(JitTestCase): def setUp(self): self.old_cpu_fuser_state = torch._C._jit_can_fuse_on_cpu() self.old_must_use_cpu_state = torch._C._jit_get_te_must_use_llvm_cpu() self.old_gpu_fuser_state = torch._C._jit_can_fuse_on_gpu() torch._C._jit_override_can_fuse...
class TestLoopnestRandomization(JitTestCase):
def setUp(self): self.old_cpu_fuser_state = torch._C._jit_can_fuse_on_cpu() self.old_must_use_cpu_state = torch._C._jit_get_te_must_use_llvm_cpu() self.old_gpu_fuser_state = torch._C._jit_can_fuse_on_gpu() torch._C._jit_override_can_fuse_on_cpu(True) # TODO: force LLVM. need...
Error("Expected test to fail. If it now works, move op into works_list") @onlyCPU @unittest.skipIf(not LLVM_ENABLED, "Compiles with TensorExprKernel") @ops([op for op in op_db if get_name(op) not in works_list + known_failures], allowed_dtypes=(torch.float,)) def test_unsupported(self, device, dtype, o...
200
200
669
11
189
vitaut/pytorch
test/test_jit_fuser_te.py
Python
TestLoopnestRandomization
TestLoopnestRandomization
2,366
2,422
2,366
2,366
eb1f3ec8093e25bdacefcbd8a13b8e1088b9e68d
bigcode/the-stack
train
90714995c84b4af923323e19
train
function
@contextlib.contextmanager def inline_fusion_groups(): old_inlining = torch._C._debug_get_fusion_group_inlining() torch._C._debug_set_fusion_group_inlining(True) try: yield finally: torch._C._debug_set_fusion_group_inlining(old_inlining)
@contextlib.contextmanager def inline_fusion_groups():
old_inlining = torch._C._debug_get_fusion_group_inlining() torch._C._debug_set_fusion_group_inlining(True) try: yield finally: torch._C._debug_set_fusion_group_inlining(old_inlining)
(): old = torch._C._jit_texpr_dynamic_shape_enabled() torch._C._jit_set_texpr_dynamic_shape_enabled(True) try: yield finally: torch._C._jit_set_texpr_dynamic_shape_enabled(old) @contextlib.contextmanager def inline_fusion_groups():
64
64
68
12
52
vitaut/pytorch
test/test_jit_fuser_te.py
Python
inline_fusion_groups
inline_fusion_groups
69
76
69
70
36ede054b113ce7cf7bda78d60af674823d10139
bigcode/the-stack
train
30b0c9e06dfbc00bb09fb422
train
function
@contextlib.contextmanager def texpr_dynamic_enabled(): old = torch._C._jit_texpr_dynamic_shape_enabled() torch._C._jit_set_texpr_dynamic_shape_enabled(True) try: yield finally: torch._C._jit_set_texpr_dynamic_shape_enabled(old)
@contextlib.contextmanager def texpr_dynamic_enabled():
old = torch._C._jit_texpr_dynamic_shape_enabled() torch._C._jit_set_texpr_dynamic_shape_enabled(True) try: yield finally: torch._C._jit_set_texpr_dynamic_shape_enabled(old)
.contextmanager def texpr_reductions_enabled(): old = torch._C._jit_set_texpr_reductions_enabled(True) try: yield finally: torch._C._jit_set_texpr_reductions_enabled(old) @contextlib.contextmanager def texpr_dynamic_enabled():
64
64
63
12
52
vitaut/pytorch
test/test_jit_fuser_te.py
Python
texpr_dynamic_enabled
texpr_dynamic_enabled
60
67
60
61
59f6ac4a10013dfed5e9cfed9ddac108fd4fc182
bigcode/the-stack
train
19c610e5318912324c579086
train
function
def warmup_forward(f, *args, profiling_count=2): for i in range(profiling_count): results = f(*args) return results
def warmup_forward(f, *args, profiling_count=2):
for i in range(profiling_count): results = f(*args) return results
llvm_enabled() def strip_profiling_nodes(nodes): profiling_opcodes = set(['prim::BailoutTemplate', 'prim::BailOut']) return [n for n in nodes if n.kind() not in profiling_opcodes] def warmup_forward(f, *args, profiling_count=2):
64
64
35
14
50
vitaut/pytorch
test/test_jit_fuser_te.py
Python
warmup_forward
warmup_forward
46
50
46
46
501c1a11adb780344e554d06988a38ba7b36d9bb
bigcode/the-stack
train
e5166304f42b0327f1a04dd0
train
class
class TestNNCOpInfo(TestCase): def te_compile(self, device, dtype, op): if op.name in skip_ops: return sample_inputs_itr = op.sample_inputs(device, dtype, requires_grad=False) for sample_input in sample_inputs_itr: arg_values = [sample_input.input] + list(sample_input...
class TestNNCOpInfo(TestCase):
def te_compile(self, device, dtype, op): if op.name in skip_ops: return sample_inputs_itr = op.sample_inputs(device, dtype, requires_grad=False) for sample_input in sample_inputs_itr: arg_values = [sample_input.input] + list(sample_input.args) kwarg_values...
trunc', 'unsqueeze', 'view', 'view_as', 'where', 'bool', 'byte', 'char', 'double', 'float', 'half', 'int', 'long', 'short', 'bool.channels_last', 'byte.channels_last', 'char.channels_last', 'double.channels_last', 'float.channels_last', 'half.c...
204
204
681
9
195
vitaut/pytorch
test/test_jit_fuser_te.py
Python
TestNNCOpInfo
TestNNCOpInfo
2,287
2,359
2,287
2,287
f8fd92039c975f0cd05ec45911d21fa107e1f378
bigcode/the-stack
train
db15682ebfdc212c99825e9c
train
function
def strip_profiling_nodes(nodes): profiling_opcodes = set(['prim::BailoutTemplate', 'prim::BailOut']) return [n for n in nodes if n.kind() not in profiling_opcodes]
def strip_profiling_nodes(nodes):
profiling_opcodes = set(['prim::BailoutTemplate', 'prim::BailOut']) return [n for n in nodes if n.kind() not in profiling_opcodes]
, LSTMCellF, LSTMCellS, MiLSTMCell from jit.test_fuser_common import TestFuserCommon # noqa: F401 FUSION_GROUP = 'prim::TensorExprGroup' LLVM_ENABLED = torch._C._llvm_enabled() def strip_profiling_nodes(nodes):
64
64
47
8
56
vitaut/pytorch
test/test_jit_fuser_te.py
Python
strip_profiling_nodes
strip_profiling_nodes
42
44
42
42
09f558ead542ec2e5ccf4cf02aef606b4bfcacc4
bigcode/the-stack
train
578739e84046c09ebc817afa
train
function
def get_name(op): l = [op.name] if op.variant_test_name != '': l.append(op.variant_test_name) return '.'.join(l)
def get_name(op):
l = [op.name] if op.variant_test_name != '': l.append(op.variant_test_name) return '.'.join(l)
long.channels_last', 'short.channels_last', ] known_failures = [ '__rmatmul__', 'frac', 'matmul', ] # If your OpInfo test causes this test to fail, add it here skip_ops = [ 'conj' ] def get_name(op):
64
64
35
5
59
vitaut/pytorch
test/test_jit_fuser_te.py
Python
get_name
get_name
2,281
2,285
2,281
2,281
6f7b66778d5f100d39be2a1083c748c54822cafc
bigcode/the-stack
train