body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
5a0c9424502c0ac26841402cff98f1f89ee92d5ad4529a4750348db153da4a3e
def test_horizons_stepsize_must_be_at_least_five_minutes(): 'Test that the time between ephemeris epochs must be at least five minutes.' with pytest.raises(ValueError) as excinfo: HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc), stepsize=(4.999 * u.minute)) assert ('time between' in str(excinfo.value))
Test that the time between ephemeris epochs must be at least five minutes.
tests/service/test_horizons.py
test_horizons_stepsize_must_be_at_least_five_minutes
saltastroops/imephu
0
python
def test_horizons_stepsize_must_be_at_least_five_minutes(): with pytest.raises(ValueError) as excinfo: HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc), stepsize=(4.999 * u.minute)) assert ('time between' in str(excinfo.value))
def test_horizons_stepsize_must_be_at_least_five_minutes(): with pytest.raises(ValueError) as excinfo: HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc), stepsize=(4.999 * u.minute)) assert ('time between' in str(excinfo.value))<|docstring|>Test that the time between ephemeris epochs must be at least five minutes.<|endoftext|>
cefab4e3ee5381685d05fdbc102c1b39e5eb3b264f7f9828bf0467fdb8b924df
def test_horizons_ephemerides_start_time_must_be_timezone_aware(): 'Test that the ephemerides method requires a timezone-aware start time.' horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(start=datetime(2022, 2, 8, 0, 0, 0, 0)) assert ('start' in str(excinfo.value))
Test that the ephemerides method requires a timezone-aware start time.
tests/service/test_horizons.py
test_horizons_ephemerides_start_time_must_be_timezone_aware
saltastroops/imephu
0
python
def test_horizons_ephemerides_start_time_must_be_timezone_aware(): horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(start=datetime(2022, 2, 8, 0, 0, 0, 0)) assert ('start' in str(excinfo.value))
def test_horizons_ephemerides_start_time_must_be_timezone_aware(): horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(start=datetime(2022, 2, 8, 0, 0, 0, 0)) assert ('start' in str(excinfo.value))<|docstring|>Test that the ephemerides method requires a timezone-aware start time.<|endoftext|>
c007532032eb94a3a6c676796579aeb28e4ba1f4b993ee4ffcf2e56b63a3a739
def test_horizons_ephemerides_end_time_must_be_timezone_aware(): 'Test that the ephemerides method requires a timezone-aware end time.' horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(end=datetime(2022, 2, 8, 1, 0, 0, 0)) assert ('end' in str(excinfo.value))
Test that the ephemerides method requires a timezone-aware end time.
tests/service/test_horizons.py
test_horizons_ephemerides_end_time_must_be_timezone_aware
saltastroops/imephu
0
python
def test_horizons_ephemerides_end_time_must_be_timezone_aware(): horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(end=datetime(2022, 2, 8, 1, 0, 0, 0)) assert ('end' in str(excinfo.value))
def test_horizons_ephemerides_end_time_must_be_timezone_aware(): horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(end=datetime(2022, 2, 8, 1, 0, 0, 0)) assert ('end' in str(excinfo.value))<|docstring|>Test that the ephemerides method requires a timezone-aware end time.<|endoftext|>
7f2bdc4e5ce32b2e3c0b2da0f5c5647d2e04c6916621f9cda2ed736ed3516256
@pytest.mark.parametrize('start', [datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc), datetime(2022, 2, 8, 1, 0, 1, 0, tzinfo=timezone.utc)]) def test_horizons_ephemerides_start_and_end_time_must_be_consistent(start): 'Test that the ephemerides start time must be earlier than the end time.' horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(start=start, end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) assert ('earlier' in str(excinfo.value))
Test that the ephemerides start time must be earlier than the end time.
tests/service/test_horizons.py
test_horizons_ephemerides_start_and_end_time_must_be_consistent
saltastroops/imephu
0
python
@pytest.mark.parametrize('start', [datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc), datetime(2022, 2, 8, 1, 0, 1, 0, tzinfo=timezone.utc)]) def test_horizons_ephemerides_start_and_end_time_must_be_consistent(start): horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(start=start, end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) assert ('earlier' in str(excinfo.value))
@pytest.mark.parametrize('start', [datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc), datetime(2022, 2, 8, 1, 0, 1, 0, tzinfo=timezone.utc)]) def test_horizons_ephemerides_start_and_end_time_must_be_consistent(start): horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(start=start, end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) assert ('earlier' in str(excinfo.value))<|docstring|>Test that the ephemerides start time must be earlier than the end time.<|endoftext|>
bb1538595f28d61f4283370b354edca969b2c4c7e30b4fc1903148df04bd2464
def test_horizons_ephemerides_interval_must_be_subinterval(): 'Test that the constructor and ephemerides interval are consistent.' horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(start=datetime(2022, 2, 7, 23, 59, 59, 0, tzinfo=timezone.utc)) assert ('start' in str(excinfo.value)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(end=datetime(2022, 2, 8, 1, 0, 1, 0, tzinfo=timezone.utc)) assert ('end' in str(excinfo.value))
Test that the constructor and ephemerides interval are consistent.
tests/service/test_horizons.py
test_horizons_ephemerides_interval_must_be_subinterval
saltastroops/imephu
0
python
def test_horizons_ephemerides_interval_must_be_subinterval(): horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(start=datetime(2022, 2, 7, 23, 59, 59, 0, tzinfo=timezone.utc)) assert ('start' in str(excinfo.value)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(end=datetime(2022, 2, 8, 1, 0, 1, 0, tzinfo=timezone.utc)) assert ('end' in str(excinfo.value))
def test_horizons_ephemerides_interval_must_be_subinterval(): horizons = HorizonsService(object_id='Ceres', location='B31', start=datetime(2022, 2, 8, 0, 0, 0, 0, tzinfo=timezone.utc), end=datetime(2022, 2, 8, 1, 0, 0, 0, tzinfo=timezone.utc)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(start=datetime(2022, 2, 7, 23, 59, 59, 0, tzinfo=timezone.utc)) assert ('start' in str(excinfo.value)) with pytest.raises(ValueError) as excinfo: horizons.ephemerides(end=datetime(2022, 2, 8, 1, 0, 1, 0, tzinfo=timezone.utc)) assert ('end' in str(excinfo.value))<|docstring|>Test that the constructor and ephemerides interval are consistent.<|endoftext|>
2c86628b47c54e2dfc43e5bfea4fb42b53cb9a3c8d340cde6d33e7d67a8a1729
def test_horizons_parses_query_results_with_magnitudes(): 'Test that the query result from JPL Horizons is parsed correctly.' with mock.patch.object(imephu.service.horizons, 'Horizons') as MockHorizons: MockHorizons.return_value.ephemerides.return_value = _MOCK_QUERY_RESULT_WITH_MAGNITUDE start = datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc) end = datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc) horizons = HorizonsService(object_id='SomeAsteroid', location='B31', start=start, end=end) ephemerides = horizons.ephemerides(start, end) assert (ephemerides[0].epoch == datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[1].epoch == datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[0].position.ra.to_value(u.deg) == pytest.approx(127)) assert (ephemerides[1].position.ra.to_value(u.deg) == pytest.approx(127.01)) assert (ephemerides[0].position.dec.to_value(u.deg) == pytest.approx((- 35))) assert (ephemerides[1].position.dec.to_value(u.deg) == pytest.approx((- 34.9))) assert (ephemerides[0].magnitude_range.min_magnitude == pytest.approx(18)) assert (ephemerides[0].magnitude_range.max_magnitude == pytest.approx(18)) assert (ephemerides[0].magnitude_range.bandpass == 'V') assert (ephemerides[1].magnitude_range.min_magnitude == pytest.approx(18.1)) assert (ephemerides[1].magnitude_range.max_magnitude == pytest.approx(18.1)) assert (ephemerides[1].magnitude_range.bandpass == 'V')
Test that the query result from JPL Horizons is parsed correctly.
tests/service/test_horizons.py
test_horizons_parses_query_results_with_magnitudes
saltastroops/imephu
0
python
def test_horizons_parses_query_results_with_magnitudes(): with mock.patch.object(imephu.service.horizons, 'Horizons') as MockHorizons: MockHorizons.return_value.ephemerides.return_value = _MOCK_QUERY_RESULT_WITH_MAGNITUDE start = datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc) end = datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc) horizons = HorizonsService(object_id='SomeAsteroid', location='B31', start=start, end=end) ephemerides = horizons.ephemerides(start, end) assert (ephemerides[0].epoch == datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[1].epoch == datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[0].position.ra.to_value(u.deg) == pytest.approx(127)) assert (ephemerides[1].position.ra.to_value(u.deg) == pytest.approx(127.01)) assert (ephemerides[0].position.dec.to_value(u.deg) == pytest.approx((- 35))) assert (ephemerides[1].position.dec.to_value(u.deg) == pytest.approx((- 34.9))) assert (ephemerides[0].magnitude_range.min_magnitude == pytest.approx(18)) assert (ephemerides[0].magnitude_range.max_magnitude == pytest.approx(18)) assert (ephemerides[0].magnitude_range.bandpass == 'V') assert (ephemerides[1].magnitude_range.min_magnitude == pytest.approx(18.1)) assert (ephemerides[1].magnitude_range.max_magnitude == pytest.approx(18.1)) assert (ephemerides[1].magnitude_range.bandpass == 'V')
def test_horizons_parses_query_results_with_magnitudes(): with mock.patch.object(imephu.service.horizons, 'Horizons') as MockHorizons: MockHorizons.return_value.ephemerides.return_value = _MOCK_QUERY_RESULT_WITH_MAGNITUDE start = datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc) end = datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc) horizons = HorizonsService(object_id='SomeAsteroid', location='B31', start=start, end=end) ephemerides = horizons.ephemerides(start, end) assert (ephemerides[0].epoch == datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[1].epoch == datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[0].position.ra.to_value(u.deg) == pytest.approx(127)) assert (ephemerides[1].position.ra.to_value(u.deg) == pytest.approx(127.01)) assert (ephemerides[0].position.dec.to_value(u.deg) == pytest.approx((- 35))) assert (ephemerides[1].position.dec.to_value(u.deg) == pytest.approx((- 34.9))) assert (ephemerides[0].magnitude_range.min_magnitude == pytest.approx(18)) assert (ephemerides[0].magnitude_range.max_magnitude == pytest.approx(18)) assert (ephemerides[0].magnitude_range.bandpass == 'V') assert (ephemerides[1].magnitude_range.min_magnitude == pytest.approx(18.1)) assert (ephemerides[1].magnitude_range.max_magnitude == pytest.approx(18.1)) assert (ephemerides[1].magnitude_range.bandpass == 'V')<|docstring|>Test that the query result from JPL Horizons is parsed correctly.<|endoftext|>
2c1fdf7866766d019f102f5dc67f606b791ae5f352ab8973949c5ca6179a6f19
def test_horizons_parses_query_results_without_magnitudes(): 'Test that the query result from JPL Horizons is parsed correctly.' with mock.patch.object(imephu.service.horizons, 'Horizons') as MockHorizons: MockHorizons.return_value.ephemerides.return_value = _MOCK_QUERY_RESULT_WITHOUT_MAGNITUDE start = datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc) end = datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc) horizons = HorizonsService(object_id='SomeAsteroid', location='B31', start=start, end=end) ephemerides = horizons.ephemerides(start, end) assert (ephemerides[0].epoch == datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[1].epoch == datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[0].position.ra.to_value(u.deg) == pytest.approx(127)) assert (ephemerides[1].position.ra.to_value(u.deg) == pytest.approx(127.01)) assert (ephemerides[0].position.dec.to_value(u.deg) == pytest.approx((- 35))) assert (ephemerides[1].position.dec.to_value(u.deg) == pytest.approx((- 34.9))) assert (ephemerides[0].magnitude_range is None) assert (ephemerides[1].magnitude_range is None)
Test that the query result from JPL Horizons is parsed correctly.
tests/service/test_horizons.py
test_horizons_parses_query_results_without_magnitudes
saltastroops/imephu
0
python
def test_horizons_parses_query_results_without_magnitudes(): with mock.patch.object(imephu.service.horizons, 'Horizons') as MockHorizons: MockHorizons.return_value.ephemerides.return_value = _MOCK_QUERY_RESULT_WITHOUT_MAGNITUDE start = datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc) end = datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc) horizons = HorizonsService(object_id='SomeAsteroid', location='B31', start=start, end=end) ephemerides = horizons.ephemerides(start, end) assert (ephemerides[0].epoch == datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[1].epoch == datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[0].position.ra.to_value(u.deg) == pytest.approx(127)) assert (ephemerides[1].position.ra.to_value(u.deg) == pytest.approx(127.01)) assert (ephemerides[0].position.dec.to_value(u.deg) == pytest.approx((- 35))) assert (ephemerides[1].position.dec.to_value(u.deg) == pytest.approx((- 34.9))) assert (ephemerides[0].magnitude_range is None) assert (ephemerides[1].magnitude_range is None)
def test_horizons_parses_query_results_without_magnitudes(): with mock.patch.object(imephu.service.horizons, 'Horizons') as MockHorizons: MockHorizons.return_value.ephemerides.return_value = _MOCK_QUERY_RESULT_WITHOUT_MAGNITUDE start = datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc) end = datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc) horizons = HorizonsService(object_id='SomeAsteroid', location='B31', start=start, end=end) ephemerides = horizons.ephemerides(start, end) assert (ephemerides[0].epoch == datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[1].epoch == datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc)) assert (ephemerides[0].position.ra.to_value(u.deg) == pytest.approx(127)) assert (ephemerides[1].position.ra.to_value(u.deg) == pytest.approx(127.01)) assert (ephemerides[0].position.dec.to_value(u.deg) == pytest.approx((- 35))) assert (ephemerides[1].position.dec.to_value(u.deg) == pytest.approx((- 34.9))) assert (ephemerides[0].magnitude_range is None) assert (ephemerides[1].magnitude_range is None)<|docstring|>Test that the query result from JPL Horizons is parsed correctly.<|endoftext|>
37a930388abcc79e087c60845411635a23eaebb9209321e4f6c600d9a4cf126c
def test_jpl_horizons_is_queried_only_once(): 'Test that the JPL Horizons service is queried only once.' with mock.patch.object(imephu.service.horizons, 'Horizons') as MockHorizons: MockHorizons.return_value.ephemerides.return_value = _MOCK_QUERY_RESULT_WITHOUT_MAGNITUDE start = datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc) end = datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc) horizons = HorizonsService(object_id='Ceres', location='B31', start=start, end=end) horizons.ephemerides(start, end) horizons.ephemerides(start, end) MockHorizons.assert_called_once()
Test that the JPL Horizons service is queried only once.
tests/service/test_horizons.py
test_jpl_horizons_is_queried_only_once
saltastroops/imephu
0
python
def test_jpl_horizons_is_queried_only_once(): with mock.patch.object(imephu.service.horizons, 'Horizons') as MockHorizons: MockHorizons.return_value.ephemerides.return_value = _MOCK_QUERY_RESULT_WITHOUT_MAGNITUDE start = datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc) end = datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc) horizons = HorizonsService(object_id='Ceres', location='B31', start=start, end=end) horizons.ephemerides(start, end) horizons.ephemerides(start, end) MockHorizons.assert_called_once()
def test_jpl_horizons_is_queried_only_once(): with mock.patch.object(imephu.service.horizons, 'Horizons') as MockHorizons: MockHorizons.return_value.ephemerides.return_value = _MOCK_QUERY_RESULT_WITHOUT_MAGNITUDE start = datetime(2022, 2, 8, 13, 27, 14, 0, tzinfo=timezone.utc) end = datetime(2022, 2, 8, 13, 32, 14, 0, tzinfo=timezone.utc) horizons = HorizonsService(object_id='Ceres', location='B31', start=start, end=end) horizons.ephemerides(start, end) horizons.ephemerides(start, end) MockHorizons.assert_called_once()<|docstring|>Test that the JPL Horizons service is queried only once.<|endoftext|>
5d1acdaf019e0ca962cef69f0886ca1d57790389b9fe2a12bddeabad7452b0cf
@pytest.mark.parametrize('start_time_diff,end_time_diff,expected', [(0, 10, [_ephemeris(time_diff) for time_diff in range(0, 11)]), (0, 5, [_ephemeris(time_diff) for time_diff in range(0, 6)]), (8, 10, [_ephemeris(time_diff) for time_diff in range(8, 11)]), (2, 6, [_ephemeris(time_diff) for time_diff in range(2, 7)]), (0.3, 7.6, [_ephemeris(time_diff) for time_diff in range(0, 9)]), (5.3, 9.1, [_ephemeris(time_diff) for time_diff in range(5, 11)]), (2.9, 7.7, [_ephemeris(time_diff) for time_diff in range(2, 9)])]) def test_ephemerides_returns_the_correct_ephemerides(start_time_diff, end_time_diff, expected): 'Test that the ephemerides method returns the correct ephemerides.' all_ephemerides = [_ephemeris(time_diff) for time_diff in range(0, 11)] horizons = HorizonsService(object_id='Ceres', location='B31', start=all_ephemerides[0].epoch, end=all_ephemerides[(- 1)].epoch) horizons._ephemerides = all_ephemerides start = _ephemeris(start_time_diff).epoch end = _ephemeris(end_time_diff).epoch ephemerides = horizons.ephemerides(start=start, end=end) assert (ephemerides == expected)
Test that the ephemerides method returns the correct ephemerides.
tests/service/test_horizons.py
test_ephemerides_returns_the_correct_ephemerides
saltastroops/imephu
0
python
@pytest.mark.parametrize('start_time_diff,end_time_diff,expected', [(0, 10, [_ephemeris(time_diff) for time_diff in range(0, 11)]), (0, 5, [_ephemeris(time_diff) for time_diff in range(0, 6)]), (8, 10, [_ephemeris(time_diff) for time_diff in range(8, 11)]), (2, 6, [_ephemeris(time_diff) for time_diff in range(2, 7)]), (0.3, 7.6, [_ephemeris(time_diff) for time_diff in range(0, 9)]), (5.3, 9.1, [_ephemeris(time_diff) for time_diff in range(5, 11)]), (2.9, 7.7, [_ephemeris(time_diff) for time_diff in range(2, 9)])]) def test_ephemerides_returns_the_correct_ephemerides(start_time_diff, end_time_diff, expected): all_ephemerides = [_ephemeris(time_diff) for time_diff in range(0, 11)] horizons = HorizonsService(object_id='Ceres', location='B31', start=all_ephemerides[0].epoch, end=all_ephemerides[(- 1)].epoch) horizons._ephemerides = all_ephemerides start = _ephemeris(start_time_diff).epoch end = _ephemeris(end_time_diff).epoch ephemerides = horizons.ephemerides(start=start, end=end) assert (ephemerides == expected)
@pytest.mark.parametrize('start_time_diff,end_time_diff,expected', [(0, 10, [_ephemeris(time_diff) for time_diff in range(0, 11)]), (0, 5, [_ephemeris(time_diff) for time_diff in range(0, 6)]), (8, 10, [_ephemeris(time_diff) for time_diff in range(8, 11)]), (2, 6, [_ephemeris(time_diff) for time_diff in range(2, 7)]), (0.3, 7.6, [_ephemeris(time_diff) for time_diff in range(0, 9)]), (5.3, 9.1, [_ephemeris(time_diff) for time_diff in range(5, 11)]), (2.9, 7.7, [_ephemeris(time_diff) for time_diff in range(2, 9)])]) def test_ephemerides_returns_the_correct_ephemerides(start_time_diff, end_time_diff, expected): all_ephemerides = [_ephemeris(time_diff) for time_diff in range(0, 11)] horizons = HorizonsService(object_id='Ceres', location='B31', start=all_ephemerides[0].epoch, end=all_ephemerides[(- 1)].epoch) horizons._ephemerides = all_ephemerides start = _ephemeris(start_time_diff).epoch end = _ephemeris(end_time_diff).epoch ephemerides = horizons.ephemerides(start=start, end=end) assert (ephemerides == expected)<|docstring|>Test that the ephemerides method returns the correct ephemerides.<|endoftext|>
1c084d0e5555139c8935abd98747a43fde07b7dfdb6cfac847cfa7050c3c7c4f
def validate_config(self, local): 'YAML files may contain a special ssm:config tag that stores information about the file when it was generated.\n This information can be used to ensure the file is compatible with future calls. For example, a file created\n with a particular subpath (e.g. /my/deep/path) should not be used to overwrite the root path since this would\n delete any keys not in the original scope. This method does that validation (with permissive defaults for\n backwards compatibility).' config = local.pop(self.METADATA_CONFIG, {}) config_no_secure = config.get(self.METADATA_NO_SECURE, False) if (config_no_secure != self.no_secure): raise ValueError('YAML file generated with no_secure={} but current class set to no_secure={}'.format(config_no_secure, self.no_secure)) if (not self.no_secure): config_no_decrypt = config.get(self.METADATA_NO_DECRYPT, False) if (config_no_decrypt != self.no_decrypt): raise ValueError('YAML file generated with no_decrypt={} but current class set to no_decrypt={}'.format(config_no_decrypt, self.no_decrypt)) config_root = config.get(self.METADATA_ROOT, '/') if (config_root != self.root_path): raise ValueError('YAML file generated with root_path={} but current class set to root_path={}'.format(config_root, self.root_path)) config_paths = config.get(self.METADATA_PATHS, ['/']) for path in self.paths: for config_path in config_paths: if (path[:len(config_path)] == config_path): break else: raise ValueError('Path {} was not included in this file when it was created.'.format(path))
YAML files may contain a special ssm:config tag that stores information about the file when it was generated. This information can be used to ensure the file is compatible with future calls. For example, a file created with a particular subpath (e.g. /my/deep/path) should not be used to overwrite the root path since this would delete any keys not in the original scope. This method does that validation (with permissive defaults for backwards compatibility).
states/storage.py
validate_config
wagensveld/ssm-diff
0
python
def validate_config(self, local): 'YAML files may contain a special ssm:config tag that stores information about the file when it was generated.\n This information can be used to ensure the file is compatible with future calls. For example, a file created\n with a particular subpath (e.g. /my/deep/path) should not be used to overwrite the root path since this would\n delete any keys not in the original scope. This method does that validation (with permissive defaults for\n backwards compatibility).' config = local.pop(self.METADATA_CONFIG, {}) config_no_secure = config.get(self.METADATA_NO_SECURE, False) if (config_no_secure != self.no_secure): raise ValueError('YAML file generated with no_secure={} but current class set to no_secure={}'.format(config_no_secure, self.no_secure)) if (not self.no_secure): config_no_decrypt = config.get(self.METADATA_NO_DECRYPT, False) if (config_no_decrypt != self.no_decrypt): raise ValueError('YAML file generated with no_decrypt={} but current class set to no_decrypt={}'.format(config_no_decrypt, self.no_decrypt)) config_root = config.get(self.METADATA_ROOT, '/') if (config_root != self.root_path): raise ValueError('YAML file generated with root_path={} but current class set to root_path={}'.format(config_root, self.root_path)) config_paths = config.get(self.METADATA_PATHS, ['/']) for path in self.paths: for config_path in config_paths: if (path[:len(config_path)] == config_path): break else: raise ValueError('Path {} was not included in this file when it was created.'.format(path))
def validate_config(self, local): 'YAML files may contain a special ssm:config tag that stores information about the file when it was generated.\n This information can be used to ensure the file is compatible with future calls. For example, a file created\n with a particular subpath (e.g. /my/deep/path) should not be used to overwrite the root path since this would\n delete any keys not in the original scope. This method does that validation (with permissive defaults for\n backwards compatibility).' config = local.pop(self.METADATA_CONFIG, {}) config_no_secure = config.get(self.METADATA_NO_SECURE, False) if (config_no_secure != self.no_secure): raise ValueError('YAML file generated with no_secure={} but current class set to no_secure={}'.format(config_no_secure, self.no_secure)) if (not self.no_secure): config_no_decrypt = config.get(self.METADATA_NO_DECRYPT, False) if (config_no_decrypt != self.no_decrypt): raise ValueError('YAML file generated with no_decrypt={} but current class set to no_decrypt={}'.format(config_no_decrypt, self.no_decrypt)) config_root = config.get(self.METADATA_ROOT, '/') if (config_root != self.root_path): raise ValueError('YAML file generated with root_path={} but current class set to root_path={}'.format(config_root, self.root_path)) config_paths = config.get(self.METADATA_PATHS, ['/']) for path in self.paths: for config_path in config_paths: if (path[:len(config_path)] == config_path): break else: raise ValueError('Path {} was not included in this file when it was created.'.format(path))<|docstring|>YAML files may contain a special ssm:config tag that stores information about the file when it was generated. This information can be used to ensure the file is compatible with future calls. For example, a file created with a particular subpath (e.g. /my/deep/path) should not be used to overwrite the root path since this would delete any keys not in the original scope. This method does that validation (with permissive defaults for backwards compatibility).<|endoftext|>
48b503c6428ec14ccf2aaede03c4954f2825661572755e22a814327a4a638278
def __init__(self): '\n Init sensors stats\n ' try: sensors.init() except: self.initok = False else: self.initok = True
Init sensors stats
glance/glance_agent/lib/GlanceSensors.py
__init__
Quinton/glance
5
python
def __init__(self): '\n \n ' try: sensors.init() except: self.initok = False else: self.initok = True
def __init__(self): '\n \n ' try: sensors.init() except: self.initok = False else: self.initok = True<|docstring|>Init sensors stats<|endoftext|>
56218eefaa8c13566c5fa64136a9d83a36ea740d5a2509c2edb19a295d0dbf5d
def __update__(self): '\n Update the stats\n ' self.sensors_list = [] if self.initok: for chip in sensors.iter_detected_chips(): for feature in chip: sensors_current = {} if feature.name.startswith('temp'): sensors_current['label'] = feature.label[:20] sensors_current['value'] = int(feature.get_value()) self.sensors_list.append(sensors_current)
Update the stats
glance/glance_agent/lib/GlanceSensors.py
__update__
Quinton/glance
5
python
def __update__(self): '\n \n ' self.sensors_list = [] if self.initok: for chip in sensors.iter_detected_chips(): for feature in chip: sensors_current = {} if feature.name.startswith('temp'): sensors_current['label'] = feature.label[:20] sensors_current['value'] = int(feature.get_value()) self.sensors_list.append(sensors_current)
def __update__(self): '\n \n ' self.sensors_list = [] if self.initok: for chip in sensors.iter_detected_chips(): for feature in chip: sensors_current = {} if feature.name.startswith('temp'): sensors_current['label'] = feature.label[:20] sensors_current['value'] = int(feature.get_value()) self.sensors_list.append(sensors_current)<|docstring|>Update the stats<|endoftext|>
55e2086071229666a8a1a68c7483a77831854b59204017084df6f2ce297163e6
def parabolic(f, x): 'Quadratic interpolation for estimating the true position of an\n inter-sample maximum when nearby samples are known.\n f is a vector and x is an index for that vector.\n Returns (vx, vy), the coordinates of the vertex of a parabola that goes\n through point x and its two neighbors.\n Example:\n Defining a vector f with a local maximum at index 3 (= 6), find local\n maximum if points 2, 3, and 4 actually defined a parabola.\n In [3]: f = [2, 3, 1, 6, 4, 2, 3, 1]\n In [4]: parabolic(f, argmax(f))\n Out[4]: (3.2142857142857144, 6.1607142857142856)\n ' xv = ((((1 / 2.0) * (f[(x - 1)] - f[(x + 1)])) / ((f[(x - 1)] - (2 * f[x])) + f[(x + 1)])) + x) yv = (f[x] - (((1 / 4.0) * (f[(x - 1)] - f[(x + 1)])) * (xv - x))) return (xv, yv)
Quadratic interpolation for estimating the true position of an inter-sample maximum when nearby samples are known. f is a vector and x is an index for that vector. Returns (vx, vy), the coordinates of the vertex of a parabola that goes through point x and its two neighbors. Example: Defining a vector f with a local maximum at index 3 (= 6), find local maximum if points 2, 3, and 4 actually defined a parabola. In [3]: f = [2, 3, 1, 6, 4, 2, 3, 1] In [4]: parabolic(f, argmax(f)) Out[4]: (3.2142857142857144, 6.1607142857142856)
08Aug.py
parabolic
dicustefania/morpheus
0
python
def parabolic(f, x): 'Quadratic interpolation for estimating the true position of an\n inter-sample maximum when nearby samples are known.\n f is a vector and x is an index for that vector.\n Returns (vx, vy), the coordinates of the vertex of a parabola that goes\n through point x and its two neighbors.\n Example:\n Defining a vector f with a local maximum at index 3 (= 6), find local\n maximum if points 2, 3, and 4 actually defined a parabola.\n In [3]: f = [2, 3, 1, 6, 4, 2, 3, 1]\n In [4]: parabolic(f, argmax(f))\n Out[4]: (3.2142857142857144, 6.1607142857142856)\n ' xv = ((((1 / 2.0) * (f[(x - 1)] - f[(x + 1)])) / ((f[(x - 1)] - (2 * f[x])) + f[(x + 1)])) + x) yv = (f[x] - (((1 / 4.0) * (f[(x - 1)] - f[(x + 1)])) * (xv - x))) return (xv, yv)
def parabolic(f, x): 'Quadratic interpolation for estimating the true position of an\n inter-sample maximum when nearby samples are known.\n f is a vector and x is an index for that vector.\n Returns (vx, vy), the coordinates of the vertex of a parabola that goes\n through point x and its two neighbors.\n Example:\n Defining a vector f with a local maximum at index 3 (= 6), find local\n maximum if points 2, 3, and 4 actually defined a parabola.\n In [3]: f = [2, 3, 1, 6, 4, 2, 3, 1]\n In [4]: parabolic(f, argmax(f))\n Out[4]: (3.2142857142857144, 6.1607142857142856)\n ' xv = ((((1 / 2.0) * (f[(x - 1)] - f[(x + 1)])) / ((f[(x - 1)] - (2 * f[x])) + f[(x + 1)])) + x) yv = (f[x] - (((1 / 4.0) * (f[(x - 1)] - f[(x + 1)])) * (xv - x))) return (xv, yv)<|docstring|>Quadratic interpolation for estimating the true position of an inter-sample maximum when nearby samples are known. f is a vector and x is an index for that vector. Returns (vx, vy), the coordinates of the vertex of a parabola that goes through point x and its two neighbors. Example: Defining a vector f with a local maximum at index 3 (= 6), find local maximum if points 2, 3, and 4 actually defined a parabola. In [3]: f = [2, 3, 1, 6, 4, 2, 3, 1] In [4]: parabolic(f, argmax(f)) Out[4]: (3.2142857142857144, 6.1607142857142856)<|endoftext|>
b0e046454339d9566d8ff3b453fa6e30eb7c574e946263538d53500e7ab8725c
def longestCommonPrefix(self, strs): '\n :type strs: List[str]\n :rtype: str\n ' if (not strs): return '' shortest = min(strs, key=len) for (i, l) in enumerate(shortest): for item in strs: if (item[i] != l): return shortest[:i] return shortest
:type strs: List[str] :rtype: str
14.py
longestCommonPrefix
wilbertgeng/LeetCode_exercise
0
python
def longestCommonPrefix(self, strs): '\n :type strs: List[str]\n :rtype: str\n ' if (not strs): return shortest = min(strs, key=len) for (i, l) in enumerate(shortest): for item in strs: if (item[i] != l): return shortest[:i] return shortest
def longestCommonPrefix(self, strs): '\n :type strs: List[str]\n :rtype: str\n ' if (not strs): return shortest = min(strs, key=len) for (i, l) in enumerate(shortest): for item in strs: if (item[i] != l): return shortest[:i] return shortest<|docstring|>:type strs: List[str] :rtype: str<|endoftext|>
0cf6bbf02e87760a440039b0df5f1bbb5094d5ede3ef6923a4ba5ef77a91b42b
def _collect_stats(args): '\n Function that is executed in a separate process.\n\n :param args: arguments of the process to be executed.\n\n :return: a vector of CTR for these confidence values:\n 0th: Q0.500\n 1st: Q0.025\n snd: Q0.975\n ' start = time.time() print(f"START: Num of Users: {args['num_offline_users']}") stats = recogym.test_agent(deepcopy(args['env']), deepcopy(args['agent']), args['num_offline_users'], args['num_online_users'], args['num_organic_offline_users'], args['num_epochs'], args['epoch_with_random_reset'], args['with_cache']) print(f"END: Num of Offline Users: {args['num_offline_users']} ({(time.time() - start)}s)") return stats
Function that is executed in a separate process. :param args: arguments of the process to be executed. :return: a vector of CTR for these confidence values: 0th: Q0.500 1st: Q0.025 snd: Q0.975
recogym/evaluate_agent.py
_collect_stats
bmazoure/reco-gym
413
python
def _collect_stats(args): '\n Function that is executed in a separate process.\n\n :param args: arguments of the process to be executed.\n\n :return: a vector of CTR for these confidence values:\n 0th: Q0.500\n 1st: Q0.025\n snd: Q0.975\n ' start = time.time() print(f"START: Num of Users: {args['num_offline_users']}") stats = recogym.test_agent(deepcopy(args['env']), deepcopy(args['agent']), args['num_offline_users'], args['num_online_users'], args['num_organic_offline_users'], args['num_epochs'], args['epoch_with_random_reset'], args['with_cache']) print(f"END: Num of Offline Users: {args['num_offline_users']} ({(time.time() - start)}s)") return stats
def _collect_stats(args): '\n Function that is executed in a separate process.\n\n :param args: arguments of the process to be executed.\n\n :return: a vector of CTR for these confidence values:\n 0th: Q0.500\n 1st: Q0.025\n snd: Q0.975\n ' start = time.time() print(f"START: Num of Users: {args['num_offline_users']}") stats = recogym.test_agent(deepcopy(args['env']), deepcopy(args['agent']), args['num_offline_users'], args['num_online_users'], args['num_organic_offline_users'], args['num_epochs'], args['epoch_with_random_reset'], args['with_cache']) print(f"END: Num of Offline Users: {args['num_offline_users']} ({(time.time() - start)}s)") return stats<|docstring|>Function that is executed in a separate process. :param args: arguments of the process to be executed. :return: a vector of CTR for these confidence values: 0th: Q0.500 1st: Q0.025 snd: Q0.975<|endoftext|>
0dc328de5c41ed1996bb29b5db6828908ca81759448262e0ea76aa60b23ce45d
def gather_agent_stats(env, env_args, extra_env_args, agents_init_data, user_samples=(100, 1000, 2000, 3000, 5000, 8000, 10000, 13000, 14000, 15000), num_online_users: int=15000, num_epochs: int=1, epoch_with_random_reset: bool=False, num_organic_offline_users: int=100, with_cache: bool=False): "\n The function that gathers Agents statistics via evaluating Agent performance\n under different Environment conditions.\n\n :param env: the Environment where some changes should be introduced and where Agent stats should\n be gathered.\n :param env_args: Environment arguments (default ones).\n :param extra_env_args: extra Environment conditions those alter default values.\n :param agents_init_data: Agent initialisation data.\n This is a dictionary that has the following structure:\n {\n '<Agent Name>': {\n AgentInit.CTOR: <Constructor>,\n AgentInit.DEF_ARG: <Default Arguments>,\n }\n }\n :param user_samples: Number of Offline Users i.e. Users used to train a Model.\n :param num_online_users: Number of Online Users i.e. Users used to validate a Model.\n :param num_epochs: how many different epochs should be tried to gather stats?\n :param epoch_with_random_reset: should be a Random Seed reset at each new epoch?\n :param num_organic_offline_users: how many Organic only users should be used for training.\n :param with_cache: is the cache used for training data or not?\n\n :return: a dictionary with stats\n {\n AgentStats.SAMPLES: [<vector of training offline users used to train a model>]\n AgentStats.AGENTS: {\n '<Agent Name>': {\n AgentStats.Q0_025: [],\n AgentStats.Q0_500: [],\n AgentStats.Q0_975: [],\n }\n }\n }\n " new_env_args = {**env_args, **extra_env_args} new_env = deepcopy(env) new_env.init_gym(new_env_args) agents = build_agents(agents_init_data, new_env_args) agent_stats = {AgentStats.SAMPLES: user_samples, AgentStats.AGENTS: dict()} for agent_key in agents: print(f'Agent: {agent_key}') stats = {AgentStats.Q0_025: [], AgentStats.Q0_500: [], AgentStats.Q0_975: []} with Pool(processes=multiprocessing.cpu_count()) as pool: argss = [{'env': new_env, 'agent': agents[agent_key], 'num_offline_users': num_offline_users, 'num_online_users': num_online_users, 'num_organic_offline_users': num_organic_offline_users, 'num_epochs': num_epochs, 'epoch_with_random_reset': epoch_with_random_reset, 'with_cache': with_cache} for num_offline_users in user_samples] for result in ([_collect_stats(args) for args in argss] if (num_epochs == 1) else pool.map(_collect_stats, argss)): stats[AgentStats.Q0_025].append(result[1]) stats[AgentStats.Q0_500].append(result[0]) stats[AgentStats.Q0_975].append(result[2]) agent_stats[AgentStats.AGENTS][agent_key] = stats return agent_stats
The function that gathers Agents statistics via evaluating Agent performance under different Environment conditions. :param env: the Environment where some changes should be introduced and where Agent stats should be gathered. :param env_args: Environment arguments (default ones). :param extra_env_args: extra Environment conditions those alter default values. :param agents_init_data: Agent initialisation data. This is a dictionary that has the following structure: { '<Agent Name>': { AgentInit.CTOR: <Constructor>, AgentInit.DEF_ARG: <Default Arguments>, } } :param user_samples: Number of Offline Users i.e. Users used to train a Model. :param num_online_users: Number of Online Users i.e. Users used to validate a Model. :param num_epochs: how many different epochs should be tried to gather stats? :param epoch_with_random_reset: should be a Random Seed reset at each new epoch? :param num_organic_offline_users: how many Organic only users should be used for training. :param with_cache: is the cache used for training data or not? :return: a dictionary with stats { AgentStats.SAMPLES: [<vector of training offline users used to train a model>] AgentStats.AGENTS: { '<Agent Name>': { AgentStats.Q0_025: [], AgentStats.Q0_500: [], AgentStats.Q0_975: [], } } }
recogym/evaluate_agent.py
gather_agent_stats
bmazoure/reco-gym
413
python
def gather_agent_stats(env, env_args, extra_env_args, agents_init_data, user_samples=(100, 1000, 2000, 3000, 5000, 8000, 10000, 13000, 14000, 15000), num_online_users: int=15000, num_epochs: int=1, epoch_with_random_reset: bool=False, num_organic_offline_users: int=100, with_cache: bool=False): "\n The function that gathers Agents statistics via evaluating Agent performance\n under different Environment conditions.\n\n :param env: the Environment where some changes should be introduced and where Agent stats should\n be gathered.\n :param env_args: Environment arguments (default ones).\n :param extra_env_args: extra Environment conditions those alter default values.\n :param agents_init_data: Agent initialisation data.\n This is a dictionary that has the following structure:\n {\n '<Agent Name>': {\n AgentInit.CTOR: <Constructor>,\n AgentInit.DEF_ARG: <Default Arguments>,\n }\n }\n :param user_samples: Number of Offline Users i.e. Users used to train a Model.\n :param num_online_users: Number of Online Users i.e. Users used to validate a Model.\n :param num_epochs: how many different epochs should be tried to gather stats?\n :param epoch_with_random_reset: should be a Random Seed reset at each new epoch?\n :param num_organic_offline_users: how many Organic only users should be used for training.\n :param with_cache: is the cache used for training data or not?\n\n :return: a dictionary with stats\n {\n AgentStats.SAMPLES: [<vector of training offline users used to train a model>]\n AgentStats.AGENTS: {\n '<Agent Name>': {\n AgentStats.Q0_025: [],\n AgentStats.Q0_500: [],\n AgentStats.Q0_975: [],\n }\n }\n }\n " new_env_args = {**env_args, **extra_env_args} new_env = deepcopy(env) new_env.init_gym(new_env_args) agents = build_agents(agents_init_data, new_env_args) agent_stats = {AgentStats.SAMPLES: user_samples, AgentStats.AGENTS: dict()} for agent_key in agents: print(f'Agent: {agent_key}') stats = {AgentStats.Q0_025: [], AgentStats.Q0_500: [], AgentStats.Q0_975: []} with Pool(processes=multiprocessing.cpu_count()) as pool: argss = [{'env': new_env, 'agent': agents[agent_key], 'num_offline_users': num_offline_users, 'num_online_users': num_online_users, 'num_organic_offline_users': num_organic_offline_users, 'num_epochs': num_epochs, 'epoch_with_random_reset': epoch_with_random_reset, 'with_cache': with_cache} for num_offline_users in user_samples] for result in ([_collect_stats(args) for args in argss] if (num_epochs == 1) else pool.map(_collect_stats, argss)): stats[AgentStats.Q0_025].append(result[1]) stats[AgentStats.Q0_500].append(result[0]) stats[AgentStats.Q0_975].append(result[2]) agent_stats[AgentStats.AGENTS][agent_key] = stats return agent_stats
def gather_agent_stats(env, env_args, extra_env_args, agents_init_data, user_samples=(100, 1000, 2000, 3000, 5000, 8000, 10000, 13000, 14000, 15000), num_online_users: int=15000, num_epochs: int=1, epoch_with_random_reset: bool=False, num_organic_offline_users: int=100, with_cache: bool=False): "\n The function that gathers Agents statistics via evaluating Agent performance\n under different Environment conditions.\n\n :param env: the Environment where some changes should be introduced and where Agent stats should\n be gathered.\n :param env_args: Environment arguments (default ones).\n :param extra_env_args: extra Environment conditions those alter default values.\n :param agents_init_data: Agent initialisation data.\n This is a dictionary that has the following structure:\n {\n '<Agent Name>': {\n AgentInit.CTOR: <Constructor>,\n AgentInit.DEF_ARG: <Default Arguments>,\n }\n }\n :param user_samples: Number of Offline Users i.e. Users used to train a Model.\n :param num_online_users: Number of Online Users i.e. Users used to validate a Model.\n :param num_epochs: how many different epochs should be tried to gather stats?\n :param epoch_with_random_reset: should be a Random Seed reset at each new epoch?\n :param num_organic_offline_users: how many Organic only users should be used for training.\n :param with_cache: is the cache used for training data or not?\n\n :return: a dictionary with stats\n {\n AgentStats.SAMPLES: [<vector of training offline users used to train a model>]\n AgentStats.AGENTS: {\n '<Agent Name>': {\n AgentStats.Q0_025: [],\n AgentStats.Q0_500: [],\n AgentStats.Q0_975: [],\n }\n }\n }\n " new_env_args = {**env_args, **extra_env_args} new_env = deepcopy(env) new_env.init_gym(new_env_args) agents = build_agents(agents_init_data, new_env_args) agent_stats = {AgentStats.SAMPLES: user_samples, AgentStats.AGENTS: dict()} for agent_key in agents: print(f'Agent: {agent_key}') stats = {AgentStats.Q0_025: [], AgentStats.Q0_500: [], AgentStats.Q0_975: []} with Pool(processes=multiprocessing.cpu_count()) as pool: argss = [{'env': new_env, 'agent': agents[agent_key], 'num_offline_users': num_offline_users, 'num_online_users': num_online_users, 'num_organic_offline_users': num_organic_offline_users, 'num_epochs': num_epochs, 'epoch_with_random_reset': epoch_with_random_reset, 'with_cache': with_cache} for num_offline_users in user_samples] for result in ([_collect_stats(args) for args in argss] if (num_epochs == 1) else pool.map(_collect_stats, argss)): stats[AgentStats.Q0_025].append(result[1]) stats[AgentStats.Q0_500].append(result[0]) stats[AgentStats.Q0_975].append(result[2]) agent_stats[AgentStats.AGENTS][agent_key] = stats return agent_stats<|docstring|>The function that gathers Agents statistics via evaluating Agent performance under different Environment conditions. :param env: the Environment where some changes should be introduced and where Agent stats should be gathered. :param env_args: Environment arguments (default ones). :param extra_env_args: extra Environment conditions those alter default values. :param agents_init_data: Agent initialisation data. This is a dictionary that has the following structure: { '<Agent Name>': { AgentInit.CTOR: <Constructor>, AgentInit.DEF_ARG: <Default Arguments>, } } :param user_samples: Number of Offline Users i.e. Users used to train a Model. :param num_online_users: Number of Online Users i.e. Users used to validate a Model. :param num_epochs: how many different epochs should be tried to gather stats? :param epoch_with_random_reset: should be a Random Seed reset at each new epoch? :param num_organic_offline_users: how many Organic only users should be used for training. :param with_cache: is the cache used for training data or not? :return: a dictionary with stats { AgentStats.SAMPLES: [<vector of training offline users used to train a model>] AgentStats.AGENTS: { '<Agent Name>': { AgentStats.Q0_025: [], AgentStats.Q0_500: [], AgentStats.Q0_975: [], } } }<|endoftext|>
e2f9cf290b766a781bc610119e02a04c70b52ea5baebc8d450dddefc3687e209
def _collect_evolution_stats(args): '\n Function that is executed in a separate process.\n\n :param args: arguments of the process to be executed.\n\n :return: a dictionary of Success/Failures of applying an Agent.\n ' start = time.time() epsilon = args['epsilon'] epsilon_key = format_epsilon(epsilon) print(f'START: ε = {epsilon_key}') num_evolution_steps = args['num_evolution_steps'] rewards = recogym.evaluate_agent(deepcopy(args['env']), args['agent'], args['num_initial_train_users'], args['num_step_users'], num_evolution_steps, args['training_approach']) assert (len(rewards[EvolutionCase.SUCCESS]) == len(rewards[EvolutionCase.FAILURE])) assert (len(rewards[EvolutionCase.SUCCESS]) == num_evolution_steps) print(f'END: ε = {epsilon_key} ({(time.time() - start)}s)') return {epsilon_key: {EvolutionCase.SUCCESS: rewards[EvolutionCase.SUCCESS], EvolutionCase.SUCCESS_GREEDY: rewards[EvolutionCase.SUCCESS_GREEDY], EvolutionCase.FAILURE: rewards[EvolutionCase.FAILURE], EvolutionCase.FAILURE_GREEDY: rewards[EvolutionCase.FAILURE_GREEDY], EvolutionCase.ACTIONS: rewards[EvolutionCase.ACTIONS]}}
Function that is executed in a separate process. :param args: arguments of the process to be executed. :return: a dictionary of Success/Failures of applying an Agent.
recogym/evaluate_agent.py
_collect_evolution_stats
bmazoure/reco-gym
413
python
def _collect_evolution_stats(args): '\n Function that is executed in a separate process.\n\n :param args: arguments of the process to be executed.\n\n :return: a dictionary of Success/Failures of applying an Agent.\n ' start = time.time() epsilon = args['epsilon'] epsilon_key = format_epsilon(epsilon) print(f'START: ε = {epsilon_key}') num_evolution_steps = args['num_evolution_steps'] rewards = recogym.evaluate_agent(deepcopy(args['env']), args['agent'], args['num_initial_train_users'], args['num_step_users'], num_evolution_steps, args['training_approach']) assert (len(rewards[EvolutionCase.SUCCESS]) == len(rewards[EvolutionCase.FAILURE])) assert (len(rewards[EvolutionCase.SUCCESS]) == num_evolution_steps) print(f'END: ε = {epsilon_key} ({(time.time() - start)}s)') return {epsilon_key: {EvolutionCase.SUCCESS: rewards[EvolutionCase.SUCCESS], EvolutionCase.SUCCESS_GREEDY: rewards[EvolutionCase.SUCCESS_GREEDY], EvolutionCase.FAILURE: rewards[EvolutionCase.FAILURE], EvolutionCase.FAILURE_GREEDY: rewards[EvolutionCase.FAILURE_GREEDY], EvolutionCase.ACTIONS: rewards[EvolutionCase.ACTIONS]}}
def _collect_evolution_stats(args): '\n Function that is executed in a separate process.\n\n :param args: arguments of the process to be executed.\n\n :return: a dictionary of Success/Failures of applying an Agent.\n ' start = time.time() epsilon = args['epsilon'] epsilon_key = format_epsilon(epsilon) print(f'START: ε = {epsilon_key}') num_evolution_steps = args['num_evolution_steps'] rewards = recogym.evaluate_agent(deepcopy(args['env']), args['agent'], args['num_initial_train_users'], args['num_step_users'], num_evolution_steps, args['training_approach']) assert (len(rewards[EvolutionCase.SUCCESS]) == len(rewards[EvolutionCase.FAILURE])) assert (len(rewards[EvolutionCase.SUCCESS]) == num_evolution_steps) print(f'END: ε = {epsilon_key} ({(time.time() - start)}s)') return {epsilon_key: {EvolutionCase.SUCCESS: rewards[EvolutionCase.SUCCESS], EvolutionCase.SUCCESS_GREEDY: rewards[EvolutionCase.SUCCESS_GREEDY], EvolutionCase.FAILURE: rewards[EvolutionCase.FAILURE], EvolutionCase.FAILURE_GREEDY: rewards[EvolutionCase.FAILURE_GREEDY], EvolutionCase.ACTIONS: rewards[EvolutionCase.ACTIONS]}}<|docstring|>Function that is executed in a separate process. :param args: arguments of the process to be executed. :return: a dictionary of Success/Failures of applying an Agent.<|endoftext|>
0c12d1e56e7ddb4562116149b3c6952aec7f82ef985108b0ef4cf90715d4199e
def gather_exploration_stats(env, env_args, extra_env_args, agents_init_data, training_approach, num_initial_train_users=1000, num_step_users=1000, epsilons=EvolutionEpsilons, num_evolution_steps=6): "\n A helper function that collects data regarding Agents evolution\n under different values of epsilon for Epsilon-Greedy Selection Policy.\n\n :param env: The Environment where evolution should be applied;\n every time when a new step of the evolution is applied, the Environment is deeply copied\n thus the Environment does not interferes with evolution steps.\n\n :param env_args: Environment arguments (default ones).\n :param extra_env_args: extra Environment conditions those alter default values.\n :param agents_init_data: Agent initialisation data.\n This is a dictionary that has the following structure:\n {\n '<Agent Name>': {\n AgentInit.CTOR: <Constructor>,\n AgentInit.DEF_ARG: <Default Arguments>,\n }\n }\n\n\n :param training_approach: A training approach applied in verification;\n for mode details look at `TrainingApproach' enum.\n\n :param num_initial_train_users: how many users' data should be used\n to train an initial model BEFORE evolution steps.\n\n :param num_step_users: how many users' data should be used\n at each evolution step.\n\n :param epsilons: a list of epsilon values.\n\n :param num_evolution_steps: how many evolution steps should be applied\n for an Agent with Epsilon-Greedy Selection Policy.\n\n :return a dictionary of Agent evolution statistics in the form:\n {\n 'Agent Name': {\n 'Epsilon Values': {\n EvolutionCase.SUCCESS: [an array of clicks (for each ith step of evolution)]\n EvolutionCase.FAILURE: [an array of failure to draw a click (for each ith step of evolution)]\n }\n }\n }\n " agent_evolution_stats = dict() new_env_args = {**env_args, **extra_env_args} new_env = deepcopy(env) new_env.init_gym(new_env_args) agents = build_agents(agents_init_data, new_env_args) for agent_key in agents: print(f'Agent: {agent_key}') agent_stats = dict() with Pool(processes=multiprocessing.cpu_count()) as pool: for result in pool.map(_collect_evolution_stats, [{'epsilon': epsilon, 'env': new_env, 'agent': EpsilonGreedy(Configuration({**epsilon_greedy_args, **new_env_args, 'epsilon': epsilon}), deepcopy(agents[agent_key])), 'num_initial_train_users': num_initial_train_users, 'num_step_users': num_step_users, 'num_evolution_steps': num_evolution_steps, 'training_approach': training_approach} for epsilon in epsilons]): agent_stats = {**agent_stats, **result} agent_evolution_stats[agent_key] = agent_stats return agent_evolution_stats
A helper function that collects data regarding Agents evolution under different values of epsilon for Epsilon-Greedy Selection Policy. :param env: The Environment where evolution should be applied; every time when a new step of the evolution is applied, the Environment is deeply copied thus the Environment does not interferes with evolution steps. :param env_args: Environment arguments (default ones). :param extra_env_args: extra Environment conditions those alter default values. :param agents_init_data: Agent initialisation data. This is a dictionary that has the following structure: { '<Agent Name>': { AgentInit.CTOR: <Constructor>, AgentInit.DEF_ARG: <Default Arguments>, } } :param training_approach: A training approach applied in verification; for mode details look at `TrainingApproach' enum. :param num_initial_train_users: how many users' data should be used to train an initial model BEFORE evolution steps. :param num_step_users: how many users' data should be used at each evolution step. :param epsilons: a list of epsilon values. :param num_evolution_steps: how many evolution steps should be applied for an Agent with Epsilon-Greedy Selection Policy. :return a dictionary of Agent evolution statistics in the form: { 'Agent Name': { 'Epsilon Values': { EvolutionCase.SUCCESS: [an array of clicks (for each ith step of evolution)] EvolutionCase.FAILURE: [an array of failure to draw a click (for each ith step of evolution)] } } }
recogym/evaluate_agent.py
gather_exploration_stats
bmazoure/reco-gym
413
python
def gather_exploration_stats(env, env_args, extra_env_args, agents_init_data, training_approach, num_initial_train_users=1000, num_step_users=1000, epsilons=EvolutionEpsilons, num_evolution_steps=6): "\n A helper function that collects data regarding Agents evolution\n under different values of epsilon for Epsilon-Greedy Selection Policy.\n\n :param env: The Environment where evolution should be applied;\n every time when a new step of the evolution is applied, the Environment is deeply copied\n thus the Environment does not interferes with evolution steps.\n\n :param env_args: Environment arguments (default ones).\n :param extra_env_args: extra Environment conditions those alter default values.\n :param agents_init_data: Agent initialisation data.\n This is a dictionary that has the following structure:\n {\n '<Agent Name>': {\n AgentInit.CTOR: <Constructor>,\n AgentInit.DEF_ARG: <Default Arguments>,\n }\n }\n\n\n :param training_approach: A training approach applied in verification;\n for mode details look at `TrainingApproach' enum.\n\n :param num_initial_train_users: how many users' data should be used\n to train an initial model BEFORE evolution steps.\n\n :param num_step_users: how many users' data should be used\n at each evolution step.\n\n :param epsilons: a list of epsilon values.\n\n :param num_evolution_steps: how many evolution steps should be applied\n for an Agent with Epsilon-Greedy Selection Policy.\n\n :return a dictionary of Agent evolution statistics in the form:\n {\n 'Agent Name': {\n 'Epsilon Values': {\n EvolutionCase.SUCCESS: [an array of clicks (for each ith step of evolution)]\n EvolutionCase.FAILURE: [an array of failure to draw a click (for each ith step of evolution)]\n }\n }\n }\n " agent_evolution_stats = dict() new_env_args = {**env_args, **extra_env_args} new_env = deepcopy(env) new_env.init_gym(new_env_args) agents = build_agents(agents_init_data, new_env_args) for agent_key in agents: print(f'Agent: {agent_key}') agent_stats = dict() with Pool(processes=multiprocessing.cpu_count()) as pool: for result in pool.map(_collect_evolution_stats, [{'epsilon': epsilon, 'env': new_env, 'agent': EpsilonGreedy(Configuration({**epsilon_greedy_args, **new_env_args, 'epsilon': epsilon}), deepcopy(agents[agent_key])), 'num_initial_train_users': num_initial_train_users, 'num_step_users': num_step_users, 'num_evolution_steps': num_evolution_steps, 'training_approach': training_approach} for epsilon in epsilons]): agent_stats = {**agent_stats, **result} agent_evolution_stats[agent_key] = agent_stats return agent_evolution_stats
def gather_exploration_stats(env, env_args, extra_env_args, agents_init_data, training_approach, num_initial_train_users=1000, num_step_users=1000, epsilons=EvolutionEpsilons, num_evolution_steps=6): "\n A helper function that collects data regarding Agents evolution\n under different values of epsilon for Epsilon-Greedy Selection Policy.\n\n :param env: The Environment where evolution should be applied;\n every time when a new step of the evolution is applied, the Environment is deeply copied\n thus the Environment does not interferes with evolution steps.\n\n :param env_args: Environment arguments (default ones).\n :param extra_env_args: extra Environment conditions those alter default values.\n :param agents_init_data: Agent initialisation data.\n This is a dictionary that has the following structure:\n {\n '<Agent Name>': {\n AgentInit.CTOR: <Constructor>,\n AgentInit.DEF_ARG: <Default Arguments>,\n }\n }\n\n\n :param training_approach: A training approach applied in verification;\n for mode details look at `TrainingApproach' enum.\n\n :param num_initial_train_users: how many users' data should be used\n to train an initial model BEFORE evolution steps.\n\n :param num_step_users: how many users' data should be used\n at each evolution step.\n\n :param epsilons: a list of epsilon values.\n\n :param num_evolution_steps: how many evolution steps should be applied\n for an Agent with Epsilon-Greedy Selection Policy.\n\n :return a dictionary of Agent evolution statistics in the form:\n {\n 'Agent Name': {\n 'Epsilon Values': {\n EvolutionCase.SUCCESS: [an array of clicks (for each ith step of evolution)]\n EvolutionCase.FAILURE: [an array of failure to draw a click (for each ith step of evolution)]\n }\n }\n }\n " agent_evolution_stats = dict() new_env_args = {**env_args, **extra_env_args} new_env = deepcopy(env) new_env.init_gym(new_env_args) agents = build_agents(agents_init_data, new_env_args) for agent_key in agents: print(f'Agent: {agent_key}') agent_stats = dict() with Pool(processes=multiprocessing.cpu_count()) as pool: for result in pool.map(_collect_evolution_stats, [{'epsilon': epsilon, 'env': new_env, 'agent': EpsilonGreedy(Configuration({**epsilon_greedy_args, **new_env_args, 'epsilon': epsilon}), deepcopy(agents[agent_key])), 'num_initial_train_users': num_initial_train_users, 'num_step_users': num_step_users, 'num_evolution_steps': num_evolution_steps, 'training_approach': training_approach} for epsilon in epsilons]): agent_stats = {**agent_stats, **result} agent_evolution_stats[agent_key] = agent_stats return agent_evolution_stats<|docstring|>A helper function that collects data regarding Agents evolution under different values of epsilon for Epsilon-Greedy Selection Policy. :param env: The Environment where evolution should be applied; every time when a new step of the evolution is applied, the Environment is deeply copied thus the Environment does not interferes with evolution steps. :param env_args: Environment arguments (default ones). :param extra_env_args: extra Environment conditions those alter default values. :param agents_init_data: Agent initialisation data. This is a dictionary that has the following structure: { '<Agent Name>': { AgentInit.CTOR: <Constructor>, AgentInit.DEF_ARG: <Default Arguments>, } } :param training_approach: A training approach applied in verification; for mode details look at `TrainingApproach' enum. :param num_initial_train_users: how many users' data should be used to train an initial model BEFORE evolution steps. :param num_step_users: how many users' data should be used at each evolution step. :param epsilons: a list of epsilon values. :param num_evolution_steps: how many evolution steps should be applied for an Agent with Epsilon-Greedy Selection Policy. :return a dictionary of Agent evolution statistics in the form: { 'Agent Name': { 'Epsilon Values': { EvolutionCase.SUCCESS: [an array of clicks (for each ith step of evolution)] EvolutionCase.FAILURE: [an array of failure to draw a click (for each ith step of evolution)] } } }<|endoftext|>
d52dcdb8b14ee2308b88954706f1eed52615f043aad4d1916698838462092f60
def plot_roi(agent_evolution_stats, epsilons=EvolutionEpsilons, max_agents_per_row=2): "\n A helper function that calculates Return of Investment (ROI) for applying Epsilon-Greedy Selection Policy.\n\n :param agent_evolution_stats: statistic about Agent evolution collected in `build_exploration_data'.\n\n :param epsilons: a list of epsilon values.\n\n :param max_agents_per_row: how many graphs should be drawn per a row\n\n :return: a dictionary of Agent ROI after applying Epsilon-Greedy Selection Strategy in the following form:\n {\n 'Agent Name': {\n 'Epsilon Value': {\n Metrics.ROI: [an array of ROIs for each ith step (starting from 1st step)]\n }\n }\n }\n " (figs, axs) = plt.subplots(int((len(agent_evolution_stats) / max_agents_per_row)), max_agents_per_row, figsize=(16, 8), squeeze=False) labels = [('$\\epsilon=$' + format_epsilon(epsilon)) for epsilon in epsilons if (epsilon != 0.0)] agent_roi_stats = dict() for (ix, agent_key) in enumerate(agent_evolution_stats): ax = axs[(int((ix / max_agents_per_row)), int((ix % max_agents_per_row)))] agent_stat = agent_evolution_stats[agent_key] zero_epsilon_key = format_epsilon(0) zero_epsilon = agent_stat[zero_epsilon_key] zero_success_evolutions = zero_epsilon[EvolutionCase.SUCCESS] zero_failure_evolutions = zero_epsilon[EvolutionCase.FAILURE] assert len(zero_success_evolutions) agent_stats = dict() roi_mean_means = [] for epsilon in generate_epsilons(): if (zero_epsilon_key == format_epsilon(epsilon)): continue epsilon_key = format_epsilon(epsilon) agent_stats[epsilon_key] = {RoiMetrics.ROI_0_025: [], RoiMetrics.ROI_MEAN: [], RoiMetrics.ROI_0_975: []} epsilon_evolutions = agent_stat[epsilon_key] success_greedy_evolutions = epsilon_evolutions[EvolutionCase.SUCCESS_GREEDY] failure_greedy_evolutions = epsilon_evolutions[EvolutionCase.FAILURE_GREEDY] assert (len(success_greedy_evolutions) == len(failure_greedy_evolutions)) assert (len(zero_success_evolutions) == len(success_greedy_evolutions)) steps = [] roi_means = [] for step in range(1, len(epsilon_evolutions[EvolutionCase.SUCCESS])): previous_zero_successes = zero_success_evolutions[(step - 1)] previous_zero_failures = zero_failure_evolutions[(step - 1)] current_zero_successes = zero_success_evolutions[step] current_zero_failures = zero_failure_evolutions[step] current_epsilon_greedy_successes = success_greedy_evolutions[step] current_epsilon_greedy_failures = failure_greedy_evolutions[step] def roi_with_confidence_interval(epsilon, previous_zero_successes, previous_zero_failures, current_zero_successes, current_zero_failures, current_epsilon_greedy_successes, current_epsilon_greedy_failures): def roi_formulae(epsilon, previous_zero, current_zero, current_epsilon_greedy): current_gain = ((current_epsilon_greedy / (1 - epsilon)) - current_zero) roi = (current_gain / (epsilon * previous_zero)) return roi return {RoiMetrics.ROI_SUCCESS: roi_formulae(epsilon, previous_zero_successes, current_zero_successes, current_epsilon_greedy_successes), RoiMetrics.ROI_FAILURE: roi_formulae(epsilon, previous_zero_failures, current_zero_failures, current_epsilon_greedy_failures)} roi_mean = roi_with_confidence_interval(epsilon, previous_zero_successes, previous_zero_failures, current_zero_successes, current_zero_failures, current_epsilon_greedy_successes, current_epsilon_greedy_failures)[RoiMetrics.ROI_SUCCESS] agent_stats[epsilon_key][RoiMetrics.ROI_MEAN].append(roi_mean) roi_means.append(roi_mean) steps.append(step) roi_mean_means.append(np.mean(roi_means)) ax.plot(steps, roi_means) roi_means_mean = np.mean(roi_mean_means) roi_means_div = np.sqrt(np.var(roi_mean_means)) ax.set_title(((((((('$ROI_{t+1}$ of Agent: ' + f''''{agent_key}' ''') + '$\\hat{\\mu}_{ROI}=') + '{0:.5f}'.format(round(roi_means_mean, 5))) + '$, ') + '$\\hat{\\sigma}_{ROI}=') + '{0:.5f}'.format(round(roi_means_div, 5))) + '$')) ax.legend(labels, loc=10) ax.set_ylabel('ROI') agent_roi_stats[agent_key] = agent_stats plt.subplots_adjust(hspace=0.5) plt.show() return agent_roi_stats
A helper function that calculates Return of Investment (ROI) for applying Epsilon-Greedy Selection Policy. :param agent_evolution_stats: statistic about Agent evolution collected in `build_exploration_data'. :param epsilons: a list of epsilon values. :param max_agents_per_row: how many graphs should be drawn per a row :return: a dictionary of Agent ROI after applying Epsilon-Greedy Selection Strategy in the following form: { 'Agent Name': { 'Epsilon Value': { Metrics.ROI: [an array of ROIs for each ith step (starting from 1st step)] } } }
recogym/evaluate_agent.py
plot_roi
bmazoure/reco-gym
413
python
def plot_roi(agent_evolution_stats, epsilons=EvolutionEpsilons, max_agents_per_row=2): "\n A helper function that calculates Return of Investment (ROI) for applying Epsilon-Greedy Selection Policy.\n\n :param agent_evolution_stats: statistic about Agent evolution collected in `build_exploration_data'.\n\n :param epsilons: a list of epsilon values.\n\n :param max_agents_per_row: how many graphs should be drawn per a row\n\n :return: a dictionary of Agent ROI after applying Epsilon-Greedy Selection Strategy in the following form:\n {\n 'Agent Name': {\n 'Epsilon Value': {\n Metrics.ROI: [an array of ROIs for each ith step (starting from 1st step)]\n }\n }\n }\n " (figs, axs) = plt.subplots(int((len(agent_evolution_stats) / max_agents_per_row)), max_agents_per_row, figsize=(16, 8), squeeze=False) labels = [('$\\epsilon=$' + format_epsilon(epsilon)) for epsilon in epsilons if (epsilon != 0.0)] agent_roi_stats = dict() for (ix, agent_key) in enumerate(agent_evolution_stats): ax = axs[(int((ix / max_agents_per_row)), int((ix % max_agents_per_row)))] agent_stat = agent_evolution_stats[agent_key] zero_epsilon_key = format_epsilon(0) zero_epsilon = agent_stat[zero_epsilon_key] zero_success_evolutions = zero_epsilon[EvolutionCase.SUCCESS] zero_failure_evolutions = zero_epsilon[EvolutionCase.FAILURE] assert len(zero_success_evolutions) agent_stats = dict() roi_mean_means = [] for epsilon in generate_epsilons(): if (zero_epsilon_key == format_epsilon(epsilon)): continue epsilon_key = format_epsilon(epsilon) agent_stats[epsilon_key] = {RoiMetrics.ROI_0_025: [], RoiMetrics.ROI_MEAN: [], RoiMetrics.ROI_0_975: []} epsilon_evolutions = agent_stat[epsilon_key] success_greedy_evolutions = epsilon_evolutions[EvolutionCase.SUCCESS_GREEDY] failure_greedy_evolutions = epsilon_evolutions[EvolutionCase.FAILURE_GREEDY] assert (len(success_greedy_evolutions) == len(failure_greedy_evolutions)) assert (len(zero_success_evolutions) == len(success_greedy_evolutions)) steps = [] roi_means = [] for step in range(1, len(epsilon_evolutions[EvolutionCase.SUCCESS])): previous_zero_successes = zero_success_evolutions[(step - 1)] previous_zero_failures = zero_failure_evolutions[(step - 1)] current_zero_successes = zero_success_evolutions[step] current_zero_failures = zero_failure_evolutions[step] current_epsilon_greedy_successes = success_greedy_evolutions[step] current_epsilon_greedy_failures = failure_greedy_evolutions[step] def roi_with_confidence_interval(epsilon, previous_zero_successes, previous_zero_failures, current_zero_successes, current_zero_failures, current_epsilon_greedy_successes, current_epsilon_greedy_failures): def roi_formulae(epsilon, previous_zero, current_zero, current_epsilon_greedy): current_gain = ((current_epsilon_greedy / (1 - epsilon)) - current_zero) roi = (current_gain / (epsilon * previous_zero)) return roi return {RoiMetrics.ROI_SUCCESS: roi_formulae(epsilon, previous_zero_successes, current_zero_successes, current_epsilon_greedy_successes), RoiMetrics.ROI_FAILURE: roi_formulae(epsilon, previous_zero_failures, current_zero_failures, current_epsilon_greedy_failures)} roi_mean = roi_with_confidence_interval(epsilon, previous_zero_successes, previous_zero_failures, current_zero_successes, current_zero_failures, current_epsilon_greedy_successes, current_epsilon_greedy_failures)[RoiMetrics.ROI_SUCCESS] agent_stats[epsilon_key][RoiMetrics.ROI_MEAN].append(roi_mean) roi_means.append(roi_mean) steps.append(step) roi_mean_means.append(np.mean(roi_means)) ax.plot(steps, roi_means) roi_means_mean = np.mean(roi_mean_means) roi_means_div = np.sqrt(np.var(roi_mean_means)) ax.set_title(((((((('$ROI_{t+1}$ of Agent: ' + f{agent_key}' ') + '$\\hat{\\mu}_{ROI}=') + '{0:.5f}'.format(round(roi_means_mean, 5))) + '$, ') + '$\\hat{\\sigma}_{ROI}=') + '{0:.5f}'.format(round(roi_means_div, 5))) + '$')) ax.legend(labels, loc=10) ax.set_ylabel('ROI') agent_roi_stats[agent_key] = agent_stats plt.subplots_adjust(hspace=0.5) plt.show() return agent_roi_stats
def plot_roi(agent_evolution_stats, epsilons=EvolutionEpsilons, max_agents_per_row=2): "\n A helper function that calculates Return of Investment (ROI) for applying Epsilon-Greedy Selection Policy.\n\n :param agent_evolution_stats: statistic about Agent evolution collected in `build_exploration_data'.\n\n :param epsilons: a list of epsilon values.\n\n :param max_agents_per_row: how many graphs should be drawn per a row\n\n :return: a dictionary of Agent ROI after applying Epsilon-Greedy Selection Strategy in the following form:\n {\n 'Agent Name': {\n 'Epsilon Value': {\n Metrics.ROI: [an array of ROIs for each ith step (starting from 1st step)]\n }\n }\n }\n " (figs, axs) = plt.subplots(int((len(agent_evolution_stats) / max_agents_per_row)), max_agents_per_row, figsize=(16, 8), squeeze=False) labels = [('$\\epsilon=$' + format_epsilon(epsilon)) for epsilon in epsilons if (epsilon != 0.0)] agent_roi_stats = dict() for (ix, agent_key) in enumerate(agent_evolution_stats): ax = axs[(int((ix / max_agents_per_row)), int((ix % max_agents_per_row)))] agent_stat = agent_evolution_stats[agent_key] zero_epsilon_key = format_epsilon(0) zero_epsilon = agent_stat[zero_epsilon_key] zero_success_evolutions = zero_epsilon[EvolutionCase.SUCCESS] zero_failure_evolutions = zero_epsilon[EvolutionCase.FAILURE] assert len(zero_success_evolutions) agent_stats = dict() roi_mean_means = [] for epsilon in generate_epsilons(): if (zero_epsilon_key == format_epsilon(epsilon)): continue epsilon_key = format_epsilon(epsilon) agent_stats[epsilon_key] = {RoiMetrics.ROI_0_025: [], RoiMetrics.ROI_MEAN: [], RoiMetrics.ROI_0_975: []} epsilon_evolutions = agent_stat[epsilon_key] success_greedy_evolutions = epsilon_evolutions[EvolutionCase.SUCCESS_GREEDY] failure_greedy_evolutions = epsilon_evolutions[EvolutionCase.FAILURE_GREEDY] assert (len(success_greedy_evolutions) == len(failure_greedy_evolutions)) assert (len(zero_success_evolutions) == len(success_greedy_evolutions)) steps = [] roi_means = [] for step in range(1, len(epsilon_evolutions[EvolutionCase.SUCCESS])): previous_zero_successes = zero_success_evolutions[(step - 1)] previous_zero_failures = zero_failure_evolutions[(step - 1)] current_zero_successes = zero_success_evolutions[step] current_zero_failures = zero_failure_evolutions[step] current_epsilon_greedy_successes = success_greedy_evolutions[step] current_epsilon_greedy_failures = failure_greedy_evolutions[step] def roi_with_confidence_interval(epsilon, previous_zero_successes, previous_zero_failures, current_zero_successes, current_zero_failures, current_epsilon_greedy_successes, current_epsilon_greedy_failures): def roi_formulae(epsilon, previous_zero, current_zero, current_epsilon_greedy): current_gain = ((current_epsilon_greedy / (1 - epsilon)) - current_zero) roi = (current_gain / (epsilon * previous_zero)) return roi return {RoiMetrics.ROI_SUCCESS: roi_formulae(epsilon, previous_zero_successes, current_zero_successes, current_epsilon_greedy_successes), RoiMetrics.ROI_FAILURE: roi_formulae(epsilon, previous_zero_failures, current_zero_failures, current_epsilon_greedy_failures)} roi_mean = roi_with_confidence_interval(epsilon, previous_zero_successes, previous_zero_failures, current_zero_successes, current_zero_failures, current_epsilon_greedy_successes, current_epsilon_greedy_failures)[RoiMetrics.ROI_SUCCESS] agent_stats[epsilon_key][RoiMetrics.ROI_MEAN].append(roi_mean) roi_means.append(roi_mean) steps.append(step) roi_mean_means.append(np.mean(roi_means)) ax.plot(steps, roi_means) roi_means_mean = np.mean(roi_mean_means) roi_means_div = np.sqrt(np.var(roi_mean_means)) ax.set_title(((((((('$ROI_{t+1}$ of Agent: ' + f{agent_key}' ') + '$\\hat{\\mu}_{ROI}=') + '{0:.5f}'.format(round(roi_means_mean, 5))) + '$, ') + '$\\hat{\\sigma}_{ROI}=') + '{0:.5f}'.format(round(roi_means_div, 5))) + '$')) ax.legend(labels, loc=10) ax.set_ylabel('ROI') agent_roi_stats[agent_key] = agent_stats plt.subplots_adjust(hspace=0.5) plt.show() return agent_roi_stats<|docstring|>A helper function that calculates Return of Investment (ROI) for applying Epsilon-Greedy Selection Policy. :param agent_evolution_stats: statistic about Agent evolution collected in `build_exploration_data'. :param epsilons: a list of epsilon values. :param max_agents_per_row: how many graphs should be drawn per a row :return: a dictionary of Agent ROI after applying Epsilon-Greedy Selection Strategy in the following form: { 'Agent Name': { 'Epsilon Value': { Metrics.ROI: [an array of ROIs for each ith step (starting from 1st step)] } } }<|endoftext|>
e4eb68f65aca3f2e7cf38b371ac9cb0d60201979f6b4569a3e31f44a97a7d84d
def useCRT(self): 'Solve the puzzle using the Chineese Remainder Theorem' adjusted = [] for (offset, position) in enumerate(self.positions): adjusted.append(((- position) - offset)) result = crt.chinese_remainder(self.sizes, adjusted) if (result == 0): return None return (result - 1)
Solve the puzzle using the Chineese Remainder Theorem
2016/15_TimingisEverything/discs.py
useCRT
deanearlwright/AdventOfCode
1
python
def useCRT(self): adjusted = [] for (offset, position) in enumerate(self.positions): adjusted.append(((- position) - offset)) result = crt.chinese_remainder(self.sizes, adjusted) if (result == 0): return None return (result - 1)
def useCRT(self): adjusted = [] for (offset, position) in enumerate(self.positions): adjusted.append(((- position) - offset)) result = crt.chinese_remainder(self.sizes, adjusted) if (result == 0): return None return (result - 1)<|docstring|>Solve the puzzle using the Chineese Remainder Theorem<|endoftext|>
0bde42499df2109364c85f124a42779881cad8daab0e1f5ea3d0c264a44e3f43
def part_one(self, verbose=False, limit=0): 'Returns the solution for part one' assert (verbose in [True, False]) assert (limit >= 0) return self.useCRT()
Returns the solution for part one
2016/15_TimingisEverything/discs.py
part_one
deanearlwright/AdventOfCode
1
python
def part_one(self, verbose=False, limit=0): assert (verbose in [True, False]) assert (limit >= 0) return self.useCRT()
def part_one(self, verbose=False, limit=0): assert (verbose in [True, False]) assert (limit >= 0) return self.useCRT()<|docstring|>Returns the solution for part one<|endoftext|>
7a83ec33ed8fc5dba2164a3b7c14ef1775889d4cf3c41661074dc2ae6890d6de
def part_two(self, verbose=False, limit=0): 'Returns the solution for part two' assert (verbose in [True, False]) assert (limit >= 0) return self.useCRT()
Returns the solution for part two
2016/15_TimingisEverything/discs.py
part_two
deanearlwright/AdventOfCode
1
python
def part_two(self, verbose=False, limit=0): assert (verbose in [True, False]) assert (limit >= 0) return self.useCRT()
def part_two(self, verbose=False, limit=0): assert (verbose in [True, False]) assert (limit >= 0) return self.useCRT()<|docstring|>Returns the solution for part two<|endoftext|>
fe71f589aebaf358ab25c9bfdf47f245d77d32ecb5770de38b69f2ed85a4d750
def object_to_binarized_sub_objects(image): 'Takes an image of a character and splits into discontinuous sub-strokes.\n\n Sub strokes are returned as binary images each of the same dimensions as the\n original image.\n\n Args:\n image:\n\n Returns:\n List of images.\n ' binary_threshold = 50 (_, bw_image) = cv2.threshold(image, binary_threshold, 255, 0) contour_image = copy.deepcopy(bw_image) (contours, _) = cv2.findContours(contour_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) masks = [] for i in range(0, len(contours)): (x, y, w, h) = cv2.boundingRect(contours[i]) mask = np.zeros(bw_image.shape, np.uint8) mask[(y:(y + h), x:(x + w))] = bw_image[(y:(y + h), x:(x + w))] masks.append(mask) return masks
Takes an image of a character and splits into discontinuous sub-strokes. Sub strokes are returned as binary images each of the same dimensions as the original image. Args: image: Returns: List of images.
video_processing/processors/stroke_tracker.py
object_to_binarized_sub_objects
learningequality/video-vectorization
22
python
def object_to_binarized_sub_objects(image): 'Takes an image of a character and splits into discontinuous sub-strokes.\n\n Sub strokes are returned as binary images each of the same dimensions as the\n original image.\n\n Args:\n image:\n\n Returns:\n List of images.\n ' binary_threshold = 50 (_, bw_image) = cv2.threshold(image, binary_threshold, 255, 0) contour_image = copy.deepcopy(bw_image) (contours, _) = cv2.findContours(contour_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) masks = [] for i in range(0, len(contours)): (x, y, w, h) = cv2.boundingRect(contours[i]) mask = np.zeros(bw_image.shape, np.uint8) mask[(y:(y + h), x:(x + w))] = bw_image[(y:(y + h), x:(x + w))] masks.append(mask) return masks
def object_to_binarized_sub_objects(image): 'Takes an image of a character and splits into discontinuous sub-strokes.\n\n Sub strokes are returned as binary images each of the same dimensions as the\n original image.\n\n Args:\n image:\n\n Returns:\n List of images.\n ' binary_threshold = 50 (_, bw_image) = cv2.threshold(image, binary_threshold, 255, 0) contour_image = copy.deepcopy(bw_image) (contours, _) = cv2.findContours(contour_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) masks = [] for i in range(0, len(contours)): (x, y, w, h) = cv2.boundingRect(contours[i]) mask = np.zeros(bw_image.shape, np.uint8) mask[(y:(y + h), x:(x + w))] = bw_image[(y:(y + h), x:(x + w))] masks.append(mask) return masks<|docstring|>Takes an image of a character and splits into discontinuous sub-strokes. Sub strokes are returned as binary images each of the same dimensions as the original image. Args: image: Returns: List of images.<|endoftext|>
396c7a247800a95134eb47d5a39b20033a4854c2d3810d098435d828c36adf45
def thinning_iteration(image, iteration): 'One iteration of the thinning function.' image = image.astype(np.uint8) mask = np.zeros(image.shape, np.uint8) for i in range(1, (image.shape[0] - 1)): for j in range(1, (image.shape[1] - 1)): p2 = image[(i - 1)][j] p3 = image[(i - 1)][(j + 1)] p4 = image[i][(j + 1)] p5 = image[(i + 1)][(j + 1)] p6 = image[(i + 1)][j] p7 = image[(i + 1)][(j - 1)] p8 = image[i][(j - 1)] p9 = image[(i - 1)][(j - 1)] adjacent = (((((((int(((p2 == 0) and (p3 > 0))) + int(((p3 == 0) and (p4 > 0)))) + int(((p4 == 0) and (p5 > 0)))) + int(((p5 == 0) and (p6 > 0)))) + int(((p6 == 0) and (p7 > 0)))) + int(((p7 == 0) and (p8 > 0)))) + int(((p8 == 0) and (p9 > 0)))) + int(((p9 == 0) and (p2 > 0)))) total = (((((((p2 + p3) + p4) + p5) + p6) + p7) + p8) + p9) m1 = (((p2 * p4) * p6) if (iteration == 0) else ((p2 * p4) * p8)) m2 = (((p4 * p6) * p8) if (iteration == 0) else ((p2 * p6) * p8)) if ((adjacent == 1) and (total >= 2) and (total <= 6) and (m1 == 0) and (m2 == 0)): mask[i][j] = 1 return (image & (~ mask))
One iteration of the thinning function.
video_processing/processors/stroke_tracker.py
thinning_iteration
learningequality/video-vectorization
22
python
def thinning_iteration(image, iteration): image = image.astype(np.uint8) mask = np.zeros(image.shape, np.uint8) for i in range(1, (image.shape[0] - 1)): for j in range(1, (image.shape[1] - 1)): p2 = image[(i - 1)][j] p3 = image[(i - 1)][(j + 1)] p4 = image[i][(j + 1)] p5 = image[(i + 1)][(j + 1)] p6 = image[(i + 1)][j] p7 = image[(i + 1)][(j - 1)] p8 = image[i][(j - 1)] p9 = image[(i - 1)][(j - 1)] adjacent = (((((((int(((p2 == 0) and (p3 > 0))) + int(((p3 == 0) and (p4 > 0)))) + int(((p4 == 0) and (p5 > 0)))) + int(((p5 == 0) and (p6 > 0)))) + int(((p6 == 0) and (p7 > 0)))) + int(((p7 == 0) and (p8 > 0)))) + int(((p8 == 0) and (p9 > 0)))) + int(((p9 == 0) and (p2 > 0)))) total = (((((((p2 + p3) + p4) + p5) + p6) + p7) + p8) + p9) m1 = (((p2 * p4) * p6) if (iteration == 0) else ((p2 * p4) * p8)) m2 = (((p4 * p6) * p8) if (iteration == 0) else ((p2 * p6) * p8)) if ((adjacent == 1) and (total >= 2) and (total <= 6) and (m1 == 0) and (m2 == 0)): mask[i][j] = 1 return (image & (~ mask))
def thinning_iteration(image, iteration): image = image.astype(np.uint8) mask = np.zeros(image.shape, np.uint8) for i in range(1, (image.shape[0] - 1)): for j in range(1, (image.shape[1] - 1)): p2 = image[(i - 1)][j] p3 = image[(i - 1)][(j + 1)] p4 = image[i][(j + 1)] p5 = image[(i + 1)][(j + 1)] p6 = image[(i + 1)][j] p7 = image[(i + 1)][(j - 1)] p8 = image[i][(j - 1)] p9 = image[(i - 1)][(j - 1)] adjacent = (((((((int(((p2 == 0) and (p3 > 0))) + int(((p3 == 0) and (p4 > 0)))) + int(((p4 == 0) and (p5 > 0)))) + int(((p5 == 0) and (p6 > 0)))) + int(((p6 == 0) and (p7 > 0)))) + int(((p7 == 0) and (p8 > 0)))) + int(((p8 == 0) and (p9 > 0)))) + int(((p9 == 0) and (p2 > 0)))) total = (((((((p2 + p3) + p4) + p5) + p6) + p7) + p8) + p9) m1 = (((p2 * p4) * p6) if (iteration == 0) else ((p2 * p4) * p8)) m2 = (((p4 * p6) * p8) if (iteration == 0) else ((p2 * p6) * p8)) if ((adjacent == 1) and (total >= 2) and (total <= 6) and (m1 == 0) and (m2 == 0)): mask[i][j] = 1 return (image & (~ mask))<|docstring|>One iteration of the thinning function.<|endoftext|>
eec9c2b8f8aff9de34b93df9346a9a46ca04172a579e93f8062947458337e4ac
def thin(src): 'Thin elemets in src.' kernel = np.ones((3, 3), np.uint8) closing = cv2.morphologyEx(src, cv2.MORPH_CLOSE, kernel) opening = cv2.morphologyEx(closing, cv2.MORPH_CLOSE, kernel) dst = (opening.copy() / 255) prev = np.zeros(src.shape[:2], np.uint8) while True: dst = thinning_iteration(dst, 0) dst = thinning_iteration(dst, 1) diff = np.absolute((dst - prev)) prev = dst.copy() if (np.sum(diff) == 0): break return (dst * 255)
Thin elemets in src.
video_processing/processors/stroke_tracker.py
thin
learningequality/video-vectorization
22
python
def thin(src): kernel = np.ones((3, 3), np.uint8) closing = cv2.morphologyEx(src, cv2.MORPH_CLOSE, kernel) opening = cv2.morphologyEx(closing, cv2.MORPH_CLOSE, kernel) dst = (opening.copy() / 255) prev = np.zeros(src.shape[:2], np.uint8) while True: dst = thinning_iteration(dst, 0) dst = thinning_iteration(dst, 1) diff = np.absolute((dst - prev)) prev = dst.copy() if (np.sum(diff) == 0): break return (dst * 255)
def thin(src): kernel = np.ones((3, 3), np.uint8) closing = cv2.morphologyEx(src, cv2.MORPH_CLOSE, kernel) opening = cv2.morphologyEx(closing, cv2.MORPH_CLOSE, kernel) dst = (opening.copy() / 255) prev = np.zeros(src.shape[:2], np.uint8) while True: dst = thinning_iteration(dst, 0) dst = thinning_iteration(dst, 1) diff = np.absolute((dst - prev)) prev = dst.copy() if (np.sum(diff) == 0): break return (dst * 255)<|docstring|>Thin elemets in src.<|endoftext|>
d9f20a1341564c06877badd2505b76ea46487ddd20a23b9842fbfacaeec62ccd
def points_list_from_sub_image(binary_sub_image): 'Returns a list of (x, y) coordinates of lit pixels in the thinned image.' thinned_img = thin(binary_sub_image) data_pts_thinned = np.nonzero(thinned_img) data_pts_thinned = list(zip(data_pts_thinned[1], data_pts_thinned[0])) return data_pts_thinned
Returns a list of (x, y) coordinates of lit pixels in the thinned image.
video_processing/processors/stroke_tracker.py
points_list_from_sub_image
learningequality/video-vectorization
22
python
def points_list_from_sub_image(binary_sub_image): thinned_img = thin(binary_sub_image) data_pts_thinned = np.nonzero(thinned_img) data_pts_thinned = list(zip(data_pts_thinned[1], data_pts_thinned[0])) return data_pts_thinned
def points_list_from_sub_image(binary_sub_image): thinned_img = thin(binary_sub_image) data_pts_thinned = np.nonzero(thinned_img) data_pts_thinned = list(zip(data_pts_thinned[1], data_pts_thinned[0])) return data_pts_thinned<|docstring|>Returns a list of (x, y) coordinates of lit pixels in the thinned image.<|endoftext|>
b8e0d90863f684c95ec4d8b256a08419b78453e8e801a54c11730ad32e2771af
def find_candidate_pen_locations(cursor_track, stroke_points_list, binary_stroke_image): 'Args:\n\n cursor_track: Tracked cursor location (relative to the stroke image).\n stroke_points_list: List of points in the relevant stroke (relative to the\n stroke image).\n binary_stroke_image: Binarized image of the stroke.\n ' valid_cursor_positions = [] if (not stroke_points_list): return valid_cursor_positions last_x = (- 1000) last_y = (- 1000) for i in range(0, len(cursor_track)): x = int(cursor_track[i][0]) y = int(cursor_track[i][1]) dim = binary_stroke_image.shape[1::(- 1)] if ((0 <= x < dim[0]) and (0 <= y < dim[1])): if ((abs((x - last_x)) + abs((y - last_y))) > 3): [mapped_x, mapped_y] = find_closest_point([x, y], stroke_points_list) valid_cursor_positions.append((mapped_x, mapped_y)) last_x = x last_y = y return valid_cursor_positions
Args: cursor_track: Tracked cursor location (relative to the stroke image). stroke_points_list: List of points in the relevant stroke (relative to the stroke image). binary_stroke_image: Binarized image of the stroke.
video_processing/processors/stroke_tracker.py
find_candidate_pen_locations
learningequality/video-vectorization
22
python
def find_candidate_pen_locations(cursor_track, stroke_points_list, binary_stroke_image): 'Args:\n\n cursor_track: Tracked cursor location (relative to the stroke image).\n stroke_points_list: List of points in the relevant stroke (relative to the\n stroke image).\n binary_stroke_image: Binarized image of the stroke.\n ' valid_cursor_positions = [] if (not stroke_points_list): return valid_cursor_positions last_x = (- 1000) last_y = (- 1000) for i in range(0, len(cursor_track)): x = int(cursor_track[i][0]) y = int(cursor_track[i][1]) dim = binary_stroke_image.shape[1::(- 1)] if ((0 <= x < dim[0]) and (0 <= y < dim[1])): if ((abs((x - last_x)) + abs((y - last_y))) > 3): [mapped_x, mapped_y] = find_closest_point([x, y], stroke_points_list) valid_cursor_positions.append((mapped_x, mapped_y)) last_x = x last_y = y return valid_cursor_positions
def find_candidate_pen_locations(cursor_track, stroke_points_list, binary_stroke_image): 'Args:\n\n cursor_track: Tracked cursor location (relative to the stroke image).\n stroke_points_list: List of points in the relevant stroke (relative to the\n stroke image).\n binary_stroke_image: Binarized image of the stroke.\n ' valid_cursor_positions = [] if (not stroke_points_list): return valid_cursor_positions last_x = (- 1000) last_y = (- 1000) for i in range(0, len(cursor_track)): x = int(cursor_track[i][0]) y = int(cursor_track[i][1]) dim = binary_stroke_image.shape[1::(- 1)] if ((0 <= x < dim[0]) and (0 <= y < dim[1])): if ((abs((x - last_x)) + abs((y - last_y))) > 3): [mapped_x, mapped_y] = find_closest_point([x, y], stroke_points_list) valid_cursor_positions.append((mapped_x, mapped_y)) last_x = x last_y = y return valid_cursor_positions<|docstring|>Args: cursor_track: Tracked cursor location (relative to the stroke image). stroke_points_list: List of points in the relevant stroke (relative to the stroke image). binary_stroke_image: Binarized image of the stroke.<|endoftext|>
9274e1dcf678ee2fb663474e4aebd207c878c1927cb88c848eddcd072c37097e
def compute_all_edges(data_pts): 'Compute all edges.' graph_connections = [] for current in range(0, len(data_pts)): adjacent = [data_pts.index(x) for x in data_pts if ((abs((x[0] - data_pts[current][0])) < 2) and (abs((x[1] - data_pts[current][1])) < 2) and ((x[0] != data_pts[current][0]) or (x[1] != data_pts[current][1])))] for a in adjacent: graph_connections.append((current, a)) list_with_duplicates = sorted([sorted(x) for x in graph_connections]) result = list((list_with_duplicates for (list_with_duplicates, _) in itertools.groupby(list_with_duplicates))) return result
Compute all edges.
video_processing/processors/stroke_tracker.py
compute_all_edges
learningequality/video-vectorization
22
python
def compute_all_edges(data_pts): graph_connections = [] for current in range(0, len(data_pts)): adjacent = [data_pts.index(x) for x in data_pts if ((abs((x[0] - data_pts[current][0])) < 2) and (abs((x[1] - data_pts[current][1])) < 2) and ((x[0] != data_pts[current][0]) or (x[1] != data_pts[current][1])))] for a in adjacent: graph_connections.append((current, a)) list_with_duplicates = sorted([sorted(x) for x in graph_connections]) result = list((list_with_duplicates for (list_with_duplicates, _) in itertools.groupby(list_with_duplicates))) return result
def compute_all_edges(data_pts): graph_connections = [] for current in range(0, len(data_pts)): adjacent = [data_pts.index(x) for x in data_pts if ((abs((x[0] - data_pts[current][0])) < 2) and (abs((x[1] - data_pts[current][1])) < 2) and ((x[0] != data_pts[current][0]) or (x[1] != data_pts[current][1])))] for a in adjacent: graph_connections.append((current, a)) list_with_duplicates = sorted([sorted(x) for x in graph_connections]) result = list((list_with_duplicates for (list_with_duplicates, _) in itertools.groupby(list_with_duplicates))) return result<|docstring|>Compute all edges.<|endoftext|>
d3b1702abaf8580639ba90c239def8f1e3b2cb890147cc97a14a6c3b98bd9e6f
def inherit_params(self, params): '\n Adopts the current screen parameters (to preserve zoom level, offset,\n etc.), but only if the image dimensions are the same.\n ' if ((self.img_w != params.img_w) or (self.img_h != params.img_h)): return self.img_x_offset = params.img_x_offset self.img_y_offset = params.img_y_offset self.screen_x_start = params.screen_x_start self.screen_y_start = params.screen_y_start self.last_thumb_x = params.last_thumb_x self.last_thumb_y = params.last_thumb_y self.zoom = params.zoom
Adopts the current screen parameters (to preserve zoom level, offset, etc.), but only if the image dimensions are the same.
rstbx/viewer/__init__.py
inherit_params
dwpaley/cctbx_project
155
python
def inherit_params(self, params): '\n Adopts the current screen parameters (to preserve zoom level, offset,\n etc.), but only if the image dimensions are the same.\n ' if ((self.img_w != params.img_w) or (self.img_h != params.img_h)): return self.img_x_offset = params.img_x_offset self.img_y_offset = params.img_y_offset self.screen_x_start = params.screen_x_start self.screen_y_start = params.screen_y_start self.last_thumb_x = params.last_thumb_x self.last_thumb_y = params.last_thumb_y self.zoom = params.zoom
def inherit_params(self, params): '\n Adopts the current screen parameters (to preserve zoom level, offset,\n etc.), but only if the image dimensions are the same.\n ' if ((self.img_w != params.img_w) or (self.img_h != params.img_h)): return self.img_x_offset = params.img_x_offset self.img_y_offset = params.img_y_offset self.screen_x_start = params.screen_x_start self.screen_y_start = params.screen_y_start self.last_thumb_x = params.last_thumb_x self.last_thumb_y = params.last_thumb_y self.zoom = params.zoom<|docstring|>Adopts the current screen parameters (to preserve zoom level, offset, etc.), but only if the image dimensions are the same.<|endoftext|>
07058b24fdac32e6b2a8275864bb2f6795400a70f66c116d7f4ff38fc761a971
def translate_image(self, delta_x, delta_y): '\n Translate the viewport to a different area of the image. Arguments are\n in pixels.\n ' scale = self.get_scale() x_new = max(0, ifloor((self.img_x_offset - (delta_x / scale)))) y_new = max(0, ifloor((self.img_y_offset - (delta_y / scale)))) max_x = ifloor((self.img_w - (self.screen_w / scale))) max_y = ifloor((self.img_h - (self.screen_h / scale))) self.img_x_offset = min(x_new, max_x) self.img_y_offset = min(y_new, max_y)
Translate the viewport to a different area of the image. Arguments are in pixels.
rstbx/viewer/__init__.py
translate_image
dwpaley/cctbx_project
155
python
def translate_image(self, delta_x, delta_y): '\n Translate the viewport to a different area of the image. Arguments are\n in pixels.\n ' scale = self.get_scale() x_new = max(0, ifloor((self.img_x_offset - (delta_x / scale)))) y_new = max(0, ifloor((self.img_y_offset - (delta_y / scale)))) max_x = ifloor((self.img_w - (self.screen_w / scale))) max_y = ifloor((self.img_h - (self.screen_h / scale))) self.img_x_offset = min(x_new, max_x) self.img_y_offset = min(y_new, max_y)
def translate_image(self, delta_x, delta_y): '\n Translate the viewport to a different area of the image. Arguments are\n in pixels.\n ' scale = self.get_scale() x_new = max(0, ifloor((self.img_x_offset - (delta_x / scale)))) y_new = max(0, ifloor((self.img_y_offset - (delta_y / scale)))) max_x = ifloor((self.img_w - (self.screen_w / scale))) max_y = ifloor((self.img_h - (self.screen_h / scale))) self.img_x_offset = min(x_new, max_x) self.img_y_offset = min(y_new, max_y)<|docstring|>Translate the viewport to a different area of the image. Arguments are in pixels.<|endoftext|>
1bdefe3524d76e7d24c85339e8cea4e5adb2ce11fafde11ece0f8237f68d7794
def center_view_from_thumbnail(self, x, y): '\n Translate the viewport to center on the X,Y coordinates equivalent to the\n point clicked in the thumbnail view. Arguments are in screen coordinates\n relative to the upper left corner of the thumbnail (which is assumed to be\n displayed in its entirety).\n ' if (self.zoom == 0): return self.last_thumb_x = x self.last_thumb_y = y (x0, y0, w, h) = self.get_bitmap_params() img_x = max(0, ifloor(((x * self.thumb_ratio) - (w / 2)))) img_y = max(0, ifloor(((y * self.thumb_ratio) - (h / 2)))) scale = self.get_scale() max_x = ifloor((self.img_w - (self.screen_w / scale))) max_y = ifloor((self.img_h - (self.screen_h / scale))) self.img_x_offset = min(img_x, max_x) self.img_y_offset = min(img_y, max_y)
Translate the viewport to center on the X,Y coordinates equivalent to the point clicked in the thumbnail view. Arguments are in screen coordinates relative to the upper left corner of the thumbnail (which is assumed to be displayed in its entirety).
rstbx/viewer/__init__.py
center_view_from_thumbnail
dwpaley/cctbx_project
155
python
def center_view_from_thumbnail(self, x, y): '\n Translate the viewport to center on the X,Y coordinates equivalent to the\n point clicked in the thumbnail view. Arguments are in screen coordinates\n relative to the upper left corner of the thumbnail (which is assumed to be\n displayed in its entirety).\n ' if (self.zoom == 0): return self.last_thumb_x = x self.last_thumb_y = y (x0, y0, w, h) = self.get_bitmap_params() img_x = max(0, ifloor(((x * self.thumb_ratio) - (w / 2)))) img_y = max(0, ifloor(((y * self.thumb_ratio) - (h / 2)))) scale = self.get_scale() max_x = ifloor((self.img_w - (self.screen_w / scale))) max_y = ifloor((self.img_h - (self.screen_h / scale))) self.img_x_offset = min(img_x, max_x) self.img_y_offset = min(img_y, max_y)
def center_view_from_thumbnail(self, x, y): '\n Translate the viewport to center on the X,Y coordinates equivalent to the\n point clicked in the thumbnail view. Arguments are in screen coordinates\n relative to the upper left corner of the thumbnail (which is assumed to be\n displayed in its entirety).\n ' if (self.zoom == 0): return self.last_thumb_x = x self.last_thumb_y = y (x0, y0, w, h) = self.get_bitmap_params() img_x = max(0, ifloor(((x * self.thumb_ratio) - (w / 2)))) img_y = max(0, ifloor(((y * self.thumb_ratio) - (h / 2)))) scale = self.get_scale() max_x = ifloor((self.img_w - (self.screen_w / scale))) max_y = ifloor((self.img_h - (self.screen_h / scale))) self.img_x_offset = min(img_x, max_x) self.img_y_offset = min(img_y, max_y)<|docstring|>Translate the viewport to center on the X,Y coordinates equivalent to the point clicked in the thumbnail view. Arguments are in screen coordinates relative to the upper left corner of the thumbnail (which is assumed to be displayed in its entirety).<|endoftext|>
145ebd464963c733afdfbc28f4cd245201195ea4201a37758404916729d31a04
def image_coords_as_screen_coords(self, x, y): '\n Convert image pixel coordinates to viewport pixel coordinates.\n ' scale = self.get_scale() x1 = (self.screen_x_start + (((x + 0.5) - self.img_x_offset) * scale)) y1 = (self.screen_y_start + (((y + 0.5) - self.img_y_offset) * scale)) (xi, yi, w, h) = self.get_bitmap_params() x2 = (x1 + max(0, ((self.screen_w - (w * scale)) / 2))) y2 = (y1 + max(0, ((self.screen_h - (h * scale)) / 2))) return (x2, y2)
Convert image pixel coordinates to viewport pixel coordinates.
rstbx/viewer/__init__.py
image_coords_as_screen_coords
dwpaley/cctbx_project
155
python
def image_coords_as_screen_coords(self, x, y): '\n \n ' scale = self.get_scale() x1 = (self.screen_x_start + (((x + 0.5) - self.img_x_offset) * scale)) y1 = (self.screen_y_start + (((y + 0.5) - self.img_y_offset) * scale)) (xi, yi, w, h) = self.get_bitmap_params() x2 = (x1 + max(0, ((self.screen_w - (w * scale)) / 2))) y2 = (y1 + max(0, ((self.screen_h - (h * scale)) / 2))) return (x2, y2)
def image_coords_as_screen_coords(self, x, y): '\n \n ' scale = self.get_scale() x1 = (self.screen_x_start + (((x + 0.5) - self.img_x_offset) * scale)) y1 = (self.screen_y_start + (((y + 0.5) - self.img_y_offset) * scale)) (xi, yi, w, h) = self.get_bitmap_params() x2 = (x1 + max(0, ((self.screen_w - (w * scale)) / 2))) y2 = (y1 + max(0, ((self.screen_h - (h * scale)) / 2))) return (x2, y2)<|docstring|>Convert image pixel coordinates to viewport pixel coordinates.<|endoftext|>
d8877c55ada0eb3317addf99e1b76fe0e6f3d488e7a334af1725c6bc408d0280
def screen_coords_as_image_coords(self, x, y): '\n Convert pixel coordinates in the viewport to pixel coordinates in the\n raw image.\n ' scale = self.get_scale() (xi, yi, w, h) = self.get_bitmap_params() x1 = (x - max(0, ((self.screen_w - (w * scale)) / 2))) y1 = (y - max(0, ((self.screen_h - (h * scale)) / 2))) x2 = (self.img_x_offset + (x1 / scale)) y2 = (self.img_y_offset + (y1 / scale)) return ((ifloor(x2) + 1), (ifloor(y2) + 1))
Convert pixel coordinates in the viewport to pixel coordinates in the raw image.
rstbx/viewer/__init__.py
screen_coords_as_image_coords
dwpaley/cctbx_project
155
python
def screen_coords_as_image_coords(self, x, y): '\n Convert pixel coordinates in the viewport to pixel coordinates in the\n raw image.\n ' scale = self.get_scale() (xi, yi, w, h) = self.get_bitmap_params() x1 = (x - max(0, ((self.screen_w - (w * scale)) / 2))) y1 = (y - max(0, ((self.screen_h - (h * scale)) / 2))) x2 = (self.img_x_offset + (x1 / scale)) y2 = (self.img_y_offset + (y1 / scale)) return ((ifloor(x2) + 1), (ifloor(y2) + 1))
def screen_coords_as_image_coords(self, x, y): '\n Convert pixel coordinates in the viewport to pixel coordinates in the\n raw image.\n ' scale = self.get_scale() (xi, yi, w, h) = self.get_bitmap_params() x1 = (x - max(0, ((self.screen_w - (w * scale)) / 2))) y1 = (y - max(0, ((self.screen_h - (h * scale)) / 2))) x2 = (self.img_x_offset + (x1 / scale)) y2 = (self.img_y_offset + (y1 / scale)) return ((ifloor(x2) + 1), (ifloor(y2) + 1))<|docstring|>Convert pixel coordinates in the viewport to pixel coordinates in the raw image.<|endoftext|>
2a8b813896717b61908d547d94390148f639934072e98430603a59392f390e30
def image_coords_as_array_coords(self, x, y): '\n Convert image pixel coordinates to indexing values in the FlexImage\n object.\n ' return ((y - 1), (x - 1))
Convert image pixel coordinates to indexing values in the FlexImage object.
rstbx/viewer/__init__.py
image_coords_as_array_coords
dwpaley/cctbx_project
155
python
def image_coords_as_array_coords(self, x, y): '\n Convert image pixel coordinates to indexing values in the FlexImage\n object.\n ' return ((y - 1), (x - 1))
def image_coords_as_array_coords(self, x, y): '\n Convert image pixel coordinates to indexing values in the FlexImage\n object.\n ' return ((y - 1), (x - 1))<|docstring|>Convert image pixel coordinates to indexing values in the FlexImage object.<|endoftext|>
25ed14e5ca480be3d65c88add8194db5902a57f9e236de21c14b37fd61691bb1
def array_coords_as_detector_coords(self, x, y): '\n Convert array indices to points on the detector surface. Used in the\n calculation of approximate lattice dimensions based on peaks in a\n user-drawn line in the viewer.\n ' (x_, y_) = ((y + 1), (x + 1)) return self._raw.image_coords_as_detector_coords(x_, y_)
Convert array indices to points on the detector surface. Used in the calculation of approximate lattice dimensions based on peaks in a user-drawn line in the viewer.
rstbx/viewer/__init__.py
array_coords_as_detector_coords
dwpaley/cctbx_project
155
python
def array_coords_as_detector_coords(self, x, y): '\n Convert array indices to points on the detector surface. Used in the\n calculation of approximate lattice dimensions based on peaks in a\n user-drawn line in the viewer.\n ' (x_, y_) = ((y + 1), (x + 1)) return self._raw.image_coords_as_detector_coords(x_, y_)
def array_coords_as_detector_coords(self, x, y): '\n Convert array indices to points on the detector surface. Used in the\n calculation of approximate lattice dimensions based on peaks in a\n user-drawn line in the viewer.\n ' (x_, y_) = ((y + 1), (x + 1)) return self._raw.image_coords_as_detector_coords(x_, y_)<|docstring|>Convert array indices to points on the detector surface. Used in the calculation of approximate lattice dimensions based on peaks in a user-drawn line in the viewer.<|endoftext|>
ff472022259bdc043626a432d404264d090e68c4cd9d410d11990a97573417e1
def distance_between_points(self, x1, y1, x2, y2): '\n Given a pair of image pixel coordinates, calculate the distance between\n them on the detector face in mm.\n ' (x1_mm, y1_mm) = self._raw.image_coords_as_detector_coords(x1, y1) (x2_mm, y2_mm) = self._raw.image_coords_as_detector_coords(x2, y2) return math.sqrt((((x1_mm - x2_mm) ** 2) + ((y1_mm - y2_mm) ** 2)))
Given a pair of image pixel coordinates, calculate the distance between them on the detector face in mm.
rstbx/viewer/__init__.py
distance_between_points
dwpaley/cctbx_project
155
python
def distance_between_points(self, x1, y1, x2, y2): '\n Given a pair of image pixel coordinates, calculate the distance between\n them on the detector face in mm.\n ' (x1_mm, y1_mm) = self._raw.image_coords_as_detector_coords(x1, y1) (x2_mm, y2_mm) = self._raw.image_coords_as_detector_coords(x2, y2) return math.sqrt((((x1_mm - x2_mm) ** 2) + ((y1_mm - y2_mm) ** 2)))
def distance_between_points(self, x1, y1, x2, y2): '\n Given a pair of image pixel coordinates, calculate the distance between\n them on the detector face in mm.\n ' (x1_mm, y1_mm) = self._raw.image_coords_as_detector_coords(x1, y1) (x2_mm, y2_mm) = self._raw.image_coords_as_detector_coords(x2, y2) return math.sqrt((((x1_mm - x2_mm) ** 2) + ((y1_mm - y2_mm) ** 2)))<|docstring|>Given a pair of image pixel coordinates, calculate the distance between them on the detector face in mm.<|endoftext|>
a9ec235b2c4442f11e1f3329d5efbca3d18992acd23ecfa441d1ebb1e9373d51
def update_image(self, brightness=100, color_scheme=0): '\n Re-process the image to adjust brightness and colors, and generate a new\n wx.Image object and corresponding thumbnail image.\n ' import wx self._color_scheme = color_scheme self._img = self.create_flex_image(brightness=brightness, color_scheme=color_scheme) w = self._img.ex_size2() h = self._img.ex_size1() self.set_image_size(w, h) wx_image = wx.EmptyImage(w, h) wx_image.SetData(self._img.export_string) self._wx_img = wx_image binning = 8 if (w > 2560): binning = 16 fi_thumb = self.create_flex_image(brightness=brightness, color_scheme=color_scheme, binning=binning) w = fi_thumb.ex_size2() h = fi_thumb.ex_size1() wx_thumb = wx.EmptyImage(w, h) wx_thumb.SetData(fi_thumb.export_string) self.set_thumbnail_size(w, h, binning) self._wx_thumb = wx_thumb self._wx_thumb_bmp = wx_thumb.ConvertToBitmap()
Re-process the image to adjust brightness and colors, and generate a new wx.Image object and corresponding thumbnail image.
rstbx/viewer/__init__.py
update_image
dwpaley/cctbx_project
155
python
def update_image(self, brightness=100, color_scheme=0): '\n Re-process the image to adjust brightness and colors, and generate a new\n wx.Image object and corresponding thumbnail image.\n ' import wx self._color_scheme = color_scheme self._img = self.create_flex_image(brightness=brightness, color_scheme=color_scheme) w = self._img.ex_size2() h = self._img.ex_size1() self.set_image_size(w, h) wx_image = wx.EmptyImage(w, h) wx_image.SetData(self._img.export_string) self._wx_img = wx_image binning = 8 if (w > 2560): binning = 16 fi_thumb = self.create_flex_image(brightness=brightness, color_scheme=color_scheme, binning=binning) w = fi_thumb.ex_size2() h = fi_thumb.ex_size1() wx_thumb = wx.EmptyImage(w, h) wx_thumb.SetData(fi_thumb.export_string) self.set_thumbnail_size(w, h, binning) self._wx_thumb = wx_thumb self._wx_thumb_bmp = wx_thumb.ConvertToBitmap()
def update_image(self, brightness=100, color_scheme=0): '\n Re-process the image to adjust brightness and colors, and generate a new\n wx.Image object and corresponding thumbnail image.\n ' import wx self._color_scheme = color_scheme self._img = self.create_flex_image(brightness=brightness, color_scheme=color_scheme) w = self._img.ex_size2() h = self._img.ex_size1() self.set_image_size(w, h) wx_image = wx.EmptyImage(w, h) wx_image.SetData(self._img.export_string) self._wx_img = wx_image binning = 8 if (w > 2560): binning = 16 fi_thumb = self.create_flex_image(brightness=brightness, color_scheme=color_scheme, binning=binning) w = fi_thumb.ex_size2() h = fi_thumb.ex_size1() wx_thumb = wx.EmptyImage(w, h) wx_thumb.SetData(fi_thumb.export_string) self.set_thumbnail_size(w, h, binning) self._wx_thumb = wx_thumb self._wx_thumb_bmp = wx_thumb.ConvertToBitmap()<|docstring|>Re-process the image to adjust brightness and colors, and generate a new wx.Image object and corresponding thumbnail image.<|endoftext|>
b7c1df7f470990a24f4d3699f8b75e368bdfbb5aad1c883bdf567e80814888e9
def get_bitmap(self): '\n Returns the primary wx.Image scaled and clipped to the current screen\n parameters for display in the main canvas.\n ' import wx (x, y, w, h) = self.get_bitmap_params() scale = self.get_scale() img = self._wx_img.GetSubImage((x, y, w, h)) img = img.Scale((w * scale), (h * scale), wx.IMAGE_QUALITY_NORMAL) return img.ConvertToBitmap()
Returns the primary wx.Image scaled and clipped to the current screen parameters for display in the main canvas.
rstbx/viewer/__init__.py
get_bitmap
dwpaley/cctbx_project
155
python
def get_bitmap(self): '\n Returns the primary wx.Image scaled and clipped to the current screen\n parameters for display in the main canvas.\n ' import wx (x, y, w, h) = self.get_bitmap_params() scale = self.get_scale() img = self._wx_img.GetSubImage((x, y, w, h)) img = img.Scale((w * scale), (h * scale), wx.IMAGE_QUALITY_NORMAL) return img.ConvertToBitmap()
def get_bitmap(self): '\n Returns the primary wx.Image scaled and clipped to the current screen\n parameters for display in the main canvas.\n ' import wx (x, y, w, h) = self.get_bitmap_params() scale = self.get_scale() img = self._wx_img.GetSubImage((x, y, w, h)) img = img.Scale((w * scale), (h * scale), wx.IMAGE_QUALITY_NORMAL) return img.ConvertToBitmap()<|docstring|>Returns the primary wx.Image scaled and clipped to the current screen parameters for display in the main canvas.<|endoftext|>
5aaced04d24fc02816d8e6b171073f48c3b6ba0927479b595017593d6afaf036
def get_thumbnail_bitmap(self): '\n Returns the thumbnail image (without any further processing).\n ' return self._wx_thumb_bmp
Returns the thumbnail image (without any further processing).
rstbx/viewer/__init__.py
get_thumbnail_bitmap
dwpaley/cctbx_project
155
python
def get_thumbnail_bitmap(self): '\n \n ' return self._wx_thumb_bmp
def get_thumbnail_bitmap(self): '\n \n ' return self._wx_thumb_bmp<|docstring|>Returns the thumbnail image (without any further processing).<|endoftext|>
d367c3d34be4709ee49c00ade8b9890cd3950bea288b35a4623822a13a32bbda
def get_zoomed_bitmap(self, x, y, boxsize=400, mag=16): '\n Returns a zoomed-in view of the image, centered around the clicked\n position.\n ' import wx (x0, y0, w, h) = self.get_zoom_box(x, y, boxsize, mag) if ((x0 < 0) or (y0 < 0)): return None assert (w == h) img = self._wx_img.GetSubImage((x0, y0, w, h)) return img.Scale(boxsize, boxsize, wx.IMAGE_QUALITY_NORMAL)
Returns a zoomed-in view of the image, centered around the clicked position.
rstbx/viewer/__init__.py
get_zoomed_bitmap
dwpaley/cctbx_project
155
python
def get_zoomed_bitmap(self, x, y, boxsize=400, mag=16): '\n Returns a zoomed-in view of the image, centered around the clicked\n position.\n ' import wx (x0, y0, w, h) = self.get_zoom_box(x, y, boxsize, mag) if ((x0 < 0) or (y0 < 0)): return None assert (w == h) img = self._wx_img.GetSubImage((x0, y0, w, h)) return img.Scale(boxsize, boxsize, wx.IMAGE_QUALITY_NORMAL)
def get_zoomed_bitmap(self, x, y, boxsize=400, mag=16): '\n Returns a zoomed-in view of the image, centered around the clicked\n position.\n ' import wx (x0, y0, w, h) = self.get_zoom_box(x, y, boxsize, mag) if ((x0 < 0) or (y0 < 0)): return None assert (w == h) img = self._wx_img.GetSubImage((x0, y0, w, h)) return img.Scale(boxsize, boxsize, wx.IMAGE_QUALITY_NORMAL)<|docstring|>Returns a zoomed-in view of the image, centered around the clicked position.<|endoftext|>
182afb96ba9f9ec797c6a0e996a82f6bc82ac2622fffd0734985ed52f5867529
def get_drawable_spots(self): '\n Given an array of spotfinder results (generated separately), determine\n which of these are within the current bounds of the viewport.\n ' if (self._spots is None): return [] (x, y, w, h) = self.get_bitmap_params() all_spots = [] for spot in self._spots: all_spots.append((spot.ctr_mass_x(), spot.ctr_mass_y())) spots_out = self._get_drawable_points(all_spots) return spots_out
Given an array of spotfinder results (generated separately), determine which of these are within the current bounds of the viewport.
rstbx/viewer/__init__.py
get_drawable_spots
dwpaley/cctbx_project
155
python
def get_drawable_spots(self): '\n Given an array of spotfinder results (generated separately), determine\n which of these are within the current bounds of the viewport.\n ' if (self._spots is None): return [] (x, y, w, h) = self.get_bitmap_params() all_spots = [] for spot in self._spots: all_spots.append((spot.ctr_mass_x(), spot.ctr_mass_y())) spots_out = self._get_drawable_points(all_spots) return spots_out
def get_drawable_spots(self): '\n Given an array of spotfinder results (generated separately), determine\n which of these are within the current bounds of the viewport.\n ' if (self._spots is None): return [] (x, y, w, h) = self.get_bitmap_params() all_spots = [] for spot in self._spots: all_spots.append((spot.ctr_mass_x(), spot.ctr_mass_y())) spots_out = self._get_drawable_points(all_spots) return spots_out<|docstring|>Given an array of spotfinder results (generated separately), determine which of these are within the current bounds of the viewport.<|endoftext|>
19e238c77b73c4c95b00a6227119ea1a45e178ff229ac51541edc09026e754fc
def set_beam_center_from_screen_coords(self, x, y): '\n Reposition the beam center for the current image - this is not saved, but\n it will override the beam center in the image header. Arguments are\n screen pixel coordinates in the main viewport.\n ' (x_im, y_im) = self.screen_coords_as_image_coords(x, y) if ((x_im <= 0) or (y_im <= 0) or (x_im > self.img_w) or (y_im > self.img_h)): raise Sorry('Coordinates are out of image!') (x_point, y_point) = self._raw.image_coords_as_detector_coords(x_im, y_im) (old_x, old_y) = self.get_beam_center_mm() self._beam_center = (x_point, y_point) return (old_x, old_y, x_point, y_point)
Reposition the beam center for the current image - this is not saved, but it will override the beam center in the image header. Arguments are screen pixel coordinates in the main viewport.
rstbx/viewer/__init__.py
set_beam_center_from_screen_coords
dwpaley/cctbx_project
155
python
def set_beam_center_from_screen_coords(self, x, y): '\n Reposition the beam center for the current image - this is not saved, but\n it will override the beam center in the image header. Arguments are\n screen pixel coordinates in the main viewport.\n ' (x_im, y_im) = self.screen_coords_as_image_coords(x, y) if ((x_im <= 0) or (y_im <= 0) or (x_im > self.img_w) or (y_im > self.img_h)): raise Sorry('Coordinates are out of image!') (x_point, y_point) = self._raw.image_coords_as_detector_coords(x_im, y_im) (old_x, old_y) = self.get_beam_center_mm() self._beam_center = (x_point, y_point) return (old_x, old_y, x_point, y_point)
def set_beam_center_from_screen_coords(self, x, y): '\n Reposition the beam center for the current image - this is not saved, but\n it will override the beam center in the image header. Arguments are\n screen pixel coordinates in the main viewport.\n ' (x_im, y_im) = self.screen_coords_as_image_coords(x, y) if ((x_im <= 0) or (y_im <= 0) or (x_im > self.img_w) or (y_im > self.img_h)): raise Sorry('Coordinates are out of image!') (x_point, y_point) = self._raw.image_coords_as_detector_coords(x_im, y_im) (old_x, old_y) = self.get_beam_center_mm() self._beam_center = (x_point, y_point) return (old_x, old_y, x_point, y_point)<|docstring|>Reposition the beam center for the current image - this is not saved, but it will override the beam center in the image header. Arguments are screen pixel coordinates in the main viewport.<|endoftext|>
db5f01650d877cac6f52c2929bb1ac3054a2a5e65bcfdc55f105f60c9ff40469
def get_point_info(self, x, y): '\n Determine the intensity, resolution, and array indices of a pixel.\n Arguments are in image pixel coordinates (starting from 1,1).\n ' wavelength = self._raw.get_beam().get_wavelength() d_min = self._raw.get_detector()[0].get_resolution_at_pixel(self._raw.get_beam().get_s0(), (x, y)) (slow, fast) = self.image_coords_as_array_coords(x, y) intensity = None if self._raw.get_detector()[0].is_coord_valid((fast, slow)): intensity = self._raw.get_raw_data()[(fast, slow)] return point_info(slow, fast, intensity, d_min)
Determine the intensity, resolution, and array indices of a pixel. Arguments are in image pixel coordinates (starting from 1,1).
rstbx/viewer/__init__.py
get_point_info
dwpaley/cctbx_project
155
python
def get_point_info(self, x, y): '\n Determine the intensity, resolution, and array indices of a pixel.\n Arguments are in image pixel coordinates (starting from 1,1).\n ' wavelength = self._raw.get_beam().get_wavelength() d_min = self._raw.get_detector()[0].get_resolution_at_pixel(self._raw.get_beam().get_s0(), (x, y)) (slow, fast) = self.image_coords_as_array_coords(x, y) intensity = None if self._raw.get_detector()[0].is_coord_valid((fast, slow)): intensity = self._raw.get_raw_data()[(fast, slow)] return point_info(slow, fast, intensity, d_min)
def get_point_info(self, x, y): '\n Determine the intensity, resolution, and array indices of a pixel.\n Arguments are in image pixel coordinates (starting from 1,1).\n ' wavelength = self._raw.get_beam().get_wavelength() d_min = self._raw.get_detector()[0].get_resolution_at_pixel(self._raw.get_beam().get_s0(), (x, y)) (slow, fast) = self.image_coords_as_array_coords(x, y) intensity = None if self._raw.get_detector()[0].is_coord_valid((fast, slow)): intensity = self._raw.get_raw_data()[(fast, slow)] return point_info(slow, fast, intensity, d_min)<|docstring|>Determine the intensity, resolution, and array indices of a pixel. Arguments are in image pixel coordinates (starting from 1,1).<|endoftext|>
8684de504a567eb58606862263d23764155184071b89621ec5f990be7369c0b3
def line_between_points(self, x1, y1, x2, y2, n_values=100): '\n Given two points on the image, sample intensities along a line connecting\n them (using linear interpolation). This also calculates the coordinates\n of each sample point, which is used for lattice dimension calculations\n once peaks have been identified. Arguments are in image pixel coordinates\n (starting at 1,1).\n ' (x1_, y1_) = self.image_coords_as_array_coords(x1, y1) (x2_, y2_) = self.image_coords_as_array_coords(x2, y2) n_values = ifloor(math.sqrt((((x2_ - x1_) ** 2) + ((y2_ - y1_) ** 2)))) delta_x = ((x2_ - x1_) / (n_values - 1)) delta_y = ((y2_ - y1_) / (n_values - 1)) vals = [] img_coords = [] d = self._raw.linearintdata for n in range(n_values): x = (x1_ + (n * delta_x)) y = (y1_ + (n * delta_y)) (xd, yd) = self.array_coords_as_detector_coords(x, y) img_coords.append((xd, yd)) x_1 = ifloor(x) x_2 = iceil(x) y_1 = ifloor(y) y_2 = iceil(y) v11 = d[(x_1, y_1)] v12 = d[(x_1, y_2)] v21 = d[(x_2, y_1)] v22 = d[(x_2, y_2)] if (x_2 == x_1): if (y_2 == y_1): vxy = v11 else: vxy = (((v12 * (y - y_1)) + (v11 * (y_2 - y))) / (y_2 - y_1)) elif (y_2 == y_1): vxy = (((v21 * (x - x_1)) + (v11 * (x_2 - x))) / (x_2 - x_1)) else: dxdy = ((y_2 - y_1) * (x_2 - x_1)) vxy = ((((((v11 / dxdy) * (x_2 - x)) * (y_2 - y)) + (((v21 / dxdy) * (x - x_1)) * (y_2 - y))) + (((v12 / dxdy) * (x_2 - x)) * (y - y_1))) + (((v22 / dxdy) * (x - x_1)) * (y - y_1))) vals.append(vxy) lattice_length = None if (len(vals) > 5): peaks = [] avg = (sum(vals) / len(vals)) filtered_vals = [] for x in vals: if (x <= (avg * 3)): filtered_vals.append(x) background = (sum(filtered_vals) / len(filtered_vals)) i = 2 while (i < (len(vals) - 2)): x = vals[i] if (x <= background): pass elif ((x > vals[(i - 1)]) and (x > vals[(i - 2)]) and (x > vals[(i + 1)]) and (x > vals[(i + 2)])): peaks.append(i) i += 1 if (len(peaks) > 0): (center_x, center_y) = self.get_beam_center_mm() distances = [] i = 1 while (i < len(peaks)): (x1, y1) = img_coords[peaks[(i - 1)]] (x2, y2) = img_coords[peaks[i]] rs_distance = rstbx.utils.reciprocal_space_distance(x1, y1, x2, y2, wavelength=self.get_wavelength(), center_x=center_x, center_y=center_y, distance=self.get_detector_distance(), detector_two_theta=self.get_detector_2theta(), distance_is_corrected=True) assert (rs_distance > 0) distances.append((1 / rs_distance)) i += 1 lattice_length = (sum(distances) / len(distances)) distance = self.distance_between_points(x1, y1, x2, y2) return line_profile(vals, distance, lattice_length)
Given two points on the image, sample intensities along a line connecting them (using linear interpolation). This also calculates the coordinates of each sample point, which is used for lattice dimension calculations once peaks have been identified. Arguments are in image pixel coordinates (starting at 1,1).
rstbx/viewer/__init__.py
line_between_points
dwpaley/cctbx_project
155
python
def line_between_points(self, x1, y1, x2, y2, n_values=100): '\n Given two points on the image, sample intensities along a line connecting\n them (using linear interpolation). This also calculates the coordinates\n of each sample point, which is used for lattice dimension calculations\n once peaks have been identified. Arguments are in image pixel coordinates\n (starting at 1,1).\n ' (x1_, y1_) = self.image_coords_as_array_coords(x1, y1) (x2_, y2_) = self.image_coords_as_array_coords(x2, y2) n_values = ifloor(math.sqrt((((x2_ - x1_) ** 2) + ((y2_ - y1_) ** 2)))) delta_x = ((x2_ - x1_) / (n_values - 1)) delta_y = ((y2_ - y1_) / (n_values - 1)) vals = [] img_coords = [] d = self._raw.linearintdata for n in range(n_values): x = (x1_ + (n * delta_x)) y = (y1_ + (n * delta_y)) (xd, yd) = self.array_coords_as_detector_coords(x, y) img_coords.append((xd, yd)) x_1 = ifloor(x) x_2 = iceil(x) y_1 = ifloor(y) y_2 = iceil(y) v11 = d[(x_1, y_1)] v12 = d[(x_1, y_2)] v21 = d[(x_2, y_1)] v22 = d[(x_2, y_2)] if (x_2 == x_1): if (y_2 == y_1): vxy = v11 else: vxy = (((v12 * (y - y_1)) + (v11 * (y_2 - y))) / (y_2 - y_1)) elif (y_2 == y_1): vxy = (((v21 * (x - x_1)) + (v11 * (x_2 - x))) / (x_2 - x_1)) else: dxdy = ((y_2 - y_1) * (x_2 - x_1)) vxy = ((((((v11 / dxdy) * (x_2 - x)) * (y_2 - y)) + (((v21 / dxdy) * (x - x_1)) * (y_2 - y))) + (((v12 / dxdy) * (x_2 - x)) * (y - y_1))) + (((v22 / dxdy) * (x - x_1)) * (y - y_1))) vals.append(vxy) lattice_length = None if (len(vals) > 5): peaks = [] avg = (sum(vals) / len(vals)) filtered_vals = [] for x in vals: if (x <= (avg * 3)): filtered_vals.append(x) background = (sum(filtered_vals) / len(filtered_vals)) i = 2 while (i < (len(vals) - 2)): x = vals[i] if (x <= background): pass elif ((x > vals[(i - 1)]) and (x > vals[(i - 2)]) and (x > vals[(i + 1)]) and (x > vals[(i + 2)])): peaks.append(i) i += 1 if (len(peaks) > 0): (center_x, center_y) = self.get_beam_center_mm() distances = [] i = 1 while (i < len(peaks)): (x1, y1) = img_coords[peaks[(i - 1)]] (x2, y2) = img_coords[peaks[i]] rs_distance = rstbx.utils.reciprocal_space_distance(x1, y1, x2, y2, wavelength=self.get_wavelength(), center_x=center_x, center_y=center_y, distance=self.get_detector_distance(), detector_two_theta=self.get_detector_2theta(), distance_is_corrected=True) assert (rs_distance > 0) distances.append((1 / rs_distance)) i += 1 lattice_length = (sum(distances) / len(distances)) distance = self.distance_between_points(x1, y1, x2, y2) return line_profile(vals, distance, lattice_length)
def line_between_points(self, x1, y1, x2, y2, n_values=100): '\n Given two points on the image, sample intensities along a line connecting\n them (using linear interpolation). This also calculates the coordinates\n of each sample point, which is used for lattice dimension calculations\n once peaks have been identified. Arguments are in image pixel coordinates\n (starting at 1,1).\n ' (x1_, y1_) = self.image_coords_as_array_coords(x1, y1) (x2_, y2_) = self.image_coords_as_array_coords(x2, y2) n_values = ifloor(math.sqrt((((x2_ - x1_) ** 2) + ((y2_ - y1_) ** 2)))) delta_x = ((x2_ - x1_) / (n_values - 1)) delta_y = ((y2_ - y1_) / (n_values - 1)) vals = [] img_coords = [] d = self._raw.linearintdata for n in range(n_values): x = (x1_ + (n * delta_x)) y = (y1_ + (n * delta_y)) (xd, yd) = self.array_coords_as_detector_coords(x, y) img_coords.append((xd, yd)) x_1 = ifloor(x) x_2 = iceil(x) y_1 = ifloor(y) y_2 = iceil(y) v11 = d[(x_1, y_1)] v12 = d[(x_1, y_2)] v21 = d[(x_2, y_1)] v22 = d[(x_2, y_2)] if (x_2 == x_1): if (y_2 == y_1): vxy = v11 else: vxy = (((v12 * (y - y_1)) + (v11 * (y_2 - y))) / (y_2 - y_1)) elif (y_2 == y_1): vxy = (((v21 * (x - x_1)) + (v11 * (x_2 - x))) / (x_2 - x_1)) else: dxdy = ((y_2 - y_1) * (x_2 - x_1)) vxy = ((((((v11 / dxdy) * (x_2 - x)) * (y_2 - y)) + (((v21 / dxdy) * (x - x_1)) * (y_2 - y))) + (((v12 / dxdy) * (x_2 - x)) * (y - y_1))) + (((v22 / dxdy) * (x - x_1)) * (y - y_1))) vals.append(vxy) lattice_length = None if (len(vals) > 5): peaks = [] avg = (sum(vals) / len(vals)) filtered_vals = [] for x in vals: if (x <= (avg * 3)): filtered_vals.append(x) background = (sum(filtered_vals) / len(filtered_vals)) i = 2 while (i < (len(vals) - 2)): x = vals[i] if (x <= background): pass elif ((x > vals[(i - 1)]) and (x > vals[(i - 2)]) and (x > vals[(i + 1)]) and (x > vals[(i + 2)])): peaks.append(i) i += 1 if (len(peaks) > 0): (center_x, center_y) = self.get_beam_center_mm() distances = [] i = 1 while (i < len(peaks)): (x1, y1) = img_coords[peaks[(i - 1)]] (x2, y2) = img_coords[peaks[i]] rs_distance = rstbx.utils.reciprocal_space_distance(x1, y1, x2, y2, wavelength=self.get_wavelength(), center_x=center_x, center_y=center_y, distance=self.get_detector_distance(), detector_two_theta=self.get_detector_2theta(), distance_is_corrected=True) assert (rs_distance > 0) distances.append((1 / rs_distance)) i += 1 lattice_length = (sum(distances) / len(distances)) distance = self.distance_between_points(x1, y1, x2, y2) return line_profile(vals, distance, lattice_length)<|docstring|>Given two points on the image, sample intensities along a line connecting them (using linear interpolation). This also calculates the coordinates of each sample point, which is used for lattice dimension calculations once peaks have been identified. Arguments are in image pixel coordinates (starting at 1,1).<|endoftext|>
876f2156acae9712d1b5014c8487ad492bed382685ec27c8b15d5f33e2df6fdb
@command(aliases=['pong']) @cooldown(1, 5, BucketType.guild) async def ping(self, ctx): 'Ping pong' t = time.perf_counter() if ctx.received_at: local_delay = (t - ctx.received_at) else: local_delay = (datetime.utcnow().timestamp() - ctx.message.created_at.timestamp()) (await ctx.trigger_typing()) t = (time.perf_counter() - t) message = 'Pong!\n🏓 took {:.0f}ms\nLocal delay {:.0f}ms\nWebsocket ping {:.0f}ms'.format((t * 1000), (local_delay * 1000), (self.bot.latency * 1000)) if hasattr(self.bot, 'pool'): try: (_, sql_t) = (await self.bot.dbutil.fetch('SELECT 1', measure_time=True)) message += '\nDatabase ping {:.0f}ms'.format((sql_t * 1000)) except PostgresError: message += '\nDatabase could not be reached' (await ctx.send(message))
Ping pong
cogs/utils.py
ping
s0hv/Not-a-bot
6
python
@command(aliases=['pong']) @cooldown(1, 5, BucketType.guild) async def ping(self, ctx): t = time.perf_counter() if ctx.received_at: local_delay = (t - ctx.received_at) else: local_delay = (datetime.utcnow().timestamp() - ctx.message.created_at.timestamp()) (await ctx.trigger_typing()) t = (time.perf_counter() - t) message = 'Pong!\n🏓 took {:.0f}ms\nLocal delay {:.0f}ms\nWebsocket ping {:.0f}ms'.format((t * 1000), (local_delay * 1000), (self.bot.latency * 1000)) if hasattr(self.bot, 'pool'): try: (_, sql_t) = (await self.bot.dbutil.fetch('SELECT 1', measure_time=True)) message += '\nDatabase ping {:.0f}ms'.format((sql_t * 1000)) except PostgresError: message += '\nDatabase could not be reached' (await ctx.send(message))
@command(aliases=['pong']) @cooldown(1, 5, BucketType.guild) async def ping(self, ctx): t = time.perf_counter() if ctx.received_at: local_delay = (t - ctx.received_at) else: local_delay = (datetime.utcnow().timestamp() - ctx.message.created_at.timestamp()) (await ctx.trigger_typing()) t = (time.perf_counter() - t) message = 'Pong!\n🏓 took {:.0f}ms\nLocal delay {:.0f}ms\nWebsocket ping {:.0f}ms'.format((t * 1000), (local_delay * 1000), (self.bot.latency * 1000)) if hasattr(self.bot, 'pool'): try: (_, sql_t) = (await self.bot.dbutil.fetch('SELECT 1', measure_time=True)) message += '\nDatabase ping {:.0f}ms'.format((sql_t * 1000)) except PostgresError: message += '\nDatabase could not be reached' (await ctx.send(message))<|docstring|>Ping pong<|endoftext|>
0f378a84cc7164266975f3f5a285f8421162590ec3efcec4c84b06f94e983944
@command(aliases=['e', 'emoji']) @cooldown(1, 5, BucketType.channel) async def emote(self, ctx, emote: str): 'Get the link to an emote' emote = get_emote_url(emote) if (emote is None): raise BadArgument('You need to specify an emote. Default (unicode) emotes are not supported ~~yet~~') (await ctx.send(emote))
Get the link to an emote
cogs/utils.py
emote
s0hv/Not-a-bot
6
python
@command(aliases=['e', 'emoji']) @cooldown(1, 5, BucketType.channel) async def emote(self, ctx, emote: str): emote = get_emote_url(emote) if (emote is None): raise BadArgument('You need to specify an emote. Default (unicode) emotes are not supported ~~yet~~') (await ctx.send(emote))
@command(aliases=['e', 'emoji']) @cooldown(1, 5, BucketType.channel) async def emote(self, ctx, emote: str): emote = get_emote_url(emote) if (emote is None): raise BadArgument('You need to specify an emote. Default (unicode) emotes are not supported ~~yet~~') (await ctx.send(emote))<|docstring|>Get the link to an emote<|endoftext|>
876b17d3111cf2424d2fe4281e42cb358c7dc70900974bf1019be0d76439e6db
@command(aliases=['roleping']) @cooldown(1, 4, BucketType.channel) async def how2role(self, ctx, *, role: FuzzyRole): 'Searches a role and tells you how to ping it' name = role.name.replace('@', '@\u200b') (await ctx.send(f'`{role.mention}` {name}'))
Searches a role and tells you how to ping it
cogs/utils.py
how2role
s0hv/Not-a-bot
6
python
@command(aliases=['roleping']) @cooldown(1, 4, BucketType.channel) async def how2role(self, ctx, *, role: FuzzyRole): name = role.name.replace('@', '@\u200b') (await ctx.send(f'`{role.mention}` {name}'))
@command(aliases=['roleping']) @cooldown(1, 4, BucketType.channel) async def how2role(self, ctx, *, role: FuzzyRole): name = role.name.replace('@', '@\u200b') (await ctx.send(f'`{role.mention}` {name}'))<|docstring|>Searches a role and tells you how to ping it<|endoftext|>
946bf5781bf83e25ed53ac4c782e36b5e4621cfecbb3606a41e3ad8915c93699
@command(aliases=['howtoping']) @cooldown(1, 4, BucketType.channel) async def how2ping(self, ctx, *, user): 'Searches a user by their name and get the string you can use to ping them' if ctx.guild: members = ctx.guild.members else: members = self.bot.get_all_members() def filter_users(predicate): for member in members: if predicate(member): return member if (member.nick and predicate(member.nick)): return member if ctx.message.raw_role_mentions: i = ((len(ctx.invoked_with) + len(ctx.prefix)) + 1) user = ctx.message.clean_content[i:] user = user[(user.find('@') + 1):] found = filter_users((lambda u: str(u).startswith(user))) s = '`<@!{}>` {}' if found: return (await ctx.send(s.format(found.id, str(found)))) found = filter_users((lambda u: (user in str(u)))) if found: return (await ctx.send(s.format(found.id, str(found)))) else: return (await ctx.send(('No users found with %s' % user)))
Searches a user by their name and get the string you can use to ping them
cogs/utils.py
how2ping
s0hv/Not-a-bot
6
python
@command(aliases=['howtoping']) @cooldown(1, 4, BucketType.channel) async def how2ping(self, ctx, *, user): if ctx.guild: members = ctx.guild.members else: members = self.bot.get_all_members() def filter_users(predicate): for member in members: if predicate(member): return member if (member.nick and predicate(member.nick)): return member if ctx.message.raw_role_mentions: i = ((len(ctx.invoked_with) + len(ctx.prefix)) + 1) user = ctx.message.clean_content[i:] user = user[(user.find('@') + 1):] found = filter_users((lambda u: str(u).startswith(user))) s = '`<@!{}>` {}' if found: return (await ctx.send(s.format(found.id, str(found)))) found = filter_users((lambda u: (user in str(u)))) if found: return (await ctx.send(s.format(found.id, str(found)))) else: return (await ctx.send(('No users found with %s' % user)))
@command(aliases=['howtoping']) @cooldown(1, 4, BucketType.channel) async def how2ping(self, ctx, *, user): if ctx.guild: members = ctx.guild.members else: members = self.bot.get_all_members() def filter_users(predicate): for member in members: if predicate(member): return member if (member.nick and predicate(member.nick)): return member if ctx.message.raw_role_mentions: i = ((len(ctx.invoked_with) + len(ctx.prefix)) + 1) user = ctx.message.clean_content[i:] user = user[(user.find('@') + 1):] found = filter_users((lambda u: str(u).startswith(user))) s = '`<@!{}>` {}' if found: return (await ctx.send(s.format(found.id, str(found)))) found = filter_users((lambda u: (user in str(u)))) if found: return (await ctx.send(s.format(found.id, str(found)))) else: return (await ctx.send(('No users found with %s' % user)))<|docstring|>Searches a user by their name and get the string you can use to ping them<|endoftext|>
caf8a7274bb0f684fd5ea89eb79b4328d566d80c301e9d6ac35fdd196fb2e9ce
@command(aliases=['src', 'source_code', 'sauce']) @cooldown(1, 5, BucketType.user) async def source(self, ctx, *cmd): 'Link to the source code for this bot\n You can also get the source code of commands by doing {prefix}{name} cmd_name' if cmd: full_name = ' '.join(cmd) cmnd = self.bot.all_commands.get(cmd[0]) if (cmnd is None): raise BadArgument(f'Command "{full_name}" not found') for c in cmd[1:]: if (not isinstance(cmnd, Group)): raise BadArgument(f'Command "{full_name}" not found') cmnd = cmnd.get_command(c) cmd = cmnd if (not cmd): (await ctx.send('You can find the source code for this bot here https://github.com/s0hv/Not-a-bot')) return (source, line_number) = inspect.getsourcelines(cmd.callback) filename = inspect.getsourcefile(cmd.callback).replace(os.getcwd(), '').strip('\\/') original_source = textwrap.dedent(''.join(source)) url = f'https://github.com/s0hv/Not-a-bot/tree/master/{filename}#L{line_number}' source = original_source.replace('```', '`\u200b`\u200b`') source = f'''<{url}> ```py {source} ```''' if (len(source) > 2000): file = discord.File(StringIO(original_source), filename=f'{full_name}.py') (await ctx.send(f'''Content was longer than 2000 ({len(source)} > 2000) <{url}>''', file=file)) return (await ctx.send(source))
Link to the source code for this bot You can also get the source code of commands by doing {prefix}{name} cmd_name
cogs/utils.py
source
s0hv/Not-a-bot
6
python
@command(aliases=['src', 'source_code', 'sauce']) @cooldown(1, 5, BucketType.user) async def source(self, ctx, *cmd): 'Link to the source code for this bot\n You can also get the source code of commands by doing {prefix}{name} cmd_name' if cmd: full_name = ' '.join(cmd) cmnd = self.bot.all_commands.get(cmd[0]) if (cmnd is None): raise BadArgument(f'Command "{full_name}" not found') for c in cmd[1:]: if (not isinstance(cmnd, Group)): raise BadArgument(f'Command "{full_name}" not found') cmnd = cmnd.get_command(c) cmd = cmnd if (not cmd): (await ctx.send('You can find the source code for this bot here https://github.com/s0hv/Not-a-bot')) return (source, line_number) = inspect.getsourcelines(cmd.callback) filename = inspect.getsourcefile(cmd.callback).replace(os.getcwd(), ).strip('\\/') original_source = textwrap.dedent(.join(source)) url = f'https://github.com/s0hv/Not-a-bot/tree/master/{filename}#L{line_number}' source = original_source.replace('```', '`\u200b`\u200b`') source = f'<{url}> ```py {source} ```' if (len(source) > 2000): file = discord.File(StringIO(original_source), filename=f'{full_name}.py') (await ctx.send(f'Content was longer than 2000 ({len(source)} > 2000) <{url}>', file=file)) return (await ctx.send(source))
@command(aliases=['src', 'source_code', 'sauce']) @cooldown(1, 5, BucketType.user) async def source(self, ctx, *cmd): 'Link to the source code for this bot\n You can also get the source code of commands by doing {prefix}{name} cmd_name' if cmd: full_name = ' '.join(cmd) cmnd = self.bot.all_commands.get(cmd[0]) if (cmnd is None): raise BadArgument(f'Command "{full_name}" not found') for c in cmd[1:]: if (not isinstance(cmnd, Group)): raise BadArgument(f'Command "{full_name}" not found') cmnd = cmnd.get_command(c) cmd = cmnd if (not cmd): (await ctx.send('You can find the source code for this bot here https://github.com/s0hv/Not-a-bot')) return (source, line_number) = inspect.getsourcelines(cmd.callback) filename = inspect.getsourcefile(cmd.callback).replace(os.getcwd(), ).strip('\\/') original_source = textwrap.dedent(.join(source)) url = f'https://github.com/s0hv/Not-a-bot/tree/master/{filename}#L{line_number}' source = original_source.replace('```', '`\u200b`\u200b`') source = f'<{url}> ```py {source} ```' if (len(source) > 2000): file = discord.File(StringIO(original_source), filename=f'{full_name}.py') (await ctx.send(f'Content was longer than 2000 ({len(source)} > 2000) <{url}>', file=file)) return (await ctx.send(source))<|docstring|>Link to the source code for this bot You can also get the source code of commands by doing {prefix}{name} cmd_name<|endoftext|>
02e637b4ebc4aeeb84df1677a6766006b4382dbfd105ed763548c76cea6f554d
@command() @cooldown(1, 5, BucketType.user) async def undo(self, ctx): '\n Undoes the last undoable command result. Not all messages will be undoable\n and undoable messages override each other because only one message can be\n undone.\n ' if (not (await ctx.undo())): (await ctx.send('Failed to undo the latest undoable command for you.\nDo note that they expire in one minute'))
Undoes the last undoable command result. Not all messages will be undoable and undoable messages override each other because only one message can be undone.
cogs/utils.py
undo
s0hv/Not-a-bot
6
python
@command() @cooldown(1, 5, BucketType.user) async def undo(self, ctx): '\n Undoes the last undoable command result. Not all messages will be undoable\n and undoable messages override each other because only one message can be\n undone.\n ' if (not (await ctx.undo())): (await ctx.send('Failed to undo the latest undoable command for you.\nDo note that they expire in one minute'))
@command() @cooldown(1, 5, BucketType.user) async def undo(self, ctx): '\n Undoes the last undoable command result. Not all messages will be undoable\n and undoable messages override each other because only one message can be\n undone.\n ' if (not (await ctx.undo())): (await ctx.send('Failed to undo the latest undoable command for you.\nDo note that they expire in one minute'))<|docstring|>Undoes the last undoable command result. Not all messages will be undoable and undoable messages override each other because only one message can be undone.<|endoftext|>
2414a3280f9bf5aadb67bb9f30ef325f951cf4026ac6bfda64d14bae4b56f1e4
@command() @cooldown(1, 10, BucketType.user) async def invite(self, ctx): 'This bots invite link' (await ctx.send(f'<https://discordapp.com/api/oauth2/authorize?client_id={self.bot.user.id}&permissions=1342557248&scope=bot>'))
This bots invite link
cogs/utils.py
invite
s0hv/Not-a-bot
6
python
@command() @cooldown(1, 10, BucketType.user) async def invite(self, ctx): (await ctx.send(f'<https://discordapp.com/api/oauth2/authorize?client_id={self.bot.user.id}&permissions=1342557248&scope=bot>'))
@command() @cooldown(1, 10, BucketType.user) async def invite(self, ctx): (await ctx.send(f'<https://discordapp.com/api/oauth2/authorize?client_id={self.bot.user.id}&permissions=1342557248&scope=bot>'))<|docstring|>This bots invite link<|endoftext|>
70bde4500b27dfa04a6ab38bd707aaef49d63a7430b6343d82e1983790d439c7
@command(aliases=['bot', 'botinfo']) @cooldown(2, 5, BucketType.user) @bot_has_permissions(embed_links=True) async def stats(self, ctx): 'Get stats about this bot' pid = os.getpid() process = psutil.Process(pid) uptime = (time.time() - process.create_time()) d = datetime.utcfromtimestamp(uptime) uptime = f'{(d.day - 1)}d {d.hour}h {d.minute}m {d.second}s' current_memory = round((process.memory_info().rss / 1048576), 2) memory_usage = f' Current: {current_memory}MB' if (sys.platform == 'linux'): try: s1 = subprocess.Popen(shlex.split(('pmap %s' % os.getpid())), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) s2 = subprocess.Popen(shlex.split('grep -Po "total +\\K([0-9])+(?=K)"'), stdin=s1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) s1.stdin.close() memory = round((int(s2.communicate()[0].decode('utf-8')) / 1024), 1) usable_memory = (str(memory) + 'MB') memory_usage = f'{current_memory}MB/{usable_memory} ({((current_memory / memory) * 100):.1f}%)' except: logger.exception('Failed to get extended mem usage') raise users = 0 for _ in self.bot.get_all_members(): users += 1 guilds = len(self.bot.guilds) try: last_updated = format_rfc2822(os.stat('.git/refs/heads/master').st_mtime, localtime=True) except OSError: logger.exception('Failed to get last updated') last_updated = 'N/A' sql = 'SELECT * FROM command_stats ORDER BY uses DESC LIMIT 3' try: rows = (await self.bot.dbutil.fetch(sql)) except PostgresError: logger.exception('Failed to get command stats') top_cmd = 'Failed to get command stats' else: top_cmd = '' i = 1 for row in rows: name = row['parent'] cmd = row['cmd'] if cmd: name += (' ' + cmd) top_cmd += f'''{i}. `{name}` with {row['uses']} uses ''' i += 1 embed = discord.Embed(title='Stats', colour=random_color()) embed.add_field(name='discord.py version', value=f'{discord.__version__}') embed.add_field(name='Uptime', value=uptime) if (ctx.guild and (ctx.guild.shard_id is not None)): embed.add_field(name='Shard', value=ctx.guild.shard_id) embed.add_field(name='Servers', value=str(guilds)) embed.add_field(name='Users', value=str(users)) embed.add_field(name='Memory usage', value=memory_usage) embed.add_field(name='Last updated', value=last_updated) embed.add_field(name='Most used commands', value=top_cmd) embed.set_thumbnail(url=get_avatar(self.bot.user)) embed.set_author(name=self.bot.user.name, icon_url=get_avatar(self.bot.user)) (await ctx.send(embed=embed))
Get stats about this bot
cogs/utils.py
stats
s0hv/Not-a-bot
6
python
@command(aliases=['bot', 'botinfo']) @cooldown(2, 5, BucketType.user) @bot_has_permissions(embed_links=True) async def stats(self, ctx): pid = os.getpid() process = psutil.Process(pid) uptime = (time.time() - process.create_time()) d = datetime.utcfromtimestamp(uptime) uptime = f'{(d.day - 1)}d {d.hour}h {d.minute}m {d.second}s' current_memory = round((process.memory_info().rss / 1048576), 2) memory_usage = f' Current: {current_memory}MB' if (sys.platform == 'linux'): try: s1 = subprocess.Popen(shlex.split(('pmap %s' % os.getpid())), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) s2 = subprocess.Popen(shlex.split('grep -Po "total +\\K([0-9])+(?=K)"'), stdin=s1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) s1.stdin.close() memory = round((int(s2.communicate()[0].decode('utf-8')) / 1024), 1) usable_memory = (str(memory) + 'MB') memory_usage = f'{current_memory}MB/{usable_memory} ({((current_memory / memory) * 100):.1f}%)' except: logger.exception('Failed to get extended mem usage') raise users = 0 for _ in self.bot.get_all_members(): users += 1 guilds = len(self.bot.guilds) try: last_updated = format_rfc2822(os.stat('.git/refs/heads/master').st_mtime, localtime=True) except OSError: logger.exception('Failed to get last updated') last_updated = 'N/A' sql = 'SELECT * FROM command_stats ORDER BY uses DESC LIMIT 3' try: rows = (await self.bot.dbutil.fetch(sql)) except PostgresError: logger.exception('Failed to get command stats') top_cmd = 'Failed to get command stats' else: top_cmd = i = 1 for row in rows: name = row['parent'] cmd = row['cmd'] if cmd: name += (' ' + cmd) top_cmd += f'{i}. `{name}` with {row['uses']} uses ' i += 1 embed = discord.Embed(title='Stats', colour=random_color()) embed.add_field(name='discord.py version', value=f'{discord.__version__}') embed.add_field(name='Uptime', value=uptime) if (ctx.guild and (ctx.guild.shard_id is not None)): embed.add_field(name='Shard', value=ctx.guild.shard_id) embed.add_field(name='Servers', value=str(guilds)) embed.add_field(name='Users', value=str(users)) embed.add_field(name='Memory usage', value=memory_usage) embed.add_field(name='Last updated', value=last_updated) embed.add_field(name='Most used commands', value=top_cmd) embed.set_thumbnail(url=get_avatar(self.bot.user)) embed.set_author(name=self.bot.user.name, icon_url=get_avatar(self.bot.user)) (await ctx.send(embed=embed))
@command(aliases=['bot', 'botinfo']) @cooldown(2, 5, BucketType.user) @bot_has_permissions(embed_links=True) async def stats(self, ctx): pid = os.getpid() process = psutil.Process(pid) uptime = (time.time() - process.create_time()) d = datetime.utcfromtimestamp(uptime) uptime = f'{(d.day - 1)}d {d.hour}h {d.minute}m {d.second}s' current_memory = round((process.memory_info().rss / 1048576), 2) memory_usage = f' Current: {current_memory}MB' if (sys.platform == 'linux'): try: s1 = subprocess.Popen(shlex.split(('pmap %s' % os.getpid())), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) s2 = subprocess.Popen(shlex.split('grep -Po "total +\\K([0-9])+(?=K)"'), stdin=s1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) s1.stdin.close() memory = round((int(s2.communicate()[0].decode('utf-8')) / 1024), 1) usable_memory = (str(memory) + 'MB') memory_usage = f'{current_memory}MB/{usable_memory} ({((current_memory / memory) * 100):.1f}%)' except: logger.exception('Failed to get extended mem usage') raise users = 0 for _ in self.bot.get_all_members(): users += 1 guilds = len(self.bot.guilds) try: last_updated = format_rfc2822(os.stat('.git/refs/heads/master').st_mtime, localtime=True) except OSError: logger.exception('Failed to get last updated') last_updated = 'N/A' sql = 'SELECT * FROM command_stats ORDER BY uses DESC LIMIT 3' try: rows = (await self.bot.dbutil.fetch(sql)) except PostgresError: logger.exception('Failed to get command stats') top_cmd = 'Failed to get command stats' else: top_cmd = i = 1 for row in rows: name = row['parent'] cmd = row['cmd'] if cmd: name += (' ' + cmd) top_cmd += f'{i}. `{name}` with {row['uses']} uses ' i += 1 embed = discord.Embed(title='Stats', colour=random_color()) embed.add_field(name='discord.py version', value=f'{discord.__version__}') embed.add_field(name='Uptime', value=uptime) if (ctx.guild and (ctx.guild.shard_id is not None)): embed.add_field(name='Shard', value=ctx.guild.shard_id) embed.add_field(name='Servers', value=str(guilds)) embed.add_field(name='Users', value=str(users)) embed.add_field(name='Memory usage', value=memory_usage) embed.add_field(name='Last updated', value=last_updated) embed.add_field(name='Most used commands', value=top_cmd) embed.set_thumbnail(url=get_avatar(self.bot.user)) embed.set_author(name=self.bot.user.name, icon_url=get_avatar(self.bot.user)) (await ctx.send(embed=embed))<|docstring|>Get stats about this bot<|endoftext|>
dab5739317fd9f56b82405d1ca45e22646e1a81745c21d463cf6bb8eba00cfe0
@command(name='roles', no_pm=True) @cooldown(1, 10, type=BucketType.guild) async def get_roles(self, ctx, page=''): 'Get roles on this server' guild_roles = sorted(ctx.guild.roles, key=(lambda r: r.name)) idx = 0 if page: try: idx = (int(page) - 1) if (idx < 0): return (await ctx.send('Index must be bigger than 0')) except ValueError: return (await ctx.send(('%s is not a valid integer' % page), delete_after=30)) roles = ('A total of %s roles\n' % len(guild_roles)) for role in guild_roles: roles += '{}: {}\n'.format(role.name, role.mention) roles = split_string(roles, splitter='\n', maxlen=1000) (await send_paged_message(ctx, roles, starting_idx=idx, page_method=(lambda p, i: '```{}```'.format(p))))
Get roles on this server
cogs/utils.py
get_roles
s0hv/Not-a-bot
6
python
@command(name='roles', no_pm=True) @cooldown(1, 10, type=BucketType.guild) async def get_roles(self, ctx, page=): guild_roles = sorted(ctx.guild.roles, key=(lambda r: r.name)) idx = 0 if page: try: idx = (int(page) - 1) if (idx < 0): return (await ctx.send('Index must be bigger than 0')) except ValueError: return (await ctx.send(('%s is not a valid integer' % page), delete_after=30)) roles = ('A total of %s roles\n' % len(guild_roles)) for role in guild_roles: roles += '{}: {}\n'.format(role.name, role.mention) roles = split_string(roles, splitter='\n', maxlen=1000) (await send_paged_message(ctx, roles, starting_idx=idx, page_method=(lambda p, i: '```{}```'.format(p))))
@command(name='roles', no_pm=True) @cooldown(1, 10, type=BucketType.guild) async def get_roles(self, ctx, page=): guild_roles = sorted(ctx.guild.roles, key=(lambda r: r.name)) idx = 0 if page: try: idx = (int(page) - 1) if (idx < 0): return (await ctx.send('Index must be bigger than 0')) except ValueError: return (await ctx.send(('%s is not a valid integer' % page), delete_after=30)) roles = ('A total of %s roles\n' % len(guild_roles)) for role in guild_roles: roles += '{}: {}\n'.format(role.name, role.mention) roles = split_string(roles, splitter='\n', maxlen=1000) (await send_paged_message(ctx, roles, starting_idx=idx, page_method=(lambda p, i: '```{}```'.format(p))))<|docstring|>Get roles on this server<|endoftext|>
add229833578f49750d88d8045192422169ab127f5a7b5e64fd802971facc6c4
@command(aliases=['created_at', 'snowflake', 'snoflake']) @cooldown(1, 5, type=BucketType.guild) async def snowflake_time(self, ctx, id: int): 'Gets creation date from the specified discord id in UTC' try: int(id) except ValueError: return (await ctx.send("{} isn't a valid integer".format(id))) (await ctx.send(str(discord.utils.snowflake_time(id))))
Gets creation date from the specified discord id in UTC
cogs/utils.py
snowflake_time
s0hv/Not-a-bot
6
python
@command(aliases=['created_at', 'snowflake', 'snoflake']) @cooldown(1, 5, type=BucketType.guild) async def snowflake_time(self, ctx, id: int): try: int(id) except ValueError: return (await ctx.send("{} isn't a valid integer".format(id))) (await ctx.send(str(discord.utils.snowflake_time(id))))
@command(aliases=['created_at', 'snowflake', 'snoflake']) @cooldown(1, 5, type=BucketType.guild) async def snowflake_time(self, ctx, id: int): try: int(id) except ValueError: return (await ctx.send("{} isn't a valid integer".format(id))) (await ctx.send(str(discord.utils.snowflake_time(id))))<|docstring|>Gets creation date from the specified discord id in UTC<|endoftext|>
d1a1fe0ee192684c01c4d0b67622cae6a249557605472ada6e1b96bed5463ce2
@command(name='unzalgo', hidden=True) @cooldown(2, 5, BucketType.guild) async def unzalgo_(self, ctx, *, zalgo_text: str): "Unzalgo text\n if text is not specified a cache lookup on zalgo text is done for the last 100 msgs\n and the first found zalgo text is unzalgo'd" (await ctx.send(unzalgo(zalgo_text)))
Unzalgo text if text is not specified a cache lookup on zalgo text is done for the last 100 msgs and the first found zalgo text is unzalgo'd
cogs/utils.py
unzalgo_
s0hv/Not-a-bot
6
python
@command(name='unzalgo', hidden=True) @cooldown(2, 5, BucketType.guild) async def unzalgo_(self, ctx, *, zalgo_text: str): "Unzalgo text\n if text is not specified a cache lookup on zalgo text is done for the last 100 msgs\n and the first found zalgo text is unzalgo'd" (await ctx.send(unzalgo(zalgo_text)))
@command(name='unzalgo', hidden=True) @cooldown(2, 5, BucketType.guild) async def unzalgo_(self, ctx, *, zalgo_text: str): "Unzalgo text\n if text is not specified a cache lookup on zalgo text is done for the last 100 msgs\n and the first found zalgo text is unzalgo'd" (await ctx.send(unzalgo(zalgo_text)))<|docstring|>Unzalgo text if text is not specified a cache lookup on zalgo text is done for the last 100 msgs and the first found zalgo text is unzalgo'd<|endoftext|>
f2be4de992531111cc90c98526025e4bac529f08c5606747136a9a3d49665117
@command() @cooldown(1, 20, BucketType.guild) async def support(self, ctx): '\n Support server\n ' (await ctx.send(('The bot does not have a dedicated support server but you can join this server and ask me (s0hvaperuna#4758) stuff\n' + self.bot.config.support_server)))
Support server
cogs/utils.py
support
s0hv/Not-a-bot
6
python
@command() @cooldown(1, 20, BucketType.guild) async def support(self, ctx): '\n \n ' (await ctx.send(('The bot does not have a dedicated support server but you can join this server and ask me (s0hvaperuna#4758) stuff\n' + self.bot.config.support_server)))
@command() @cooldown(1, 20, BucketType.guild) async def support(self, ctx): '\n \n ' (await ctx.send(('The bot does not have a dedicated support server but you can join this server and ask me (s0hvaperuna#4758) stuff\n' + self.bot.config.support_server)))<|docstring|>Support server<|endoftext|>
483cc3c603530a0d4f00447d6f8a9daaa97e2243f24a072144aec7c8af338273
@command() @cooldown(1, 120, BucketType.user) async def feedback(self, ctx, *, feedback): '\n Send feedback of the bot.\n Bug reports should go to https://github.com/s0hvaperuna/Not-a-bot/issues\n ' webhook = self.bot.config.feedback_webhook if (not webhook): return (await ctx.send('This command is unavailable atm')) e = discord.Embed(title='Feedback', description=feedback) author = ctx.author avatar = get_avatar(author) e.set_thumbnail(url=avatar) e.set_footer(text=str(author), icon_url=avatar) e.add_field(name='Guild', value=f'''{ctx.guild.id} {ctx.guild.name}''') json = {'embeds': [e.to_dict()], 'avatar_url': avatar, 'username': ctx.author.name, 'wait': True} headers = {'Content-type': 'application/json'} success = False try: r = (await self.bot.aiohttp_client.post(webhook, json=json, headers=headers)) except aiohttp.ClientError: logger.exception('') else: status = str(r.status) if status.startswith('2'): success = True if success: (await ctx.send('Feedback sent')) else: (await ctx.send('Failed to send feedback'))
Send feedback of the bot. Bug reports should go to https://github.com/s0hvaperuna/Not-a-bot/issues
cogs/utils.py
feedback
s0hv/Not-a-bot
6
python
@command() @cooldown(1, 120, BucketType.user) async def feedback(self, ctx, *, feedback): '\n Send feedback of the bot.\n Bug reports should go to https://github.com/s0hvaperuna/Not-a-bot/issues\n ' webhook = self.bot.config.feedback_webhook if (not webhook): return (await ctx.send('This command is unavailable atm')) e = discord.Embed(title='Feedback', description=feedback) author = ctx.author avatar = get_avatar(author) e.set_thumbnail(url=avatar) e.set_footer(text=str(author), icon_url=avatar) e.add_field(name='Guild', value=f'{ctx.guild.id} {ctx.guild.name}') json = {'embeds': [e.to_dict()], 'avatar_url': avatar, 'username': ctx.author.name, 'wait': True} headers = {'Content-type': 'application/json'} success = False try: r = (await self.bot.aiohttp_client.post(webhook, json=json, headers=headers)) except aiohttp.ClientError: logger.exception() else: status = str(r.status) if status.startswith('2'): success = True if success: (await ctx.send('Feedback sent')) else: (await ctx.send('Failed to send feedback'))
@command() @cooldown(1, 120, BucketType.user) async def feedback(self, ctx, *, feedback): '\n Send feedback of the bot.\n Bug reports should go to https://github.com/s0hvaperuna/Not-a-bot/issues\n ' webhook = self.bot.config.feedback_webhook if (not webhook): return (await ctx.send('This command is unavailable atm')) e = discord.Embed(title='Feedback', description=feedback) author = ctx.author avatar = get_avatar(author) e.set_thumbnail(url=avatar) e.set_footer(text=str(author), icon_url=avatar) e.add_field(name='Guild', value=f'{ctx.guild.id} {ctx.guild.name}') json = {'embeds': [e.to_dict()], 'avatar_url': avatar, 'username': ctx.author.name, 'wait': True} headers = {'Content-type': 'application/json'} success = False try: r = (await self.bot.aiohttp_client.post(webhook, json=json, headers=headers)) except aiohttp.ClientError: logger.exception() else: status = str(r.status) if status.startswith('2'): success = True if success: (await ctx.send('Feedback sent')) else: (await ctx.send('Failed to send feedback'))<|docstring|>Send feedback of the bot. Bug reports should go to https://github.com/s0hvaperuna/Not-a-bot/issues<|endoftext|>
f2dec0e406c43b5c56ef11e33c7ed9fdfb283046c14850aa7b233004532ce08c
@command(ingore_extra=True) @cooldown(1, 10, BucketType.guild) async def vote(self, ctx): 'Pls vote thx' (await ctx.send('https://top.gg/bot/214724376669585409/vote'))
Pls vote thx
cogs/utils.py
vote
s0hv/Not-a-bot
6
python
@command(ingore_extra=True) @cooldown(1, 10, BucketType.guild) async def vote(self, ctx): (await ctx.send('https://top.gg/bot/214724376669585409/vote'))
@command(ingore_extra=True) @cooldown(1, 10, BucketType.guild) async def vote(self, ctx): (await ctx.send('https://top.gg/bot/214724376669585409/vote'))<|docstring|>Pls vote thx<|endoftext|>
076e887dc68c5afca2c698c922f668646aa7979295d3de66c57b91cdc9675ed6
@command() @cooldown(1, 5, BucketType.user) async def emojify(self, ctx, *, text: str): 'Turns your text without emotes to text with discord custom emotes\n To blacklist words from emoji search use a quoted string at the\n beginning of the command denoting those words\n e.g. emojify "blacklisted words here" rest of the sentence\n This will make sure that the words blacklisted, words and here are not turned into emojis' emojis = ctx.bot.emojis new_text = '' word_blacklist = None if text.startswith('"'): idx = text.find('"', 1) word_blacklist = text[1:idx] if word_blacklist: text = text[(idx + 1):] word_blacklist = [s.lower().strip(',.') for s in word_blacklist.split(' ')] if (not text): (await ctx.send('No text given to emojify. Text needs to be given in addition to blacklisted words.')) return emoji_cache = {} lines = text.split('\n') for line in lines: for s in line.split(' '): es = s.lower().strip(',.:') if ((len(s) <= 3) or (word_blacklist and (es in word_blacklist))): new_text += (s + ' ') continue e = emoji_cache.get(es) if (not e): e = self.find_emoji(emojis, es) if (e is None): e = s else: e = str(e) emoji_cache[es] = e new_text += (e + ' ') new_text += '\n' (await ctx.send(new_text[:2000], undoable=True))
Turns your text without emotes to text with discord custom emotes To blacklist words from emoji search use a quoted string at the beginning of the command denoting those words e.g. emojify "blacklisted words here" rest of the sentence This will make sure that the words blacklisted, words and here are not turned into emojis
cogs/utils.py
emojify
s0hv/Not-a-bot
6
python
@command() @cooldown(1, 5, BucketType.user) async def emojify(self, ctx, *, text: str): 'Turns your text without emotes to text with discord custom emotes\n To blacklist words from emoji search use a quoted string at the\n beginning of the command denoting those words\n e.g. emojify "blacklisted words here" rest of the sentence\n This will make sure that the words blacklisted, words and here are not turned into emojis' emojis = ctx.bot.emojis new_text = word_blacklist = None if text.startswith('"'): idx = text.find('"', 1) word_blacklist = text[1:idx] if word_blacklist: text = text[(idx + 1):] word_blacklist = [s.lower().strip(',.') for s in word_blacklist.split(' ')] if (not text): (await ctx.send('No text given to emojify. Text needs to be given in addition to blacklisted words.')) return emoji_cache = {} lines = text.split('\n') for line in lines: for s in line.split(' '): es = s.lower().strip(',.:') if ((len(s) <= 3) or (word_blacklist and (es in word_blacklist))): new_text += (s + ' ') continue e = emoji_cache.get(es) if (not e): e = self.find_emoji(emojis, es) if (e is None): e = s else: e = str(e) emoji_cache[es] = e new_text += (e + ' ') new_text += '\n' (await ctx.send(new_text[:2000], undoable=True))
@command() @cooldown(1, 5, BucketType.user) async def emojify(self, ctx, *, text: str): 'Turns your text without emotes to text with discord custom emotes\n To blacklist words from emoji search use a quoted string at the\n beginning of the command denoting those words\n e.g. emojify "blacklisted words here" rest of the sentence\n This will make sure that the words blacklisted, words and here are not turned into emojis' emojis = ctx.bot.emojis new_text = word_blacklist = None if text.startswith('"'): idx = text.find('"', 1) word_blacklist = text[1:idx] if word_blacklist: text = text[(idx + 1):] word_blacklist = [s.lower().strip(',.') for s in word_blacklist.split(' ')] if (not text): (await ctx.send('No text given to emojify. Text needs to be given in addition to blacklisted words.')) return emoji_cache = {} lines = text.split('\n') for line in lines: for s in line.split(' '): es = s.lower().strip(',.:') if ((len(s) <= 3) or (word_blacklist and (es in word_blacklist))): new_text += (s + ' ') continue e = emoji_cache.get(es) if (not e): e = self.find_emoji(emojis, es) if (e is None): e = s else: e = str(e) emoji_cache[es] = e new_text += (e + ' ') new_text += '\n' (await ctx.send(new_text[:2000], undoable=True))<|docstring|>Turns your text without emotes to text with discord custom emotes To blacklist words from emoji search use a quoted string at the beginning of the command denoting those words e.g. emojify "blacklisted words here" rest of the sentence This will make sure that the words blacklisted, words and here are not turned into emojis<|endoftext|>
ff3eb514dc0f9412115e20b6966e90aa980c6b3005763eb8c346748d478717bd
@command(name='pip', enabled=False) @cooldown(1, 5, BucketType.channel) @bot_has_permissions(embed_links=True) async def get_package(self, ctx, *, name): 'Get a package from pypi' if (SearchCommand is None): return (await ctx.send('Not supported')) def search(): try: search_command = SearchCommand('search', 'search command') (options, _) = search_command.parse_args([name]) hits = search_command.search(name, options) if hits: return hits[0] except: logger.exception('Failed to search package from PyPi') raise hit = (await self.bot.loop.run_in_executor(self.bot.threadpool, search)) if (not hit): return (await ctx.send('No matches')) async with self.bot.aiohttp_client.get(f"https://pypi.org/pypi/{quote(hit['name'])}/json") as r: if (r.status != 200): return (await ctx.send(f'HTTP error {r.status}')) json = (await r.json()) info = json['info'] description = info['description'] if (len(description) > 1000): description = (split_string(description, splitter='\n', maxlen=1000)[0] + '...') embed = discord.Embed(title=hit['name'], description=description, url=info['package_url']) embed.add_field(name='Author', value=(info['author'] or 'None')) embed.add_field(name='Version', value=(info['version'] or 'None')) embed.add_field(name='License', value=(info['license'] or 'None')) (await ctx.send(embed=embed))
Get a package from pypi
cogs/utils.py
get_package
s0hv/Not-a-bot
6
python
@command(name='pip', enabled=False) @cooldown(1, 5, BucketType.channel) @bot_has_permissions(embed_links=True) async def get_package(self, ctx, *, name): if (SearchCommand is None): return (await ctx.send('Not supported')) def search(): try: search_command = SearchCommand('search', 'search command') (options, _) = search_command.parse_args([name]) hits = search_command.search(name, options) if hits: return hits[0] except: logger.exception('Failed to search package from PyPi') raise hit = (await self.bot.loop.run_in_executor(self.bot.threadpool, search)) if (not hit): return (await ctx.send('No matches')) async with self.bot.aiohttp_client.get(f"https://pypi.org/pypi/{quote(hit['name'])}/json") as r: if (r.status != 200): return (await ctx.send(f'HTTP error {r.status}')) json = (await r.json()) info = json['info'] description = info['description'] if (len(description) > 1000): description = (split_string(description, splitter='\n', maxlen=1000)[0] + '...') embed = discord.Embed(title=hit['name'], description=description, url=info['package_url']) embed.add_field(name='Author', value=(info['author'] or 'None')) embed.add_field(name='Version', value=(info['version'] or 'None')) embed.add_field(name='License', value=(info['license'] or 'None')) (await ctx.send(embed=embed))
@command(name='pip', enabled=False) @cooldown(1, 5, BucketType.channel) @bot_has_permissions(embed_links=True) async def get_package(self, ctx, *, name): if (SearchCommand is None): return (await ctx.send('Not supported')) def search(): try: search_command = SearchCommand('search', 'search command') (options, _) = search_command.parse_args([name]) hits = search_command.search(name, options) if hits: return hits[0] except: logger.exception('Failed to search package from PyPi') raise hit = (await self.bot.loop.run_in_executor(self.bot.threadpool, search)) if (not hit): return (await ctx.send('No matches')) async with self.bot.aiohttp_client.get(f"https://pypi.org/pypi/{quote(hit['name'])}/json") as r: if (r.status != 200): return (await ctx.send(f'HTTP error {r.status}')) json = (await r.json()) info = json['info'] description = info['description'] if (len(description) > 1000): description = (split_string(description, splitter='\n', maxlen=1000)[0] + '...') embed = discord.Embed(title=hit['name'], description=description, url=info['package_url']) embed.add_field(name='Author', value=(info['author'] or 'None')) embed.add_field(name='Version', value=(info['version'] or 'None')) embed.add_field(name='License', value=(info['license'] or 'None')) (await ctx.send(embed=embed))<|docstring|>Get a package from pypi<|endoftext|>
028b7724f7dc7b0467eaa4a6493f72d758b618e5b969addfb91acb1d9781fa20
@command(aliases=['tz']) @cooldown(2, 7) async def timezone(self, ctx, *, timezone: str=None): "\n Set or view your timezone. If timezone isn't given shows your current timezone\n If timezone is given sets your current timezone to that.\n Summer time should be supported for any timezone that's not a plain utc offset.\n Due to [technical reasons](https://en.wikipedia.org/wiki/Tz_database#Area)\n the sign in gmt offsets is flipped. e.g. UTC+5 offset is GMT-5\n Examples:\n • `{prefix}{name} utc+4`\n • `{prefix}{name} London`\n • `{prefix}{name} EST`\n " user = ctx.author if (not timezone): tz = (await self.get_timezone(ctx, user.id)) s = tz.localize(datetime.utcnow()).strftime('Your current timezone is UTC %z') (await ctx.send(s)) return tz = fuzzy_tz.get(timezone.lower()) extra = '' if (not tz): tz = tz_dict.get(timezone.upper()) if tz: tz = fuzzy_tz.get(f'utc{(int(tz) // 3600):+d}') if (not tz): (await ctx.send(f'Timezone {timezone} not found')) ctx.command.undo_use(ctx) return if tz.startswith('Etc/GMT'): extra = "UTC offset used. Consider using a locality based timezone instead. You can set it usually by using your country's capital's name or your country's name as long as it has a single timezone\nThe sign in the GMT timezone is flipped due to technical reasons." if (await self.bot.dbutil.set_timezone(user.id, tz)): (await ctx.send(f'''Timezone set to {tz} {extra}''')) else: (await ctx.send('Failed to set timezone because of an error'))
Set or view your timezone. If timezone isn't given shows your current timezone If timezone is given sets your current timezone to that. Summer time should be supported for any timezone that's not a plain utc offset. Due to [technical reasons](https://en.wikipedia.org/wiki/Tz_database#Area) the sign in gmt offsets is flipped. e.g. UTC+5 offset is GMT-5 Examples: • `{prefix}{name} utc+4` • `{prefix}{name} London` • `{prefix}{name} EST`
cogs/utils.py
timezone
s0hv/Not-a-bot
6
python
@command(aliases=['tz']) @cooldown(2, 7) async def timezone(self, ctx, *, timezone: str=None): "\n Set or view your timezone. If timezone isn't given shows your current timezone\n If timezone is given sets your current timezone to that.\n Summer time should be supported for any timezone that's not a plain utc offset.\n Due to [technical reasons](https://en.wikipedia.org/wiki/Tz_database#Area)\n the sign in gmt offsets is flipped. e.g. UTC+5 offset is GMT-5\n Examples:\n • `{prefix}{name} utc+4`\n • `{prefix}{name} London`\n • `{prefix}{name} EST`\n " user = ctx.author if (not timezone): tz = (await self.get_timezone(ctx, user.id)) s = tz.localize(datetime.utcnow()).strftime('Your current timezone is UTC %z') (await ctx.send(s)) return tz = fuzzy_tz.get(timezone.lower()) extra = if (not tz): tz = tz_dict.get(timezone.upper()) if tz: tz = fuzzy_tz.get(f'utc{(int(tz) // 3600):+d}') if (not tz): (await ctx.send(f'Timezone {timezone} not found')) ctx.command.undo_use(ctx) return if tz.startswith('Etc/GMT'): extra = "UTC offset used. Consider using a locality based timezone instead. You can set it usually by using your country's capital's name or your country's name as long as it has a single timezone\nThe sign in the GMT timezone is flipped due to technical reasons." if (await self.bot.dbutil.set_timezone(user.id, tz)): (await ctx.send(f'Timezone set to {tz} {extra}')) else: (await ctx.send('Failed to set timezone because of an error'))
@command(aliases=['tz']) @cooldown(2, 7) async def timezone(self, ctx, *, timezone: str=None): "\n Set or view your timezone. If timezone isn't given shows your current timezone\n If timezone is given sets your current timezone to that.\n Summer time should be supported for any timezone that's not a plain utc offset.\n Due to [technical reasons](https://en.wikipedia.org/wiki/Tz_database#Area)\n the sign in gmt offsets is flipped. e.g. UTC+5 offset is GMT-5\n Examples:\n • `{prefix}{name} utc+4`\n • `{prefix}{name} London`\n • `{prefix}{name} EST`\n " user = ctx.author if (not timezone): tz = (await self.get_timezone(ctx, user.id)) s = tz.localize(datetime.utcnow()).strftime('Your current timezone is UTC %z') (await ctx.send(s)) return tz = fuzzy_tz.get(timezone.lower()) extra = if (not tz): tz = tz_dict.get(timezone.upper()) if tz: tz = fuzzy_tz.get(f'utc{(int(tz) // 3600):+d}') if (not tz): (await ctx.send(f'Timezone {timezone} not found')) ctx.command.undo_use(ctx) return if tz.startswith('Etc/GMT'): extra = "UTC offset used. Consider using a locality based timezone instead. You can set it usually by using your country's capital's name or your country's name as long as it has a single timezone\nThe sign in the GMT timezone is flipped due to technical reasons." if (await self.bot.dbutil.set_timezone(user.id, tz)): (await ctx.send(f'Timezone set to {tz} {extra}')) else: (await ctx.send('Failed to set timezone because of an error'))<|docstring|>Set or view your timezone. If timezone isn't given shows your current timezone If timezone is given sets your current timezone to that. Summer time should be supported for any timezone that's not a plain utc offset. Due to [technical reasons](https://en.wikipedia.org/wiki/Tz_database#Area) the sign in gmt offsets is flipped. e.g. UTC+5 offset is GMT-5 Examples: • `{prefix}{name} utc+4` • `{prefix}{name} London` • `{prefix}{name} EST`<|endoftext|>
deef8ef91d5d0dad6b8b39e887b02dbed8d5f852476e5ce8dff49f2f838d9772
@command(name='timedelta', aliases=['td'], usage='[duration or date] [timezones and users]') @cooldown(1, 3, BucketType.user) async def timedelta_(self, ctx, *, args=''): '\n Get a date that is in the amount of duration given.\n To get past dates start your duration with `-`\n Time format is `1d 1h 1m 1s` where each one is optional.\n When no time is given it is interpreted as 0 seconds.\n\n You can also give a date and duration will be calculated as the time to that point in time.\n Timezone will be user timezone by default but you can specify the date utc offset with e.g. UTC+3\n If the date doesn\'t have spaces in it, put it inside quotes. In ambiguous 3-integer dates day is assumed to be first\n e.g. `"14:00"`, `14:00 UTC+1`, `"Mon 14:00 UTC-3"`\n\n You can also specify which timezones to use for comparison.\n By default your own timezone is always put at the bottom (defaults to UTC).\n Timezones can be just an integer determining the UTC offset in hours or\n a city name or a country (Not all countries and cities are accepted as input).\n Remember to use quotes if the city name contains spaces.\n You can also give users and their timezone is used if they\'ve set it\n Max given timezones is 5.\n\n Examples\n `{prefix}{name} 1h ny`\n `{prefix}{name} "Mon 22:00 UTC-3"`\n `{prefix}{name} "Jan 4th 10:00" @user berlin`\n ' addition = True if args.startswith('-'): addition = False args = args[1:] (duration, timezones) = parse_timeout(args) quote_start = timezones.startswith('"') user_tz = (await self.get_timezone(ctx, ctx.author.id)) timezones = shlex.split(timezones) if ((not duration) and timezones): try: if quote_start: t = timezones[0] else: t = ' '.join(timezones[:2]) def get_date(): def get_tz(name, offset): if name: found_tz = tz_dict.get(name) if (not found_tz): found_tz = gettz(fuzzy_tz.get(name.lower(), 'a')) return found_tz elif offset: return (offset * (- 1)) return parser.parse(t.upper(), tzinfos=get_tz, parserinfo=parserinfo) date = (await self.bot.run_async(get_date)) if (not date.tzinfo): duration = (user_tz.localize(date) - datetime.now(user_tz)) else: tz = pytz.FixedOffset((date.tzinfo.utcoffset(datetime.utcnow()).total_seconds() // 60)) duration = (date.replace(tzinfo=tz) - datetime.now(user_tz)) addition = (duration.days >= 0) if (not addition): duration *= (- 1) if quote_start: timezones = timezones[1:] else: timezones = timezones[2:] except (ValueError, OverflowError): pass if (len(timezones) > 5): (await ctx.send('Over 5 timezones given. Give fewer timezones (Use quotes if a tz has spaces)')) return async def add_time(dt): try: if addition: return (dt + duration) else: return (dt - duration) except OverflowError: (await ctx.send('Failed to get new date because of an Overflow error. Try giving a smaller duration')) tz_converter = TzConverter() user_converter = PossibleUser() s = '' for timezone in timezones: try: tz = (await tz_converter.convert(ctx, timezone)) except BadArgument as e: try: user = (await user_converter.convert(ctx, timezone)) if isinstance(user, int): tz = (await self.get_timezone(ctx, user)) else: tz = (await self.get_timezone(ctx, user.id)) except BadArgument: raise e dt = (await add_time(datetime.now(tz))) if (not dt): return s += f'''`{dt.strftime('%Y-%m-%d %H:%M UTC%z')}` `{tz.zone}` ''' dt = (await add_time(datetime.now(user_tz))) if (not dt): return s += f'''`{dt.strftime('%Y-%m-%d %H:%M UTC%z')}` `{user_tz.zone}` ''' td = format_timedelta(duration, accuracy=(DateAccuracy.Day - DateAccuracy.Minute)) if addition: s += f'which is in {td}' else: s += f'which was {td} ago' (await ctx.send(s))
Get a date that is in the amount of duration given. To get past dates start your duration with `-` Time format is `1d 1h 1m 1s` where each one is optional. When no time is given it is interpreted as 0 seconds. You can also give a date and duration will be calculated as the time to that point in time. Timezone will be user timezone by default but you can specify the date utc offset with e.g. UTC+3 If the date doesn't have spaces in it, put it inside quotes. In ambiguous 3-integer dates day is assumed to be first e.g. `"14:00"`, `14:00 UTC+1`, `"Mon 14:00 UTC-3"` You can also specify which timezones to use for comparison. By default your own timezone is always put at the bottom (defaults to UTC). Timezones can be just an integer determining the UTC offset in hours or a city name or a country (Not all countries and cities are accepted as input). Remember to use quotes if the city name contains spaces. You can also give users and their timezone is used if they've set it Max given timezones is 5. Examples `{prefix}{name} 1h ny` `{prefix}{name} "Mon 22:00 UTC-3"` `{prefix}{name} "Jan 4th 10:00" @user berlin`
cogs/utils.py
timedelta_
s0hv/Not-a-bot
6
python
@command(name='timedelta', aliases=['td'], usage='[duration or date] [timezones and users]') @cooldown(1, 3, BucketType.user) async def timedelta_(self, ctx, *, args=): '\n Get a date that is in the amount of duration given.\n To get past dates start your duration with `-`\n Time format is `1d 1h 1m 1s` where each one is optional.\n When no time is given it is interpreted as 0 seconds.\n\n You can also give a date and duration will be calculated as the time to that point in time.\n Timezone will be user timezone by default but you can specify the date utc offset with e.g. UTC+3\n If the date doesn\'t have spaces in it, put it inside quotes. In ambiguous 3-integer dates day is assumed to be first\n e.g. `"14:00"`, `14:00 UTC+1`, `"Mon 14:00 UTC-3"`\n\n You can also specify which timezones to use for comparison.\n By default your own timezone is always put at the bottom (defaults to UTC).\n Timezones can be just an integer determining the UTC offset in hours or\n a city name or a country (Not all countries and cities are accepted as input).\n Remember to use quotes if the city name contains spaces.\n You can also give users and their timezone is used if they\'ve set it\n Max given timezones is 5.\n\n Examples\n `{prefix}{name} 1h ny`\n `{prefix}{name} "Mon 22:00 UTC-3"`\n `{prefix}{name} "Jan 4th 10:00" @user berlin`\n ' addition = True if args.startswith('-'): addition = False args = args[1:] (duration, timezones) = parse_timeout(args) quote_start = timezones.startswith('"') user_tz = (await self.get_timezone(ctx, ctx.author.id)) timezones = shlex.split(timezones) if ((not duration) and timezones): try: if quote_start: t = timezones[0] else: t = ' '.join(timezones[:2]) def get_date(): def get_tz(name, offset): if name: found_tz = tz_dict.get(name) if (not found_tz): found_tz = gettz(fuzzy_tz.get(name.lower(), 'a')) return found_tz elif offset: return (offset * (- 1)) return parser.parse(t.upper(), tzinfos=get_tz, parserinfo=parserinfo) date = (await self.bot.run_async(get_date)) if (not date.tzinfo): duration = (user_tz.localize(date) - datetime.now(user_tz)) else: tz = pytz.FixedOffset((date.tzinfo.utcoffset(datetime.utcnow()).total_seconds() // 60)) duration = (date.replace(tzinfo=tz) - datetime.now(user_tz)) addition = (duration.days >= 0) if (not addition): duration *= (- 1) if quote_start: timezones = timezones[1:] else: timezones = timezones[2:] except (ValueError, OverflowError): pass if (len(timezones) > 5): (await ctx.send('Over 5 timezones given. Give fewer timezones (Use quotes if a tz has spaces)')) return async def add_time(dt): try: if addition: return (dt + duration) else: return (dt - duration) except OverflowError: (await ctx.send('Failed to get new date because of an Overflow error. Try giving a smaller duration')) tz_converter = TzConverter() user_converter = PossibleUser() s = for timezone in timezones: try: tz = (await tz_converter.convert(ctx, timezone)) except BadArgument as e: try: user = (await user_converter.convert(ctx, timezone)) if isinstance(user, int): tz = (await self.get_timezone(ctx, user)) else: tz = (await self.get_timezone(ctx, user.id)) except BadArgument: raise e dt = (await add_time(datetime.now(tz))) if (not dt): return s += f'`{dt.strftime('%Y-%m-%d %H:%M UTC%z')}` `{tz.zone}` ' dt = (await add_time(datetime.now(user_tz))) if (not dt): return s += f'`{dt.strftime('%Y-%m-%d %H:%M UTC%z')}` `{user_tz.zone}` ' td = format_timedelta(duration, accuracy=(DateAccuracy.Day - DateAccuracy.Minute)) if addition: s += f'which is in {td}' else: s += f'which was {td} ago' (await ctx.send(s))
@command(name='timedelta', aliases=['td'], usage='[duration or date] [timezones and users]') @cooldown(1, 3, BucketType.user) async def timedelta_(self, ctx, *, args=): '\n Get a date that is in the amount of duration given.\n To get past dates start your duration with `-`\n Time format is `1d 1h 1m 1s` where each one is optional.\n When no time is given it is interpreted as 0 seconds.\n\n You can also give a date and duration will be calculated as the time to that point in time.\n Timezone will be user timezone by default but you can specify the date utc offset with e.g. UTC+3\n If the date doesn\'t have spaces in it, put it inside quotes. In ambiguous 3-integer dates day is assumed to be first\n e.g. `"14:00"`, `14:00 UTC+1`, `"Mon 14:00 UTC-3"`\n\n You can also specify which timezones to use for comparison.\n By default your own timezone is always put at the bottom (defaults to UTC).\n Timezones can be just an integer determining the UTC offset in hours or\n a city name or a country (Not all countries and cities are accepted as input).\n Remember to use quotes if the city name contains spaces.\n You can also give users and their timezone is used if they\'ve set it\n Max given timezones is 5.\n\n Examples\n `{prefix}{name} 1h ny`\n `{prefix}{name} "Mon 22:00 UTC-3"`\n `{prefix}{name} "Jan 4th 10:00" @user berlin`\n ' addition = True if args.startswith('-'): addition = False args = args[1:] (duration, timezones) = parse_timeout(args) quote_start = timezones.startswith('"') user_tz = (await self.get_timezone(ctx, ctx.author.id)) timezones = shlex.split(timezones) if ((not duration) and timezones): try: if quote_start: t = timezones[0] else: t = ' '.join(timezones[:2]) def get_date(): def get_tz(name, offset): if name: found_tz = tz_dict.get(name) if (not found_tz): found_tz = gettz(fuzzy_tz.get(name.lower(), 'a')) return found_tz elif offset: return (offset * (- 1)) return parser.parse(t.upper(), tzinfos=get_tz, parserinfo=parserinfo) date = (await self.bot.run_async(get_date)) if (not date.tzinfo): duration = (user_tz.localize(date) - datetime.now(user_tz)) else: tz = pytz.FixedOffset((date.tzinfo.utcoffset(datetime.utcnow()).total_seconds() // 60)) duration = (date.replace(tzinfo=tz) - datetime.now(user_tz)) addition = (duration.days >= 0) if (not addition): duration *= (- 1) if quote_start: timezones = timezones[1:] else: timezones = timezones[2:] except (ValueError, OverflowError): pass if (len(timezones) > 5): (await ctx.send('Over 5 timezones given. Give fewer timezones (Use quotes if a tz has spaces)')) return async def add_time(dt): try: if addition: return (dt + duration) else: return (dt - duration) except OverflowError: (await ctx.send('Failed to get new date because of an Overflow error. Try giving a smaller duration')) tz_converter = TzConverter() user_converter = PossibleUser() s = for timezone in timezones: try: tz = (await tz_converter.convert(ctx, timezone)) except BadArgument as e: try: user = (await user_converter.convert(ctx, timezone)) if isinstance(user, int): tz = (await self.get_timezone(ctx, user)) else: tz = (await self.get_timezone(ctx, user.id)) except BadArgument: raise e dt = (await add_time(datetime.now(tz))) if (not dt): return s += f'`{dt.strftime('%Y-%m-%d %H:%M UTC%z')}` `{tz.zone}` ' dt = (await add_time(datetime.now(user_tz))) if (not dt): return s += f'`{dt.strftime('%Y-%m-%d %H:%M UTC%z')}` `{user_tz.zone}` ' td = format_timedelta(duration, accuracy=(DateAccuracy.Day - DateAccuracy.Minute)) if addition: s += f'which is in {td}' else: s += f'which was {td} ago' (await ctx.send(s))<|docstring|>Get a date that is in the amount of duration given. To get past dates start your duration with `-` Time format is `1d 1h 1m 1s` where each one is optional. When no time is given it is interpreted as 0 seconds. You can also give a date and duration will be calculated as the time to that point in time. Timezone will be user timezone by default but you can specify the date utc offset with e.g. UTC+3 If the date doesn't have spaces in it, put it inside quotes. In ambiguous 3-integer dates day is assumed to be first e.g. `"14:00"`, `14:00 UTC+1`, `"Mon 14:00 UTC-3"` You can also specify which timezones to use for comparison. By default your own timezone is always put at the bottom (defaults to UTC). Timezones can be just an integer determining the UTC offset in hours or a city name or a country (Not all countries and cities are accepted as input). Remember to use quotes if the city name contains spaces. You can also give users and their timezone is used if they've set it Max given timezones is 5. Examples `{prefix}{name} 1h ny` `{prefix}{name} "Mon 22:00 UTC-3"` `{prefix}{name} "Jan 4th 10:00" @user berlin`<|endoftext|>
9a30974ee63788bb10d4f22fb6037c857fbf198f22b02d77fdc7cfb66abb401b
@command(aliases=['st']) @cooldown(1, 4, BucketType.user) async def sort_tags(self, ctx, tagname, *, tags): 'Gets missing tag indexes from a 42 bot tag search.\n The first tagname must be the one that is gonna be looked for' tagname = tagname.rstrip(',') tags = tags.split(', ') match = re.match('(.+?)(\\d+)', tagname) numbers = set() if match: (tagname, number) = match.groups() numbers.add(int(number)) else: numbers.add(0) tagname = tagname.lstrip('\u200b') tl = len(tagname) for tag in tags: if tag.endswith('...'): continue if (tagname not in tag): continue if (tagname == tag): numbers.add(0) continue try: n = tag[tl:] if (len(n) > 4): continue numbers.add(int(n)) except ValueError: continue if (not numbers): (await ctx.send(f'No other numbered tags found for {tagname}')) return numbers = list(sorted(numbers)) last = numbers[0] if (last > 2): s = f'-{(last - 1)}, ' else: s = '' for i in numbers[1:]: delta = (i - last) if (delta > 4): s += f'{(last + 1)}-{(i - 1)}, ' elif (delta == 3): s += f'{(last + 1)}, {(i - 1)}, ' elif (delta == 2): s += f'{(i - 1)}, ' last = i s += f'{(last + 1)}-' (await ctx.send(f'Missing tag numbers for {tagname} are {s}'))
Gets missing tag indexes from a 42 bot tag search. The first tagname must be the one that is gonna be looked for
cogs/utils.py
sort_tags
s0hv/Not-a-bot
6
python
@command(aliases=['st']) @cooldown(1, 4, BucketType.user) async def sort_tags(self, ctx, tagname, *, tags): 'Gets missing tag indexes from a 42 bot tag search.\n The first tagname must be the one that is gonna be looked for' tagname = tagname.rstrip(',') tags = tags.split(', ') match = re.match('(.+?)(\\d+)', tagname) numbers = set() if match: (tagname, number) = match.groups() numbers.add(int(number)) else: numbers.add(0) tagname = tagname.lstrip('\u200b') tl = len(tagname) for tag in tags: if tag.endswith('...'): continue if (tagname not in tag): continue if (tagname == tag): numbers.add(0) continue try: n = tag[tl:] if (len(n) > 4): continue numbers.add(int(n)) except ValueError: continue if (not numbers): (await ctx.send(f'No other numbered tags found for {tagname}')) return numbers = list(sorted(numbers)) last = numbers[0] if (last > 2): s = f'-{(last - 1)}, ' else: s = for i in numbers[1:]: delta = (i - last) if (delta > 4): s += f'{(last + 1)}-{(i - 1)}, ' elif (delta == 3): s += f'{(last + 1)}, {(i - 1)}, ' elif (delta == 2): s += f'{(i - 1)}, ' last = i s += f'{(last + 1)}-' (await ctx.send(f'Missing tag numbers for {tagname} are {s}'))
@command(aliases=['st']) @cooldown(1, 4, BucketType.user) async def sort_tags(self, ctx, tagname, *, tags): 'Gets missing tag indexes from a 42 bot tag search.\n The first tagname must be the one that is gonna be looked for' tagname = tagname.rstrip(',') tags = tags.split(', ') match = re.match('(.+?)(\\d+)', tagname) numbers = set() if match: (tagname, number) = match.groups() numbers.add(int(number)) else: numbers.add(0) tagname = tagname.lstrip('\u200b') tl = len(tagname) for tag in tags: if tag.endswith('...'): continue if (tagname not in tag): continue if (tagname == tag): numbers.add(0) continue try: n = tag[tl:] if (len(n) > 4): continue numbers.add(int(n)) except ValueError: continue if (not numbers): (await ctx.send(f'No other numbered tags found for {tagname}')) return numbers = list(sorted(numbers)) last = numbers[0] if (last > 2): s = f'-{(last - 1)}, ' else: s = for i in numbers[1:]: delta = (i - last) if (delta > 4): s += f'{(last + 1)}-{(i - 1)}, ' elif (delta == 3): s += f'{(last + 1)}, {(i - 1)}, ' elif (delta == 2): s += f'{(i - 1)}, ' last = i s += f'{(last + 1)}-' (await ctx.send(f'Missing tag numbers for {tagname} are {s}'))<|docstring|>Gets missing tag indexes from a 42 bot tag search. The first tagname must be the one that is gonna be looked for<|endoftext|>
3066bc812e6a997905e9ee85b35e1e4abd3a268bf280cb8e7f67ca62fdb609b2
@command(aliases=['who', 'user', 'whois']) @cooldown(7, 10, BucketType.guild) async def userinfo(self, ctx: Context, *, user: Union[(discord.Member, discord.User)]): '\n Shows info of a user.\n Using the username might not always work. In those cases use the user id\n ' embed = discord.Embed(title=str(user)) embed.set_thumbnail(url=get_avatar(user)) embed.add_field(name='Username', value=str(user)) embed.add_field(name='ID', value=str(user.id)) embed.add_field(name='Created at', value=formatted_datetime(user.created_at, TimestampFormat.Relative)) if isinstance(user, discord.Member): embed.add_field(name='Joined at', value=formatted_datetime(user.joined_at, TimestampFormat.Relative)) max_roles = 20 embed.add_field(name='Roles', value=(' '.join([r.mention for r in reversed(user.roles[(- max_roles):])]) + (f' and {(len(user.roles) - max_roles)} more' if (len(user.roles) > max_roles) else '')), inline=False) (await ctx.send(embed=embed))
Shows info of a user. Using the username might not always work. In those cases use the user id
cogs/utils.py
userinfo
s0hv/Not-a-bot
6
python
@command(aliases=['who', 'user', 'whois']) @cooldown(7, 10, BucketType.guild) async def userinfo(self, ctx: Context, *, user: Union[(discord.Member, discord.User)]): '\n Shows info of a user.\n Using the username might not always work. In those cases use the user id\n ' embed = discord.Embed(title=str(user)) embed.set_thumbnail(url=get_avatar(user)) embed.add_field(name='Username', value=str(user)) embed.add_field(name='ID', value=str(user.id)) embed.add_field(name='Created at', value=formatted_datetime(user.created_at, TimestampFormat.Relative)) if isinstance(user, discord.Member): embed.add_field(name='Joined at', value=formatted_datetime(user.joined_at, TimestampFormat.Relative)) max_roles = 20 embed.add_field(name='Roles', value=(' '.join([r.mention for r in reversed(user.roles[(- max_roles):])]) + (f' and {(len(user.roles) - max_roles)} more' if (len(user.roles) > max_roles) else )), inline=False) (await ctx.send(embed=embed))
@command(aliases=['who', 'user', 'whois']) @cooldown(7, 10, BucketType.guild) async def userinfo(self, ctx: Context, *, user: Union[(discord.Member, discord.User)]): '\n Shows info of a user.\n Using the username might not always work. In those cases use the user id\n ' embed = discord.Embed(title=str(user)) embed.set_thumbnail(url=get_avatar(user)) embed.add_field(name='Username', value=str(user)) embed.add_field(name='ID', value=str(user.id)) embed.add_field(name='Created at', value=formatted_datetime(user.created_at, TimestampFormat.Relative)) if isinstance(user, discord.Member): embed.add_field(name='Joined at', value=formatted_datetime(user.joined_at, TimestampFormat.Relative)) max_roles = 20 embed.add_field(name='Roles', value=(' '.join([r.mention for r in reversed(user.roles[(- max_roles):])]) + (f' and {(len(user.roles) - max_roles)} more' if (len(user.roles) > max_roles) else )), inline=False) (await ctx.send(embed=embed))<|docstring|>Shows info of a user. Using the username might not always work. In those cases use the user id<|endoftext|>
ad792e053657033fe4c09376663cc16f4845a631e212e54d70ac38c4e25662f1
def get_matrix_compression_object(hparams, global_step=None, sparsity=None): 'Returns a pruning/compression object.\n\n Args:\n hparams: Pruning spec as defined in pruing.py;\n global_step: A tensorflow variable that is used for scheduling\n pruning/compression;\n sparsity: A tensorflow scalar variable storing the sparsity.\n\n Returns:\n A Pruning or compression_lib.compression_op.ApplyCompression object.\n ' if (global_step is None): train_global_step = tf.train.get_global_step() if (train_global_step is None): global_step = 0 else: global_step = tf.cast(train_global_step, tf.int32) if (hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return pruning.Pruning(hparams, global_step, sparsity) else: return compression_wrapper.get_apply_compression(hparams, global_step=global_step)
Returns a pruning/compression object. Args: hparams: Pruning spec as defined in pruing.py; global_step: A tensorflow variable that is used for scheduling pruning/compression; sparsity: A tensorflow scalar variable storing the sparsity. Returns: A Pruning or compression_lib.compression_op.ApplyCompression object.
model_pruning/python/pruning_interface.py
get_matrix_compression_object
wy-go/google-research
23,901
python
def get_matrix_compression_object(hparams, global_step=None, sparsity=None): 'Returns a pruning/compression object.\n\n Args:\n hparams: Pruning spec as defined in pruing.py;\n global_step: A tensorflow variable that is used for scheduling\n pruning/compression;\n sparsity: A tensorflow scalar variable storing the sparsity.\n\n Returns:\n A Pruning or compression_lib.compression_op.ApplyCompression object.\n ' if (global_step is None): train_global_step = tf.train.get_global_step() if (train_global_step is None): global_step = 0 else: global_step = tf.cast(train_global_step, tf.int32) if (hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return pruning.Pruning(hparams, global_step, sparsity) else: return compression_wrapper.get_apply_compression(hparams, global_step=global_step)
def get_matrix_compression_object(hparams, global_step=None, sparsity=None): 'Returns a pruning/compression object.\n\n Args:\n hparams: Pruning spec as defined in pruing.py;\n global_step: A tensorflow variable that is used for scheduling\n pruning/compression;\n sparsity: A tensorflow scalar variable storing the sparsity.\n\n Returns:\n A Pruning or compression_lib.compression_op.ApplyCompression object.\n ' if (global_step is None): train_global_step = tf.train.get_global_step() if (train_global_step is None): global_step = 0 else: global_step = tf.cast(train_global_step, tf.int32) if (hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return pruning.Pruning(hparams, global_step, sparsity) else: return compression_wrapper.get_apply_compression(hparams, global_step=global_step)<|docstring|>Returns a pruning/compression object. Args: hparams: Pruning spec as defined in pruing.py; global_step: A tensorflow variable that is used for scheduling pruning/compression; sparsity: A tensorflow scalar variable storing the sparsity. Returns: A Pruning or compression_lib.compression_op.ApplyCompression object.<|endoftext|>
7fa363700beb0705ff5b3d1c1969e3eab7c01f871a8f80c56bded60d2db7c44f
def apply_matrix_compression(matrix_compression_obj, weight, scope='', spec=None): "Apply pruning/compression to a weight tensor.\n\n For pruning, this is equivalent to apply_mask; for compression, this is\n equivalent to apply_compression.\n\n Args:\n matrix_compression_obj: A Pruning or\n compression_lib.compression_op.ApplyCompression object;\n weight: input weight tensor;\n scope: the current variable scope. Defaults to ''.\n spec: spec to use for the compression op.\n\n Returns:\n A TF node that represents the masked weight tensor if pruning_indicator is\n True, and the compressed version of weight tensor if pruning_indicator is\n False.\n " if isinstance(matrix_compression_obj, pruning.Pruning): prune_option = matrix_compression_obj.matrix_compression_spec.prune_option return pruning.apply_mask(x=weight, scope=scope, prune_option=prune_option) else: compressed_matrix = matrix_compression_obj.apply_compression(weight, scope, spec) hparams = matrix_compression_obj.get_spec() if hparams.use_collection: tf.add_to_collection(UPDATE_OP_COLLECTION, matrix_compression_obj.all_update_op()) return compressed_matrix
Apply pruning/compression to a weight tensor. For pruning, this is equivalent to apply_mask; for compression, this is equivalent to apply_compression. Args: matrix_compression_obj: A Pruning or compression_lib.compression_op.ApplyCompression object; weight: input weight tensor; scope: the current variable scope. Defaults to ''. spec: spec to use for the compression op. Returns: A TF node that represents the masked weight tensor if pruning_indicator is True, and the compressed version of weight tensor if pruning_indicator is False.
model_pruning/python/pruning_interface.py
apply_matrix_compression
wy-go/google-research
23,901
python
def apply_matrix_compression(matrix_compression_obj, weight, scope=, spec=None): "Apply pruning/compression to a weight tensor.\n\n For pruning, this is equivalent to apply_mask; for compression, this is\n equivalent to apply_compression.\n\n Args:\n matrix_compression_obj: A Pruning or\n compression_lib.compression_op.ApplyCompression object;\n weight: input weight tensor;\n scope: the current variable scope. Defaults to .\n spec: spec to use for the compression op.\n\n Returns:\n A TF node that represents the masked weight tensor if pruning_indicator is\n True, and the compressed version of weight tensor if pruning_indicator is\n False.\n " if isinstance(matrix_compression_obj, pruning.Pruning): prune_option = matrix_compression_obj.matrix_compression_spec.prune_option return pruning.apply_mask(x=weight, scope=scope, prune_option=prune_option) else: compressed_matrix = matrix_compression_obj.apply_compression(weight, scope, spec) hparams = matrix_compression_obj.get_spec() if hparams.use_collection: tf.add_to_collection(UPDATE_OP_COLLECTION, matrix_compression_obj.all_update_op()) return compressed_matrix
def apply_matrix_compression(matrix_compression_obj, weight, scope=, spec=None): "Apply pruning/compression to a weight tensor.\n\n For pruning, this is equivalent to apply_mask; for compression, this is\n equivalent to apply_compression.\n\n Args:\n matrix_compression_obj: A Pruning or\n compression_lib.compression_op.ApplyCompression object;\n weight: input weight tensor;\n scope: the current variable scope. Defaults to .\n spec: spec to use for the compression op.\n\n Returns:\n A TF node that represents the masked weight tensor if pruning_indicator is\n True, and the compressed version of weight tensor if pruning_indicator is\n False.\n " if isinstance(matrix_compression_obj, pruning.Pruning): prune_option = matrix_compression_obj.matrix_compression_spec.prune_option return pruning.apply_mask(x=weight, scope=scope, prune_option=prune_option) else: compressed_matrix = matrix_compression_obj.apply_compression(weight, scope, spec) hparams = matrix_compression_obj.get_spec() if hparams.use_collection: tf.add_to_collection(UPDATE_OP_COLLECTION, matrix_compression_obj.all_update_op()) return compressed_matrix<|docstring|>Apply pruning/compression to a weight tensor. For pruning, this is equivalent to apply_mask; for compression, this is equivalent to apply_compression. Args: matrix_compression_obj: A Pruning or compression_lib.compression_op.ApplyCompression object; weight: input weight tensor; scope: the current variable scope. Defaults to ''. spec: spec to use for the compression op. Returns: A TF node that represents the masked weight tensor if pruning_indicator is True, and the compressed version of weight tensor if pruning_indicator is False.<|endoftext|>
4ddacc8092317aaa536b24da6adb99645ea6941166426cd809c860ee526a24c5
def apply_customized_matrix_compression(matrix_compression_obj, weight_params_fn, weight_init_obj, layer_obj, weight_name, weight_shape, weight_dtype, scope_name='pruning_interface', spec=None): 'Apply pruning or compression to a lingvo layer.\n\n This provides a unified interface to perform pruning or compression for a\n lingvo layer.\n\n Args:\n matrix_compression_obj: A Pruning or\n compression_lib.lingvo_compression_op.ApplyCompression object;\n weight_params_fn: functional handle to create model parameters;\n weight_init_obj: a weight initialization object;\n layer_obj: a layer object in the lingvo package, weight matrix of this\n layer is pruned or compressed;\n weight_name: name of the tensor that is compressed, str;\n weight_shape: shape of the weight matrix;\n weight_dtype: data type of the weight matrix;\n scope_name: TensorFlow scope for creating relavant variables.\n spec: spec to use for the compression op.\n\n Returns:\n None.\n ' if isinstance(matrix_compression_obj, pruning.Pruning): prune_option = matrix_compression_obj.matrix_compression_spec.prune_option with tf.variable_scope(scope_name): mask_pc = weight_params_fn(weight_shape, weight_init_obj.Constant(1.0), weight_dtype) threshold_pc = weight_params_fn([], weight_init_obj.Constant(0.0), tf.float32) layer_obj.CreateVariable('mask', mask_pc, trainable=False) layer_obj.CreateVariable('threshold', threshold_pc, trainable=False) if (layer_obj.vars.mask not in tf.get_collection(pruning.MASK_COLLECTION)): tf.add_to_collection(pruning.WEIGHT_COLLECTION, getattr(layer_obj.vars, weight_name)) tf.add_to_collection(pruning.MASK_COLLECTION, layer_obj.vars.mask) tf.add_to_collection(pruning.THRESHOLD_COLLECTION, layer_obj.vars.threshold) if (prune_option in ['first_order_gradient', 'second_order_gradient']): grad_pc = weight_params_fn(weight_shape, weight_init_obj.Constant(0.0), weight_dtype) layer_obj.CreateVariable('gradient', grad_pc, trainable=False) layer_obj.CreateVariable('old_weight', grad_pc, trainable=False) layer_obj.CreateVariable('old_old_weight', grad_pc, trainable=False) tf.add_to_collection(pruning.WEIGHT_GRADIENT_COLLECTION, layer_obj.vars.gradient) tf.add_to_collection(pruning.OLD_WEIGHT_COLLECTION, layer_obj.vars.old_weight) tf.add_to_collection(pruning.OLD_OLD_WEIGHT_COLLECTION, layer_obj.vars.old_old_weight) else: _ = matrix_compression_obj.customized_apply_compression(getattr(layer_obj.vars, weight_name), layer_obj, weight_params_fn, weight_init_obj, scope=scope_name, spec=spec) hparams = matrix_compression_obj.get_spec() if hparams.use_collection: tf.add_to_collection(UPDATE_OP_COLLECTION, matrix_compression_obj.all_update_op())
Apply pruning or compression to a lingvo layer. This provides a unified interface to perform pruning or compression for a lingvo layer. Args: matrix_compression_obj: A Pruning or compression_lib.lingvo_compression_op.ApplyCompression object; weight_params_fn: functional handle to create model parameters; weight_init_obj: a weight initialization object; layer_obj: a layer object in the lingvo package, weight matrix of this layer is pruned or compressed; weight_name: name of the tensor that is compressed, str; weight_shape: shape of the weight matrix; weight_dtype: data type of the weight matrix; scope_name: TensorFlow scope for creating relavant variables. spec: spec to use for the compression op. Returns: None.
model_pruning/python/pruning_interface.py
apply_customized_matrix_compression
wy-go/google-research
23,901
python
def apply_customized_matrix_compression(matrix_compression_obj, weight_params_fn, weight_init_obj, layer_obj, weight_name, weight_shape, weight_dtype, scope_name='pruning_interface', spec=None): 'Apply pruning or compression to a lingvo layer.\n\n This provides a unified interface to perform pruning or compression for a\n lingvo layer.\n\n Args:\n matrix_compression_obj: A Pruning or\n compression_lib.lingvo_compression_op.ApplyCompression object;\n weight_params_fn: functional handle to create model parameters;\n weight_init_obj: a weight initialization object;\n layer_obj: a layer object in the lingvo package, weight matrix of this\n layer is pruned or compressed;\n weight_name: name of the tensor that is compressed, str;\n weight_shape: shape of the weight matrix;\n weight_dtype: data type of the weight matrix;\n scope_name: TensorFlow scope for creating relavant variables.\n spec: spec to use for the compression op.\n\n Returns:\n None.\n ' if isinstance(matrix_compression_obj, pruning.Pruning): prune_option = matrix_compression_obj.matrix_compression_spec.prune_option with tf.variable_scope(scope_name): mask_pc = weight_params_fn(weight_shape, weight_init_obj.Constant(1.0), weight_dtype) threshold_pc = weight_params_fn([], weight_init_obj.Constant(0.0), tf.float32) layer_obj.CreateVariable('mask', mask_pc, trainable=False) layer_obj.CreateVariable('threshold', threshold_pc, trainable=False) if (layer_obj.vars.mask not in tf.get_collection(pruning.MASK_COLLECTION)): tf.add_to_collection(pruning.WEIGHT_COLLECTION, getattr(layer_obj.vars, weight_name)) tf.add_to_collection(pruning.MASK_COLLECTION, layer_obj.vars.mask) tf.add_to_collection(pruning.THRESHOLD_COLLECTION, layer_obj.vars.threshold) if (prune_option in ['first_order_gradient', 'second_order_gradient']): grad_pc = weight_params_fn(weight_shape, weight_init_obj.Constant(0.0), weight_dtype) layer_obj.CreateVariable('gradient', grad_pc, trainable=False) layer_obj.CreateVariable('old_weight', grad_pc, trainable=False) layer_obj.CreateVariable('old_old_weight', grad_pc, trainable=False) tf.add_to_collection(pruning.WEIGHT_GRADIENT_COLLECTION, layer_obj.vars.gradient) tf.add_to_collection(pruning.OLD_WEIGHT_COLLECTION, layer_obj.vars.old_weight) tf.add_to_collection(pruning.OLD_OLD_WEIGHT_COLLECTION, layer_obj.vars.old_old_weight) else: _ = matrix_compression_obj.customized_apply_compression(getattr(layer_obj.vars, weight_name), layer_obj, weight_params_fn, weight_init_obj, scope=scope_name, spec=spec) hparams = matrix_compression_obj.get_spec() if hparams.use_collection: tf.add_to_collection(UPDATE_OP_COLLECTION, matrix_compression_obj.all_update_op())
def apply_customized_matrix_compression(matrix_compression_obj, weight_params_fn, weight_init_obj, layer_obj, weight_name, weight_shape, weight_dtype, scope_name='pruning_interface', spec=None): 'Apply pruning or compression to a lingvo layer.\n\n This provides a unified interface to perform pruning or compression for a\n lingvo layer.\n\n Args:\n matrix_compression_obj: A Pruning or\n compression_lib.lingvo_compression_op.ApplyCompression object;\n weight_params_fn: functional handle to create model parameters;\n weight_init_obj: a weight initialization object;\n layer_obj: a layer object in the lingvo package, weight matrix of this\n layer is pruned or compressed;\n weight_name: name of the tensor that is compressed, str;\n weight_shape: shape of the weight matrix;\n weight_dtype: data type of the weight matrix;\n scope_name: TensorFlow scope for creating relavant variables.\n spec: spec to use for the compression op.\n\n Returns:\n None.\n ' if isinstance(matrix_compression_obj, pruning.Pruning): prune_option = matrix_compression_obj.matrix_compression_spec.prune_option with tf.variable_scope(scope_name): mask_pc = weight_params_fn(weight_shape, weight_init_obj.Constant(1.0), weight_dtype) threshold_pc = weight_params_fn([], weight_init_obj.Constant(0.0), tf.float32) layer_obj.CreateVariable('mask', mask_pc, trainable=False) layer_obj.CreateVariable('threshold', threshold_pc, trainable=False) if (layer_obj.vars.mask not in tf.get_collection(pruning.MASK_COLLECTION)): tf.add_to_collection(pruning.WEIGHT_COLLECTION, getattr(layer_obj.vars, weight_name)) tf.add_to_collection(pruning.MASK_COLLECTION, layer_obj.vars.mask) tf.add_to_collection(pruning.THRESHOLD_COLLECTION, layer_obj.vars.threshold) if (prune_option in ['first_order_gradient', 'second_order_gradient']): grad_pc = weight_params_fn(weight_shape, weight_init_obj.Constant(0.0), weight_dtype) layer_obj.CreateVariable('gradient', grad_pc, trainable=False) layer_obj.CreateVariable('old_weight', grad_pc, trainable=False) layer_obj.CreateVariable('old_old_weight', grad_pc, trainable=False) tf.add_to_collection(pruning.WEIGHT_GRADIENT_COLLECTION, layer_obj.vars.gradient) tf.add_to_collection(pruning.OLD_WEIGHT_COLLECTION, layer_obj.vars.old_weight) tf.add_to_collection(pruning.OLD_OLD_WEIGHT_COLLECTION, layer_obj.vars.old_old_weight) else: _ = matrix_compression_obj.customized_apply_compression(getattr(layer_obj.vars, weight_name), layer_obj, weight_params_fn, weight_init_obj, scope=scope_name, spec=spec) hparams = matrix_compression_obj.get_spec() if hparams.use_collection: tf.add_to_collection(UPDATE_OP_COLLECTION, matrix_compression_obj.all_update_op())<|docstring|>Apply pruning or compression to a lingvo layer. This provides a unified interface to perform pruning or compression for a lingvo layer. Args: matrix_compression_obj: A Pruning or compression_lib.lingvo_compression_op.ApplyCompression object; weight_params_fn: functional handle to create model parameters; weight_init_obj: a weight initialization object; layer_obj: a layer object in the lingvo package, weight matrix of this layer is pruned or compressed; weight_name: name of the tensor that is compressed, str; weight_shape: shape of the weight matrix; weight_dtype: data type of the weight matrix; scope_name: TensorFlow scope for creating relavant variables. spec: spec to use for the compression op. Returns: None.<|endoftext|>
80dab2101228da20dbdc67f075245717b9ba8c707d9720d845ace510b9b2b712
def apply_pruning(pruning_obj, pruning_hparams, weight_params_fn, weight_init_obj, layerobj, wm_pc, dtype): 'Apply pruning to an lingvo layer.\n\n Args:\n pruning_obj: a Pruning object;\n pruning_hparams: a Pruning hparams object;\n weight_params_fn: functional handle to create model parameters;\n weight_init_obj: a weight initialization object;\n layerobj: a layer object in the lingvo package;\n wm_pc: weight matrix;\n dtype: data type of the weight matrix.\n\n Returns:\n pruning_obj as passed in or a compression_obj.\n ' if (pruning_hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): mask_pc = weight_params_fn(wm_pc.shape, weight_init_obj.Constant(1.0), dtype) threshold_pc = weight_params_fn([], weight_init_obj.Constant(0.0), tf.float32) layerobj.CreateVariable('mask', mask_pc, trainable=False) layerobj.CreateVariable('threshold', threshold_pc, trainable=False) if (layerobj.vars.mask not in tf.get_collection(pruning.MASK_COLLECTION)): tf.add_to_collection(pruning.WEIGHT_COLLECTION, layerobj.vars.wm) tf.add_to_collection(pruning.MASK_COLLECTION, layerobj.vars.mask) tf.add_to_collection(pruning.THRESHOLD_COLLECTION, layerobj.vars.threshold) return pruning_obj else: return pruning_obj
Apply pruning to an lingvo layer. Args: pruning_obj: a Pruning object; pruning_hparams: a Pruning hparams object; weight_params_fn: functional handle to create model parameters; weight_init_obj: a weight initialization object; layerobj: a layer object in the lingvo package; wm_pc: weight matrix; dtype: data type of the weight matrix. Returns: pruning_obj as passed in or a compression_obj.
model_pruning/python/pruning_interface.py
apply_pruning
wy-go/google-research
23,901
python
def apply_pruning(pruning_obj, pruning_hparams, weight_params_fn, weight_init_obj, layerobj, wm_pc, dtype): 'Apply pruning to an lingvo layer.\n\n Args:\n pruning_obj: a Pruning object;\n pruning_hparams: a Pruning hparams object;\n weight_params_fn: functional handle to create model parameters;\n weight_init_obj: a weight initialization object;\n layerobj: a layer object in the lingvo package;\n wm_pc: weight matrix;\n dtype: data type of the weight matrix.\n\n Returns:\n pruning_obj as passed in or a compression_obj.\n ' if (pruning_hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): mask_pc = weight_params_fn(wm_pc.shape, weight_init_obj.Constant(1.0), dtype) threshold_pc = weight_params_fn([], weight_init_obj.Constant(0.0), tf.float32) layerobj.CreateVariable('mask', mask_pc, trainable=False) layerobj.CreateVariable('threshold', threshold_pc, trainable=False) if (layerobj.vars.mask not in tf.get_collection(pruning.MASK_COLLECTION)): tf.add_to_collection(pruning.WEIGHT_COLLECTION, layerobj.vars.wm) tf.add_to_collection(pruning.MASK_COLLECTION, layerobj.vars.mask) tf.add_to_collection(pruning.THRESHOLD_COLLECTION, layerobj.vars.threshold) return pruning_obj else: return pruning_obj
def apply_pruning(pruning_obj, pruning_hparams, weight_params_fn, weight_init_obj, layerobj, wm_pc, dtype): 'Apply pruning to an lingvo layer.\n\n Args:\n pruning_obj: a Pruning object;\n pruning_hparams: a Pruning hparams object;\n weight_params_fn: functional handle to create model parameters;\n weight_init_obj: a weight initialization object;\n layerobj: a layer object in the lingvo package;\n wm_pc: weight matrix;\n dtype: data type of the weight matrix.\n\n Returns:\n pruning_obj as passed in or a compression_obj.\n ' if (pruning_hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): mask_pc = weight_params_fn(wm_pc.shape, weight_init_obj.Constant(1.0), dtype) threshold_pc = weight_params_fn([], weight_init_obj.Constant(0.0), tf.float32) layerobj.CreateVariable('mask', mask_pc, trainable=False) layerobj.CreateVariable('threshold', threshold_pc, trainable=False) if (layerobj.vars.mask not in tf.get_collection(pruning.MASK_COLLECTION)): tf.add_to_collection(pruning.WEIGHT_COLLECTION, layerobj.vars.wm) tf.add_to_collection(pruning.MASK_COLLECTION, layerobj.vars.mask) tf.add_to_collection(pruning.THRESHOLD_COLLECTION, layerobj.vars.threshold) return pruning_obj else: return pruning_obj<|docstring|>Apply pruning to an lingvo layer. Args: pruning_obj: a Pruning object; pruning_hparams: a Pruning hparams object; weight_params_fn: functional handle to create model parameters; weight_init_obj: a weight initialization object; layerobj: a layer object in the lingvo package; wm_pc: weight matrix; dtype: data type of the weight matrix. Returns: pruning_obj as passed in or a compression_obj.<|endoftext|>
8b62cfdba3f52b5b4eec61a007943cccc5385a658b4dae0e3ddc64968e143e5c
def get_pruning_update(pruning_obj, pruning_hparams): "Return pruning mask update op.\n\n Note: clients are encouraged to use get_matrix_compression_update_op instead,\n which has the same functionality as this function, but supports compression\n too.\n\n Args:\n pruning_obj: a Pruning object;\n pruning_hparams: a Pruning hparams object.\n\n Returns:\n a mask_update_op if the prune_option of the pruning_obj is 'weight',\n 'first_order_gradient', or 'second_order_gradient'.\n\n Raises:\n NotImplementedError if the prune_option of the pruning_obj is not 'weight',\n 'first_order_gradient', or 'second_order_gradient'.\n " if (pruning_hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return pruning_obj.conditional_mask_update_op() else: raise NotImplementedError()
Return pruning mask update op. Note: clients are encouraged to use get_matrix_compression_update_op instead, which has the same functionality as this function, but supports compression too. Args: pruning_obj: a Pruning object; pruning_hparams: a Pruning hparams object. Returns: a mask_update_op if the prune_option of the pruning_obj is 'weight', 'first_order_gradient', or 'second_order_gradient'. Raises: NotImplementedError if the prune_option of the pruning_obj is not 'weight', 'first_order_gradient', or 'second_order_gradient'.
model_pruning/python/pruning_interface.py
get_pruning_update
wy-go/google-research
23,901
python
def get_pruning_update(pruning_obj, pruning_hparams): "Return pruning mask update op.\n\n Note: clients are encouraged to use get_matrix_compression_update_op instead,\n which has the same functionality as this function, but supports compression\n too.\n\n Args:\n pruning_obj: a Pruning object;\n pruning_hparams: a Pruning hparams object.\n\n Returns:\n a mask_update_op if the prune_option of the pruning_obj is 'weight',\n 'first_order_gradient', or 'second_order_gradient'.\n\n Raises:\n NotImplementedError if the prune_option of the pruning_obj is not 'weight',\n 'first_order_gradient', or 'second_order_gradient'.\n " if (pruning_hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return pruning_obj.conditional_mask_update_op() else: raise NotImplementedError()
def get_pruning_update(pruning_obj, pruning_hparams): "Return pruning mask update op.\n\n Note: clients are encouraged to use get_matrix_compression_update_op instead,\n which has the same functionality as this function, but supports compression\n too.\n\n Args:\n pruning_obj: a Pruning object;\n pruning_hparams: a Pruning hparams object.\n\n Returns:\n a mask_update_op if the prune_option of the pruning_obj is 'weight',\n 'first_order_gradient', or 'second_order_gradient'.\n\n Raises:\n NotImplementedError if the prune_option of the pruning_obj is not 'weight',\n 'first_order_gradient', or 'second_order_gradient'.\n " if (pruning_hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return pruning_obj.conditional_mask_update_op() else: raise NotImplementedError()<|docstring|>Return pruning mask update op. Note: clients are encouraged to use get_matrix_compression_update_op instead, which has the same functionality as this function, but supports compression too. Args: pruning_obj: a Pruning object; pruning_hparams: a Pruning hparams object. Returns: a mask_update_op if the prune_option of the pruning_obj is 'weight', 'first_order_gradient', or 'second_order_gradient'. Raises: NotImplementedError if the prune_option of the pruning_obj is not 'weight', 'first_order_gradient', or 'second_order_gradient'.<|endoftext|>
8c9f2a4127a407b7a1641acae9acab757145255ac2c263ffd94e709a6d12bb5a
def get_matrix_compression_update_op(matrix_compression_obj): "Return pruning/compression update op.\n\n For pruning, this returns a contional_mask_update_op; for compression, this\n returns an ApplyCompression.all_update_op.\n\n Args:\n matrix_compression_obj: a Pruning or a compression_lib.ApplyCompression\n object;\n\n Returns:\n a mask_update_op if the prune_option of the pruning_obj is 'weight',\n 'first_order_gradient', or 'second_order_gradient'; or an\n ApplyCompression.all_update_op otherwise.\n\n Raises:\n NotImplementedError if the prune_option of the pruning_obj is not 'weight',\n 'first_order_gradient', or 'second_order_gradient' and update_option is not\n 0; in this case, the compression should be applied by calling\n compression_obj.run_update_step(session=session).\n " hparams = matrix_compression_obj.get_spec() if (hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return matrix_compression_obj.conditional_mask_update_op() elif ((hparams.update_option == UpdateOptions.TF_UPDATE) or (hparams.update_option == UpdateOptions.TF_AND_PYTHON_UPDATE)): if hparams.use_collection: update_ops = tf.get_collection(UPDATE_OP_COLLECTION) return tf.group(*update_ops) else: return matrix_compression_obj.all_update_op() else: raise NotImplementedError()
Return pruning/compression update op. For pruning, this returns a contional_mask_update_op; for compression, this returns an ApplyCompression.all_update_op. Args: matrix_compression_obj: a Pruning or a compression_lib.ApplyCompression object; Returns: a mask_update_op if the prune_option of the pruning_obj is 'weight', 'first_order_gradient', or 'second_order_gradient'; or an ApplyCompression.all_update_op otherwise. Raises: NotImplementedError if the prune_option of the pruning_obj is not 'weight', 'first_order_gradient', or 'second_order_gradient' and update_option is not 0; in this case, the compression should be applied by calling compression_obj.run_update_step(session=session).
model_pruning/python/pruning_interface.py
get_matrix_compression_update_op
wy-go/google-research
23,901
python
def get_matrix_compression_update_op(matrix_compression_obj): "Return pruning/compression update op.\n\n For pruning, this returns a contional_mask_update_op; for compression, this\n returns an ApplyCompression.all_update_op.\n\n Args:\n matrix_compression_obj: a Pruning or a compression_lib.ApplyCompression\n object;\n\n Returns:\n a mask_update_op if the prune_option of the pruning_obj is 'weight',\n 'first_order_gradient', or 'second_order_gradient'; or an\n ApplyCompression.all_update_op otherwise.\n\n Raises:\n NotImplementedError if the prune_option of the pruning_obj is not 'weight',\n 'first_order_gradient', or 'second_order_gradient' and update_option is not\n 0; in this case, the compression should be applied by calling\n compression_obj.run_update_step(session=session).\n " hparams = matrix_compression_obj.get_spec() if (hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return matrix_compression_obj.conditional_mask_update_op() elif ((hparams.update_option == UpdateOptions.TF_UPDATE) or (hparams.update_option == UpdateOptions.TF_AND_PYTHON_UPDATE)): if hparams.use_collection: update_ops = tf.get_collection(UPDATE_OP_COLLECTION) return tf.group(*update_ops) else: return matrix_compression_obj.all_update_op() else: raise NotImplementedError()
def get_matrix_compression_update_op(matrix_compression_obj): "Return pruning/compression update op.\n\n For pruning, this returns a contional_mask_update_op; for compression, this\n returns an ApplyCompression.all_update_op.\n\n Args:\n matrix_compression_obj: a Pruning or a compression_lib.ApplyCompression\n object;\n\n Returns:\n a mask_update_op if the prune_option of the pruning_obj is 'weight',\n 'first_order_gradient', or 'second_order_gradient'; or an\n ApplyCompression.all_update_op otherwise.\n\n Raises:\n NotImplementedError if the prune_option of the pruning_obj is not 'weight',\n 'first_order_gradient', or 'second_order_gradient' and update_option is not\n 0; in this case, the compression should be applied by calling\n compression_obj.run_update_step(session=session).\n " hparams = matrix_compression_obj.get_spec() if (hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return matrix_compression_obj.conditional_mask_update_op() elif ((hparams.update_option == UpdateOptions.TF_UPDATE) or (hparams.update_option == UpdateOptions.TF_AND_PYTHON_UPDATE)): if hparams.use_collection: update_ops = tf.get_collection(UPDATE_OP_COLLECTION) return tf.group(*update_ops) else: return matrix_compression_obj.all_update_op() else: raise NotImplementedError()<|docstring|>Return pruning/compression update op. For pruning, this returns a contional_mask_update_op; for compression, this returns an ApplyCompression.all_update_op. Args: matrix_compression_obj: a Pruning or a compression_lib.ApplyCompression object; Returns: a mask_update_op if the prune_option of the pruning_obj is 'weight', 'first_order_gradient', or 'second_order_gradient'; or an ApplyCompression.all_update_op otherwise. Raises: NotImplementedError if the prune_option of the pruning_obj is not 'weight', 'first_order_gradient', or 'second_order_gradient' and update_option is not 0; in this case, the compression should be applied by calling compression_obj.run_update_step(session=session).<|endoftext|>
254670ed9b5d7345cccded65f7271ea2b5dc1189b51780671f552fd7fc77b179
def run_update_step(matrix_compression_obj, session, step_number=None): 'This the update step that needs to be called periodically.' hparams = matrix_compression_obj.get_spec() if ((hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']) or (hparams.update_option == UpdateOptions.TF_UPDATE)): update_op = get_matrix_compression_update_op(matrix_compression_obj) session.run(update_op) else: matrix_compression_obj.run_update_step(session, step_number)
This the update step that needs to be called periodically.
model_pruning/python/pruning_interface.py
run_update_step
wy-go/google-research
23,901
python
def run_update_step(matrix_compression_obj, session, step_number=None): hparams = matrix_compression_obj.get_spec() if ((hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']) or (hparams.update_option == UpdateOptions.TF_UPDATE)): update_op = get_matrix_compression_update_op(matrix_compression_obj) session.run(update_op) else: matrix_compression_obj.run_update_step(session, step_number)
def run_update_step(matrix_compression_obj, session, step_number=None): hparams = matrix_compression_obj.get_spec() if ((hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']) or (hparams.update_option == UpdateOptions.TF_UPDATE)): update_op = get_matrix_compression_update_op(matrix_compression_obj) session.run(update_op) else: matrix_compression_obj.run_update_step(session, step_number)<|docstring|>This the update step that needs to be called periodically.<|endoftext|>
196f1d2da5a06bd25065fb1bdfba91d4aec6fc7819286d78eb44dc0695b4600c
def add_compression_summaries(matrix_compression_obj): 'Add compression summaries.\n\n Args:\n matrix_compression_obj: a Pruning or a compression_lib.ApplyCompression\n object.\n\n Returns:\n None\n ' if isinstance(matrix_compression_obj, pruning.Pruning): matrix_compression_obj.add_pruning_summaries()
Add compression summaries. Args: matrix_compression_obj: a Pruning or a compression_lib.ApplyCompression object. Returns: None
model_pruning/python/pruning_interface.py
add_compression_summaries
wy-go/google-research
23,901
python
def add_compression_summaries(matrix_compression_obj): 'Add compression summaries.\n\n Args:\n matrix_compression_obj: a Pruning or a compression_lib.ApplyCompression\n object.\n\n Returns:\n None\n ' if isinstance(matrix_compression_obj, pruning.Pruning): matrix_compression_obj.add_pruning_summaries()
def add_compression_summaries(matrix_compression_obj): 'Add compression summaries.\n\n Args:\n matrix_compression_obj: a Pruning or a compression_lib.ApplyCompression\n object.\n\n Returns:\n None\n ' if isinstance(matrix_compression_obj, pruning.Pruning): matrix_compression_obj.add_pruning_summaries()<|docstring|>Add compression summaries. Args: matrix_compression_obj: a Pruning or a compression_lib.ApplyCompression object. Returns: None<|endoftext|>
90317d5481594bd13799798cfc691f5b47387af9cb19b8a414c3623fabb881c8
def flat_embedding_lookup(emb_table, flat_ids, vocab_size, matmul_axis=1, fprop_mode='matmul'): "Performs embedding lookup operation.\n\n Args:\n emb_table: tf.Tensor containing the embedding vectors.\n flat_ids: tf.Tensor of shape (number_ids,).\n vocab_size: vocabulary size of the embedding table, int.\n matmul_axis: the axis of flat_ids that is used for matmul, int.\n fprop_mode: embedding lookup option, should be 'matmul' or 'gather'.\n\n Returns:\n Embedding lookup result.\n " if (fprop_mode == 'matmul'): lhs = tf.equal(tf.expand_dims(flat_ids, matmul_axis), tf.range(vocab_size, dtype=flat_ids.dtype)) return tf.matmul(tf.cast(lhs, emb_table.dtype), emb_table) elif (fprop_mode == 'gather'): return tf.nn.embedding_lookup(emb_table, flat_ids) else: raise ValueError('flat_embedding_lookup(): fprop_mode {} is not supported.'.format(fprop_mode))
Performs embedding lookup operation. Args: emb_table: tf.Tensor containing the embedding vectors. flat_ids: tf.Tensor of shape (number_ids,). vocab_size: vocabulary size of the embedding table, int. matmul_axis: the axis of flat_ids that is used for matmul, int. fprop_mode: embedding lookup option, should be 'matmul' or 'gather'. Returns: Embedding lookup result.
model_pruning/python/pruning_interface.py
flat_embedding_lookup
wy-go/google-research
23,901
python
def flat_embedding_lookup(emb_table, flat_ids, vocab_size, matmul_axis=1, fprop_mode='matmul'): "Performs embedding lookup operation.\n\n Args:\n emb_table: tf.Tensor containing the embedding vectors.\n flat_ids: tf.Tensor of shape (number_ids,).\n vocab_size: vocabulary size of the embedding table, int.\n matmul_axis: the axis of flat_ids that is used for matmul, int.\n fprop_mode: embedding lookup option, should be 'matmul' or 'gather'.\n\n Returns:\n Embedding lookup result.\n " if (fprop_mode == 'matmul'): lhs = tf.equal(tf.expand_dims(flat_ids, matmul_axis), tf.range(vocab_size, dtype=flat_ids.dtype)) return tf.matmul(tf.cast(lhs, emb_table.dtype), emb_table) elif (fprop_mode == 'gather'): return tf.nn.embedding_lookup(emb_table, flat_ids) else: raise ValueError('flat_embedding_lookup(): fprop_mode {} is not supported.'.format(fprop_mode))
def flat_embedding_lookup(emb_table, flat_ids, vocab_size, matmul_axis=1, fprop_mode='matmul'): "Performs embedding lookup operation.\n\n Args:\n emb_table: tf.Tensor containing the embedding vectors.\n flat_ids: tf.Tensor of shape (number_ids,).\n vocab_size: vocabulary size of the embedding table, int.\n matmul_axis: the axis of flat_ids that is used for matmul, int.\n fprop_mode: embedding lookup option, should be 'matmul' or 'gather'.\n\n Returns:\n Embedding lookup result.\n " if (fprop_mode == 'matmul'): lhs = tf.equal(tf.expand_dims(flat_ids, matmul_axis), tf.range(vocab_size, dtype=flat_ids.dtype)) return tf.matmul(tf.cast(lhs, emb_table.dtype), emb_table) elif (fprop_mode == 'gather'): return tf.nn.embedding_lookup(emb_table, flat_ids) else: raise ValueError('flat_embedding_lookup(): fprop_mode {} is not supported.'.format(fprop_mode))<|docstring|>Performs embedding lookup operation. Args: emb_table: tf.Tensor containing the embedding vectors. flat_ids: tf.Tensor of shape (number_ids,). vocab_size: vocabulary size of the embedding table, int. matmul_axis: the axis of flat_ids that is used for matmul, int. fprop_mode: embedding lookup option, should be 'matmul' or 'gather'. Returns: Embedding lookup result.<|endoftext|>
e67a0ea52e59d81c71e5434f4bf30831ff0fc1311f3ce333c7317425fe6d042e
@classmethod def Setup(cls, pruning_hparams_dict, global_step): 'Set up the pruning op with pruning hyperparameters and global step.\n\n Args:\n pruning_hparams_dict: a dict containing pruning hyperparameters;\n global_step: global step in TensorFlow.\n ' if (cls._pruning_obj is not None): pass assert (pruning_hparams_dict is not None) assert isinstance(pruning_hparams_dict, dict) cls._pruning_hparams_dict = pruning_hparams_dict cls._global_step = global_step cls._pruning_hparams = pruning.get_pruning_hparams().override_from_dict(pruning_hparams_dict) cls._pruning_obj = get_matrix_compression_object(cls._pruning_hparams, global_step=global_step) add_compression_summaries(cls._pruning_obj)
Set up the pruning op with pruning hyperparameters and global step. Args: pruning_hparams_dict: a dict containing pruning hyperparameters; global_step: global step in TensorFlow.
model_pruning/python/pruning_interface.py
Setup
wy-go/google-research
23,901
python
@classmethod def Setup(cls, pruning_hparams_dict, global_step): 'Set up the pruning op with pruning hyperparameters and global step.\n\n Args:\n pruning_hparams_dict: a dict containing pruning hyperparameters;\n global_step: global step in TensorFlow.\n ' if (cls._pruning_obj is not None): pass assert (pruning_hparams_dict is not None) assert isinstance(pruning_hparams_dict, dict) cls._pruning_hparams_dict = pruning_hparams_dict cls._global_step = global_step cls._pruning_hparams = pruning.get_pruning_hparams().override_from_dict(pruning_hparams_dict) cls._pruning_obj = get_matrix_compression_object(cls._pruning_hparams, global_step=global_step) add_compression_summaries(cls._pruning_obj)
@classmethod def Setup(cls, pruning_hparams_dict, global_step): 'Set up the pruning op with pruning hyperparameters and global step.\n\n Args:\n pruning_hparams_dict: a dict containing pruning hyperparameters;\n global_step: global step in TensorFlow.\n ' if (cls._pruning_obj is not None): pass assert (pruning_hparams_dict is not None) assert isinstance(pruning_hparams_dict, dict) cls._pruning_hparams_dict = pruning_hparams_dict cls._global_step = global_step cls._pruning_hparams = pruning.get_pruning_hparams().override_from_dict(pruning_hparams_dict) cls._pruning_obj = get_matrix_compression_object(cls._pruning_hparams, global_step=global_step) add_compression_summaries(cls._pruning_obj)<|docstring|>Set up the pruning op with pruning hyperparameters and global step. Args: pruning_hparams_dict: a dict containing pruning hyperparameters; global_step: global step in TensorFlow.<|endoftext|>
107b4ea3485293fdead8362900e6cc9444481d794ff563615802a574cc777632
@classmethod def GetMixResult(cls, theta, concat, lstmobj): "Compute the mix result.\n\n Args:\n theta: a theta object in the LSTM cells;\n concat: Tensor, concat of previous output and current state vector;\n lstmobj: a LSTM cell object.\n\n Returns:\n result Tensor.\n\n Raises:\n NotImplementedError if prune_option is not 'weight',\n 'first_order_gradient', or 'second_order_gradient'.\n " if (cls._pruning_hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return tf.matmul(concat, lstmobj.QWeight(tf.multiply(theta.wm, theta.mask, 'masked_weight'))) elif cls._pruning_obj: return lstmobj.compression_op.get_mix_operator(theta, concat) else: raise NotImplementedError()
Compute the mix result. Args: theta: a theta object in the LSTM cells; concat: Tensor, concat of previous output and current state vector; lstmobj: a LSTM cell object. Returns: result Tensor. Raises: NotImplementedError if prune_option is not 'weight', 'first_order_gradient', or 'second_order_gradient'.
model_pruning/python/pruning_interface.py
GetMixResult
wy-go/google-research
23,901
python
@classmethod def GetMixResult(cls, theta, concat, lstmobj): "Compute the mix result.\n\n Args:\n theta: a theta object in the LSTM cells;\n concat: Tensor, concat of previous output and current state vector;\n lstmobj: a LSTM cell object.\n\n Returns:\n result Tensor.\n\n Raises:\n NotImplementedError if prune_option is not 'weight',\n 'first_order_gradient', or 'second_order_gradient'.\n " if (cls._pruning_hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return tf.matmul(concat, lstmobj.QWeight(tf.multiply(theta.wm, theta.mask, 'masked_weight'))) elif cls._pruning_obj: return lstmobj.compression_op.get_mix_operator(theta, concat) else: raise NotImplementedError()
@classmethod def GetMixResult(cls, theta, concat, lstmobj): "Compute the mix result.\n\n Args:\n theta: a theta object in the LSTM cells;\n concat: Tensor, concat of previous output and current state vector;\n lstmobj: a LSTM cell object.\n\n Returns:\n result Tensor.\n\n Raises:\n NotImplementedError if prune_option is not 'weight',\n 'first_order_gradient', or 'second_order_gradient'.\n " if (cls._pruning_hparams.prune_option in ['weight', 'first_order_gradient', 'second_order_gradient']): return tf.matmul(concat, lstmobj.QWeight(tf.multiply(theta.wm, theta.mask, 'masked_weight'))) elif cls._pruning_obj: return lstmobj.compression_op.get_mix_operator(theta, concat) else: raise NotImplementedError()<|docstring|>Compute the mix result. Args: theta: a theta object in the LSTM cells; concat: Tensor, concat of previous output and current state vector; lstmobj: a LSTM cell object. Returns: result Tensor. Raises: NotImplementedError if prune_option is not 'weight', 'first_order_gradient', or 'second_order_gradient'.<|endoftext|>
06cb4d70676c5fb9591c3deac8db26d12fe5b6083cabb47eda2692b753feaa2e
@classmethod def GetMatmulResult(cls, a, b, softmaxlayerobj, transpose_a=False, transpose_b=False): "Compute the compressed result of matmul(a,b).\n\n Args:\n a: a tensor of rank 2;\n b: a tensor of rank 2;\n softmaxlayerobj: a SimpleFullSoftmax layer object;\n transpose_a: whether to transpose a before matmul;\n transpose_b: whether to transpose b before matmul.\n\n Returns:\n result Tensor.\n\n Raises:\n NotImplementedError if prune_option is not 'weight',\n 'first_order_gradient', or 'second_order_gradient'\n and pruning_obj is None.\n " if cls._pruning_obj: return softmaxlayerobj.compression_ops[(- 1)].get_matmul_operator(a, b, transpose_a, transpose_b) else: raise NotImplementedError()
Compute the compressed result of matmul(a,b). Args: a: a tensor of rank 2; b: a tensor of rank 2; softmaxlayerobj: a SimpleFullSoftmax layer object; transpose_a: whether to transpose a before matmul; transpose_b: whether to transpose b before matmul. Returns: result Tensor. Raises: NotImplementedError if prune_option is not 'weight', 'first_order_gradient', or 'second_order_gradient' and pruning_obj is None.
model_pruning/python/pruning_interface.py
GetMatmulResult
wy-go/google-research
23,901
python
@classmethod def GetMatmulResult(cls, a, b, softmaxlayerobj, transpose_a=False, transpose_b=False): "Compute the compressed result of matmul(a,b).\n\n Args:\n a: a tensor of rank 2;\n b: a tensor of rank 2;\n softmaxlayerobj: a SimpleFullSoftmax layer object;\n transpose_a: whether to transpose a before matmul;\n transpose_b: whether to transpose b before matmul.\n\n Returns:\n result Tensor.\n\n Raises:\n NotImplementedError if prune_option is not 'weight',\n 'first_order_gradient', or 'second_order_gradient'\n and pruning_obj is None.\n " if cls._pruning_obj: return softmaxlayerobj.compression_ops[(- 1)].get_matmul_operator(a, b, transpose_a, transpose_b) else: raise NotImplementedError()
@classmethod def GetMatmulResult(cls, a, b, softmaxlayerobj, transpose_a=False, transpose_b=False): "Compute the compressed result of matmul(a,b).\n\n Args:\n a: a tensor of rank 2;\n b: a tensor of rank 2;\n softmaxlayerobj: a SimpleFullSoftmax layer object;\n transpose_a: whether to transpose a before matmul;\n transpose_b: whether to transpose b before matmul.\n\n Returns:\n result Tensor.\n\n Raises:\n NotImplementedError if prune_option is not 'weight',\n 'first_order_gradient', or 'second_order_gradient'\n and pruning_obj is None.\n " if cls._pruning_obj: return softmaxlayerobj.compression_ops[(- 1)].get_matmul_operator(a, b, transpose_a, transpose_b) else: raise NotImplementedError()<|docstring|>Compute the compressed result of matmul(a,b). Args: a: a tensor of rank 2; b: a tensor of rank 2; softmaxlayerobj: a SimpleFullSoftmax layer object; transpose_a: whether to transpose a before matmul; transpose_b: whether to transpose b before matmul. Returns: result Tensor. Raises: NotImplementedError if prune_option is not 'weight', 'first_order_gradient', or 'second_order_gradient' and pruning_obj is None.<|endoftext|>
2a3a02c8ba223bf061320884368da8be981b38538246fa82dbd80eb76641b4e2
@classmethod def GetEinSumResult(cls, inputs, proj_obj): 'Compute the einsum result.\n\n Args:\n inputs: the left operand of the matmul operation.\n proj_obj: the ProjectionLayer object from where get_einsum_operator\n is called.\n\n Returns:\n result Tensor.\n\n Raises:\n NotImplementedError if pruning_obj is None.\n ' if cls._pruning_obj: return proj_obj.compression_op.get_einsum_operator(inputs, proj_obj) else: raise NotImplementedError()
Compute the einsum result. Args: inputs: the left operand of the matmul operation. proj_obj: the ProjectionLayer object from where get_einsum_operator is called. Returns: result Tensor. Raises: NotImplementedError if pruning_obj is None.
model_pruning/python/pruning_interface.py
GetEinSumResult
wy-go/google-research
23,901
python
@classmethod def GetEinSumResult(cls, inputs, proj_obj): 'Compute the einsum result.\n\n Args:\n inputs: the left operand of the matmul operation.\n proj_obj: the ProjectionLayer object from where get_einsum_operator\n is called.\n\n Returns:\n result Tensor.\n\n Raises:\n NotImplementedError if pruning_obj is None.\n ' if cls._pruning_obj: return proj_obj.compression_op.get_einsum_operator(inputs, proj_obj) else: raise NotImplementedError()
@classmethod def GetEinSumResult(cls, inputs, proj_obj): 'Compute the einsum result.\n\n Args:\n inputs: the left operand of the matmul operation.\n proj_obj: the ProjectionLayer object from where get_einsum_operator\n is called.\n\n Returns:\n result Tensor.\n\n Raises:\n NotImplementedError if pruning_obj is None.\n ' if cls._pruning_obj: return proj_obj.compression_op.get_einsum_operator(inputs, proj_obj) else: raise NotImplementedError()<|docstring|>Compute the einsum result. Args: inputs: the left operand of the matmul operation. proj_obj: the ProjectionLayer object from where get_einsum_operator is called. Returns: result Tensor. Raises: NotImplementedError if pruning_obj is None.<|endoftext|>
fd0808225b214fb34777ec93e8456060e8c4b91ddc38724527f83d0f9805b9e1
@classmethod def GetProjectLastDim(cls, inputs, weight, input_dim, output_dim, proj_obj): 'Linear projection on the last dim of the input tensor along with pruning.\n\n This is a TPU efficient implementation to avoid reshaping inputs to Rank-2\n tensor by using Einsum for the compute.\n\n Args:\n inputs: An input Tensor, the last dimension of which is input_dim.\n weight: A weight matrix with shape [input_dim, output_dim].\n input_dim: An integer or a symbolic dim, the last dimension of the inputs.\n output_dim: An integer or a symbolic dim, the last dimension of the\n outputs.\n proj_obj: a ProjectionLayer object.\n\n Returns:\n An output Tensor of the same rank as inputs, the last dimension is\n output_dim.\n ' theta = proj_obj.theta p = proj_obj.params input_dim = int((symbolic.ToStatic(input_dim) if symbolic.IsExpr(input_dim) else input_dim)) output_dim = int((symbolic.ToStatic(output_dim) if symbolic.IsExpr(output_dim) else output_dim)) if (py_utils.use_tpu() and (inputs.shape is not None) and (inputs.shape.rank is not None) and (inputs.shape.rank < 26)): if (inputs.shape.rank == 2): outputs = tf.matmul(inputs, weight) else: outputs = cls.GetEinSumResult(inputs, proj_obj) else: if ((p.pruning_hparams_dict['compression_option'] == 9) and p.pruning_hparams_dict['compress_input']): blocked_inputs = tf.reshape(inputs, py_utils.ToStaticShape([(- 1), p.pruning_hparams_dict['input_block_size']])) compressed_inputs = tf.reshape(py_utils.Matmul(blocked_inputs, theta.b_matrix_tfvar), py_utils.ToStaticShape([(- 1), (input_dim // p.pruning_hparams_dict['input_compression_factor'])])) else: compressed_inputs = tf.reshape(inputs, py_utils.ToStaticShape([(- 1), input_dim])) if (p.pruning_hparams_dict['compression_option'] == 10): if (p.pruning_hparams_dict['block_method'] == 'mask'): intermediate_result = py_utils.Matmul(compressed_inputs, tf.multiply(theta.c_matrix_tfvar, theta.c_mask_tfvar)) elif (p.pruning_hparams_dict['block_method'] == 'loop'): num_blocks = p.pruning_hparams_dict['block_compression_factor'] input_splitted = tf.split(compressed_inputs, num_blocks, axis=(- 1)) output_splitted = [] for (i, input_i) in enumerate(input_splitted): output_splitted.append(py_utils.Matmul(input_i, theta.c_matrix_tfvar[(i, :, :)])) intermediate_result = tf.concat(output_splitted, axis=(- 1)) else: intermediate_result = py_utils.Matmul(compressed_inputs, theta.c_matrix_tfvar) if ((p.pruning_hparams_dict['compression_option'] == 9) and p.pruning_hparams_dict['compress_output']): blocked_intermediate_result = tf.reshape(intermediate_result, py_utils.ToStaticShape([(- 1), (p.pruning_hparams_dict['output_block_size'] // p.pruning_hparams_dict['output_compression_factor'])])) outputs = py_utils.Matmul(blocked_intermediate_result, theta.d_matrix_tfvar) else: outputs = intermediate_result outputs = tf.reshape(outputs, tf.concat([tf.cast(py_utils.GetShape(inputs)[:(- 1)], tf.int32), py_utils.ToStaticShape([output_dim])], axis=0)) return outputs
Linear projection on the last dim of the input tensor along with pruning. This is a TPU efficient implementation to avoid reshaping inputs to Rank-2 tensor by using Einsum for the compute. Args: inputs: An input Tensor, the last dimension of which is input_dim. weight: A weight matrix with shape [input_dim, output_dim]. input_dim: An integer or a symbolic dim, the last dimension of the inputs. output_dim: An integer or a symbolic dim, the last dimension of the outputs. proj_obj: a ProjectionLayer object. Returns: An output Tensor of the same rank as inputs, the last dimension is output_dim.
model_pruning/python/pruning_interface.py
GetProjectLastDim
wy-go/google-research
23,901
python
@classmethod def GetProjectLastDim(cls, inputs, weight, input_dim, output_dim, proj_obj): 'Linear projection on the last dim of the input tensor along with pruning.\n\n This is a TPU efficient implementation to avoid reshaping inputs to Rank-2\n tensor by using Einsum for the compute.\n\n Args:\n inputs: An input Tensor, the last dimension of which is input_dim.\n weight: A weight matrix with shape [input_dim, output_dim].\n input_dim: An integer or a symbolic dim, the last dimension of the inputs.\n output_dim: An integer or a symbolic dim, the last dimension of the\n outputs.\n proj_obj: a ProjectionLayer object.\n\n Returns:\n An output Tensor of the same rank as inputs, the last dimension is\n output_dim.\n ' theta = proj_obj.theta p = proj_obj.params input_dim = int((symbolic.ToStatic(input_dim) if symbolic.IsExpr(input_dim) else input_dim)) output_dim = int((symbolic.ToStatic(output_dim) if symbolic.IsExpr(output_dim) else output_dim)) if (py_utils.use_tpu() and (inputs.shape is not None) and (inputs.shape.rank is not None) and (inputs.shape.rank < 26)): if (inputs.shape.rank == 2): outputs = tf.matmul(inputs, weight) else: outputs = cls.GetEinSumResult(inputs, proj_obj) else: if ((p.pruning_hparams_dict['compression_option'] == 9) and p.pruning_hparams_dict['compress_input']): blocked_inputs = tf.reshape(inputs, py_utils.ToStaticShape([(- 1), p.pruning_hparams_dict['input_block_size']])) compressed_inputs = tf.reshape(py_utils.Matmul(blocked_inputs, theta.b_matrix_tfvar), py_utils.ToStaticShape([(- 1), (input_dim // p.pruning_hparams_dict['input_compression_factor'])])) else: compressed_inputs = tf.reshape(inputs, py_utils.ToStaticShape([(- 1), input_dim])) if (p.pruning_hparams_dict['compression_option'] == 10): if (p.pruning_hparams_dict['block_method'] == 'mask'): intermediate_result = py_utils.Matmul(compressed_inputs, tf.multiply(theta.c_matrix_tfvar, theta.c_mask_tfvar)) elif (p.pruning_hparams_dict['block_method'] == 'loop'): num_blocks = p.pruning_hparams_dict['block_compression_factor'] input_splitted = tf.split(compressed_inputs, num_blocks, axis=(- 1)) output_splitted = [] for (i, input_i) in enumerate(input_splitted): output_splitted.append(py_utils.Matmul(input_i, theta.c_matrix_tfvar[(i, :, :)])) intermediate_result = tf.concat(output_splitted, axis=(- 1)) else: intermediate_result = py_utils.Matmul(compressed_inputs, theta.c_matrix_tfvar) if ((p.pruning_hparams_dict['compression_option'] == 9) and p.pruning_hparams_dict['compress_output']): blocked_intermediate_result = tf.reshape(intermediate_result, py_utils.ToStaticShape([(- 1), (p.pruning_hparams_dict['output_block_size'] // p.pruning_hparams_dict['output_compression_factor'])])) outputs = py_utils.Matmul(blocked_intermediate_result, theta.d_matrix_tfvar) else: outputs = intermediate_result outputs = tf.reshape(outputs, tf.concat([tf.cast(py_utils.GetShape(inputs)[:(- 1)], tf.int32), py_utils.ToStaticShape([output_dim])], axis=0)) return outputs
@classmethod def GetProjectLastDim(cls, inputs, weight, input_dim, output_dim, proj_obj): 'Linear projection on the last dim of the input tensor along with pruning.\n\n This is a TPU efficient implementation to avoid reshaping inputs to Rank-2\n tensor by using Einsum for the compute.\n\n Args:\n inputs: An input Tensor, the last dimension of which is input_dim.\n weight: A weight matrix with shape [input_dim, output_dim].\n input_dim: An integer or a symbolic dim, the last dimension of the inputs.\n output_dim: An integer or a symbolic dim, the last dimension of the\n outputs.\n proj_obj: a ProjectionLayer object.\n\n Returns:\n An output Tensor of the same rank as inputs, the last dimension is\n output_dim.\n ' theta = proj_obj.theta p = proj_obj.params input_dim = int((symbolic.ToStatic(input_dim) if symbolic.IsExpr(input_dim) else input_dim)) output_dim = int((symbolic.ToStatic(output_dim) if symbolic.IsExpr(output_dim) else output_dim)) if (py_utils.use_tpu() and (inputs.shape is not None) and (inputs.shape.rank is not None) and (inputs.shape.rank < 26)): if (inputs.shape.rank == 2): outputs = tf.matmul(inputs, weight) else: outputs = cls.GetEinSumResult(inputs, proj_obj) else: if ((p.pruning_hparams_dict['compression_option'] == 9) and p.pruning_hparams_dict['compress_input']): blocked_inputs = tf.reshape(inputs, py_utils.ToStaticShape([(- 1), p.pruning_hparams_dict['input_block_size']])) compressed_inputs = tf.reshape(py_utils.Matmul(blocked_inputs, theta.b_matrix_tfvar), py_utils.ToStaticShape([(- 1), (input_dim // p.pruning_hparams_dict['input_compression_factor'])])) else: compressed_inputs = tf.reshape(inputs, py_utils.ToStaticShape([(- 1), input_dim])) if (p.pruning_hparams_dict['compression_option'] == 10): if (p.pruning_hparams_dict['block_method'] == 'mask'): intermediate_result = py_utils.Matmul(compressed_inputs, tf.multiply(theta.c_matrix_tfvar, theta.c_mask_tfvar)) elif (p.pruning_hparams_dict['block_method'] == 'loop'): num_blocks = p.pruning_hparams_dict['block_compression_factor'] input_splitted = tf.split(compressed_inputs, num_blocks, axis=(- 1)) output_splitted = [] for (i, input_i) in enumerate(input_splitted): output_splitted.append(py_utils.Matmul(input_i, theta.c_matrix_tfvar[(i, :, :)])) intermediate_result = tf.concat(output_splitted, axis=(- 1)) else: intermediate_result = py_utils.Matmul(compressed_inputs, theta.c_matrix_tfvar) if ((p.pruning_hparams_dict['compression_option'] == 9) and p.pruning_hparams_dict['compress_output']): blocked_intermediate_result = tf.reshape(intermediate_result, py_utils.ToStaticShape([(- 1), (p.pruning_hparams_dict['output_block_size'] // p.pruning_hparams_dict['output_compression_factor'])])) outputs = py_utils.Matmul(blocked_intermediate_result, theta.d_matrix_tfvar) else: outputs = intermediate_result outputs = tf.reshape(outputs, tf.concat([tf.cast(py_utils.GetShape(inputs)[:(- 1)], tf.int32), py_utils.ToStaticShape([output_dim])], axis=0)) return outputs<|docstring|>Linear projection on the last dim of the input tensor along with pruning. This is a TPU efficient implementation to avoid reshaping inputs to Rank-2 tensor by using Einsum for the compute. Args: inputs: An input Tensor, the last dimension of which is input_dim. weight: A weight matrix with shape [input_dim, output_dim]. input_dim: An integer or a symbolic dim, the last dimension of the inputs. output_dim: An integer or a symbolic dim, the last dimension of the outputs. proj_obj: a ProjectionLayer object. Returns: An output Tensor of the same rank as inputs, the last dimension is output_dim.<|endoftext|>
591ab60daf6af9494977847bf67723fd102dd3d6011634fcd43e3ebbb18f2fd7
@classmethod def ApplyTensorflowAndPythonUpdate(cls): 'Returns True if both Tensorflow and Python updates need to run.' if (not cls._pruning_obj): return False hparams = cls._pruning_obj.get_spec() return (hparams.update_option == UpdateOptions.TF_AND_PYTHON_UPDATE)
Returns True if both Tensorflow and Python updates need to run.
model_pruning/python/pruning_interface.py
ApplyTensorflowAndPythonUpdate
wy-go/google-research
23,901
python
@classmethod def ApplyTensorflowAndPythonUpdate(cls): if (not cls._pruning_obj): return False hparams = cls._pruning_obj.get_spec() return (hparams.update_option == UpdateOptions.TF_AND_PYTHON_UPDATE)
@classmethod def ApplyTensorflowAndPythonUpdate(cls): if (not cls._pruning_obj): return False hparams = cls._pruning_obj.get_spec() return (hparams.update_option == UpdateOptions.TF_AND_PYTHON_UPDATE)<|docstring|>Returns True if both Tensorflow and Python updates need to run.<|endoftext|>
afb35c833745b69cc42faca207aa3c9ad0a574652c17c4f1c351c98d3e58f9fd
def _get_file_path(self): '\n Get the directory of the file to be extracted\n :return: File directory\n ' self.file_path = filedialog.askopenfilename(filetypes=(('PDF Files', '*.pdf'), ('Image Files', '*.jpg *.jpeg *.png'))) if (self.file_path != ''): self.label_file['text'] = ('File: ' + self.file_path.split('/')[(len(self.file_path.split('/')) - 1)]) self.extract_file.configure(state=tkinter.ACTIVE) else: self.label_file['text'] = '' self.extract_file.configure(state=tkinter.DISABLED)
Get the directory of the file to be extracted :return: File directory
main.py
_get_file_path
felipeucelli/extract-text
0
python
def _get_file_path(self): '\n Get the directory of the file to be extracted\n :return: File directory\n ' self.file_path = filedialog.askopenfilename(filetypes=(('PDF Files', '*.pdf'), ('Image Files', '*.jpg *.jpeg *.png'))) if (self.file_path != ): self.label_file['text'] = ('File: ' + self.file_path.split('/')[(len(self.file_path.split('/')) - 1)]) self.extract_file.configure(state=tkinter.ACTIVE) else: self.label_file['text'] = self.extract_file.configure(state=tkinter.DISABLED)
def _get_file_path(self): '\n Get the directory of the file to be extracted\n :return: File directory\n ' self.file_path = filedialog.askopenfilename(filetypes=(('PDF Files', '*.pdf'), ('Image Files', '*.jpg *.jpeg *.png'))) if (self.file_path != ): self.label_file['text'] = ('File: ' + self.file_path.split('/')[(len(self.file_path.split('/')) - 1)]) self.extract_file.configure(state=tkinter.ACTIVE) else: self.label_file['text'] = self.extract_file.configure(state=tkinter.DISABLED)<|docstring|>Get the directory of the file to be extracted :return: File directory<|endoftext|>
27dd9a1d3ac2f30d760bceee60a3cc581575aba7e822b3170240ab7a2d16b5fd
def _save_file(self, extracted_file): '\n Save the extracted file in the selected directory\n :param extracted_file:\n :return:\n ' file_name = self.file_path.split('/')[(len(self.file_path.split('/')) - 1)] file_extension = file_name.split('.')[(len(file_name.split('.')) - 1)] new_file_name = file_name.replace(f'.{file_extension}', '') save_file_path = filedialog.asksaveasfilename(defaultextension='txt', initialfile=new_file_name, filetypes=(('Text files', '*.txt'), ('All files', '*.*'))) if (save_file_path != ''): with open(save_file_path, 'w') as save: save.writelines(extracted_file)
Save the extracted file in the selected directory :param extracted_file: :return:
main.py
_save_file
felipeucelli/extract-text
0
python
def _save_file(self, extracted_file): '\n Save the extracted file in the selected directory\n :param extracted_file:\n :return:\n ' file_name = self.file_path.split('/')[(len(self.file_path.split('/')) - 1)] file_extension = file_name.split('.')[(len(file_name.split('.')) - 1)] new_file_name = file_name.replace(f'.{file_extension}', ) save_file_path = filedialog.asksaveasfilename(defaultextension='txt', initialfile=new_file_name, filetypes=(('Text files', '*.txt'), ('All files', '*.*'))) if (save_file_path != ): with open(save_file_path, 'w') as save: save.writelines(extracted_file)
def _save_file(self, extracted_file): '\n Save the extracted file in the selected directory\n :param extracted_file:\n :return:\n ' file_name = self.file_path.split('/')[(len(self.file_path.split('/')) - 1)] file_extension = file_name.split('.')[(len(file_name.split('.')) - 1)] new_file_name = file_name.replace(f'.{file_extension}', ) save_file_path = filedialog.asksaveasfilename(defaultextension='txt', initialfile=new_file_name, filetypes=(('Text files', '*.txt'), ('All files', '*.*'))) if (save_file_path != ): with open(save_file_path, 'w') as save: save.writelines(extracted_file)<|docstring|>Save the extracted file in the selected directory :param extracted_file: :return:<|endoftext|>
ccd281dc6891c957280c04a307a0ba10b27457ce474a9b6303635a45932b9914
def _disable_btn(self): '\n Disables the import file and extract file buttons and writes a message to the screen during extraction\n :return:\n ' self.get_file.configure(state=tkinter.DISABLED) self.extract_file.configure(state=tkinter.DISABLED) self.label_status['text'] = 'Extracting, please wait.'
Disables the import file and extract file buttons and writes a message to the screen during extraction :return:
main.py
_disable_btn
felipeucelli/extract-text
0
python
def _disable_btn(self): '\n Disables the import file and extract file buttons and writes a message to the screen during extraction\n :return:\n ' self.get_file.configure(state=tkinter.DISABLED) self.extract_file.configure(state=tkinter.DISABLED) self.label_status['text'] = 'Extracting, please wait.'
def _disable_btn(self): '\n Disables the import file and extract file buttons and writes a message to the screen during extraction\n :return:\n ' self.get_file.configure(state=tkinter.DISABLED) self.extract_file.configure(state=tkinter.DISABLED) self.label_status['text'] = 'Extracting, please wait.'<|docstring|>Disables the import file and extract file buttons and writes a message to the screen during extraction :return:<|endoftext|>
a679044ca510566f37571e0328c22abaf2a69fa56a3d5fbf49e4bffd0060a35f
def _enable_btn(self): '\n Activates the import file and extract file buttons and clears the message after extraction\n :return:\n ' self.get_file.configure(state=tkinter.ACTIVE) self.extract_file.configure(state=tkinter.ACTIVE) self.label_status['text'] = ''
Activates the import file and extract file buttons and clears the message after extraction :return:
main.py
_enable_btn
felipeucelli/extract-text
0
python
def _enable_btn(self): '\n Activates the import file and extract file buttons and clears the message after extraction\n :return:\n ' self.get_file.configure(state=tkinter.ACTIVE) self.extract_file.configure(state=tkinter.ACTIVE) self.label_status['text'] =
def _enable_btn(self): '\n Activates the import file and extract file buttons and clears the message after extraction\n :return:\n ' self.get_file.configure(state=tkinter.ACTIVE) self.extract_file.configure(state=tkinter.ACTIVE) self.label_status['text'] = <|docstring|>Activates the import file and extract file buttons and clears the message after extraction :return:<|endoftext|>
094669c0bbb98378a6a5d25eae309283e4a271e39b1439c774457a21a8ace60d
def _thread_pdf(self, *args): '\n Extract .pdf files\n :param args: Receive the file to be extracted\n :return:\n ' self._disable_btn() with fitz.open(args[0]) as pdf: text = '' for page in pdf: text += page.getText() self.label_status['text'] = 'Extraction Finished.' self._save_file(text) self._enable_btn()
Extract .pdf files :param args: Receive the file to be extracted :return:
main.py
_thread_pdf
felipeucelli/extract-text
0
python
def _thread_pdf(self, *args): '\n Extract .pdf files\n :param args: Receive the file to be extracted\n :return:\n ' self._disable_btn() with fitz.open(args[0]) as pdf: text = for page in pdf: text += page.getText() self.label_status['text'] = 'Extraction Finished.' self._save_file(text) self._enable_btn()
def _thread_pdf(self, *args): '\n Extract .pdf files\n :param args: Receive the file to be extracted\n :return:\n ' self._disable_btn() with fitz.open(args[0]) as pdf: text = for page in pdf: text += page.getText() self.label_status['text'] = 'Extraction Finished.' self._save_file(text) self._enable_btn()<|docstring|>Extract .pdf files :param args: Receive the file to be extracted :return:<|endoftext|>
c0b5927ab2e4bff3b09807ed587342669ad953fc91425cdcc4d1dc4ad15b92f8
def _thread_image(self, *args): '\n Extract image files\n :param args: Receive the file to be extracted\n :return:\n ' self._disable_btn() reader = Reader(['pt'], verbose=False) result_file = reader.readtext(args[0], paragraph=False) text = '' for result in result_file: text += f'''{result[1]} ''' self.label_status['text'] = 'Extraction Finished.' self._save_file(text) self._enable_btn()
Extract image files :param args: Receive the file to be extracted :return:
main.py
_thread_image
felipeucelli/extract-text
0
python
def _thread_image(self, *args): '\n Extract image files\n :param args: Receive the file to be extracted\n :return:\n ' self._disable_btn() reader = Reader(['pt'], verbose=False) result_file = reader.readtext(args[0], paragraph=False) text = for result in result_file: text += f'{result[1]} ' self.label_status['text'] = 'Extraction Finished.' self._save_file(text) self._enable_btn()
def _thread_image(self, *args): '\n Extract image files\n :param args: Receive the file to be extracted\n :return:\n ' self._disable_btn() reader = Reader(['pt'], verbose=False) result_file = reader.readtext(args[0], paragraph=False) text = for result in result_file: text += f'{result[1]} ' self.label_status['text'] = 'Extraction Finished.' self._save_file(text) self._enable_btn()<|docstring|>Extract image files :param args: Receive the file to be extracted :return:<|endoftext|>
47bda915337cbed70ef09507ba78a4df8fe8e52f9e11abf7023f49f4cee6dbd6
def _extract_pdf(self, pdf_file): '\n Start a new thread for extracting .pdf files\n :param pdf_file: Receive the file to be extracted\n :return:\n ' _thread.start_new_thread(self._thread_pdf, (pdf_file, 0))
Start a new thread for extracting .pdf files :param pdf_file: Receive the file to be extracted :return:
main.py
_extract_pdf
felipeucelli/extract-text
0
python
def _extract_pdf(self, pdf_file): '\n Start a new thread for extracting .pdf files\n :param pdf_file: Receive the file to be extracted\n :return:\n ' _thread.start_new_thread(self._thread_pdf, (pdf_file, 0))
def _extract_pdf(self, pdf_file): '\n Start a new thread for extracting .pdf files\n :param pdf_file: Receive the file to be extracted\n :return:\n ' _thread.start_new_thread(self._thread_pdf, (pdf_file, 0))<|docstring|>Start a new thread for extracting .pdf files :param pdf_file: Receive the file to be extracted :return:<|endoftext|>
7ea057f3169e82db280da824cd955ff43d5259e32a0620ea83a7879e8b140be9
def _extract_image(self, image_file): '\n Starts a new thread for extracting image files\n :param image_file: Receive the file to be extracted\n :return:\n ' _thread.start_new_thread(self._thread_image, (image_file, 0))
Starts a new thread for extracting image files :param image_file: Receive the file to be extracted :return:
main.py
_extract_image
felipeucelli/extract-text
0
python
def _extract_image(self, image_file): '\n Starts a new thread for extracting image files\n :param image_file: Receive the file to be extracted\n :return:\n ' _thread.start_new_thread(self._thread_image, (image_file, 0))
def _extract_image(self, image_file): '\n Starts a new thread for extracting image files\n :param image_file: Receive the file to be extracted\n :return:\n ' _thread.start_new_thread(self._thread_image, (image_file, 0))<|docstring|>Starts a new thread for extracting image files :param image_file: Receive the file to be extracted :return:<|endoftext|>
6c7bef8b9c5ae81c22f2c4a6475e9678388faeaf042a55b902fceb1322d61b0b
def _extract(self): '\n Valid and call the function matches the format of the file to be extracted\n :return:\n ' if (self.file_path != ''): file = self.file_path.split('/')[(len(self.file_path.split('/')) - 1)] file_extension = file.split('.')[(len(file.split('.')) - 1)] if (file_extension == 'pdf'): self._extract_pdf(self.file_path) if ((file_extension == 'jpg') or (file_extension == 'jpeg') or (file_extension == 'png')): self._extract_image(self.file_path)
Valid and call the function matches the format of the file to be extracted :return:
main.py
_extract
felipeucelli/extract-text
0
python
def _extract(self): '\n Valid and call the function matches the format of the file to be extracted\n :return:\n ' if (self.file_path != ): file = self.file_path.split('/')[(len(self.file_path.split('/')) - 1)] file_extension = file.split('.')[(len(file.split('.')) - 1)] if (file_extension == 'pdf'): self._extract_pdf(self.file_path) if ((file_extension == 'jpg') or (file_extension == 'jpeg') or (file_extension == 'png')): self._extract_image(self.file_path)
def _extract(self): '\n Valid and call the function matches the format of the file to be extracted\n :return:\n ' if (self.file_path != ): file = self.file_path.split('/')[(len(self.file_path.split('/')) - 1)] file_extension = file.split('.')[(len(file.split('.')) - 1)] if (file_extension == 'pdf'): self._extract_pdf(self.file_path) if ((file_extension == 'jpg') or (file_extension == 'jpeg') or (file_extension == 'png')): self._extract_image(self.file_path)<|docstring|>Valid and call the function matches the format of the file to be extracted :return:<|endoftext|>
6bab17b2d2e92ea39c7d1ade90264b8e79db9b40feab8a25c4b15dfe30cb2764
def start(self): '\n Start tkinter interface\n :return:\n ' self.root.mainloop()
Start tkinter interface :return:
main.py
start
felipeucelli/extract-text
0
python
def start(self): '\n Start tkinter interface\n :return:\n ' self.root.mainloop()
def start(self): '\n Start tkinter interface\n :return:\n ' self.root.mainloop()<|docstring|>Start tkinter interface :return:<|endoftext|>
fe064aff0d5db07a74bb44889cd5475514e51c4361af529a6e57de0971832fe6
def make_filter(my_request): '\n Build a list of filters for each object\n ' query_attrs = dict() query_attrs['program'] = dict() query_attrs['project'] = dict() query_attrs['indicator'] = dict() query_attrs['collecteddata'] = dict() for (param, val) in my_request.items(): if (param == 'program'): query_attrs['program']['id__in'] = val.split(',') query_attrs['project']['program__id__in'] = val.split(',') query_attrs['indicator']['program__id__in'] = val.split(',') query_attrs['collecteddata']['indicator__program__id__in'] = val.split(',') elif (param == 'sector'): query_attrs['program']['sector__in'] = val.split(',') query_attrs['project']['sector__in'] = val.split(',') query_attrs['indicator']['sector__in'] = val.split(',') query_attrs['collecteddata']['indicator__sector__in'] = val.split(',') elif (param == 'country'): query_attrs['program']['country__id__in'] = val.split(',') query_attrs['project']['program__country__id__in'] = val.split(',') query_attrs['indicator']['program__country__in'] = val.split(',') query_attrs['collecteddata']['program__country__in'] = val.split(',') elif (param == 'indicator__id'): query_attrs['indicator']['id'] = val query_attrs['collecteddata']['indicator__id'] = val elif (param == 'approval'): if (val == 'new'): query_attrs['project']['approval'] = '' else: query_attrs['project']['approval'] = val elif (param == 'collecteddata__isnull'): if (val == 'True'): query_attrs['indicator']['collecteddata__isnull'] = True else: query_attrs['indicator']['collecteddata__isnull'] = False elif (param == 'export'): '\n IGNORE EXPORT PARAM\n ' else: query_attrs['program'][param] = val query_attrs['project'][param] = val query_attrs['indicator'][param] = val query_attrs['collecteddata'][param] = val return query_attrs
Build a list of filters for each object
reports/views.py
make_filter
mikael19/activity
1
python
def make_filter(my_request): '\n \n ' query_attrs = dict() query_attrs['program'] = dict() query_attrs['project'] = dict() query_attrs['indicator'] = dict() query_attrs['collecteddata'] = dict() for (param, val) in my_request.items(): if (param == 'program'): query_attrs['program']['id__in'] = val.split(',') query_attrs['project']['program__id__in'] = val.split(',') query_attrs['indicator']['program__id__in'] = val.split(',') query_attrs['collecteddata']['indicator__program__id__in'] = val.split(',') elif (param == 'sector'): query_attrs['program']['sector__in'] = val.split(',') query_attrs['project']['sector__in'] = val.split(',') query_attrs['indicator']['sector__in'] = val.split(',') query_attrs['collecteddata']['indicator__sector__in'] = val.split(',') elif (param == 'country'): query_attrs['program']['country__id__in'] = val.split(',') query_attrs['project']['program__country__id__in'] = val.split(',') query_attrs['indicator']['program__country__in'] = val.split(',') query_attrs['collecteddata']['program__country__in'] = val.split(',') elif (param == 'indicator__id'): query_attrs['indicator']['id'] = val query_attrs['collecteddata']['indicator__id'] = val elif (param == 'approval'): if (val == 'new'): query_attrs['project']['approval'] = else: query_attrs['project']['approval'] = val elif (param == 'collecteddata__isnull'): if (val == 'True'): query_attrs['indicator']['collecteddata__isnull'] = True else: query_attrs['indicator']['collecteddata__isnull'] = False elif (param == 'export'): '\n IGNORE EXPORT PARAM\n ' else: query_attrs['program'][param] = val query_attrs['project'][param] = val query_attrs['indicator'][param] = val query_attrs['collecteddata'][param] = val return query_attrs
def make_filter(my_request): '\n \n ' query_attrs = dict() query_attrs['program'] = dict() query_attrs['project'] = dict() query_attrs['indicator'] = dict() query_attrs['collecteddata'] = dict() for (param, val) in my_request.items(): if (param == 'program'): query_attrs['program']['id__in'] = val.split(',') query_attrs['project']['program__id__in'] = val.split(',') query_attrs['indicator']['program__id__in'] = val.split(',') query_attrs['collecteddata']['indicator__program__id__in'] = val.split(',') elif (param == 'sector'): query_attrs['program']['sector__in'] = val.split(',') query_attrs['project']['sector__in'] = val.split(',') query_attrs['indicator']['sector__in'] = val.split(',') query_attrs['collecteddata']['indicator__sector__in'] = val.split(',') elif (param == 'country'): query_attrs['program']['country__id__in'] = val.split(',') query_attrs['project']['program__country__id__in'] = val.split(',') query_attrs['indicator']['program__country__in'] = val.split(',') query_attrs['collecteddata']['program__country__in'] = val.split(',') elif (param == 'indicator__id'): query_attrs['indicator']['id'] = val query_attrs['collecteddata']['indicator__id'] = val elif (param == 'approval'): if (val == 'new'): query_attrs['project']['approval'] = else: query_attrs['project']['approval'] = val elif (param == 'collecteddata__isnull'): if (val == 'True'): query_attrs['indicator']['collecteddata__isnull'] = True else: query_attrs['indicator']['collecteddata__isnull'] = False elif (param == 'export'): '\n IGNORE EXPORT PARAM\n ' else: query_attrs['program'][param] = val query_attrs['project'][param] = val query_attrs['indicator'][param] = val query_attrs['collecteddata'][param] = val return query_attrs<|docstring|>Build a list of filters for each object<|endoftext|>
f5ccda34b4dd43f5eddd58e826cd4ad8ac1569dff150bc7712c9510bbdb1abaa
def filter_json(request, service, **kwargs): '\n For populating indicators in dropdown\n ' final_dict = {'criteria': kwargs} print(final_dict) JsonResponse(final_dict, safe=False)
For populating indicators in dropdown
reports/views.py
filter_json
mikael19/activity
1
python
def filter_json(request, service, **kwargs): '\n \n ' final_dict = {'criteria': kwargs} print(final_dict) JsonResponse(final_dict, safe=False)
def filter_json(request, service, **kwargs): '\n \n ' final_dict = {'criteria': kwargs} print(final_dict) JsonResponse(final_dict, safe=False)<|docstring|>For populating indicators in dropdown<|endoftext|>
617b44d132da383257fe81ddf4b946c87ff9362f6ef1d711e15b27b4241bbb2a
def _run_test_suite(runner, suite): 'Run the test suite.\n\n Preserve the current development apiproxy, create a new apiproxy and\n replace the datastore with a temporary one that will be used for this\n test suite, run the test suite, and restore the development apiproxy.\n This isolates the test datastore from the development datastore.\n\n ' original_apiproxy = apiproxy_stub_map.apiproxy try: apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() temp_stub = datastore_file_stub.DatastoreFileStub('GAEUnitDataStore', None, None) apiproxy_stub_map.apiproxy.RegisterStub('datastore', temp_stub) for name in ['user', 'urlfetch', 'mail', 'memcache', 'images']: apiproxy_stub_map.apiproxy.RegisterStub(name, original_apiproxy.GetStub(name)) runner.run(suite) finally: apiproxy_stub_map.apiproxy = original_apiproxy
Run the test suite. Preserve the current development apiproxy, create a new apiproxy and replace the datastore with a temporary one that will be used for this test suite, run the test suite, and restore the development apiproxy. This isolates the test datastore from the development datastore.
gaeunit.py
_run_test_suite
al3x/downforeveryoneorjustme
26
python
def _run_test_suite(runner, suite): 'Run the test suite.\n\n Preserve the current development apiproxy, create a new apiproxy and\n replace the datastore with a temporary one that will be used for this\n test suite, run the test suite, and restore the development apiproxy.\n This isolates the test datastore from the development datastore.\n\n ' original_apiproxy = apiproxy_stub_map.apiproxy try: apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() temp_stub = datastore_file_stub.DatastoreFileStub('GAEUnitDataStore', None, None) apiproxy_stub_map.apiproxy.RegisterStub('datastore', temp_stub) for name in ['user', 'urlfetch', 'mail', 'memcache', 'images']: apiproxy_stub_map.apiproxy.RegisterStub(name, original_apiproxy.GetStub(name)) runner.run(suite) finally: apiproxy_stub_map.apiproxy = original_apiproxy
def _run_test_suite(runner, suite): 'Run the test suite.\n\n Preserve the current development apiproxy, create a new apiproxy and\n replace the datastore with a temporary one that will be used for this\n test suite, run the test suite, and restore the development apiproxy.\n This isolates the test datastore from the development datastore.\n\n ' original_apiproxy = apiproxy_stub_map.apiproxy try: apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() temp_stub = datastore_file_stub.DatastoreFileStub('GAEUnitDataStore', None, None) apiproxy_stub_map.apiproxy.RegisterStub('datastore', temp_stub) for name in ['user', 'urlfetch', 'mail', 'memcache', 'images']: apiproxy_stub_map.apiproxy.RegisterStub(name, original_apiproxy.GetStub(name)) runner.run(suite) finally: apiproxy_stub_map.apiproxy = original_apiproxy<|docstring|>Run the test suite. Preserve the current development apiproxy, create a new apiproxy and replace the datastore with a temporary one that will be used for this test suite, run the test suite, and restore the development apiproxy. This isolates the test datastore from the development datastore.<|endoftext|>
0d396a8f3a77070fdc14f0f19335050fad59d25808bdb7e0dd95ff2e6604e2a7
def get_indent_text_from_depth(depth: int): '\n インデント文字列を階層の深さから取得\n\n :param depth: インデント階層の深さ\n :return: インデントを表現する文字列\n ' return ''.join([INDENT for _ in range(depth)])
インデント文字列を階層の深さから取得 :param depth: インデント階層の深さ :return: インデントを表現する文字列
app/html/block_builder.py
get_indent_text_from_depth
a-pompom/Python-markdownParser
0
python
def get_indent_text_from_depth(depth: int): '\n インデント文字列を階層の深さから取得\n\n :param depth: インデント階層の深さ\n :return: インデントを表現する文字列\n ' return .join([INDENT for _ in range(depth)])
def get_indent_text_from_depth(depth: int): '\n インデント文字列を階層の深さから取得\n\n :param depth: インデント階層の深さ\n :return: インデントを表現する文字列\n ' return .join([INDENT for _ in range(depth)])<|docstring|>インデント文字列を階層の深さから取得 :param depth: インデント階層の深さ :return: インデントを表現する文字列<|endoftext|>
1feada9195cca681d3779ef330d5152532edca2a1e2901b292c0f4490ff7fa28
def build(self, block: Block, child_text: str) -> str: '\n Block要素をもとに対応するHTML文字列を生成\n\n :param block: 処理対象Block要素\n :param child_text: 子要素を解釈した結果の文字列\n :return: HTML文字列\n ' for builder in self._builders: if builder.is_target(block): return builder.build(block, child_text) if isinstance(block, PlainBlock): return (get_indent_text_from_depth(block.indent_depth) + child_text)
Block要素をもとに対応するHTML文字列を生成 :param block: 処理対象Block要素 :param child_text: 子要素を解釈した結果の文字列 :return: HTML文字列
app/html/block_builder.py
build
a-pompom/Python-markdownParser
0
python
def build(self, block: Block, child_text: str) -> str: '\n Block要素をもとに対応するHTML文字列を生成\n\n :param block: 処理対象Block要素\n :param child_text: 子要素を解釈した結果の文字列\n :return: HTML文字列\n ' for builder in self._builders: if builder.is_target(block): return builder.build(block, child_text) if isinstance(block, PlainBlock): return (get_indent_text_from_depth(block.indent_depth) + child_text)
def build(self, block: Block, child_text: str) -> str: '\n Block要素をもとに対応するHTML文字列を生成\n\n :param block: 処理対象Block要素\n :param child_text: 子要素を解釈した結果の文字列\n :return: HTML文字列\n ' for builder in self._builders: if builder.is_target(block): return builder.build(block, child_text) if isinstance(block, PlainBlock): return (get_indent_text_from_depth(block.indent_depth) + child_text)<|docstring|>Block要素をもとに対応するHTML文字列を生成 :param block: 処理対象Block要素 :param child_text: 子要素を解釈した結果の文字列 :return: HTML文字列<|endoftext|>
cfbe6d056768c01360c3f31525caa70e44868e95dadc3cd43979ca0dda677496
def is_target(self, block: Block) -> bool: '\n Block要素の種別がビルダと対応したものであるか判定\n\n :param block: 判定対象Block要素\n :return: ビルド対象-> True ビルド対象でない-> False\n ' raise NotImplementedError
Block要素の種別がビルダと対応したものであるか判定 :param block: 判定対象Block要素 :return: ビルド対象-> True ビルド対象でない-> False
app/html/block_builder.py
is_target
a-pompom/Python-markdownParser
0
python
def is_target(self, block: Block) -> bool: '\n Block要素の種別がビルダと対応したものであるか判定\n\n :param block: 判定対象Block要素\n :return: ビルド対象-> True ビルド対象でない-> False\n ' raise NotImplementedError
def is_target(self, block: Block) -> bool: '\n Block要素の種別がビルダと対応したものであるか判定\n\n :param block: 判定対象Block要素\n :return: ビルド対象-> True ビルド対象でない-> False\n ' raise NotImplementedError<|docstring|>Block要素の種別がビルダと対応したものであるか判定 :param block: 判定対象Block要素 :return: ビルド対象-> True ビルド対象でない-> False<|endoftext|>
e1713df60ad9e144f736cd55c913de57916d41835a6636c2ef9b3da1d5c8ee74
def build(self, block: Block, child_text: str) -> str: '\n Block要素をもとにHTMLタグ要素を組み立て\n\n :param block: Block要素\n :param child_text: タグの子要素である文字列\n :return: HTML文字列\n ' raise NotImplementedError
Block要素をもとにHTMLタグ要素を組み立て :param block: Block要素 :param child_text: タグの子要素である文字列 :return: HTML文字列
app/html/block_builder.py
build
a-pompom/Python-markdownParser
0
python
def build(self, block: Block, child_text: str) -> str: '\n Block要素をもとにHTMLタグ要素を組み立て\n\n :param block: Block要素\n :param child_text: タグの子要素である文字列\n :return: HTML文字列\n ' raise NotImplementedError
def build(self, block: Block, child_text: str) -> str: '\n Block要素をもとにHTMLタグ要素を組み立て\n\n :param block: Block要素\n :param child_text: タグの子要素である文字列\n :return: HTML文字列\n ' raise NotImplementedError<|docstring|>Block要素をもとにHTMLタグ要素を組み立て :param block: Block要素 :param child_text: タグの子要素である文字列 :return: HTML文字列<|endoftext|>
e5b293aedd16a1c91904d965b10c2a85b230234d06347485fde5a8ac2bea3993
def build(self, block: ParagraphBlock, child_text: str) -> str: '\n 段落要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのpタグを含む文字列\n ' paragraph = self.TEMPLATE.replace(self.INDENT_EXPRESSION, get_indent_text_from_depth(block.indent_depth)).replace(self.CLASSNAME_EXPRESSION, setting['class_name']['p']).replace(self.TEXT_EXPRESSION, child_text) return paragraph
段落要素のHTML文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのpタグを含む文字列
app/html/block_builder.py
build
a-pompom/Python-markdownParser
0
python
def build(self, block: ParagraphBlock, child_text: str) -> str: '\n 段落要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのpタグを含む文字列\n ' paragraph = self.TEMPLATE.replace(self.INDENT_EXPRESSION, get_indent_text_from_depth(block.indent_depth)).replace(self.CLASSNAME_EXPRESSION, setting['class_name']['p']).replace(self.TEXT_EXPRESSION, child_text) return paragraph
def build(self, block: ParagraphBlock, child_text: str) -> str: '\n 段落要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのpタグを含む文字列\n ' paragraph = self.TEMPLATE.replace(self.INDENT_EXPRESSION, get_indent_text_from_depth(block.indent_depth)).replace(self.CLASSNAME_EXPRESSION, setting['class_name']['p']).replace(self.TEXT_EXPRESSION, child_text) return paragraph<|docstring|>段落要素のHTML文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのpタグを含む文字列<|endoftext|>
e84837cfaf81ffad228cec3e51af590f53db3339d84290cef71399732c95cdd7
def build(self, block: HeadingBlock, child_text: str) -> str: '\n ヘッダのHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのヘッダタグを含む文字列\n ' heading_tag = f'h{block.size}' heading = self.TEMPLATE.replace(self.HEADING_EXPRESSION, heading_tag).replace(self.CLASSNAME_EXPRESSION, setting['class_name'].get(heading_tag, '')).replace(self.TEXT_EXPRESSION, child_text) return heading
ヘッダのHTML文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのヘッダタグを含む文字列
app/html/block_builder.py
build
a-pompom/Python-markdownParser
0
python
def build(self, block: HeadingBlock, child_text: str) -> str: '\n ヘッダのHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのヘッダタグを含む文字列\n ' heading_tag = f'h{block.size}' heading = self.TEMPLATE.replace(self.HEADING_EXPRESSION, heading_tag).replace(self.CLASSNAME_EXPRESSION, setting['class_name'].get(heading_tag, )).replace(self.TEXT_EXPRESSION, child_text) return heading
def build(self, block: HeadingBlock, child_text: str) -> str: '\n ヘッダのHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのヘッダタグを含む文字列\n ' heading_tag = f'h{block.size}' heading = self.TEMPLATE.replace(self.HEADING_EXPRESSION, heading_tag).replace(self.CLASSNAME_EXPRESSION, setting['class_name'].get(heading_tag, )).replace(self.TEXT_EXPRESSION, child_text) return heading<|docstring|>ヘッダのHTML文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのヘッダタグを含む文字列<|endoftext|>
e79f846b59a176ef57a08a3d07e26ab2a7635072af17f7bc58f5c2c15215fe93
def build(self, block: QuoteBlock, child_text: str) -> str: '\n 引用要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのblockquoteタグを含む文字列\n ' blockquote = self.TEMPLATE.replace(self.CLASSNAME_EXPRESSION, setting['class_name']['blockquote']).replace(self.TEXT_EXPRESSION, child_text) return blockquote
引用要素のHTML文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのblockquoteタグを含む文字列
app/html/block_builder.py
build
a-pompom/Python-markdownParser
0
python
def build(self, block: QuoteBlock, child_text: str) -> str: '\n 引用要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのblockquoteタグを含む文字列\n ' blockquote = self.TEMPLATE.replace(self.CLASSNAME_EXPRESSION, setting['class_name']['blockquote']).replace(self.TEXT_EXPRESSION, child_text) return blockquote
def build(self, block: QuoteBlock, child_text: str) -> str: '\n 引用要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのblockquoteタグを含む文字列\n ' blockquote = self.TEMPLATE.replace(self.CLASSNAME_EXPRESSION, setting['class_name']['blockquote']).replace(self.TEXT_EXPRESSION, child_text) return blockquote<|docstring|>引用要素のHTML文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのblockquoteタグを含む文字列<|endoftext|>
0ed0f7a2a91aa2e12b4f45a6789db693ab8b1cda56f564353b15ff3737cd30c4
def build(self, block: ListBlock, child_text: str) -> str: '\n リスト要素のHTML文字列を組み立て\n\n 子要素liの組み立てはListItemBuilderへ委譲\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのulタグを含む文字列\n ' unordered_list = self.TEMPLATE.replace(self.CLASSNAME_EXPRESSION, setting['class_name']['ul']).replace(self.TEXT_EXPRESSION, child_text) return unordered_list
リスト要素のHTML文字列を組み立て 子要素liの組み立てはListItemBuilderへ委譲 :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのulタグを含む文字列
app/html/block_builder.py
build
a-pompom/Python-markdownParser
0
python
def build(self, block: ListBlock, child_text: str) -> str: '\n リスト要素のHTML文字列を組み立て\n\n 子要素liの組み立てはListItemBuilderへ委譲\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのulタグを含む文字列\n ' unordered_list = self.TEMPLATE.replace(self.CLASSNAME_EXPRESSION, setting['class_name']['ul']).replace(self.TEXT_EXPRESSION, child_text) return unordered_list
def build(self, block: ListBlock, child_text: str) -> str: '\n リスト要素のHTML文字列を組み立て\n\n 子要素liの組み立てはListItemBuilderへ委譲\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのulタグを含む文字列\n ' unordered_list = self.TEMPLATE.replace(self.CLASSNAME_EXPRESSION, setting['class_name']['ul']).replace(self.TEXT_EXPRESSION, child_text) return unordered_list<|docstring|>リスト要素のHTML文字列を組み立て 子要素liの組み立てはListItemBuilderへ委譲 :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのulタグを含む文字列<|endoftext|>