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
1108a509f0ac53c92c5194aa
train
function
def test_profile_sys_object(aggregator): instance = common.generate_instance_config([]) init_config = { 'profiles': { 'profile1': { 'definition': {'metrics': common.SUPPORTED_METRIC_TYPES, 'sysobjectid': '1.3.6.1.4.1.8072.3.2.10'} } } } check = Snm...
def test_profile_sys_object(aggregator):
instance = common.generate_instance_config([]) init_config = { 'profiles': { 'profile1': { 'definition': {'metrics': common.SUPPORTED_METRIC_TYPES, 'sysobjectid': '1.3.6.1.4.1.8072.3.2.10'} } } } check = SnmpCheck('snmp', init_config, [instance]) ...
." + metric['name'] aggregator.assert_metric(metric_name, tags=common_tags, count=1) aggregator.assert_metric('snmp.sysUpTimeInstance', count=1) common.assert_common_metrics(aggregator) aggregator.assert_all_metrics_covered() def test_profile_sys_object(aggregator):
64
64
194
9
55
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_profile_sys_object
test_profile_sys_object
736
755
736
736
2693a39b3b6b20c171dcbd1feeddb668b95ecd6f
bigcode/the-stack
train
40d0e459261b40ca596afa15
train
function
def test_extract_value_does_not_match(aggregator, caplog): instance = common.generate_instance_config( [ { "MIB": "DUMMY-MIB", 'symbol': { 'OID': "1.3.6.1.4.1.123456789.4.0", 'name': "aTemperatureValueInferred", ...
def test_extract_value_does_not_match(aggregator, caplog):
instance = common.generate_instance_config( [ { "MIB": "DUMMY-MIB", 'symbol': { 'OID': "1.3.6.1.4.1.123456789.4.0", 'name': "aTemperatureValueInferred", 'extract_value': r'(\d+)ZZZ', }, ...
instance]) check.check(instance) aggregator.assert_metric( 'snmp.aTemperatureValueInferred', metric_type=aggregator.GAUGE, count=1, value=22, tags=common.CHECK_TAGS ) def test_extract_value_does_not_match(aggregator, caplog):
64
64
155
15
49
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_extract_value_does_not_match
test_extract_value_does_not_match
147
163
147
147
40150de9ef699ab1e28abf5a4b35ad0d2ebe7b1f
bigcode/the-stack
train
414ed06b6c0c733dc9d7946b
train
function
def test_table(aggregator): """ Support SNMP tabular objects """ instance = common.generate_instance_config(common.TABULAR_OBJECTS) check = common.create_check(instance) check.check(instance) # Test metrics for symbol in common.TABULAR_OBJECTS[0]['symbols']: metric_name = "snmp...
def test_table(aggregator):
""" Support SNMP tabular objects """ instance = common.generate_instance_config(common.TABULAR_OBJECTS) check = common.create_check(instance) check.check(instance) # Test metrics for symbol in common.TABULAR_OBJECTS[0]['symbols']: metric_name = "snmp." + symbol aggregat...
S, count=1) # Test service check aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=common.CHECK_TAGS, at_least=1) common.assert_common_metrics(aggregator) aggregator.all_metrics_asserted() def test_table(aggregator):
67
67
226
7
60
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_table
test_table
318
342
318
318
a0e10db55cde13c542facdd18a53889bbfd1df60
bigcode/the-stack
train
54f298b95df1e26187969a18
train
function
def test_metric_tag_multiple(aggregator, caplog): metrics = common.SUPPORTED_METRIC_TYPES instance = common.generate_instance_config(metrics) instance['metric_tags'] = [ {'MIB': 'SNMPv2-MIB', 'symbol': 'sysName', 'tag': 'snmp_host'}, {'MIB': 'IF-MIB', 'symbol': 'ifOutOctets', 'tag': 'out'}, ...
def test_metric_tag_multiple(aggregator, caplog):
metrics = common.SUPPORTED_METRIC_TYPES instance = common.generate_instance_config(metrics) instance['metric_tags'] = [ {'MIB': 'SNMPv2-MIB', 'symbol': 'sysName', 'tag': 'snmp_host'}, {'MIB': 'IF-MIB', 'symbol': 'ifOutOctets', 'tag': 'out'}, ] check = common.create_check(instance) ...
instance['metric_tags'] = [{'tags': {'foo': 'bar'}, 'match': '(', 'symbol': 'sysName', 'MIB': 'SNMPv2-MIB'}] with pytest.raises(ConfigurationError): common.create_check(instance) def test_metric_tag_multiple(aggregator, caplog):
66
66
221
12
54
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_metric_tag_multiple
test_metric_tag_multiple
1,155
1,175
1,155
1,155
37f1a79d4cfbf66375855202d748dc46bba67fc9
bigcode/the-stack
train
f1bd7f704ee49d0c7d1bdf5c
train
function
def test_unenforce_constraint(aggregator): """ Allow ignoring constraints """ instance = common.generate_instance_config(common.CONSTRAINED_OID) instance["community_string"] = "constraint" instance["enforce_mib_constraints"] = False check = common.create_check(instance) check.check(insta...
def test_unenforce_constraint(aggregator):
""" Allow ignoring constraints """ instance = common.generate_instance_config(common.CONSTRAINED_OID) instance["community_string"] = "constraint" instance["enforce_mib_constraints"] = False check = common.create_check(instance) check.check(instance) # Test metrics for metric in ...
_service_check("snmp.can_check", status=SnmpCheck.CRITICAL, tags=common.CHECK_TAGS, at_least=1) assert "failed at: ValueConstraintError" in aggregator.service_checks("snmp.can_check")[0].message def test_unenforce_constraint(aggregator):
64
64
180
10
53
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_unenforce_constraint
test_unenforce_constraint
296
315
296
296
3e063792466dd05af7df51360910758eeb38c39a
bigcode/the-stack
train
c9ea632132a96d2cf502d95c
train
function
def test_timeout(aggregator, caplog): caplog.set_level(logging.WARNING) instance = common.generate_instance_config([]) instance['community_string'] = 'public_delay' instance['timeout'] = 1 instance['retries'] = 0 check = SnmpCheck('snmp', {'oid_batch_size': 1}, [instance]) check.check(insta...
def test_timeout(aggregator, caplog):
caplog.set_level(logging.WARNING) instance = common.generate_instance_config([]) instance['community_string'] = 'public_delay' instance['timeout'] = 1 instance['retries'] = 0 check = SnmpCheck('snmp', {'oid_batch_size': 1}, [instance]) check.check(instance) aggregator.assert_service_ch...
metric_name = "snmp." + metric['name'] aggregator.assert_metric(metric_name, tags=tags, count=1) aggregator.assert_metric('snmp.sysUpTimeInstance', count=1) aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=tags, at_least=1) common.assert_common_metrics(aggregator...
98
98
328
10
88
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_timeout
test_timeout
1,208
1,236
1,208
1,208
dfb909c18edad84c2d46db1f571247786e7304df
bigcode/the-stack
train
ed268a106516aa2bc7cc56ce
train
function
def test_metric_tags_misconfiguration(): metrics = common.SUPPORTED_METRIC_TYPES instance = common.generate_instance_config(metrics) instance['metric_tags'] = [{'OID': '1.3.6.1.2.1.1.5.0', 'tag': 'snmp_host'}] with pytest.raises(ConfigurationError): common.create_check(instance) instance['...
def test_metric_tags_misconfiguration():
metrics = common.SUPPORTED_METRIC_TYPES instance = common.generate_instance_config(metrics) instance['metric_tags'] = [{'OID': '1.3.6.1.2.1.1.5.0', 'tag': 'snmp_host'}] with pytest.raises(ConfigurationError): common.create_check(instance) instance['metric_tags'] = [{'OID': '1.3.6.1.2.1.1.5...
metric_name = "snmp." + metric['name'] aggregator.assert_metric(metric_name, tags=tags, count=1) aggregator.assert_metric('snmp.sysUpTimeInstance', count=1) aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=tags, at_least=1) common.assert_common_metrics(aggregator) a...
95
95
319
8
87
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_metric_tags_misconfiguration
test_metric_tags_misconfiguration
1,126
1,152
1,126
1,126
ccf3c48623a23be52f7c5811dfc47808a7f2529f
bigcode/the-stack
train
8080c673805bf51b9cb05b84
train
function
def test_invalid_metric(aggregator): """ Invalid metrics raise a Warning and a critical service check """ instance = common.generate_instance_config(common.INVALID_METRICS) check = common.create_check(instance) check.check(instance) # Test service check aggregator.assert_service_check("...
def test_invalid_metric(aggregator):
""" Invalid metrics raise a Warning and a critical service check """ instance = common.generate_instance_config(common.INVALID_METRICS) check = common.create_check(instance) check.check(instance) # Test service check aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.WAR...
1) # Test service check aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=common.CHECK_TAGS, at_least=1) common.assert_common_metrics(aggregator) aggregator.all_metrics_asserted() def test_invalid_metric(aggregator):
64
64
88
8
56
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_invalid_metric
test_invalid_metric
593
602
593
593
d6f1d95fcaef8c34dfc9946004903b16da9f867e
bigcode/the-stack
train
a9f5183d27743d46c6287deb
train
function
@mock.patch("datadog_checks.snmp.snmp.read_persistent_cache") def test_discovery_devices_monitored_count(read_mock, aggregator): read_mock.return_value = '["192.168.0.1","192.168.0.2"]' host = socket.gethostbyname(common.HOST) network = ipaddress.ip_network(u'{}/29'.format(host), strict=False).with_prefixl...
@mock.patch("datadog_checks.snmp.snmp.read_persistent_cache") def test_discovery_devices_monitored_count(read_mock, aggregator):
read_mock.return_value = '["192.168.0.1","192.168.0.2"]' host = socket.gethostbyname(common.HOST) network = ipaddress.ip_network(u'{}/29'.format(host), strict=False).with_prefixlen check_tags = [ 'autodiscovery_subnet:{}'.format(to_native_string(network)), ] network_tags = ['network:{}'...
['name'] aggregator.assert_metric(metric_name, tags=check_tags, count=1) aggregator.assert_metric('snmp.sysUpTimeInstance') aggregator.assert_metric('snmp.discovered_devices_count', tags=network_tags) common.assert_common_device_metrics(aggregator, tags=check_tags) common.assert_common_check_r...
115
115
385
30
85
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_discovery_devices_monitored_count
test_discovery_devices_monitored_count
947
982
947
948
65202ada21160a32e52bd4eea16ece3c0183d16d
bigcode/the-stack
train
2c90cab397184f2cad419e05
train
function
def test_scalar(aggregator): """ Support SNMP scalar objects """ instance = common.generate_instance_config(common.SCALAR_OBJECTS) check = common.create_check(instance) check.check(instance) # Test metrics for metric in common.SCALAR_OBJECTS: metric_name = "snmp." + (metric.get...
def test_scalar(aggregator):
""" Support SNMP scalar objects """ instance = common.generate_instance_config(common.SCALAR_OBJECTS) check = common.create_check(instance) check.check(instance) # Test metrics for metric in common.SCALAR_OBJECTS: metric_name = "snmp." + (metric.get('name') or metric.get('symbo...
0'] check = SnmpCheck('snmp', common.MIBS_FOLDER, [instance]) check.check(instance) aggregator.assert_metric('snmp.extractValue', metric_type=aggregator.GAUGE, count=1, value=6, tags=tags) def test_scalar(aggregator):
64
64
179
7
57
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_scalar
test_scalar
227
246
227
227
009117c27ab03e27b8699ceee003e99e8727f638
bigcode/the-stack
train
d634d604cfa7ab7bc9717b81
train
function
def test_table_v3_SHA_AES(aggregator): """ Support SNMP V3 priv modes: SHA + AES """ # build multiple confgs auth = 'SHA' priv = 'AES' name = 'instance_{}_{}'.format(auth, priv) instance = common.generate_v3_instance_config( common.TABULAR_OBJECTS, name=name, user...
def test_table_v3_SHA_AES(aggregator):
""" Support SNMP V3 priv modes: SHA + AES """ # build multiple confgs auth = 'SHA' priv = 'AES' name = 'instance_{}_{}'.format(auth, priv) instance = common.generate_v3_instance_config( common.TABULAR_OBJECTS, name=name, user='datadog{}{}'.format(auth.upper(), pri...
aggregator.assert_metric_has_tag_prefix(metric_name, tag, at_least=1) aggregator.assert_metric('snmp.sysUpTimeInstance', count=1) # Test service check aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=common.CHECK_TAGS, at_least=1) common.assert_common_metrics(agg...
99
99
330
11
88
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_table_v3_SHA_AES
test_table_v3_SHA_AES
522
558
522
522
415d13b20bfc99c801a5f8521757bc4db8cc403a
bigcode/the-stack
train
2c34f01282810e20b896b01f
train
function
def test_table_regex_match(aggregator): metrics = [ { 'MIB': "IF-MIB", 'table': "ifTable", 'symbols': ["ifInOctets", "ifOutOctets"], 'metric_tags': [ {'tag': "interface", 'column': "ifDescr"}, {'column': "ifDescr", 'match': '(\\...
def test_table_regex_match(aggregator):
metrics = [ { 'MIB': "IF-MIB", 'table': "ifTable", 'symbols': ["ifInOctets", "ifOutOctets"], 'metric_tags': [ {'tag': "interface", 'column': "ifDescr"}, {'column': "ifDescr", 'match': '(\\w)(\\w+)', 'tags': {'prefix': '\\1', 'su...
=1) aggregator.assert_metric('snmp.sysUpTimeInstance', count=1) # Test service check aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=common.CHECK_TAGS, at_least=1) common.assert_common_metrics(aggregator) aggregator.all_metrics_asserted() def test_table_regex_match(aggr...
82
82
276
9
73
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_table_regex_match
test_table_regex_match
345
378
345
345
829eefcbff2ac84b0f0801e010df0a991709375e
bigcode/the-stack
train
c9e2942cdac905b00dc96068
train
function
def test_metric_tag_matching(aggregator): metrics = common.SUPPORTED_METRIC_TYPES instance = common.generate_instance_config(metrics) instance['metric_tags'] = [ { 'MIB': 'SNMPv2-MIB', 'symbol': 'sysName', 'match': '(\\d\\d)(.*)', 'tags': {'host_prefix...
def test_metric_tag_matching(aggregator):
metrics = common.SUPPORTED_METRIC_TYPES instance = common.generate_instance_config(metrics) instance['metric_tags'] = [ { 'MIB': 'SNMPv2-MIB', 'symbol': 'sysName', 'match': '(\\d\\d)(.*)', 'tags': {'host_prefix': '\\1', 'host': '\\2'}, } ] ...
IDs.'.format(instance['metric_tags'][1]['symbol']) ) for _, level, message in caplog.record_tuples: if level == logging.WARNING and message == expected_message: break else: raise AssertionError('Expected WARNING log with message `{}`'.format(expected_message)) def test_metric_tag...
71
71
237
9
62
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_metric_tag_matching
test_metric_tag_matching
1,178
1,205
1,178
1,178
83ca4df3f933976fb80f4914f8bb29c5b2e767e5
bigcode/the-stack
train
1ba05c4c62dbd1e939f5649a
train
function
def test_network_failure(aggregator): """ Network failure is reported in service check """ instance = common.generate_instance_config(common.SCALAR_OBJECTS) # Change port so connection will fail instance['port'] = 162 check = common.create_check(instance) check.check(instance) # T...
def test_network_failure(aggregator):
""" Network failure is reported in service check """ instance = common.generate_instance_config(common.SCALAR_OBJECTS) # Change port so connection will fail instance['port'] = 162 check = common.create_check(instance) check.check(instance) # Test service check aggregator.asser...
1) # Test service check aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=common.CHECK_TAGS, at_least=1) common.assert_common_metrics(aggregator) aggregator.all_metrics_asserted() def test_network_failure(aggregator):
64
64
121
8
56
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_network_failure
test_network_failure
666
682
666
666
7e367259b5a8aaa326f37517f5311f8922debbf0
bigcode/the-stack
train
734877584bf9120785124741
train
function
def test_oids_cache_metrics_collected_using_scalar_oids(aggregator): """ Test if we still collect all metrics using saved scalar oids. """ instance = common.generate_instance_config(common.TABULAR_OBJECTS) instance['refresh_oids_cache_interval'] = 3600 check = common.create_check(instance) ...
def test_oids_cache_metrics_collected_using_scalar_oids(aggregator):
""" Test if we still collect all metrics using saved scalar oids. """ instance = common.generate_instance_config(common.TABULAR_OBJECTS) instance['refresh_oids_cache_interval'] = 3600 check = common.create_check(instance) def run_check(): aggregator.reset() check.check(insta...
aggregator.assert_metric('snmp.sysUpTimeInstance', count=1) common.assert_common_metrics(aggregator) aggregator.assert_all_metrics_covered() assert ( len([record for record in caplog.records if "No SNMP response received before timeout" in record.message]) > 0 ) def test_oids_cache_metrics...
82
82
276
16
66
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_oids_cache_metrics_collected_using_scalar_oids
test_oids_cache_metrics_collected_using_scalar_oids
1,239
1,269
1,239
1,239
951fa5f9dd000c5a3ee6ec9d788762f3808fd81b
bigcode/the-stack
train
a509675e97665443de2c31ae
train
function
def test_metric_tag_profile_manual(aggregator): instance = common.generate_instance_config([]) instance['profile'] = 'profile1' definition = { 'metric_tags': [{'OID': '1.3.6.1.2.1.1.5.0', 'symbol': 'sysName', 'tag': 'snmp_host'}], 'metrics': common.SUPPORTED_METRIC_TYPES, } init_conf...
def test_metric_tag_profile_manual(aggregator):
instance = common.generate_instance_config([]) instance['profile'] = 'profile1' definition = { 'metric_tags': [{'OID': '1.3.6.1.2.1.1.5.0', 'symbol': 'sysName', 'tag': 'snmp_host'}], 'metrics': common.SUPPORTED_METRIC_TYPES, } init_config = {'profiles': {'profile1': {'definition': de...
tags=tags, count=1) aggregator.assert_metric('snmp.sysUpTimeInstance', count=1) aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=tags, at_least=1) common.assert_common_metrics(aggregator) aggregator.all_metrics_asserted() def test_metric_tag_profile_manual(aggregator):
78
78
263
10
68
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_metric_tag_profile_manual
test_metric_tag_profile_manual
1,072
1,096
1,072
1,072
03494e71e052502a582b6c8bce7fe0e7ec5d5301
bigcode/the-stack
train
e240ea4615018ddaae884bd7
train
function
def test_transient_error(aggregator): instance = common.generate_instance_config(common.SUPPORTED_METRIC_TYPES) check = common.create_check(instance) with mock.patch('datadog_checks.snmp.commands._handle_error', side_effect=RuntimeError): check.check(instance) aggregator.assert_service_check("...
def test_transient_error(aggregator):
instance = common.generate_instance_config(common.SUPPORTED_METRIC_TYPES) check = common.create_check(instance) with mock.patch('datadog_checks.snmp.commands._handle_error', side_effect=RuntimeError): check.check(instance) aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.CRIT...
) # Test service check aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=common.CHECK_TAGS, at_least=1) common.assert_common_metrics(aggregator) aggregator.all_metrics_asserted() def test_transient_error(aggregator):
64
64
129
9
55
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_transient_error
test_transient_error
70
80
70
70
c7ec2f9634c7198cc601b7090f6fb496b2d9ac49
bigcode/the-stack
train
9286fd91f9e5ba9541c63c31
train
function
@pytest.mark.parametrize( 'most_specific_oid, least_specific_oid', [ pytest.param('1.3.6.1.4.1.8072.3.2.10', '1.3.6.1.4.1.5082.4', id='literal-literal'), pytest.param('1.3.6.1.4.1.8072.3.2.10', '1.3.6.1.4.1.8072.3.2.9', id='literal-literal-same-length'), pytest.param('1.3.6.1.4.1.8072.3....
@pytest.mark.parametrize( 'most_specific_oid, least_specific_oid', [ pytest.param('1.3.6.1.4.1.8072.3.2.10', '1.3.6.1.4.1.5082.4', id='literal-literal'), pytest.param('1.3.6.1.4.1.8072.3.2.10', '1.3.6.1.4.1.8072.3.2.9', id='literal-literal-same-length'), pytest.param('1.3.6.1.4.1.8072.3....
instance = common.generate_instance_config([]) most_specific_profile = {'metrics': common.SUPPORTED_METRIC_TYPES, 'sysobjectid': most_specific_oid} least_specific_profile = {'metrics': common.CAST_METRICS, 'sysobjectid': least_specific_oid} init_config = { 'profiles': {'most': {'definition': m...
@pytest.mark.parametrize( 'most_specific_oid, least_specific_oid', [ pytest.param('1.3.6.1.4.1.8072.3.2.10', '1.3.6.1.4.1.5082.4', id='literal-literal'), pytest.param('1.3.6.1.4.1.8072.3.2.10', '1.3.6.1.4.1.8072.3.2.9', id='literal-literal-same-length'), pytest.param('1.3.6.1.4.1.8072.3....
279
163
544
279
0
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_profile_sys_object_prefix
test_profile_sys_object_prefix
804
840
804
814
85f024505d868556f6b842f829af8bcd6f99a463
bigcode/the-stack
train
287e0e43b7820244decca926
train
function
def test_profile_sys_object_no_metrics(): """If an instance is created without metrics and there is no profile defined, an error is raised.""" instance = common.generate_instance_config([]) with pytest.raises(ConfigurationError): SnmpCheck('snmp', {'profiles': {}}, [instance])
def test_profile_sys_object_no_metrics():
"""If an instance is created without metrics and there is no profile defined, an error is raised.""" instance = common.generate_instance_config([]) with pytest.raises(ConfigurationError): SnmpCheck('snmp', {'profiles': {}}, [instance])
matching profile. check.check(instance) check._running = False check._thread.join() for record in caplog.records: if "Host {} didn't match a profile".format(host) in record.message: break else: pytest.fail() def test_profile_sys_object_no_metrics():
64
64
60
8
56
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_profile_sys_object_no_metrics
test_profile_sys_object_no_metrics
892
896
892
892
517d35f48050ece4b2e2652ff5b38ecad35e7ea8
bigcode/the-stack
train
d37daba04b5e6fd9ba09cb55
train
function
def test_scalar_with_tags(aggregator): """ Support SNMP scalar objects with tags """ instance = common.generate_instance_config(common.SCALAR_OBJECTS_WITH_TAGS) check = common.create_check(instance) check.check(instance) # Test metrics for metric in common.SCALAR_OBJECTS_WITH_TAGS: ...
def test_scalar_with_tags(aggregator):
""" Support SNMP scalar objects with tags """ instance = common.generate_instance_config(common.SCALAR_OBJECTS_WITH_TAGS) check = common.create_check(instance) check.check(instance) # Test metrics for metric in common.SCALAR_OBJECTS_WITH_TAGS: metric_name = "snmp." + (metric.ge...
common.create_check(instance) check.check(instance) aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=common.CHECK_TAGS, at_least=1) assert "Unable to submit metric" in caplog.text def test_scalar_with_tags(aggregator):
64
64
192
9
54
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_scalar_with_tags
test_scalar_with_tags
643
663
643
643
744d3d9831ca17ca2a84df2ccaec89e0c3a89fe3
bigcode/the-stack
train
6a6340a2ce863a368e04972e
train
function
def test_submitted_metrics_count(aggregator): instance = common.generate_instance_config(common.SCALAR_OBJECTS) check = common.create_check(instance) check.check(instance) telemetry_tags = common.CHECK_TAGS + ['loader:python'] for metric in common.SCALAR_OBJECTS: metric_name = "snmp." + (m...
def test_submitted_metrics_count(aggregator):
instance = common.generate_instance_config(common.SCALAR_OBJECTS) check = common.create_check(instance) check.check(instance) telemetry_tags = common.CHECK_TAGS + ['loader:python'] for metric in common.SCALAR_OBJECTS: metric_name = "snmp." + (metric.get('name') or metric.get('symbol')) ...
_name, tags=common.CHECK_TAGS, count=1) aggregator.assert_metric('snmp.sysUpTimeInstance', count=1) # Test service check aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=common.CHECK_TAGS, at_least=1) common.assert_common_metrics(aggregator, tags=common.CHECK_TAGS) aggre...
102
102
342
10
92
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_submitted_metrics_count
test_submitted_metrics_count
249
280
249
249
76b6c91dfabfabd4905d79d7fcfd433484aec8dc
bigcode/the-stack
train
a0133d75baec53f47aef352b
train
function
def test_different_mibs(aggregator): metrics = [ { 'MIB': 'ENTITY-SENSOR-MIB', 'table': 'entitySensorObjects', 'symbols': ['entPhySensorValue'], 'metric_tags': [ {'tag': 'desc', 'column': 'entLogicalDescr', 'table': 'entLogicalTable', 'MIB': 'E...
def test_different_mibs(aggregator):
metrics = [ { 'MIB': 'ENTITY-SENSOR-MIB', 'table': 'entitySensorObjects', 'symbols': ['entPhySensorValue'], 'metric_tags': [ {'tag': 'desc', 'column': 'entLogicalDescr', 'table': 'entLogicalTable', 'MIB': 'ENTITY-MIB'} ], } ...
_device:{}'.format(device_ip)] common.assert_common_device_metrics(aggregator, devices_monitored_value=1, count=1, tags=tags) common.assert_common_check_run_metrics(aggregator, network_tags) aggregator.assert_all_metrics_covered() def test_different_mibs(aggregator):
64
64
141
10
54
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_different_mibs
test_different_mibs
985
1,001
985
985
31ed0a7e768cdfe39db672adad25734dcf47e536
bigcode/the-stack
train
2d4783fe08a9d9efbf4ca005
train
function
def test_discovery(aggregator): host = socket.gethostbyname(common.HOST) network = ipaddress.ip_network(u'{}/29'.format(host), strict=False).with_prefixlen check_tags = [ 'snmp_device:{}'.format(host), 'snmp_profile:profile1', 'autodiscovery_subnet:{}'.format(to_native_string(network...
def test_discovery(aggregator):
host = socket.gethostbyname(common.HOST) network = ipaddress.ip_network(u'{}/29'.format(host), strict=False).with_prefixlen check_tags = [ 'snmp_device:{}'.format(host), 'snmp_profile:profile1', 'autodiscovery_subnet:{}'.format(to_native_string(network)), ] network_tags = ['n...
finding a matching profile. check.check(instance) check._running = False check._thread.join() for record in caplog.records: if "Host {} didn't match a profile".format(host) in record.message: break else: pytest.fail() def test_profile_sys_object_no_metrics(): """I...
126
126
422
8
118
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_discovery
test_discovery
899
944
899
899
576f187e88a4ef22d6920a9e935bea0d4d2e485f
bigcode/the-stack
train
a5a57cfb1a84fc9ffc78d370
train
function
def test_invalid_forcedtype_metric(aggregator, caplog): """ If a forced type is invalid a warning should be issued but the check should continue processing the remaining metrics. """ instance = common.generate_instance_config(common.INVALID_FORCED_METRICS) check = common.create_check(instance) ...
def test_invalid_forcedtype_metric(aggregator, caplog):
""" If a forced type is invalid a warning should be issued but the check should continue processing the remaining metrics. """ instance = common.generate_instance_config(common.INVALID_FORCED_METRICS) check = common.create_check(instance) check.check(instance) aggregator.assert_service...
check aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=common.CHECK_TAGS, at_least=1) common.assert_common_metrics(aggregator) aggregator.all_metrics_asserted() def test_invalid_forcedtype_metric(aggregator, caplog):
64
64
115
14
50
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_invalid_forcedtype_metric
test_invalid_forcedtype_metric
628
640
628
628
2cb2008bdec3cc8f6a81fabd1779d8f5e18da760
bigcode/the-stack
train
32e67c3c303e713dd394ccea
train
function
@pytest.mark.parametrize( "refresh_interval, getnext_call_counts, getnext_call_count_after_reset", [ # When the cache is enabled. # GETNEXT calls are made only at the first check and run and after every reset pytest.param( 3600, [GETNEXT_CALL_COUNT_PER_CHECK_RUN, ...
@pytest.mark.parametrize( "refresh_interval, getnext_call_counts, getnext_call_count_after_reset", [ # When the cache is enabled. # GETNEXT calls are made only at the first check and run and after every reset pytest.param( 3600, [GETNEXT_CALL_COUNT_PER_CHECK_RUN, ...
""" Check that less snmp PDU calls are made using `refresh_oids_cache_interval` config. """ instance = common.generate_instance_config(common.BULK_TABULAR_OBJECTS) instance['refresh_oids_cache_interval'] = refresh_interval check = common.create_check(instance) with mock.patch('datadog_check...
@pytest.mark.parametrize( "refresh_interval, getnext_call_counts, getnext_call_count_after_reset", [ # When the cache is enabled. # GETNEXT calls are made only at the first check and run and after every reset pytest.param( 3600, [GETNEXT_CALL_COUNT_PER_CHECK_RUN, ...
225
115
385
225
0
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_oids_cache_command_calls
test_oids_cache_command_calls
1,321
1,362
1,321
1,346
1124e0fb12e78ea77a37e7a199fb1382ad66ab53
bigcode/the-stack
train
b5499b4c2863413ebba43999
train
function
def test_profile(aggregator): instance = common.generate_instance_config([]) instance['profile'] = 'profile1' init_config = {'profiles': {'profile1': {'definition': {'metrics': common.SUPPORTED_METRIC_TYPES}}}} check = SnmpCheck('snmp', init_config, [instance]) check.check(instance) common_tags...
def test_profile(aggregator):
instance = common.generate_instance_config([]) instance['profile'] = 'profile1' init_config = {'profiles': {'profile1': {'definition': {'metrics': common.SUPPORTED_METRIC_TYPES}}}} check = SnmpCheck('snmp', init_config, [instance]) check.check(instance) common_tags = common.CHECK_TAGS + ['snmp_...
', value=0.06) aggregator.assert_metric('snmp.cpuload2', value=0.06) aggregator.assert_metric('snmp.sysUpTimeInstance', count=1) common.assert_common_metrics(aggregator) aggregator.all_metrics_asserted() def test_profile(aggregator):
64
64
164
7
57
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_profile
test_profile
698
712
698
698
481a9bc58769608a23837a2c6eb10055485a92ba
bigcode/the-stack
train
6861ec288cc7b3a837e7fe47
train
function
def test_table_v3_MD5_DES(aggregator): """ Support SNMP V3 priv modes: MD5 + DES """ # build multiple confgs auth = 'MD5' priv = 'DES' name = 'instance_{}_{}'.format(auth, priv) instance = common.generate_v3_instance_config( common.TABULAR_OBJECTS, name=name, use...
def test_table_v3_MD5_DES(aggregator):
""" Support SNMP V3 priv modes: MD5 + DES """ # build multiple confgs auth = 'MD5' priv = 'DES' name = 'instance_{}_{}'.format(auth, priv) instance = common.generate_v3_instance_config( common.TABULAR_OBJECTS, name=name, user='datadog{}{}'.format(auth.upper(), pr...
mtag['tag'] aggregator.assert_metric_has_tag_prefix(metric_name, tag, at_least=1) aggregator.assert_metric('snmp.sysUpTimeInstance', count=1) aggregator.assert_service_check("snmp.can_check", status=SnmpCheck.OK, tags=common.CHECK_TAGS, at_least=1) common.assert_common_metrics(aggregator) ...
99
99
333
12
87
mchelen-gov/integrations-core
snmp/tests/test_check.py
Python
test_table_v3_MD5_DES
test_table_v3_MD5_DES
403
440
403
403
f1147c8685973bd128fae00ee6e849258bfbbf0a
bigcode/the-stack
train
455dee0a9b1ce916e9443302
train
class
class Zip(Package): """Zip analysis package.""" def extract_zip(self, zip_path, extract_path, password): """Extracts a nested ZIP file. @param zip_path: ZIP path @param extract_path: where to extract @param password: ZIP password """ # Test if zip file contains a...
class Zip(Package):
"""Zip analysis package.""" def extract_zip(self, zip_path, extract_path, password): """Extracts a nested ZIP file. @param zip_path: ZIP path @param extract_path: where to extract @param password: ZIP password """ # Test if zip file contains a file named as itsel...
# Copyright (C) 2010-2013 Claudio Guarnieri. # Copyright (C) 2014-2016 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. import os import shutil import logging from zipfile import ZipFile, BadZipfile from lib.common.abstracts...
117
198
661
5
112
Yuanmessi/Bold-Falcon
analyzer/windows/modules/packages/zip.py
Python
Zip
Zip
17
97
17
17
1c45ffe8761ae69d129e82474b52970653399a87
bigcode/the-stack
train
ee67154d9187e38b6cc77858
train
function
def _validate_saved_model(tf_saved_model_dir, tf_meta_graph_tags, tf_signature_def_key): """ Validate the TensorFlow SavedModel by attempting to load it in a new TensorFlow graph. If the loading process fails, any exceptions thrown by TensorFlow will be propagated. """ validation_tf_graph = tf.Graph...
def _validate_saved_model(tf_saved_model_dir, tf_meta_graph_tags, tf_signature_def_key):
""" Validate the TensorFlow SavedModel by attempting to load it in a new TensorFlow graph. If the loading process fails, any exceptions thrown by TensorFlow will be propagated. """ validation_tf_graph = tf.Graph() validation_tf_sess = tf.Session(graph=validation_tf_graph) with validation_tf_...
_key) pyfunc.add_to_model(mlflow_model, loader_module="mlflow.tensorflow", env=conda_env_subpath) mlflow_model.save(os.path.join(path, "MLmodel")) def _validate_saved_model(tf_saved_model_dir, tf_meta_graph_tags, tf_signature_def_key):
63
64
133
20
43
Kublai-Jing/mlflow
mlflow/tensorflow.py
Python
_validate_saved_model
_validate_saved_model
160
171
160
160
cb91b11bf4533716cf8fe3ee8ef1180f93295e0e
bigcode/the-stack
train
35dfe7a6a47280e24822b53a
train
function
def _load_model(tf_saved_model_dir, tf_sess, tf_meta_graph_tags, tf_signature_def_key): """ Load a specified TensorFlow model consisting of a TensorFlow meta graph and signature definition from a serialized TensorFlow ``SavedModel`` collection. :param tf_saved_model_dir: The local filesystem path or ru...
def _load_model(tf_saved_model_dir, tf_sess, tf_meta_graph_tags, tf_signature_def_key):
""" Load a specified TensorFlow model consisting of a TensorFlow meta graph and signature definition from a serialized TensorFlow ``SavedModel`` collection. :param tf_saved_model_dir: The local filesystem path or run-relative artifact path to the model. :param tf_sess: The TensorFlow session in whi...
flavor_conf = _get_flavor_configuration(model_path=path, flavor_name=FLAVOR_NAME) tf_saved_model_dir = os.path.join(path, flavor_conf['saved_model_dir']) return _load_model(tf_saved_model_dir=tf_saved_model_dir, tf_sess=tf_sess, tf_meta_graph_tags=flavor_conf['meta_graph_tags'], ...
110
111
372
23
87
Kublai-Jing/mlflow
mlflow/tensorflow.py
Python
_load_model
_load_model
207
234
207
207
8a810659f0d1b396107a6a98701be87bfff2eb49
bigcode/the-stack
train
863b0b5459a2caf6f650021a
train
function
def save_model(tf_saved_model_dir, tf_meta_graph_tags, tf_signature_def_key, path, mlflow_model=Model(), conda_env=None): """ Save a *serialized* collection of TensorFlow graphs and variables as an MLflow model to a local path. This method operates on TensorFlow variables and graphs that have...
def save_model(tf_saved_model_dir, tf_meta_graph_tags, tf_signature_def_key, path, mlflow_model=Model(), conda_env=None):
""" Save a *serialized* collection of TensorFlow graphs and variables as an MLflow model to a local path. This method operates on TensorFlow variables and graphs that have been serialized in TensorFlow's ``SavedModel`` format. For more information about ``SavedModel`` format, see the TensorFlow docu...
dictionary representation of a Conda environment or the path to a Conda environment yaml file. If provided, this decribes the environment this model should be run in. At minimum, it should specify the dependencies contained in ``mlflow.tensorflow.DEFAUL...
242
242
807
32
210
Kublai-Jing/mlflow
mlflow/tensorflow.py
Python
save_model
save_model
89
157
89
90
8f510987a0d954693ad1356e0d4219ab0b0f53f7
bigcode/the-stack
train
af07bfdcea5f154c09af3d24
train
class
class _TFWrapper(object): """ Wrapper class that exposes a TensorFlow model for inference via a ``predict`` function such that predict(data: pandas.DataFrame) -> pandas.DataFrame. """ def __init__(self, tf_sess, tf_graph, signature_def): """ :param tf_sess: The TensorFlow session use...
class _TFWrapper(object):
""" Wrapper class that exposes a TensorFlow model for inference via a ``predict`` function such that predict(data: pandas.DataFrame) -> pandas.DataFrame. """ def __init__(self, tf_sess, tf_graph, signature_def): """ :param tf_sess: The TensorFlow session used to evaluate the model. ...
_pyfunc``. This function loads an MLflow model with the TensorFlow flavor into a new TensorFlow graph and exposes it behind the `pyfunc.predict` interface. """ tf_graph = tf.Graph() tf_sess = tf.Session(graph=tf_graph) with tf_graph.as_default(): signature_def = load_model(path=path, tf_...
115
115
386
6
109
Kublai-Jing/mlflow
mlflow/tensorflow.py
Python
_TFWrapper
_TFWrapper
251
287
251
251
1173ec7194c25f8cd735f99d0a6f2436dee0de37
bigcode/the-stack
train
7bf69b9cca885f5c4575ba7a
train
function
def log_model(tf_saved_model_dir, tf_meta_graph_tags, tf_signature_def_key, artifact_path, conda_env=None): """ Log a *serialized* collection of TensorFlow graphs and variables as an MLflow model for the current run. This method operates on TensorFlow variables and graphs that have been se...
def log_model(tf_saved_model_dir, tf_meta_graph_tags, tf_signature_def_key, artifact_path, conda_env=None):
""" Log a *serialized* collection of TensorFlow graphs and variables as an MLflow model for the current run. This method operates on TensorFlow variables and graphs that have been serialized in TensorFlow's ``SavedModel`` format. For more information about ``SavedModel`` format, see the TensorFlow d...
_pb2 import DIRECTORY_NOT_EMPTY from mlflow.tracking.artifact_utils import _get_model_log_dir from mlflow.utils.environment import _mlflow_conda_env from mlflow.utils.file_utils import _copy_file_or_tree from mlflow.utils.model_utils import _get_flavor_configuration FLAVOR_NAME = "tensorflow" DEFAULT_CONDA_ENV = _mlf...
151
151
505
27
124
Kublai-Jing/mlflow
mlflow/tensorflow.py
Python
log_model
log_model
45
86
45
46
08065c50af621a40cb676974bb20ea94ec5d935b
bigcode/the-stack
train
6446e1c41d0dfa55cba85535
train
function
def load_model(path, tf_sess, run_id=None): """ Load an MLflow model that contains the TensorFlow flavor from the specified path. **This method must be called within a TensorFlow graph context.** :param path: The local filesystem path or run-relative artifact path to the model. :param tf_sess: The...
def load_model(path, tf_sess, run_id=None):
""" Load an MLflow model that contains the TensorFlow flavor from the specified path. **This method must be called within a TensorFlow graph context.** :param path: The local filesystem path or run-relative artifact path to the model. :param tf_sess: The TensorFlow session in which to the load the...
it in a new TensorFlow graph. If the loading process fails, any exceptions thrown by TensorFlow will be propagated. """ validation_tf_graph = tf.Graph() validation_tf_sess = tf.Session(graph=validation_tf_graph) with validation_tf_graph.as_default(): _load_model(tf_saved_model_dir=tf_saved_...
113
113
377
13
100
Kublai-Jing/mlflow
mlflow/tensorflow.py
Python
load_model
load_model
174
204
174
174
b7166f36b8412ffdfd18fa36196ff1dc5b4c7495
bigcode/the-stack
train
54c50ae2d532c48acf73facc
train
function
def _load_pyfunc(path): """ Load PyFunc implementation. Called by ``pyfunc.load_pyfunc``. This function loads an MLflow model with the TensorFlow flavor into a new TensorFlow graph and exposes it behind the `pyfunc.predict` interface. """ tf_graph = tf.Graph() tf_sess = tf.Session(graph=tf_g...
def _load_pyfunc(path):
""" Load PyFunc implementation. Called by ``pyfunc.load_pyfunc``. This function loads an MLflow model with the TensorFlow flavor into a new TensorFlow graph and exposes it behind the `pyfunc.predict` interface. """ tf_graph = tf.Graph() tf_sess = tf.Session(graph=tf_graph) with tf_graph....
, export_dir=tf_saved_model_dir) if tf_signature_def_key not in meta_graph_def.signature_def: raise MlflowException("Could not find signature def key %s" % tf_signature_def_key) return meta_graph_def.signature_def[tf_signature_def_key] def _load_pyfunc(path):
64
64
130
7
57
Kublai-Jing/mlflow
mlflow/tensorflow.py
Python
_load_pyfunc
_load_pyfunc
237
248
237
237
7363702435a77cfdfa06ebf67f347d0e88c0a724
bigcode/the-stack
train
dd5d39316e7c044120e1cec1
train
class
class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_name("pass").click() wd.find_element_by_name("pass").clear() wd.find_element_by_name("pass").send_keys(...
class SessionHelper:
def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_name("pass").click() wd.find_element_by_name("pass").clear() wd.find_element_by_name("pass").send_keys(password) wd....
class SessionHelper:
4
97
326
4
0
kovernik/python_training
fixture/session.py
Python
SessionHelper
SessionHelper
1
44
1
1
41dd6bb51ae7cc8adcdb5d33e486d9081547a8c3
bigcode/the-stack
train
3072080e264f416749d36933
train
function
def main(): # セッション開始 session = requests.session() # csrf_token取得 r = session.get(LOGIN_URL) s = BeautifulSoup(r.text, 'lxml') csrf_token = s.find(attrs={'name': 'csrf_token'}).get('value') # パラメータセット login_info = { "csrf_token": csrf_token, "username": config.USERNAME,...
def main(): # セッション開始
session = requests.session() # csrf_token取得 r = session.get(LOGIN_URL) s = BeautifulSoup(r.text, 'lxml') csrf_token = s.find(attrs={'name': 'csrf_token'}).get('value') # パラメータセット login_info = { "csrf_token": csrf_token, "username": config.USERNAME, "password": confi...
#!/usr/bin/env python # coding: utf-8 """ atcoderの問題のスクレイピング用スクリプト pipenv run start """ import sys import requests import copy from bs4 import BeautifulSoup import config LOGIN_URL = "https://atcoder.jp/login" def main(): # セッション開始
74
77
258
9
65
pogin503/vbautil
atcoder/scrape/.ipynb_checkpoints/scrape-checkpoint.py
Python
main
main
19
50
19
20
0e7b20a6accc7ec91087d9c98922b08e34af50a3
bigcode/the-stack
train
20e106af155f6ae1a64d8863
train
class
class ReorderLevelChangeRequest(Document): def on_submit(self): item = frappe.get_doc("Item",self.item_code) to_remove = [ row for row in item.reorder_levels] [ item.remove(row) for row in to_remove ] child = self.reorder_item for c in child: item.append("reorder_levels",{ "warehouse_reorder_level" : ...
class ReorderLevelChangeRequest(Document):
def on_submit(self): item = frappe.get_doc("Item",self.item_code) to_remove = [ row for row in item.reorder_levels] [ item.remove(row) for row in to_remove ] child = self.reorder_item for c in child: item.append("reorder_levels",{ "warehouse_reorder_level" : c.change_reorder_level, "warehouse_reor...
# -*- coding: utf-8 -*- # Copyright (c) 2020, TeamPRO and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class ReorderLevelChangeRequest(Document):
58
64
150
8
49
TridotsTech/senergy
senergy/senergy/doctype/reorder_level_change_request/reorder_level_change_request.py
Python
ReorderLevelChangeRequest
ReorderLevelChangeRequest
9
23
9
9
6aae687fe20ee27e3373bd78df1e3b7ef30e06eb
bigcode/the-stack
train
71c6bb79db20223626ba28f0
train
class
class readlat(): head = ("head",">i") tail = ("tail",">i") head2 = ("head2",">i") tail2 = ("tail2",">i") def __init__(self,y=64): self.y=y file=thisdir+'/GTAXDIR/GTAXLOC.GGLA'+str(self.y) data=open(file,'br') dt = np.dtype([self.head ,("header",...
class readlat():
head = ("head",">i") tail = ("tail",">i") head2 = ("head2",">i") tail2 = ("tail2",">i") def __init__(self,y=64): self.y=y file=thisdir+'/GTAXDIR/GTAXLOC.GGLA'+str(self.y) data=open(file,'br') dt = np.dtype([self.head ,("header",">64S16") ...
'] if cyclic: lon = np.append(lon,[360.0]) return lon def showlon(self,cyclic=False): lon=self.getlon(cyclic=cyclic) for i in range(len(lon)): print(i,':',lon[i]) class readlat():
64
64
208
4
60
earth06/pygtool
pygtool.py
Python
readlat
readlat
183
206
183
183
58e3d0f9b395b29d1df346137c05c9137840f6ef
bigcode/the-stack
train
3f1876e88acc41d22885389b
train
function
def to_netcdf(lon,lat,datetime,arr ,filename='test.nc' ,arrname='undefined' ,attrs={'None':'None'}): ds = xr.Dataset( { arrname:(['time','lat','lon'],arr) }, coords={ 'time':datetime, 'lat':('lat',lat,{'units':'...
def to_netcdf(lon,lat,datetime,arr ,filename='test.nc' ,arrname='undefined' ,attrs={'None':'None'}):
ds = xr.Dataset( { arrname:(['time','lat','lon'],arr) }, coords={ 'time':datetime, 'lat':('lat',lat,{'units':'degrees_north'}), 'lon':('lon',lon,{'units':'degrees_east'}) } ,attrs=attrs ) return ds
: arr = cutil.add_cyclic_point(arr) # print(self.getDate(timestep=timestep)) return arr def to_netcdf(lon,lat,datetime,arr ,filename='test.nc' ,arrname='undefined' ,attrs={'None':'None'}):
64
64
116
37
26
earth06/pygtool
pygtool.py
Python
to_netcdf
to_netcdf
309
326
309
313
62e792c7015332c0c4af32ca547ca679204378e6
bigcode/the-stack
train
7f7a5f4570f3b9b1d3db5ffc
train
class
class readgrid(): def __init__(self,x=128,y=64): self.x=x self.y=y def getlonlat(self,cyclic=False): lat=readlat(self.y).getlat() lon=readlon(self.x).getlon(cyclic=cyclic) return lon,lat def getmesh(self,cyclic=False): x,y=self.getlonlat(cyclic=cyclic) ...
class readgrid():
def __init__(self,x=128,y=64): self.x=x self.y=y def getlonlat(self,cyclic=False): lat=readlat(self.y).getlat() lon=readlon(self.x).getlon(cyclic=cyclic) return lon,lat def getmesh(self,cyclic=False): x,y=self.getlonlat(cyclic=cyclic) xx,yy=np.meshgrid...
self.chunk = chunk data.close() def getlat(self): lat = self.chunk[0]['arr'] return lat def showlat(self): lat = self.getlat() for i in range(len(lat)): print(i,':',lat[i]) class readgrid():
64
64
163
4
60
earth06/pygtool
pygtool.py
Python
readgrid
readgrid
207
223
207
207
f39d3d4fe07b49b5d8ad2be4f6bac60b07082d0c
bigcode/the-stack
train
dc7115c370ef98eef97c1965
train
class
class read3D: """ read gtool format data to generate this instance pass filename Constant value --------------- head,tail,head2,tail2 :4byte binary size info of fortran binary header Method -------------- __init__(self,data,count,x,y,z) getarr(self,timestep) ge...
class read3D:
""" read gtool format data to generate this instance pass filename Constant value --------------- head,tail,head2,tail2 :4byte binary size info of fortran binary header Method -------------- __init__(self,data,count,x,y,z) getarr(self,timestep) getheader() ...
import numpy as np import datetime import cartopy.util as cutil import carto_kit as ckit import xarray as xr import pandas as pd import gtutil import gtplot import pathlib """ """ thisdir=str(pathlib.Path(__file__).resolve().parent) class read3D:
67
256
1,074
5
62
earth06/pygtool
pygtool.py
Python
read3D
read3D
14
153
14
14
067adbda75318c956a41b6cdb5d5350b0beb40b9
bigcode/the-stack
train
3a2b420557905674ec20565b
train
class
class readalt(): """ read sigma if you need sigma,pa,beta, set count=3 """ head = ("head",">i") tail = ("tail",">i") head2 = ("head2",">i") tail2 = ("tail2",">i") def __init__(self,z=36): self.z=z if z==36: file=thisdir+'/GTAXDIR/GTAXLOC.HETA'+str(self.z)...
class readalt():
""" read sigma if you need sigma,pa,beta, set count=3 """ head = ("head",">i") tail = ("tail",">i") head2 = ("head2",">i") tail2 = ("tail2",">i") def __init__(self,z=36): self.z=z if z==36: file=thisdir+'/GTAXDIR/GTAXLOC.HETA'+str(self.z) elif z==...
(self.x).getlon(cyclic=cyclic) return lon,lat def getmesh(self,cyclic=False): x,y=self.getlonlat(cyclic=cyclic) xx,yy=np.meshgrid(x,y) return xx,yy def getmesh2(self): y=readlat(self.y).getlat() x=np.arange(1.40625,360.1,2.8125) xx,yy=np.meshgrid(x,y) ...
113
113
378
4
108
earth06/pygtool
pygtool.py
Python
readalt
readalt
226
273
226
226
6f90f9eb2144214c4d5d113f93d994ba8f6b5900
bigcode/the-stack
train
b2d5bedb6f0da30fb4d3b99a
train
class
class read2D(read3D): """ read surface Parameter ----------------- file : string filename count : totaldata number """ def __init__(self,file,count=1,x=128,y=64,z=None): super().__init__(file,count,x,y,z) pass def getarr(self,timestep=0,cyclic=False,na_values=-999,...
class read2D(read3D):
""" read surface Parameter ----------------- file : string filename count : totaldata number """ def __init__(self,file,count=1,x=128,y=64,z=None): super().__init__(file,count,x,y,z) pass def getarr(self,timestep=0,cyclic=False,na_values=-999,miss=False): "...
Return ------------------ sig :np.ndarray(z) pa :np.ndarray(z) beta :np.ndarray(z) """ sig=self.chunk[0]['arr'] pa=self.chunk[1]['arr'] beta=self.chunk[2]['arr'] return sig,pa,beta class read2D(read3D):
75
75
251
8
66
earth06/pygtool
pygtool.py
Python
read2D
read2D
274
307
274
274
27d87f2dabfb04f85b26479a03feae42bfaf881e
bigcode/the-stack
train
46b0e113feb1dc833cb8b8bd
train
class
class readlon(): head = ("head",">i") tail = ("tail",">i") head2 = ("head2",">i") tail2 = ("tail2",">i") def __init__(self,x=128): self.x=x file=thisdir+'/GTAXDIR/GTAXLOC.GLON'+str(self.x) data=open(file,'br') dt = np.dtype([self.head ,("header"...
class readlon():
head = ("head",">i") tail = ("tail",">i") head2 = ("head2",">i") tail2 = ("tail2",">i") def __init__(self,x=128): self.x=x file=thisdir+'/GTAXDIR/GTAXLOC.GLON'+str(self.x) data=open(file,'br') dt = np.dtype([self.head ,("header",">64S16") ...
dataarray=np.zeros((end-start,self.z,self.y,x)) for i in range(end-start): dataarray[i,:,:,:]=self.getarr(timestep=start+i,cyclic=cyclic) return dataarray def to_dataset(self): ds = 'Null' return ds class readlon():
69
70
236
4
64
earth06/pygtool
pygtool.py
Python
readlon
readlon
157
182
157
157
36cdddfe57804079d71a795b0c78ec4b6f0a67e9
bigcode/the-stack
train
32510d3da24823771ff5d45c
train
class
class SACTrainer(RLTrainer): """ The SACTrainer is an implementation of the SAC algorithm, with support for discrete actions and recurrent networks. """ def __init__( self, behavior_name: str, reward_buff_cap: int, trainer_settings: TrainerSettings, training:...
class SACTrainer(RLTrainer):
""" The SACTrainer is an implementation of the SAC algorithm, with support for discrete actions and recurrent networks. """ def __init__( self, behavior_name: str, reward_buff_cap: int, trainer_settings: TrainerSettings, training: bool, load: bool, ...
ainers.policy.checkpoint_manager import ModelCheckpoint from mlagents_envs.logging_util import get_logger from mlagents_envs.timers import timed from mlagents_envs.base_env import BehaviorSpec from mlagents.trainers.policy.tf_policy import TFPolicy from mlagents.trainers.policy import Policy from mlagents.trainers.sac...
256
256
3,100
7
248
Taikatou/ml-agents
ml-agents/mlagents/trainers/sac/trainer.py
Python
SACTrainer
SACTrainer
37
428
37
37
0e6dec592fe692e4d65e227a8944a53969029a30
bigcode/the-stack
train
dfeba84b1b07267d82544744
train
function
def add_to_dict(row): global link_id_dict link_id=row["link_id"] link_time=row["link_time"] link_cur_status=row["link_current_status"] link_arr_status=row["link_arrival_status"] if not link_id in link_id_dict: link_id_dict[link_id]=[[link_time, [link_cur_status, link_arr_status]]] ...
def add_to_dict(row):
global link_id_dict link_id=row["link_id"] link_time=row["link_time"] link_cur_status=row["link_current_status"] link_arr_status=row["link_arrival_status"] if not link_id in link_id_dict: link_id_dict[link_id]=[[link_time, [link_cur_status, link_arr_status]]] else: link...
import matplotlib matplotlib.use('agg') import pandas as pd import matplotlib.pyplot as plt import numpy as np import os from sklearn import tree link_id_dict={} def add_to_dict(row):
43
64
106
6
37
XDZhelheim/GISCUP2021
preprocessing/link_status_dt.py
Python
add_to_dict
add_to_dict
12
23
12
12
e0a23ecfeb428f18bc4e1dc6929d5fda82cb8646
bigcode/the-stack
train
5b3031540f91024200a3373a
train
function
def sssp(G, source): """ Compute the distance and predecessors for shortest paths from the specified source to all the vertices in the graph. The distances column will store the distance from the source to each vertex. The predecessors column will store each vertex's predecessor in the shortest path...
def sssp(G, source):
""" Compute the distance and predecessors for shortest paths from the specified source to all the vertices in the graph. The distances column will store the distance from the source to each vertex. The predecessors column will store each vertex's predecessor in the shortest path. Vertices that are ...
a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the sp...
108
108
363
7
100
codereport/cugraph
python/cugraph/traversal/sssp.py
Python
sssp
sssp
18
57
18
18
bdd342c715eedb1e39c57da67bd9807d3e8ab232
bigcode/the-stack
train
3daeea73561981124e97ce38
train
function
def filter_unreachable(df): """ Remove unreachable vertices from the result of SSSP or BFS Parameters ---------- df : cudf.DataFrame cudf.DataFrame that is the output of SSSP or BFS Returns ------- df : filtered cudf.DataFrame with only reachable vertices df['vertex'][i...
def filter_unreachable(df):
""" Remove unreachable vertices from the result of SSSP or BFS Parameters ---------- df : cudf.DataFrame cudf.DataFrame that is the output of SSSP or BFS Returns ------- df : filtered cudf.DataFrame with only reachable vertices df['vertex'][i] gives the vertex id of the...
int32', 'float32'], header=None) >>> G = cugraph.Graph() >>> G.from_cudf_edgelist(M, source='0', destination='1') >>> distances = cugraph.sssp(G, 0) """ df = sssp_wrapper.sssp(G, source) return df def filter_unreachable(df):
77
77
257
6
70
codereport/cugraph
python/cugraph/traversal/sssp.py
Python
filter_unreachable
filter_unreachable
60
87
60
60
b6ddb069c5471010eb7b6610ade0925aaff79d62
bigcode/the-stack
train
7b16852325b06f6347ed33f3
train
function
def postRequest(url, params, headers): print("Calling URL: "+ url) try: with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: # future_to_url = executor.submit(load_url, url, params, headers, 10) # future = concurrent.futures.as_completed(future_to_url) ...
def postRequest(url, params, headers):
print("Calling URL: "+ url) try: with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: # future_to_url = executor.submit(load_url, url, params, headers, 10) # future = concurrent.futures.as_completed(future_to_url) # print(future) ...
)) urls = [url] rs = (grequests.post(u, data=payload, headers={'Content-Type':'application/json'}) for u in urls) requests = grequests.map(rs) for response in requests: print(response) def get_urls(): return ["url1","url2"] def postRequest(url, params, headers):
74
74
249
9
65
JFKenso/pipe-to-python-demo
pipeClientReadImages.py
Python
postRequest
postRequest
153
179
153
153
6e14baea9d84e78a0515d1d46cd6bfc0516ca78f
bigcode/the-stack
train
6460912351baf1a7f12ff558
train
function
def load_url2(url, params, headers, timeout): print("Received request with params: "+ str(params)) urls = [url] rs = (grequests.post(u, data=payload, headers={'Content-Type':'application/json'}) for u in urls) requests = grequests.map(rs) for response in requests: print(response)
def load_url2(url, params, headers, timeout):
print("Received request with params: "+ str(params)) urls = [url] rs = (grequests.post(u, data=payload, headers={'Content-Type':'application/json'}) for u in urls) requests = grequests.map(rs) for response in requests: print(response)
return r def load_url(url, params, headers, timeout): r = requests.post(url, data=payload, headers={'Content-Type':'application/json'}, timeout = timeout) print("Request Response: "+ str(r)) return r def load_url2(url, params, headers, timeout):
64
64
75
12
51
JFKenso/pipe-to-python-demo
pipeClientReadImages.py
Python
load_url2
load_url2
142
148
142
142
f646536edda97e10156423bd107946c49449d1ad
bigcode/the-stack
train
dfa0a06fe14834df2ad2b4ae
train
function
def running_mean(x, N): cumsum = np.cumsum(np.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N]) / float(N)
def running_mean(x, N):
cumsum = np.cumsum(np.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N]) / float(N)
in a rectangle def getRectangle(faceDictionary): rect = faceDictionary.face_rectangle left = rect.left top = rect.top bottom = left + rect.height right = top + rect.width return (left, top, bottom, right) def running_mean(x, N):
64
64
42
7
57
JFKenso/pipe-to-python-demo
pipeClientReadImages.py
Python
running_mean
running_mean
110
112
110
110
c04d1cefbbb615e34069d4ad5dd225fed0885f0d
bigcode/the-stack
train
7d84cde89537048e2afc99eb
train
function
def get_urls(): return ["url1","url2"]
def get_urls():
return ["url1","url2"]
Received request with params: "+ str(params)) urls = [url] rs = (grequests.post(u, data=payload, headers={'Content-Type':'application/json'}) for u in urls) requests = grequests.map(rs) for response in requests: print(response) def get_urls():
64
64
13
4
60
JFKenso/pipe-to-python-demo
pipeClientReadImages.py
Python
get_urls
get_urls
150
151
150
150
e18759cbf25c96d3663963f4ac8e42e82ef21149
bigcode/the-stack
train
5374e1a9838a6507108d93c8
train
function
def load_url3(url, params, headers, timeout): r = session.post(url, data=payload, headers={'Content-Type':'application/json'}) #response_one = r.result() #print('response one status: {0}'.format(response_one.status_code)) #print(response_one.content) return r
def load_url3(url, params, headers, timeout):
r = session.post(url, data=payload, headers={'Content-Type':'application/json'}) #response_one = r.result() #print('response one status: {0}'.format(response_one.status_code)) #print(response_one.content) return r
str(response.request.url)) print (str(response)) if response.status_code != 200: print (str(response.request.url)) print (str(response.content)) def exception_handler(request, exception): print("Exception Found: "+ str(exception)) def load_url3(url, params, headers, timeout):
64
64
67
12
52
JFKenso/pipe-to-python-demo
pipeClientReadImages.py
Python
load_url3
load_url3
130
135
130
130
ecbae86436964887ce788ee231f349706b20759a
bigcode/the-stack
train
57437696704ccd43d6d2377b
train
function
def getRectangle(faceDictionary): rect = faceDictionary.face_rectangle left = rect.left top = rect.top bottom = left + rect.height right = top + rect.width return (left, top, bottom, right)
def getRectangle(faceDictionary):
rect = faceDictionary.face_rectangle left = rect.left top = rect.top bottom = left + rect.height right = top + rect.width return (left, top, bottom, right)
7KPmiQksG06WJzTYXA3KKggYDgQVab6jQ%2FStyCJaBTSJPt1AR3JC%2Bnzw%3D%3D" # Convert width height to a point in a rectangle def getRectangle(faceDictionary):
64
64
53
6
57
JFKenso/pipe-to-python-demo
pipeClientReadImages.py
Python
getRectangle
getRectangle
102
108
102
102
43cccf5e81a8e80a14c31a118a9d3cadd3d1a246
bigcode/the-stack
train
2bad8b1eecc71517c42222bc
train
function
def proc_response(response, **kwargs): # do something .. print ("========Processing response=============" + str(response.request.url)) print (str(response)) if response.status_code != 200: print (str(response.request.url)) print (str(response.content))
def proc_response(response, **kwargs): # do something ..
print ("========Processing response=============" + str(response.request.url)) print (str(response)) if response.status_code != 200: print (str(response.request.url)) print (str(response.content))
umsum[:-N]) / float(N) def moving_average(a, n) : ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n def proc_response(response, **kwargs): # do something ..
64
64
57
13
50
JFKenso/pipe-to-python-demo
pipeClientReadImages.py
Python
proc_response
proc_response
119
125
119
120
c0cbda2e21e6e2cd7e230d9c5d60616d53864ec8
bigcode/the-stack
train
36c59e331975116be7c48ea4
train
function
def load_url(url, params, headers, timeout): r = requests.post(url, data=payload, headers={'Content-Type':'application/json'}, timeout = timeout) print("Request Response: "+ str(r)) return r
def load_url(url, params, headers, timeout):
r = requests.post(url, data=payload, headers={'Content-Type':'application/json'}, timeout = timeout) print("Request Response: "+ str(r)) return r
= session.post(url, data=payload, headers={'Content-Type':'application/json'}) #response_one = r.result() #print('response one status: {0}'.format(response_one.status_code)) #print(response_one.content) return r def load_url(url, params, headers, timeout):
64
64
48
11
52
JFKenso/pipe-to-python-demo
pipeClientReadImages.py
Python
load_url
load_url
137
140
137
137
3d171cd7ad04334247c43d5255bcdccce1521923
bigcode/the-stack
train
c90b2f064364418d8088596a
train
function
def exception_handler(request, exception): print("Exception Found: "+ str(exception))
def exception_handler(request, exception):
print("Exception Found: "+ str(exception))
def proc_response(response, **kwargs): # do something .. print ("========Processing response=============" + str(response.request.url)) print (str(response)) if response.status_code != 200: print (str(response.request.url)) print (str(response.content)) def exception_handler(request, exc...
64
64
17
7
57
JFKenso/pipe-to-python-demo
pipeClientReadImages.py
Python
exception_handler
exception_handler
127
128
127
127
ce26fa33dad9afcf44cd23284ef30126e6667839
bigcode/the-stack
train
413d4cc0d5944461944332fb
train
function
def moving_average(a, n) : ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n
def moving_average(a, n) :
ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n
rect.width return (left, top, bottom, right) def running_mean(x, N): cumsum = np.cumsum(np.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N]) / float(N) def moving_average(a, n) :
64
64
43
8
56
JFKenso/pipe-to-python-demo
pipeClientReadImages.py
Python
moving_average
moving_average
114
117
114
114
7fba3ad335acb24d23d08e6cb6ec62416dd246e1
bigcode/the-stack
train
ce335ca53d9dd18f14a92b00
train
class
class Value_function(object): """ NN-based state-value function """ def __init__(self, obs_dim, epochs=20, cliprange=0.2, network_scale=10, lr=None): """ Args: obs_dim: number of dimensions in observation vector (int) network_scale: NN input layer is of dim <input...
class Value_function(object):
""" NN-based state-value function """ def __init__(self, obs_dim, epochs=20, cliprange=0.2, network_scale=10, lr=None): """ Args: obs_dim: number of dimensions in observation vector (int) network_scale: NN input layer is of dim <input_network_scale> * obs_dim ...
""" State-Value Function Modified from code Written by Patrick Coady (pat-coady.github.io) added option for value function clipping """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from sklearn.utils import shuffle class Value_function(object):
63
244
814
5
57
Aerospace-AI/AAS-18-290-6DOF
RL_lib/Agents/PPO/value_function_pt.py
Python
Value_function
Value_function
16
91
16
16
01d9bbc7279c46a697fa4cae6bc005d5a3bdae81
bigcode/the-stack
train
9b1033541423f79b9f3caf94
train
class
class VF_net(nn.Module): def __init__(self, obs_dim, network_scale): super(VF_net, self).__init__() hid1_size = obs_dim * network_scale # 10 chosen empirically on 'Hopper-v1' hid3_size = 5 hid2_size = int(np.sqrt(hid1_size * hid3_size)) self.lr = 1e-2 / np.sqrt(hid2_size)...
class VF_net(nn.Module):
def __init__(self, obs_dim, network_scale): super(VF_net, self).__init__() hid1_size = obs_dim * network_scale # 10 chosen empirically on 'Hopper-v1' hid3_size = 5 hid2_size = int(np.sqrt(hid1_size * hid3_size)) self.lr = 1e-2 / np.sqrt(hid2_size) self.fc1 = nn.Li...
= pred - targ loss1 = torch.mul(error, error) error = vpred_clipped - targ loss2 = torch.mul(error, error) loss = 0.5 * torch.mean(torch.max(loss1,loss2)) else: error = pred - targ loss = torch.mean(error, error) return loss ...
97
98
329
6
91
Aerospace-AI/AAS-18-290-6DOF
RL_lib/Agents/PPO/value_function_pt.py
Python
VF_net
VF_net
93
126
93
93
4c6608699d494914d63770b461cfec7629a3f6e5
bigcode/the-stack
train
1b0c60ff7614c357ce4c604e
train
function
def index(request): return render(request, 'maps/team.html')
def index(request):
return render(request, 'maps/team.html')
from django.shortcuts import render def index(request):
10
64
14
4
5
acdh-oeaw/diauma
maps/views/team.py
Python
index
index
4
5
4
4
c4031581b6d5eb766b7797b2c13bef7133879d1d
bigcode/the-stack
train
84f89b062ba5544d2b59bdbc
train
function
def gen_grid(fp, path): """Generate numerical grid based on h5 "Grid" specifications. Expect grid specifications: type, npts, start, end. H5 file can be generated using pimc++ dmparser.py. Args: fp (h5py.File): handle to h5file path (str): path to grid specifiers e.g. '/Ukj0/Grid' Return: np.ar...
def gen_grid(fp, path):
"""Generate numerical grid based on h5 "Grid" specifications. Expect grid specifications: type, npts, start, end. H5 file can be generated using pimc++ dmparser.py. Args: fp (h5py.File): handle to h5file path (str): path to grid specifiers e.g. '/Ukj0/Grid' Return: np.array: 1D array of grid po...
(nrow): ax_arr[irow, icol].set_yticks([]) for icol in range(ncol): ax_arr[-1, icol].set_xlabel('x') ax_arr[0, 0].set_ylabel('ukj') ax_arr[1, 0].set_ylabel('dukj/dbeta') ax_arr[-1, -1].legend() fig.subplots_adjust(wspace=0, hspace=0) plt.show() def gen_grid(fp, path):
108
108
362
7
101
Paul-St-Young/carto-upi
caupi/esq/dmh5.py
Python
gen_grid
gen_grid
107
143
107
107
d2b03628af8f72d276d01a26e36e1a7ef2662440
bigcode/the-stack
train
ef26897669da38024d20efec
train
function
def get_data(fh5, name='Ukj0'): fp = h5py.File(fh5, 'r') data = fp['%s/Data' % name][()] fp.close() return data
def get_data(fh5, name='Ukj0'):
fp = h5py.File(fh5, 'r') data = fp['%s/Data' % name][()] fp.close() return data
np def get_grid(fh5): gpath = 'Ukj0/Grid' fp = h5py.File(fh5, 'r') grid = gen_grid(fp, gpath) fp.close() return grid def get_data(fh5, name='Ukj0'):
64
64
48
13
50
Paul-St-Young/carto-upi
caupi/esq/dmh5.py
Python
get_data
get_data
12
16
12
12
cc0c6659545281003ebeadb6b7828b0e2701514d
bigcode/the-stack
train
1d04cb1ffcb338e89bd01e7d
train
function
def show_all_ukj(fh5, orders=range(1, 4), itau=0, xmin=0.05, xmax=None): import matplotlib.pyplot as plt # get raw data grid = get_grid(fh5) nr = len(grid) ukjl = [] dukjl = [] for norder in orders: name = 'Ukj%d' % (norder-1) ukj = get_data(fh5, name) assert len(ukj) == nr ukjl.append(ukj...
def show_all_ukj(fh5, orders=range(1, 4), itau=0, xmin=0.05, xmax=None):
import matplotlib.pyplot as plt # get raw data grid = get_grid(fh5) nr = len(grid) ukjl = [] dukjl = [] for norder in orders: name = 'Ukj%d' % (norder-1) ukj = get_data(fh5, name) assert len(ukj) == nr ukjl.append(ukj) name = 'dUkjdBeta%d' % (norder-1) dukj = get_data(fh5, name) ...
1, nmover, ntau = sampl[0].shape assert nr1 == nr fig, ax_arr = plt.subplots(nsamp, nmover, sharex=True) ax_arr[0, 0].set_ylabel(r'$d\tilde{U}/dR_m$') ax_arr[1, 0].set_ylabel(r'$d^2\tilde{U}/dR_m^2$') for imover in range(nmover): for isamp in range(nsamp): ax = ax_arr[isamp, imover] ax.plot(g...
208
208
694
33
175
Paul-St-Young/carto-upi
caupi/esq/dmh5.py
Python
show_all_ukj
show_all_ukj
42
105
42
42
fd360ed85afa2260cfda15370e0e53193bb2bb03
bigcode/the-stack
train
3a27ef7267bbf1cfdb8daaf5
train
function
def get_grid(fh5): gpath = 'Ukj0/Grid' fp = h5py.File(fh5, 'r') grid = gen_grid(fp, gpath) fp.close() return grid
def get_grid(fh5):
gpath = 'Ukj0/Grid' fp = h5py.File(fh5, 'r') grid = gen_grid(fp, gpath) fp.close() return grid
import os import h5py import numpy as np def get_grid(fh5):
20
64
49
7
12
Paul-St-Young/carto-upi
caupi/esq/dmh5.py
Python
get_grid
get_grid
5
10
5
5
367ab575688b3c96cd92ea8eaf40c316112340c0
bigcode/the-stack
train
9254730599826bc949f4e547
train
function
def show_sampling(fh5, nsamp=2): import matplotlib.pyplot as plt grid = get_grid(fh5) nr = len(grid) sampl = [] for isamp in range(nsamp): name = 'Sampling_%d' % isamp samp = get_data(fh5, name) sampl.append(samp) nr1, nmover, ntau = sampl[0].shape assert nr1 == nr fig, ax_arr = plt.subplot...
def show_sampling(fh5, nsamp=2):
import matplotlib.pyplot as plt grid = get_grid(fh5) nr = len(grid) sampl = [] for isamp in range(nsamp): name = 'Sampling_%d' % isamp samp = get_data(fh5, name) sampl.append(samp) nr1, nmover, ntau = sampl[0].shape assert nr1 == nr fig, ax_arr = plt.subplots(nsamp, nmover, sharex=True) a...
= gen_grid(fp, gpath) fp.close() return grid def get_data(fh5, name='Ukj0'): fp = h5py.File(fh5, 'r') data = fp['%s/Data' % name][()] fp.close() return data def show_sampling(fh5, nsamp=2):
76
76
255
12
63
Paul-St-Young/carto-upi
caupi/esq/dmh5.py
Python
show_sampling
show_sampling
18
40
18
18
5f09325583c8d19cbed67e71e4558871cb41accc
bigcode/the-stack
train
8bcecab5f153c389162e7adf
train
class
class TestInsertQuestionFeature: class TestDatabaseInsertions: @pytest.fixture def question(self): return Question(profile=Profile.objects.first(), title="Question in Math", content='How much is it 1+1?', ...
class TestInsertQuestionFeature:
class TestDatabaseInsertions: @pytest.fixture def question(self): return Question(profile=Profile.objects.first(), title="Question in Math", content='How much is it 1+1?', subject=Subject.objects.first(),...
import pytest import pytz from home.models import Profile, Subject, Question, Grade from pytest_django.asserts import assertTemplateUsed from home.forms import QuestionForm from datetime import datetime from django.core.exceptions import ValidationError class TestInsertQuestionFeature:
56
256
2,961
6
49
rebeccaTubman/shlifim
home/tests/test_insert_question_feature.py
Python
TestInsertQuestionFeature
TestInsertQuestionFeature
10
226
10
10
5c9800c67475c7800bdafe29b1e23bea5abdbe5b
bigcode/the-stack
train
b2aa7358d2e523c011d09fa4
train
function
def index(request): return HttpResponse("Hello, world.")
def index(request):
return HttpResponse("Hello, world.")
from django.shortcuts import render from django.http import HttpResponse def index(request):
17
64
13
4
12
itachikryst/GroupProject
GroupProject/client/views.py
Python
index
index
5
6
5
5
915c9cb00e5f2920951338341fbf1f92faf3e13f
bigcode/the-stack
train
065a8037cd6e00b2592731b6
train
function
def extractGashaconepubsWordpressCom(item): ''' Parser for 'gashaconepubs.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None if 'Epubs' in item['tags']: return None tagmap = [ ('PRC', ...
def extractGashaconepubsWordpressCom(item):
''' Parser for 'gashaconepubs.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None if 'Epubs' in item['tags']: return None tagmap = [ ('PRC', 'PRC', 'translated'), ...
def extractGashaconepubsWordpressCom(item):
13
64
180
13
0
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractGashaconepubsWordpressCom.py
Python
extractGashaconepubsWordpressCom
extractGashaconepubsWordpressCom
1
22
1
1
f15990770cfcf3c346c780b2f41632c850671f4a
bigcode/the-stack
train
9464f0970914d673ae9d725a
train
function
def create_motor_class(cls): return create_class_with_framework(cls, tornado_framework, 'motor.motor_tornado')
def create_motor_class(cls):
return create_class_with_framework(cls, tornado_framework, 'motor.motor_tornado')
, an asynchronous driver for MongoDB.""" from __future__ import unicode_literals, absolute_import from . import core, motor_gridfs from .frameworks import tornado as tornado_framework from .metaprogramming import create_class_with_framework __all__ = ['MotorClient'] def create_motor_class(cls):
64
64
24
6
58
TryAgain98/testPython
lib/python3.7/site-packages/motor/motor_tornado.py
Python
create_motor_class
create_motor_class
26
28
26
26
68cefb3631d06148d02a93eb05e2ef2ec775f840
bigcode/the-stack
train
934cf931ac1fc3fddddf59ed
train
class
class ITemplateHelpers(Interface): '''Add custom template helper functions. By implementing this plugin interface plugins can provide their own template helper functions, which custom templates can then access via the ``h`` variable. See ``ckanext/example_itemplatehelpers`` for an example plugin. ...
class ITemplateHelpers(Interface):
'''Add custom template helper functions. By implementing this plugin interface plugins can provide their own template helper functions, which custom templates can then access via the ``h`` variable. See ``ckanext/example_itemplatehelpers`` for an example plugin. ''' def get_helpers(self):...
) through the action API. """ class IAuthFunctions(Interface): """ Allow customisation of default Authorization implementation """ def get_auth_functions(self): """ Returns a dict of all the authorization functions which the implementation overrides """ class IT...
63
64
179
7
56
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
ITemplateHelpers
ITemplateHelpers
531
553
531
531
47eaee5a268d08a04550db470136bd6f0bd34c08
bigcode/the-stack
train
d87ced99cd0ab87e330d21cc
train
class
class IPluginObserver(Interface): """ Plugin to the plugin loading mechanism """ def before_load(self, plugin): """ Called before a plugin is loaded This method is passed the plugin class. """ def after_load(self, service): """ Called after a plugin ...
class IPluginObserver(Interface):
""" Plugin to the plugin loading mechanism """ def before_load(self, plugin): """ Called before a plugin is loaded This method is passed the plugin class. """ def after_load(self, service): """ Called after a plugin has been loaded. This meth...
(Interface): """ Hook into the resource controller. (see IGroupController) """ def before_show(self, resource_dict): ''' Extensions will receive the validated data dict before the resource is ready for display. ''' return resource_dict class IPluginOb...
64
64
141
7
56
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IPluginObserver
IPluginObserver
450
477
450
450
191332862c5e06ca55058806772ca775bb7a3d47
bigcode/the-stack
train
6210c0f2e2367886929c3db1
train
class
class IResourcePreview(Interface): """ Hook into the resource previews in helpers.py. This lets you create custom previews for example for xml files. """ def can_preview(self, data_dict): ''' Returns info on whether the plugin can preview the resource. This can be done in t...
class IResourcePreview(Interface):
""" Hook into the resource previews in helpers.py. This lets you create custom previews for example for xml files. """ def can_preview(self, data_dict): ''' Returns info on whether the plugin can preview the resource. This can be done in two ways. The old way is to ...
Execute after a commit has occured. """ def after_rollback(self, session): """ Execute after a rollback has occured. """ class IDomainObjectModification(Interface): """ Receives notification of new, changed and deleted datesets. """ def notify(self, entity, opera...
105
105
352
7
97
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IResourcePreview
IResourcePreview
198
241
198
198
f55edfa2d6c683da2abe7c9c396e0980e5ac1769
bigcode/the-stack
train
4694465ab5b38af0ece94955
train
class
class ISession(Interface): """ A subset of the SQLAlchemy session extension hooks. """ def after_begin(self, session, transaction, connection): """ Execute after a transaction is begun on a connection """ def before_flush(self, session, flush_context, instances): ""...
class ISession(Interface):
""" A subset of the SQLAlchemy session extension hooks. """ def after_begin(self, session, transaction, connection): """ Execute after a transaction is begun on a connection """ def before_flush(self, session, flush_context, instances): """ Execute before fl...
""" def after_update(self, mapper, connection, instance): """ Receive an object instance after that instance is UPDATEed. """ def after_delete(self, mapper, connection, instance): """ Receive an object instance after that instance is DELETEed. """ class ISessio...
63
64
163
6
57
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
ISession
ISession
144
177
144
144
922cc939d8d9a710aa4748d06bfa7b2d566a69ef
bigcode/the-stack
train
3c342140d1873fc0a4087e52
train
class
class IPackageController(Interface): """ Hook into the package controller. (see IGroupController) """ def read(self, entity): pass def create(self, entity): pass def edit(self, entity): pass def authz_add_role(self, object_role): pass def authz_re...
class IPackageController(Interface):
""" Hook into the package controller. (see IGroupController) """ def read(self, entity): pass def create(self, entity): pass def edit(self, entity): pass def authz_add_role(self, object_role): pass def authz_remove_role(self, object_role): ...
dictionary passed will be the one that gets sent to the template. ''' return pkg_dict class IOrganizationController(Interface): """ Hook into the Organization controller. These will usually be called just before committing or returning the respective object, i.e. all vali...
195
195
653
7
187
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IPackageController
IPackageController
330
433
330
330
b31009a3bf119596630700d40a368365297f03ae
bigcode/the-stack
train
12113651edfa69d886bdb153
train
class
class IAuthFunctions(Interface): """ Allow customisation of default Authorization implementation """ def get_auth_functions(self): """ Returns a dict of all the authorization functions which the implementation overrides """
class IAuthFunctions(Interface):
""" Allow customisation of default Authorization implementation """ def get_auth_functions(self): """ Returns a dict of all the authorization functions which the implementation overrides """
function and the values being the functions themselves. By decorating a function with the `ckan.logic.side_effect_free` decorator, the associated action will be made available by a GET request (as well as the usual POST request) through the action API. """ class IAuthFunctions(Interfac...
63
64
47
7
56
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IAuthFunctions
IAuthFunctions
520
528
520
520
670956a7aa0d870c77d5a509a4fcae0da893789b
bigcode/the-stack
train
bb3db96c1b4ef85ffe15b451
train
class
class IGroupController(Interface): """ Hook into the Group controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. """ def read(self, entity): pass def create(...
class IGroupController(Interface):
""" Hook into the Group controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. """ def read(self, entity): pass def create(self, entity): pass de...
validation, synchronization and authorization setup are complete. ''' def before_view(self, tag_dict): ''' Extensions will recieve this before the tag gets displayed. The dictionary passed will be the one that gets sent to the template. ''' return tag_dict class IG...
64
64
166
7
56
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IGroupController
IGroupController
260
292
260
260
08600298d4c8ddbdf21fc966be6ff28e52cd355a
bigcode/the-stack
train
4cbb7c3aed19d193966d5404
train
class
class IGenshiStreamFilter(Interface): ''' Hook into template rendering. See ckan.lib.base.py:render ''' def filter(self, stream): """ Return a filtered Genshi stream. Called when any page is rendered. :param stream: Genshi stream of the current output document ...
class IGenshiStreamFilter(Interface):
''' Hook into template rendering. See ckan.lib.base.py:render ''' def filter(self, stream): """ Return a filtered Genshi stream. Called when any page is rendered. :param stream: Genshi stream of the current output document :returns: filtered Genshi stream ...
implements except AttributeError: return False class IMiddleware(Interface): '''Hook into Pylons middleware stack ''' def make_middleware(self, app, config): '''Return an app configured with this middleware ''' return app class IGenshiStreamFilter(Interface):
64
64
82
8
55
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IGenshiStreamFilter
IGenshiStreamFilter
54
68
54
54
944b5848237c0601b9e660d7f9f36609353155e4
bigcode/the-stack
train
377860e92f9051deeee7eb51
train
class
class IAuthenticator(Interface): '''EXPERIMENTAL Allows custom authentication methods to be integrated into CKAN. Currently it is experimental and the interface may change.''' def identify(self): '''called to identify the user. If the user is identfied then it should set c.us...
class IAuthenticator(Interface):
'''EXPERIMENTAL Allows custom authentication methods to be integrated into CKAN. Currently it is experimental and the interface may change.''' def identify(self): '''called to identify the user. If the user is identfied then it should set c.user: The id of the user c....
, facets_dict, group_type, package_type): ''' Update the facets_dict and return it. ''' return facets_dict def organization_facets(self, facets_dict, organization_type, package_type): ''' Update the facets_dict and return it. ''' return facets_dict class IAuthenticator(Interface):
64
64
183
6
57
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IAuthenticator
IAuthenticator
899
925
899
899
bf0e620e862e9c4b35265201ceb06a3f41b20c58
bigcode/the-stack
train
c9c84201b7cef51b553a4918
train
class
class IResourceUrlChange(Interface): """ Receives notification of changed urls. """ def notify(self, resource): pass
class IResourceUrlChange(Interface):
""" Receives notification of changed urls. """ def notify(self, resource): pass
_rollback(self, session): """ Execute after a rollback has occured. """ class IDomainObjectModification(Interface): """ Receives notification of new, changed and deleted datesets. """ def notify(self, entity, operation): pass class IResourceUrlChange(Interface):
64
64
30
8
55
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IResourceUrlChange
IResourceUrlChange
189
195
189
189
5104051b896d37b58da6bf61712c886f50536fe3
bigcode/the-stack
train
4255eceb7fff0fbd37bb6d01
train
class
class IMapper(Interface): """ A subset of the SQLAlchemy mapper extension hooks. See http://www.sqlalchemy.org/docs/05/reference/orm/interfaces.html#sqlalchemy.orm.interfaces.MapperExtension Example:: >>> class MyPlugin(SingletonPlugin): ... ... implements(IMapper) ...
class IMapper(Interface):
""" A subset of the SQLAlchemy mapper extension hooks. See http://www.sqlalchemy.org/docs/05/reference/orm/interfaces.html#sqlalchemy.orm.interfaces.MapperExtension Example:: >>> class MyPlugin(SingletonPlugin): ... ... implements(IMapper) ... ... def af...
: Modified version of the map object """ return map def after_map(self, map): """ Called after routes map is set up. ``after_map`` can be used to add fall-back handlers. :param map: Routes map object :returns: Modified version of the map object """ ...
80
80
268
6
73
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IMapper
IMapper
97
141
97
97
edf40e9e928fae9ddc0fbbdac4a10de1db1d4fa8
bigcode/the-stack
train
b7ecb2f8d5b885a17d5c5873
train
class
class IDomainObjectModification(Interface): """ Receives notification of new, changed and deleted datesets. """ def notify(self, entity, operation): pass
class IDomainObjectModification(Interface):
""" Receives notification of new, changed and deleted datesets. """ def notify(self, entity, operation): pass
session): """ Execute right before commit is called. """ def after_commit(self, session): """ Execute after a commit has occured. """ def after_rollback(self, session): """ Execute after a rollback has occured. """ class IDomainObjectMod...
63
64
37
8
55
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IDomainObjectModification
IDomainObjectModification
180
186
180
180
44feb766d3c46df9d3c87f88ed22b9c1a1189483
bigcode/the-stack
train
ccc8a7e9ff2dc761698716a2
train
class
class IGroupForm(Interface): """ Allows customisation of the group controller as a plugin. The behaviour of the plugin is determined by 5 method hooks: - package_form(self) - form_to_db_schema(self) - db_to_form_schema(self) - check_data_dict(self, data_dict) - setup_template_vari...
class IGroupForm(Interface):
""" Allows customisation of the group controller as a plugin. The behaviour of the plugin is determined by 5 method hooks: - package_form(self) - form_to_db_schema(self) - db_to_form_schema(self) - check_data_dict(self, data_dict) - setup_template_variables(self, context, data_dic...
'''Return the path to the template for the dataset edit page. The path should be relative to the plugin's templates dir, e.g. ``'package/edit.html'``. :rtype: string ''' def search_template(self): '''Return the path to the template for use in the dataset search page. ...
233
234
782
7
226
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IGroupForm
IGroupForm
754
871
754
754
519be66b05a90c71ed90b25342a22db00ac7697b
bigcode/the-stack
train
8b587e6d8dbec3ad4e3ddc20
train
class
class Interface(_pca_Interface): @classmethod def provided_by(cls, instance): return cls.implemented_by(instance.__class__) @classmethod def implemented_by(cls, other): if not isclass(other): raise TypeError("Class expected", other) try: return cls in ot...
class Interface(_pca_Interface): @classmethod
def provided_by(cls, instance): return cls.implemented_by(instance.__class__) @classmethod def implemented_by(cls, other): if not isclass(other): raise TypeError("Class expected", other) try: return cls in other._implements except AttributeError: ...
ResourceController', 'IGroupForm', 'ITagController', 'ITemplateHelpers', 'IFacets', 'IAuthenticator', ] from inspect import isclass from pyutilib.component.core import Interface as _pca_Interface class Interface(_pca_Interface): @classmethod
64
64
78
11
52
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
Interface
Interface
29
42
29
31
f4ea4fc6d28adf2c5d65e89d4954167b430427fa
bigcode/the-stack
train
40b598edd964d0ef1d03d80b
train
class
class IActions(Interface): """ Allow adding of actions to the logic layer. """ def get_actions(self): """ Should return a dict, the keys being the name of the logic function and the values being the functions themselves. By decorating a function with the `ckan.logic.side...
class IActions(Interface):
""" Allow adding of actions to the logic layer. """ def get_actions(self): """ Should return a dict, the keys being the name of the logic function and the values being the functions themselves. By decorating a function with the `ckan.logic.side_effect_free` decor...
ons.config`` object """ def update_config(self, config): """ Called by load_environment at earliest point when config is available to plugins. The config should be updated in place. :param config: ``pylons.config`` object """ class IActions(Interface):
63
64
100
6
57
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IActions
IActions
505
517
505
505
4cf2f071a8213c53512486f097b54ad5f997365e
bigcode/the-stack
train
d29585c85f2c4608aa8d710b
train
class
class IFacets(Interface): ''' Allows specify which facets are displayed and also the names used. facet_dicts are in the form {'facet_name': 'display name', ...} to allow translatable display names use _(...) eg {'facet_name': _('display name'), ...} and ensure that this is created each time the fun...
class IFacets(Interface):
''' Allows specify which facets are displayed and also the names used. facet_dicts are in the form {'facet_name': 'display name', ...} to allow translatable display names use _(...) eg {'facet_name': _('display name'), ...} and ensure that this is created each time the function is called. The ...
""" Check if the return data is correct. raise a DataError if not. """ def setup_template_variables(self, context, data_dict): """ Add variables to c just prior to the template being rendered. """ ##### End of hooks ...
64
64
181
7
56
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IFacets
IFacets
875
896
875
875
54bbd78ff10986dbea8999056beeb24f2ea52d8f
bigcode/the-stack
train
89ee59f42f613383453c2c43
train
class
class IDatasetForm(Interface): '''Customize CKAN's dataset (package) schemas and forms. By implementing this interface plugins can customise CKAN's dataset schema, for example to add new custom fields to datasets. Multiple IDatasetForm plugins can be used at once, each plugin associating itself wi...
class IDatasetForm(Interface):
'''Customize CKAN's dataset (package) schemas and forms. By implementing this interface plugins can customise CKAN's dataset schema, for example to add new custom fields to datasets. Multiple IDatasetForm plugins can be used at once, each plugin associating itself with different package types usin...
GET request (as well as the usual POST request) through the action API. """ class IAuthFunctions(Interface): """ Allow customisation of default Authorization implementation """ def get_auth_functions(self): """ Returns a dict of all the authorization functions which th...
255
256
1,494
7
248
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IDatasetForm
IDatasetForm
556
751
556
556
8bd4daea879a4e8083978c2390289b10b59a02c3
bigcode/the-stack
train
c278380e0a6d67373bc16b63
train
class
class IMiddleware(Interface): '''Hook into Pylons middleware stack ''' def make_middleware(self, app, config): '''Return an app configured with this middleware ''' return app
class IMiddleware(Interface):
'''Hook into Pylons middleware stack ''' def make_middleware(self, app, config): '''Return an app configured with this middleware ''' return app
return cls.implemented_by(instance.__class__) @classmethod def implemented_by(cls, other): if not isclass(other): raise TypeError("Class expected", other) try: return cls in other._implements except AttributeError: return False class IMiddleware(Inte...
64
64
45
6
57
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IMiddleware
IMiddleware
45
51
45
45
2685a00afce0c745c7cff719382bf344f6cecf09
bigcode/the-stack
train
84881f1885eff65620d3623b
train
class
class IOrganizationController(Interface): """ Hook into the Organization controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. """ def read(self, entity): pass ...
class IOrganizationController(Interface):
""" Hook into the Organization controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. """ def read(self, entity): pass def create(self, entity): pass ...
def delete(self, entity): pass def before_view(self, pkg_dict): ''' Extensions will recieve this before the group gets displayed. The dictionary passed will be the one that gets sent to the template. ''' return pkg_dict class IOrganizationC...
64
64
166
7
56
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IOrganizationController
IOrganizationController
295
327
295
295
0e29759d8504ca6b2c5878d4831980454c9fb3c1
bigcode/the-stack
train
07e9a2330ea30073b86faa27
train
class
class IConfigurer(Interface): """ Configure CKAN (pylons) environment via the ``pylons.config`` object """ def update_config(self, config): """ Called by load_environment at earliest point when config is available to plugins. The config should be updated in place. :para...
class IConfigurer(Interface):
""" Configure CKAN (pylons) environment via the ``pylons.config`` object """ def update_config(self, config): """ Called by load_environment at earliest point when config is available to plugins. The config should be updated in place. :param config: ``pylons.config`` ob...
Called after a plugin has been unloaded. This method is passed the instantiated service object. """ class IConfigurable(Interface): """ Pass configuration to plugins and extensions """ def configure(self, config): """ Called by load_environment """ class IConf...
63
64
80
6
57
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IConfigurer
IConfigurer
491
502
491
491
fa245803b1c45845348bafff77207a24780279da
bigcode/the-stack
train
a66255af65a7da1766db6a47
train
class
class IResourceController(Interface): """ Hook into the resource controller. (see IGroupController) """ def before_show(self, resource_dict): ''' Extensions will receive the validated data dict before the resource is ready for display. ''' return reso...
class IResourceController(Interface):
""" Hook into the resource controller. (see IGroupController) """ def before_show(self, resource_dict): ''' Extensions will receive the validated data dict before the resource is ready for display. ''' return resource_dict
altered version. ''' return pkg_dict def before_view(self, pkg_dict): ''' Extensions will recieve this before the dataset gets displayed. The dictionary passed will be the one that gets sent to the template. ''' return pkg_dict class I...
64
64
61
7
56
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IResourceController
IResourceController
436
447
436
436
a4cb6e006f20300acbbc2c6d8597a1d7e6d5d259
bigcode/the-stack
train
1190c9d2932a585c080f638e
train
class
class IRoutes(Interface): """ Plugin into the setup of the routes map creation. """ def before_map(self, map): """ Called before the routes map is generated. ``before_map`` is before any other mappings are created so can override all other mappings. :param map: Routes m...
class IRoutes(Interface):
""" Plugin into the setup of the routes map creation. """ def before_map(self, map): """ Called before the routes map is generated. ``before_map`` is before any other mappings are created so can override all other mappings. :param map: Routes map object :returns...
render ''' def filter(self, stream): """ Return a filtered Genshi stream. Called when any page is rendered. :param stream: Genshi stream of the current output document :returns: filtered Genshi stream """ return stream class IRoutes(Interface):
64
64
146
6
57
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IRoutes
IRoutes
71
94
71
71
93a713905eae68efdacad6029e617651e46bf1f9
bigcode/the-stack
train
7609613d441d3d07d60859f3
train
class
class IConfigurable(Interface): """ Pass configuration to plugins and extensions """ def configure(self, config): """ Called by load_environment """
class IConfigurable(Interface):
""" Pass configuration to plugins and extensions """ def configure(self, config): """ Called by load_environment """
, plugin): """ Called before a plugin is loaded This method is passed the plugin class. """ def after_unload(self, service): """ Called after a plugin has been unloaded. This method is passed the instantiated service object. """ class IConfigurable(In...
63
64
36
7
56
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
IConfigurable
IConfigurable
480
488
480
480
2587b75ed97ae0294c00ddb8724aa8a5b967550d
bigcode/the-stack
train
1d88446faf9d6f56abd34650
train
class
class ITagController(Interface): ''' Hook into the Tag controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. ''' def before_view(self, tag_dict): ''' Extensio...
class ITagController(Interface):
''' Hook into the Tag controller. These will usually be called just before committing or returning the respective object, i.e. all validation, synchronization and authorization setup are complete. ''' def before_view(self, tag_dict): ''' Extensions will recieve this before the t...
proxied domain if necessary. ''' def preview_template(self, context, data_dict): ''' Returns a string representing the location of the template to be rendered for the read page. The ``data_dict`` contains the resource and the package. ''' class ITagController(Interf...
63
64
93
7
56
CodeandoMexico/ckan
ckan/plugins/interfaces.py
Python
ITagController
ITagController
244
257
244
244
be088319cbe889aa36944cda652baf1de47209fe
bigcode/the-stack
train
1b886da15eb0efe9603bb3da
train
class
class EncodeProcessDecode(snt.AbstractModule): """Encode-Process-Decode function approximator for learnable simulator.""" def __init__( self, latent_size: int, mlp_hidden_size: int, mlp_num_hidden_layers: int, num_message_passing_steps: int, output_size: int, reducer: Redu...
class EncodeProcessDecode(snt.AbstractModule):
"""Encode-Process-Decode function approximator for learnable simulator.""" def __init__( self, latent_size: int, mlp_hidden_size: int, mlp_num_hidden_layers: int, num_message_passing_steps: int, output_size: int, reducer: Reducer = tf.math.unsorted_segment_sum, name:...
Networks" Alvaro Sanchez-Gonzalez*, Jonathan Godwin*, Tobias Pfaff*, Rex Ying, Jure Leskovec, Peter W. Battaglia https://arxiv.org/abs/2002.09405 The Sonnet `EncodeProcessDecode` module provided here implements the learnable parts of the model. It assumes an encoder preprocessor has already built a graph w...
256
256
1,183
9
246
feifzhou/deepmind-research
learning_to_simulate/graph_network.py
Python
EncodeProcessDecode
EncodeProcessDecode
51
183
51
51
baf5f0715384c735ca984287a1aac25dc0511b27
bigcode/the-stack
train
092b221c3add00c789ffeb72
train
function
def build_mlp( hidden_size: int, num_hidden_layers: int, output_size: int) -> snt.Module: """Builds an MLP.""" return snt.nets.MLP( output_sizes=[hidden_size] * num_hidden_layers + [output_size]) # pytype: disable=bad-return-type # gen-stub-imports
def build_mlp( hidden_size: int, num_hidden_layers: int, output_size: int) -> snt.Module:
"""Builds an MLP.""" return snt.nets.MLP( output_sizes=[hidden_size] * num_hidden_layers + [output_size]) # pytype: disable=bad-return-type # gen-stub-imports
Callable import graph_nets as gn import sonnet as snt import tensorflow as tf Reducer = Callable[[tf.Tensor, tf.Tensor, tf.Tensor], tf.Tensor] def build_mlp( hidden_size: int, num_hidden_layers: int, output_size: int) -> snt.Module:
64
64
78
27
37
feifzhou/deepmind-research
learning_to_simulate/graph_network.py
Python
build_mlp
build_mlp
44
48
44
45
0f5195b996472d857d64f0ea238d34718867a501
bigcode/the-stack
train
3593a656d7b7e91e4f1bfa53
train
function
def main(params): simplefilter(action='ignore', category=UserWarning) simplefilter(action='ignore', category=SparseEfficiencyWarning) graph_classifier = initialize_model(params, None, load_model=True) logging.info(f"Device: {params.device}") all_auc = [] auc_mean = 0 all_auc_pr = [] ...
def main(params):
simplefilter(action='ignore', category=UserWarning) simplefilter(action='ignore', category=SparseEfficiencyWarning) graph_classifier = initialize_model(params, None, load_model=True) logging.info(f"Device: {params.device}") all_auc = [] auc_mean = 0 all_auc_pr = [] auc_pr_mean = 0 ...
# from comet_ml import Experiment import pdb import os import argparse import logging import torch from scipy.sparse import SparseEfficiencyWarning import numpy as np from subgraph_extraction.datasets import SubgraphDataset, generate_subgraph_datasets from utils.initialization_utils import initialize_experiment, initi...
101
134
449
4
96
hebatallah/LCILP
test_auc.py
Python
main
main
18
59
18
18
942491e29bdff5ca0030bc232c869985c3a6d8c6
bigcode/the-stack
train
edd7b5676306da310361e896
train
function
def load_doc(filename): # open file as a read only file = open(filename, 'r') # read entire text text = file.read() # close file file.close() return text
def load_doc(filename): # open file as a read only
file = open(filename, 'r') # read entire text text = file.read() # close file file.close() return text
Tokenizer from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Embedding # load text document in # to memory; return text def load_doc(filename): # open file as a read only
64
64
48
14
49
Keenandrea/lit-bot
train.py
Python
load_doc
load_doc
13
20
13
14
026e7ec9ef49b73a8f142638d94b41968bedfd62
bigcode/the-stack
train
9a9ddcbb0e1cbc08acd469da
train
function
def testCantDeserializeStringThatDoesntEndWithBracket(data): with pytest.raises(SlimSyntaxError): deserialize('[000000:')
def testCantDeserializeStringThatDoesntEndWithBracket(data):
with pytest.raises(SlimSyntaxError): deserialize('[000000:')
deserialize(None) def testCantDeserializeEmptyString(data): with pytest.raises(SlimSyntaxError): deserialize('') def testCantDeserializeStringThatDoesntStartWithBracket(data): with pytest.raises(SlimSyntaxError): deserialize('hello') def testCantDeserializeStringThatDoesntEndWithBracket(dat...
64
64
28
13
51
BernardNotarianni/slimer
test/test_list_deserializer.py
Python
testCantDeserializeStringThatDoesntEndWithBracket
testCantDeserializeStringThatDoesntEndWithBracket
33
35
33
33
31d1fc0457f65765629bd51c2b0d0fecebd3dc69
bigcode/the-stack
train