code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import smtplib from unittest.mock import patch, Mock import pytest from logbook import Logger from fibratus.output.smtp import SmtpOutput @pytest.fixture(scope='module') def smtp_adapter(): config = { 'host': 'smtp.gmail.com', 'from': '<EMAIL>', 'password': '<PASSWORD>', 'to': ['<EMAIL>', '<EMAIL>'] } return SmtpOutput(**config) class TestSmtpOutput(object): def test_init(self, smtp_adapter): assert 'smtp.gmail.com' in smtp_adapter.host assert '<EMAIL>' in smtp_adapter.sender assert set(['<EMAIL>', '<EMAIL>']) == set(smtp_adapter.to) assert smtp_adapter.port == 587 def test_emit(self, smtp_adapter): body = 'Anomalous network activity detected from notepad.exe process' with patch('smtplib.SMTP'): smtp_adapter.emit(body, subject='Anomalous network activity detected') assert smtp_adapter._smtp.ehlo.call_count == 2 smtp_adapter._smtp.starttls.assert_called_once() smtp_adapter._smtp.login.assert_called_with('<EMAIL>', 'secret') message = 'From: <EMAIL>' \ 'To: <EMAIL>, <EMAIL>' \ 'Subject: Anomalous network activity detected' \ 'Anomalous network activity detected from notepad.exe process' smtp_adapter._smtp.login.sendmail('<EMAIL>', ['<EMAIL>', '<EMAIL>'], message) smtp_adapter._smtp.quit.assert_called_once() def test_emit_invalid_credentials(self, smtp_adapter): body = 'Anomalous network activity detected from notpead.exe process' smtp_adapter.logger = Mock(spec_set=Logger) with patch('smtplib.SMTP'): smtp_adapter._smtp.login.side_effect = smtplib.SMTPAuthenticationError(534, 'Invalid smtp credentials') smtp_adapter.emit(body, subject='Anomalous network activity detected') smtp_adapter.logger.error.assert_called_with('Invalid SMTP credentials for ' '<EMAIL>') smtp_adapter._smtp.quit.assert_called_once()
tests/unit/output/smtp.py
import smtplib from unittest.mock import patch, Mock import pytest from logbook import Logger from fibratus.output.smtp import SmtpOutput @pytest.fixture(scope='module') def smtp_adapter(): config = { 'host': 'smtp.gmail.com', 'from': '<EMAIL>', 'password': '<PASSWORD>', 'to': ['<EMAIL>', '<EMAIL>'] } return SmtpOutput(**config) class TestSmtpOutput(object): def test_init(self, smtp_adapter): assert 'smtp.gmail.com' in smtp_adapter.host assert '<EMAIL>' in smtp_adapter.sender assert set(['<EMAIL>', '<EMAIL>']) == set(smtp_adapter.to) assert smtp_adapter.port == 587 def test_emit(self, smtp_adapter): body = 'Anomalous network activity detected from notepad.exe process' with patch('smtplib.SMTP'): smtp_adapter.emit(body, subject='Anomalous network activity detected') assert smtp_adapter._smtp.ehlo.call_count == 2 smtp_adapter._smtp.starttls.assert_called_once() smtp_adapter._smtp.login.assert_called_with('<EMAIL>', 'secret') message = 'From: <EMAIL>' \ 'To: <EMAIL>, <EMAIL>' \ 'Subject: Anomalous network activity detected' \ 'Anomalous network activity detected from notepad.exe process' smtp_adapter._smtp.login.sendmail('<EMAIL>', ['<EMAIL>', '<EMAIL>'], message) smtp_adapter._smtp.quit.assert_called_once() def test_emit_invalid_credentials(self, smtp_adapter): body = 'Anomalous network activity detected from notpead.exe process' smtp_adapter.logger = Mock(spec_set=Logger) with patch('smtplib.SMTP'): smtp_adapter._smtp.login.side_effect = smtplib.SMTPAuthenticationError(534, 'Invalid smtp credentials') smtp_adapter.emit(body, subject='Anomalous network activity detected') smtp_adapter.logger.error.assert_called_with('Invalid SMTP credentials for ' '<EMAIL>') smtp_adapter._smtp.quit.assert_called_once()
0.409221
0.414662
from __future__ import unicode_literals import re from calendar import timegm from datetime import MAXYEAR, timedelta from dateutil import relativedelta from dateutil.tz import tzlocal, tzutc from faker.utils import is_string from faker.utils.datetime_safe import date, datetime, real_date, real_datetime from .. import BaseProvider localized = True def datetime_to_timestamp(dt): if getattr(dt, 'tzinfo', None) is not None: dt = dt.astimezone(tzutc()) return timegm(dt.timetuple()) def timestamp_to_datetime(timestamp, tzinfo): if tzinfo is None: pick = datetime.fromtimestamp(timestamp, tzlocal()) pick = pick.astimezone(tzutc()).replace(tzinfo=None) else: pick = datetime.fromtimestamp(timestamp, tzinfo) return pick class ParseError(ValueError): pass timedelta_pattern = r'' for name, sym in [('years', 'y'), ('months', 'M'), ('weeks', 'w'), ('days', 'd'), ('hours', 'h'), ('minutes', 'm'), ('seconds', 's')]: timedelta_pattern += r'((?P<{}>(?:\+|-)\d+?){})?'.format(name, sym) class Provider(BaseProvider): centuries = [ 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI', 'XVII', 'XVIII', 'XIX', 'XX', 'XXI'] countries = [{'timezones': ['Europe/Andorra'], 'alpha-2-code': 'AD', 'alpha-3-code': 'AND', 'continent': 'Europe', 'name': 'Andorra', 'capital': 'Andorra la Vella'}, {'timezones': ['Asia/Kabul'], 'alpha-2-code': 'AF', 'alpha-3-code': 'AFG', 'continent': 'Asia', 'name': 'Afghanistan', 'capital': 'Kabul'}, {'timezones': ['America/Antigua'], 'alpha-2-code': 'AG', 'alpha-3-code': 'ATG', 'continent': 'North America', 'name': 'Antigua and Barbuda', 'capital': "St. John's"}, {'timezones': ['Europe/Tirane'], 'alpha-2-code': 'AL', 'alpha-3-code': 'ALB', 'continent': 'Europe', 'name': 'Albania', 'capital': 'Tirana'}, {'timezones': ['Asia/Yerevan'], 'alpha-2-code': 'AM', 'alpha-3-code': 'ARM', 'continent': 'Asia', 'name': 'Armenia', 'capital': 'Yerevan'}, {'timezones': ['Africa/Luanda'], 'alpha-2-code': 'AO', 'alpha-3-code': 'AGO', 'continent': 'Africa', 'name': 'Angola', 'capital': 'Luanda'}, {'timezones': ['America/Argentina/Buenos_Aires', 'America/Argentina/Cordoba', 'America/Argentina/Jujuy', 'America/Argentina/Tucuman', 'America/Argentina/Catamarca', 'America/Argentina/La_Rioja', 'America/Argentina/San_Juan', 'America/Argentina/Mendoza', 'America/Argentina/Rio_Gallegos', 'America/Argentina/Ushuaia'], 'alpha-2-code': 'AR', 'alpha-3-code': 'ARG', 'continent': 'South America', 'name': 'Argentina', 'capital': 'Buenos Aires'}, {'timezones': ['Europe/Vienna'], 'alpha-2-code': 'AT', 'alpha-3-code': 'AUT', 'continent': 'Europe', 'name': 'Austria', 'capital': 'Vienna'}, {'timezones': ['Australia/Lord_Howe', 'Australia/Hobart', 'Australia/Currie', 'Australia/Melbourne', 'Australia/Sydney', 'Australia/Broken_Hill', 'Australia/Brisbane', 'Australia/Lindeman', 'Australia/Adelaide', 'Australia/Darwin', 'Australia/Perth'], 'alpha-2-code': 'AU', 'alpha-3-code': 'AUS', 'continent': 'Oceania', 'name': 'Australia', 'capital': 'Canberra'}, {'timezones': ['Asia/Baku'], 'alpha-2-code': 'AZ', 'alpha-3-code': 'AZE', 'continent': 'Asia', 'name': 'Azerbaijan', 'capital': 'Baku'}, {'timezones': ['America/Barbados'], 'alpha-2-code': 'BB', 'alpha-3-code': 'BRB', 'continent': 'North America', 'name': 'Barbados', 'capital': 'Bridgetown'}, {'timezones': ['Asia/Dhaka'], 'alpha-2-code': 'BD', 'alpha-3-code': 'BGD', 'continent': 'Asia', 'name': 'Bangladesh', 'capital': 'Dhaka'}, {'timezones': ['Europe/Brussels'], 'alpha-2-code': 'BE', 'alpha-3-code': 'BEL', 'continent': 'Europe', 'name': 'Belgium', 'capital': 'Brussels'}, {'timezones': ['Africa/Ouagadougou'], 'alpha-2-code': 'BF', 'alpha-3-code': 'BFA', 'continent': 'Africa', 'name': 'Burkina Faso', 'capital': 'Ouagadougou'}, {'timezones': ['Europe/Sofia'], 'alpha-2-code': 'BG', 'alpha-3-code': 'BGR', 'continent': 'Europe', 'name': 'Bulgaria', 'capital': 'Sofia'}, {'timezones': ['Asia/Bahrain'], 'alpha-2-code': 'BH', 'alpha-3-code': 'BHR', 'continent': 'Asia', 'name': 'Bahrain', 'capital': 'Manama'}, {'timezones': ['Africa/Bujumbura'], 'alpha-2-code': 'BI', 'alpha-3-code': 'BDI', 'continent': 'Africa', 'name': 'Burundi', 'capital': 'Bujumbura'}, {'timezones': ['Africa/Porto-Novo'], 'alpha-2-code': 'BJ', 'alpha-3-code': 'BEN', 'continent': 'Africa', 'name': 'Benin', 'capital': 'Porto-Novo'}, {'timezones': ['Asia/Brunei'], 'alpha-2-code': 'BN', 'alpha-3-code': 'BRN', 'continent': 'Asia', 'name': '<NAME>', 'capital': 'Bandar Seri Begawan'}, {'timezones': ['America/La_Paz'], 'alpha-2-code': 'BO', 'alpha-3-code': 'BOL', 'continent': 'South America', 'name': 'Bolivia', 'capital': 'Sucre'}, {'timezones': ['America/Noronha', 'America/Belem', 'America/Fortaleza', 'America/Recife', 'America/Araguaina', 'America/Maceio', 'America/Bahia', 'America/Sao_Paulo', 'America/Campo_Grande', 'America/Cuiaba', 'America/Porto_Velho', 'America/Boa_Vista', 'America/Manaus', 'America/Eirunepe', 'America/Rio_Branco'], 'alpha-2-code': 'BR', 'alpha-3-code': 'BRA', 'continent': 'South America', 'name': 'Brazil', 'capital': 'Bras\xc3\xadlia'}, {'timezones': ['America/Nassau'], 'alpha-2-code': 'BS', 'alpha-3-code': 'BHS', 'continent': 'North America', 'name': 'Bahamas', 'capital': 'Nassau'}, {'timezones': ['Asia/Thimphu'], 'alpha-2-code': 'BT', 'alpha-3-code': 'BTN', 'continent': 'Asia', 'name': 'Bhutan', 'capital': 'Thimphu'}, {'timezones': ['Africa/Gaborone'], 'alpha-2-code': 'BW', 'alpha-3-code': 'BWA', 'continent': 'Africa', 'name': 'Botswana', 'capital': 'Gaborone'}, {'timezones': ['Europe/Minsk'], 'alpha-2-code': 'BY', 'alpha-3-code': 'BLR', 'continent': 'Europe', 'name': 'Belarus', 'capital': 'Minsk'}, {'timezones': ['America/Belize'], 'alpha-2-code': 'BZ', 'alpha-3-code': 'BLZ', 'continent': 'North America', 'name': 'Belize', 'capital': 'Belmopan'}, {'timezones': ['America/St_Johns', 'America/Halifax', 'America/Glace_Bay', 'America/Moncton', 'America/Goose_Bay', 'America/Blanc-Sablon', 'America/Montreal', 'America/Toronto', 'America/Nipigon', 'America/Thunder_Bay', 'America/Pangnirtung', 'America/Iqaluit', 'America/Atikokan', 'America/Rankin_Inlet', 'America/Winnipeg', 'America/Rainy_River', 'America/Cambridge_Bay', 'America/Regina', 'America/Swift_Current', 'America/Edmonton', 'America/Yellowknife', 'America/Inuvik', 'America/Dawson_Creek', 'America/Vancouver', 'America/Whitehorse', 'America/Dawson'], 'alpha-2-code': 'CA', 'alpha-3-code': 'CAN', 'continent': 'North America', 'name': 'Canada', 'capital': 'Ottawa'}, {'timezones': ['Africa/Kinshasa', 'Africa/Lubumbashi'], 'alpha-2-code': 'CD', 'alpha-3-code': 'COD', 'continent': 'Africa', 'name': 'Democratic Republic of the Congo', 'capital': 'Kinshasa'}, {'timezones': ['Africa/Brazzaville'], 'alpha-2-code': 'CG', 'alpha-3-code': 'COG', 'continent': 'Africa', 'name': 'Republic of the Congo', 'capital': 'Brazzaville'}, {'timezones': ['Africa/Abidjan'], 'alpha-2-code': 'CI', 'alpha-3-code': 'CIV', 'continent': 'Africa', 'name': "C\xc3\xb4te d'Ivoire", 'capital': 'Yamoussoukro'}, {'timezones': ['America/Santiago', 'Pacific/Easter'], 'alpha-2-code': 'CL', 'alpha-3-code': 'CHL', 'continent': 'South America', 'name': 'Chile', 'capital': 'Santiago'}, {'timezones': ['Africa/Douala'], 'alpha-2-code': 'CM', 'alpha-3-code': 'CMR', 'continent': 'Africa', 'name': 'Cameroon', 'capital': 'Yaound\xc3\xa9'}, {'timezones': ['Asia/Shanghai', 'Asia/Harbin', 'Asia/Chongqing', 'Asia/Urumqi', 'Asia/Kashgar'], 'alpha-2-code': 'CN', 'alpha-3-code': 'CHN', 'continent': 'Asia', 'name': "People's Republic of China", 'capital': 'Beijing'}, {'timezones': ['America/Bogota'], 'alpha-2-code': 'CO', 'alpha-3-code': 'COL', 'continent': 'South America', 'name': 'Colombia', 'capital': 'Bogot\xc3\xa1'}, {'timezones': ['America/Costa_Rica'], 'alpha-2-code': 'CR', 'alpha-3-code': 'CRI', 'continent': 'North America', 'name': 'Costa Rica', 'capital': 'San Jos\xc3\xa9'}, {'timezones': ['America/Havana'], 'alpha-2-code': 'CU', 'alpha-3-code': 'CUB', 'continent': 'North America', 'name': 'Cuba', 'capital': 'Havana'}, {'timezones': ['Atlantic/Cape_Verde'], 'alpha-2-code': 'CV', 'alpha-3-code': 'CPV', 'continent': 'Africa', 'name': 'Cape Verde', 'capital': 'Praia'}, {'timezones': ['Asia/Nicosia'], 'alpha-2-code': 'CY', 'alpha-3-code': 'CYP', 'continent': 'Asia', 'name': 'Cyprus', 'capital': 'Nicosia'}, {'timezones': ['Europe/Prague'], 'alpha-2-code': 'CZ', 'alpha-3-code': 'CZE', 'continent': 'Europe', 'name': 'Czech Republic', 'capital': 'Prague'}, {'timezones': ['Europe/Berlin'], 'alpha-2-code': 'DE', 'alpha-3-code': 'DEU', 'continent': 'Europe', 'name': 'Germany', 'capital': 'Berlin'}, {'timezones': ['Africa/Djibouti'], 'alpha-2-code': 'DJ', 'alpha-3-code': 'DJI', 'continent': 'Africa', 'name': 'Djibouti', 'capital': 'Djibouti City'}, {'timezones': ['Europe/Copenhagen'], 'alpha-2-code': 'DK', 'alpha-3-code': 'DNK', 'continent': 'Europe', 'name': 'Denmark', 'capital': 'Copenhagen'}, {'timezones': ['America/Dominica'], 'alpha-2-code': 'DM', 'alpha-3-code': 'DMA', 'continent': 'North America', 'name': 'Dominica', 'capital': 'Roseau'}, {'timezones': ['America/Santo_Domingo'], 'alpha-2-code': 'DO', 'alpha-3-code': 'DOM', 'continent': 'North America', 'name': 'Dominican Republic', 'capital': 'Santo Domingo'}, {'timezones': ['America/Guayaquil', 'Pacific/Galapagos'], 'alpha-2-code': 'EC', 'alpha-3-code': 'ECU', 'continent': 'South America', 'name': 'Ecuador', 'capital': 'Quito'}, {'timezones': ['Europe/Tallinn'], 'alpha-2-code': 'EE', 'alpha-3-code': 'EST', 'continent': 'Europe', 'name': 'Estonia', 'capital': 'Tallinn'}, {'timezones': ['Africa/Cairo'], 'alpha-2-code': 'EG', 'alpha-3-code': 'EGY', 'continent': 'Africa', 'name': 'Egypt', 'capital': 'Cairo'}, {'timezones': ['Africa/Asmera'], 'alpha-2-code': 'ER', 'alpha-3-code': 'ERI', 'continent': 'Africa', 'name': 'Eritrea', 'capital': 'Asmara'}, {'timezones': ['Africa/Addis_Ababa'], 'alpha-2-code': 'ET', 'alpha-3-code': 'ETH', 'continent': 'Africa', 'name': 'Ethiopia', 'capital': 'Addis Ababa'}, {'timezones': ['Europe/Helsinki'], 'alpha-2-code': 'FI', 'alpha-3-code': 'FIN', 'continent': 'Europe', 'name': 'Finland', 'capital': 'Helsinki'}, {'timezones': ['Pacific/Fiji'], 'alpha-2-code': 'FJ', 'alpha-3-code': 'FJI', 'continent': 'Oceania', 'name': 'Fiji', 'capital': 'Suva'}, {'timezones': ['Europe/Paris'], 'alpha-2-code': 'FR', 'alpha-3-code': 'FRA', 'continent': 'Europe', 'name': 'France', 'capital': 'Paris'}, {'timezones': ['Africa/Libreville'], 'alpha-2-code': 'GA', 'alpha-3-code': 'GAB', 'continent': 'Africa', 'name': 'Gabon', 'capital': 'Libreville'}, {'timezones': ['Asia/Tbilisi'], 'alpha-2-code': 'GE', 'alpha-3-code': 'GEO', 'continent': 'Asia', 'name': 'Georgia', 'capital': 'Tbilisi'}, {'timezones': ['Africa/Accra'], 'alpha-2-code': 'GH', 'alpha-3-code': 'GHA', 'continent': 'Africa', 'name': 'Ghana', 'capital': 'Accra'}, {'timezones': ['Africa/Banjul'], 'alpha-2-code': 'GM', 'alpha-3-code': 'GMB', 'continent': 'Africa', 'name': 'The Gambia', 'capital': 'Banjul'}, {'timezones': ['Africa/Conakry'], 'alpha-2-code': 'GN', 'alpha-3-code': 'GIN', 'continent': 'Africa', 'name': 'Guinea', 'capital': 'Conakry'}, {'timezones': ['Europe/Athens'], 'alpha-2-code': 'GR', 'alpha-3-code': 'GRC', 'continent': 'Europe', 'name': 'Greece', 'capital': 'Athens'}, {'timezones': ['America/Guatemala'], 'alpha-2-code': 'GT', 'alpha-3-code': 'GTM', 'continent': 'North America', 'name': 'Guatemala', 'capital': 'Guatemala City'}, {'timezones': ['America/Guatemala'], 'alpha-2-code': 'HT', 'alpha-3-code': 'HTI', 'continent': 'North America', 'name': 'Haiti', 'capital': 'Port-au-Prince'}, {'timezones': ['Africa/Bissau'], 'alpha-2-code': 'GW', 'alpha-3-code': 'GNB', 'continent': 'Africa', 'name': 'Guinea-Bissau', 'capital': 'Bissau'}, {'timezones': ['America/Guyana'], 'alpha-2-code': 'GY', 'alpha-3-code': 'GUY', 'continent': 'South America', 'name': 'Guyana', 'capital': 'Georgetown'}, {'timezones': ['America/Tegucigalpa'], 'alpha-2-code': 'HN', 'alpha-3-code': 'HND', 'continent': 'North America', 'name': 'Honduras', 'capital': 'Tegucigalpa'}, {'timezones': ['Europe/Budapest'], 'alpha-2-code': 'HU', 'alpha-3-code': 'HUN', 'continent': 'Europe', 'name': 'Hungary', 'capital': 'Budapest'}, {'timezones': ['Asia/Jakarta', 'Asia/Pontianak', 'Asia/Makassar', 'Asia/Jayapura'], 'alpha-2-code': 'ID', 'alpha-3-code': 'IDN', 'continent': 'Asia', 'name': 'Indonesia', 'capital': 'Jakarta'}, {'timezones': ['Europe/Dublin'], 'alpha-2-code': 'IE', 'alpha-3-code': 'IRL', 'continent': 'Europe', 'name': 'Republic of Ireland', 'capital': 'Dublin'}, {'timezones': ['Asia/Jerusalem'], 'alpha-2-code': 'IL', 'alpha-3-code': 'ISR', 'continent': 'Asia', 'name': 'Israel', 'capital': 'Jerusalem'}, {'timezones': ['Asia/Calcutta'], 'alpha-2-code': 'IN', 'alpha-3-code': 'IND', 'continent': 'Asia', 'name': 'India', 'capital': 'New Delhi'}, {'timezones': ['Asia/Baghdad'], 'alpha-2-code': 'IQ', 'alpha-3-code': 'IRQ', 'continent': 'Asia', 'name': 'Iraq', 'capital': 'Baghdad'}, {'timezones': ['Asia/Tehran'], 'alpha-2-code': 'IR', 'alpha-3-code': 'IRN', 'continent': 'Asia', 'name': 'Iran', 'capital': 'Tehran'}, {'timezones': ['Atlantic/Reykjavik'], 'alpha-2-code': 'IS', 'alpha-3-code': 'ISL', 'continent': 'Europe', 'name': 'Iceland', 'capital': 'Reykjav\xc3\xadk'}, {'timezones': ['Europe/Rome'], 'alpha-2-code': 'IT', 'alpha-3-code': 'ITA', 'continent': 'Europe', 'name': 'Italy', 'capital': 'Rome'}, {'timezones': ['America/Jamaica'], 'alpha-2-code': 'JM', 'alpha-3-code': 'JAM', 'continent': 'North America', 'name': 'Jamaica', 'capital': 'Kingston'}, {'timezones': ['Asia/Amman'], 'alpha-2-code': 'JO', 'alpha-3-code': 'JOR', 'continent': 'Asia', 'name': 'Jordan', 'capital': 'Amman'}, {'timezones': ['Asia/Tokyo'], 'alpha-2-code': 'JP', 'alpha-3-code': 'JPN', 'continent': 'Asia', 'name': 'Japan', 'capital': 'Tokyo'}, {'timezones': ['Africa/Nairobi'], 'alpha-2-code': 'KE', 'alpha-3-code': 'KEN', 'continent': 'Africa', 'name': 'Kenya', 'capital': 'Nairobi'}, {'timezones': ['Asia/Bishkek'], 'alpha-2-code': 'KG', 'alpha-3-code': 'KGZ', 'continent': 'Asia', 'name': 'Kyrgyzstan', 'capital': 'Bishkek'}, {'timezones': ['Pacific/Tarawa', 'Pacific/Enderbury', 'Pacific/Kiritimati'], 'alpha-2-code': 'KI', 'alpha-3-code': 'KIR', 'continent': 'Oceania', 'name': 'Kiribati', 'capital': 'Tarawa'}, {'timezones': ['Asia/Pyongyang'], 'alpha-2-code': 'KP', 'alpha-3-code': 'PRK', 'continent': 'Asia', 'name': 'North Korea', 'capital': 'Pyongyang'}, {'timezones': ['Asia/Seoul'], 'alpha-2-code': 'KR', 'alpha-3-code': 'KOR', 'continent': 'Asia', 'name': 'South Korea', 'capital': 'Seoul'}, {'timezones': ['Asia/Kuwait'], 'alpha-2-code': 'KW', 'alpha-3-code': 'KWT', 'continent': 'Asia', 'name': 'Kuwait', 'capital': 'Kuwait City'}, {'timezones': ['Asia/Beirut'], 'alpha-2-code': 'LB', 'alpha-3-code': 'LBN', 'continent': 'Asia', 'name': 'Lebanon', 'capital': 'Beirut'}, {'timezones': ['Europe/Vaduz'], 'alpha-2-code': 'LI', 'alpha-3-code': 'LIE', 'continent': 'Europe', 'name': 'Liechtenstein', 'capital': 'Vaduz'}, {'timezones': ['Africa/Monrovia'], 'alpha-2-code': 'LR', 'alpha-3-code': 'LBR', 'continent': 'Africa', 'name': 'Liberia', 'capital': 'Monrovia'}, {'timezones': ['Africa/Maseru'], 'alpha-2-code': 'LS', 'alpha-3-code': 'LSO', 'continent': 'Africa', 'name': 'Lesotho', 'capital': 'Maseru'}, {'timezones': ['Europe/Vilnius'], 'alpha-2-code': 'LT', 'alpha-3-code': 'LTU', 'continent': 'Europe', 'name': 'Lithuania', 'capital': 'Vilnius'}, {'timezones': ['Europe/Luxembourg'], 'alpha-2-code': 'LU', 'alpha-3-code': 'LUX', 'continent': 'Europe', 'name': 'Luxembourg', 'capital': 'Luxembourg City'}, {'timezones': ['Europe/Riga'], 'alpha-2-code': 'LV', 'alpha-3-code': 'LVA', 'continent': 'Europe', 'name': 'Latvia', 'capital': 'Riga'}, {'timezones': ['Africa/Tripoli'], 'alpha-2-code': 'LY', 'alpha-3-code': 'LBY', 'continent': 'Africa', 'name': 'Libya', 'capital': 'Tripoli'}, {'timezones': ['Indian/Antananarivo'], 'alpha-2-code': 'MG', 'alpha-3-code': 'MDG', 'continent': 'Africa', 'name': 'Madagascar', 'capital': 'Antananarivo'}, {'timezones': ['Pacific/Majuro', 'Pacific/Kwajalein'], 'alpha-2-code': 'MH', 'alpha-3-code': 'MHL', 'continent': 'Oceania', 'name': 'Marshall Islands', 'capital': 'Majuro'}, {'timezones': ['Europe/Skopje'], 'alpha-2-code': 'MK', 'alpha-3-code': 'MKD', 'continent': 'Europe', 'name': 'Macedonia', 'capital': 'Skopje'}, {'timezones': ['Africa/Bamako'], 'alpha-2-code': 'ML', 'alpha-3-code': 'MLI', 'continent': 'Africa', 'name': 'Mali', 'capital': 'Bamako'}, {'timezones': ['Asia/Rangoon'], 'alpha-2-code': 'MM', 'alpha-3-code': 'MMR', 'continent': 'Asia', 'name': 'Myanmar', 'capital': 'Naypyidaw'}, {'timezones': ['Asia/Ulaanbaatar', 'Asia/Hovd', 'Asia/Choibalsan'], 'alpha-2-code': 'MN', 'alpha-3-code': 'MNG', 'continent': 'Asia', 'name': 'Mongolia', 'capital': 'Ulaanbaatar'}, {'timezones': ['Africa/Nouakchott'], 'alpha-2-code': 'MR', 'alpha-3-code': 'MRT', 'continent': 'Africa', 'name': 'Mauritania', 'capital': 'Nouakchott'}, {'timezones': ['Europe/Malta'], 'alpha-2-code': 'MT', 'alpha-3-code': 'MLT', 'continent': 'Europe', 'name': 'Malta', 'capital': 'Valletta'}, {'timezones': ['Indian/Mauritius'], 'alpha-2-code': 'MU', 'alpha-3-code': 'MUS', 'continent': 'Africa', 'name': 'Mauritius', 'capital': 'Port Louis'}, {'timezones': ['Indian/Maldives'], 'alpha-2-code': 'MV', 'alpha-3-code': 'MDV', 'continent': 'Asia', 'name': 'Maldives', 'capital': 'Mal\xc3\xa9'}, {'timezones': ['Africa/Blantyre'], 'alpha-2-code': 'MW', 'alpha-3-code': 'MWI', 'continent': 'Africa', 'name': 'Malawi', 'capital': 'Lilongwe'}, {'timezones': ['America/Mexico_City', 'America/Cancun', 'America/Merida', 'America/Monterrey', 'America/Mazatlan', 'America/Chihuahua', 'America/Hermosillo', 'America/Tijuana'], 'alpha-2-code': 'MX', 'alpha-3-code': 'MEX', 'continent': 'North America', 'name': 'Mexico', 'capital': 'Mexico City'}, {'timezones': ['Asia/Kuala_Lumpur', 'Asia/Kuching'], 'alpha-2-code': 'MY', 'alpha-3-code': 'MYS', 'continent': 'Asia', 'name': 'Malaysia', 'capital': 'Kuala Lumpur'}, {'timezones': ['Africa/Maputo'], 'alpha-2-code': 'MZ', 'alpha-3-code': 'MOZ', 'continent': 'Africa', 'name': 'Mozambique', 'capital': 'Maputo'}, {'timezones': ['Africa/Windhoek'], 'alpha-2-code': 'NA', 'alpha-3-code': 'NAM', 'continent': 'Africa', 'name': 'Namibia', 'capital': 'Windhoek'}, {'timezones': ['Africa/Niamey'], 'alpha-2-code': 'NE', 'alpha-3-code': 'NER', 'continent': 'Africa', 'name': 'Niger', 'capital': 'Niamey'}, {'timezones': ['Africa/Lagos'], 'alpha-2-code': 'NG', 'alpha-3-code': 'NGA', 'continent': 'Africa', 'name': 'Nigeria', 'capital': 'Abuja'}, {'timezones': ['America/Managua'], 'alpha-2-code': 'NI', 'alpha-3-code': 'NIC', 'continent': 'North America', 'name': 'Nicaragua', 'capital': 'Managua'}, {'timezones': ['Europe/Amsterdam'], 'alpha-2-code': 'NL', 'alpha-3-code': 'NLD', 'continent': 'Europe', 'name': 'Kingdom of the Netherlands', 'capital': 'Amsterdam'}, {'timezones': ['Europe/Oslo'], 'alpha-2-code': 'NO', 'alpha-3-code': 'NOR', 'continent': 'Europe', 'name': 'Norway', 'capital': 'Oslo'}, {'timezones': ['Asia/Katmandu'], 'alpha-2-code': 'NP', 'alpha-3-code': 'NPL', 'continent': 'Asia', 'name': 'Nepal', 'capital': 'Kathmandu'}, {'timezones': ['Pacific/Nauru'], 'alpha-2-code': 'NR', 'alpha-3-code': 'NRU', 'continent': 'Oceania', 'name': 'Nauru', 'capital': 'Yaren'}, {'timezones': ['Pacific/Auckland', 'Pacific/Chatham'], 'alpha-2-code': 'NZ', 'alpha-3-code': 'NZL', 'continent': 'Oceania', 'name': 'New Zealand', 'capital': 'Wellington'}, {'timezones': ['Asia/Muscat'], 'alpha-2-code': 'OM', 'alpha-3-code': 'OMN', 'continent': 'Asia', 'name': 'Oman', 'capital': 'Muscat'}, {'timezones': ['America/Panama'], 'alpha-2-code': 'PA', 'alpha-3-code': 'PAN', 'continent': 'North America', 'name': 'Panama', 'capital': 'Panama City'}, {'timezones': ['America/Lima'], 'alpha-2-code': 'PE', 'alpha-3-code': 'PER', 'continent': 'South America', 'name': 'Peru', 'capital': 'Lima'}, {'timezones': ['Pacific/Port_Moresby'], 'alpha-2-code': 'PG', 'alpha-3-code': 'PNG', 'continent': 'Oceania', 'name': 'Papua New Guinea', 'capital': 'Port Moresby'}, {'timezones': ['Asia/Manila'], 'alpha-2-code': 'PH', 'alpha-3-code': 'PHL', 'continent': 'Asia', 'name': 'Philippines', 'capital': 'Manila'}, {'timezones': ['Asia/Karachi'], 'alpha-2-code': 'PK', 'alpha-3-code': 'PAK', 'continent': 'Asia', 'name': 'Pakistan', 'capital': 'Islamabad'}, {'timezones': ['Europe/Warsaw'], 'alpha-2-code': 'PL', 'alpha-3-code': 'POL', 'continent': 'Europe', 'name': 'Poland', 'capital': 'Warsaw'}, {'timezones': ['Europe/Lisbon', 'Atlantic/Madeira', 'Atlantic/Azores'], 'alpha-2-code': 'PT', 'alpha-3-code': 'PRT', 'continent': 'Europe', 'name': 'Portugal', 'capital': 'Lisbon'}, {'timezones': ['Pacific/Palau'], 'alpha-2-code': 'PW', 'alpha-3-code': 'PLW', 'continent': 'Oceania', 'name': 'Palau', 'capital': 'Ngerulmud'}, {'timezones': ['America/Asuncion'], 'alpha-2-code': 'PY', 'alpha-3-code': 'PRY', 'continent': 'South America', 'name': 'Paraguay', 'capital': 'Asunci\xc3\xb3n'}, {'timezones': ['Asia/Qatar'], 'alpha-2-code': 'QA', 'alpha-3-code': 'QAT', 'continent': 'Asia', 'name': 'Qatar', 'capital': 'Doha'}, {'timezones': ['Europe/Bucharest'], 'alpha-2-code': 'RO', 'alpha-3-code': 'ROU', 'continent': 'Europe', 'name': 'Romania', 'capital': 'Bucharest'}, {'timezones': ['Europe/Kaliningrad', 'Europe/Moscow', 'Europe/Volgograd', 'Europe/Samara', 'Asia/Yekaterinburg', 'Asia/Omsk', 'Asia/Novosibirsk', 'Asia/Krasnoyarsk', 'Asia/Irkutsk', 'Asia/Yakutsk', 'Asia/Vladivostok', 'Asia/Sakhalin', 'Asia/Magadan', 'Asia/Kamchatka', 'Asia/Anadyr'], 'alpha-2-code': 'RU', 'alpha-3-code': 'RUS', 'continent': 'Europe', 'name': 'Russia', 'capital': 'Moscow'}, {'timezones': ['Africa/Kigali'], 'alpha-2-code': 'RW', 'alpha-3-code': 'RWA', 'continent': 'Africa', 'name': 'Rwanda', 'capital': 'Kigali'}, {'timezones': ['Asia/Riyadh'], 'alpha-2-code': 'SA', 'alpha-3-code': 'SAU', 'continent': 'Asia', 'name': '<NAME>', 'capital': 'Riyadh'}, {'timezones': ['Pacific/Guadalcanal'], 'alpha-2-code': 'SB', 'alpha-3-code': 'SLB', 'continent': 'Oceania', 'name': 'Solomon Islands', 'capital': 'Honiara'}, {'timezones': ['Indian/Mahe'], 'alpha-2-code': 'SC', 'alpha-3-code': 'SYC', 'continent': 'Africa', 'name': 'Seychelles', 'capital': 'Victoria'}, {'timezones': ['Africa/Khartoum'], 'alpha-2-code': 'SD', 'alpha-3-code': 'SDN', 'continent': 'Africa', 'name': 'Sudan', 'capital': 'Khartoum'}, {'timezones': ['Europe/Stockholm'], 'alpha-2-code': 'SE', 'alpha-3-code': 'SWE', 'continent': 'Europe', 'name': 'Sweden', 'capital': 'Stockholm'}, {'timezones': ['Asia/Singapore'], 'alpha-2-code': 'SG', 'alpha-3-code': 'SGP', 'continent': 'Asia', 'name': 'Singapore', 'capital': 'Singapore'}, {'timezones': ['Europe/Ljubljana'], 'alpha-2-code': 'SI', 'alpha-3-code': 'SVN', 'continent': 'Europe', 'name': 'Slovenia', 'capital': 'Ljubljana'}, {'timezones': ['Europe/Bratislava'], 'alpha-2-code': 'SK', 'alpha-3-code': 'SVK', 'continent': 'Europe', 'name': 'Slovakia', 'capital': 'Bratislava'}, {'timezones': ['Africa/Freetown'], 'alpha-2-code': 'SL', 'alpha-3-code': 'SLE', 'continent': 'Africa', 'name': 'Sierra Leone', 'capital': 'Freetown'}, {'timezones': ['Europe/San_Marino'], 'alpha-2-code': 'SM', 'alpha-3-code': 'SMR', 'continent': 'Europe', 'name': 'San Marino', 'capital': 'San Marino'}, {'timezones': ['Africa/Dakar'], 'alpha-2-code': 'SN', 'alpha-3-code': 'SEN', 'continent': 'Africa', 'name': 'Senegal', 'capital': 'Dakar'}, {'timezones': ['Africa/Mogadishu'], 'alpha-2-code': 'SO', 'alpha-3-code': 'SOM', 'continent': 'Africa', 'name': 'Somalia', 'capital': 'Mogadishu'}, {'timezones': ['America/Paramaribo'], 'alpha-2-code': 'SR', 'alpha-3-code': 'SUR', 'continent': 'South America', 'name': 'Suriname', 'capital': 'Paramaribo'}, {'timezones': ['Africa/Sao_Tome'], 'alpha-2-code': 'ST', 'alpha-3-code': 'STP', 'continent': 'Africa', 'name': 'S\xc3\xa3o Tom\xc3\xa9 and Pr\xc3\xadncipe', 'capital': 'S\xc3\xa3o Tom\xc3\xa9'}, {'timezones': ['Asia/Damascus'], 'alpha-2-code': 'SY', 'alpha-3-code': 'SYR', 'continent': 'Asia', 'name': 'Syria', 'capital': 'Damascus'}, {'timezones': ['Africa/Lome'], 'alpha-2-code': 'TG', 'alpha-3-code': 'TGO', 'continent': 'Africa', 'name': 'Togo', 'capital': 'Lom\xc3\xa9'}, {'timezones': ['Asia/Bangkok'], 'alpha-2-code': 'TH', 'alpha-3-code': 'THA', 'continent': 'Asia', 'name': 'Thailand', 'capital': 'Bangkok'}, {'timezones': ['Asia/Dushanbe'], 'alpha-2-code': 'TJ', 'alpha-3-code': 'TJK', 'continent': 'Asia', 'name': 'Tajikistan', 'capital': 'Dushanbe'}, {'timezones': ['Asia/Ashgabat'], 'alpha-2-code': 'TM', 'alpha-3-code': 'TKM', 'continent': 'Asia', 'name': 'Turkmenistan', 'capital': 'Ashgabat'}, {'timezones': ['Africa/Tunis'], 'alpha-2-code': 'TN', 'alpha-3-code': 'TUN', 'continent': 'Africa', 'name': 'Tunisia', 'capital': 'Tunis'}, {'timezones': ['Pacific/Tongatapu'], 'alpha-2-code': 'TO', 'alpha-3-code': 'TON', 'continent': 'Oceania', 'name': 'Tonga', 'capital': 'Nuku\xca\xbbalofa'}, {'timezones': ['Europe/Istanbul'], 'alpha-2-code': 'TR', 'alpha-3-code': 'TUR', 'continent': 'Asia', 'name': 'Turkey', 'capital': 'Ankara'}, {'timezones': ['America/Port_of_Spain'], 'alpha-2-code': 'TT', 'alpha-3-code': 'TTO', 'continent': 'North America', 'name': 'Trinidad and Tobago', 'capital': 'Port of Spain'}, {'timezones': ['Pacific/Funafuti'], 'alpha-2-code': 'TV', 'alpha-3-code': 'TUV', 'continent': 'Oceania', 'name': 'Tuvalu', 'capital': 'Funafuti'}, {'timezones': ['Africa/Dar_es_Salaam'], 'alpha-2-code': 'TZ', 'alpha-3-code': 'TZA', 'continent': 'Africa', 'name': 'Tanzania', 'capital': 'Dodoma'}, {'timezones': ['Europe/Kiev', 'Europe/Uzhgorod', 'Europe/Zaporozhye', 'Europe/Simferopol'], 'alpha-2-code': 'UA', 'alpha-3-code': 'UKR', 'continent': 'Europe', 'name': 'Ukraine', 'capital': 'Kiev'}, {'timezones': ['Africa/Kampala'], 'alpha-2-code': 'UG', 'alpha-3-code': 'UGA', 'continent': 'Africa', 'name': 'Uganda', 'capital': 'Kampala'}, {'timezones': ['America/New_York', 'America/Detroit', 'America/Kentucky/Louisville', 'America/Kentucky/Monticello', 'America/Indiana/Indianapolis', 'America/Indiana/Marengo', 'America/Indiana/Knox', 'America/Indiana/Vevay', 'America/Chicago', 'America/Indiana/Vincennes', 'America/Indiana/Petersburg', 'America/Menominee', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/Denver', 'America/Boise', 'America/Shiprock', 'America/Phoenix', 'America/Los_Angeles', 'America/Anchorage', 'America/Juneau', 'America/Yakutat', 'America/Nome', 'America/Adak', 'Pacific/Honolulu'], 'alpha-2-code': 'US', 'alpha-3-code': 'USA', 'continent': 'North America', 'name': 'United States', 'capital': 'Washington, D.C.'}, {'timezones': ['America/Montevideo'], 'alpha-2-code': 'UY', 'alpha-3-code': 'URY', 'continent': 'South America', 'name': 'Uruguay', 'capital': 'Montevideo'}, {'timezones': ['Asia/Samarkand', 'Asia/Tashkent'], 'alpha-2-code': 'UZ', 'alpha-3-code': 'UZB', 'continent': 'Asia', 'name': 'Uzbekistan', 'capital': 'Tashkent'}, {'timezones': ['Europe/Vatican'], 'alpha-2-code': 'VA', 'alpha-3-code': 'VAT', 'continent': 'Europe', 'name': 'Vatican City', 'capital': 'Vatican City'}, {'timezones': ['America/Caracas'], 'alpha-2-code': 'VE', 'alpha-3-code': 'VEN', 'continent': 'South America', 'name': 'Venezuela', 'capital': 'Caracas'}, {'timezones': ['Asia/Saigon'], 'alpha-2-code': 'VN', 'alpha-3-code': 'VNM', 'continent': 'Asia', 'name': 'Vietnam', 'capital': 'Hanoi'}, {'timezones': ['Pacific/Efate'], 'alpha-2-code': 'VU', 'alpha-3-code': 'VUT', 'continent': 'Oceania', 'name': 'Vanuatu', 'capital': 'Port Vila'}, {'timezones': ['Asia/Aden'], 'alpha-2-code': 'YE', 'alpha-3-code': 'YEM', 'continent': 'Asia', 'name': 'Yemen', 'capital': "Sana'a"}, {'timezones': ['Africa/Lusaka'], 'alpha-2-code': 'ZM', 'alpha-3-code': 'ZMB', 'continent': 'Africa', 'name': 'Zambia', 'capital': 'Lusaka'}, {'timezones': ['Africa/Harare'], 'alpha-2-code': 'ZW', 'alpha-3-code': 'ZWE', 'continent': 'Africa', 'name': 'Zimbabwe', 'capital': 'Harare'}, {'timezones': ['Africa/Algiers'], 'alpha-2-code': 'DZ', 'alpha-3-code': 'DZA', 'continent': 'Africa', 'name': 'Algeria', 'capital': 'Algiers'}, {'timezones': ['Europe/Sarajevo'], 'alpha-2-code': 'BA', 'alpha-3-code': 'BIH', 'continent': 'Europe', 'name': 'Bosnia and Herzegovina', 'capital': 'Sarajevo'}, {'timezones': ['Asia/Phnom_Penh'], 'alpha-2-code': 'KH', 'alpha-3-code': 'KHM', 'continent': 'Asia', 'name': 'Cambodia', 'capital': 'Phnom Penh'}, {'timezones': ['Africa/Bangui'], 'alpha-2-code': 'CF', 'alpha-3-code': 'CAF', 'continent': 'Africa', 'name': 'Central African Republic', 'capital': 'Bangui'}, {'timezones': ['Africa/Ndjamena'], 'alpha-2-code': 'TD', 'alpha-3-code': 'TCD', 'continent': 'Africa', 'name': 'Chad', 'capital': "N'Djamena"}, {'timezones': ['Indian/Comoro'], 'alpha-2-code': 'KM', 'alpha-3-code': 'COM', 'continent': 'Africa', 'name': 'Comoros', 'capital': 'Moroni'}, {'timezones': ['Europe/Zagreb'], 'alpha-2-code': 'HR', 'alpha-3-code': 'HRV', 'continent': 'Europe', 'name': 'Croatia', 'capital': 'Zagreb'}, {'timezones': ['Asia/Dili'], 'alpha-2-code': 'TL', 'alpha-3-code': 'TLS', 'continent': 'Asia', 'name': 'East Timor', 'capital': 'Dili'}, {'timezones': ['America/El_Salvador'], 'alpha-2-code': 'SV', 'alpha-3-code': 'SLV', 'continent': 'North America', 'name': 'El Salvador', 'capital': 'San Salvador'}, {'timezones': ['Africa/Malabo'], 'alpha-2-code': 'GQ', 'alpha-3-code': 'GNQ', 'continent': 'Africa', 'name': 'Equatorial Guinea', 'capital': 'Malabo'}, {'timezones': ['America/Grenada'], 'alpha-2-code': 'GD', 'alpha-3-code': 'GRD', 'continent': 'North America', 'name': 'Grenada', 'capital': "St. George's"}, {'timezones': ['Asia/Almaty', 'Asia/Qyzylorda', 'Asia/Aqtobe', 'Asia/Aqtau', 'Asia/Oral'], 'alpha-2-code': 'KZ', 'alpha-3-code': 'KAZ', 'continent': 'Asia', 'name': 'Kazakhstan', 'capital': 'Astana'}, {'timezones': ['Asia/Vientiane'], 'alpha-2-code': 'LA', 'alpha-3-code': 'LAO', 'continent': 'Asia', 'name': 'Laos', 'capital': 'Vientiane'}, {'timezones': ['Pacific/Truk', 'Pacific/Ponape', 'Pacific/Kosrae'], 'alpha-2-code': 'FM', 'alpha-3-code': 'FSM', 'continent': 'Oceania', 'name': 'Federated States of Micronesia', 'capital': 'Palikir'}, {'timezones': ['Europe/Chisinau'], 'alpha-2-code': 'MD', 'alpha-3-code': 'MDA', 'continent': 'Europe', 'name': 'Moldova', 'capital': 'Chi\xc5\x9fin\xc4\x83u'}, {'timezones': ['Europe/Monaco'], 'alpha-2-code': 'MC', 'alpha-3-code': 'MCO', 'continent': 'Europe', 'name': 'Monaco', 'capital': 'Monaco'}, {'timezones': ['Europe/Podgorica'], 'alpha-2-code': 'ME', 'alpha-3-code': 'MNE', 'continent': 'Europe', 'name': 'Montenegro', 'capital': 'Podgorica'}, {'timezones': ['Africa/Casablanca'], 'alpha-2-code': 'MA', 'alpha-3-code': 'MAR', 'continent': 'Africa', 'name': 'Morocco', 'capital': 'Rabat'}, {'timezones': ['America/St_Kitts'], 'alpha-2-code': 'KN', 'alpha-3-code': 'KNA', 'continent': 'North America', 'name': 'Saint Kitts and Nevis', 'capital': 'Basseterre'}, {'timezones': ['America/St_Lucia'], 'alpha-2-code': 'LC', 'alpha-3-code': 'LCA', 'continent': 'North America', 'name': 'Saint Lucia', 'capital': 'Castries'}, {'timezones': ['America/St_Vincent'], 'alpha-2-code': 'VC', 'alpha-3-code': 'VCT', 'continent': 'North America', 'name': 'Saint Vincent and the Grenadines', 'capital': 'Kingstown'}, {'timezones': ['Pacific/Apia'], 'alpha-2-code': 'WS', 'alpha-3-code': 'WSM', 'continent': 'Oceania', 'name': 'Samoa', 'capital': 'Apia'}, {'timezones': ['Europe/Belgrade'], 'alpha-2-code': 'RS', 'alpha-3-code': 'SRB', 'continent': 'Europe', 'name': 'Serbia', 'capital': 'Belgrade'}, {'timezones': ['Africa/Johannesburg'], 'alpha-2-code': 'ZA', 'alpha-3-code': 'ZAF', 'continent': 'Africa', 'name': 'South Africa', 'capital': 'Pretoria'}, {'timezones': ['Europe/Madrid', 'Africa/Ceuta', 'Atlantic/Canary'], 'alpha-2-code': 'ES', 'alpha-3-code': 'ESP', 'continent': 'Europe', 'name': 'Spain', 'capital': 'Madrid'}, {'timezones': ['Asia/Colombo'], 'alpha-2-code': 'LK', 'alpha-3-code': 'LKA', 'continent': 'Asia', 'name': 'Sri Lanka', 'capital': 'Sri Jayewardenepura Kotte'}, {'timezones': ['Africa/Mbabane'], 'alpha-2-code': 'SZ', 'alpha-3-code': 'SWZ', 'continent': 'Africa', 'name': 'Swaziland', 'capital': 'Mbabane'}, {'timezones': ['Europe/Zurich'], 'alpha-2-code': 'CH', 'alpha-3-code': 'CHE', 'continent': 'Europe', 'name': 'Switzerland', 'capital': 'Bern'}, {'timezones': ['Asia/Dubai'], 'alpha-2-code': 'AE', 'alpha-3-code': 'ARE', 'continent': 'Asia', 'name': 'United Arab Emirates', 'capital': 'Abu Dhabi'}, {'timezones': ['Europe/London'], 'alpha-2-code': 'GB', 'alpha-3-code': 'GBR', 'continent': 'Europe', 'name': 'United Kingdom', 'capital': 'London'}, ] regex = re.compile(timedelta_pattern) def unix_time(self, end_datetime=None, start_datetime=None): """ Get a timestamp between January 1, 1970 and now, unless passed explicit start_datetime or end_datetime values. :example 1061306726 """ start_datetime = self._parse_start_datetime(start_datetime) end_datetime = self._parse_end_datetime(end_datetime) return self.generator.random.randint(start_datetime, end_datetime) def time_delta(self, end_datetime=None): """ Get a timedelta object """ start_datetime = self._parse_start_datetime('now') end_datetime = self._parse_end_datetime(end_datetime) seconds = end_datetime - start_datetime ts = self.generator.random.randint(*sorted([0, seconds])) return timedelta(seconds=ts) def date_time(self, tzinfo=None, end_datetime=None): """ Get a datetime object for a date between January 1, 1970 and now :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2005-08-16 20:39:21') :return datetime """ # NOTE: On windows, the lowest value you can get from windows is 86400 # on the first day. Known python issue: # https://bugs.python.org/issue30684 return datetime(1970, 1, 1, tzinfo=tzinfo) + \ timedelta(seconds=self.unix_time(end_datetime=end_datetime)) def date_time_ad(self, tzinfo=None, end_datetime=None, start_datetime=None): """ Get a datetime object for a date between January 1, 001 and now :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1265-03-22 21:15:52') :return datetime """ # 1970-01-01 00:00:00 UTC minus 62135596800 seconds is # 0001-01-01 00:00:00 UTC. Since _parse_end_datetime() is used # elsewhere where a default value of 0 is expected, we can't # simply change that class method to use this magic number as a # default value when None is provided. start_time = -62135596800 if start_datetime is None else self._parse_start_datetime(start_datetime) end_datetime = self._parse_end_datetime(end_datetime) ts = self.generator.random.randint(start_time, end_datetime) # NOTE: using datetime.fromtimestamp(ts) directly will raise # a "ValueError: timestamp out of range for platform time_t" # on some platforms due to system C functions; # see http://stackoverflow.com/a/10588133/2315612 # NOTE: On windows, the lowest value you can get from windows is 86400 # on the first day. Known python issue: # https://bugs.python.org/issue30684 return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=ts) def iso8601(self, tzinfo=None, end_datetime=None): """ :param tzinfo: timezone, instance of datetime.tzinfo subclass :example '2003-10-21T16:05:52+0000' """ return self.date_time(tzinfo, end_datetime=end_datetime).isoformat() def date(self, pattern='%Y-%m-%d', end_datetime=None): """ Get a date string between January 1, 1970 and now :param pattern format :example '2008-11-27' """ return self.date_time(end_datetime=end_datetime).strftime(pattern) def date_object(self, end_datetime=None): """ Get a date object between January 1, 1970 and now :example datetime.date(2016, 9, 20) """ return self.date_time(end_datetime=end_datetime).date() def time(self, pattern='%H:%M:%S', end_datetime=None): """ Get a time string (24h format by default) :param pattern format :example '15:02:34' """ return self.date_time( end_datetime=end_datetime).time().strftime(pattern) def time_object(self, end_datetime=None): """ Get a time object :example datetime.time(15, 56, 56, 772876) """ return self.date_time(end_datetime=end_datetime).time() @classmethod def _parse_start_datetime(cls, value): if value is None: return 0 return cls._parse_date_time(value) @classmethod def _parse_end_datetime(cls, value): if value is None: return datetime_to_timestamp(datetime.now()) return cls._parse_date_time(value) @classmethod def _parse_date_string(cls, value): parts = cls.regex.match(value) if not parts: raise ParseError("Can't parse date string `{}`.".format(value)) parts = parts.groupdict() time_params = {} for (name_, param_) in parts.items(): if param_: time_params[name_] = int(param_) if 'years' in time_params: if 'days' not in time_params: time_params['days'] = 0 time_params['days'] += 365.24 * time_params.pop('years') if 'months' in time_params: if 'days' not in time_params: time_params['days'] = 0 time_params['days'] += 30.42 * time_params.pop('months') if not time_params: raise ParseError("Can't parse date string `{}`.".format(value)) return time_params @classmethod def _parse_timedelta(cls, value): if isinstance(value, timedelta): return value.total_seconds() if is_string(value): time_params = cls._parse_date_string(value) return timedelta(**time_params).total_seconds() if isinstance(value, (int, float)): return value raise ParseError("Invalid format for timedelta '{}'".format(value)) @classmethod def _parse_date_time(cls, value, tzinfo=None): if isinstance(value, (datetime, date, real_datetime, real_date)): return datetime_to_timestamp(value) now = datetime.now(tzinfo) if isinstance(value, timedelta): return datetime_to_timestamp(now + value) if is_string(value): if value == 'now': return datetime_to_timestamp(datetime.now(tzinfo)) time_params = cls._parse_date_string(value) return datetime_to_timestamp(now + timedelta(**time_params)) if isinstance(value, int): return datetime_to_timestamp(now + timedelta(value)) raise ParseError("Invalid format for date '{}'".format(value)) @classmethod def _parse_date(cls, value): if isinstance(value, (datetime, real_datetime)): return value.date() elif isinstance(value, (date, real_date)): return value today = date.today() if isinstance(value, timedelta): return today + value if is_string(value): if value in ('today', 'now'): return today time_params = cls._parse_date_string(value) return today + timedelta(**time_params) if isinstance(value, int): return today + timedelta(value) raise ParseError("Invalid format for date '{}'".format(value)) def date_time_between(self, start_date='-30y', end_date='now', tzinfo=None): """ Get a DateTime object based on a random date between two given dates. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to 30 years ago :param end_date Defaults to "now" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ start_date = self._parse_date_time(start_date, tzinfo=tzinfo) end_date = self._parse_date_time(end_date, tzinfo=tzinfo) if end_date - start_date <= 1: ts = start_date + self.generator.random.random() else: ts = self.generator.random.randint(start_date, end_date) if tzinfo is None: return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=ts) else: return ( datetime(1970, 1, 1, tzinfo=tzutc()) + timedelta(seconds=ts) ).astimezone(tzinfo) def date_between(self, start_date='-30y', end_date='today'): """ Get a Date object based on a random date between two given dates. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to 30 years ago :param end_date Defaults to "today" :example Date('1999-02-02') :return Date """ start_date = self._parse_date(start_date) end_date = self._parse_date(end_date) return self.date_between_dates(date_start=start_date, date_end=end_date) def future_datetime(self, end_date='+30d', tzinfo=None): """ Get a DateTime object based on a random date between 1 second form now and a given date. Accepts date strings that can be recognized by strtotime(). :param end_date Defaults to "+30d" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ return self.date_time_between( start_date='+1s', end_date=end_date, tzinfo=tzinfo, ) def future_date(self, end_date='+30d', tzinfo=None): """ Get a Date object based on a random date between 1 day from now and a given date. Accepts date strings that can be recognized by strtotime(). :param end_date Defaults to "+30d" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ return self.date_between(start_date='+1d', end_date=end_date) def past_datetime(self, start_date='-30d', tzinfo=None): """ Get a DateTime object based on a random date between a given date and 1 second ago. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to "-30d" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ return self.date_time_between( start_date=start_date, end_date='-1s', tzinfo=tzinfo, ) def past_date(self, start_date='-30d', tzinfo=None): """ Get a Date object based on a random date between a given date and 1 day ago. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to "-30d" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ return self.date_between(start_date=start_date, end_date='-1d') def date_time_between_dates( self, datetime_start=None, datetime_end=None, tzinfo=None): """ Takes two DateTime objects and returns a random datetime between the two given datetimes. Accepts DateTime objects. :param datetime_start: DateTime :param datetime_end: DateTime :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ if datetime_start is None: datetime_start = datetime.now(tzinfo) if datetime_end is None: datetime_end = datetime.now(tzinfo) timestamp = self.generator.random.randint( datetime_to_timestamp(datetime_start), datetime_to_timestamp(datetime_end), ) try: if tzinfo is None: pick = datetime.fromtimestamp(timestamp, tzlocal()) pick = pick.astimezone(tzutc()).replace(tzinfo=None) else: pick = datetime.fromtimestamp(timestamp, tzinfo) except OverflowError: raise OverflowError( "You specified an end date with a timestamp bigger than the maximum allowed on this" " system. Please specify an earlier date.", ) return pick def date_between_dates(self, date_start=None, date_end=None): """ Takes two Date objects and returns a random date between the two given dates. Accepts Date or Datetime objects :param date_start: Date :param date_end: Date :return Date """ return self.date_time_between_dates(date_start, date_end).date() def date_time_this_century( self, before_now=True, after_now=False, tzinfo=None): """ Gets a DateTime object for the current century. :param before_now: include days in current century before today :param after_now: include days in current century after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ now = datetime.now(tzinfo) this_century_start = datetime( now.year - (now.year % 100), 1, 1, tzinfo=tzinfo) next_century_start = datetime( min(this_century_start.year + 100, MAXYEAR), 1, 1, tzinfo=tzinfo) if before_now and after_now: return self.date_time_between_dates( this_century_start, next_century_start, tzinfo) elif not before_now and after_now: return self.date_time_between_dates(now, next_century_start, tzinfo) elif not after_now and before_now: return self.date_time_between_dates(this_century_start, now, tzinfo) else: return now def date_time_this_decade( self, before_now=True, after_now=False, tzinfo=None): """ Gets a DateTime object for the decade year. :param before_now: include days in current decade before today :param after_now: include days in current decade after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ now = datetime.now(tzinfo) this_decade_start = datetime( now.year - (now.year % 10), 1, 1, tzinfo=tzinfo) next_decade_start = datetime( min(this_decade_start.year + 10, MAXYEAR), 1, 1, tzinfo=tzinfo) if before_now and after_now: return self.date_time_between_dates( this_decade_start, next_decade_start, tzinfo) elif not before_now and after_now: return self.date_time_between_dates(now, next_decade_start, tzinfo) elif not after_now and before_now: return self.date_time_between_dates(this_decade_start, now, tzinfo) else: return now def date_time_this_year( self, before_now=True, after_now=False, tzinfo=None): """ Gets a DateTime object for the current year. :param before_now: include days in current year before today :param after_now: include days in current year after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ now = datetime.now(tzinfo) this_year_start = now.replace( month=1, day=1, hour=0, minute=0, second=0, microsecond=0) next_year_start = datetime(now.year + 1, 1, 1, tzinfo=tzinfo) if before_now and after_now: return self.date_time_between_dates( this_year_start, next_year_start, tzinfo) elif not before_now and after_now: return self.date_time_between_dates(now, next_year_start, tzinfo) elif not after_now and before_now: return self.date_time_between_dates(this_year_start, now, tzinfo) else: return now def date_time_this_month( self, before_now=True, after_now=False, tzinfo=None): """ Gets a DateTime object for the current month. :param before_now: include days in current month before today :param after_now: include days in current month after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ now = datetime.now(tzinfo) this_month_start = now.replace( day=1, hour=0, minute=0, second=0, microsecond=0) next_month_start = this_month_start + \ relativedelta.relativedelta(months=1) if before_now and after_now: return self.date_time_between_dates( this_month_start, next_month_start, tzinfo) elif not before_now and after_now: return self.date_time_between_dates(now, next_month_start, tzinfo) elif not after_now and before_now: return self.date_time_between_dates(this_month_start, now, tzinfo) else: return now def date_this_century(self, before_today=True, after_today=False): """ Gets a Date object for the current century. :param before_today: include days in current century before today :param after_today: include days in current century after today :example Date('2012-04-04') :return Date """ today = date.today() this_century_start = date(today.year - (today.year % 100), 1, 1) next_century_start = date(this_century_start.year + 100, 1, 1) if before_today and after_today: return self.date_between_dates( this_century_start, next_century_start) elif not before_today and after_today: return self.date_between_dates(today, next_century_start) elif not after_today and before_today: return self.date_between_dates(this_century_start, today) else: return today def date_this_decade(self, before_today=True, after_today=False): """ Gets a Date object for the decade year. :param before_today: include days in current decade before today :param after_today: include days in current decade after today :example Date('2012-04-04') :return Date """ today = date.today() this_decade_start = date(today.year - (today.year % 10), 1, 1) next_decade_start = date(this_decade_start.year + 10, 1, 1) if before_today and after_today: return self.date_between_dates(this_decade_start, next_decade_start) elif not before_today and after_today: return self.date_between_dates(today, next_decade_start) elif not after_today and before_today: return self.date_between_dates(this_decade_start, today) else: return today def date_this_year(self, before_today=True, after_today=False): """ Gets a Date object for the current year. :param before_today: include days in current year before today :param after_today: include days in current year after today :example Date('2012-04-04') :return Date """ today = date.today() this_year_start = today.replace(month=1, day=1) next_year_start = date(today.year + 1, 1, 1) if before_today and after_today: return self.date_between_dates(this_year_start, next_year_start) elif not before_today and after_today: return self.date_between_dates(today, next_year_start) elif not after_today and before_today: return self.date_between_dates(this_year_start, today) else: return today def date_this_month(self, before_today=True, after_today=False): """ Gets a Date object for the current month. :param before_today: include days in current month before today :param after_today: include days in current month after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ today = date.today() this_month_start = today.replace(day=1) next_month_start = this_month_start + \ relativedelta.relativedelta(months=1) if before_today and after_today: return self.date_between_dates(this_month_start, next_month_start) elif not before_today and after_today: return self.date_between_dates(today, next_month_start) elif not after_today and before_today: return self.date_between_dates(this_month_start, today) else: return today def time_series( self, start_date='-30d', end_date='now', precision=None, distrib=None, tzinfo=None): """ Returns a generator yielding tuples of ``(<datetime>, <value>)``. The data points will start at ``start_date``, and be at every time interval specified by ``precision``. ``distrib`` is a callable that accepts ``<datetime>`` and returns ``<value>`` """ start_date = self._parse_date_time(start_date, tzinfo=tzinfo) end_date = self._parse_date_time(end_date, tzinfo=tzinfo) if end_date < start_date: raise ValueError("`end_date` must be greater than `start_date`.") if precision is None: precision = (end_date - start_date) / 30 precision = self._parse_timedelta(precision) if distrib is None: def distrib(dt): return self.generator.random.uniform(0, precision) # noqa if not callable(distrib): raise ValueError( "`distrib` must be a callable. Got {} instead.".format(distrib)) datapoint = start_date while datapoint < end_date: dt = timestamp_to_datetime(datapoint, tzinfo) datapoint += precision yield (dt, distrib(dt)) def am_pm(self): return self.date('%p') def day_of_month(self): return self.date('%d') def day_of_week(self): return self.date('%A') def month(self): return self.date('%m') def month_name(self): return self.date('%B') def year(self): return self.date('%Y') def century(self): """ :example 'XVII' """ return self.random_element(self.centuries) def timezone(self): return self.generator.random.choice( self.random_element(self.countries)['timezones']) def date_of_birth(self, tzinfo=None, minimum_age=0, maximum_age=115): """ Generate a random date of birth represented as a Date object, constrained by optional miminimum_age and maximum_age parameters. :param tzinfo Defaults to None. :param minimum_age Defaults to 0. :param maximum_age Defaults to 115. :example Date('1979-02-02') :return Date """ if not isinstance(minimum_age, int): raise TypeError("minimum_age must be an integer.") if not isinstance(maximum_age, int): raise TypeError("maximum_age must be an integer.") if (maximum_age < 0): raise ValueError("maximum_age must be greater than or equal to zero.") if (minimum_age < 0): raise ValueError("minimum_age must be greater than or equal to zero.") if (minimum_age > maximum_age): raise ValueError("minimum_age must be less than or equal to maximum_age.") # In order to return the full range of possible dates of birth, add one # year to the potential age cap and subtract one day if we land on the # boundary. now = datetime.now(tzinfo).date() start_date = now.replace(year=now.year - (maximum_age+1)) end_date = now.replace(year=now.year - minimum_age) dob = self.date_time_ad(tzinfo=tzinfo, start_datetime=start_date, end_datetime=end_date).date() return dob if dob != start_date else dob + timedelta(days=1)
frappe-bench/env/lib/python2.7/site-packages/faker/providers/date_time/__init__.py
from __future__ import unicode_literals import re from calendar import timegm from datetime import MAXYEAR, timedelta from dateutil import relativedelta from dateutil.tz import tzlocal, tzutc from faker.utils import is_string from faker.utils.datetime_safe import date, datetime, real_date, real_datetime from .. import BaseProvider localized = True def datetime_to_timestamp(dt): if getattr(dt, 'tzinfo', None) is not None: dt = dt.astimezone(tzutc()) return timegm(dt.timetuple()) def timestamp_to_datetime(timestamp, tzinfo): if tzinfo is None: pick = datetime.fromtimestamp(timestamp, tzlocal()) pick = pick.astimezone(tzutc()).replace(tzinfo=None) else: pick = datetime.fromtimestamp(timestamp, tzinfo) return pick class ParseError(ValueError): pass timedelta_pattern = r'' for name, sym in [('years', 'y'), ('months', 'M'), ('weeks', 'w'), ('days', 'd'), ('hours', 'h'), ('minutes', 'm'), ('seconds', 's')]: timedelta_pattern += r'((?P<{}>(?:\+|-)\d+?){})?'.format(name, sym) class Provider(BaseProvider): centuries = [ 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI', 'XVII', 'XVIII', 'XIX', 'XX', 'XXI'] countries = [{'timezones': ['Europe/Andorra'], 'alpha-2-code': 'AD', 'alpha-3-code': 'AND', 'continent': 'Europe', 'name': 'Andorra', 'capital': 'Andorra la Vella'}, {'timezones': ['Asia/Kabul'], 'alpha-2-code': 'AF', 'alpha-3-code': 'AFG', 'continent': 'Asia', 'name': 'Afghanistan', 'capital': 'Kabul'}, {'timezones': ['America/Antigua'], 'alpha-2-code': 'AG', 'alpha-3-code': 'ATG', 'continent': 'North America', 'name': 'Antigua and Barbuda', 'capital': "St. John's"}, {'timezones': ['Europe/Tirane'], 'alpha-2-code': 'AL', 'alpha-3-code': 'ALB', 'continent': 'Europe', 'name': 'Albania', 'capital': 'Tirana'}, {'timezones': ['Asia/Yerevan'], 'alpha-2-code': 'AM', 'alpha-3-code': 'ARM', 'continent': 'Asia', 'name': 'Armenia', 'capital': 'Yerevan'}, {'timezones': ['Africa/Luanda'], 'alpha-2-code': 'AO', 'alpha-3-code': 'AGO', 'continent': 'Africa', 'name': 'Angola', 'capital': 'Luanda'}, {'timezones': ['America/Argentina/Buenos_Aires', 'America/Argentina/Cordoba', 'America/Argentina/Jujuy', 'America/Argentina/Tucuman', 'America/Argentina/Catamarca', 'America/Argentina/La_Rioja', 'America/Argentina/San_Juan', 'America/Argentina/Mendoza', 'America/Argentina/Rio_Gallegos', 'America/Argentina/Ushuaia'], 'alpha-2-code': 'AR', 'alpha-3-code': 'ARG', 'continent': 'South America', 'name': 'Argentina', 'capital': 'Buenos Aires'}, {'timezones': ['Europe/Vienna'], 'alpha-2-code': 'AT', 'alpha-3-code': 'AUT', 'continent': 'Europe', 'name': 'Austria', 'capital': 'Vienna'}, {'timezones': ['Australia/Lord_Howe', 'Australia/Hobart', 'Australia/Currie', 'Australia/Melbourne', 'Australia/Sydney', 'Australia/Broken_Hill', 'Australia/Brisbane', 'Australia/Lindeman', 'Australia/Adelaide', 'Australia/Darwin', 'Australia/Perth'], 'alpha-2-code': 'AU', 'alpha-3-code': 'AUS', 'continent': 'Oceania', 'name': 'Australia', 'capital': 'Canberra'}, {'timezones': ['Asia/Baku'], 'alpha-2-code': 'AZ', 'alpha-3-code': 'AZE', 'continent': 'Asia', 'name': 'Azerbaijan', 'capital': 'Baku'}, {'timezones': ['America/Barbados'], 'alpha-2-code': 'BB', 'alpha-3-code': 'BRB', 'continent': 'North America', 'name': 'Barbados', 'capital': 'Bridgetown'}, {'timezones': ['Asia/Dhaka'], 'alpha-2-code': 'BD', 'alpha-3-code': 'BGD', 'continent': 'Asia', 'name': 'Bangladesh', 'capital': 'Dhaka'}, {'timezones': ['Europe/Brussels'], 'alpha-2-code': 'BE', 'alpha-3-code': 'BEL', 'continent': 'Europe', 'name': 'Belgium', 'capital': 'Brussels'}, {'timezones': ['Africa/Ouagadougou'], 'alpha-2-code': 'BF', 'alpha-3-code': 'BFA', 'continent': 'Africa', 'name': 'Burkina Faso', 'capital': 'Ouagadougou'}, {'timezones': ['Europe/Sofia'], 'alpha-2-code': 'BG', 'alpha-3-code': 'BGR', 'continent': 'Europe', 'name': 'Bulgaria', 'capital': 'Sofia'}, {'timezones': ['Asia/Bahrain'], 'alpha-2-code': 'BH', 'alpha-3-code': 'BHR', 'continent': 'Asia', 'name': 'Bahrain', 'capital': 'Manama'}, {'timezones': ['Africa/Bujumbura'], 'alpha-2-code': 'BI', 'alpha-3-code': 'BDI', 'continent': 'Africa', 'name': 'Burundi', 'capital': 'Bujumbura'}, {'timezones': ['Africa/Porto-Novo'], 'alpha-2-code': 'BJ', 'alpha-3-code': 'BEN', 'continent': 'Africa', 'name': 'Benin', 'capital': 'Porto-Novo'}, {'timezones': ['Asia/Brunei'], 'alpha-2-code': 'BN', 'alpha-3-code': 'BRN', 'continent': 'Asia', 'name': '<NAME>', 'capital': 'Bandar Seri Begawan'}, {'timezones': ['America/La_Paz'], 'alpha-2-code': 'BO', 'alpha-3-code': 'BOL', 'continent': 'South America', 'name': 'Bolivia', 'capital': 'Sucre'}, {'timezones': ['America/Noronha', 'America/Belem', 'America/Fortaleza', 'America/Recife', 'America/Araguaina', 'America/Maceio', 'America/Bahia', 'America/Sao_Paulo', 'America/Campo_Grande', 'America/Cuiaba', 'America/Porto_Velho', 'America/Boa_Vista', 'America/Manaus', 'America/Eirunepe', 'America/Rio_Branco'], 'alpha-2-code': 'BR', 'alpha-3-code': 'BRA', 'continent': 'South America', 'name': 'Brazil', 'capital': 'Bras\xc3\xadlia'}, {'timezones': ['America/Nassau'], 'alpha-2-code': 'BS', 'alpha-3-code': 'BHS', 'continent': 'North America', 'name': 'Bahamas', 'capital': 'Nassau'}, {'timezones': ['Asia/Thimphu'], 'alpha-2-code': 'BT', 'alpha-3-code': 'BTN', 'continent': 'Asia', 'name': 'Bhutan', 'capital': 'Thimphu'}, {'timezones': ['Africa/Gaborone'], 'alpha-2-code': 'BW', 'alpha-3-code': 'BWA', 'continent': 'Africa', 'name': 'Botswana', 'capital': 'Gaborone'}, {'timezones': ['Europe/Minsk'], 'alpha-2-code': 'BY', 'alpha-3-code': 'BLR', 'continent': 'Europe', 'name': 'Belarus', 'capital': 'Minsk'}, {'timezones': ['America/Belize'], 'alpha-2-code': 'BZ', 'alpha-3-code': 'BLZ', 'continent': 'North America', 'name': 'Belize', 'capital': 'Belmopan'}, {'timezones': ['America/St_Johns', 'America/Halifax', 'America/Glace_Bay', 'America/Moncton', 'America/Goose_Bay', 'America/Blanc-Sablon', 'America/Montreal', 'America/Toronto', 'America/Nipigon', 'America/Thunder_Bay', 'America/Pangnirtung', 'America/Iqaluit', 'America/Atikokan', 'America/Rankin_Inlet', 'America/Winnipeg', 'America/Rainy_River', 'America/Cambridge_Bay', 'America/Regina', 'America/Swift_Current', 'America/Edmonton', 'America/Yellowknife', 'America/Inuvik', 'America/Dawson_Creek', 'America/Vancouver', 'America/Whitehorse', 'America/Dawson'], 'alpha-2-code': 'CA', 'alpha-3-code': 'CAN', 'continent': 'North America', 'name': 'Canada', 'capital': 'Ottawa'}, {'timezones': ['Africa/Kinshasa', 'Africa/Lubumbashi'], 'alpha-2-code': 'CD', 'alpha-3-code': 'COD', 'continent': 'Africa', 'name': 'Democratic Republic of the Congo', 'capital': 'Kinshasa'}, {'timezones': ['Africa/Brazzaville'], 'alpha-2-code': 'CG', 'alpha-3-code': 'COG', 'continent': 'Africa', 'name': 'Republic of the Congo', 'capital': 'Brazzaville'}, {'timezones': ['Africa/Abidjan'], 'alpha-2-code': 'CI', 'alpha-3-code': 'CIV', 'continent': 'Africa', 'name': "C\xc3\xb4te d'Ivoire", 'capital': 'Yamoussoukro'}, {'timezones': ['America/Santiago', 'Pacific/Easter'], 'alpha-2-code': 'CL', 'alpha-3-code': 'CHL', 'continent': 'South America', 'name': 'Chile', 'capital': 'Santiago'}, {'timezones': ['Africa/Douala'], 'alpha-2-code': 'CM', 'alpha-3-code': 'CMR', 'continent': 'Africa', 'name': 'Cameroon', 'capital': 'Yaound\xc3\xa9'}, {'timezones': ['Asia/Shanghai', 'Asia/Harbin', 'Asia/Chongqing', 'Asia/Urumqi', 'Asia/Kashgar'], 'alpha-2-code': 'CN', 'alpha-3-code': 'CHN', 'continent': 'Asia', 'name': "People's Republic of China", 'capital': 'Beijing'}, {'timezones': ['America/Bogota'], 'alpha-2-code': 'CO', 'alpha-3-code': 'COL', 'continent': 'South America', 'name': 'Colombia', 'capital': 'Bogot\xc3\xa1'}, {'timezones': ['America/Costa_Rica'], 'alpha-2-code': 'CR', 'alpha-3-code': 'CRI', 'continent': 'North America', 'name': 'Costa Rica', 'capital': 'San Jos\xc3\xa9'}, {'timezones': ['America/Havana'], 'alpha-2-code': 'CU', 'alpha-3-code': 'CUB', 'continent': 'North America', 'name': 'Cuba', 'capital': 'Havana'}, {'timezones': ['Atlantic/Cape_Verde'], 'alpha-2-code': 'CV', 'alpha-3-code': 'CPV', 'continent': 'Africa', 'name': 'Cape Verde', 'capital': 'Praia'}, {'timezones': ['Asia/Nicosia'], 'alpha-2-code': 'CY', 'alpha-3-code': 'CYP', 'continent': 'Asia', 'name': 'Cyprus', 'capital': 'Nicosia'}, {'timezones': ['Europe/Prague'], 'alpha-2-code': 'CZ', 'alpha-3-code': 'CZE', 'continent': 'Europe', 'name': 'Czech Republic', 'capital': 'Prague'}, {'timezones': ['Europe/Berlin'], 'alpha-2-code': 'DE', 'alpha-3-code': 'DEU', 'continent': 'Europe', 'name': 'Germany', 'capital': 'Berlin'}, {'timezones': ['Africa/Djibouti'], 'alpha-2-code': 'DJ', 'alpha-3-code': 'DJI', 'continent': 'Africa', 'name': 'Djibouti', 'capital': 'Djibouti City'}, {'timezones': ['Europe/Copenhagen'], 'alpha-2-code': 'DK', 'alpha-3-code': 'DNK', 'continent': 'Europe', 'name': 'Denmark', 'capital': 'Copenhagen'}, {'timezones': ['America/Dominica'], 'alpha-2-code': 'DM', 'alpha-3-code': 'DMA', 'continent': 'North America', 'name': 'Dominica', 'capital': 'Roseau'}, {'timezones': ['America/Santo_Domingo'], 'alpha-2-code': 'DO', 'alpha-3-code': 'DOM', 'continent': 'North America', 'name': 'Dominican Republic', 'capital': 'Santo Domingo'}, {'timezones': ['America/Guayaquil', 'Pacific/Galapagos'], 'alpha-2-code': 'EC', 'alpha-3-code': 'ECU', 'continent': 'South America', 'name': 'Ecuador', 'capital': 'Quito'}, {'timezones': ['Europe/Tallinn'], 'alpha-2-code': 'EE', 'alpha-3-code': 'EST', 'continent': 'Europe', 'name': 'Estonia', 'capital': 'Tallinn'}, {'timezones': ['Africa/Cairo'], 'alpha-2-code': 'EG', 'alpha-3-code': 'EGY', 'continent': 'Africa', 'name': 'Egypt', 'capital': 'Cairo'}, {'timezones': ['Africa/Asmera'], 'alpha-2-code': 'ER', 'alpha-3-code': 'ERI', 'continent': 'Africa', 'name': 'Eritrea', 'capital': 'Asmara'}, {'timezones': ['Africa/Addis_Ababa'], 'alpha-2-code': 'ET', 'alpha-3-code': 'ETH', 'continent': 'Africa', 'name': 'Ethiopia', 'capital': 'Addis Ababa'}, {'timezones': ['Europe/Helsinki'], 'alpha-2-code': 'FI', 'alpha-3-code': 'FIN', 'continent': 'Europe', 'name': 'Finland', 'capital': 'Helsinki'}, {'timezones': ['Pacific/Fiji'], 'alpha-2-code': 'FJ', 'alpha-3-code': 'FJI', 'continent': 'Oceania', 'name': 'Fiji', 'capital': 'Suva'}, {'timezones': ['Europe/Paris'], 'alpha-2-code': 'FR', 'alpha-3-code': 'FRA', 'continent': 'Europe', 'name': 'France', 'capital': 'Paris'}, {'timezones': ['Africa/Libreville'], 'alpha-2-code': 'GA', 'alpha-3-code': 'GAB', 'continent': 'Africa', 'name': 'Gabon', 'capital': 'Libreville'}, {'timezones': ['Asia/Tbilisi'], 'alpha-2-code': 'GE', 'alpha-3-code': 'GEO', 'continent': 'Asia', 'name': 'Georgia', 'capital': 'Tbilisi'}, {'timezones': ['Africa/Accra'], 'alpha-2-code': 'GH', 'alpha-3-code': 'GHA', 'continent': 'Africa', 'name': 'Ghana', 'capital': 'Accra'}, {'timezones': ['Africa/Banjul'], 'alpha-2-code': 'GM', 'alpha-3-code': 'GMB', 'continent': 'Africa', 'name': 'The Gambia', 'capital': 'Banjul'}, {'timezones': ['Africa/Conakry'], 'alpha-2-code': 'GN', 'alpha-3-code': 'GIN', 'continent': 'Africa', 'name': 'Guinea', 'capital': 'Conakry'}, {'timezones': ['Europe/Athens'], 'alpha-2-code': 'GR', 'alpha-3-code': 'GRC', 'continent': 'Europe', 'name': 'Greece', 'capital': 'Athens'}, {'timezones': ['America/Guatemala'], 'alpha-2-code': 'GT', 'alpha-3-code': 'GTM', 'continent': 'North America', 'name': 'Guatemala', 'capital': 'Guatemala City'}, {'timezones': ['America/Guatemala'], 'alpha-2-code': 'HT', 'alpha-3-code': 'HTI', 'continent': 'North America', 'name': 'Haiti', 'capital': 'Port-au-Prince'}, {'timezones': ['Africa/Bissau'], 'alpha-2-code': 'GW', 'alpha-3-code': 'GNB', 'continent': 'Africa', 'name': 'Guinea-Bissau', 'capital': 'Bissau'}, {'timezones': ['America/Guyana'], 'alpha-2-code': 'GY', 'alpha-3-code': 'GUY', 'continent': 'South America', 'name': 'Guyana', 'capital': 'Georgetown'}, {'timezones': ['America/Tegucigalpa'], 'alpha-2-code': 'HN', 'alpha-3-code': 'HND', 'continent': 'North America', 'name': 'Honduras', 'capital': 'Tegucigalpa'}, {'timezones': ['Europe/Budapest'], 'alpha-2-code': 'HU', 'alpha-3-code': 'HUN', 'continent': 'Europe', 'name': 'Hungary', 'capital': 'Budapest'}, {'timezones': ['Asia/Jakarta', 'Asia/Pontianak', 'Asia/Makassar', 'Asia/Jayapura'], 'alpha-2-code': 'ID', 'alpha-3-code': 'IDN', 'continent': 'Asia', 'name': 'Indonesia', 'capital': 'Jakarta'}, {'timezones': ['Europe/Dublin'], 'alpha-2-code': 'IE', 'alpha-3-code': 'IRL', 'continent': 'Europe', 'name': 'Republic of Ireland', 'capital': 'Dublin'}, {'timezones': ['Asia/Jerusalem'], 'alpha-2-code': 'IL', 'alpha-3-code': 'ISR', 'continent': 'Asia', 'name': 'Israel', 'capital': 'Jerusalem'}, {'timezones': ['Asia/Calcutta'], 'alpha-2-code': 'IN', 'alpha-3-code': 'IND', 'continent': 'Asia', 'name': 'India', 'capital': 'New Delhi'}, {'timezones': ['Asia/Baghdad'], 'alpha-2-code': 'IQ', 'alpha-3-code': 'IRQ', 'continent': 'Asia', 'name': 'Iraq', 'capital': 'Baghdad'}, {'timezones': ['Asia/Tehran'], 'alpha-2-code': 'IR', 'alpha-3-code': 'IRN', 'continent': 'Asia', 'name': 'Iran', 'capital': 'Tehran'}, {'timezones': ['Atlantic/Reykjavik'], 'alpha-2-code': 'IS', 'alpha-3-code': 'ISL', 'continent': 'Europe', 'name': 'Iceland', 'capital': 'Reykjav\xc3\xadk'}, {'timezones': ['Europe/Rome'], 'alpha-2-code': 'IT', 'alpha-3-code': 'ITA', 'continent': 'Europe', 'name': 'Italy', 'capital': 'Rome'}, {'timezones': ['America/Jamaica'], 'alpha-2-code': 'JM', 'alpha-3-code': 'JAM', 'continent': 'North America', 'name': 'Jamaica', 'capital': 'Kingston'}, {'timezones': ['Asia/Amman'], 'alpha-2-code': 'JO', 'alpha-3-code': 'JOR', 'continent': 'Asia', 'name': 'Jordan', 'capital': 'Amman'}, {'timezones': ['Asia/Tokyo'], 'alpha-2-code': 'JP', 'alpha-3-code': 'JPN', 'continent': 'Asia', 'name': 'Japan', 'capital': 'Tokyo'}, {'timezones': ['Africa/Nairobi'], 'alpha-2-code': 'KE', 'alpha-3-code': 'KEN', 'continent': 'Africa', 'name': 'Kenya', 'capital': 'Nairobi'}, {'timezones': ['Asia/Bishkek'], 'alpha-2-code': 'KG', 'alpha-3-code': 'KGZ', 'continent': 'Asia', 'name': 'Kyrgyzstan', 'capital': 'Bishkek'}, {'timezones': ['Pacific/Tarawa', 'Pacific/Enderbury', 'Pacific/Kiritimati'], 'alpha-2-code': 'KI', 'alpha-3-code': 'KIR', 'continent': 'Oceania', 'name': 'Kiribati', 'capital': 'Tarawa'}, {'timezones': ['Asia/Pyongyang'], 'alpha-2-code': 'KP', 'alpha-3-code': 'PRK', 'continent': 'Asia', 'name': 'North Korea', 'capital': 'Pyongyang'}, {'timezones': ['Asia/Seoul'], 'alpha-2-code': 'KR', 'alpha-3-code': 'KOR', 'continent': 'Asia', 'name': 'South Korea', 'capital': 'Seoul'}, {'timezones': ['Asia/Kuwait'], 'alpha-2-code': 'KW', 'alpha-3-code': 'KWT', 'continent': 'Asia', 'name': 'Kuwait', 'capital': 'Kuwait City'}, {'timezones': ['Asia/Beirut'], 'alpha-2-code': 'LB', 'alpha-3-code': 'LBN', 'continent': 'Asia', 'name': 'Lebanon', 'capital': 'Beirut'}, {'timezones': ['Europe/Vaduz'], 'alpha-2-code': 'LI', 'alpha-3-code': 'LIE', 'continent': 'Europe', 'name': 'Liechtenstein', 'capital': 'Vaduz'}, {'timezones': ['Africa/Monrovia'], 'alpha-2-code': 'LR', 'alpha-3-code': 'LBR', 'continent': 'Africa', 'name': 'Liberia', 'capital': 'Monrovia'}, {'timezones': ['Africa/Maseru'], 'alpha-2-code': 'LS', 'alpha-3-code': 'LSO', 'continent': 'Africa', 'name': 'Lesotho', 'capital': 'Maseru'}, {'timezones': ['Europe/Vilnius'], 'alpha-2-code': 'LT', 'alpha-3-code': 'LTU', 'continent': 'Europe', 'name': 'Lithuania', 'capital': 'Vilnius'}, {'timezones': ['Europe/Luxembourg'], 'alpha-2-code': 'LU', 'alpha-3-code': 'LUX', 'continent': 'Europe', 'name': 'Luxembourg', 'capital': 'Luxembourg City'}, {'timezones': ['Europe/Riga'], 'alpha-2-code': 'LV', 'alpha-3-code': 'LVA', 'continent': 'Europe', 'name': 'Latvia', 'capital': 'Riga'}, {'timezones': ['Africa/Tripoli'], 'alpha-2-code': 'LY', 'alpha-3-code': 'LBY', 'continent': 'Africa', 'name': 'Libya', 'capital': 'Tripoli'}, {'timezones': ['Indian/Antananarivo'], 'alpha-2-code': 'MG', 'alpha-3-code': 'MDG', 'continent': 'Africa', 'name': 'Madagascar', 'capital': 'Antananarivo'}, {'timezones': ['Pacific/Majuro', 'Pacific/Kwajalein'], 'alpha-2-code': 'MH', 'alpha-3-code': 'MHL', 'continent': 'Oceania', 'name': 'Marshall Islands', 'capital': 'Majuro'}, {'timezones': ['Europe/Skopje'], 'alpha-2-code': 'MK', 'alpha-3-code': 'MKD', 'continent': 'Europe', 'name': 'Macedonia', 'capital': 'Skopje'}, {'timezones': ['Africa/Bamako'], 'alpha-2-code': 'ML', 'alpha-3-code': 'MLI', 'continent': 'Africa', 'name': 'Mali', 'capital': 'Bamako'}, {'timezones': ['Asia/Rangoon'], 'alpha-2-code': 'MM', 'alpha-3-code': 'MMR', 'continent': 'Asia', 'name': 'Myanmar', 'capital': 'Naypyidaw'}, {'timezones': ['Asia/Ulaanbaatar', 'Asia/Hovd', 'Asia/Choibalsan'], 'alpha-2-code': 'MN', 'alpha-3-code': 'MNG', 'continent': 'Asia', 'name': 'Mongolia', 'capital': 'Ulaanbaatar'}, {'timezones': ['Africa/Nouakchott'], 'alpha-2-code': 'MR', 'alpha-3-code': 'MRT', 'continent': 'Africa', 'name': 'Mauritania', 'capital': 'Nouakchott'}, {'timezones': ['Europe/Malta'], 'alpha-2-code': 'MT', 'alpha-3-code': 'MLT', 'continent': 'Europe', 'name': 'Malta', 'capital': 'Valletta'}, {'timezones': ['Indian/Mauritius'], 'alpha-2-code': 'MU', 'alpha-3-code': 'MUS', 'continent': 'Africa', 'name': 'Mauritius', 'capital': 'Port Louis'}, {'timezones': ['Indian/Maldives'], 'alpha-2-code': 'MV', 'alpha-3-code': 'MDV', 'continent': 'Asia', 'name': 'Maldives', 'capital': 'Mal\xc3\xa9'}, {'timezones': ['Africa/Blantyre'], 'alpha-2-code': 'MW', 'alpha-3-code': 'MWI', 'continent': 'Africa', 'name': 'Malawi', 'capital': 'Lilongwe'}, {'timezones': ['America/Mexico_City', 'America/Cancun', 'America/Merida', 'America/Monterrey', 'America/Mazatlan', 'America/Chihuahua', 'America/Hermosillo', 'America/Tijuana'], 'alpha-2-code': 'MX', 'alpha-3-code': 'MEX', 'continent': 'North America', 'name': 'Mexico', 'capital': 'Mexico City'}, {'timezones': ['Asia/Kuala_Lumpur', 'Asia/Kuching'], 'alpha-2-code': 'MY', 'alpha-3-code': 'MYS', 'continent': 'Asia', 'name': 'Malaysia', 'capital': 'Kuala Lumpur'}, {'timezones': ['Africa/Maputo'], 'alpha-2-code': 'MZ', 'alpha-3-code': 'MOZ', 'continent': 'Africa', 'name': 'Mozambique', 'capital': 'Maputo'}, {'timezones': ['Africa/Windhoek'], 'alpha-2-code': 'NA', 'alpha-3-code': 'NAM', 'continent': 'Africa', 'name': 'Namibia', 'capital': 'Windhoek'}, {'timezones': ['Africa/Niamey'], 'alpha-2-code': 'NE', 'alpha-3-code': 'NER', 'continent': 'Africa', 'name': 'Niger', 'capital': 'Niamey'}, {'timezones': ['Africa/Lagos'], 'alpha-2-code': 'NG', 'alpha-3-code': 'NGA', 'continent': 'Africa', 'name': 'Nigeria', 'capital': 'Abuja'}, {'timezones': ['America/Managua'], 'alpha-2-code': 'NI', 'alpha-3-code': 'NIC', 'continent': 'North America', 'name': 'Nicaragua', 'capital': 'Managua'}, {'timezones': ['Europe/Amsterdam'], 'alpha-2-code': 'NL', 'alpha-3-code': 'NLD', 'continent': 'Europe', 'name': 'Kingdom of the Netherlands', 'capital': 'Amsterdam'}, {'timezones': ['Europe/Oslo'], 'alpha-2-code': 'NO', 'alpha-3-code': 'NOR', 'continent': 'Europe', 'name': 'Norway', 'capital': 'Oslo'}, {'timezones': ['Asia/Katmandu'], 'alpha-2-code': 'NP', 'alpha-3-code': 'NPL', 'continent': 'Asia', 'name': 'Nepal', 'capital': 'Kathmandu'}, {'timezones': ['Pacific/Nauru'], 'alpha-2-code': 'NR', 'alpha-3-code': 'NRU', 'continent': 'Oceania', 'name': 'Nauru', 'capital': 'Yaren'}, {'timezones': ['Pacific/Auckland', 'Pacific/Chatham'], 'alpha-2-code': 'NZ', 'alpha-3-code': 'NZL', 'continent': 'Oceania', 'name': 'New Zealand', 'capital': 'Wellington'}, {'timezones': ['Asia/Muscat'], 'alpha-2-code': 'OM', 'alpha-3-code': 'OMN', 'continent': 'Asia', 'name': 'Oman', 'capital': 'Muscat'}, {'timezones': ['America/Panama'], 'alpha-2-code': 'PA', 'alpha-3-code': 'PAN', 'continent': 'North America', 'name': 'Panama', 'capital': 'Panama City'}, {'timezones': ['America/Lima'], 'alpha-2-code': 'PE', 'alpha-3-code': 'PER', 'continent': 'South America', 'name': 'Peru', 'capital': 'Lima'}, {'timezones': ['Pacific/Port_Moresby'], 'alpha-2-code': 'PG', 'alpha-3-code': 'PNG', 'continent': 'Oceania', 'name': 'Papua New Guinea', 'capital': 'Port Moresby'}, {'timezones': ['Asia/Manila'], 'alpha-2-code': 'PH', 'alpha-3-code': 'PHL', 'continent': 'Asia', 'name': 'Philippines', 'capital': 'Manila'}, {'timezones': ['Asia/Karachi'], 'alpha-2-code': 'PK', 'alpha-3-code': 'PAK', 'continent': 'Asia', 'name': 'Pakistan', 'capital': 'Islamabad'}, {'timezones': ['Europe/Warsaw'], 'alpha-2-code': 'PL', 'alpha-3-code': 'POL', 'continent': 'Europe', 'name': 'Poland', 'capital': 'Warsaw'}, {'timezones': ['Europe/Lisbon', 'Atlantic/Madeira', 'Atlantic/Azores'], 'alpha-2-code': 'PT', 'alpha-3-code': 'PRT', 'continent': 'Europe', 'name': 'Portugal', 'capital': 'Lisbon'}, {'timezones': ['Pacific/Palau'], 'alpha-2-code': 'PW', 'alpha-3-code': 'PLW', 'continent': 'Oceania', 'name': 'Palau', 'capital': 'Ngerulmud'}, {'timezones': ['America/Asuncion'], 'alpha-2-code': 'PY', 'alpha-3-code': 'PRY', 'continent': 'South America', 'name': 'Paraguay', 'capital': 'Asunci\xc3\xb3n'}, {'timezones': ['Asia/Qatar'], 'alpha-2-code': 'QA', 'alpha-3-code': 'QAT', 'continent': 'Asia', 'name': 'Qatar', 'capital': 'Doha'}, {'timezones': ['Europe/Bucharest'], 'alpha-2-code': 'RO', 'alpha-3-code': 'ROU', 'continent': 'Europe', 'name': 'Romania', 'capital': 'Bucharest'}, {'timezones': ['Europe/Kaliningrad', 'Europe/Moscow', 'Europe/Volgograd', 'Europe/Samara', 'Asia/Yekaterinburg', 'Asia/Omsk', 'Asia/Novosibirsk', 'Asia/Krasnoyarsk', 'Asia/Irkutsk', 'Asia/Yakutsk', 'Asia/Vladivostok', 'Asia/Sakhalin', 'Asia/Magadan', 'Asia/Kamchatka', 'Asia/Anadyr'], 'alpha-2-code': 'RU', 'alpha-3-code': 'RUS', 'continent': 'Europe', 'name': 'Russia', 'capital': 'Moscow'}, {'timezones': ['Africa/Kigali'], 'alpha-2-code': 'RW', 'alpha-3-code': 'RWA', 'continent': 'Africa', 'name': 'Rwanda', 'capital': 'Kigali'}, {'timezones': ['Asia/Riyadh'], 'alpha-2-code': 'SA', 'alpha-3-code': 'SAU', 'continent': 'Asia', 'name': '<NAME>', 'capital': 'Riyadh'}, {'timezones': ['Pacific/Guadalcanal'], 'alpha-2-code': 'SB', 'alpha-3-code': 'SLB', 'continent': 'Oceania', 'name': 'Solomon Islands', 'capital': 'Honiara'}, {'timezones': ['Indian/Mahe'], 'alpha-2-code': 'SC', 'alpha-3-code': 'SYC', 'continent': 'Africa', 'name': 'Seychelles', 'capital': 'Victoria'}, {'timezones': ['Africa/Khartoum'], 'alpha-2-code': 'SD', 'alpha-3-code': 'SDN', 'continent': 'Africa', 'name': 'Sudan', 'capital': 'Khartoum'}, {'timezones': ['Europe/Stockholm'], 'alpha-2-code': 'SE', 'alpha-3-code': 'SWE', 'continent': 'Europe', 'name': 'Sweden', 'capital': 'Stockholm'}, {'timezones': ['Asia/Singapore'], 'alpha-2-code': 'SG', 'alpha-3-code': 'SGP', 'continent': 'Asia', 'name': 'Singapore', 'capital': 'Singapore'}, {'timezones': ['Europe/Ljubljana'], 'alpha-2-code': 'SI', 'alpha-3-code': 'SVN', 'continent': 'Europe', 'name': 'Slovenia', 'capital': 'Ljubljana'}, {'timezones': ['Europe/Bratislava'], 'alpha-2-code': 'SK', 'alpha-3-code': 'SVK', 'continent': 'Europe', 'name': 'Slovakia', 'capital': 'Bratislava'}, {'timezones': ['Africa/Freetown'], 'alpha-2-code': 'SL', 'alpha-3-code': 'SLE', 'continent': 'Africa', 'name': 'Sierra Leone', 'capital': 'Freetown'}, {'timezones': ['Europe/San_Marino'], 'alpha-2-code': 'SM', 'alpha-3-code': 'SMR', 'continent': 'Europe', 'name': 'San Marino', 'capital': 'San Marino'}, {'timezones': ['Africa/Dakar'], 'alpha-2-code': 'SN', 'alpha-3-code': 'SEN', 'continent': 'Africa', 'name': 'Senegal', 'capital': 'Dakar'}, {'timezones': ['Africa/Mogadishu'], 'alpha-2-code': 'SO', 'alpha-3-code': 'SOM', 'continent': 'Africa', 'name': 'Somalia', 'capital': 'Mogadishu'}, {'timezones': ['America/Paramaribo'], 'alpha-2-code': 'SR', 'alpha-3-code': 'SUR', 'continent': 'South America', 'name': 'Suriname', 'capital': 'Paramaribo'}, {'timezones': ['Africa/Sao_Tome'], 'alpha-2-code': 'ST', 'alpha-3-code': 'STP', 'continent': 'Africa', 'name': 'S\xc3\xa3o Tom\xc3\xa9 and Pr\xc3\xadncipe', 'capital': 'S\xc3\xa3o Tom\xc3\xa9'}, {'timezones': ['Asia/Damascus'], 'alpha-2-code': 'SY', 'alpha-3-code': 'SYR', 'continent': 'Asia', 'name': 'Syria', 'capital': 'Damascus'}, {'timezones': ['Africa/Lome'], 'alpha-2-code': 'TG', 'alpha-3-code': 'TGO', 'continent': 'Africa', 'name': 'Togo', 'capital': 'Lom\xc3\xa9'}, {'timezones': ['Asia/Bangkok'], 'alpha-2-code': 'TH', 'alpha-3-code': 'THA', 'continent': 'Asia', 'name': 'Thailand', 'capital': 'Bangkok'}, {'timezones': ['Asia/Dushanbe'], 'alpha-2-code': 'TJ', 'alpha-3-code': 'TJK', 'continent': 'Asia', 'name': 'Tajikistan', 'capital': 'Dushanbe'}, {'timezones': ['Asia/Ashgabat'], 'alpha-2-code': 'TM', 'alpha-3-code': 'TKM', 'continent': 'Asia', 'name': 'Turkmenistan', 'capital': 'Ashgabat'}, {'timezones': ['Africa/Tunis'], 'alpha-2-code': 'TN', 'alpha-3-code': 'TUN', 'continent': 'Africa', 'name': 'Tunisia', 'capital': 'Tunis'}, {'timezones': ['Pacific/Tongatapu'], 'alpha-2-code': 'TO', 'alpha-3-code': 'TON', 'continent': 'Oceania', 'name': 'Tonga', 'capital': 'Nuku\xca\xbbalofa'}, {'timezones': ['Europe/Istanbul'], 'alpha-2-code': 'TR', 'alpha-3-code': 'TUR', 'continent': 'Asia', 'name': 'Turkey', 'capital': 'Ankara'}, {'timezones': ['America/Port_of_Spain'], 'alpha-2-code': 'TT', 'alpha-3-code': 'TTO', 'continent': 'North America', 'name': 'Trinidad and Tobago', 'capital': 'Port of Spain'}, {'timezones': ['Pacific/Funafuti'], 'alpha-2-code': 'TV', 'alpha-3-code': 'TUV', 'continent': 'Oceania', 'name': 'Tuvalu', 'capital': 'Funafuti'}, {'timezones': ['Africa/Dar_es_Salaam'], 'alpha-2-code': 'TZ', 'alpha-3-code': 'TZA', 'continent': 'Africa', 'name': 'Tanzania', 'capital': 'Dodoma'}, {'timezones': ['Europe/Kiev', 'Europe/Uzhgorod', 'Europe/Zaporozhye', 'Europe/Simferopol'], 'alpha-2-code': 'UA', 'alpha-3-code': 'UKR', 'continent': 'Europe', 'name': 'Ukraine', 'capital': 'Kiev'}, {'timezones': ['Africa/Kampala'], 'alpha-2-code': 'UG', 'alpha-3-code': 'UGA', 'continent': 'Africa', 'name': 'Uganda', 'capital': 'Kampala'}, {'timezones': ['America/New_York', 'America/Detroit', 'America/Kentucky/Louisville', 'America/Kentucky/Monticello', 'America/Indiana/Indianapolis', 'America/Indiana/Marengo', 'America/Indiana/Knox', 'America/Indiana/Vevay', 'America/Chicago', 'America/Indiana/Vincennes', 'America/Indiana/Petersburg', 'America/Menominee', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/Denver', 'America/Boise', 'America/Shiprock', 'America/Phoenix', 'America/Los_Angeles', 'America/Anchorage', 'America/Juneau', 'America/Yakutat', 'America/Nome', 'America/Adak', 'Pacific/Honolulu'], 'alpha-2-code': 'US', 'alpha-3-code': 'USA', 'continent': 'North America', 'name': 'United States', 'capital': 'Washington, D.C.'}, {'timezones': ['America/Montevideo'], 'alpha-2-code': 'UY', 'alpha-3-code': 'URY', 'continent': 'South America', 'name': 'Uruguay', 'capital': 'Montevideo'}, {'timezones': ['Asia/Samarkand', 'Asia/Tashkent'], 'alpha-2-code': 'UZ', 'alpha-3-code': 'UZB', 'continent': 'Asia', 'name': 'Uzbekistan', 'capital': 'Tashkent'}, {'timezones': ['Europe/Vatican'], 'alpha-2-code': 'VA', 'alpha-3-code': 'VAT', 'continent': 'Europe', 'name': 'Vatican City', 'capital': 'Vatican City'}, {'timezones': ['America/Caracas'], 'alpha-2-code': 'VE', 'alpha-3-code': 'VEN', 'continent': 'South America', 'name': 'Venezuela', 'capital': 'Caracas'}, {'timezones': ['Asia/Saigon'], 'alpha-2-code': 'VN', 'alpha-3-code': 'VNM', 'continent': 'Asia', 'name': 'Vietnam', 'capital': 'Hanoi'}, {'timezones': ['Pacific/Efate'], 'alpha-2-code': 'VU', 'alpha-3-code': 'VUT', 'continent': 'Oceania', 'name': 'Vanuatu', 'capital': 'Port Vila'}, {'timezones': ['Asia/Aden'], 'alpha-2-code': 'YE', 'alpha-3-code': 'YEM', 'continent': 'Asia', 'name': 'Yemen', 'capital': "Sana'a"}, {'timezones': ['Africa/Lusaka'], 'alpha-2-code': 'ZM', 'alpha-3-code': 'ZMB', 'continent': 'Africa', 'name': 'Zambia', 'capital': 'Lusaka'}, {'timezones': ['Africa/Harare'], 'alpha-2-code': 'ZW', 'alpha-3-code': 'ZWE', 'continent': 'Africa', 'name': 'Zimbabwe', 'capital': 'Harare'}, {'timezones': ['Africa/Algiers'], 'alpha-2-code': 'DZ', 'alpha-3-code': 'DZA', 'continent': 'Africa', 'name': 'Algeria', 'capital': 'Algiers'}, {'timezones': ['Europe/Sarajevo'], 'alpha-2-code': 'BA', 'alpha-3-code': 'BIH', 'continent': 'Europe', 'name': 'Bosnia and Herzegovina', 'capital': 'Sarajevo'}, {'timezones': ['Asia/Phnom_Penh'], 'alpha-2-code': 'KH', 'alpha-3-code': 'KHM', 'continent': 'Asia', 'name': 'Cambodia', 'capital': 'Phnom Penh'}, {'timezones': ['Africa/Bangui'], 'alpha-2-code': 'CF', 'alpha-3-code': 'CAF', 'continent': 'Africa', 'name': 'Central African Republic', 'capital': 'Bangui'}, {'timezones': ['Africa/Ndjamena'], 'alpha-2-code': 'TD', 'alpha-3-code': 'TCD', 'continent': 'Africa', 'name': 'Chad', 'capital': "N'Djamena"}, {'timezones': ['Indian/Comoro'], 'alpha-2-code': 'KM', 'alpha-3-code': 'COM', 'continent': 'Africa', 'name': 'Comoros', 'capital': 'Moroni'}, {'timezones': ['Europe/Zagreb'], 'alpha-2-code': 'HR', 'alpha-3-code': 'HRV', 'continent': 'Europe', 'name': 'Croatia', 'capital': 'Zagreb'}, {'timezones': ['Asia/Dili'], 'alpha-2-code': 'TL', 'alpha-3-code': 'TLS', 'continent': 'Asia', 'name': 'East Timor', 'capital': 'Dili'}, {'timezones': ['America/El_Salvador'], 'alpha-2-code': 'SV', 'alpha-3-code': 'SLV', 'continent': 'North America', 'name': 'El Salvador', 'capital': 'San Salvador'}, {'timezones': ['Africa/Malabo'], 'alpha-2-code': 'GQ', 'alpha-3-code': 'GNQ', 'continent': 'Africa', 'name': 'Equatorial Guinea', 'capital': 'Malabo'}, {'timezones': ['America/Grenada'], 'alpha-2-code': 'GD', 'alpha-3-code': 'GRD', 'continent': 'North America', 'name': 'Grenada', 'capital': "St. George's"}, {'timezones': ['Asia/Almaty', 'Asia/Qyzylorda', 'Asia/Aqtobe', 'Asia/Aqtau', 'Asia/Oral'], 'alpha-2-code': 'KZ', 'alpha-3-code': 'KAZ', 'continent': 'Asia', 'name': 'Kazakhstan', 'capital': 'Astana'}, {'timezones': ['Asia/Vientiane'], 'alpha-2-code': 'LA', 'alpha-3-code': 'LAO', 'continent': 'Asia', 'name': 'Laos', 'capital': 'Vientiane'}, {'timezones': ['Pacific/Truk', 'Pacific/Ponape', 'Pacific/Kosrae'], 'alpha-2-code': 'FM', 'alpha-3-code': 'FSM', 'continent': 'Oceania', 'name': 'Federated States of Micronesia', 'capital': 'Palikir'}, {'timezones': ['Europe/Chisinau'], 'alpha-2-code': 'MD', 'alpha-3-code': 'MDA', 'continent': 'Europe', 'name': 'Moldova', 'capital': 'Chi\xc5\x9fin\xc4\x83u'}, {'timezones': ['Europe/Monaco'], 'alpha-2-code': 'MC', 'alpha-3-code': 'MCO', 'continent': 'Europe', 'name': 'Monaco', 'capital': 'Monaco'}, {'timezones': ['Europe/Podgorica'], 'alpha-2-code': 'ME', 'alpha-3-code': 'MNE', 'continent': 'Europe', 'name': 'Montenegro', 'capital': 'Podgorica'}, {'timezones': ['Africa/Casablanca'], 'alpha-2-code': 'MA', 'alpha-3-code': 'MAR', 'continent': 'Africa', 'name': 'Morocco', 'capital': 'Rabat'}, {'timezones': ['America/St_Kitts'], 'alpha-2-code': 'KN', 'alpha-3-code': 'KNA', 'continent': 'North America', 'name': 'Saint Kitts and Nevis', 'capital': 'Basseterre'}, {'timezones': ['America/St_Lucia'], 'alpha-2-code': 'LC', 'alpha-3-code': 'LCA', 'continent': 'North America', 'name': 'Saint Lucia', 'capital': 'Castries'}, {'timezones': ['America/St_Vincent'], 'alpha-2-code': 'VC', 'alpha-3-code': 'VCT', 'continent': 'North America', 'name': 'Saint Vincent and the Grenadines', 'capital': 'Kingstown'}, {'timezones': ['Pacific/Apia'], 'alpha-2-code': 'WS', 'alpha-3-code': 'WSM', 'continent': 'Oceania', 'name': 'Samoa', 'capital': 'Apia'}, {'timezones': ['Europe/Belgrade'], 'alpha-2-code': 'RS', 'alpha-3-code': 'SRB', 'continent': 'Europe', 'name': 'Serbia', 'capital': 'Belgrade'}, {'timezones': ['Africa/Johannesburg'], 'alpha-2-code': 'ZA', 'alpha-3-code': 'ZAF', 'continent': 'Africa', 'name': 'South Africa', 'capital': 'Pretoria'}, {'timezones': ['Europe/Madrid', 'Africa/Ceuta', 'Atlantic/Canary'], 'alpha-2-code': 'ES', 'alpha-3-code': 'ESP', 'continent': 'Europe', 'name': 'Spain', 'capital': 'Madrid'}, {'timezones': ['Asia/Colombo'], 'alpha-2-code': 'LK', 'alpha-3-code': 'LKA', 'continent': 'Asia', 'name': 'Sri Lanka', 'capital': 'Sri Jayewardenepura Kotte'}, {'timezones': ['Africa/Mbabane'], 'alpha-2-code': 'SZ', 'alpha-3-code': 'SWZ', 'continent': 'Africa', 'name': 'Swaziland', 'capital': 'Mbabane'}, {'timezones': ['Europe/Zurich'], 'alpha-2-code': 'CH', 'alpha-3-code': 'CHE', 'continent': 'Europe', 'name': 'Switzerland', 'capital': 'Bern'}, {'timezones': ['Asia/Dubai'], 'alpha-2-code': 'AE', 'alpha-3-code': 'ARE', 'continent': 'Asia', 'name': 'United Arab Emirates', 'capital': 'Abu Dhabi'}, {'timezones': ['Europe/London'], 'alpha-2-code': 'GB', 'alpha-3-code': 'GBR', 'continent': 'Europe', 'name': 'United Kingdom', 'capital': 'London'}, ] regex = re.compile(timedelta_pattern) def unix_time(self, end_datetime=None, start_datetime=None): """ Get a timestamp between January 1, 1970 and now, unless passed explicit start_datetime or end_datetime values. :example 1061306726 """ start_datetime = self._parse_start_datetime(start_datetime) end_datetime = self._parse_end_datetime(end_datetime) return self.generator.random.randint(start_datetime, end_datetime) def time_delta(self, end_datetime=None): """ Get a timedelta object """ start_datetime = self._parse_start_datetime('now') end_datetime = self._parse_end_datetime(end_datetime) seconds = end_datetime - start_datetime ts = self.generator.random.randint(*sorted([0, seconds])) return timedelta(seconds=ts) def date_time(self, tzinfo=None, end_datetime=None): """ Get a datetime object for a date between January 1, 1970 and now :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2005-08-16 20:39:21') :return datetime """ # NOTE: On windows, the lowest value you can get from windows is 86400 # on the first day. Known python issue: # https://bugs.python.org/issue30684 return datetime(1970, 1, 1, tzinfo=tzinfo) + \ timedelta(seconds=self.unix_time(end_datetime=end_datetime)) def date_time_ad(self, tzinfo=None, end_datetime=None, start_datetime=None): """ Get a datetime object for a date between January 1, 001 and now :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1265-03-22 21:15:52') :return datetime """ # 1970-01-01 00:00:00 UTC minus 62135596800 seconds is # 0001-01-01 00:00:00 UTC. Since _parse_end_datetime() is used # elsewhere where a default value of 0 is expected, we can't # simply change that class method to use this magic number as a # default value when None is provided. start_time = -62135596800 if start_datetime is None else self._parse_start_datetime(start_datetime) end_datetime = self._parse_end_datetime(end_datetime) ts = self.generator.random.randint(start_time, end_datetime) # NOTE: using datetime.fromtimestamp(ts) directly will raise # a "ValueError: timestamp out of range for platform time_t" # on some platforms due to system C functions; # see http://stackoverflow.com/a/10588133/2315612 # NOTE: On windows, the lowest value you can get from windows is 86400 # on the first day. Known python issue: # https://bugs.python.org/issue30684 return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=ts) def iso8601(self, tzinfo=None, end_datetime=None): """ :param tzinfo: timezone, instance of datetime.tzinfo subclass :example '2003-10-21T16:05:52+0000' """ return self.date_time(tzinfo, end_datetime=end_datetime).isoformat() def date(self, pattern='%Y-%m-%d', end_datetime=None): """ Get a date string between January 1, 1970 and now :param pattern format :example '2008-11-27' """ return self.date_time(end_datetime=end_datetime).strftime(pattern) def date_object(self, end_datetime=None): """ Get a date object between January 1, 1970 and now :example datetime.date(2016, 9, 20) """ return self.date_time(end_datetime=end_datetime).date() def time(self, pattern='%H:%M:%S', end_datetime=None): """ Get a time string (24h format by default) :param pattern format :example '15:02:34' """ return self.date_time( end_datetime=end_datetime).time().strftime(pattern) def time_object(self, end_datetime=None): """ Get a time object :example datetime.time(15, 56, 56, 772876) """ return self.date_time(end_datetime=end_datetime).time() @classmethod def _parse_start_datetime(cls, value): if value is None: return 0 return cls._parse_date_time(value) @classmethod def _parse_end_datetime(cls, value): if value is None: return datetime_to_timestamp(datetime.now()) return cls._parse_date_time(value) @classmethod def _parse_date_string(cls, value): parts = cls.regex.match(value) if not parts: raise ParseError("Can't parse date string `{}`.".format(value)) parts = parts.groupdict() time_params = {} for (name_, param_) in parts.items(): if param_: time_params[name_] = int(param_) if 'years' in time_params: if 'days' not in time_params: time_params['days'] = 0 time_params['days'] += 365.24 * time_params.pop('years') if 'months' in time_params: if 'days' not in time_params: time_params['days'] = 0 time_params['days'] += 30.42 * time_params.pop('months') if not time_params: raise ParseError("Can't parse date string `{}`.".format(value)) return time_params @classmethod def _parse_timedelta(cls, value): if isinstance(value, timedelta): return value.total_seconds() if is_string(value): time_params = cls._parse_date_string(value) return timedelta(**time_params).total_seconds() if isinstance(value, (int, float)): return value raise ParseError("Invalid format for timedelta '{}'".format(value)) @classmethod def _parse_date_time(cls, value, tzinfo=None): if isinstance(value, (datetime, date, real_datetime, real_date)): return datetime_to_timestamp(value) now = datetime.now(tzinfo) if isinstance(value, timedelta): return datetime_to_timestamp(now + value) if is_string(value): if value == 'now': return datetime_to_timestamp(datetime.now(tzinfo)) time_params = cls._parse_date_string(value) return datetime_to_timestamp(now + timedelta(**time_params)) if isinstance(value, int): return datetime_to_timestamp(now + timedelta(value)) raise ParseError("Invalid format for date '{}'".format(value)) @classmethod def _parse_date(cls, value): if isinstance(value, (datetime, real_datetime)): return value.date() elif isinstance(value, (date, real_date)): return value today = date.today() if isinstance(value, timedelta): return today + value if is_string(value): if value in ('today', 'now'): return today time_params = cls._parse_date_string(value) return today + timedelta(**time_params) if isinstance(value, int): return today + timedelta(value) raise ParseError("Invalid format for date '{}'".format(value)) def date_time_between(self, start_date='-30y', end_date='now', tzinfo=None): """ Get a DateTime object based on a random date between two given dates. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to 30 years ago :param end_date Defaults to "now" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ start_date = self._parse_date_time(start_date, tzinfo=tzinfo) end_date = self._parse_date_time(end_date, tzinfo=tzinfo) if end_date - start_date <= 1: ts = start_date + self.generator.random.random() else: ts = self.generator.random.randint(start_date, end_date) if tzinfo is None: return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=ts) else: return ( datetime(1970, 1, 1, tzinfo=tzutc()) + timedelta(seconds=ts) ).astimezone(tzinfo) def date_between(self, start_date='-30y', end_date='today'): """ Get a Date object based on a random date between two given dates. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to 30 years ago :param end_date Defaults to "today" :example Date('1999-02-02') :return Date """ start_date = self._parse_date(start_date) end_date = self._parse_date(end_date) return self.date_between_dates(date_start=start_date, date_end=end_date) def future_datetime(self, end_date='+30d', tzinfo=None): """ Get a DateTime object based on a random date between 1 second form now and a given date. Accepts date strings that can be recognized by strtotime(). :param end_date Defaults to "+30d" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ return self.date_time_between( start_date='+1s', end_date=end_date, tzinfo=tzinfo, ) def future_date(self, end_date='+30d', tzinfo=None): """ Get a Date object based on a random date between 1 day from now and a given date. Accepts date strings that can be recognized by strtotime(). :param end_date Defaults to "+30d" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ return self.date_between(start_date='+1d', end_date=end_date) def past_datetime(self, start_date='-30d', tzinfo=None): """ Get a DateTime object based on a random date between a given date and 1 second ago. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to "-30d" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ return self.date_time_between( start_date=start_date, end_date='-1s', tzinfo=tzinfo, ) def past_date(self, start_date='-30d', tzinfo=None): """ Get a Date object based on a random date between a given date and 1 day ago. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to "-30d" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ return self.date_between(start_date=start_date, end_date='-1d') def date_time_between_dates( self, datetime_start=None, datetime_end=None, tzinfo=None): """ Takes two DateTime objects and returns a random datetime between the two given datetimes. Accepts DateTime objects. :param datetime_start: DateTime :param datetime_end: DateTime :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ if datetime_start is None: datetime_start = datetime.now(tzinfo) if datetime_end is None: datetime_end = datetime.now(tzinfo) timestamp = self.generator.random.randint( datetime_to_timestamp(datetime_start), datetime_to_timestamp(datetime_end), ) try: if tzinfo is None: pick = datetime.fromtimestamp(timestamp, tzlocal()) pick = pick.astimezone(tzutc()).replace(tzinfo=None) else: pick = datetime.fromtimestamp(timestamp, tzinfo) except OverflowError: raise OverflowError( "You specified an end date with a timestamp bigger than the maximum allowed on this" " system. Please specify an earlier date.", ) return pick def date_between_dates(self, date_start=None, date_end=None): """ Takes two Date objects and returns a random date between the two given dates. Accepts Date or Datetime objects :param date_start: Date :param date_end: Date :return Date """ return self.date_time_between_dates(date_start, date_end).date() def date_time_this_century( self, before_now=True, after_now=False, tzinfo=None): """ Gets a DateTime object for the current century. :param before_now: include days in current century before today :param after_now: include days in current century after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ now = datetime.now(tzinfo) this_century_start = datetime( now.year - (now.year % 100), 1, 1, tzinfo=tzinfo) next_century_start = datetime( min(this_century_start.year + 100, MAXYEAR), 1, 1, tzinfo=tzinfo) if before_now and after_now: return self.date_time_between_dates( this_century_start, next_century_start, tzinfo) elif not before_now and after_now: return self.date_time_between_dates(now, next_century_start, tzinfo) elif not after_now and before_now: return self.date_time_between_dates(this_century_start, now, tzinfo) else: return now def date_time_this_decade( self, before_now=True, after_now=False, tzinfo=None): """ Gets a DateTime object for the decade year. :param before_now: include days in current decade before today :param after_now: include days in current decade after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ now = datetime.now(tzinfo) this_decade_start = datetime( now.year - (now.year % 10), 1, 1, tzinfo=tzinfo) next_decade_start = datetime( min(this_decade_start.year + 10, MAXYEAR), 1, 1, tzinfo=tzinfo) if before_now and after_now: return self.date_time_between_dates( this_decade_start, next_decade_start, tzinfo) elif not before_now and after_now: return self.date_time_between_dates(now, next_decade_start, tzinfo) elif not after_now and before_now: return self.date_time_between_dates(this_decade_start, now, tzinfo) else: return now def date_time_this_year( self, before_now=True, after_now=False, tzinfo=None): """ Gets a DateTime object for the current year. :param before_now: include days in current year before today :param after_now: include days in current year after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ now = datetime.now(tzinfo) this_year_start = now.replace( month=1, day=1, hour=0, minute=0, second=0, microsecond=0) next_year_start = datetime(now.year + 1, 1, 1, tzinfo=tzinfo) if before_now and after_now: return self.date_time_between_dates( this_year_start, next_year_start, tzinfo) elif not before_now and after_now: return self.date_time_between_dates(now, next_year_start, tzinfo) elif not after_now and before_now: return self.date_time_between_dates(this_year_start, now, tzinfo) else: return now def date_time_this_month( self, before_now=True, after_now=False, tzinfo=None): """ Gets a DateTime object for the current month. :param before_now: include days in current month before today :param after_now: include days in current month after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ now = datetime.now(tzinfo) this_month_start = now.replace( day=1, hour=0, minute=0, second=0, microsecond=0) next_month_start = this_month_start + \ relativedelta.relativedelta(months=1) if before_now and after_now: return self.date_time_between_dates( this_month_start, next_month_start, tzinfo) elif not before_now and after_now: return self.date_time_between_dates(now, next_month_start, tzinfo) elif not after_now and before_now: return self.date_time_between_dates(this_month_start, now, tzinfo) else: return now def date_this_century(self, before_today=True, after_today=False): """ Gets a Date object for the current century. :param before_today: include days in current century before today :param after_today: include days in current century after today :example Date('2012-04-04') :return Date """ today = date.today() this_century_start = date(today.year - (today.year % 100), 1, 1) next_century_start = date(this_century_start.year + 100, 1, 1) if before_today and after_today: return self.date_between_dates( this_century_start, next_century_start) elif not before_today and after_today: return self.date_between_dates(today, next_century_start) elif not after_today and before_today: return self.date_between_dates(this_century_start, today) else: return today def date_this_decade(self, before_today=True, after_today=False): """ Gets a Date object for the decade year. :param before_today: include days in current decade before today :param after_today: include days in current decade after today :example Date('2012-04-04') :return Date """ today = date.today() this_decade_start = date(today.year - (today.year % 10), 1, 1) next_decade_start = date(this_decade_start.year + 10, 1, 1) if before_today and after_today: return self.date_between_dates(this_decade_start, next_decade_start) elif not before_today and after_today: return self.date_between_dates(today, next_decade_start) elif not after_today and before_today: return self.date_between_dates(this_decade_start, today) else: return today def date_this_year(self, before_today=True, after_today=False): """ Gets a Date object for the current year. :param before_today: include days in current year before today :param after_today: include days in current year after today :example Date('2012-04-04') :return Date """ today = date.today() this_year_start = today.replace(month=1, day=1) next_year_start = date(today.year + 1, 1, 1) if before_today and after_today: return self.date_between_dates(this_year_start, next_year_start) elif not before_today and after_today: return self.date_between_dates(today, next_year_start) elif not after_today and before_today: return self.date_between_dates(this_year_start, today) else: return today def date_this_month(self, before_today=True, after_today=False): """ Gets a Date object for the current month. :param before_today: include days in current month before today :param after_today: include days in current month after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ today = date.today() this_month_start = today.replace(day=1) next_month_start = this_month_start + \ relativedelta.relativedelta(months=1) if before_today and after_today: return self.date_between_dates(this_month_start, next_month_start) elif not before_today and after_today: return self.date_between_dates(today, next_month_start) elif not after_today and before_today: return self.date_between_dates(this_month_start, today) else: return today def time_series( self, start_date='-30d', end_date='now', precision=None, distrib=None, tzinfo=None): """ Returns a generator yielding tuples of ``(<datetime>, <value>)``. The data points will start at ``start_date``, and be at every time interval specified by ``precision``. ``distrib`` is a callable that accepts ``<datetime>`` and returns ``<value>`` """ start_date = self._parse_date_time(start_date, tzinfo=tzinfo) end_date = self._parse_date_time(end_date, tzinfo=tzinfo) if end_date < start_date: raise ValueError("`end_date` must be greater than `start_date`.") if precision is None: precision = (end_date - start_date) / 30 precision = self._parse_timedelta(precision) if distrib is None: def distrib(dt): return self.generator.random.uniform(0, precision) # noqa if not callable(distrib): raise ValueError( "`distrib` must be a callable. Got {} instead.".format(distrib)) datapoint = start_date while datapoint < end_date: dt = timestamp_to_datetime(datapoint, tzinfo) datapoint += precision yield (dt, distrib(dt)) def am_pm(self): return self.date('%p') def day_of_month(self): return self.date('%d') def day_of_week(self): return self.date('%A') def month(self): return self.date('%m') def month_name(self): return self.date('%B') def year(self): return self.date('%Y') def century(self): """ :example 'XVII' """ return self.random_element(self.centuries) def timezone(self): return self.generator.random.choice( self.random_element(self.countries)['timezones']) def date_of_birth(self, tzinfo=None, minimum_age=0, maximum_age=115): """ Generate a random date of birth represented as a Date object, constrained by optional miminimum_age and maximum_age parameters. :param tzinfo Defaults to None. :param minimum_age Defaults to 0. :param maximum_age Defaults to 115. :example Date('1979-02-02') :return Date """ if not isinstance(minimum_age, int): raise TypeError("minimum_age must be an integer.") if not isinstance(maximum_age, int): raise TypeError("maximum_age must be an integer.") if (maximum_age < 0): raise ValueError("maximum_age must be greater than or equal to zero.") if (minimum_age < 0): raise ValueError("minimum_age must be greater than or equal to zero.") if (minimum_age > maximum_age): raise ValueError("minimum_age must be less than or equal to maximum_age.") # In order to return the full range of possible dates of birth, add one # year to the potential age cap and subtract one day if we land on the # boundary. now = datetime.now(tzinfo).date() start_date = now.replace(year=now.year - (maximum_age+1)) end_date = now.replace(year=now.year - minimum_age) dob = self.date_time_ad(tzinfo=tzinfo, start_datetime=start_date, end_datetime=end_date).date() return dob if dob != start_date else dob + timedelta(days=1)
0.555676
0.089296
import json from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.common.abstract_client import AbstractClient from tencentcloud.dayu.v20180709 import models class DayuClient(AbstractClient): _apiVersion = '2018-07-09' _endpoint = 'dayu.tencentcloudapi.com' def CreateBasicDDoSAlarmThreshold(self, request): """设置基础防护的DDoS告警阈值,只支持基础防护产品 :param request: Request instance for CreateBasicDDoSAlarmThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateBasicDDoSAlarmThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateBasicDDoSAlarmThresholdResponse` """ try: params = request._serialize() body = self.call("CreateBasicDDoSAlarmThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateBasicDDoSAlarmThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateBoundIP(self, request): """绑定IP到高防包实例,支持独享包、共享包;需要注意的是此接口绑定或解绑IP是异步接口,当处于绑定或解绑中时,则不允许再进行绑定或解绑,需要等待当前绑定或解绑完成。 :param request: Request instance for CreateBoundIP. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateBoundIPRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateBoundIPResponse` """ try: params = request._serialize() body = self.call("CreateBoundIP", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateBoundIPResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateCCFrequencyRules(self, request): """添加CC防护的访问频率控制规则 :param request: Request instance for CreateCCFrequencyRules. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateCCFrequencyRulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateCCFrequencyRulesResponse` """ try: params = request._serialize() body = self.call("CreateCCFrequencyRules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateCCFrequencyRulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateCCSelfDefinePolicy(self, request): """创建CC自定义策略 :param request: Request instance for CreateCCSelfDefinePolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateCCSelfDefinePolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateCCSelfDefinePolicyResponse` """ try: params = request._serialize() body = self.call("CreateCCSelfDefinePolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateCCSelfDefinePolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateDDoSPolicy(self, request): """添加DDoS高级策略 :param request: Request instance for CreateDDoSPolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateDDoSPolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateDDoSPolicyResponse` """ try: params = request._serialize() body = self.call("CreateDDoSPolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateDDoSPolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateDDoSPolicyCase(self, request): """添加策略场景 :param request: Request instance for CreateDDoSPolicyCase. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateDDoSPolicyCaseRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateDDoSPolicyCaseResponse` """ try: params = request._serialize() body = self.call("CreateDDoSPolicyCase", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateDDoSPolicyCaseResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateInstanceName(self, request): """资源实例重命名,支持独享包、共享包、高防IP、高防IP专业版; :param request: Request instance for CreateInstanceName. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateInstanceNameRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateInstanceNameResponse` """ try: params = request._serialize() body = self.call("CreateInstanceName", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateInstanceNameResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL4HealthConfig(self, request): """上传四层健康检查配置 :param request: Request instance for CreateL4HealthConfig. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL4HealthConfigRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL4HealthConfigResponse` """ try: params = request._serialize() body = self.call("CreateL4HealthConfig", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL4HealthConfigResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL4Rules(self, request): """添加L4转发规则 :param request: Request instance for CreateL4Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL4RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL4RulesResponse` """ try: params = request._serialize() body = self.call("CreateL4Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL4RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL7CCRule(self, request): """此接口是7层CC的访问频控自定义规则(IP+Host维度,不支持具体的URI),此接口已弃用,请调用新接口CreateCCFrequencyRules,新接口同时支持IP+Host维度以及具体的URI; :param request: Request instance for CreateL7CCRule. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL7CCRuleRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL7CCRuleResponse` """ try: params = request._serialize() body = self.call("CreateL7CCRule", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL7CCRuleResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL7HealthConfig(self, request): """上传七层健康检查配置 :param request: Request instance for CreateL7HealthConfig. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL7HealthConfigRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL7HealthConfigResponse` """ try: params = request._serialize() body = self.call("CreateL7HealthConfig", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL7HealthConfigResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL7RuleCert(self, request): """配置7层转发规则的证书 :param request: Request instance for CreateL7RuleCert. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL7RuleCertRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL7RuleCertResponse` """ try: params = request._serialize() body = self.call("CreateL7RuleCert", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL7RuleCertResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL7Rules(self, request): """添加7层(网站)转发规则 :param request: Request instance for CreateL7Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL7RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL7RulesResponse` """ try: params = request._serialize() body = self.call("CreateL7Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL7RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL7RulesUpload(self, request): """批量上传7层转发规则 :param request: Request instance for CreateL7RulesUpload. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL7RulesUploadRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL7RulesUploadResponse` """ try: params = request._serialize() body = self.call("CreateL7RulesUpload", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL7RulesUploadResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateNetReturn(self, request): """高防IP专业版一键切回源站 :param request: Request instance for CreateNetReturn. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateNetReturnRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateNetReturnResponse` """ try: params = request._serialize() body = self.call("CreateNetReturn", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateNetReturnResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateUnblockIp(self, request): """IP解封操作 :param request: Request instance for CreateUnblockIp. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateUnblockIpRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateUnblockIpResponse` """ try: params = request._serialize() body = self.call("CreateUnblockIp", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateUnblockIpResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteCCFrequencyRules(self, request): """删除CC防护的访问频率控制规则 :param request: Request instance for DeleteCCFrequencyRules. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteCCFrequencyRulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteCCFrequencyRulesResponse` """ try: params = request._serialize() body = self.call("DeleteCCFrequencyRules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteCCFrequencyRulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteCCSelfDefinePolicy(self, request): """删除CC自定义策略 :param request: Request instance for DeleteCCSelfDefinePolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteCCSelfDefinePolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteCCSelfDefinePolicyResponse` """ try: params = request._serialize() body = self.call("DeleteCCSelfDefinePolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteCCSelfDefinePolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteDDoSPolicy(self, request): """删除DDoS高级策略 :param request: Request instance for DeleteDDoSPolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteDDoSPolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteDDoSPolicyResponse` """ try: params = request._serialize() body = self.call("DeleteDDoSPolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteDDoSPolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteDDoSPolicyCase(self, request): """删除策略场景 :param request: Request instance for DeleteDDoSPolicyCase. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteDDoSPolicyCaseRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteDDoSPolicyCaseResponse` """ try: params = request._serialize() body = self.call("DeleteDDoSPolicyCase", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteDDoSPolicyCaseResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteL4Rules(self, request): """删除四层转发规则 :param request: Request instance for DeleteL4Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteL4RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteL4RulesResponse` """ try: params = request._serialize() body = self.call("DeleteL4Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteL4RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteL7Rules(self, request): """删除七层转发规则 :param request: Request instance for DeleteL7Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteL7RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteL7RulesResponse` """ try: params = request._serialize() body = self.call("DeleteL7Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteL7RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeActionLog(self, request): """获取操作日志 :param request: Request instance for DescribeActionLog. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeActionLogRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeActionLogResponse` """ try: params = request._serialize() body = self.call("DescribeActionLog", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeActionLogResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeBaradData(self, request): """为大禹子产品提供业务转发指标数据的接口 :param request: Request instance for DescribeBaradData. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeBaradDataRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeBaradDataResponse` """ try: params = request._serialize() body = self.call("DescribeBaradData", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeBaradDataResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeBasicCCThreshold(self, request): """获取基础防护CC防护阈值 :param request: Request instance for DescribeBasicCCThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeBasicCCThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeBasicCCThresholdResponse` """ try: params = request._serialize() body = self.call("DescribeBasicCCThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeBasicCCThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeBasicDeviceThreshold(self, request): """获取基础防护黑洞阈值 :param request: Request instance for DescribeBasicDeviceThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeBasicDeviceThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeBasicDeviceThresholdResponse` """ try: params = request._serialize() body = self.call("DescribeBasicDeviceThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeBasicDeviceThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCAlarmThreshold(self, request): """获取高防包、高防IP、高防IP专业版、棋牌盾产品设置CC攻击的告警通知阈值 :param request: Request instance for DescribeCCAlarmThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCAlarmThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCAlarmThresholdResponse` """ try: params = request._serialize() body = self.call("DescribeCCAlarmThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCAlarmThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCEvList(self, request): """获取CC攻击事件列表 :param request: Request instance for DescribeCCEvList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCEvListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCEvListResponse` """ try: params = request._serialize() body = self.call("DescribeCCEvList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCEvListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCFrequencyRules(self, request): """获取CC防护的访问频率控制规则 :param request: Request instance for DescribeCCFrequencyRules. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCFrequencyRulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCFrequencyRulesResponse` """ try: params = request._serialize() body = self.call("DescribeCCFrequencyRules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCFrequencyRulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCIpAllowDeny(self, request): """获取CC的IP黑白名单 :param request: Request instance for DescribeCCIpAllowDeny. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCIpAllowDenyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCIpAllowDenyResponse` """ try: params = request._serialize() body = self.call("DescribeCCIpAllowDeny", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCIpAllowDenyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCSelfDefinePolicy(self, request): """获取CC自定义策略 :param request: Request instance for DescribeCCSelfDefinePolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCSelfDefinePolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCSelfDefinePolicyResponse` """ try: params = request._serialize() body = self.call("DescribeCCSelfDefinePolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCSelfDefinePolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCTrend(self, request): """获取CC攻击指标数据,包括总请求峰值(QPS)和攻击请求(QPS) :param request: Request instance for DescribeCCTrend. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCTrendRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCTrendResponse` """ try: params = request._serialize() body = self.call("DescribeCCTrend", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCTrendResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCUrlAllow(self, request): """获取CC的Url白名单 :param request: Request instance for DescribeCCUrlAllow. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCUrlAllowRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCUrlAllowResponse` """ try: params = request._serialize() body = self.call("DescribeCCUrlAllow", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCUrlAllowResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSAlarmThreshold(self, request): """获取高防包、高防IP、高防IP专业版、棋牌盾产品设置DDoS攻击的告警通知阈值 :param request: Request instance for DescribeDDoSAlarmThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAlarmThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAlarmThresholdResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSAlarmThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSAlarmThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSAttackIPRegionMap(self, request): """获取DDoS攻击源IP地域分布图,支持全球攻击分布和国内省份攻击分布; :param request: Request instance for DescribeDDoSAttackIPRegionMap. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAttackIPRegionMapRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAttackIPRegionMapResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSAttackIPRegionMap", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSAttackIPRegionMapResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSAttackSource(self, request): """获取DDoS攻击源列表 :param request: Request instance for DescribeDDoSAttackSource. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAttackSourceRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAttackSourceResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSAttackSource", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSAttackSourceResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSCount(self, request): """获取DDoS攻击占比分析 :param request: Request instance for DescribeDDoSCount. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSCountRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSCountResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSCount", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSCountResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSDefendStatus(self, request): """获取DDoS防护状态(临时关闭状态),支持产品:基础防护,独享包,共享包,高防IP,高防IP专业版;调用此接口是获取当前是否有设置临时关闭DDoS防护状态,如果有设置会返回临时关闭的时长等参数。 :param request: Request instance for DescribeDDoSDefendStatus. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSDefendStatusRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSDefendStatusResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSDefendStatus", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSDefendStatusResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSEvInfo(self, request): """获取DDoS攻击事件详情 :param request: Request instance for DescribeDDoSEvInfo. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSEvInfoRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSEvInfoResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSEvInfo", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSEvInfoResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSEvList(self, request): """获取DDoS攻击事件列表 :param request: Request instance for DescribeDDoSEvList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSEvListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSEvListResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSEvList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSEvListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSIpLog(self, request): """获取DDoSIP攻击日志 :param request: Request instance for DescribeDDoSIpLog. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSIpLogRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSIpLogResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSIpLog", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSIpLogResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSNetCount(self, request): """获取高防IP专业版资源的DDoS攻击占比分析 :param request: Request instance for DescribeDDoSNetCount. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetCountRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetCountResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSNetCount", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSNetCountResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSNetEvInfo(self, request): """获取高防IP专业版资源的DDoS攻击事件详情 :param request: Request instance for DescribeDDoSNetEvInfo. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetEvInfoRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetEvInfoResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSNetEvInfo", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSNetEvInfoResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSNetEvList(self, request): """获取高防IP专业版资源的DDoS攻击事件列表 :param request: Request instance for DescribeDDoSNetEvList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetEvListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetEvListResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSNetEvList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSNetEvListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSNetIpLog(self, request): """获取高防IP专业版资源的DDoSIP攻击日志 :param request: Request instance for DescribeDDoSNetIpLog. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetIpLogRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetIpLogResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSNetIpLog", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSNetIpLogResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSNetTrend(self, request): """获取高防IP专业版资源的DDoS攻击指标数据 :param request: Request instance for DescribeDDoSNetTrend. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetTrendRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetTrendResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSNetTrend", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSNetTrendResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSPolicy(self, request): """获取DDoS高级策略 :param request: Request instance for DescribeDDoSPolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSPolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSPolicyResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSPolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSPolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSTrend(self, request): """获取DDoS攻击流量带宽和攻击包速率数据 :param request: Request instance for DescribeDDoSTrend. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSTrendRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSTrendResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSTrend", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSTrendResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSUsedStatis(self, request): """统计用户的高防资源的使用天数和DDoS攻击防护次数 :param request: Request instance for DescribeDDoSUsedStatis. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSUsedStatisRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSUsedStatisResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSUsedStatis", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSUsedStatisResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeIPProductInfo(self, request): """获取独享包或共享包IP对应的云资产信息,只支持独享包和共享包的IP :param request: Request instance for DescribeIPProductInfo. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeIPProductInfoRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeIPProductInfoResponse` """ try: params = request._serialize() body = self.call("DescribeIPProductInfo", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeIPProductInfoResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeInsurePacks(self, request): """获取保险包套餐列表 :param request: Request instance for DescribeInsurePacks. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeInsurePacksRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeInsurePacksResponse` """ try: params = request._serialize() body = self.call("DescribeInsurePacks", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeInsurePacksResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeIpBlockList(self, request): """获取IP封堵列表 :param request: Request instance for DescribeIpBlockList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeIpBlockListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeIpBlockListResponse` """ try: params = request._serialize() body = self.call("DescribeIpBlockList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeIpBlockListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeIpUnBlockList(self, request): """获取IP解封记录 :param request: Request instance for DescribeIpUnBlockList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeIpUnBlockListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeIpUnBlockListResponse` """ try: params = request._serialize() body = self.call("DescribeIpUnBlockList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeIpUnBlockListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeL4HealthConfig(self, request): """导出四层健康检查配置 :param request: Request instance for DescribeL4HealthConfig. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeL4HealthConfigRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeL4HealthConfigResponse` """ try: params = request._serialize() body = self.call("DescribeL4HealthConfig", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeL4HealthConfigResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeL4RulesErrHealth(self, request): """获取L4转发规则健康检查异常结果 :param request: Request instance for DescribeL4RulesErrHealth. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeL4RulesErrHealthRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeL4RulesErrHealthResponse` """ try: params = request._serialize() body = self.call("DescribeL4RulesErrHealth", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeL4RulesErrHealthResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeL7HealthConfig(self, request): """导出七层健康检查配置 :param request: Request instance for DescribeL7HealthConfig. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeL7HealthConfigRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeL7HealthConfigResponse` """ try: params = request._serialize() body = self.call("DescribeL7HealthConfig", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeL7HealthConfigResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribePackIndex(self, request): """获取产品总览统计,支持高防包、高防IP、高防IP专业版; :param request: Request instance for DescribePackIndex. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribePackIndexRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribePackIndexResponse` """ try: params = request._serialize() body = self.call("DescribePackIndex", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribePackIndexResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribePcap(self, request): """下载攻击事件的pcap包 :param request: Request instance for DescribePcap. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribePcapRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribePcapResponse` """ try: params = request._serialize() body = self.call("DescribePcap", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribePcapResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribePolicyCase(self, request): """获取策略场景 :param request: Request instance for DescribePolicyCase. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribePolicyCaseRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribePolicyCaseResponse` """ try: params = request._serialize() body = self.call("DescribePolicyCase", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribePolicyCaseResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeResIpList(self, request): """获取资源的IP列表 :param request: Request instance for DescribeResIpList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeResIpListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeResIpListResponse` """ try: params = request._serialize() body = self.call("DescribeResIpList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeResIpListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeResourceList(self, request): """获取资源列表 :param request: Request instance for DescribeResourceList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeResourceListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeResourceListResponse` """ try: params = request._serialize() body = self.call("DescribeResourceList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeResourceListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeRuleSets(self, request): """获取资源的规则数 :param request: Request instance for DescribeRuleSets. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeRuleSetsRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeRuleSetsResponse` """ try: params = request._serialize() body = self.call("DescribeRuleSets", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeRuleSetsResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeSecIndex(self, request): """获取本月安全统计 :param request: Request instance for DescribeSecIndex. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeSecIndexRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeSecIndexResponse` """ try: params = request._serialize() body = self.call("DescribeSecIndex", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeSecIndexResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeSourceIpSegment(self, request): """获取回源IP段,支持的产品:高防IP,高防IP专业版; :param request: Request instance for DescribeSourceIpSegment. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeSourceIpSegmentRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeSourceIpSegmentResponse` """ try: params = request._serialize() body = self.call("DescribeSourceIpSegment", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeSourceIpSegmentResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeTransmitStatis(self, request): """获取业务转发统计数据,支持转发流量和转发包速率 :param request: Request instance for DescribeTransmitStatis. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeTransmitStatisRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeTransmitStatisResponse` """ try: params = request._serialize() body = self.call("DescribeTransmitStatis", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeTransmitStatisResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeUnBlockStatis(self, request): """获取黑洞解封次数 :param request: Request instance for DescribeUnBlockStatis. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeUnBlockStatisRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeUnBlockStatisResponse` """ try: params = request._serialize() body = self.call("DescribeUnBlockStatis", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeUnBlockStatisResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribleL4Rules(self, request): """获取四层转发规则 :param request: Request instance for DescribleL4Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribleL4RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribleL4RulesResponse` """ try: params = request._serialize() body = self.call("DescribleL4Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribleL4RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribleL7Rules(self, request): """获取七层转发规则 :param request: Request instance for DescribleL7Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribleL7RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribleL7RulesResponse` """ try: params = request._serialize() body = self.call("DescribleL7Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribleL7RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribleRegionCount(self, request): """获取地域的资源实例数 :param request: Request instance for DescribleRegionCount. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribleRegionCountRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribleRegionCountResponse` """ try: params = request._serialize() body = self.call("DescribleRegionCount", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribleRegionCountResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCAlarmThreshold(self, request): """为高防包、高防IP、高防IP专业版、棋牌盾产品设置CC攻击的告警通知阈值 :param request: Request instance for ModifyCCAlarmThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCAlarmThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCAlarmThresholdResponse` """ try: params = request._serialize() body = self.call("ModifyCCAlarmThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCAlarmThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCFrequencyRules(self, request): """修改CC防护的访问频率控制规则 :param request: Request instance for ModifyCCFrequencyRules. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCFrequencyRulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCFrequencyRulesResponse` """ try: params = request._serialize() body = self.call("ModifyCCFrequencyRules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCFrequencyRulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCFrequencyRulesStatus(self, request): """开启或关闭CC防护的访问频率控制规则 :param request: Request instance for ModifyCCFrequencyRulesStatus. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCFrequencyRulesStatusRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCFrequencyRulesStatusResponse` """ try: params = request._serialize() body = self.call("ModifyCCFrequencyRulesStatus", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCFrequencyRulesStatusResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCHostProtection(self, request): """开启或关闭CC域名防护 :param request: Request instance for ModifyCCHostProtection. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCHostProtectionRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCHostProtectionResponse` """ try: params = request._serialize() body = self.call("ModifyCCHostProtection", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCHostProtectionResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCIpAllowDeny(self, request): """添加或删除CC的IP黑白名单 :param request: Request instance for ModifyCCIpAllowDeny. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCIpAllowDenyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCIpAllowDenyResponse` """ try: params = request._serialize() body = self.call("ModifyCCIpAllowDeny", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCIpAllowDenyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCLevel(self, request): """修改CC防护等级 :param request: Request instance for ModifyCCLevel. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCLevelRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCLevelResponse` """ try: params = request._serialize() body = self.call("ModifyCCLevel", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCLevelResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCPolicySwitch(self, request): """修改CC自定义策略开关 :param request: Request instance for ModifyCCPolicySwitch. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCPolicySwitchRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCPolicySwitchResponse` """ try: params = request._serialize() body = self.call("ModifyCCPolicySwitch", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCPolicySwitchResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCSelfDefinePolicy(self, request): """修改CC自定义策略 :param request: Request instance for ModifyCCSelfDefinePolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCSelfDefinePolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCSelfDefinePolicyResponse` """ try: params = request._serialize() body = self.call("ModifyCCSelfDefinePolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCSelfDefinePolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCThreshold(self, request): """修改CC的防护阈值 :param request: Request instance for ModifyCCThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCThresholdResponse` """ try: params = request._serialize() body = self.call("ModifyCCThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCUrlAllow(self, request): """添加或删除CC的URL白名单 :param request: Request instance for ModifyCCUrlAllow. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCUrlAllowRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCUrlAllowResponse` """ try: params = request._serialize() body = self.call("ModifyCCUrlAllow", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCUrlAllowResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSAIStatus(self, request): """读取或修改DDoS的AI防护状态 :param request: Request instance for ModifyDDoSAIStatus. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSAIStatusRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSAIStatusResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSAIStatus", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSAIStatusResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSAlarmThreshold(self, request): """为高防包、高防IP、高防IP专业版、棋牌盾等产品设置DDoS攻击的告警通知阈值 :param request: Request instance for ModifyDDoSAlarmThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSAlarmThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSAlarmThresholdResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSAlarmThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSAlarmThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSDefendStatus(self, request): """开启或关闭DDoS防护状态,调用此接口允许临时关闭DDoS防护一段时间,等时间到了会自动开启DDoS防护; :param request: Request instance for ModifyDDoSDefendStatus. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSDefendStatusRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSDefendStatusResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSDefendStatus", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSDefendStatusResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSLevel(self, request): """读取或修改DDoS的防护等级 :param request: Request instance for ModifyDDoSLevel. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSLevelRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSLevelResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSLevel", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSLevelResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSPolicy(self, request): """修改DDoS高级策略 :param request: Request instance for ModifyDDoSPolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSPolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSPolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSPolicyCase(self, request): """修改策略场景 :param request: Request instance for ModifyDDoSPolicyCase. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyCaseRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyCaseResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSPolicyCase", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSPolicyCaseResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSPolicyName(self, request): """修改DDoS高级策略名称 :param request: Request instance for ModifyDDoSPolicyName. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyNameRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyNameResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSPolicyName", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSPolicyNameResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSSwitch(self, request): """开启或关闭DDoS防护,只支持基础防护产品; :param request: Request instance for ModifyDDoSSwitch. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSSwitchRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSSwitchResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSSwitch", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSSwitchResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSThreshold(self, request): """修改DDoS清洗阈值 :param request: Request instance for ModifyDDoSThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSThresholdResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSWaterKey(self, request): """支持水印密钥的添加,删除,开启,关闭 :param request: Request instance for ModifyDDoSWaterKey. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSWaterKeyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSWaterKeyResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSWaterKey", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSWaterKeyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyElasticLimit(self, request): """修改弹性防护阈值 :param request: Request instance for ModifyElasticLimit. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyElasticLimitRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyElasticLimitResponse` """ try: params = request._serialize() body = self.call("ModifyElasticLimit", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyElasticLimitResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyL4Health(self, request): """修改L4转发规则健康检查参数,支持的子产品:高防IP、高防IP专业版 :param request: Request instance for ModifyL4Health. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyL4HealthRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyL4HealthResponse` """ try: params = request._serialize() body = self.call("ModifyL4Health", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyL4HealthResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyL4KeepTime(self, request): """修改L4转发规则的会话保持,支持的子产品:高防IP、高防IP专业版 :param request: Request instance for ModifyL4KeepTime. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyL4KeepTimeRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyL4KeepTimeResponse` """ try: params = request._serialize() body = self.call("ModifyL4KeepTime", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyL4KeepTimeResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyL4Rules(self, request): """修改L4转发规则 :param request: Request instance for ModifyL4Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyL4RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyL4RulesResponse` """ try: params = request._serialize() body = self.call("ModifyL4Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyL4RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyL7Rules(self, request): """修改L7转发规则 :param request: Request instance for ModifyL7Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyL7RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyL7RulesResponse` """ try: params = request._serialize() body = self.call("ModifyL7Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyL7RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyNetReturnSwitch(self, request): """在客户收攻击或者被封堵时,切回到源站,并设置回切的时长 :param request: Request instance for ModifyNetReturnSwitch. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyNetReturnSwitchRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyNetReturnSwitchResponse` """ try: params = request._serialize() body = self.call("ModifyNetReturnSwitch", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyNetReturnSwitchResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyResBindDDoSPolicy(self, request): """资源实例绑定DDoS高级策略 :param request: Request instance for ModifyResBindDDoSPolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyResBindDDoSPolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyResBindDDoSPolicyResponse` """ try: params = request._serialize() body = self.call("ModifyResBindDDoSPolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyResBindDDoSPolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyResourceRenewFlag(self, request): """修改资源自动续费标记 :param request: Request instance for ModifyResourceRenewFlag. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyResourceRenewFlagRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyResourceRenewFlagResponse` """ try: params = request._serialize() body = self.call("ModifyResourceRenewFlag", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyResourceRenewFlagResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
tencentcloud/dayu/v20180709/dayu_client.py
import json from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.common.abstract_client import AbstractClient from tencentcloud.dayu.v20180709 import models class DayuClient(AbstractClient): _apiVersion = '2018-07-09' _endpoint = 'dayu.tencentcloudapi.com' def CreateBasicDDoSAlarmThreshold(self, request): """设置基础防护的DDoS告警阈值,只支持基础防护产品 :param request: Request instance for CreateBasicDDoSAlarmThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateBasicDDoSAlarmThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateBasicDDoSAlarmThresholdResponse` """ try: params = request._serialize() body = self.call("CreateBasicDDoSAlarmThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateBasicDDoSAlarmThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateBoundIP(self, request): """绑定IP到高防包实例,支持独享包、共享包;需要注意的是此接口绑定或解绑IP是异步接口,当处于绑定或解绑中时,则不允许再进行绑定或解绑,需要等待当前绑定或解绑完成。 :param request: Request instance for CreateBoundIP. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateBoundIPRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateBoundIPResponse` """ try: params = request._serialize() body = self.call("CreateBoundIP", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateBoundIPResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateCCFrequencyRules(self, request): """添加CC防护的访问频率控制规则 :param request: Request instance for CreateCCFrequencyRules. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateCCFrequencyRulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateCCFrequencyRulesResponse` """ try: params = request._serialize() body = self.call("CreateCCFrequencyRules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateCCFrequencyRulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateCCSelfDefinePolicy(self, request): """创建CC自定义策略 :param request: Request instance for CreateCCSelfDefinePolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateCCSelfDefinePolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateCCSelfDefinePolicyResponse` """ try: params = request._serialize() body = self.call("CreateCCSelfDefinePolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateCCSelfDefinePolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateDDoSPolicy(self, request): """添加DDoS高级策略 :param request: Request instance for CreateDDoSPolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateDDoSPolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateDDoSPolicyResponse` """ try: params = request._serialize() body = self.call("CreateDDoSPolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateDDoSPolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateDDoSPolicyCase(self, request): """添加策略场景 :param request: Request instance for CreateDDoSPolicyCase. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateDDoSPolicyCaseRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateDDoSPolicyCaseResponse` """ try: params = request._serialize() body = self.call("CreateDDoSPolicyCase", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateDDoSPolicyCaseResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateInstanceName(self, request): """资源实例重命名,支持独享包、共享包、高防IP、高防IP专业版; :param request: Request instance for CreateInstanceName. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateInstanceNameRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateInstanceNameResponse` """ try: params = request._serialize() body = self.call("CreateInstanceName", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateInstanceNameResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL4HealthConfig(self, request): """上传四层健康检查配置 :param request: Request instance for CreateL4HealthConfig. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL4HealthConfigRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL4HealthConfigResponse` """ try: params = request._serialize() body = self.call("CreateL4HealthConfig", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL4HealthConfigResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL4Rules(self, request): """添加L4转发规则 :param request: Request instance for CreateL4Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL4RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL4RulesResponse` """ try: params = request._serialize() body = self.call("CreateL4Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL4RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL7CCRule(self, request): """此接口是7层CC的访问频控自定义规则(IP+Host维度,不支持具体的URI),此接口已弃用,请调用新接口CreateCCFrequencyRules,新接口同时支持IP+Host维度以及具体的URI; :param request: Request instance for CreateL7CCRule. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL7CCRuleRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL7CCRuleResponse` """ try: params = request._serialize() body = self.call("CreateL7CCRule", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL7CCRuleResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL7HealthConfig(self, request): """上传七层健康检查配置 :param request: Request instance for CreateL7HealthConfig. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL7HealthConfigRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL7HealthConfigResponse` """ try: params = request._serialize() body = self.call("CreateL7HealthConfig", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL7HealthConfigResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL7RuleCert(self, request): """配置7层转发规则的证书 :param request: Request instance for CreateL7RuleCert. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL7RuleCertRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL7RuleCertResponse` """ try: params = request._serialize() body = self.call("CreateL7RuleCert", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL7RuleCertResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL7Rules(self, request): """添加7层(网站)转发规则 :param request: Request instance for CreateL7Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL7RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL7RulesResponse` """ try: params = request._serialize() body = self.call("CreateL7Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL7RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateL7RulesUpload(self, request): """批量上传7层转发规则 :param request: Request instance for CreateL7RulesUpload. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateL7RulesUploadRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateL7RulesUploadResponse` """ try: params = request._serialize() body = self.call("CreateL7RulesUpload", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateL7RulesUploadResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateNetReturn(self, request): """高防IP专业版一键切回源站 :param request: Request instance for CreateNetReturn. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateNetReturnRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateNetReturnResponse` """ try: params = request._serialize() body = self.call("CreateNetReturn", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateNetReturnResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def CreateUnblockIp(self, request): """IP解封操作 :param request: Request instance for CreateUnblockIp. :type request: :class:`tencentcloud.dayu.v20180709.models.CreateUnblockIpRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.CreateUnblockIpResponse` """ try: params = request._serialize() body = self.call("CreateUnblockIp", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateUnblockIpResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteCCFrequencyRules(self, request): """删除CC防护的访问频率控制规则 :param request: Request instance for DeleteCCFrequencyRules. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteCCFrequencyRulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteCCFrequencyRulesResponse` """ try: params = request._serialize() body = self.call("DeleteCCFrequencyRules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteCCFrequencyRulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteCCSelfDefinePolicy(self, request): """删除CC自定义策略 :param request: Request instance for DeleteCCSelfDefinePolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteCCSelfDefinePolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteCCSelfDefinePolicyResponse` """ try: params = request._serialize() body = self.call("DeleteCCSelfDefinePolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteCCSelfDefinePolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteDDoSPolicy(self, request): """删除DDoS高级策略 :param request: Request instance for DeleteDDoSPolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteDDoSPolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteDDoSPolicyResponse` """ try: params = request._serialize() body = self.call("DeleteDDoSPolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteDDoSPolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteDDoSPolicyCase(self, request): """删除策略场景 :param request: Request instance for DeleteDDoSPolicyCase. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteDDoSPolicyCaseRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteDDoSPolicyCaseResponse` """ try: params = request._serialize() body = self.call("DeleteDDoSPolicyCase", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteDDoSPolicyCaseResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteL4Rules(self, request): """删除四层转发规则 :param request: Request instance for DeleteL4Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteL4RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteL4RulesResponse` """ try: params = request._serialize() body = self.call("DeleteL4Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteL4RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DeleteL7Rules(self, request): """删除七层转发规则 :param request: Request instance for DeleteL7Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.DeleteL7RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DeleteL7RulesResponse` """ try: params = request._serialize() body = self.call("DeleteL7Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DeleteL7RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeActionLog(self, request): """获取操作日志 :param request: Request instance for DescribeActionLog. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeActionLogRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeActionLogResponse` """ try: params = request._serialize() body = self.call("DescribeActionLog", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeActionLogResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeBaradData(self, request): """为大禹子产品提供业务转发指标数据的接口 :param request: Request instance for DescribeBaradData. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeBaradDataRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeBaradDataResponse` """ try: params = request._serialize() body = self.call("DescribeBaradData", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeBaradDataResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeBasicCCThreshold(self, request): """获取基础防护CC防护阈值 :param request: Request instance for DescribeBasicCCThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeBasicCCThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeBasicCCThresholdResponse` """ try: params = request._serialize() body = self.call("DescribeBasicCCThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeBasicCCThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeBasicDeviceThreshold(self, request): """获取基础防护黑洞阈值 :param request: Request instance for DescribeBasicDeviceThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeBasicDeviceThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeBasicDeviceThresholdResponse` """ try: params = request._serialize() body = self.call("DescribeBasicDeviceThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeBasicDeviceThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCAlarmThreshold(self, request): """获取高防包、高防IP、高防IP专业版、棋牌盾产品设置CC攻击的告警通知阈值 :param request: Request instance for DescribeCCAlarmThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCAlarmThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCAlarmThresholdResponse` """ try: params = request._serialize() body = self.call("DescribeCCAlarmThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCAlarmThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCEvList(self, request): """获取CC攻击事件列表 :param request: Request instance for DescribeCCEvList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCEvListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCEvListResponse` """ try: params = request._serialize() body = self.call("DescribeCCEvList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCEvListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCFrequencyRules(self, request): """获取CC防护的访问频率控制规则 :param request: Request instance for DescribeCCFrequencyRules. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCFrequencyRulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCFrequencyRulesResponse` """ try: params = request._serialize() body = self.call("DescribeCCFrequencyRules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCFrequencyRulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCIpAllowDeny(self, request): """获取CC的IP黑白名单 :param request: Request instance for DescribeCCIpAllowDeny. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCIpAllowDenyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCIpAllowDenyResponse` """ try: params = request._serialize() body = self.call("DescribeCCIpAllowDeny", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCIpAllowDenyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCSelfDefinePolicy(self, request): """获取CC自定义策略 :param request: Request instance for DescribeCCSelfDefinePolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCSelfDefinePolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCSelfDefinePolicyResponse` """ try: params = request._serialize() body = self.call("DescribeCCSelfDefinePolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCSelfDefinePolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCTrend(self, request): """获取CC攻击指标数据,包括总请求峰值(QPS)和攻击请求(QPS) :param request: Request instance for DescribeCCTrend. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCTrendRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCTrendResponse` """ try: params = request._serialize() body = self.call("DescribeCCTrend", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCTrendResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeCCUrlAllow(self, request): """获取CC的Url白名单 :param request: Request instance for DescribeCCUrlAllow. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeCCUrlAllowRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeCCUrlAllowResponse` """ try: params = request._serialize() body = self.call("DescribeCCUrlAllow", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeCCUrlAllowResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSAlarmThreshold(self, request): """获取高防包、高防IP、高防IP专业版、棋牌盾产品设置DDoS攻击的告警通知阈值 :param request: Request instance for DescribeDDoSAlarmThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAlarmThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAlarmThresholdResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSAlarmThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSAlarmThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSAttackIPRegionMap(self, request): """获取DDoS攻击源IP地域分布图,支持全球攻击分布和国内省份攻击分布; :param request: Request instance for DescribeDDoSAttackIPRegionMap. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAttackIPRegionMapRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAttackIPRegionMapResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSAttackIPRegionMap", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSAttackIPRegionMapResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSAttackSource(self, request): """获取DDoS攻击源列表 :param request: Request instance for DescribeDDoSAttackSource. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAttackSourceRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSAttackSourceResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSAttackSource", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSAttackSourceResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSCount(self, request): """获取DDoS攻击占比分析 :param request: Request instance for DescribeDDoSCount. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSCountRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSCountResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSCount", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSCountResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSDefendStatus(self, request): """获取DDoS防护状态(临时关闭状态),支持产品:基础防护,独享包,共享包,高防IP,高防IP专业版;调用此接口是获取当前是否有设置临时关闭DDoS防护状态,如果有设置会返回临时关闭的时长等参数。 :param request: Request instance for DescribeDDoSDefendStatus. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSDefendStatusRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSDefendStatusResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSDefendStatus", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSDefendStatusResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSEvInfo(self, request): """获取DDoS攻击事件详情 :param request: Request instance for DescribeDDoSEvInfo. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSEvInfoRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSEvInfoResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSEvInfo", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSEvInfoResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSEvList(self, request): """获取DDoS攻击事件列表 :param request: Request instance for DescribeDDoSEvList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSEvListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSEvListResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSEvList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSEvListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSIpLog(self, request): """获取DDoSIP攻击日志 :param request: Request instance for DescribeDDoSIpLog. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSIpLogRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSIpLogResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSIpLog", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSIpLogResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSNetCount(self, request): """获取高防IP专业版资源的DDoS攻击占比分析 :param request: Request instance for DescribeDDoSNetCount. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetCountRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetCountResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSNetCount", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSNetCountResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSNetEvInfo(self, request): """获取高防IP专业版资源的DDoS攻击事件详情 :param request: Request instance for DescribeDDoSNetEvInfo. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetEvInfoRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetEvInfoResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSNetEvInfo", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSNetEvInfoResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSNetEvList(self, request): """获取高防IP专业版资源的DDoS攻击事件列表 :param request: Request instance for DescribeDDoSNetEvList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetEvListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetEvListResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSNetEvList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSNetEvListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSNetIpLog(self, request): """获取高防IP专业版资源的DDoSIP攻击日志 :param request: Request instance for DescribeDDoSNetIpLog. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetIpLogRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetIpLogResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSNetIpLog", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSNetIpLogResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSNetTrend(self, request): """获取高防IP专业版资源的DDoS攻击指标数据 :param request: Request instance for DescribeDDoSNetTrend. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetTrendRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSNetTrendResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSNetTrend", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSNetTrendResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSPolicy(self, request): """获取DDoS高级策略 :param request: Request instance for DescribeDDoSPolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSPolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSPolicyResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSPolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSPolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSTrend(self, request): """获取DDoS攻击流量带宽和攻击包速率数据 :param request: Request instance for DescribeDDoSTrend. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSTrendRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSTrendResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSTrend", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSTrendResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeDDoSUsedStatis(self, request): """统计用户的高防资源的使用天数和DDoS攻击防护次数 :param request: Request instance for DescribeDDoSUsedStatis. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSUsedStatisRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeDDoSUsedStatisResponse` """ try: params = request._serialize() body = self.call("DescribeDDoSUsedStatis", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDDoSUsedStatisResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeIPProductInfo(self, request): """获取独享包或共享包IP对应的云资产信息,只支持独享包和共享包的IP :param request: Request instance for DescribeIPProductInfo. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeIPProductInfoRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeIPProductInfoResponse` """ try: params = request._serialize() body = self.call("DescribeIPProductInfo", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeIPProductInfoResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeInsurePacks(self, request): """获取保险包套餐列表 :param request: Request instance for DescribeInsurePacks. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeInsurePacksRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeInsurePacksResponse` """ try: params = request._serialize() body = self.call("DescribeInsurePacks", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeInsurePacksResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeIpBlockList(self, request): """获取IP封堵列表 :param request: Request instance for DescribeIpBlockList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeIpBlockListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeIpBlockListResponse` """ try: params = request._serialize() body = self.call("DescribeIpBlockList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeIpBlockListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeIpUnBlockList(self, request): """获取IP解封记录 :param request: Request instance for DescribeIpUnBlockList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeIpUnBlockListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeIpUnBlockListResponse` """ try: params = request._serialize() body = self.call("DescribeIpUnBlockList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeIpUnBlockListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeL4HealthConfig(self, request): """导出四层健康检查配置 :param request: Request instance for DescribeL4HealthConfig. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeL4HealthConfigRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeL4HealthConfigResponse` """ try: params = request._serialize() body = self.call("DescribeL4HealthConfig", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeL4HealthConfigResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeL4RulesErrHealth(self, request): """获取L4转发规则健康检查异常结果 :param request: Request instance for DescribeL4RulesErrHealth. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeL4RulesErrHealthRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeL4RulesErrHealthResponse` """ try: params = request._serialize() body = self.call("DescribeL4RulesErrHealth", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeL4RulesErrHealthResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeL7HealthConfig(self, request): """导出七层健康检查配置 :param request: Request instance for DescribeL7HealthConfig. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeL7HealthConfigRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeL7HealthConfigResponse` """ try: params = request._serialize() body = self.call("DescribeL7HealthConfig", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeL7HealthConfigResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribePackIndex(self, request): """获取产品总览统计,支持高防包、高防IP、高防IP专业版; :param request: Request instance for DescribePackIndex. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribePackIndexRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribePackIndexResponse` """ try: params = request._serialize() body = self.call("DescribePackIndex", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribePackIndexResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribePcap(self, request): """下载攻击事件的pcap包 :param request: Request instance for DescribePcap. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribePcapRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribePcapResponse` """ try: params = request._serialize() body = self.call("DescribePcap", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribePcapResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribePolicyCase(self, request): """获取策略场景 :param request: Request instance for DescribePolicyCase. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribePolicyCaseRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribePolicyCaseResponse` """ try: params = request._serialize() body = self.call("DescribePolicyCase", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribePolicyCaseResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeResIpList(self, request): """获取资源的IP列表 :param request: Request instance for DescribeResIpList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeResIpListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeResIpListResponse` """ try: params = request._serialize() body = self.call("DescribeResIpList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeResIpListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeResourceList(self, request): """获取资源列表 :param request: Request instance for DescribeResourceList. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeResourceListRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeResourceListResponse` """ try: params = request._serialize() body = self.call("DescribeResourceList", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeResourceListResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeRuleSets(self, request): """获取资源的规则数 :param request: Request instance for DescribeRuleSets. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeRuleSetsRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeRuleSetsResponse` """ try: params = request._serialize() body = self.call("DescribeRuleSets", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeRuleSetsResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeSecIndex(self, request): """获取本月安全统计 :param request: Request instance for DescribeSecIndex. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeSecIndexRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeSecIndexResponse` """ try: params = request._serialize() body = self.call("DescribeSecIndex", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeSecIndexResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeSourceIpSegment(self, request): """获取回源IP段,支持的产品:高防IP,高防IP专业版; :param request: Request instance for DescribeSourceIpSegment. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeSourceIpSegmentRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeSourceIpSegmentResponse` """ try: params = request._serialize() body = self.call("DescribeSourceIpSegment", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeSourceIpSegmentResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeTransmitStatis(self, request): """获取业务转发统计数据,支持转发流量和转发包速率 :param request: Request instance for DescribeTransmitStatis. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeTransmitStatisRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeTransmitStatisResponse` """ try: params = request._serialize() body = self.call("DescribeTransmitStatis", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeTransmitStatisResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribeUnBlockStatis(self, request): """获取黑洞解封次数 :param request: Request instance for DescribeUnBlockStatis. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribeUnBlockStatisRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribeUnBlockStatisResponse` """ try: params = request._serialize() body = self.call("DescribeUnBlockStatis", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeUnBlockStatisResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribleL4Rules(self, request): """获取四层转发规则 :param request: Request instance for DescribleL4Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribleL4RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribleL4RulesResponse` """ try: params = request._serialize() body = self.call("DescribleL4Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribleL4RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribleL7Rules(self, request): """获取七层转发规则 :param request: Request instance for DescribleL7Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribleL7RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribleL7RulesResponse` """ try: params = request._serialize() body = self.call("DescribleL7Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribleL7RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def DescribleRegionCount(self, request): """获取地域的资源实例数 :param request: Request instance for DescribleRegionCount. :type request: :class:`tencentcloud.dayu.v20180709.models.DescribleRegionCountRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.DescribleRegionCountResponse` """ try: params = request._serialize() body = self.call("DescribleRegionCount", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribleRegionCountResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCAlarmThreshold(self, request): """为高防包、高防IP、高防IP专业版、棋牌盾产品设置CC攻击的告警通知阈值 :param request: Request instance for ModifyCCAlarmThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCAlarmThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCAlarmThresholdResponse` """ try: params = request._serialize() body = self.call("ModifyCCAlarmThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCAlarmThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCFrequencyRules(self, request): """修改CC防护的访问频率控制规则 :param request: Request instance for ModifyCCFrequencyRules. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCFrequencyRulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCFrequencyRulesResponse` """ try: params = request._serialize() body = self.call("ModifyCCFrequencyRules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCFrequencyRulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCFrequencyRulesStatus(self, request): """开启或关闭CC防护的访问频率控制规则 :param request: Request instance for ModifyCCFrequencyRulesStatus. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCFrequencyRulesStatusRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCFrequencyRulesStatusResponse` """ try: params = request._serialize() body = self.call("ModifyCCFrequencyRulesStatus", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCFrequencyRulesStatusResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCHostProtection(self, request): """开启或关闭CC域名防护 :param request: Request instance for ModifyCCHostProtection. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCHostProtectionRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCHostProtectionResponse` """ try: params = request._serialize() body = self.call("ModifyCCHostProtection", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCHostProtectionResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCIpAllowDeny(self, request): """添加或删除CC的IP黑白名单 :param request: Request instance for ModifyCCIpAllowDeny. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCIpAllowDenyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCIpAllowDenyResponse` """ try: params = request._serialize() body = self.call("ModifyCCIpAllowDeny", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCIpAllowDenyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCLevel(self, request): """修改CC防护等级 :param request: Request instance for ModifyCCLevel. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCLevelRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCLevelResponse` """ try: params = request._serialize() body = self.call("ModifyCCLevel", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCLevelResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCPolicySwitch(self, request): """修改CC自定义策略开关 :param request: Request instance for ModifyCCPolicySwitch. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCPolicySwitchRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCPolicySwitchResponse` """ try: params = request._serialize() body = self.call("ModifyCCPolicySwitch", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCPolicySwitchResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCSelfDefinePolicy(self, request): """修改CC自定义策略 :param request: Request instance for ModifyCCSelfDefinePolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCSelfDefinePolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCSelfDefinePolicyResponse` """ try: params = request._serialize() body = self.call("ModifyCCSelfDefinePolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCSelfDefinePolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCThreshold(self, request): """修改CC的防护阈值 :param request: Request instance for ModifyCCThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCThresholdResponse` """ try: params = request._serialize() body = self.call("ModifyCCThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyCCUrlAllow(self, request): """添加或删除CC的URL白名单 :param request: Request instance for ModifyCCUrlAllow. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyCCUrlAllowRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyCCUrlAllowResponse` """ try: params = request._serialize() body = self.call("ModifyCCUrlAllow", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyCCUrlAllowResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSAIStatus(self, request): """读取或修改DDoS的AI防护状态 :param request: Request instance for ModifyDDoSAIStatus. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSAIStatusRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSAIStatusResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSAIStatus", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSAIStatusResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSAlarmThreshold(self, request): """为高防包、高防IP、高防IP专业版、棋牌盾等产品设置DDoS攻击的告警通知阈值 :param request: Request instance for ModifyDDoSAlarmThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSAlarmThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSAlarmThresholdResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSAlarmThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSAlarmThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSDefendStatus(self, request): """开启或关闭DDoS防护状态,调用此接口允许临时关闭DDoS防护一段时间,等时间到了会自动开启DDoS防护; :param request: Request instance for ModifyDDoSDefendStatus. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSDefendStatusRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSDefendStatusResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSDefendStatus", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSDefendStatusResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSLevel(self, request): """读取或修改DDoS的防护等级 :param request: Request instance for ModifyDDoSLevel. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSLevelRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSLevelResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSLevel", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSLevelResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSPolicy(self, request): """修改DDoS高级策略 :param request: Request instance for ModifyDDoSPolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSPolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSPolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSPolicyCase(self, request): """修改策略场景 :param request: Request instance for ModifyDDoSPolicyCase. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyCaseRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyCaseResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSPolicyCase", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSPolicyCaseResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSPolicyName(self, request): """修改DDoS高级策略名称 :param request: Request instance for ModifyDDoSPolicyName. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyNameRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSPolicyNameResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSPolicyName", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSPolicyNameResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSSwitch(self, request): """开启或关闭DDoS防护,只支持基础防护产品; :param request: Request instance for ModifyDDoSSwitch. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSSwitchRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSSwitchResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSSwitch", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSSwitchResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSThreshold(self, request): """修改DDoS清洗阈值 :param request: Request instance for ModifyDDoSThreshold. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSThresholdRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSThresholdResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSThreshold", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSThresholdResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyDDoSWaterKey(self, request): """支持水印密钥的添加,删除,开启,关闭 :param request: Request instance for ModifyDDoSWaterKey. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSWaterKeyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyDDoSWaterKeyResponse` """ try: params = request._serialize() body = self.call("ModifyDDoSWaterKey", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyDDoSWaterKeyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyElasticLimit(self, request): """修改弹性防护阈值 :param request: Request instance for ModifyElasticLimit. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyElasticLimitRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyElasticLimitResponse` """ try: params = request._serialize() body = self.call("ModifyElasticLimit", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyElasticLimitResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyL4Health(self, request): """修改L4转发规则健康检查参数,支持的子产品:高防IP、高防IP专业版 :param request: Request instance for ModifyL4Health. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyL4HealthRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyL4HealthResponse` """ try: params = request._serialize() body = self.call("ModifyL4Health", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyL4HealthResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyL4KeepTime(self, request): """修改L4转发规则的会话保持,支持的子产品:高防IP、高防IP专业版 :param request: Request instance for ModifyL4KeepTime. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyL4KeepTimeRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyL4KeepTimeResponse` """ try: params = request._serialize() body = self.call("ModifyL4KeepTime", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyL4KeepTimeResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyL4Rules(self, request): """修改L4转发规则 :param request: Request instance for ModifyL4Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyL4RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyL4RulesResponse` """ try: params = request._serialize() body = self.call("ModifyL4Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyL4RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyL7Rules(self, request): """修改L7转发规则 :param request: Request instance for ModifyL7Rules. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyL7RulesRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyL7RulesResponse` """ try: params = request._serialize() body = self.call("ModifyL7Rules", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyL7RulesResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyNetReturnSwitch(self, request): """在客户收攻击或者被封堵时,切回到源站,并设置回切的时长 :param request: Request instance for ModifyNetReturnSwitch. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyNetReturnSwitchRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyNetReturnSwitchResponse` """ try: params = request._serialize() body = self.call("ModifyNetReturnSwitch", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyNetReturnSwitchResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyResBindDDoSPolicy(self, request): """资源实例绑定DDoS高级策略 :param request: Request instance for ModifyResBindDDoSPolicy. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyResBindDDoSPolicyRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyResBindDDoSPolicyResponse` """ try: params = request._serialize() body = self.call("ModifyResBindDDoSPolicy", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyResBindDDoSPolicyResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message) def ModifyResourceRenewFlag(self, request): """修改资源自动续费标记 :param request: Request instance for ModifyResourceRenewFlag. :type request: :class:`tencentcloud.dayu.v20180709.models.ModifyResourceRenewFlagRequest` :rtype: :class:`tencentcloud.dayu.v20180709.models.ModifyResourceRenewFlagResponse` """ try: params = request._serialize() body = self.call("ModifyResourceRenewFlag", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyResourceRenewFlagResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
0.324128
0.055158
import os import re import sys import glob if len(sys.argv) < 2 or sys.argv[1] != 'YES!': print('CAUTION: running this will alter **ALL** .py files in every subdirectory!') print('To ensure you are certain you want to run it, call %s again with the argument "YES!"' % sys.argv[0]) sys.exit(1) re_function = re.compile(r'\n(?P<indent> *)(?P<pr>@profiler\.function)\n') re_add_note = re.compile(r'\n(?P<indent> *)(?P<pr>profiler\.add_note\(.*?\))\n') re_withcode = re.compile(r'\n(?P<indent> *)(?P<pr>with profiler\.code\(.*?\)( +as +.*?)?:)\n') re_dprint = re.compile(r'\n(?P<indent> *)(?P<dp>(Debugger\.)?dprint\(.*?\))\n') ignore_pyfiles = { 'profiler.py', 'debug.py', } ignore_folders = { '__pycache__', } def go(root): for fn in glob.glob('*.py'): if fn in ignore_pyfiles: continue f = open(fn, 'rt').read() of = str(f) while True: m = re_function.search(f) if not m: break replace = '\n%s# %s\n' % (m.group('indent'), m.group('pr')) f = f[:m.start()] + replace + f[m.end():] while True: m = re_add_note.search(f) if not m: break replace = '\n%s# %s\n' % (m.group('indent'), m.group('pr')) f = f[:m.start()] + replace + f[m.end():] while True: m = re_withcode.search(f) if not m: break replace = '\n%sif True: # %s\n' % (m.group('indent'), m.group('pr')) f = f[:m.start()] + replace + f[m.end():] while True: m = re_dprint.search(f) if not m: break replace = '\n%s# %s\n%spass\n' % (m.group('indent'), m.group('dp'), m.group('indent')) f = f[:m.start()] + replace + f[m.end():] if f == of: continue open(fn, 'wt').write(f) for fn in glob.glob('*'): if not os.path.isdir(fn): continue if fn in ignore_folders: continue os.chdir(fn) go(os.path.join(root, fn)) os.chdir('..') go('.')
addon_common/scripts/strip_debugging.py
import os import re import sys import glob if len(sys.argv) < 2 or sys.argv[1] != 'YES!': print('CAUTION: running this will alter **ALL** .py files in every subdirectory!') print('To ensure you are certain you want to run it, call %s again with the argument "YES!"' % sys.argv[0]) sys.exit(1) re_function = re.compile(r'\n(?P<indent> *)(?P<pr>@profiler\.function)\n') re_add_note = re.compile(r'\n(?P<indent> *)(?P<pr>profiler\.add_note\(.*?\))\n') re_withcode = re.compile(r'\n(?P<indent> *)(?P<pr>with profiler\.code\(.*?\)( +as +.*?)?:)\n') re_dprint = re.compile(r'\n(?P<indent> *)(?P<dp>(Debugger\.)?dprint\(.*?\))\n') ignore_pyfiles = { 'profiler.py', 'debug.py', } ignore_folders = { '__pycache__', } def go(root): for fn in glob.glob('*.py'): if fn in ignore_pyfiles: continue f = open(fn, 'rt').read() of = str(f) while True: m = re_function.search(f) if not m: break replace = '\n%s# %s\n' % (m.group('indent'), m.group('pr')) f = f[:m.start()] + replace + f[m.end():] while True: m = re_add_note.search(f) if not m: break replace = '\n%s# %s\n' % (m.group('indent'), m.group('pr')) f = f[:m.start()] + replace + f[m.end():] while True: m = re_withcode.search(f) if not m: break replace = '\n%sif True: # %s\n' % (m.group('indent'), m.group('pr')) f = f[:m.start()] + replace + f[m.end():] while True: m = re_dprint.search(f) if not m: break replace = '\n%s# %s\n%spass\n' % (m.group('indent'), m.group('dp'), m.group('indent')) f = f[:m.start()] + replace + f[m.end():] if f == of: continue open(fn, 'wt').write(f) for fn in glob.glob('*'): if not os.path.isdir(fn): continue if fn in ignore_folders: continue os.chdir(fn) go(os.path.join(root, fn)) os.chdir('..') go('.')
0.150029
0.082401
import mock from six.moves import http_client import sys from cinder import context from cinder import exception from cinder.objects import volume as obj_volume from cinder import test from cinder.tests.unit import fake_constants as fake from cinder.volume.drivers import nimble from cinder.volume import volume_types NIMBLE_CLIENT = 'cinder.volume.drivers.nimble.NimbleRestAPIExecutor' NIMBLE_URLLIB2 = 'cinder.volume.drivers.nimble.requests' NIMBLE_RANDOM = 'cinder.volume.drivers.nimble.random' NIMBLE_ISCSI_DRIVER = 'cinder.volume.drivers.nimble.NimbleISCSIDriver' NIMBLE_FC_DRIVER = 'cinder.volume.drivers.nimble.NimbleFCDriver' DRIVER_VERSION = '4.0.1' nimble.DEFAULT_SLEEP = 0 FAKE_POSITIVE_LOGIN_RESPONSE_1 = '2c20aad78a220ed1dae21dcd6f9446f5' FAKE_POSITIVE_LOGIN_RESPONSE_2 = '2c20aad78a220ed1dae21dcd6f9446ff' FAKE_POSITIVE_HEADERS = {'X-Auth-Token': FAKE_POSITIVE_LOGIN_RESPONSE_1} FAKE_POSITIVE_NETCONFIG_RESPONSE = { 'role': 'active', 'subnet_list': [{'network': '172.18.212.0', 'discovery_ip': '172.18.108.21', 'type': 'data', 'allow_iscsi': True, 'label': 'data1', 'allow_group': True, 'vlan_id': 0}], 'array_list': [{'nic_list': [{'subnet_label': 'data1', 'tagged': False, 'data_ip': '172.18.212.82', 'name': 'eth3'}]}], 'name': 'test-array'} FAKE_NEGATIVE_NETCONFIG_RESPONSE = exception.VolumeDriverException( "Session expired") FAKE_CREATE_VOLUME_POSITIVE_RESPONSE = { 'clone': False, 'name': "testvolume"} FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_ENCRYPTION = { 'clone': False, 'name': "testvolume-encryption"} FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_PERF_POLICY = { 'clone': False, 'name': "testvolume-perf-policy"} FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_MULTI_INITIATOR = { 'clone': False, 'name': "testvolume-multi-initiator"} FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_DEDUPE = { 'clone': False, 'name': "testvolume-dedupe"} FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_QOS = { 'clone': False, 'name': "testvolume-qos"} FAKE_GET_VOL_INFO_RESPONSE = {'name': 'testvolume', 'clone': False, 'target_name': 'iqn.test', 'online': True, 'agent_type': 'openstack'} FAKE_GET_VOL_INFO_RESPONSE_MANAGE = {'name': 'testvolume', 'agent_type': 'none', 'online': False, 'target_name': 'iqn.test'} FAKE_GET_VOL_INFO_ONLINE = {'name': 'testvolume', 'size': 2048, 'online': True, 'agent_type': 'none'} FAKE_GET_VOL_INFO_BACKUP_RESPONSE = {'name': 'testvolume', 'clone': True, 'target_name': 'iqn.test', 'online': False, 'agent_type': 'openstack', 'parent_vol_id': 'volume-' + fake.VOLUME2_ID, 'base_snap_id': 'test-backup-snap'} FAKE_GET_SNAP_INFO_BACKUP_RESPONSE = { 'description': "backup-vol-" + fake.VOLUME2_ID, 'name': 'test-backup-snap', 'id': fake.SNAPSHOT_ID, 'vol_id': fake.VOLUME_ID, 'volume_name': 'volume-' + fake.VOLUME_ID} FAKE_POSITIVE_GROUP_CONFIG_RESPONSE = { 'name': 'group-test', 'version_current': '0.0.0.0', 'access_protocol_list': ['iscsi']} FAKE_LOGIN_POST_RESPONSE = { 'data': {'session_token': FAKE_POSITIVE_LOGIN_RESPONSE_1}} FAKE_EXTEND_VOLUME_PARAMS = {'data': {'size': 5120, 'reserve': 0, 'warn_level': 80, 'limit': 100, 'snap_limit': sys.maxsize}} FAKE_IGROUP_LIST_RESPONSE = [ {'iscsi_initiators': [{'iqn': 'test-initiator1'}], 'name': 'test-igrp1'}, {'iscsi_initiators': [{'iqn': 'test-initiator2'}], 'name': 'test-igrp2'}] FAKE_IGROUP_LIST_RESPONSE_FC = [ {'fc_initiators': [{'wwpn': 'fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b'}], 'name': 'test-igrp1'}, {'fc_initiators': [{'wwpn': 'fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b'}, {'wwpn': 'fc00:e968:6179::de52:7100'}], 'name': 'test-igrp2'}] FAKE_CREATE_VOLUME_NEGATIVE_RESPONSE = exception.VolumeBackendAPIException( "Volume testvolume not found") FAKE_VOLUME_INFO_NEGATIVE_RESPONSE = exception.VolumeBackendAPIException( "Volume testvolume not found") FAKE_CREATE_VOLUME_NEGATIVE_ENCRYPTION = exception.VolumeBackendAPIException( "Volume testvolume-encryption not found") FAKE_CREATE_VOLUME_NEGATIVE_PERFPOLICY = exception.VolumeBackendAPIException( "Volume testvolume-perfpolicy not found") FAKE_CREATE_VOLUME_NEGATIVE_DEDUPE = exception.VolumeBackendAPIException( "The specified pool is not capable of hosting deduplicated volumes") FAKE_CREATE_VOLUME_NEGATIVE_QOS = exception.VolumeBackendAPIException( "Please set valid IOPS limitin the range [256, 4294967294]") FAKE_POSITIVE_GROUP_INFO_RESPONSE = { 'version_current': '3.0.0.0', 'group_target_enabled': False, 'name': 'group-nimble', 'usage_valid': True, 'usable_capacity_bytes': 8016883089408, 'compressed_vol_usage_bytes': 2938311843, 'compressed_snap_usage_bytes': 36189, 'unused_reserve_bytes': 0} FAKE_GENERIC_POSITIVE_RESPONSE = "" FAKE_VOLUME_DELETE_HAS_CLONE_RESPONSE = "Object has a clone" FAKE_TYPE_ID = fake.VOLUME_TYPE_ID FAKE_POOL_ID = fake.GROUP_ID FAKE_PERFORMANCE_POLICY_ID = fake.OBJECT_ID NIMBLE_MANAGEMENT_IP = "10.18.108.55" NIMBLE_SAN_LOGIN = "nimble" NIMBLE_SAN_PASS = "<PASSWORD>" def create_configuration(username, password, ip_address, pool_name=None, subnet_label=None, thin_provision=True): configuration = mock.Mock() configuration.san_login = username configuration.san_password = password configuration.san_ip = ip_address configuration.san_thin_provision = thin_provision configuration.nimble_pool_name = pool_name configuration.nimble_subnet_label = subnet_label configuration.safe_get.return_value = 'NIMBLE' return configuration class NimbleDriverBaseTestCase(test.TestCase): """Base Class for the NimbleDriver Tests.""" def setUp(self): super(NimbleDriverBaseTestCase, self).setUp() self.mock_client_service = None self.mock_client_class = None self.driver = None @staticmethod def client_mock_decorator(configuration): def client_mock_wrapper(func): def inner_client_mock( self, mock_client_class, mock_urllib2, *args, **kwargs): self.mock_client_class = mock_client_class self.mock_client_service = mock.MagicMock(name='Client') self.mock_client_class.return_value = self.mock_client_service self.driver = nimble.NimbleISCSIDriver( configuration=configuration) mock_login_response = mock_urllib2.post.return_value mock_login_response = mock.MagicMock() mock_login_response.status_code.return_value = http_client.OK mock_login_response.json.return_value = ( FAKE_LOGIN_POST_RESPONSE) self.driver.do_setup(context.get_admin_context()) self.driver.APIExecutor.login() func(self, *args, **kwargs) return inner_client_mock return client_mock_wrapper @staticmethod def client_mock_decorator_fc(configuration): def client_mock_wrapper(func): def inner_client_mock( self, mock_client_class, mock_urllib2, *args, **kwargs): self.mock_client_class = mock_client_class self.mock_client_service = mock.MagicMock(name='Client') self.mock_client_class.return_value = ( self.mock_client_service) self.driver = nimble.NimbleFCDriver( configuration=configuration) mock_login_response = mock_urllib2.post.return_value mock_login_response = mock.MagicMock() mock_login_response.status_code.return_value = http_client.OK mock_login_response.json.return_value = ( FAKE_LOGIN_POST_RESPONSE) self.driver.do_setup(context.get_admin_context()) self.driver.APIExecutor.login() func(self, *args, **kwargs) return inner_client_mock return client_mock_wrapper class NimbleDriverLoginTestCase(NimbleDriverBaseTestCase): """Tests do_setup api.""" @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( "nimble", "nimble_pass", "10.18.108.55", 'default', '*')) def test_do_setup_positive(self): expected_call_list = [mock.call.login()] self.mock_client_service.assert_has_calls(expected_call_list) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_expire_session_id(self): expected_call_list = [mock.call.login()] self.mock_client_service.assert_has_calls(expected_call_list) self.driver.APIExecutor.get("groups") expected_call_list = [mock.call.get_group_info(), mock.call.login(), mock.call.get("groups")] self.assertEqual( self.mock_client_service.method_calls, expected_call_list) class NimbleDriverVolumeTestCase(NimbleDriverBaseTestCase): """Tests volume related api's.""" @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'yes'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( NIMBLE_SAN_LOGIN, NIMBLE_SAN_PASS, NIMBLE_MANAGEMENT_IP, 'default', '*')) def test_create_volume_positive(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''}, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'yes'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( NIMBLE_SAN_LOGIN, NIMBLE_SAN_PASS, NIMBLE_MANAGEMENT_IP, 'default', '*')) def test_create_volume_with_unicode(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume', 'size': 1, 'volume_type_id': None, 'display_name': u'unicode_name', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume', 'size': 1, 'volume_type_id': None, 'display_name': u'unicode_name', 'display_description': ''}, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'yes', 'nimble:multi-initiator': 'false'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_encryption_positive(self): self.mock_client_service._execute_create_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_ENCRYPTION) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) volume = {'name': 'testvolume-encryption', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''} self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume(volume)) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume-encryption', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': '', }, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'VMware ESX', 'nimble:encryption': 'no', 'nimble:multi-initiator': 'false'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_perfpolicy_positive(self): self.mock_client_service._execute_create_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_PERF_POLICY) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual( {'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume-perfpolicy', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume-perfpolicy', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': '', }, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'no', 'nimble:multi-initiator': 'true'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_multi_initiator_positive(self): self.mock_client_service._execute_create_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_MULTI_INITIATOR) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual( {'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume-multi-initiator', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume-multi-initiator', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': '', }, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'no', 'nimble:dedupe': 'true'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_dedupe_positive(self): self.mock_client_service._execute_create_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_DEDUPE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual( {'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume-dedupe', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume-dedupe', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': '', }, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:iops-limit': '1024'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_qos_positive(self): self.mock_client_service._execute_create_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_QOS) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual( {'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume-qos', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume-qos', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': '', }, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'no', 'nimble:multi-initiator': 'true'})) def test_create_volume_negative(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_CREATE_VOLUME_NEGATIVE_RESPONSE) self.assertRaises( exception.VolumeBackendAPIException, self.driver.create_volume, {'name': 'testvolume', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_encryption_negative(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_CREATE_VOLUME_NEGATIVE_ENCRYPTION) self.assertRaises( exception.VolumeBackendAPIException, self.driver.create_volume, {'name': 'testvolume-encryption', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_perfpolicy_negative(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_CREATE_VOLUME_NEGATIVE_PERFPOLICY) self.assertRaises( exception.VolumeBackendAPIException, self.driver.create_volume, {'name': 'testvolume-perfpolicy', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_dedupe_negative(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_CREATE_VOLUME_NEGATIVE_DEDUPE) self.assertRaises( exception.VolumeBackendAPIException, self.driver.create_volume, {'name': 'testvolume-dedupe', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:iops-limit': '200'})) def test_create_volume_qos_negative(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_CREATE_VOLUME_NEGATIVE_QOS) self.assertRaises( exception.VolumeBackendAPIException, self.driver.create_volume, {'name': 'testvolume-qos', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_ISCSI_DRIVER + ".is_volume_backup_clone", mock.Mock( return_value = ['', ''])) def test_delete_volume(self): self.mock_client_service.online_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.delete_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.driver.delete_volume({'name': 'testvolume'}) expected_calls = [mock.call.online_vol( 'testvolume', False), mock.call.delete_vol('testvolume')] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_ISCSI_DRIVER + ".is_volume_backup_clone", mock.Mock( return_value = ['', ''])) def test_delete_volume_with_clone(self): self.mock_client_service.delete_vol.side_effect = \ nimble.NimbleAPIException(FAKE_VOLUME_DELETE_HAS_CLONE_RESPONSE) self.assertRaises( exception.VolumeIsBusy, self.driver.delete_volume, {'name': 'testvolume'}) expected_calls = [mock.call.online_vol( 'testvolume', False), mock.call.delete_vol('testvolume'), mock.call.online_vol('testvolume', True)] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_ISCSI_DRIVER + ".is_volume_backup_clone", mock.Mock( return_value=['test-backup-snap', 'volume-' + fake.VOLUME_ID])) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host') def test_delete_volume_with_backup(self, mock_volume_list): mock_volume_list.return_value = [] self.mock_client_service.online_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.delete_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.online_snap.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.delete_snap.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.driver.delete_volume({'name': 'testvolume'}) expected_calls = [mock.call.online_vol( 'testvolume', False), mock.call.delete_vol('testvolume'), mock.call.online_snap('volume-' + fake.VOLUME_ID, False, 'test-backup-snap'), mock.call.delete_snap('volume-' + fake.VOLUME_ID, 'test-backup-snap')] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_extend_volume(self): self.mock_client_service.edit_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE) self.driver.extend_volume({'name': 'testvolume'}, 5) self.mock_client_service.edit_vol.assert_called_once_with( 'testvolume', FAKE_EXTEND_VOLUME_PARAMS) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value= {'nimble:perfpol-name': 'default', 'nimble:encryption': 'yes', 'nimble:multi-initiator': 'false', 'nimble:iops-limit': '1024'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*', False)) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host') @mock.patch(NIMBLE_RANDOM) def test_create_cloned_volume(self, mock_random, mock_volume_list): mock_random.sample.return_value = fake.VOLUME_ID mock_volume_list.return_value = [] self.mock_client_service.snap_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.clone_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) volume = obj_volume.Volume(context.get_admin_context(), id=fake.VOLUME_ID, size=5.0, _name_id=None, display_name='', volume_type_id=FAKE_TYPE_ID ) src_volume = obj_volume.Volume(context.get_admin_context(), id=fake.VOLUME2_ID, _name_id=None, size=5.0) self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_cloned_volume(volume, src_volume)) expected_calls = [mock.call.snap_vol( {'volume_name': "volume-" + fake.VOLUME2_ID, 'name': 'openstack-clone-volume-' + fake.VOLUME_ID + "-" + fake.VOLUME_ID, 'volume_size': src_volume['size'], 'display_name': volume['display_name'], 'display_description': ''}), mock.call.clone_vol(volume, {'volume_name': "volume-" + fake.VOLUME2_ID, 'name': 'openstack-clone-volume-' + fake.VOLUME_ID + "-" + fake.VOLUME_ID, 'volume_size': src_volume['size'], 'display_name': volume['display_name'], 'display_description': ''}, True, False, 'iSCSI', 'default')] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_positive(self): self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE_MANAGE) self.mock_client_service.online_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.edit_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE) self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.manage_existing({'name': 'volume-abcdef', 'id': fake.VOLUME_ID, 'agent_type': None}, {'source-name': 'test-vol'})) expected_calls = [mock.call.edit_vol( 'test-vol', {'data': {'agent_type': 'openstack', 'name': 'volume-abcdef'}}), mock.call.online_vol('volume-abcdef', True)] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_which_is_online(self): self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_ONLINE) self.assertRaises( exception.InvalidVolume, self.driver.manage_existing, {'name': 'volume-abcdef'}, {'source-name': 'test-vol'}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_get_size(self): self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_ONLINE) size = self.driver.manage_existing_get_size( {'name': 'volume-abcdef'}, {'source-name': 'test-vol'}) self.assertEqual(2, size) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_with_improper_ref(self): self.assertRaises( exception.ManageExistingInvalidReference, self.driver.manage_existing, {'name': 'volume-abcdef'}, {'source-id': 'test-vol'}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_with_nonexistant_volume(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_VOLUME_INFO_NEGATIVE_RESPONSE) self.assertRaises( exception.VolumeBackendAPIException, self.driver.manage_existing, {'name': 'volume-abcdef'}, {'source-name': 'test-vol'}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_with_wrong_agent_type(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.assertRaises( exception.ManageExistingAlreadyManaged, self.driver.manage_existing, {'id': 'abcdef', 'name': 'volume-abcdef'}, {'source-name': 'test-vol'}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_unmanage_volume_positive(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.edit_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE) self.driver.unmanage({'name': 'volume-abcdef'}) expected_calls = [ mock.call.edit_vol( 'volume-abcdef', {'data': {'agent_type': 'none'}}), mock.call.online_vol('volume-abcdef', False)] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_unmanage_with_invalid_volume(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_VOLUME_INFO_NEGATIVE_RESPONSE) self.assertRaises( exception.VolumeBackendAPIException, self.driver.unmanage, {'name': 'volume-abcdef'} ) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_unmanage_with_invalid_agent_type(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_ONLINE) self.assertRaises( exception.InvalidVolume, self.driver.unmanage, {'name': 'volume-abcdef'} ) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_get_volume_stats(self): self.mock_client_service.get_group_info.return_value = ( FAKE_POSITIVE_GROUP_INFO_RESPONSE) expected_res = {'driver_version': DRIVER_VERSION, 'vendor_name': 'Nimble', 'volume_backend_name': 'NIMBLE', 'storage_protocol': 'iSCSI', 'pools': [{'pool_name': 'NIMBLE', 'total_capacity_gb': 7466.30419921875, 'free_capacity_gb': 7463.567649364471, 'reserved_percentage': 0, 'QoS_support': False}]} self.assertEqual( expected_res, self.driver.get_volume_stats(refresh=True)) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_is_volume_backup_clone(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_BACKUP_RESPONSE) self.mock_client_service.get_snap_info_by_id.return_value = ( FAKE_GET_SNAP_INFO_BACKUP_RESPONSE) self.mock_client_service.get_snap_info_detail.return_value = ( FAKE_GET_SNAP_INFO_BACKUP_RESPONSE) self.mock_client_service.get_volume_name.return_value = ( 'volume-' + fake.VOLUME2_ID) volume = obj_volume.Volume(context.get_admin_context(), id=fake.VOLUME_ID, _name_id=None) self.assertEqual(("test-backup-snap", "volume-" + fake.VOLUME2_ID), self.driver.is_volume_backup_clone(volume)) expected_calls = [ mock.call.get_vol_info('volume-' + fake.VOLUME_ID), mock.call.get_snap_info_by_id('test-backup-snap', 'volume-' + fake.VOLUME2_ID) ] self.mock_client_service.assert_has_calls(expected_calls) class NimbleDriverSnapshotTestCase(NimbleDriverBaseTestCase): """Tests snapshot related api's.""" @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_snapshot(self): self.mock_client_service.snap_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.driver.create_snapshot( {'volume_name': 'testvolume', 'name': 'testvolume-snap1', 'display_name': ''}) self.mock_client_service.snap_vol.assert_called_once_with( {'volume_name': 'testvolume', 'name': 'testvolume-snap1', 'display_name': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_delete_snapshot(self): self.mock_client_service.online_snap.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.delete_snap.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.driver.delete_snapshot( {'volume_name': 'testvolume', 'name': 'testvolume-snap1'}) expected_calls = [mock.call.online_snap( 'testvolume', False, 'testvolume-snap1'), mock.call.delete_snap('testvolume', 'testvolume-snap1')] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'yes', 'nimble:multi-initiator': 'false'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_from_snapshot(self): self.mock_client_service.clone_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume_from_snapshot( {'name': 'clone-testvolume', 'size': 2, 'volume_type_id': FAKE_TYPE_ID}, {'volume_name': 'testvolume', 'name': 'testvolume-snap1', 'volume_size': 1})) expected_calls = [ mock.call.clone_vol( {'name': 'clone-testvolume', 'volume_type_id': FAKE_TYPE_ID, 'size': 2}, {'volume_name': 'testvolume', 'name': 'testvolume-snap1', 'volume_size': 1}, False, False, 'iSCSI', 'default'), mock.call.edit_vol('clone-testvolume', {'data': {'size': 2048, 'snap_limit': sys.maxsize, 'warn_level': 80, 'reserve': 0, 'limit': 100}})] self.mock_client_service.assert_has_calls(expected_calls) class NimbleDriverConnectionTestCase(NimbleDriverBaseTestCase): """Tests Connection related api's.""" @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_initialize_connection_igroup_exist(self): self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE) expected_res = { 'driver_volume_type': 'iscsi', 'data': { 'volume_id': 12, 'target_iqn': '13', 'target_lun': 0, 'target_portal': '12'}} self.assertEqual( expected_res, self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator1'})) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_initialize_connection_live_migration(self): self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE) expected_res = { 'driver_volume_type': 'iscsi', 'data': { 'volume_id': 12, 'target_iqn': '13', 'target_lun': 0, 'target_portal': '12'}} self.assertEqual( expected_res, self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator1'})) self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator1'}) # 2 or more calls to initialize connection and add_acl for live # migration to work expected_calls = [ mock.call.get_initiator_grp_list(), mock.call.add_acl({'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, 'test-igrp1'), mock.call.get_initiator_grp_list(), mock.call.add_acl({'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, 'test-igrp1')] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator_fc(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_FC_DRIVER + ".get_lun_number") @mock.patch(NIMBLE_FC_DRIVER + ".get_wwpns_from_array") def test_initialize_connection_fc_igroup_exist(self, mock_wwpns, mock_lun_number): mock_lun_number.return_value = 13 mock_wwpns.return_value = ["1111111111111101"] self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE_FC) expected_res = { 'driver_volume_type': 'fibre_channel', 'data': { 'target_lun': 13, 'target_discovered': True, 'target_wwn': ["1111111111111101"], 'initiator_target_map': {'1000000000000000': ['1111111111111101']}}} self.assertEqual( expected_res, self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': 'array1', 'id': 12}, {'initiator': 'test-initiator1', 'wwpns': ['1000000000000000']})) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_RANDOM) def test_initialize_connection_igroup_not_exist(self, mock_random): mock_random.sample.return_value = 'abcdefghijkl' self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE) expected_res = { 'driver_volume_type': 'iscsi', 'data': { 'target_lun': 0, 'volume_id': 12, 'target_iqn': '13', 'target_portal': '12'}} self.assertEqual( expected_res, self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator3'})) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator_fc(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_FC_DRIVER + ".get_wwpns_from_array") @mock.patch(NIMBLE_FC_DRIVER + ".get_lun_number") @mock.patch(NIMBLE_RANDOM) def test_initialize_connection_fc_igroup_not_exist(self, mock_random, mock_lun_number, mock_wwpns): mock_random.sample.return_value = 'abcdefghijkl' mock_lun_number.return_value = 13 mock_wwpns.return_value = ["1111111111111101"] self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE_FC) expected_res = { 'driver_volume_type': 'fibre_channel', 'data': { 'target_lun': 13, 'target_discovered': True, 'target_wwn': ["1111111111111101"], 'initiator_target_map': {'1000000000000000': ['1111111111111101']}}} self.driver._create_igroup_for_initiator("test-initiator3", [1111111111111101]) self.assertEqual( expected_res, self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': 'array1', 'id': 12}, {'initiator': 'test-initiator3', 'wwpns': ['1000000000000000']})) expected_calls = [mock.call.create_initiator_group_fc( 'openstack-abcdefghijkl'), mock.call.add_initiator_to_igroup_fc('openstack-abcdefghijkl', 1111111111111101)] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_terminate_connection_positive(self): self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE) self.driver.terminate_connection( {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator1'}) expected_calls = [mock.call._get_igroupname_for_initiator( 'test-initiator1'), mock.call.remove_acl({'name': 'test-volume'}, 'test-igrp1')] self.mock_client_service.assert_has_calls( self.mock_client_service.method_calls, expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator_fc(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_FC_DRIVER + ".get_wwpns_from_array") def test_terminate_connection_positive_fc(self, mock_wwpns): mock_wwpns.return_value = ["1111111111111101"] self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE_FC) self.driver.terminate_connection( {'name': 'test-volume', 'provider_location': 'array1', 'id': 12}, {'initiator': 'test-initiator1', 'wwpns': ['1000000000000000']}) expected_calls = [ mock.call.get_igroupname_for_initiator_fc( "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"), mock.call.remove_acl({'name': 'test-volume'}, 'test-igrp1')] self.mock_client_service.assert_has_calls( self.mock_client_service.method_calls, expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_terminate_connection_negative(self): self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE) self.assertRaises( exception.VolumeDriverException, self.driver.terminate_connection, {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator3'})
cinder/tests/unit/volume/drivers/test_nimble.py
import mock from six.moves import http_client import sys from cinder import context from cinder import exception from cinder.objects import volume as obj_volume from cinder import test from cinder.tests.unit import fake_constants as fake from cinder.volume.drivers import nimble from cinder.volume import volume_types NIMBLE_CLIENT = 'cinder.volume.drivers.nimble.NimbleRestAPIExecutor' NIMBLE_URLLIB2 = 'cinder.volume.drivers.nimble.requests' NIMBLE_RANDOM = 'cinder.volume.drivers.nimble.random' NIMBLE_ISCSI_DRIVER = 'cinder.volume.drivers.nimble.NimbleISCSIDriver' NIMBLE_FC_DRIVER = 'cinder.volume.drivers.nimble.NimbleFCDriver' DRIVER_VERSION = '4.0.1' nimble.DEFAULT_SLEEP = 0 FAKE_POSITIVE_LOGIN_RESPONSE_1 = '2c20aad78a220ed1dae21dcd6f9446f5' FAKE_POSITIVE_LOGIN_RESPONSE_2 = '2c20aad78a220ed1dae21dcd6f9446ff' FAKE_POSITIVE_HEADERS = {'X-Auth-Token': FAKE_POSITIVE_LOGIN_RESPONSE_1} FAKE_POSITIVE_NETCONFIG_RESPONSE = { 'role': 'active', 'subnet_list': [{'network': '172.18.212.0', 'discovery_ip': '172.18.108.21', 'type': 'data', 'allow_iscsi': True, 'label': 'data1', 'allow_group': True, 'vlan_id': 0}], 'array_list': [{'nic_list': [{'subnet_label': 'data1', 'tagged': False, 'data_ip': '172.18.212.82', 'name': 'eth3'}]}], 'name': 'test-array'} FAKE_NEGATIVE_NETCONFIG_RESPONSE = exception.VolumeDriverException( "Session expired") FAKE_CREATE_VOLUME_POSITIVE_RESPONSE = { 'clone': False, 'name': "testvolume"} FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_ENCRYPTION = { 'clone': False, 'name': "testvolume-encryption"} FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_PERF_POLICY = { 'clone': False, 'name': "testvolume-perf-policy"} FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_MULTI_INITIATOR = { 'clone': False, 'name': "testvolume-multi-initiator"} FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_DEDUPE = { 'clone': False, 'name': "testvolume-dedupe"} FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_QOS = { 'clone': False, 'name': "testvolume-qos"} FAKE_GET_VOL_INFO_RESPONSE = {'name': 'testvolume', 'clone': False, 'target_name': 'iqn.test', 'online': True, 'agent_type': 'openstack'} FAKE_GET_VOL_INFO_RESPONSE_MANAGE = {'name': 'testvolume', 'agent_type': 'none', 'online': False, 'target_name': 'iqn.test'} FAKE_GET_VOL_INFO_ONLINE = {'name': 'testvolume', 'size': 2048, 'online': True, 'agent_type': 'none'} FAKE_GET_VOL_INFO_BACKUP_RESPONSE = {'name': 'testvolume', 'clone': True, 'target_name': 'iqn.test', 'online': False, 'agent_type': 'openstack', 'parent_vol_id': 'volume-' + fake.VOLUME2_ID, 'base_snap_id': 'test-backup-snap'} FAKE_GET_SNAP_INFO_BACKUP_RESPONSE = { 'description': "backup-vol-" + fake.VOLUME2_ID, 'name': 'test-backup-snap', 'id': fake.SNAPSHOT_ID, 'vol_id': fake.VOLUME_ID, 'volume_name': 'volume-' + fake.VOLUME_ID} FAKE_POSITIVE_GROUP_CONFIG_RESPONSE = { 'name': 'group-test', 'version_current': '0.0.0.0', 'access_protocol_list': ['iscsi']} FAKE_LOGIN_POST_RESPONSE = { 'data': {'session_token': FAKE_POSITIVE_LOGIN_RESPONSE_1}} FAKE_EXTEND_VOLUME_PARAMS = {'data': {'size': 5120, 'reserve': 0, 'warn_level': 80, 'limit': 100, 'snap_limit': sys.maxsize}} FAKE_IGROUP_LIST_RESPONSE = [ {'iscsi_initiators': [{'iqn': 'test-initiator1'}], 'name': 'test-igrp1'}, {'iscsi_initiators': [{'iqn': 'test-initiator2'}], 'name': 'test-igrp2'}] FAKE_IGROUP_LIST_RESPONSE_FC = [ {'fc_initiators': [{'wwpn': 'fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b'}], 'name': 'test-igrp1'}, {'fc_initiators': [{'wwpn': 'fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b'}, {'wwpn': 'fc00:e968:6179::de52:7100'}], 'name': 'test-igrp2'}] FAKE_CREATE_VOLUME_NEGATIVE_RESPONSE = exception.VolumeBackendAPIException( "Volume testvolume not found") FAKE_VOLUME_INFO_NEGATIVE_RESPONSE = exception.VolumeBackendAPIException( "Volume testvolume not found") FAKE_CREATE_VOLUME_NEGATIVE_ENCRYPTION = exception.VolumeBackendAPIException( "Volume testvolume-encryption not found") FAKE_CREATE_VOLUME_NEGATIVE_PERFPOLICY = exception.VolumeBackendAPIException( "Volume testvolume-perfpolicy not found") FAKE_CREATE_VOLUME_NEGATIVE_DEDUPE = exception.VolumeBackendAPIException( "The specified pool is not capable of hosting deduplicated volumes") FAKE_CREATE_VOLUME_NEGATIVE_QOS = exception.VolumeBackendAPIException( "Please set valid IOPS limitin the range [256, 4294967294]") FAKE_POSITIVE_GROUP_INFO_RESPONSE = { 'version_current': '3.0.0.0', 'group_target_enabled': False, 'name': 'group-nimble', 'usage_valid': True, 'usable_capacity_bytes': 8016883089408, 'compressed_vol_usage_bytes': 2938311843, 'compressed_snap_usage_bytes': 36189, 'unused_reserve_bytes': 0} FAKE_GENERIC_POSITIVE_RESPONSE = "" FAKE_VOLUME_DELETE_HAS_CLONE_RESPONSE = "Object has a clone" FAKE_TYPE_ID = fake.VOLUME_TYPE_ID FAKE_POOL_ID = fake.GROUP_ID FAKE_PERFORMANCE_POLICY_ID = fake.OBJECT_ID NIMBLE_MANAGEMENT_IP = "10.18.108.55" NIMBLE_SAN_LOGIN = "nimble" NIMBLE_SAN_PASS = "<PASSWORD>" def create_configuration(username, password, ip_address, pool_name=None, subnet_label=None, thin_provision=True): configuration = mock.Mock() configuration.san_login = username configuration.san_password = password configuration.san_ip = ip_address configuration.san_thin_provision = thin_provision configuration.nimble_pool_name = pool_name configuration.nimble_subnet_label = subnet_label configuration.safe_get.return_value = 'NIMBLE' return configuration class NimbleDriverBaseTestCase(test.TestCase): """Base Class for the NimbleDriver Tests.""" def setUp(self): super(NimbleDriverBaseTestCase, self).setUp() self.mock_client_service = None self.mock_client_class = None self.driver = None @staticmethod def client_mock_decorator(configuration): def client_mock_wrapper(func): def inner_client_mock( self, mock_client_class, mock_urllib2, *args, **kwargs): self.mock_client_class = mock_client_class self.mock_client_service = mock.MagicMock(name='Client') self.mock_client_class.return_value = self.mock_client_service self.driver = nimble.NimbleISCSIDriver( configuration=configuration) mock_login_response = mock_urllib2.post.return_value mock_login_response = mock.MagicMock() mock_login_response.status_code.return_value = http_client.OK mock_login_response.json.return_value = ( FAKE_LOGIN_POST_RESPONSE) self.driver.do_setup(context.get_admin_context()) self.driver.APIExecutor.login() func(self, *args, **kwargs) return inner_client_mock return client_mock_wrapper @staticmethod def client_mock_decorator_fc(configuration): def client_mock_wrapper(func): def inner_client_mock( self, mock_client_class, mock_urllib2, *args, **kwargs): self.mock_client_class = mock_client_class self.mock_client_service = mock.MagicMock(name='Client') self.mock_client_class.return_value = ( self.mock_client_service) self.driver = nimble.NimbleFCDriver( configuration=configuration) mock_login_response = mock_urllib2.post.return_value mock_login_response = mock.MagicMock() mock_login_response.status_code.return_value = http_client.OK mock_login_response.json.return_value = ( FAKE_LOGIN_POST_RESPONSE) self.driver.do_setup(context.get_admin_context()) self.driver.APIExecutor.login() func(self, *args, **kwargs) return inner_client_mock return client_mock_wrapper class NimbleDriverLoginTestCase(NimbleDriverBaseTestCase): """Tests do_setup api.""" @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( "nimble", "nimble_pass", "10.18.108.55", 'default', '*')) def test_do_setup_positive(self): expected_call_list = [mock.call.login()] self.mock_client_service.assert_has_calls(expected_call_list) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_expire_session_id(self): expected_call_list = [mock.call.login()] self.mock_client_service.assert_has_calls(expected_call_list) self.driver.APIExecutor.get("groups") expected_call_list = [mock.call.get_group_info(), mock.call.login(), mock.call.get("groups")] self.assertEqual( self.mock_client_service.method_calls, expected_call_list) class NimbleDriverVolumeTestCase(NimbleDriverBaseTestCase): """Tests volume related api's.""" @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'yes'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( NIMBLE_SAN_LOGIN, NIMBLE_SAN_PASS, NIMBLE_MANAGEMENT_IP, 'default', '*')) def test_create_volume_positive(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''}, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'yes'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( NIMBLE_SAN_LOGIN, NIMBLE_SAN_PASS, NIMBLE_MANAGEMENT_IP, 'default', '*')) def test_create_volume_with_unicode(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume', 'size': 1, 'volume_type_id': None, 'display_name': u'unicode_name', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume', 'size': 1, 'volume_type_id': None, 'display_name': u'unicode_name', 'display_description': ''}, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'yes', 'nimble:multi-initiator': 'false'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_encryption_positive(self): self.mock_client_service._execute_create_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_ENCRYPTION) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) volume = {'name': 'testvolume-encryption', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''} self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume(volume)) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume-encryption', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': '', }, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'VMware ESX', 'nimble:encryption': 'no', 'nimble:multi-initiator': 'false'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_perfpolicy_positive(self): self.mock_client_service._execute_create_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_PERF_POLICY) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual( {'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume-perfpolicy', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume-perfpolicy', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': '', }, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'no', 'nimble:multi-initiator': 'true'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_multi_initiator_positive(self): self.mock_client_service._execute_create_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_MULTI_INITIATOR) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual( {'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume-multi-initiator', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume-multi-initiator', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': '', }, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'no', 'nimble:dedupe': 'true'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_dedupe_positive(self): self.mock_client_service._execute_create_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_DEDUPE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual( {'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume-dedupe', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume-dedupe', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': '', }, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:iops-limit': '1024'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_qos_positive(self): self.mock_client_service._execute_create_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE_QOS) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual( {'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume({'name': 'testvolume-qos', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''})) self.mock_client_service.create_vol.assert_called_once_with( {'name': 'testvolume-qos', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': '', }, 'default', False, 'iSCSI', False) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'no', 'nimble:multi-initiator': 'true'})) def test_create_volume_negative(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_CREATE_VOLUME_NEGATIVE_RESPONSE) self.assertRaises( exception.VolumeBackendAPIException, self.driver.create_volume, {'name': 'testvolume', 'size': 1, 'volume_type_id': FAKE_TYPE_ID, 'display_name': '', 'display_description': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_encryption_negative(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_CREATE_VOLUME_NEGATIVE_ENCRYPTION) self.assertRaises( exception.VolumeBackendAPIException, self.driver.create_volume, {'name': 'testvolume-encryption', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_perfpolicy_negative(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_CREATE_VOLUME_NEGATIVE_PERFPOLICY) self.assertRaises( exception.VolumeBackendAPIException, self.driver.create_volume, {'name': 'testvolume-perfpolicy', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_dedupe_negative(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_CREATE_VOLUME_NEGATIVE_DEDUPE) self.assertRaises( exception.VolumeBackendAPIException, self.driver.create_volume, {'name': 'testvolume-dedupe', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:iops-limit': '200'})) def test_create_volume_qos_negative(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_CREATE_VOLUME_NEGATIVE_QOS) self.assertRaises( exception.VolumeBackendAPIException, self.driver.create_volume, {'name': 'testvolume-qos', 'size': 1, 'volume_type_id': None, 'display_name': '', 'display_description': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_ISCSI_DRIVER + ".is_volume_backup_clone", mock.Mock( return_value = ['', ''])) def test_delete_volume(self): self.mock_client_service.online_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.delete_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.driver.delete_volume({'name': 'testvolume'}) expected_calls = [mock.call.online_vol( 'testvolume', False), mock.call.delete_vol('testvolume')] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_ISCSI_DRIVER + ".is_volume_backup_clone", mock.Mock( return_value = ['', ''])) def test_delete_volume_with_clone(self): self.mock_client_service.delete_vol.side_effect = \ nimble.NimbleAPIException(FAKE_VOLUME_DELETE_HAS_CLONE_RESPONSE) self.assertRaises( exception.VolumeIsBusy, self.driver.delete_volume, {'name': 'testvolume'}) expected_calls = [mock.call.online_vol( 'testvolume', False), mock.call.delete_vol('testvolume'), mock.call.online_vol('testvolume', True)] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_ISCSI_DRIVER + ".is_volume_backup_clone", mock.Mock( return_value=['test-backup-snap', 'volume-' + fake.VOLUME_ID])) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host') def test_delete_volume_with_backup(self, mock_volume_list): mock_volume_list.return_value = [] self.mock_client_service.online_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.delete_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.online_snap.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.delete_snap.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.driver.delete_volume({'name': 'testvolume'}) expected_calls = [mock.call.online_vol( 'testvolume', False), mock.call.delete_vol('testvolume'), mock.call.online_snap('volume-' + fake.VOLUME_ID, False, 'test-backup-snap'), mock.call.delete_snap('volume-' + fake.VOLUME_ID, 'test-backup-snap')] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_extend_volume(self): self.mock_client_service.edit_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE) self.driver.extend_volume({'name': 'testvolume'}, 5) self.mock_client_service.edit_vol.assert_called_once_with( 'testvolume', FAKE_EXTEND_VOLUME_PARAMS) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value= {'nimble:perfpol-name': 'default', 'nimble:encryption': 'yes', 'nimble:multi-initiator': 'false', 'nimble:iops-limit': '1024'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*', False)) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host') @mock.patch(NIMBLE_RANDOM) def test_create_cloned_volume(self, mock_random, mock_volume_list): mock_random.sample.return_value = fake.VOLUME_ID mock_volume_list.return_value = [] self.mock_client_service.snap_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.clone_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) volume = obj_volume.Volume(context.get_admin_context(), id=fake.VOLUME_ID, size=5.0, _name_id=None, display_name='', volume_type_id=FAKE_TYPE_ID ) src_volume = obj_volume.Volume(context.get_admin_context(), id=fake.VOLUME2_ID, _name_id=None, size=5.0) self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_cloned_volume(volume, src_volume)) expected_calls = [mock.call.snap_vol( {'volume_name': "volume-" + fake.VOLUME2_ID, 'name': 'openstack-clone-volume-' + fake.VOLUME_ID + "-" + fake.VOLUME_ID, 'volume_size': src_volume['size'], 'display_name': volume['display_name'], 'display_description': ''}), mock.call.clone_vol(volume, {'volume_name': "volume-" + fake.VOLUME2_ID, 'name': 'openstack-clone-volume-' + fake.VOLUME_ID + "-" + fake.VOLUME_ID, 'volume_size': src_volume['size'], 'display_name': volume['display_name'], 'display_description': ''}, True, False, 'iSCSI', 'default')] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_positive(self): self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE_MANAGE) self.mock_client_service.online_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.edit_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE) self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.manage_existing({'name': 'volume-abcdef', 'id': fake.VOLUME_ID, 'agent_type': None}, {'source-name': 'test-vol'})) expected_calls = [mock.call.edit_vol( 'test-vol', {'data': {'agent_type': 'openstack', 'name': 'volume-abcdef'}}), mock.call.online_vol('volume-abcdef', True)] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_which_is_online(self): self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_ONLINE) self.assertRaises( exception.InvalidVolume, self.driver.manage_existing, {'name': 'volume-abcdef'}, {'source-name': 'test-vol'}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_get_size(self): self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_ONLINE) size = self.driver.manage_existing_get_size( {'name': 'volume-abcdef'}, {'source-name': 'test-vol'}) self.assertEqual(2, size) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_with_improper_ref(self): self.assertRaises( exception.ManageExistingInvalidReference, self.driver.manage_existing, {'name': 'volume-abcdef'}, {'source-id': 'test-vol'}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_with_nonexistant_volume(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_VOLUME_INFO_NEGATIVE_RESPONSE) self.assertRaises( exception.VolumeBackendAPIException, self.driver.manage_existing, {'name': 'volume-abcdef'}, {'source-name': 'test-vol'}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_manage_volume_with_wrong_agent_type(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.assertRaises( exception.ManageExistingAlreadyManaged, self.driver.manage_existing, {'id': 'abcdef', 'name': 'volume-abcdef'}, {'source-name': 'test-vol'}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_unmanage_volume_positive(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.edit_vol.return_value = ( FAKE_CREATE_VOLUME_POSITIVE_RESPONSE) self.driver.unmanage({'name': 'volume-abcdef'}) expected_calls = [ mock.call.edit_vol( 'volume-abcdef', {'data': {'agent_type': 'none'}}), mock.call.online_vol('volume-abcdef', False)] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_unmanage_with_invalid_volume(self): self.mock_client_service.get_vol_info.side_effect = ( FAKE_VOLUME_INFO_NEGATIVE_RESPONSE) self.assertRaises( exception.VolumeBackendAPIException, self.driver.unmanage, {'name': 'volume-abcdef'} ) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_unmanage_with_invalid_agent_type(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_ONLINE) self.assertRaises( exception.InvalidVolume, self.driver.unmanage, {'name': 'volume-abcdef'} ) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_get_volume_stats(self): self.mock_client_service.get_group_info.return_value = ( FAKE_POSITIVE_GROUP_INFO_RESPONSE) expected_res = {'driver_version': DRIVER_VERSION, 'vendor_name': 'Nimble', 'volume_backend_name': 'NIMBLE', 'storage_protocol': 'iSCSI', 'pools': [{'pool_name': 'NIMBLE', 'total_capacity_gb': 7466.30419921875, 'free_capacity_gb': 7463.567649364471, 'reserved_percentage': 0, 'QoS_support': False}]} self.assertEqual( expected_res, self.driver.get_volume_stats(refresh=True)) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_is_volume_backup_clone(self): self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_BACKUP_RESPONSE) self.mock_client_service.get_snap_info_by_id.return_value = ( FAKE_GET_SNAP_INFO_BACKUP_RESPONSE) self.mock_client_service.get_snap_info_detail.return_value = ( FAKE_GET_SNAP_INFO_BACKUP_RESPONSE) self.mock_client_service.get_volume_name.return_value = ( 'volume-' + fake.VOLUME2_ID) volume = obj_volume.Volume(context.get_admin_context(), id=fake.VOLUME_ID, _name_id=None) self.assertEqual(("test-backup-snap", "volume-" + fake.VOLUME2_ID), self.driver.is_volume_backup_clone(volume)) expected_calls = [ mock.call.get_vol_info('volume-' + fake.VOLUME_ID), mock.call.get_snap_info_by_id('test-backup-snap', 'volume-' + fake.VOLUME2_ID) ] self.mock_client_service.assert_has_calls(expected_calls) class NimbleDriverSnapshotTestCase(NimbleDriverBaseTestCase): """Tests snapshot related api's.""" @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_snapshot(self): self.mock_client_service.snap_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.driver.create_snapshot( {'volume_name': 'testvolume', 'name': 'testvolume-snap1', 'display_name': ''}) self.mock_client_service.snap_vol.assert_called_once_with( {'volume_name': 'testvolume', 'name': 'testvolume-snap1', 'display_name': ''}) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_delete_snapshot(self): self.mock_client_service.online_snap.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.delete_snap.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.driver.delete_snapshot( {'volume_name': 'testvolume', 'name': 'testvolume-snap1'}) expected_calls = [mock.call.online_snap( 'testvolume', False, 'testvolume-snap1'), mock.call.delete_snap('testvolume', 'testvolume-snap1')] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @mock.patch.object(volume_types, 'get_volume_type_extra_specs', mock.Mock(type_id=FAKE_TYPE_ID, return_value={ 'nimble:perfpol-name': 'default', 'nimble:encryption': 'yes', 'nimble:multi-initiator': 'false'})) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_create_volume_from_snapshot(self): self.mock_client_service.clone_vol.return_value = ( FAKE_GENERIC_POSITIVE_RESPONSE) self.mock_client_service.get_vol_info.return_value = ( FAKE_GET_VOL_INFO_RESPONSE) self.mock_client_service.get_netconfig.return_value = ( FAKE_POSITIVE_NETCONFIG_RESPONSE) self.assertEqual({ 'provider_location': '172.18.108.21:3260 iqn.test', 'provider_auth': None}, self.driver.create_volume_from_snapshot( {'name': 'clone-testvolume', 'size': 2, 'volume_type_id': FAKE_TYPE_ID}, {'volume_name': 'testvolume', 'name': 'testvolume-snap1', 'volume_size': 1})) expected_calls = [ mock.call.clone_vol( {'name': 'clone-testvolume', 'volume_type_id': FAKE_TYPE_ID, 'size': 2}, {'volume_name': 'testvolume', 'name': 'testvolume-snap1', 'volume_size': 1}, False, False, 'iSCSI', 'default'), mock.call.edit_vol('clone-testvolume', {'data': {'size': 2048, 'snap_limit': sys.maxsize, 'warn_level': 80, 'reserve': 0, 'limit': 100}})] self.mock_client_service.assert_has_calls(expected_calls) class NimbleDriverConnectionTestCase(NimbleDriverBaseTestCase): """Tests Connection related api's.""" @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_initialize_connection_igroup_exist(self): self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE) expected_res = { 'driver_volume_type': 'iscsi', 'data': { 'volume_id': 12, 'target_iqn': '13', 'target_lun': 0, 'target_portal': '12'}} self.assertEqual( expected_res, self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator1'})) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_initialize_connection_live_migration(self): self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE) expected_res = { 'driver_volume_type': 'iscsi', 'data': { 'volume_id': 12, 'target_iqn': '13', 'target_lun': 0, 'target_portal': '12'}} self.assertEqual( expected_res, self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator1'})) self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator1'}) # 2 or more calls to initialize connection and add_acl for live # migration to work expected_calls = [ mock.call.get_initiator_grp_list(), mock.call.add_acl({'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, 'test-igrp1'), mock.call.get_initiator_grp_list(), mock.call.add_acl({'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, 'test-igrp1')] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator_fc(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_FC_DRIVER + ".get_lun_number") @mock.patch(NIMBLE_FC_DRIVER + ".get_wwpns_from_array") def test_initialize_connection_fc_igroup_exist(self, mock_wwpns, mock_lun_number): mock_lun_number.return_value = 13 mock_wwpns.return_value = ["1111111111111101"] self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE_FC) expected_res = { 'driver_volume_type': 'fibre_channel', 'data': { 'target_lun': 13, 'target_discovered': True, 'target_wwn': ["1111111111111101"], 'initiator_target_map': {'1000000000000000': ['1111111111111101']}}} self.assertEqual( expected_res, self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': 'array1', 'id': 12}, {'initiator': 'test-initiator1', 'wwpns': ['1000000000000000']})) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_RANDOM) def test_initialize_connection_igroup_not_exist(self, mock_random): mock_random.sample.return_value = 'abcdefghijkl' self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE) expected_res = { 'driver_volume_type': 'iscsi', 'data': { 'target_lun': 0, 'volume_id': 12, 'target_iqn': '13', 'target_portal': '12'}} self.assertEqual( expected_res, self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator3'})) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator_fc(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_FC_DRIVER + ".get_wwpns_from_array") @mock.patch(NIMBLE_FC_DRIVER + ".get_lun_number") @mock.patch(NIMBLE_RANDOM) def test_initialize_connection_fc_igroup_not_exist(self, mock_random, mock_lun_number, mock_wwpns): mock_random.sample.return_value = 'abcdefghijkl' mock_lun_number.return_value = 13 mock_wwpns.return_value = ["1111111111111101"] self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE_FC) expected_res = { 'driver_volume_type': 'fibre_channel', 'data': { 'target_lun': 13, 'target_discovered': True, 'target_wwn': ["1111111111111101"], 'initiator_target_map': {'1000000000000000': ['1111111111111101']}}} self.driver._create_igroup_for_initiator("test-initiator3", [1111111111111101]) self.assertEqual( expected_res, self.driver.initialize_connection( {'name': 'test-volume', 'provider_location': 'array1', 'id': 12}, {'initiator': 'test-initiator3', 'wwpns': ['1000000000000000']})) expected_calls = [mock.call.create_initiator_group_fc( 'openstack-abcdefghijkl'), mock.call.add_initiator_to_igroup_fc('openstack-abcdefghijkl', 1111111111111101)] self.mock_client_service.assert_has_calls(expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_terminate_connection_positive(self): self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE) self.driver.terminate_connection( {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator1'}) expected_calls = [mock.call._get_igroupname_for_initiator( 'test-initiator1'), mock.call.remove_acl({'name': 'test-volume'}, 'test-igrp1')] self.mock_client_service.assert_has_calls( self.mock_client_service.method_calls, expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator_fc(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) @mock.patch(NIMBLE_FC_DRIVER + ".get_wwpns_from_array") def test_terminate_connection_positive_fc(self, mock_wwpns): mock_wwpns.return_value = ["1111111111111101"] self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE_FC) self.driver.terminate_connection( {'name': 'test-volume', 'provider_location': 'array1', 'id': 12}, {'initiator': 'test-initiator1', 'wwpns': ['1000000000000000']}) expected_calls = [ mock.call.get_igroupname_for_initiator_fc( "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"), mock.call.remove_acl({'name': 'test-volume'}, 'test-igrp1')] self.mock_client_service.assert_has_calls( self.mock_client_service.method_calls, expected_calls) @mock.patch(NIMBLE_URLLIB2) @mock.patch(NIMBLE_CLIENT) @mock.patch.object(obj_volume.VolumeList, 'get_all_by_host', mock.Mock(return_value=[])) @NimbleDriverBaseTestCase.client_mock_decorator(create_configuration( 'nimble', 'nimble_pass', '10.18.108.55', 'default', '*')) def test_terminate_connection_negative(self): self.mock_client_service.get_initiator_grp_list.return_value = ( FAKE_IGROUP_LIST_RESPONSE) self.assertRaises( exception.VolumeDriverException, self.driver.terminate_connection, {'name': 'test-volume', 'provider_location': '12 13', 'id': 12}, {'initiator': 'test-initiator3'})
0.292797
0.118615
import roslib roslib.load_manifest('SAFMC-21-D2-Team2') import sys import rospy from statistics import mean import numpy as np import cv2 as cv from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError class BoxCV: def __init__(self, output=False): #self.image_pub = rospy.Publisher("camera/depth/image_rect_raw",Image) self.bridge = CvBridge() self.image_sub = rospy.Subscriber("/d400/depth/image_rect_raw", Image, self.image_cb) #self.image_sub = rospy.Subscriber("/camera/depth/image_raw", Image, self.image_cb) self.running_sum = [] self.theta = np.array([0, 0]) self.output=output def image_cb(self, data): #print("image") try: cv_image = self.bridge.imgmsg_to_cv2(data) except CvBridgeError as e: print(e) # cv_image=cv_image[:,80:] print(cv_image.shape) cv_image=cv_image[140:-140,220:-220] cv_image=cv_image/1000 (rows,cols) = cv_image.shape if self.output: cv.imshow("image",cv_image/18) cv.waitKey(3) self.running_sum.append(np.mean(cv_image)) if len(self.running_sum)>20: self.running_sum.pop(0) print("mean:", mean(self.running_sum)) y_mean = np.mean(cv_image, axis=0) x = np.array([[1, i/cols] for i in range(cols)]).reshape(cols, 2) self.theta = np.matmul(np.matmul(np.linalg.inv(np.matmul(np.transpose(x), x)), np.transpose(x)), y_mean) if self.output: print(self.theta) def get_theta(self): return self.theta def get_mean(self): return mean(self.running_sum) def main(args): print(sys.version) boxCV = BoxCV(output=False) rospy.init_node('image_converter', anonymous=True) try: rospy.spin() except KeyboardInterrupt: print("Shutting down") cv.destroyAllWindows() if __name__ == '__main__': main(sys.argv)
src/box.py
import roslib roslib.load_manifest('SAFMC-21-D2-Team2') import sys import rospy from statistics import mean import numpy as np import cv2 as cv from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError class BoxCV: def __init__(self, output=False): #self.image_pub = rospy.Publisher("camera/depth/image_rect_raw",Image) self.bridge = CvBridge() self.image_sub = rospy.Subscriber("/d400/depth/image_rect_raw", Image, self.image_cb) #self.image_sub = rospy.Subscriber("/camera/depth/image_raw", Image, self.image_cb) self.running_sum = [] self.theta = np.array([0, 0]) self.output=output def image_cb(self, data): #print("image") try: cv_image = self.bridge.imgmsg_to_cv2(data) except CvBridgeError as e: print(e) # cv_image=cv_image[:,80:] print(cv_image.shape) cv_image=cv_image[140:-140,220:-220] cv_image=cv_image/1000 (rows,cols) = cv_image.shape if self.output: cv.imshow("image",cv_image/18) cv.waitKey(3) self.running_sum.append(np.mean(cv_image)) if len(self.running_sum)>20: self.running_sum.pop(0) print("mean:", mean(self.running_sum)) y_mean = np.mean(cv_image, axis=0) x = np.array([[1, i/cols] for i in range(cols)]).reshape(cols, 2) self.theta = np.matmul(np.matmul(np.linalg.inv(np.matmul(np.transpose(x), x)), np.transpose(x)), y_mean) if self.output: print(self.theta) def get_theta(self): return self.theta def get_mean(self): return mean(self.running_sum) def main(args): print(sys.version) boxCV = BoxCV(output=False) rospy.init_node('image_converter', anonymous=True) try: rospy.spin() except KeyboardInterrupt: print("Shutting down") cv.destroyAllWindows() if __name__ == '__main__': main(sys.argv)
0.214034
0.1941
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ class graceful_restart(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-common-def - based on the path /routing-system/router/router-bgp/address-family/ipv6/ipv6-unicast/default-vrf/af-common-cmds-holder/graceful-restart. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__graceful_restart_status','__restart_time','__purge_time','__stale_routes_time',) _yang_name = 'graceful-restart' _rest_name = 'graceful-restart' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__graceful_restart_status = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="graceful-restart-status", rest_name="graceful-restart-status", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'cli-drop-node-name': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='empty', is_config=True) self.__restart_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="restart-time", rest_name="restart-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum restart wait time advertised to neighbors (1-3600s), default 120', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='rtime-type', is_config=True) self.__stale_routes_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="stale-routes-time", rest_name="stale-routes-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before helper router clean up stale routes (1-3600s), default 360', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='st-time-type', is_config=True) self.__purge_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="purge-time", rest_name="purge-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before restarting router clean up stale (1-3600s), default 600', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='ptime-type', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'routing-system', u'router', u'router-bgp', u'address-family', u'ipv6', u'ipv6-unicast', u'default-vrf', u'af-common-cmds-holder', u'graceful-restart'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'router', u'bgp', u'address-family', u'ipv6', u'unicast', u'graceful-restart'] def _get_graceful_restart_status(self): """ Getter method for graceful_restart_status, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/graceful_restart_status (empty) """ return self.__graceful_restart_status def _set_graceful_restart_status(self, v, load=False): """ Setter method for graceful_restart_status, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/graceful_restart_status (empty) If this variable is read-only (config: false) in the source YANG file, then _set_graceful_restart_status is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_graceful_restart_status() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="graceful-restart-status", rest_name="graceful-restart-status", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'cli-drop-node-name': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='empty', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """graceful_restart_status must be of a type compatible with empty""", 'defined-type': "empty", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="graceful-restart-status", rest_name="graceful-restart-status", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'cli-drop-node-name': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='empty', is_config=True)""", }) self.__graceful_restart_status = t if hasattr(self, '_set'): self._set() def _unset_graceful_restart_status(self): self.__graceful_restart_status = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="graceful-restart-status", rest_name="graceful-restart-status", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'cli-drop-node-name': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='empty', is_config=True) def _get_restart_time(self): """ Getter method for restart_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/restart_time (rtime-type) """ return self.__restart_time def _set_restart_time(self, v, load=False): """ Setter method for restart_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/restart_time (rtime-type) If this variable is read-only (config: false) in the source YANG file, then _set_restart_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_restart_time() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="restart-time", rest_name="restart-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum restart wait time advertised to neighbors (1-3600s), default 120', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='rtime-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """restart_time must be of a type compatible with rtime-type""", 'defined-type': "brocade-bgp:rtime-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="restart-time", rest_name="restart-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum restart wait time advertised to neighbors (1-3600s), default 120', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='rtime-type', is_config=True)""", }) self.__restart_time = t if hasattr(self, '_set'): self._set() def _unset_restart_time(self): self.__restart_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="restart-time", rest_name="restart-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum restart wait time advertised to neighbors (1-3600s), default 120', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='rtime-type', is_config=True) def _get_purge_time(self): """ Getter method for purge_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/purge_time (ptime-type) """ return self.__purge_time def _set_purge_time(self, v, load=False): """ Setter method for purge_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/purge_time (ptime-type) If this variable is read-only (config: false) in the source YANG file, then _set_purge_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_purge_time() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="purge-time", rest_name="purge-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before restarting router clean up stale (1-3600s), default 600', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='ptime-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """purge_time must be of a type compatible with ptime-type""", 'defined-type': "brocade-bgp:ptime-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="purge-time", rest_name="purge-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before restarting router clean up stale (1-3600s), default 600', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='ptime-type', is_config=True)""", }) self.__purge_time = t if hasattr(self, '_set'): self._set() def _unset_purge_time(self): self.__purge_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="purge-time", rest_name="purge-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before restarting router clean up stale (1-3600s), default 600', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='ptime-type', is_config=True) def _get_stale_routes_time(self): """ Getter method for stale_routes_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/stale_routes_time (st-time-type) """ return self.__stale_routes_time def _set_stale_routes_time(self, v, load=False): """ Setter method for stale_routes_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/stale_routes_time (st-time-type) If this variable is read-only (config: false) in the source YANG file, then _set_stale_routes_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_stale_routes_time() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="stale-routes-time", rest_name="stale-routes-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before helper router clean up stale routes (1-3600s), default 360', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='st-time-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """stale_routes_time must be of a type compatible with st-time-type""", 'defined-type': "brocade-bgp:st-time-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="stale-routes-time", rest_name="stale-routes-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before helper router clean up stale routes (1-3600s), default 360', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='st-time-type', is_config=True)""", }) self.__stale_routes_time = t if hasattr(self, '_set'): self._set() def _unset_stale_routes_time(self): self.__stale_routes_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="stale-routes-time", rest_name="stale-routes-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before helper router clean up stale routes (1-3600s), default 360', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='st-time-type', is_config=True) graceful_restart_status = __builtin__.property(_get_graceful_restart_status, _set_graceful_restart_status) restart_time = __builtin__.property(_get_restart_time, _set_restart_time) purge_time = __builtin__.property(_get_purge_time, _set_purge_time) stale_routes_time = __builtin__.property(_get_stale_routes_time, _set_stale_routes_time) _pyangbind_elements = {'graceful_restart_status': graceful_restart_status, 'restart_time': restart_time, 'purge_time': purge_time, 'stale_routes_time': stale_routes_time, }
pybind/slxos/v16r_1_00b/routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/__init__.py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ class graceful_restart(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-common-def - based on the path /routing-system/router/router-bgp/address-family/ipv6/ipv6-unicast/default-vrf/af-common-cmds-holder/graceful-restart. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__graceful_restart_status','__restart_time','__purge_time','__stale_routes_time',) _yang_name = 'graceful-restart' _rest_name = 'graceful-restart' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__graceful_restart_status = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="graceful-restart-status", rest_name="graceful-restart-status", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'cli-drop-node-name': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='empty', is_config=True) self.__restart_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="restart-time", rest_name="restart-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum restart wait time advertised to neighbors (1-3600s), default 120', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='rtime-type', is_config=True) self.__stale_routes_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="stale-routes-time", rest_name="stale-routes-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before helper router clean up stale routes (1-3600s), default 360', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='st-time-type', is_config=True) self.__purge_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="purge-time", rest_name="purge-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before restarting router clean up stale (1-3600s), default 600', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='ptime-type', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'routing-system', u'router', u'router-bgp', u'address-family', u'ipv6', u'ipv6-unicast', u'default-vrf', u'af-common-cmds-holder', u'graceful-restart'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'router', u'bgp', u'address-family', u'ipv6', u'unicast', u'graceful-restart'] def _get_graceful_restart_status(self): """ Getter method for graceful_restart_status, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/graceful_restart_status (empty) """ return self.__graceful_restart_status def _set_graceful_restart_status(self, v, load=False): """ Setter method for graceful_restart_status, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/graceful_restart_status (empty) If this variable is read-only (config: false) in the source YANG file, then _set_graceful_restart_status is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_graceful_restart_status() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="graceful-restart-status", rest_name="graceful-restart-status", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'cli-drop-node-name': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='empty', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """graceful_restart_status must be of a type compatible with empty""", 'defined-type': "empty", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="graceful-restart-status", rest_name="graceful-restart-status", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'cli-drop-node-name': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='empty', is_config=True)""", }) self.__graceful_restart_status = t if hasattr(self, '_set'): self._set() def _unset_graceful_restart_status(self): self.__graceful_restart_status = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="graceful-restart-status", rest_name="graceful-restart-status", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'cli-drop-node-name': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='empty', is_config=True) def _get_restart_time(self): """ Getter method for restart_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/restart_time (rtime-type) """ return self.__restart_time def _set_restart_time(self, v, load=False): """ Setter method for restart_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/restart_time (rtime-type) If this variable is read-only (config: false) in the source YANG file, then _set_restart_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_restart_time() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="restart-time", rest_name="restart-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum restart wait time advertised to neighbors (1-3600s), default 120', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='rtime-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """restart_time must be of a type compatible with rtime-type""", 'defined-type': "brocade-bgp:rtime-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="restart-time", rest_name="restart-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum restart wait time advertised to neighbors (1-3600s), default 120', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='rtime-type', is_config=True)""", }) self.__restart_time = t if hasattr(self, '_set'): self._set() def _unset_restart_time(self): self.__restart_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="restart-time", rest_name="restart-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum restart wait time advertised to neighbors (1-3600s), default 120', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='rtime-type', is_config=True) def _get_purge_time(self): """ Getter method for purge_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/purge_time (ptime-type) """ return self.__purge_time def _set_purge_time(self, v, load=False): """ Setter method for purge_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/purge_time (ptime-type) If this variable is read-only (config: false) in the source YANG file, then _set_purge_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_purge_time() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="purge-time", rest_name="purge-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before restarting router clean up stale (1-3600s), default 600', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='ptime-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """purge_time must be of a type compatible with ptime-type""", 'defined-type': "brocade-bgp:ptime-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="purge-time", rest_name="purge-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before restarting router clean up stale (1-3600s), default 600', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='ptime-type', is_config=True)""", }) self.__purge_time = t if hasattr(self, '_set'): self._set() def _unset_purge_time(self): self.__purge_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="purge-time", rest_name="purge-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before restarting router clean up stale (1-3600s), default 600', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='ptime-type', is_config=True) def _get_stale_routes_time(self): """ Getter method for stale_routes_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/stale_routes_time (st-time-type) """ return self.__stale_routes_time def _set_stale_routes_time(self, v, load=False): """ Setter method for stale_routes_time, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/stale_routes_time (st-time-type) If this variable is read-only (config: false) in the source YANG file, then _set_stale_routes_time is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_stale_routes_time() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="stale-routes-time", rest_name="stale-routes-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before helper router clean up stale routes (1-3600s), default 360', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='st-time-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """stale_routes_time must be of a type compatible with st-time-type""", 'defined-type': "brocade-bgp:st-time-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="stale-routes-time", rest_name="stale-routes-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before helper router clean up stale routes (1-3600s), default 360', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='st-time-type', is_config=True)""", }) self.__stale_routes_time = t if hasattr(self, '_set'): self._set() def _unset_stale_routes_time(self): self.__stale_routes_time = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..3600']}), is_leaf=True, yang_name="stale-routes-time", rest_name="stale-routes-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Maximum time before helper router clean up stale routes (1-3600s), default 360', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='st-time-type', is_config=True) graceful_restart_status = __builtin__.property(_get_graceful_restart_status, _set_graceful_restart_status) restart_time = __builtin__.property(_get_restart_time, _set_restart_time) purge_time = __builtin__.property(_get_purge_time, _set_purge_time) stale_routes_time = __builtin__.property(_get_stale_routes_time, _set_stale_routes_time) _pyangbind_elements = {'graceful_restart_status': graceful_restart_status, 'restart_time': restart_time, 'purge_time': purge_time, 'stale_routes_time': stale_routes_time, }
0.667148
0.067424
import json from pyrogram import Client, filters from firebase import firebase from process import check, searches, truecaller_search, fb_search, logreturn, log, eyecon_search from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from creds import cred firebase = firebase.FirebaseApplication(cred.DB_URL) app = Client( "Truecaller-Bot", api_id=cred.API_ID, api_hash=cred.API_HASH, bot_token=cred.BOT_TOKEN ) @app.on_message(filters.command(["start"])) def start(client, message): client.send_message(chat_id=message.chat.id, text=f"`Hi` **{message.from_user.first_name}**\n Enter the number to search...\n** __Join My Channel For Updates @HxBots__**",reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("About", callback_data="about"), InlineKeyboardButton("Buy Me A Coffee ☕", url="https://upayme.vercel.app/kkirodewal@ybl")]])) check_status = check(message.chat.id) @app.on_callback_query() def newbt(client,callback_query): txt=callback_query.data if txt=="about": callback_query.message.edit(text=f"**🔹 Bot Name 🔹 :** __[Truecaller-Bot](t.me/truecalerbot)__\n\n**🔹 Channel 🔹 :** __[HxBots](t.me/hxbots)__\n\n**🔹 Creator 🔹 :** __[oVoIndia](https://github.com/oVoIndia)__\n\n**🔹 Owner 🔹 :** __[Kirodewal](t.me/Kirodewal)__\n\n**🔹 Server 🔹 :** __[Heroku](https://herokuapp.com/)__", disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("Any Feedback 🙋‍♂️", url="t.me/hxsupport")]])) elif txt=="src": callback_query.message.edit(text="Enjoy...😁:-D\nhttps://github.com/oVoIndia/Truecaller-Bot", disable_web_page_preview=True) @app.on_message(filters.command(["about"])) def about(client, message): client.send_message(chat_id=message.chat.id, reply_to_message_id=message.message_id, text=f"**🔸 Bot Name 🔸 :** __[Truecaller-Bot](t.me/truecalerbot)__\n\n**🔸 Channel 🔸 :** __[HxBots](t.me/hxbots)__\n\n**🔸 Creator 🔸 :** __[oVoIndia](https://github.com/oVoIndia)__\n\n**🔸 Owner 🔸 :** __[Kirodewal](t.me/Kirodewal)__\n\n**🔸 Server 🔸 :** __[Heroku](https://herokuapp.com/)__", disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("Any Feedback 🙋‍♀️", url="t.me/hxsupport")]])) @app.on_message(filters.command(["log"])) def stats(client, message): stat = client.send_message(chat_id=message.chat.id, reply_to_message_id=message.message_id, text="`Fetching details`") txt = logreturn() stat.edit(txt) @app.on_message(filters.text) def echo(client, message): actvt = "" actvt = firebase.get('/stats', 'total_searches') data = {"total_searches": 1} if not actvt: firebase.put('/stats', 'total_searches', data) global pq pq = "" pro = client.send_message(chat_id=message.chat.id, text="Searching...", reply_to_message_id=message.message_id) r_num = message.text num = r_num.replace("+91", "").replace(" ", "") frbseyename = "" frbsefb = "" frbsetrname = "" frbsetrmail = "" if num.isnumeric and len(num) == 10: pq = "\n\n**----••Truecaller says----**\n\nLimit exceeded ,try again tomorrow 🤦🏻‍♂️" tresponse = "" try: tresponse = truecaller_search(cred.T_AUTH, num) if tresponse: restj = tresponse.json() trslt = json.dumps(restj) tjsonload = json.loads(trslt) if "name" in tjsonload['data'][0]: if tjsonload['data'][0]['internetAddresses']: pq = f"\n\n**----••Truecaller says----**\n\nName : `{tjsonload['data'][0]['name']}`\nCarrier : `{tjsonload['data'][0]['phones'][0]['carrier']}` \nE-mail : {tjsonload['data'][0]['internetAddresses'][0]['id']}" frbsetrname = tjsonload['data'][0]['name'] frbsetrmail = tjsonload['data'][0]['internetAddresses'][0]['id'] elif not tjsonload['data'][0]['internetAddresses']: pq = f"\n\n**----••Truecaller says----**\n\nName : `{tjsonload['data'][0]['name']}`\nCarrier : `{tjsonload['data'][0]['phones'][0]['carrier']}`" frbsetrname = tjsonload['data'][0]['name'] else: pq = "\n\n**----••Truecaller says----**\n\nNo results found 🤦🏻‍♂️" if tresponse.status_code == 429: pq = "\n\n**----••Truecaller says----**\n\nLimit exceeded ,try again tomorrow 🤦🏻‍♂️" except: pass response = eyecon_search(num) fbres = fb_search(num) fbrslt = fbres.url.replace('https://graph.', '').replace('picture?width=600', '') if response: rslt = response.json() if rslt: temp = json.dumps(rslt).replace('[', '').replace(']', '') jsonload = json.loads(temp) yk = f"\n\n**----••Eyecon says----**\n\nName :`{jsonload['name']}`" frbseyename = jsonload["name"] if "facebook.com" in fbrslt: yk = f"\n\n**----••Eyecon says----**\n\nName : `{jsonload['name']}`\nFacebook : {fbrslt}" frbseyename = jsonload["name"] frbsefb = fbrslt else: yk = "**----••Eyecon says----**\n\nNo results found 🤦🏻‍♂️" else: yk = "**----••Eyecon says----**\n\nNo results found 🤦🏻‍♂️" yk += pq pro.edit(text=yk, disable_web_page_preview=True,reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("Source", callback_data="src")]])) searches() log() if frbseyename and frbsefb and frbsetrname and frbsetrmail: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname, "Facebook": frbsefb, "Mail": frbsetrmail } firebase.put('/knowho-log', num, data) elif frbseyename and frbsefb and frbsetrname: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname, "Facebook": frbsefb } firebase.put('/knowho-log', num, data) elif frbseyename and frbsefb: data = { "Eyecon Name": frbseyename, "Mob": num, "Facebook": frbsefb } firebase.put('/knowho-log', num, data) elif frbseyename and frbsetrname and frbsetrmail: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname, "Mail": frbsetrmail } firebase.put('/knowho-log', num, data) elif frbseyename and frbsetrname: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname } firebase.put('/knowho-log', num, data) elif frbsetrname and frbsetrmail: data = { "Truecaller name": frbsetrname, "Mob": num, "Mail": frbsetrmail } firebase.put('/knowho-log', num, data) elif frbsetrname: data = { "Truecaller name": frbsetrname } firebase.put('/knowho-log', num, data) else: pro.edit("`Only` **10** `digit numbers allowed` 🤦🏻‍♂️") app.run()
main.py
import json from pyrogram import Client, filters from firebase import firebase from process import check, searches, truecaller_search, fb_search, logreturn, log, eyecon_search from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from creds import cred firebase = firebase.FirebaseApplication(cred.DB_URL) app = Client( "Truecaller-Bot", api_id=cred.API_ID, api_hash=cred.API_HASH, bot_token=cred.BOT_TOKEN ) @app.on_message(filters.command(["start"])) def start(client, message): client.send_message(chat_id=message.chat.id, text=f"`Hi` **{message.from_user.first_name}**\n Enter the number to search...\n** __Join My Channel For Updates @HxBots__**",reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("About", callback_data="about"), InlineKeyboardButton("Buy Me A Coffee ☕", url="https://upayme.vercel.app/kkirodewal@ybl")]])) check_status = check(message.chat.id) @app.on_callback_query() def newbt(client,callback_query): txt=callback_query.data if txt=="about": callback_query.message.edit(text=f"**🔹 Bot Name 🔹 :** __[Truecaller-Bot](t.me/truecalerbot)__\n\n**🔹 Channel 🔹 :** __[HxBots](t.me/hxbots)__\n\n**🔹 Creator 🔹 :** __[oVoIndia](https://github.com/oVoIndia)__\n\n**🔹 Owner 🔹 :** __[Kirodewal](t.me/Kirodewal)__\n\n**🔹 Server 🔹 :** __[Heroku](https://herokuapp.com/)__", disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("Any Feedback 🙋‍♂️", url="t.me/hxsupport")]])) elif txt=="src": callback_query.message.edit(text="Enjoy...😁:-D\nhttps://github.com/oVoIndia/Truecaller-Bot", disable_web_page_preview=True) @app.on_message(filters.command(["about"])) def about(client, message): client.send_message(chat_id=message.chat.id, reply_to_message_id=message.message_id, text=f"**🔸 Bot Name 🔸 :** __[Truecaller-Bot](t.me/truecalerbot)__\n\n**🔸 Channel 🔸 :** __[HxBots](t.me/hxbots)__\n\n**🔸 Creator 🔸 :** __[oVoIndia](https://github.com/oVoIndia)__\n\n**🔸 Owner 🔸 :** __[Kirodewal](t.me/Kirodewal)__\n\n**🔸 Server 🔸 :** __[Heroku](https://herokuapp.com/)__", disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("Any Feedback 🙋‍♀️", url="t.me/hxsupport")]])) @app.on_message(filters.command(["log"])) def stats(client, message): stat = client.send_message(chat_id=message.chat.id, reply_to_message_id=message.message_id, text="`Fetching details`") txt = logreturn() stat.edit(txt) @app.on_message(filters.text) def echo(client, message): actvt = "" actvt = firebase.get('/stats', 'total_searches') data = {"total_searches": 1} if not actvt: firebase.put('/stats', 'total_searches', data) global pq pq = "" pro = client.send_message(chat_id=message.chat.id, text="Searching...", reply_to_message_id=message.message_id) r_num = message.text num = r_num.replace("+91", "").replace(" ", "") frbseyename = "" frbsefb = "" frbsetrname = "" frbsetrmail = "" if num.isnumeric and len(num) == 10: pq = "\n\n**----••Truecaller says----**\n\nLimit exceeded ,try again tomorrow 🤦🏻‍♂️" tresponse = "" try: tresponse = truecaller_search(cred.T_AUTH, num) if tresponse: restj = tresponse.json() trslt = json.dumps(restj) tjsonload = json.loads(trslt) if "name" in tjsonload['data'][0]: if tjsonload['data'][0]['internetAddresses']: pq = f"\n\n**----••Truecaller says----**\n\nName : `{tjsonload['data'][0]['name']}`\nCarrier : `{tjsonload['data'][0]['phones'][0]['carrier']}` \nE-mail : {tjsonload['data'][0]['internetAddresses'][0]['id']}" frbsetrname = tjsonload['data'][0]['name'] frbsetrmail = tjsonload['data'][0]['internetAddresses'][0]['id'] elif not tjsonload['data'][0]['internetAddresses']: pq = f"\n\n**----••Truecaller says----**\n\nName : `{tjsonload['data'][0]['name']}`\nCarrier : `{tjsonload['data'][0]['phones'][0]['carrier']}`" frbsetrname = tjsonload['data'][0]['name'] else: pq = "\n\n**----••Truecaller says----**\n\nNo results found 🤦🏻‍♂️" if tresponse.status_code == 429: pq = "\n\n**----••Truecaller says----**\n\nLimit exceeded ,try again tomorrow 🤦🏻‍♂️" except: pass response = eyecon_search(num) fbres = fb_search(num) fbrslt = fbres.url.replace('https://graph.', '').replace('picture?width=600', '') if response: rslt = response.json() if rslt: temp = json.dumps(rslt).replace('[', '').replace(']', '') jsonload = json.loads(temp) yk = f"\n\n**----••Eyecon says----**\n\nName :`{jsonload['name']}`" frbseyename = jsonload["name"] if "facebook.com" in fbrslt: yk = f"\n\n**----••Eyecon says----**\n\nName : `{jsonload['name']}`\nFacebook : {fbrslt}" frbseyename = jsonload["name"] frbsefb = fbrslt else: yk = "**----••Eyecon says----**\n\nNo results found 🤦🏻‍♂️" else: yk = "**----••Eyecon says----**\n\nNo results found 🤦🏻‍♂️" yk += pq pro.edit(text=yk, disable_web_page_preview=True,reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("Source", callback_data="src")]])) searches() log() if frbseyename and frbsefb and frbsetrname and frbsetrmail: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname, "Facebook": frbsefb, "Mail": frbsetrmail } firebase.put('/knowho-log', num, data) elif frbseyename and frbsefb and frbsetrname: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname, "Facebook": frbsefb } firebase.put('/knowho-log', num, data) elif frbseyename and frbsefb: data = { "Eyecon Name": frbseyename, "Mob": num, "Facebook": frbsefb } firebase.put('/knowho-log', num, data) elif frbseyename and frbsetrname and frbsetrmail: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname, "Mail": frbsetrmail } firebase.put('/knowho-log', num, data) elif frbseyename and frbsetrname: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname } firebase.put('/knowho-log', num, data) elif frbsetrname and frbsetrmail: data = { "Truecaller name": frbsetrname, "Mob": num, "Mail": frbsetrmail } firebase.put('/knowho-log', num, data) elif frbsetrname: data = { "Truecaller name": frbsetrname } firebase.put('/knowho-log', num, data) else: pro.edit("`Only` **10** `digit numbers allowed` 🤦🏻‍♂️") app.run()
0.257765
0.088072
# Import `FEModel3D` from `PyNite` from PyNite import FEModel3D # Import 'Visualization' for rendering the model from PyNite import Visualization # Create a new finite element model SimpleBeam = FEModel3D() # Add nodes (14 ft apart) SimpleBeam.AddNode('N1', 0, 0, 0) SimpleBeam.AddNode('N2', 14*12, 0, 0) # Add a beam with the following properties: # E = 29000 ksi, G = 11400 ksi, Iy = 100 in^4, Iz = 150 in^4, J = 250 in^4, A = 20 in^2 SimpleBeam.AddMember('M1', 'N1', 'N2', 29000, 11400, 100, 150, 250, 20) # Provide simple supports SimpleBeam.DefineSupport('N1', True, True, True, True, False, False) # Constrained for torsion at 'N1' SimpleBeam.DefineSupport('N2', True, True, True, False, False, False) # Not constrained for torsion at 'N2' # Add a downward point load of 5 kips at the midspan of the beam SimpleBeam.AddMemberPtLoad('M1', 'Fy', -5, 7*12, 'D') # 5 kips Dead load SimpleBeam.AddMemberPtLoad('M1', 'Fy', -8, 7*12, 'L') # 8 kips Live load # Add load combinations SimpleBeam.AddLoadCombo('1.4D', {'D':1.0}) SimpleBeam.AddLoadCombo('1.2D+1.6L', {'D':1.2, 'L':1.6}) # Analyze the beam and perform a statics check SimpleBeam.Analyze(check_statics=True) Visualization.RenderModel(SimpleBeam, text_height=10, deformed_shape=True, deformed_scale=30, render_loads=True, combo_name='1.2D+1.6L',) # Print the shear, moment, and deflection diagrams SimpleBeam.GetMember('M1').PlotShear('Fy', '1.2D+1.6L') SimpleBeam.GetMember('M1').PlotMoment('Mz', '1.2D+1.6L') SimpleBeam.GetMember('M1').PlotDeflection('dy', '1.2D+1.6L') # Print reactions at each end of the beam print('Left Support Reaction:', SimpleBeam.GetNode('N1').RxnFY['1.2D+1.6L'], 'kip') print('Right Support Reacton:', SimpleBeam.GetNode('N2').RxnFY['1.2D+1.6L'], 'kip') # Print the max/min shears and moments in the beam print('Maximum Shear:', SimpleBeam.GetMember('M1').MaxShear('Fy', '1.2D+1.6L'), 'kip') print('Minimum Shear:', SimpleBeam.GetMember('M1').MinShear('Fy', '1.2D+1.6L'), 'kip') print('Maximum Moment:', SimpleBeam.GetMember('M1').MaxMoment('Mz', '1.2D+1.6L')/12, 'kip-ft') print('Minimum Moment:', SimpleBeam.GetMember('M1').MinMoment('Mz', '1.2D+1.6L')/12, 'kip-ft') # Print the max/min deflections in the beam print('Maximum Deflection:', SimpleBeam.GetMember('M1').MaxDeflection('dy', '1.2D+1.6L'), 'in') print('Minimum Deflection:', SimpleBeam.GetMember('M1').MinDeflection('dy', '1.2D+1.6L'), 'in')
Examples/Simple Beam - Point Load.py
# Import `FEModel3D` from `PyNite` from PyNite import FEModel3D # Import 'Visualization' for rendering the model from PyNite import Visualization # Create a new finite element model SimpleBeam = FEModel3D() # Add nodes (14 ft apart) SimpleBeam.AddNode('N1', 0, 0, 0) SimpleBeam.AddNode('N2', 14*12, 0, 0) # Add a beam with the following properties: # E = 29000 ksi, G = 11400 ksi, Iy = 100 in^4, Iz = 150 in^4, J = 250 in^4, A = 20 in^2 SimpleBeam.AddMember('M1', 'N1', 'N2', 29000, 11400, 100, 150, 250, 20) # Provide simple supports SimpleBeam.DefineSupport('N1', True, True, True, True, False, False) # Constrained for torsion at 'N1' SimpleBeam.DefineSupport('N2', True, True, True, False, False, False) # Not constrained for torsion at 'N2' # Add a downward point load of 5 kips at the midspan of the beam SimpleBeam.AddMemberPtLoad('M1', 'Fy', -5, 7*12, 'D') # 5 kips Dead load SimpleBeam.AddMemberPtLoad('M1', 'Fy', -8, 7*12, 'L') # 8 kips Live load # Add load combinations SimpleBeam.AddLoadCombo('1.4D', {'D':1.0}) SimpleBeam.AddLoadCombo('1.2D+1.6L', {'D':1.2, 'L':1.6}) # Analyze the beam and perform a statics check SimpleBeam.Analyze(check_statics=True) Visualization.RenderModel(SimpleBeam, text_height=10, deformed_shape=True, deformed_scale=30, render_loads=True, combo_name='1.2D+1.6L',) # Print the shear, moment, and deflection diagrams SimpleBeam.GetMember('M1').PlotShear('Fy', '1.2D+1.6L') SimpleBeam.GetMember('M1').PlotMoment('Mz', '1.2D+1.6L') SimpleBeam.GetMember('M1').PlotDeflection('dy', '1.2D+1.6L') # Print reactions at each end of the beam print('Left Support Reaction:', SimpleBeam.GetNode('N1').RxnFY['1.2D+1.6L'], 'kip') print('Right Support Reacton:', SimpleBeam.GetNode('N2').RxnFY['1.2D+1.6L'], 'kip') # Print the max/min shears and moments in the beam print('Maximum Shear:', SimpleBeam.GetMember('M1').MaxShear('Fy', '1.2D+1.6L'), 'kip') print('Minimum Shear:', SimpleBeam.GetMember('M1').MinShear('Fy', '1.2D+1.6L'), 'kip') print('Maximum Moment:', SimpleBeam.GetMember('M1').MaxMoment('Mz', '1.2D+1.6L')/12, 'kip-ft') print('Minimum Moment:', SimpleBeam.GetMember('M1').MinMoment('Mz', '1.2D+1.6L')/12, 'kip-ft') # Print the max/min deflections in the beam print('Maximum Deflection:', SimpleBeam.GetMember('M1').MaxDeflection('dy', '1.2D+1.6L'), 'in') print('Minimum Deflection:', SimpleBeam.GetMember('M1').MinDeflection('dy', '1.2D+1.6L'), 'in')
0.798344
0.6508
import gi try: gi.require_version('Gtk', '3.0') gi.require_version('Gdk', '3.0') except Exception as e: print(e) exit(-1) from gi.repository import Gtk from gi.repository import Gdk import sys import importlib import comun from config import Configuration from croni import Croni from autostart import Autostart from dwdownloader import change_wallpaper from fsync import async_function from comun import get_modules from comun import _ from singleton import listen_for_activation, activate_if_already_running sys.path.insert(1, comun.DAILIESDIR) sys.path.insert(1, comun.USERDAILIESDIR) def select_value_in_combo(combo, value): model = combo.get_model() for i, item in enumerate(model): if value == item[1]: combo.set_active(i) return combo.set_active(0) def get_selected_value_in_combo(combo): model = combo.get_model() return model.get_value(combo.get_active_iter(), 1) class DWW(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.set_title(_('Daily Wallpaper')) self.set_modal(True) self.set_destroy_with_parent(True) self.set_size_request(370, 80) self.set_icon_from_file(comun.ICON) self.connect('realize', self.on_realize) self.connect('destroy', self.close_application) self.croni = Croni() self.autostart = Autostart() grid = Gtk.Grid() grid.set_row_spacing(10) grid.set_column_spacing(10) grid.set_border_width(10) self.add(grid) label10 = Gtk.Label.new(_('Change wallpaper automatically?')) label10.set_halign(True) grid.add(label10) self.switch = Gtk.Switch.new() self.switch.set_halign(True) self.switch.set_active(self.croni.is_enabled()) grid.attach(self.switch, 1, 0, 1, 1) label20 = Gtk.Label.new(_('Random source?')) label20.set_halign(True) grid.attach(label20, 0, 1, 1, 1) self.switch_random = Gtk.Switch.new() self.switch_random.set_halign(True) self.switch_random.set_active(True) self.switch_random.connect('state-set', self.on_switch_random_changed) grid.attach(self.switch_random, 1, 1, 1, 1) self.label30 = Gtk.Label.new(_('Select backgrounds source:')) self.label30.set_halign(True) grid.attach(self.label30, 0, 2, 1, 1) source_store = Gtk.ListStore(str, str) source_store.set_sort_func(0, self.tree_compare_func, None) for module_name in get_modules(): module = importlib.import_module(module_name) daily = module.get_daily() source_store.append([daily.get_name(), daily.get_id()]) self.combobox_source = Gtk.ComboBox.new() self.combobox_source.set_model(source_store) cell1 = Gtk.CellRendererText() self.combobox_source.pack_start(cell1, True) self.combobox_source.add_attribute(cell1, 'text', 0) grid.attach(self.combobox_source, 1, 2, 1, 1) button = Gtk.Button.new_with_label(_('Change now')) button.set_halign(Gtk.Align.CENTER) button.connect('clicked', self.button_pressed) grid.attach(button, 0, 3, 2, 1) hb = Gtk.HeaderBar() self.set_titlebar(hb) hb.set_show_close_button(True) hb.props.title = comun.APP button_cancel = Gtk.Button.new_with_label(_('Cancel')) button_cancel.get_style_context().add_class( Gtk.STYLE_CLASS_DESTRUCTIVE_ACTION) button_cancel.set_halign(Gtk.Align.START) button_cancel.connect('clicked', self.on_button_cancel_clicked) hb.pack_start(button_cancel) button_ok = Gtk.Button.new_with_label(_('Ok')) button_ok.get_style_context().add_class( Gtk.STYLE_CLASS_SUGGESTED_ACTION) button_ok.set_halign(Gtk.Align.END) button_ok.connect('clicked', self.on_button_ok_clicked) hb.pack_end(button_ok) self.load_preferences() self.show_all() def tree_compare_func(self, row1, row2): """ a negative integer, zero or a positive integer depending on whether a sorts before, with or after b """ print(type(row1), row1) if row1 < row2: return -1 elif row1 > row2: return 1 return 0 def on_button_ok_clicked(self, widget): self.hide() self.set_autostart_activate() self.save_preferences() self.destroy() def on_button_cancel_clicked(self, widget): self.destroy() def set_source_state(self, state): self.label30.set_sensitive(state) self.combobox_source.set_sensitive(state) def on_switch_random_changed(self, widget, state): state = self.switch_random.get_active() self.set_source_state(not state) def set_autostart_activate(self): if self.switch.get_active(): self.croni.set_jobs() self.autostart.set_autostart(True) else: self.croni.unset_jobs() self.autostart.set_autostart(False) def button_pressed(self, widget): self.change_wallpaper_async() def close_application(self, widget, data=None): exit(0) def load_preferences(self): config = Configuration() select_value_in_combo(self.combobox_source, config.get('source')) self.switch_random.set_active(config.get('random')) self.set_source_state(not config.get('random')) def save_preferences(self): config = Configuration() config.set('source', get_selected_value_in_combo(self.combobox_source)) config.set('random', self.switch_random.get_active()) config.save() def change_wallpaper_async(self): def on_change_wallpaper_done(result, error): self.get_window().set_cursor(None) @async_function(on_done=on_change_wallpaper_done) def do_change_wallpaper_in_thread(): self.save_preferences() change_wallpaper() return True self.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH)) do_change_wallpaper_in_thread() def on_realize(self, *_): monitor = Gdk.Display.get_primary_monitor(Gdk.Display.get_default()) scale = monitor.get_scale_factor() monitor_width = monitor.get_geometry().width / scale monitor_height = monitor.get_geometry().height / scale width = self.get_preferred_width()[0] height = self.get_preferred_height()[0] self.move((monitor_width - width)/2, (monitor_height - height)/2) def main(): """TODO: Docstring for main. :returns: TODO """ APP_ID = 'es.atareao.daily_wallpaper' activated = activate_if_already_running(APP_ID) if activated: sys.exit(0) dww = DWW() listen_for_activation(APP_ID, dww) Gtk.main() if __name__ == '__main__': main()
src/main.py
import gi try: gi.require_version('Gtk', '3.0') gi.require_version('Gdk', '3.0') except Exception as e: print(e) exit(-1) from gi.repository import Gtk from gi.repository import Gdk import sys import importlib import comun from config import Configuration from croni import Croni from autostart import Autostart from dwdownloader import change_wallpaper from fsync import async_function from comun import get_modules from comun import _ from singleton import listen_for_activation, activate_if_already_running sys.path.insert(1, comun.DAILIESDIR) sys.path.insert(1, comun.USERDAILIESDIR) def select_value_in_combo(combo, value): model = combo.get_model() for i, item in enumerate(model): if value == item[1]: combo.set_active(i) return combo.set_active(0) def get_selected_value_in_combo(combo): model = combo.get_model() return model.get_value(combo.get_active_iter(), 1) class DWW(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.set_title(_('Daily Wallpaper')) self.set_modal(True) self.set_destroy_with_parent(True) self.set_size_request(370, 80) self.set_icon_from_file(comun.ICON) self.connect('realize', self.on_realize) self.connect('destroy', self.close_application) self.croni = Croni() self.autostart = Autostart() grid = Gtk.Grid() grid.set_row_spacing(10) grid.set_column_spacing(10) grid.set_border_width(10) self.add(grid) label10 = Gtk.Label.new(_('Change wallpaper automatically?')) label10.set_halign(True) grid.add(label10) self.switch = Gtk.Switch.new() self.switch.set_halign(True) self.switch.set_active(self.croni.is_enabled()) grid.attach(self.switch, 1, 0, 1, 1) label20 = Gtk.Label.new(_('Random source?')) label20.set_halign(True) grid.attach(label20, 0, 1, 1, 1) self.switch_random = Gtk.Switch.new() self.switch_random.set_halign(True) self.switch_random.set_active(True) self.switch_random.connect('state-set', self.on_switch_random_changed) grid.attach(self.switch_random, 1, 1, 1, 1) self.label30 = Gtk.Label.new(_('Select backgrounds source:')) self.label30.set_halign(True) grid.attach(self.label30, 0, 2, 1, 1) source_store = Gtk.ListStore(str, str) source_store.set_sort_func(0, self.tree_compare_func, None) for module_name in get_modules(): module = importlib.import_module(module_name) daily = module.get_daily() source_store.append([daily.get_name(), daily.get_id()]) self.combobox_source = Gtk.ComboBox.new() self.combobox_source.set_model(source_store) cell1 = Gtk.CellRendererText() self.combobox_source.pack_start(cell1, True) self.combobox_source.add_attribute(cell1, 'text', 0) grid.attach(self.combobox_source, 1, 2, 1, 1) button = Gtk.Button.new_with_label(_('Change now')) button.set_halign(Gtk.Align.CENTER) button.connect('clicked', self.button_pressed) grid.attach(button, 0, 3, 2, 1) hb = Gtk.HeaderBar() self.set_titlebar(hb) hb.set_show_close_button(True) hb.props.title = comun.APP button_cancel = Gtk.Button.new_with_label(_('Cancel')) button_cancel.get_style_context().add_class( Gtk.STYLE_CLASS_DESTRUCTIVE_ACTION) button_cancel.set_halign(Gtk.Align.START) button_cancel.connect('clicked', self.on_button_cancel_clicked) hb.pack_start(button_cancel) button_ok = Gtk.Button.new_with_label(_('Ok')) button_ok.get_style_context().add_class( Gtk.STYLE_CLASS_SUGGESTED_ACTION) button_ok.set_halign(Gtk.Align.END) button_ok.connect('clicked', self.on_button_ok_clicked) hb.pack_end(button_ok) self.load_preferences() self.show_all() def tree_compare_func(self, row1, row2): """ a negative integer, zero or a positive integer depending on whether a sorts before, with or after b """ print(type(row1), row1) if row1 < row2: return -1 elif row1 > row2: return 1 return 0 def on_button_ok_clicked(self, widget): self.hide() self.set_autostart_activate() self.save_preferences() self.destroy() def on_button_cancel_clicked(self, widget): self.destroy() def set_source_state(self, state): self.label30.set_sensitive(state) self.combobox_source.set_sensitive(state) def on_switch_random_changed(self, widget, state): state = self.switch_random.get_active() self.set_source_state(not state) def set_autostart_activate(self): if self.switch.get_active(): self.croni.set_jobs() self.autostart.set_autostart(True) else: self.croni.unset_jobs() self.autostart.set_autostart(False) def button_pressed(self, widget): self.change_wallpaper_async() def close_application(self, widget, data=None): exit(0) def load_preferences(self): config = Configuration() select_value_in_combo(self.combobox_source, config.get('source')) self.switch_random.set_active(config.get('random')) self.set_source_state(not config.get('random')) def save_preferences(self): config = Configuration() config.set('source', get_selected_value_in_combo(self.combobox_source)) config.set('random', self.switch_random.get_active()) config.save() def change_wallpaper_async(self): def on_change_wallpaper_done(result, error): self.get_window().set_cursor(None) @async_function(on_done=on_change_wallpaper_done) def do_change_wallpaper_in_thread(): self.save_preferences() change_wallpaper() return True self.get_window().set_cursor(Gdk.Cursor(Gdk.CursorType.WATCH)) do_change_wallpaper_in_thread() def on_realize(self, *_): monitor = Gdk.Display.get_primary_monitor(Gdk.Display.get_default()) scale = monitor.get_scale_factor() monitor_width = monitor.get_geometry().width / scale monitor_height = monitor.get_geometry().height / scale width = self.get_preferred_width()[0] height = self.get_preferred_height()[0] self.move((monitor_width - width)/2, (monitor_height - height)/2) def main(): """TODO: Docstring for main. :returns: TODO """ APP_ID = 'es.atareao.daily_wallpaper' activated = activate_if_already_running(APP_ID) if activated: sys.exit(0) dww = DWW() listen_for_activation(APP_ID, dww) Gtk.main() if __name__ == '__main__': main()
0.31237
0.13707
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('application', '0049_auto_20201119_0924'), ] operations = [ migrations.RemoveField( model_name='landingpages', name='button_text_en', ), migrations.RemoveField( model_name='landingpages', name='button_text_fi', ), migrations.RemoveField( model_name='landingpages', name='button_text_sv', ), migrations.RemoveField( model_name='landingpages', name='button_url_en', ), migrations.RemoveField( model_name='landingpages', name='button_url_fi', ), migrations.RemoveField( model_name='landingpages', name='button_url_sv', ), migrations.RemoveField( model_name='landingpages', name='description_en', ), migrations.RemoveField( model_name='landingpages', name='description_fi', ), migrations.RemoveField( model_name='landingpages', name='description_sv', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_color_en', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_color_fi', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_color_sv', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_en', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_fi', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_mobile_en', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_mobile_fi', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_mobile_sv', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_sv', ), migrations.RemoveField( model_name='landingpages', name='hero_top_layer_image_en', ), migrations.RemoveField( model_name='landingpages', name='hero_top_layer_image_fi', ), migrations.RemoveField( model_name='landingpages', name='hero_top_layer_image_sv', ), migrations.RemoveField( model_name='landingpages', name='social_media_image_en', ), migrations.RemoveField( model_name='landingpages', name='social_media_image_fi', ), migrations.RemoveField( model_name='landingpages', name='social_media_image_sv', ), migrations.RemoveField( model_name='landingpages', name='title_and_description_color_en', ), migrations.RemoveField( model_name='landingpages', name='title_and_description_color_fi', ), migrations.RemoveField( model_name='landingpages', name='title_and_description_color_sv', ), migrations.RemoveField( model_name='landingpages', name='title_en', ), migrations.RemoveField( model_name='landingpages', name='title_fi', ), migrations.RemoveField( model_name='landingpages', name='title_sv', ), ]
application/migrations/0050_auto_20201222_1046.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('application', '0049_auto_20201119_0924'), ] operations = [ migrations.RemoveField( model_name='landingpages', name='button_text_en', ), migrations.RemoveField( model_name='landingpages', name='button_text_fi', ), migrations.RemoveField( model_name='landingpages', name='button_text_sv', ), migrations.RemoveField( model_name='landingpages', name='button_url_en', ), migrations.RemoveField( model_name='landingpages', name='button_url_fi', ), migrations.RemoveField( model_name='landingpages', name='button_url_sv', ), migrations.RemoveField( model_name='landingpages', name='description_en', ), migrations.RemoveField( model_name='landingpages', name='description_fi', ), migrations.RemoveField( model_name='landingpages', name='description_sv', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_color_en', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_color_fi', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_color_sv', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_en', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_fi', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_mobile_en', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_mobile_fi', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_mobile_sv', ), migrations.RemoveField( model_name='landingpages', name='hero_background_image_sv', ), migrations.RemoveField( model_name='landingpages', name='hero_top_layer_image_en', ), migrations.RemoveField( model_name='landingpages', name='hero_top_layer_image_fi', ), migrations.RemoveField( model_name='landingpages', name='hero_top_layer_image_sv', ), migrations.RemoveField( model_name='landingpages', name='social_media_image_en', ), migrations.RemoveField( model_name='landingpages', name='social_media_image_fi', ), migrations.RemoveField( model_name='landingpages', name='social_media_image_sv', ), migrations.RemoveField( model_name='landingpages', name='title_and_description_color_en', ), migrations.RemoveField( model_name='landingpages', name='title_and_description_color_fi', ), migrations.RemoveField( model_name='landingpages', name='title_and_description_color_sv', ), migrations.RemoveField( model_name='landingpages', name='title_en', ), migrations.RemoveField( model_name='landingpages', name='title_fi', ), migrations.RemoveField( model_name='landingpages', name='title_sv', ), ]
0.594904
0.097347
import argparse import logging import os import random import socket import sys import traceback import numpy as np import psutil import setproctitle import torch import wandb from mpi4py import MPI # add the FedML root directory to the python path sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../"))) from fedml_api.distributed.utils.gpu_mapping import mapping_processes_to_gpu_device_from_yaml_file from fedml_api.data_preprocessing.FederatedEMNIST.data_loader import load_partition_data_federated_emnist from fedml_api.data_preprocessing.fed_cifar100.data_loader import load_partition_data_federated_cifar100 from fedml_api.data_preprocessing.fed_shakespeare.data_loader import load_partition_data_federated_shakespeare from fedml_api.data_preprocessing.shakespeare.data_loader import load_partition_data_shakespeare from fedml_api.data_preprocessing.stackoverflow_lr.data_loader import load_partition_data_federated_stackoverflow_lr from fedml_api.data_preprocessing.stackoverflow_nwp.data_loader import load_partition_data_federated_stackoverflow_nwp from fedml_api.data_preprocessing.MNIST.data_loader import load_partition_data_mnist from fedml_api.data_preprocessing.ImageNet.data_loader import load_partition_data_ImageNet from fedml_api.data_preprocessing.Landmarks.data_loader import load_partition_data_landmarks from fedml_api.data_preprocessing.cifar10.data_loader import load_partition_data_cifar10 from fedml_api.data_preprocessing.cifar100.data_loader import load_partition_data_cifar100 from fedml_api.data_preprocessing.cinic10.data_loader import load_partition_data_cinic10 from fedml_api.model.cv.cnn import CNN_DropOut from fedml_api.model.cv.resnet_gn import resnet18 from fedml_api.model.cv.mobilenet import mobilenet from fedml_api.model.cv.resnet import resnet56 from fedml_api.model.nlp.rnn import RNN_OriginalFedAvg, RNN_StackOverFlow from fedml_api.model.linear.lr import LogisticRegression from fedml_api.model.cv.mobilenet_v3 import MobileNetV3 from fedml_api.model.cv.efficientnet import EfficientNet from fedml_api.distributed.fedavg.FedAvgAPI import FedML_init, FedML_FedAvg_distributed def add_args(parser): """ parser : argparse.ArgumentParser return a parser added with args required by fit """ # Training settings parser.add_argument('--model', type=str, default='mobilenet', metavar='N', help='neural network used in training') parser.add_argument('--dataset', type=str, default='cifar10', metavar='N', help='dataset used for training') parser.add_argument('--data_dir', type=str, default='./../../../data/cifar10', help='data directory') parser.add_argument('--partition_method', type=str, default='hetero', metavar='N', help='how to partition the dataset on local workers') parser.add_argument('--partition_alpha', type=float, default=0.5, metavar='PA', help='partition alpha (default: 0.5)') parser.add_argument('--client_num_in_total', type=int, default=1000, metavar='NN', help='number of workers in a distributed cluster') parser.add_argument('--client_num_per_round', type=int, default=4, metavar='NN', help='number of workers') parser.add_argument('--batch_size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--client_optimizer', type=str, default='adam', help='SGD with momentum; adam') parser.add_argument('--lr', type=float, default=0.001, metavar='LR', help='learning rate (default: 0.001)') parser.add_argument('--wd', help='weight decay parameter;', type=float, default=0.001) parser.add_argument('--epochs', type=int, default=5, metavar='EP', help='how many epochs will be trained locally') parser.add_argument('--comm_round', type=int, default=10, help='how many round of communications we shoud use') parser.add_argument('--is_mobile', type=int, default=0, help='whether the program is running on the FedML-Mobile server side') parser.add_argument('--frequency_of_the_test', type=int, default=1, help='the frequency of the algorithms') parser.add_argument('--gpu_server_num', type=int, default=1, help='gpu_server_num') parser.add_argument('--gpu_num_per_server', type=int, default=4, help='gpu_num_per_server') parser.add_argument('--gpu_mapping_file', type=str, default="gpu_mapping.yaml", help='the gpu utilization file for servers and clients. If there is no \ gpu_util_file, gpu will not be used.') parser.add_argument('--gpu_mapping_key', type=str, default="mapping_default", help='the key in gpu utilization file') parser.add_argument('--ci', type=int, default=0, help='CI') args = parser.parse_args() return args def load_data(args, dataset_name): if dataset_name == "mnist": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_mnist(args.batch_size) """ For shallow NN or linear models, we uniformly sample a fraction of clients each round (as the original FedAvg paper) """ args.client_num_in_total = client_num elif dataset_name == "femnist": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_federated_emnist(args.dataset, args.data_dir) args.client_num_in_total = client_num elif dataset_name == "shakespeare": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_shakespeare(args.batch_size) args.client_num_in_total = client_num elif dataset_name == "fed_shakespeare": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_federated_shakespeare(args.dataset, args.data_dir) args.client_num_in_total = client_num elif dataset_name == "fed_cifar100": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_federated_cifar100(args.dataset, args.data_dir) args.client_num_in_total = client_num elif dataset_name == "stackoverflow_lr": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_federated_stackoverflow_lr(args.dataset, args.data_dir) args.client_num_in_total = client_num elif dataset_name == "stackoverflow_nwp": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_federated_stackoverflow_nwp(args.dataset, args.data_dir) args.client_num_in_total = client_num elif dataset_name == "ILSVRC2012": logging.info("load_data. dataset_name = %s" % dataset_name) train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_ImageNet(dataset=dataset_name, data_dir=args.data_dir, partition_method=None, partition_alpha=None, client_number=args.client_num_in_total, batch_size=args.batch_size) elif dataset_name == "gld23k": logging.info("load_data. dataset_name = %s" % dataset_name) args.client_num_in_total = 233 fed_train_map_file = os.path.join(args.data_dir, 'mini_gld_train_split.csv') fed_test_map_file = os.path.join(args.data_dir, 'mini_gld_test.csv') args.data_dir = os.path.join(args.data_dir, 'images') train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_landmarks(dataset=dataset_name, data_dir=args.data_dir, fed_train_map_file=fed_train_map_file, fed_test_map_file=fed_test_map_file, partition_method=None, partition_alpha=None, client_number=args.client_num_in_total, batch_size=args.batch_size) elif dataset_name == "gld160k": logging.info("load_data. dataset_name = %s" % dataset_name) args.client_num_in_total = 1262 fed_train_map_file = os.path.join(args.data_dir, 'federated_train.csv') fed_test_map_file = os.path.join(args.data_dir, 'test.csv') args.data_dir = os.path.join(args.data_dir, 'images') train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_landmarks(dataset=dataset_name, data_dir=args.data_dir, fed_train_map_file=fed_train_map_file, fed_test_map_file=fed_test_map_file, partition_method=None, partition_alpha=None, client_number=args.client_num_in_total, batch_size=args.batch_size) else: if dataset_name == "cifar10": data_loader = load_partition_data_cifar10 elif dataset_name == "cifar100": data_loader = load_partition_data_cifar100 elif dataset_name == "cinic10": data_loader = load_partition_data_cinic10 else: data_loader = load_partition_data_cifar10 train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = data_loader(args.dataset, args.data_dir, args.partition_method, args.partition_alpha, args.client_num_in_total, args.batch_size) dataset = [train_data_num, test_data_num, train_data_global, test_data_global, train_data_local_num_dict, train_data_local_dict, test_data_local_dict, class_num] return dataset def create_model(args, model_name, output_dim): logging.info("create_model. model_name = %s, output_dim = %s" % (model_name, output_dim)) model = None if model_name == "lr" and args.dataset == "mnist": logging.info("LogisticRegression + MNIST") model = LogisticRegression(28 * 28, output_dim) elif model_name == "rnn" and args.dataset == "shakespeare": logging.info("RNN + shakespeare") model = RNN_OriginalFedAvg() elif model_name == "cnn" and args.dataset == "femnist": logging.info("CNN + FederatedEMNIST") model = CNN_DropOut(False) elif model_name == "resnet18_gn" and args.dataset == "fed_cifar100": logging.info("ResNet18_GN + Federated_CIFAR100") model = resnet18() elif model_name == "rnn" and args.dataset == "fed_shakespeare": logging.info("RNN + fed_shakespeare") model = RNN_OriginalFedAvg() elif model_name == "lr" and args.dataset == "stackoverflow_lr": logging.info("lr + stackoverflow_lr") model = LogisticRegression(10004, output_dim) elif model_name == "rnn" and args.dataset == "stackoverflow_nwp": logging.info("CNN + stackoverflow_nwp") model = RNN_StackOverFlow() elif model_name == "resnet56": model = resnet56(class_num=output_dim) elif model_name == "mobilenet": model = mobilenet(class_num=output_dim) # TODO elif model_name == 'mobilenet_v3': '''model_mode \in {LARGE: 5.15M, SMALL: 2.94M}''' model = MobileNetV3(model_mode='LARGE') elif model_name == 'efficientnet': model = EfficientNet() return model if __name__ == "__main__": # initialize distributed computing (MPI) comm, process_id, worker_number = FedML_init() # parse python script input parameters parser = argparse.ArgumentParser() args = add_args(parser) logging.info(args) # customize the process name str_process_name = "FedAvg (distributed):" + str(process_id) setproctitle.setproctitle(str_process_name) # customize the log format # logging.basicConfig(level=logging.INFO, logging.basicConfig(level=logging.DEBUG, format=str( process_id) + ' - %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S') hostname = socket.gethostname() logging.info("#############process ID = " + str(process_id) + ", host name = " + hostname + "########" + ", process ID = " + str(os.getpid()) + ", process Name = " + str(psutil.Process(os.getpid()))) # initialize the wandb machine learning experimental tracking platform (https://www.wandb.com/). if process_id == 0: wandb.init( # project="federated_nas", project="fedml", name="FedAVG(d)" + str(args.partition_method) + "r" + str(args.comm_round) + "-e" + str( args.epochs) + "-lr" + str( args.lr), config=args ) # Set the random seed. The np.random seed determines the dataset partition. # The torch_manual_seed determines the initial weight. # We fix these two, so that we can reproduce the result. random.seed(0) np.random.seed(0) torch.manual_seed(0) torch.cuda.manual_seed_all(0) # Please check "GPU_MAPPING.md" to see how to define the topology logging.info("process_id = %d, size = %d" % (process_id, worker_number)) device = mapping_processes_to_gpu_device_from_yaml_file(process_id, worker_number, args.gpu_mapping_file, args.gpu_mapping_key) # load data dataset = load_data(args, args.dataset) [train_data_num, test_data_num, train_data_global, test_data_global, train_data_local_num_dict, train_data_local_dict, test_data_local_dict, class_num] = dataset # create model. # Note if the model is DNN (e.g., ResNet), the training will be very slow. # In this case, please use our FedML distributed version (./fedml_experiments/distributed_fedavg) model = create_model(args, model_name=args.model, output_dim=dataset[7]) try: # start "federated averaging (FedAvg)" FedML_FedAvg_distributed(process_id, worker_number, device, comm, model, train_data_num, train_data_global, test_data_global, train_data_local_num_dict, train_data_local_dict, test_data_local_dict, args) except Exception as e: print(e) logging.info('traceback.format_exc():\n%s' % traceback.format_exc()) MPI.COMM_WORLD.Abort()
fedml_experiments/distributed/fedavg/main_fedavg.py
import argparse import logging import os import random import socket import sys import traceback import numpy as np import psutil import setproctitle import torch import wandb from mpi4py import MPI # add the FedML root directory to the python path sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../"))) from fedml_api.distributed.utils.gpu_mapping import mapping_processes_to_gpu_device_from_yaml_file from fedml_api.data_preprocessing.FederatedEMNIST.data_loader import load_partition_data_federated_emnist from fedml_api.data_preprocessing.fed_cifar100.data_loader import load_partition_data_federated_cifar100 from fedml_api.data_preprocessing.fed_shakespeare.data_loader import load_partition_data_federated_shakespeare from fedml_api.data_preprocessing.shakespeare.data_loader import load_partition_data_shakespeare from fedml_api.data_preprocessing.stackoverflow_lr.data_loader import load_partition_data_federated_stackoverflow_lr from fedml_api.data_preprocessing.stackoverflow_nwp.data_loader import load_partition_data_federated_stackoverflow_nwp from fedml_api.data_preprocessing.MNIST.data_loader import load_partition_data_mnist from fedml_api.data_preprocessing.ImageNet.data_loader import load_partition_data_ImageNet from fedml_api.data_preprocessing.Landmarks.data_loader import load_partition_data_landmarks from fedml_api.data_preprocessing.cifar10.data_loader import load_partition_data_cifar10 from fedml_api.data_preprocessing.cifar100.data_loader import load_partition_data_cifar100 from fedml_api.data_preprocessing.cinic10.data_loader import load_partition_data_cinic10 from fedml_api.model.cv.cnn import CNN_DropOut from fedml_api.model.cv.resnet_gn import resnet18 from fedml_api.model.cv.mobilenet import mobilenet from fedml_api.model.cv.resnet import resnet56 from fedml_api.model.nlp.rnn import RNN_OriginalFedAvg, RNN_StackOverFlow from fedml_api.model.linear.lr import LogisticRegression from fedml_api.model.cv.mobilenet_v3 import MobileNetV3 from fedml_api.model.cv.efficientnet import EfficientNet from fedml_api.distributed.fedavg.FedAvgAPI import FedML_init, FedML_FedAvg_distributed def add_args(parser): """ parser : argparse.ArgumentParser return a parser added with args required by fit """ # Training settings parser.add_argument('--model', type=str, default='mobilenet', metavar='N', help='neural network used in training') parser.add_argument('--dataset', type=str, default='cifar10', metavar='N', help='dataset used for training') parser.add_argument('--data_dir', type=str, default='./../../../data/cifar10', help='data directory') parser.add_argument('--partition_method', type=str, default='hetero', metavar='N', help='how to partition the dataset on local workers') parser.add_argument('--partition_alpha', type=float, default=0.5, metavar='PA', help='partition alpha (default: 0.5)') parser.add_argument('--client_num_in_total', type=int, default=1000, metavar='NN', help='number of workers in a distributed cluster') parser.add_argument('--client_num_per_round', type=int, default=4, metavar='NN', help='number of workers') parser.add_argument('--batch_size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--client_optimizer', type=str, default='adam', help='SGD with momentum; adam') parser.add_argument('--lr', type=float, default=0.001, metavar='LR', help='learning rate (default: 0.001)') parser.add_argument('--wd', help='weight decay parameter;', type=float, default=0.001) parser.add_argument('--epochs', type=int, default=5, metavar='EP', help='how many epochs will be trained locally') parser.add_argument('--comm_round', type=int, default=10, help='how many round of communications we shoud use') parser.add_argument('--is_mobile', type=int, default=0, help='whether the program is running on the FedML-Mobile server side') parser.add_argument('--frequency_of_the_test', type=int, default=1, help='the frequency of the algorithms') parser.add_argument('--gpu_server_num', type=int, default=1, help='gpu_server_num') parser.add_argument('--gpu_num_per_server', type=int, default=4, help='gpu_num_per_server') parser.add_argument('--gpu_mapping_file', type=str, default="gpu_mapping.yaml", help='the gpu utilization file for servers and clients. If there is no \ gpu_util_file, gpu will not be used.') parser.add_argument('--gpu_mapping_key', type=str, default="mapping_default", help='the key in gpu utilization file') parser.add_argument('--ci', type=int, default=0, help='CI') args = parser.parse_args() return args def load_data(args, dataset_name): if dataset_name == "mnist": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_mnist(args.batch_size) """ For shallow NN or linear models, we uniformly sample a fraction of clients each round (as the original FedAvg paper) """ args.client_num_in_total = client_num elif dataset_name == "femnist": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_federated_emnist(args.dataset, args.data_dir) args.client_num_in_total = client_num elif dataset_name == "shakespeare": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_shakespeare(args.batch_size) args.client_num_in_total = client_num elif dataset_name == "fed_shakespeare": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_federated_shakespeare(args.dataset, args.data_dir) args.client_num_in_total = client_num elif dataset_name == "fed_cifar100": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_federated_cifar100(args.dataset, args.data_dir) args.client_num_in_total = client_num elif dataset_name == "stackoverflow_lr": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_federated_stackoverflow_lr(args.dataset, args.data_dir) args.client_num_in_total = client_num elif dataset_name == "stackoverflow_nwp": logging.info("load_data. dataset_name = %s" % dataset_name) client_num, train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_federated_stackoverflow_nwp(args.dataset, args.data_dir) args.client_num_in_total = client_num elif dataset_name == "ILSVRC2012": logging.info("load_data. dataset_name = %s" % dataset_name) train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_ImageNet(dataset=dataset_name, data_dir=args.data_dir, partition_method=None, partition_alpha=None, client_number=args.client_num_in_total, batch_size=args.batch_size) elif dataset_name == "gld23k": logging.info("load_data. dataset_name = %s" % dataset_name) args.client_num_in_total = 233 fed_train_map_file = os.path.join(args.data_dir, 'mini_gld_train_split.csv') fed_test_map_file = os.path.join(args.data_dir, 'mini_gld_test.csv') args.data_dir = os.path.join(args.data_dir, 'images') train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_landmarks(dataset=dataset_name, data_dir=args.data_dir, fed_train_map_file=fed_train_map_file, fed_test_map_file=fed_test_map_file, partition_method=None, partition_alpha=None, client_number=args.client_num_in_total, batch_size=args.batch_size) elif dataset_name == "gld160k": logging.info("load_data. dataset_name = %s" % dataset_name) args.client_num_in_total = 1262 fed_train_map_file = os.path.join(args.data_dir, 'federated_train.csv') fed_test_map_file = os.path.join(args.data_dir, 'test.csv') args.data_dir = os.path.join(args.data_dir, 'images') train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = load_partition_data_landmarks(dataset=dataset_name, data_dir=args.data_dir, fed_train_map_file=fed_train_map_file, fed_test_map_file=fed_test_map_file, partition_method=None, partition_alpha=None, client_number=args.client_num_in_total, batch_size=args.batch_size) else: if dataset_name == "cifar10": data_loader = load_partition_data_cifar10 elif dataset_name == "cifar100": data_loader = load_partition_data_cifar100 elif dataset_name == "cinic10": data_loader = load_partition_data_cinic10 else: data_loader = load_partition_data_cifar10 train_data_num, test_data_num, train_data_global, test_data_global, \ train_data_local_num_dict, train_data_local_dict, test_data_local_dict, \ class_num = data_loader(args.dataset, args.data_dir, args.partition_method, args.partition_alpha, args.client_num_in_total, args.batch_size) dataset = [train_data_num, test_data_num, train_data_global, test_data_global, train_data_local_num_dict, train_data_local_dict, test_data_local_dict, class_num] return dataset def create_model(args, model_name, output_dim): logging.info("create_model. model_name = %s, output_dim = %s" % (model_name, output_dim)) model = None if model_name == "lr" and args.dataset == "mnist": logging.info("LogisticRegression + MNIST") model = LogisticRegression(28 * 28, output_dim) elif model_name == "rnn" and args.dataset == "shakespeare": logging.info("RNN + shakespeare") model = RNN_OriginalFedAvg() elif model_name == "cnn" and args.dataset == "femnist": logging.info("CNN + FederatedEMNIST") model = CNN_DropOut(False) elif model_name == "resnet18_gn" and args.dataset == "fed_cifar100": logging.info("ResNet18_GN + Federated_CIFAR100") model = resnet18() elif model_name == "rnn" and args.dataset == "fed_shakespeare": logging.info("RNN + fed_shakespeare") model = RNN_OriginalFedAvg() elif model_name == "lr" and args.dataset == "stackoverflow_lr": logging.info("lr + stackoverflow_lr") model = LogisticRegression(10004, output_dim) elif model_name == "rnn" and args.dataset == "stackoverflow_nwp": logging.info("CNN + stackoverflow_nwp") model = RNN_StackOverFlow() elif model_name == "resnet56": model = resnet56(class_num=output_dim) elif model_name == "mobilenet": model = mobilenet(class_num=output_dim) # TODO elif model_name == 'mobilenet_v3': '''model_mode \in {LARGE: 5.15M, SMALL: 2.94M}''' model = MobileNetV3(model_mode='LARGE') elif model_name == 'efficientnet': model = EfficientNet() return model if __name__ == "__main__": # initialize distributed computing (MPI) comm, process_id, worker_number = FedML_init() # parse python script input parameters parser = argparse.ArgumentParser() args = add_args(parser) logging.info(args) # customize the process name str_process_name = "FedAvg (distributed):" + str(process_id) setproctitle.setproctitle(str_process_name) # customize the log format # logging.basicConfig(level=logging.INFO, logging.basicConfig(level=logging.DEBUG, format=str( process_id) + ' - %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S') hostname = socket.gethostname() logging.info("#############process ID = " + str(process_id) + ", host name = " + hostname + "########" + ", process ID = " + str(os.getpid()) + ", process Name = " + str(psutil.Process(os.getpid()))) # initialize the wandb machine learning experimental tracking platform (https://www.wandb.com/). if process_id == 0: wandb.init( # project="federated_nas", project="fedml", name="FedAVG(d)" + str(args.partition_method) + "r" + str(args.comm_round) + "-e" + str( args.epochs) + "-lr" + str( args.lr), config=args ) # Set the random seed. The np.random seed determines the dataset partition. # The torch_manual_seed determines the initial weight. # We fix these two, so that we can reproduce the result. random.seed(0) np.random.seed(0) torch.manual_seed(0) torch.cuda.manual_seed_all(0) # Please check "GPU_MAPPING.md" to see how to define the topology logging.info("process_id = %d, size = %d" % (process_id, worker_number)) device = mapping_processes_to_gpu_device_from_yaml_file(process_id, worker_number, args.gpu_mapping_file, args.gpu_mapping_key) # load data dataset = load_data(args, args.dataset) [train_data_num, test_data_num, train_data_global, test_data_global, train_data_local_num_dict, train_data_local_dict, test_data_local_dict, class_num] = dataset # create model. # Note if the model is DNN (e.g., ResNet), the training will be very slow. # In this case, please use our FedML distributed version (./fedml_experiments/distributed_fedavg) model = create_model(args, model_name=args.model, output_dim=dataset[7]) try: # start "federated averaging (FedAvg)" FedML_FedAvg_distributed(process_id, worker_number, device, comm, model, train_data_num, train_data_global, test_data_global, train_data_local_num_dict, train_data_local_dict, test_data_local_dict, args) except Exception as e: print(e) logging.info('traceback.format_exc():\n%s' % traceback.format_exc()) MPI.COMM_WORLD.Abort()
0.441432
0.173113
"""End-to-end tests for federated trainer tasks.""" import collections import os.path from absl.testing import parameterized import tensorflow as tf import tensorflow_federated as tff from optimization.cifar100 import federated_cifar100 from optimization.emnist import federated_emnist from optimization.emnist_ae import federated_emnist_ae from optimization.shakespeare import federated_shakespeare from optimization.shared import fed_avg_schedule from optimization.stackoverflow import federated_stackoverflow from optimization.stackoverflow_lr import federated_stackoverflow_lr def iterative_process_builder(model_fn, client_weight_fn=None): return fed_avg_schedule.build_fed_avg_process( model_fn=model_fn, client_optimizer_fn=tf.keras.optimizers.SGD, client_lr=0.1, server_optimizer_fn=tf.keras.optimizers.SGD, server_lr=1.0, client_weight_fn=client_weight_fn) class FederatedTasksTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('cifar100', federated_cifar100.run_federated), ('emnist_cr', federated_emnist.run_federated), ('emnist_ae', federated_emnist_ae.run_federated), ('shakespeare', federated_shakespeare.run_federated), ('stackoverflow_nwp', federated_stackoverflow.run_federated), ('stackoverflow_lr', federated_stackoverflow_lr.run_federated), ) def test_run_federated(self, run_federated_fn): total_rounds = 1 shared_args = collections.OrderedDict( client_epochs_per_round=1, client_batch_size=10, clients_per_round=1, client_datasets_random_seed=1, total_rounds=total_rounds, iterative_process_builder=iterative_process_builder, rounds_per_checkpoint=10, rounds_per_eval=10) root_output_dir = self.get_temp_dir() exp_name = 'test_run_federated' shared_args['root_output_dir'] = root_output_dir shared_args['experiment_name'] = exp_name run_federated_fn(**shared_args) results_dir = os.path.join(root_output_dir, 'results', exp_name) self.assertTrue(tf.io.gfile.exists(results_dir)) scalar_manager = tff.simulation.CSVMetricsManager( os.path.join(results_dir, 'experiment.metrics.csv')) fieldnames, metrics = scalar_manager.get_metrics() self.assertIn( 'train/loss', fieldnames, msg='The output metrics should have a `train/loss` column if training ' 'is successful.') self.assertIn( 'eval/loss', fieldnames, msg='The output metrics should have a `train/loss` column if validation' ' metrics computation is successful.') self.assertIn( 'test/loss', fieldnames, msg='The output metrics should have a `test/loss` column if test ' 'metrics computation is successful.') self.assertLen( metrics, total_rounds + 1, msg='The number of rows in the metrics CSV should be the number of ' 'training rounds + 1 (as there is an extra row for validation/test set' 'metrics after training has completed.') if __name__ == '__main__': tf.test.main()
optimization/main/federated_tasks_test.py
"""End-to-end tests for federated trainer tasks.""" import collections import os.path from absl.testing import parameterized import tensorflow as tf import tensorflow_federated as tff from optimization.cifar100 import federated_cifar100 from optimization.emnist import federated_emnist from optimization.emnist_ae import federated_emnist_ae from optimization.shakespeare import federated_shakespeare from optimization.shared import fed_avg_schedule from optimization.stackoverflow import federated_stackoverflow from optimization.stackoverflow_lr import federated_stackoverflow_lr def iterative_process_builder(model_fn, client_weight_fn=None): return fed_avg_schedule.build_fed_avg_process( model_fn=model_fn, client_optimizer_fn=tf.keras.optimizers.SGD, client_lr=0.1, server_optimizer_fn=tf.keras.optimizers.SGD, server_lr=1.0, client_weight_fn=client_weight_fn) class FederatedTasksTest(tf.test.TestCase, parameterized.TestCase): @parameterized.named_parameters( ('cifar100', federated_cifar100.run_federated), ('emnist_cr', federated_emnist.run_federated), ('emnist_ae', federated_emnist_ae.run_federated), ('shakespeare', federated_shakespeare.run_federated), ('stackoverflow_nwp', federated_stackoverflow.run_federated), ('stackoverflow_lr', federated_stackoverflow_lr.run_federated), ) def test_run_federated(self, run_federated_fn): total_rounds = 1 shared_args = collections.OrderedDict( client_epochs_per_round=1, client_batch_size=10, clients_per_round=1, client_datasets_random_seed=1, total_rounds=total_rounds, iterative_process_builder=iterative_process_builder, rounds_per_checkpoint=10, rounds_per_eval=10) root_output_dir = self.get_temp_dir() exp_name = 'test_run_federated' shared_args['root_output_dir'] = root_output_dir shared_args['experiment_name'] = exp_name run_federated_fn(**shared_args) results_dir = os.path.join(root_output_dir, 'results', exp_name) self.assertTrue(tf.io.gfile.exists(results_dir)) scalar_manager = tff.simulation.CSVMetricsManager( os.path.join(results_dir, 'experiment.metrics.csv')) fieldnames, metrics = scalar_manager.get_metrics() self.assertIn( 'train/loss', fieldnames, msg='The output metrics should have a `train/loss` column if training ' 'is successful.') self.assertIn( 'eval/loss', fieldnames, msg='The output metrics should have a `train/loss` column if validation' ' metrics computation is successful.') self.assertIn( 'test/loss', fieldnames, msg='The output metrics should have a `test/loss` column if test ' 'metrics computation is successful.') self.assertLen( metrics, total_rounds + 1, msg='The number of rows in the metrics CSV should be the number of ' 'training rounds + 1 (as there is an extra row for validation/test set' 'metrics after training has completed.') if __name__ == '__main__': tf.test.main()
0.838944
0.402627
import re # noqa: F401 from xero_python.models import BaseModel class EmployeeLeaveBalance(BaseModel): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { "name": "str", "leave_type_id": "str", "balance": "float", "type_of_units": "str", } attribute_map = { "name": "name", "leave_type_id": "leaveTypeID", "balance": "balance", "type_of_units": "typeOfUnits", } def __init__( self, name=None, leave_type_id=None, balance=None, type_of_units=None ): # noqa: E501 """EmployeeLeaveBalance - a model defined in OpenAPI""" # noqa: E501 self._name = None self._leave_type_id = None self._balance = None self._type_of_units = None self.discriminator = None if name is not None: self.name = name if leave_type_id is not None: self.leave_type_id = leave_type_id if balance is not None: self.balance = balance if type_of_units is not None: self.type_of_units = type_of_units @property def name(self): """Gets the name of this EmployeeLeaveBalance. # noqa: E501 Name of the leave type. # noqa: E501 :return: The name of this EmployeeLeaveBalance. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this EmployeeLeaveBalance. Name of the leave type. # noqa: E501 :param name: The name of this EmployeeLeaveBalance. # noqa: E501 :type: str """ self._name = name @property def leave_type_id(self): """Gets the leave_type_id of this EmployeeLeaveBalance. # noqa: E501 The Xero identifier for leave type # noqa: E501 :return: The leave_type_id of this EmployeeLeaveBalance. # noqa: E501 :rtype: str """ return self._leave_type_id @leave_type_id.setter def leave_type_id(self, leave_type_id): """Sets the leave_type_id of this EmployeeLeaveBalance. The Xero identifier for leave type # noqa: E501 :param leave_type_id: The leave_type_id of this EmployeeLeaveBalance. # noqa: E501 :type: str """ self._leave_type_id = leave_type_id @property def balance(self): """Gets the balance of this EmployeeLeaveBalance. # noqa: E501 The employees current balance for the corresponding leave type. # noqa: E501 :return: The balance of this EmployeeLeaveBalance. # noqa: E501 :rtype: float """ return self._balance @balance.setter def balance(self, balance): """Sets the balance of this EmployeeLeaveBalance. The employees current balance for the corresponding leave type. # noqa: E501 :param balance: The balance of this EmployeeLeaveBalance. # noqa: E501 :type: float """ self._balance = balance @property def type_of_units(self): """Gets the type_of_units of this EmployeeLeaveBalance. # noqa: E501 The type of the units of the leave. # noqa: E501 :return: The type_of_units of this EmployeeLeaveBalance. # noqa: E501 :rtype: str """ return self._type_of_units @type_of_units.setter def type_of_units(self, type_of_units): """Sets the type_of_units of this EmployeeLeaveBalance. The type of the units of the leave. # noqa: E501 :param type_of_units: The type_of_units of this EmployeeLeaveBalance. # noqa: E501 :type: str """ self._type_of_units = type_of_units
xero_python/payrolluk/models/employee_leave_balance.py
import re # noqa: F401 from xero_python.models import BaseModel class EmployeeLeaveBalance(BaseModel): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { "name": "str", "leave_type_id": "str", "balance": "float", "type_of_units": "str", } attribute_map = { "name": "name", "leave_type_id": "leaveTypeID", "balance": "balance", "type_of_units": "typeOfUnits", } def __init__( self, name=None, leave_type_id=None, balance=None, type_of_units=None ): # noqa: E501 """EmployeeLeaveBalance - a model defined in OpenAPI""" # noqa: E501 self._name = None self._leave_type_id = None self._balance = None self._type_of_units = None self.discriminator = None if name is not None: self.name = name if leave_type_id is not None: self.leave_type_id = leave_type_id if balance is not None: self.balance = balance if type_of_units is not None: self.type_of_units = type_of_units @property def name(self): """Gets the name of this EmployeeLeaveBalance. # noqa: E501 Name of the leave type. # noqa: E501 :return: The name of this EmployeeLeaveBalance. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this EmployeeLeaveBalance. Name of the leave type. # noqa: E501 :param name: The name of this EmployeeLeaveBalance. # noqa: E501 :type: str """ self._name = name @property def leave_type_id(self): """Gets the leave_type_id of this EmployeeLeaveBalance. # noqa: E501 The Xero identifier for leave type # noqa: E501 :return: The leave_type_id of this EmployeeLeaveBalance. # noqa: E501 :rtype: str """ return self._leave_type_id @leave_type_id.setter def leave_type_id(self, leave_type_id): """Sets the leave_type_id of this EmployeeLeaveBalance. The Xero identifier for leave type # noqa: E501 :param leave_type_id: The leave_type_id of this EmployeeLeaveBalance. # noqa: E501 :type: str """ self._leave_type_id = leave_type_id @property def balance(self): """Gets the balance of this EmployeeLeaveBalance. # noqa: E501 The employees current balance for the corresponding leave type. # noqa: E501 :return: The balance of this EmployeeLeaveBalance. # noqa: E501 :rtype: float """ return self._balance @balance.setter def balance(self, balance): """Sets the balance of this EmployeeLeaveBalance. The employees current balance for the corresponding leave type. # noqa: E501 :param balance: The balance of this EmployeeLeaveBalance. # noqa: E501 :type: float """ self._balance = balance @property def type_of_units(self): """Gets the type_of_units of this EmployeeLeaveBalance. # noqa: E501 The type of the units of the leave. # noqa: E501 :return: The type_of_units of this EmployeeLeaveBalance. # noqa: E501 :rtype: str """ return self._type_of_units @type_of_units.setter def type_of_units(self, type_of_units): """Sets the type_of_units of this EmployeeLeaveBalance. The type of the units of the leave. # noqa: E501 :param type_of_units: The type_of_units of this EmployeeLeaveBalance. # noqa: E501 :type: str """ self._type_of_units = type_of_units
0.784773
0.140631
import numpy as np import scipy.linalg as spla from scipy.spatial.distance import cdist def chol2inv(chol): return spla.cho_solve((chol, False), np.eye(chol.shape[ 0 ])) def matrixInverse(M): return chol2inv(spla.cholesky(M, lower=False)) def compute_kernel(lls, lsf, x, z): ls = np.exp(lls) sf = np.exp(lsf) if x.ndim == 1: x= x[ None, : ] if z.ndim == 1: z= z[ None, : ] r2 = cdist(x, z, 'seuclidean', V = ls)**2.0 k = sf * np.exp(-0.5*r2) return k def compute_psi1(lls, lsf, xmean, xvar, z): if xmean.ndim == 1: xmean = xmean[ None, : ] ls = np.exp(lls) sf = np.exp(lsf) lspxvar = ls + xvar constterm1 = ls / lspxvar constterm2 = np.prod(np.sqrt(constterm1)) r2_psi1 = cdist(xmean, z, 'seuclidean', V = lspxvar)**2.0 psi1 = sf*constterm2*np.exp(-0.5*r2_psi1) return psi1 def compute_psi2(lls, lsf, xmean, xvar, z): ls = np.exp(lls) sf = np.exp(lsf) lsp2xvar = ls + 2.0 * xvar constterm1 = ls / lsp2xvar constterm2 = np.prod(np.sqrt(constterm1)) n_psi = z.shape[ 0 ] v_ones_n_psi = np.ones(n_psi) v_ones_dim = np.ones(z.shape[ 1 ]) D = ls Dnew = ls / 2.0 Btilde = 1.0 / (Dnew + xvar) Vtilde = Btilde - 1.0 / Dnew Qtilde = 1.0 / D + 0.25 * Vtilde T1 = -0.5 * np.outer(np.dot((z**2) * np.outer(v_ones_n_psi, Qtilde), v_ones_dim), v_ones_n_psi) T2 = +0.5 * np.outer(np.dot(z, xmean * Btilde), v_ones_n_psi) T3 = -0.25 * np.dot(z * np.outer(v_ones_n_psi, Vtilde), z.T) T4 = -0.5 * np.sum((xmean**2) * Btilde) M = T1 + T1.T + T2 + T2.T + T3 + T4 psi2 = sf**2.0 * constterm2 * np.exp(M) return psi2 def d_trace_MKzz_dhypers(lls, lsf, z, M, Kzz): dKzz_dlsf = Kzz ls = np.exp(lls) # This is extracted from the R-code of Scalable EP for GP Classification by DHL and JMHL gr_lsf = np.sum(M * dKzz_dlsf) # This uses the vact that the distance is v^21^T - vv^T + 1v^2^T, where v is a vector with the l-dimension # of the inducing points. Ml = 0.5 * M * Kzz Xl = z * np.outer(np.ones(z.shape[ 0 ]), 1.0 / np.sqrt(ls)) gr_lls = np.dot(np.ones(Ml.shape[ 0 ]), np.dot(Ml.T, Xl**2)) + np.dot(np.ones(Ml.shape[ 0 ]), np.dot(Ml, Xl**2)) \ - 2.0 * np.dot(np.ones(Xl.shape[ 0 ]), (Xl * np.dot(Ml, Xl))) Xbar = z * np.outer(np.ones(z.shape[ 0 ]), 1.0 / ls) Mbar1 = - M.T * Kzz Mbar2 = - M * Kzz gr_z = (Xbar * np.outer(np.dot(np.ones(Mbar1.shape[ 0 ]) , Mbar1), np.ones(Xbar.shape[ 1 ])) - np.dot(Mbar1, Xbar)) +\ (Xbar * np.outer(np.dot(np.ones(Mbar2.shape[ 0 ]) , Mbar2), np.ones(Xbar.shape[ 1 ])) - np.dot(Mbar2, Xbar)) # The cost of this function is dominated by five matrix multiplications with cost M^2 * D each where D is # the dimensionality of the data!!! return gr_lsf, gr_lls, gr_z
numpy/deepgp_approxep/EQ_kernel.py
import numpy as np import scipy.linalg as spla from scipy.spatial.distance import cdist def chol2inv(chol): return spla.cho_solve((chol, False), np.eye(chol.shape[ 0 ])) def matrixInverse(M): return chol2inv(spla.cholesky(M, lower=False)) def compute_kernel(lls, lsf, x, z): ls = np.exp(lls) sf = np.exp(lsf) if x.ndim == 1: x= x[ None, : ] if z.ndim == 1: z= z[ None, : ] r2 = cdist(x, z, 'seuclidean', V = ls)**2.0 k = sf * np.exp(-0.5*r2) return k def compute_psi1(lls, lsf, xmean, xvar, z): if xmean.ndim == 1: xmean = xmean[ None, : ] ls = np.exp(lls) sf = np.exp(lsf) lspxvar = ls + xvar constterm1 = ls / lspxvar constterm2 = np.prod(np.sqrt(constterm1)) r2_psi1 = cdist(xmean, z, 'seuclidean', V = lspxvar)**2.0 psi1 = sf*constterm2*np.exp(-0.5*r2_psi1) return psi1 def compute_psi2(lls, lsf, xmean, xvar, z): ls = np.exp(lls) sf = np.exp(lsf) lsp2xvar = ls + 2.0 * xvar constterm1 = ls / lsp2xvar constterm2 = np.prod(np.sqrt(constterm1)) n_psi = z.shape[ 0 ] v_ones_n_psi = np.ones(n_psi) v_ones_dim = np.ones(z.shape[ 1 ]) D = ls Dnew = ls / 2.0 Btilde = 1.0 / (Dnew + xvar) Vtilde = Btilde - 1.0 / Dnew Qtilde = 1.0 / D + 0.25 * Vtilde T1 = -0.5 * np.outer(np.dot((z**2) * np.outer(v_ones_n_psi, Qtilde), v_ones_dim), v_ones_n_psi) T2 = +0.5 * np.outer(np.dot(z, xmean * Btilde), v_ones_n_psi) T3 = -0.25 * np.dot(z * np.outer(v_ones_n_psi, Vtilde), z.T) T4 = -0.5 * np.sum((xmean**2) * Btilde) M = T1 + T1.T + T2 + T2.T + T3 + T4 psi2 = sf**2.0 * constterm2 * np.exp(M) return psi2 def d_trace_MKzz_dhypers(lls, lsf, z, M, Kzz): dKzz_dlsf = Kzz ls = np.exp(lls) # This is extracted from the R-code of Scalable EP for GP Classification by DHL and JMHL gr_lsf = np.sum(M * dKzz_dlsf) # This uses the vact that the distance is v^21^T - vv^T + 1v^2^T, where v is a vector with the l-dimension # of the inducing points. Ml = 0.5 * M * Kzz Xl = z * np.outer(np.ones(z.shape[ 0 ]), 1.0 / np.sqrt(ls)) gr_lls = np.dot(np.ones(Ml.shape[ 0 ]), np.dot(Ml.T, Xl**2)) + np.dot(np.ones(Ml.shape[ 0 ]), np.dot(Ml, Xl**2)) \ - 2.0 * np.dot(np.ones(Xl.shape[ 0 ]), (Xl * np.dot(Ml, Xl))) Xbar = z * np.outer(np.ones(z.shape[ 0 ]), 1.0 / ls) Mbar1 = - M.T * Kzz Mbar2 = - M * Kzz gr_z = (Xbar * np.outer(np.dot(np.ones(Mbar1.shape[ 0 ]) , Mbar1), np.ones(Xbar.shape[ 1 ])) - np.dot(Mbar1, Xbar)) +\ (Xbar * np.outer(np.dot(np.ones(Mbar2.shape[ 0 ]) , Mbar2), np.ones(Xbar.shape[ 1 ])) - np.dot(Mbar2, Xbar)) # The cost of this function is dominated by five matrix multiplications with cost M^2 * D each where D is # the dimensionality of the data!!! return gr_lsf, gr_lls, gr_z
0.579638
0.640833
# pylint: disable-msg=C6310 """Channel Tic Tac Toe This module demonstrates the App Engine Channel API by implementing a simple tic-tac-toe game. """ import datetime import logging import os import random import re import uuid import sys from django.utils import simplejson from google.appengine.api import channel from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app class Game(db.Model): """All the data we store for a game""" userX = db.StringProperty() userO = db.StringProperty() board = db.StringProperty() moveX = db.BooleanProperty() winner = db.StringProperty() winning_board = db.StringProperty() class Wins(): x_win_patterns = ['XXX......', '...XXX...', '......XXX', 'X..X..X..', '.X..X..X.', '..X..X..X', 'X...X...X', '..X.X.X..'] o_win_patterns = map(lambda s: s.replace('X','O'), x_win_patterns) x_wins = map(lambda s: re.compile(s), x_win_patterns) o_wins = map(lambda s: re.compile(s), o_win_patterns) class GameUpdater(): game = None def __init__(self, game): self.game = game def get_game_message(self): gameUpdate = { 'board': self.game.board, 'userX': self.game.userX, 'userO': '' if not self.game.userO else self.game.userO, 'moveX': self.game.moveX, 'winner': self.game.winner, 'winningBoard': self.game.winning_board } return simplejson.dumps(gameUpdate) def send_update(self): message = self.get_game_message() channel.send_message(self.game.userX + self.game.key().id_or_name(), message) if self.game.userO: channel.send_message(self.game.userO + self.game.key().id_or_name(), message) def check_win(self): if self.game.moveX: # O just moved, check for O wins wins = Wins().o_wins potential_winner = self.game.userO else: # X just moved, check for X wins wins = Wins().x_wins potential_winner = self.game.userX for win in wins: if win.match(self.game.board): self.game.winner = potential_winner self.game.winning_board = win.pattern return def make_move(self, position, user): if position >= 0 and user == self.game.userX or user == self.game.userO: if self.game.moveX == (user == self.game.userX): boardList = list(self.game.board) if (boardList[position] == ' '): boardList[position] = 'X' if self.game.moveX else 'O' self.game.board = "".join(boardList) self.game.moveX = not self.game.moveX self.check_win() self.game.put() self.send_update() return class GameFromRequest(): game = None; user = None; def __init__(self, request): self.user = request.get('u') game_key = request.get('g') if game_key: self.game = Game.get_by_key_name(game_key) def get_game_data(self): return ( self.game, self.user ) class MovePage(webapp.RequestHandler): def post(self): (game, user) = GameFromRequest(self.request).get_game_data() if game and user: id = int(self.request.get('i')) GameUpdater(game).make_move(id, user) class OpenedPage(webapp.RequestHandler): def post(self): (game, user) = GameFromRequest(self.request).get_game_data() GameUpdater(game).send_update() class MainPage(webapp.RequestHandler): """The main UI page, renders the 'index.html' template.""" def get(self): """Renders the main page. When this page is shown, we create a new channel to push asynchronous updates to the client.""" game_key = self.request.get('g') game = None user = None if game_key: game = Game.get_by_key_name(game_key) if game: user = game.userO if not user: user = uuid.uuid4().hex game.userO = user game.put() if not game: game_key = <KEY> user = uuid.uuid4().hex game = Game(key_name = game_key, moveX = True, userX = user, complete = False, board = ' ') game.put() game_link = 'http://localhost:8080/?g=' + game_key if game: token = channel.create_channel(user + game_key) values = {'token': token, 'me': user, 'game_key': game_key, 'game_link': game_link, 'initial_message': GameUpdater(game).get_game_message() } self.response.out.write(simplejson.dumps(values)) else: self.response.out.write(simplejson.dumps({'error': 'No such game'})) application = webapp.WSGIApplication([ ('/', MainPage), ('/opened', OpenedPage), ('/move', MovePage)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
apps/samples/appengine-channelapi/appengine/chatactoe.py
# pylint: disable-msg=C6310 """Channel Tic Tac Toe This module demonstrates the App Engine Channel API by implementing a simple tic-tac-toe game. """ import datetime import logging import os import random import re import uuid import sys from django.utils import simplejson from google.appengine.api import channel from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app class Game(db.Model): """All the data we store for a game""" userX = db.StringProperty() userO = db.StringProperty() board = db.StringProperty() moveX = db.BooleanProperty() winner = db.StringProperty() winning_board = db.StringProperty() class Wins(): x_win_patterns = ['XXX......', '...XXX...', '......XXX', 'X..X..X..', '.X..X..X.', '..X..X..X', 'X...X...X', '..X.X.X..'] o_win_patterns = map(lambda s: s.replace('X','O'), x_win_patterns) x_wins = map(lambda s: re.compile(s), x_win_patterns) o_wins = map(lambda s: re.compile(s), o_win_patterns) class GameUpdater(): game = None def __init__(self, game): self.game = game def get_game_message(self): gameUpdate = { 'board': self.game.board, 'userX': self.game.userX, 'userO': '' if not self.game.userO else self.game.userO, 'moveX': self.game.moveX, 'winner': self.game.winner, 'winningBoard': self.game.winning_board } return simplejson.dumps(gameUpdate) def send_update(self): message = self.get_game_message() channel.send_message(self.game.userX + self.game.key().id_or_name(), message) if self.game.userO: channel.send_message(self.game.userO + self.game.key().id_or_name(), message) def check_win(self): if self.game.moveX: # O just moved, check for O wins wins = Wins().o_wins potential_winner = self.game.userO else: # X just moved, check for X wins wins = Wins().x_wins potential_winner = self.game.userX for win in wins: if win.match(self.game.board): self.game.winner = potential_winner self.game.winning_board = win.pattern return def make_move(self, position, user): if position >= 0 and user == self.game.userX or user == self.game.userO: if self.game.moveX == (user == self.game.userX): boardList = list(self.game.board) if (boardList[position] == ' '): boardList[position] = 'X' if self.game.moveX else 'O' self.game.board = "".join(boardList) self.game.moveX = not self.game.moveX self.check_win() self.game.put() self.send_update() return class GameFromRequest(): game = None; user = None; def __init__(self, request): self.user = request.get('u') game_key = request.get('g') if game_key: self.game = Game.get_by_key_name(game_key) def get_game_data(self): return ( self.game, self.user ) class MovePage(webapp.RequestHandler): def post(self): (game, user) = GameFromRequest(self.request).get_game_data() if game and user: id = int(self.request.get('i')) GameUpdater(game).make_move(id, user) class OpenedPage(webapp.RequestHandler): def post(self): (game, user) = GameFromRequest(self.request).get_game_data() GameUpdater(game).send_update() class MainPage(webapp.RequestHandler): """The main UI page, renders the 'index.html' template.""" def get(self): """Renders the main page. When this page is shown, we create a new channel to push asynchronous updates to the client.""" game_key = self.request.get('g') game = None user = None if game_key: game = Game.get_by_key_name(game_key) if game: user = game.userO if not user: user = uuid.uuid4().hex game.userO = user game.put() if not game: game_key = <KEY> user = uuid.uuid4().hex game = Game(key_name = game_key, moveX = True, userX = user, complete = False, board = ' ') game.put() game_link = 'http://localhost:8080/?g=' + game_key if game: token = channel.create_channel(user + game_key) values = {'token': token, 'me': user, 'game_key': game_key, 'game_link': game_link, 'initial_message': GameUpdater(game).get_game_message() } self.response.out.write(simplejson.dumps(values)) else: self.response.out.write(simplejson.dumps({'error': 'No such game'})) application = webapp.WSGIApplication([ ('/', MainPage), ('/opened', OpenedPage), ('/move', MovePage)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
0.480722
0.081703
from jumpscale import j from zerorobot.template.base import TemplateBase from zerorobot.template.state import StateCheckError from zerorobot.service_collection import ServiceNotFoundError ZERODB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' NODE_CLIENT = 'local' class Vdisk(TemplateBase): version = '0.0.1' template_name = "vdisk" def __init__(self, name=None, guid=None, data=None): super().__init__(name=name, guid=guid, data=data) self.add_delete_callback(self.uninstall) self.recurring_action('_monitor', 10) if not self.data.get('password'): self.data['password'] = <PASSWORD>(32) def validate(self): try: # ensure that a node service exists node = self.api.services.get(template_account='threefoldtech', template_name='node') node.state.check('actions', 'install', 'ok') except: raise RuntimeError("not node service found, can't install the namespace") for param in ['diskType', 'size', 'label']: if not self.data.get(param): raise ValueError("parameter '%s' not valid: %s" % (param, str(self.data[param]))) @property def _node_sal(self): """ connection to the node """ return j.clients.zos.get(NODE_CLIENT) @property def _zerodb(self): return self.api.services.get(template_uid=ZERODB_TEMPLATE_UID, name=self.data['zerodb']) def _monitor(self): self.state.check('actions', 'install', 'ok') try: self._zerodb.state.check('status', 'running', 'ok') self.state.set('status', 'running', 'ok') except StateCheckError: data = { 'attributes': {}, 'resource': self.guid, 'text': 'Failed to start vdisk {}'.format(self.name), 'environment': 'Production', 'severity': 'critical', 'event': 'Hardware', 'tags': [], 'service': ['vdisk'] } alertas = self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1') for alerta in alertas: alerta.schedule_action('send_alert', args={'data': data}) self.state.delete('status', 'running') def install(self): try: # no op is already installed self.state.check('actions', 'install', 'ok') return except StateCheckError: pass node = self.api.services.get(template_account='threefoldtech', template_name='node') kwargs = { 'disktype': self.data['diskType'], 'mode': 'user', 'password': <PASSWORD>['password'], 'public': False, 'ns_size': int(self.data['size']), } # use the method on the node service to create the zdb and the namespace. # this action hold the logic of the capacity planning for the zdb and namespaces self.data['zerodb'], self.data['nsName'] = node.schedule_action('create_zdb_namespace', kwargs).wait(die=True).result zerodb_data = self._zerodb.data.copy() zerodb_data['name'] = self._zerodb.name zerodb_sal = self._node_sal.primitives.from_dict('zerodb', zerodb_data) disk = self._node_sal.primitives.create_disk(self.data['nsName'], zerodb_sal, mountpoint=self.data['mountPoint'] or None, filesystem=self.data['filesystem'] or None, size=int(self.data['size']), label=self.data['label']) disk.deploy() self.state.set('actions', 'install', 'ok') self.state.set('status', 'running', 'ok') def info(self): self.state.check('actions', 'install', 'ok') return self._zerodb.schedule_action('namespace_info', args={'name': self.data['nsName']}).wait(die=True).result def url(self): self.state.check('actions', 'install', 'ok') return self._zerodb.schedule_action('namespace_url', args={'name': self.data['nsName']}).wait(die=True).result def private_url(self): self.state.check('actions', 'install', 'ok') return self._zerodb.schedule_action('namespace_private_url', args={'name': self.data['nsName']}).wait(die=True).result def uninstall(self): self._zerodb.schedule_action('namespace_delete', args={'name': self.data['nsName']}).wait(die=True) self.state.delete('actions', 'install') self.state.delete('status', 'running')
templates/vdisk/vdisk.py
from jumpscale import j from zerorobot.template.base import TemplateBase from zerorobot.template.state import StateCheckError from zerorobot.service_collection import ServiceNotFoundError ZERODB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1' NODE_CLIENT = 'local' class Vdisk(TemplateBase): version = '0.0.1' template_name = "vdisk" def __init__(self, name=None, guid=None, data=None): super().__init__(name=name, guid=guid, data=data) self.add_delete_callback(self.uninstall) self.recurring_action('_monitor', 10) if not self.data.get('password'): self.data['password'] = <PASSWORD>(32) def validate(self): try: # ensure that a node service exists node = self.api.services.get(template_account='threefoldtech', template_name='node') node.state.check('actions', 'install', 'ok') except: raise RuntimeError("not node service found, can't install the namespace") for param in ['diskType', 'size', 'label']: if not self.data.get(param): raise ValueError("parameter '%s' not valid: %s" % (param, str(self.data[param]))) @property def _node_sal(self): """ connection to the node """ return j.clients.zos.get(NODE_CLIENT) @property def _zerodb(self): return self.api.services.get(template_uid=ZERODB_TEMPLATE_UID, name=self.data['zerodb']) def _monitor(self): self.state.check('actions', 'install', 'ok') try: self._zerodb.state.check('status', 'running', 'ok') self.state.set('status', 'running', 'ok') except StateCheckError: data = { 'attributes': {}, 'resource': self.guid, 'text': 'Failed to start vdisk {}'.format(self.name), 'environment': 'Production', 'severity': 'critical', 'event': 'Hardware', 'tags': [], 'service': ['vdisk'] } alertas = self.api.services.find(template_uid='github.com/threefoldtech/0-templates/alerta/0.0.1') for alerta in alertas: alerta.schedule_action('send_alert', args={'data': data}) self.state.delete('status', 'running') def install(self): try: # no op is already installed self.state.check('actions', 'install', 'ok') return except StateCheckError: pass node = self.api.services.get(template_account='threefoldtech', template_name='node') kwargs = { 'disktype': self.data['diskType'], 'mode': 'user', 'password': <PASSWORD>['password'], 'public': False, 'ns_size': int(self.data['size']), } # use the method on the node service to create the zdb and the namespace. # this action hold the logic of the capacity planning for the zdb and namespaces self.data['zerodb'], self.data['nsName'] = node.schedule_action('create_zdb_namespace', kwargs).wait(die=True).result zerodb_data = self._zerodb.data.copy() zerodb_data['name'] = self._zerodb.name zerodb_sal = self._node_sal.primitives.from_dict('zerodb', zerodb_data) disk = self._node_sal.primitives.create_disk(self.data['nsName'], zerodb_sal, mountpoint=self.data['mountPoint'] or None, filesystem=self.data['filesystem'] or None, size=int(self.data['size']), label=self.data['label']) disk.deploy() self.state.set('actions', 'install', 'ok') self.state.set('status', 'running', 'ok') def info(self): self.state.check('actions', 'install', 'ok') return self._zerodb.schedule_action('namespace_info', args={'name': self.data['nsName']}).wait(die=True).result def url(self): self.state.check('actions', 'install', 'ok') return self._zerodb.schedule_action('namespace_url', args={'name': self.data['nsName']}).wait(die=True).result def private_url(self): self.state.check('actions', 'install', 'ok') return self._zerodb.schedule_action('namespace_private_url', args={'name': self.data['nsName']}).wait(die=True).result def uninstall(self): self._zerodb.schedule_action('namespace_delete', args={'name': self.data['nsName']}).wait(die=True) self.state.delete('actions', 'install') self.state.delete('status', 'running')
0.591015
0.138666
import logging SUPPORTED_SCALING_FACTORS = [(7, 8), (3, 4), (5, 8), (1, 2), (3, 8), (1, 4), (1, 8)] _LOGGER = logging.getLogger(__name__) def scale_jpeg_camera_image(cam_image, width, height): """Scale a camera image as close as possible to one of the supported scaling factors.""" turbo_jpeg = TurboJPEGSingleton.instance() if not turbo_jpeg: return cam_image.content (current_width, current_height, _, _) = turbo_jpeg.decode_header(cam_image.content) if current_width <= width or current_height <= height: return cam_image.content ratio = width / current_width scaling_factor = SUPPORTED_SCALING_FACTORS[-1] for supported_sf in SUPPORTED_SCALING_FACTORS: if ratio >= (supported_sf[0] / supported_sf[1]): scaling_factor = supported_sf break return turbo_jpeg.scale_with_quality( cam_image.content, scaling_factor=scaling_factor, quality=75, ) class TurboJPEGSingleton: """ Load TurboJPEG only once. Ensures we do not log load failures each snapshot since camera image fetches happen every few seconds. """ __instance = None @staticmethod def instance(): """Singleton for TurboJPEG.""" if TurboJPEGSingleton.__instance is None: TurboJPEGSingleton() return TurboJPEGSingleton.__instance def __init__(self): """Try to create TurboJPEG only once.""" try: # TurboJPEG checks for libturbojpeg # when its created, but it imports # numpy which may or may not work so # we have to guard the import here. from turbojpeg import TurboJPEG # pylint: disable=import-outside-toplevel TurboJPEGSingleton.__instance = TurboJPEG() except Exception: # pylint: disable=broad-except _LOGGER.exception( "Error loading libturbojpeg; Cameras may impact HomeKit performance" ) TurboJPEGSingleton.__instance = False
homeassistant/components/homekit/img_util.py
import logging SUPPORTED_SCALING_FACTORS = [(7, 8), (3, 4), (5, 8), (1, 2), (3, 8), (1, 4), (1, 8)] _LOGGER = logging.getLogger(__name__) def scale_jpeg_camera_image(cam_image, width, height): """Scale a camera image as close as possible to one of the supported scaling factors.""" turbo_jpeg = TurboJPEGSingleton.instance() if not turbo_jpeg: return cam_image.content (current_width, current_height, _, _) = turbo_jpeg.decode_header(cam_image.content) if current_width <= width or current_height <= height: return cam_image.content ratio = width / current_width scaling_factor = SUPPORTED_SCALING_FACTORS[-1] for supported_sf in SUPPORTED_SCALING_FACTORS: if ratio >= (supported_sf[0] / supported_sf[1]): scaling_factor = supported_sf break return turbo_jpeg.scale_with_quality( cam_image.content, scaling_factor=scaling_factor, quality=75, ) class TurboJPEGSingleton: """ Load TurboJPEG only once. Ensures we do not log load failures each snapshot since camera image fetches happen every few seconds. """ __instance = None @staticmethod def instance(): """Singleton for TurboJPEG.""" if TurboJPEGSingleton.__instance is None: TurboJPEGSingleton() return TurboJPEGSingleton.__instance def __init__(self): """Try to create TurboJPEG only once.""" try: # TurboJPEG checks for libturbojpeg # when its created, but it imports # numpy which may or may not work so # we have to guard the import here. from turbojpeg import TurboJPEG # pylint: disable=import-outside-toplevel TurboJPEGSingleton.__instance = TurboJPEG() except Exception: # pylint: disable=broad-except _LOGGER.exception( "Error loading libturbojpeg; Cameras may impact HomeKit performance" ) TurboJPEGSingleton.__instance = False
0.803135
0.201401
from hangulize import * class Dutch(Language): """For transcribing Dutch.""" __iso639__ = {1: 'nl', 2: 'dut', 3: 'nld'} __tmp__ = '%,;&' vowels = 'aeEioOuUyQ' cs = 'b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'j', 'J', \ 'k', 'K', 'l', 'm', 'n', 'N', 'p', 'P', 'q', 'r', 's', 't', 'T', \ 'v', 'w', 'x', 'X', 'z', '%' # consonants son = 'lmnNrw' # sonorants short = 'aeEiouU' # short vowels notation = Notation([ (u'’', '\''), (' aan ', '/aan/'), ('^aan ', 'aan/'), (' bij ', '/bij/'), ('^bij ', 'bij/'), (' boven ', '/boven/'), ('^boven ', 'boven/'), (' en ', '/en/'), ('^en ', 'en/'), (' in ', '/in/'), ('^in ', 'in/'), (' op ', '/op/'), ('^op ', 'op/'), (' over ', '/over/'), ('^over ', 'over/'), (' of ', '/of/'), ('^de ', 'de/'), ('^den ', 'den/'), ('^der ', 'der/'), ('^des ', 'des/'), ('^di ', 'di/'), ('^het ', 'het/'), ('^onder ', 'onder/'), ('^sint ', 'sint/'), ('^te ', 'te/'), ('^ten ', 'ten/'), ('^ter ', 'ter/'), ('^thoe ', 'thoe/'), ('^tot ', 'tot/'), ('^uit ', 'uit/'), ('^uijt ', 'uijt/'), ('^van ', 'van/'), ('^ver ', 'ver/'), ('^voor ', 'voor/'), ('-', '/'), ('^\'s ', 's/'), ('^\'t ', 'Qt,/'), ('^\'t', 'Qt,'), ('hoek van/holland', 'hoek/van/holland'), ('hof van/twente', 'hof/van/twente'), ('ronde venen', 'ronde/venen'), ('^midden ', 'midden/'), ('^neder ', 'neder/'), ('^nieuw ', 'nieuw/'), ('^nieuwe ', 'nieuwe/'), ('^noord ', 'noord/'), ('^oost ', 'oost/'), ('^west ', 'west/'), ('^zuid ', 'zuid/'), (u'aimé', u'emé'), (u'curaçao', 'curaso'), ('curacao', 'curaso'), (u'française', 'frangsEzY'), ('francaise', 'frangsEzY'), (u'français', 'frangsE'), ('francais', 'frangsE'), (u'françoise', 'frangsoeazY'), ('francoise', 'frangsoeazY'), (u'françois', 'frangsoea'), ('francois', 'frangsoea'), (u'ç', 's'), (u'{@}ä{@}', '%a%'), (u'{@}ä', '%a'), (u'ä{@}', 'a%'), (u'ä', 'e'), (u'{@}ë{@}', '%e%'), (u'{@}ë', '%e'), (u'ë{@}', 'e%'), (u'ë', 'E'), (u'ée', 'ee'), (u'é', 'E'), (u'{@}ï{@}', '%i%'), (u'{@}ï', '%i'), (u'ï{@}', 'i%'), (u'ï', 'i'), (u'{@}ö{@}', '%o%'), (u'{@}ö', '%o'), (u'ö{@}', 'o%'), (u'ö', 'eu'), (u'{@}ü{@}', '%u%'), (u'{@}ü', '%u'), (u'ü{@}', 'u%'), (u'ü', 'u'), ('^{<cs>}ig', 'igg'), ('^{(<cs>)(<cs>)}ig', 'igg'), ('^{(<cs>)(<cs>)(<cs>)}ig', 'igg'), ('aalbes', 'aalbEs'), ('^aang', 'aan-g'), ('aapmens', 'aapmEns'), ('^abc$', 'abece'), ('adelbert', 'adelbErt'), ('ademtest', 'ademtEst'), ('adres', 'adrEs'), ('adrien', 'adriEn'), ('advocaat', 'aDvocaat'), ('aequo', 'equo'), ('aftershave', 'aftQrsjeev'), ('afvalrace', 'afvalrees'), ('agaath', 'agaat'), ('agath', 'agat'), ('ageeth', 'ageet'), ('ageth', 'aget'), ('^aim{e|ee}', 'em'), ('allerbest', 'allerbEst'), ('altsaxo', 'altYsaxo'), ('amanuens', 'amanu%ens'), ('amulet', 'amulEt'), ('ancien', 'anciEn'), ('andelst', 'andElst'), ('angina', 'anggina'), ('angli{c|st}', 'anggli'), ('angol{a|ees}', 'anggol'), ('anouk', 'anoek'), ('anthon', 'anton'), ('apothe{ek|k}', 'apote'), ('^apropos$', 'apropo'), ('^a propos$', 'apropo'), ('aquarel', 'aquarEl'), ('archipel', 'archipEl'), ('architect', 'architEct'), ('arrest', 'arrEst'), ('aspect', 'aspEct'), ('asbest', 'asbEst'), ('autorace', 'autorees'), ('baby', 'beeby'), ('badge', 'bezi'), ('badminton', 'bedminton'), ('bagage', 'bagaze'), ('bagatel', 'bagatEl'), ('bajonet', 'bajonEt'), ('^balpen', 'balpEn'), ('balth', 'balt'), ('banket', 'bankEt'), ('bankstel', 'bankstEl'), ('baret', 'barEt'), ('barkeep', 'barkip'), ('barones', 'baronEs'), ('barrage', 'barraze'), ('barthol', 'bartol'), ('baseball', 'beesbol'), ('bassin', 'bassEng'), ('beautycase', 'bJoetykees'), ('bed', 'bEd'), ('bEdekt', 'bedEkt'), ('beige', 'beize'), ('^beken', 'bekEn'), ('bekend', 'bekEnd'), ('berg', 'bErg'), ('besef', 'besEf'), ('besmet', 'besmEt'), ('beste{k|l|m}', 'bestE'), ('bevlek', 'bevlEk'), ('bijec', 'bi-jec'), ('bijou', 'bizoe'), ('biljet', 'biljEt'), ('bingo', 'bingGo'), ('biscuit', 'biscu%i'), ('bordes', 'bordEs'), ('bosbes', 'bosbEs'), ('boudier', 'boediE'), ('boulevard', 'boelevar'), ('bourgogne', 'boergonje'), ('bourgond', 'boergond'), ('bouvier', 'boeviE'), ('bowl', 'bol'), ('braille', 'braje'), ('brek', 'brEk'), ('breng', 'brEng'), ('budget', 'buzEt'), ('buffet', 'buffEt'), ('bungalowtent', 'bungalowtEnt'), ('bungalow', 'bungGalo'), ('cabaretier', 'cabarEtiE'), ('cabaret', 'cabarE'), ('cabriolet', 'cabriolEt'), ('cadet', 'cadEt'), ('caissiEre', 'cassiEre'), ('cake', 'keek'), ('cahier', 'cajE'), ('camouflage', 'camoeflaze'), ('campagne', 'campanje'), ('cantharel', 'cantarEl'), ('capuchon', 'capusjon'), ('cari%es', 'cariEs'), ('carillon', 'cariljon'), ('cashew', 'kesjoe'), ('cash', 'kesj'), ('castagnet', 'castanjet'), ('catheter', 'cateter'), ('^cees', 'kees'), ('chalet', 'sjalE'), ('champagne', 'sjampanje'), ('champignon', 'sjampinjon'), ('chantage', 'sjantaze'), ('chante{er|re}', 'sjante'), ('chaperon', 'sjaperon'), ('charcuterie', 'sjarcuterie'), ('charles', 'sjarl'), ('^charl', 'sjarl'), ('charmant', 'sjarmant'), ('chauffeur', 'sjoffeur'), ('cheque', 'sjEk'), ('cheryl', 'sjeryl'), ('chris', 'kris'), ('cologne', 'colonje'), ('compagn{i|y}', 'compan'), ('compagn', 'companj'), ('concertza{al|l}', 'concert-za'), ('conci%erge', 'conciErze'), ('concours', 'concoer'), ('concurrent', 'concurrEnt'), ('condens', 'condEns'), ('conferencier', 'conferangsiE'), ('conference', 'conferangs'), ('congres', 'conggrEs'), ('consequent', 'consequEnt'), ('consignatie', 'consinjatie'), ('contactlens', 'contactlEns'), ('container', 'conteener'), ('continue{er|r}', 'continu%e'), ('contour', 'contoer'), ('copyright', 'copyrajt'), ('cornedbeef', 'cornedbif'), ('corps', 'cor'), ('correct', 'corrEct'), ('corrige', 'corrize'), ('corsage', 'corsaze'), ('coulant', 'coelant'), ('coulisse', 'coelisse'), ('coup', 'coep'), ('courant', 'coerant'), ('coureur', 'coereur'), ('courgette', 'coerzette'), ('courtage', 'coertaze'), ('couture', 'coeture'), ('couturier', 'coeturiE'), ('couveuse', 'coeveuse'), ('cowboy', 'cauboy'), ('crash', 'crEsj'), ('crawl', 'crol'), ('crEche', 'crEsj'), ('crEme', 'crEm'), ('crime', 'crim'), ('croissant', 'croeassang'), ('croque', 'crok'), ('cursusjaar', 'cursusYjaar'), ('damhert', 'damhErt'), ('daniel', 'daniEl'), ('dani%el', 'daniEl'), ('dashboard', 'desjbord'), ('davidster', 'davit,ster'), ('debet', 'debEt'), ('decadent', 'decadEnt'), ('decibel', 'decibEl'), ('defect', 'defEct'), ('depot$', 'depo'), ('depots', 'depos'), ('dessert', 'dessEr'), ('dessin', 'dessEng'), ('detaillist', 'detajist'), ('detail', 'detaj'), ('detective', 'ditectiv'), ('diligence', 'dilizangce'), ('direct', 'dirEct'), ('discothe', 'discote'), ('discretie', 'discreti'), ('display', 'displey'), ('divers', 'divErs'), ('dividend', 'dividEnd'), ('doodstraf', 'dood%straf'), ('doodziek', 'dood%ziek'), ('doodzonde', 'dood%zonde'), ('doroth', 'dorot'), ('dossier', 'dossiE'), ('douan{e|i}', 'doean'), ('doubl', 'doebl'), ('douche$', 'doesj'), ('douche', 'doesje'), ('drenthe', 'drente'), ('drinkyoghurt', 'drinkYJoghurt'), ('drukpers', 'drukpErs'), ('drumstel', 'drumstEl'), ('^dumas$', 'duma'), ('dyk', 'dijk'), ('eerhestel', 'eerhestEl'), ('effect', 'effEct'), ('eicel', 'eicEl'), ('eindhoven', 'einthoven'), ('elektricien', 'elektriciEng'), ('^eljero', 'elzero'), ('employE', 'amploeajE'), ('enschede', 'enschedE'), ('ernst', 'Ernst'), ('erwt', 'Ert'), ('esther', 'ester'), ('etage', 'etaze'), ('etalage', 'etalaze'), ('ether', 'eter'), ('ethiek', 'etiek'), ('ethiop', 'etiop'), ('ethisch', 'etisch'), ('eugene', 'euzEn'), ('eurocent', 'eurocEnt'), ('euthanas', 'eutanas'), ('evacue{er|r}', 'evacu%e'), ('evangel', 'evanggel'), ('evengoed', 'even-goed'), ('examengeld', 'examen-gEld'), ('exces', 'excEs'), ('{~@}ex', 'Ex'), ('floret', 'florEt'), ('foetus', 'feutus'), ('forel', 'forEl'), ('forfait', 'forfE'), ('fokstier', 'fokstir'), ('formulier', 'formulir'), ('foyer', 'foeajE'), ('franchise', 'fransjize'), ('frangipane', 'frangzipane'), ('freak', 'fri-k'), ('freelancer', 'frilangcer'), ('freelance', 'frilangs'), ('freudia', 'froidia'), ('frikadel', 'frikadEl'), ('frou-frou', 'froe-froe'), ('fulltime', 'foeltajm'), ('funest', 'funEst'), ('gabriel', 'GabriEl'), ('gabri%el', 'GabriEl'), ('^game$', 'Geem'), ('^games$', 'Geems'), ('gameboy', 'Geemboy'), ('gebrek', 'gebrEk'), ('gelukwens', 'gelukwEns'), ('gemenebest', 'gemenebEst'), ('gemengd', 'gemEngd'), ('gEnant', 'zEnant'), ('gendarme', 'zangdarme'), ('genEve', 'zenEve'), ('genie$', 'zenie'), ('genie{%en|tj}', 'zenie'), ('genre', 'zangrY'), ('^giovan', 'zovan'), ('gogh', 'Gogh'), ('grens', 'grEns'), ('greth{a|e}', 'gret'), ('^guido', 'gido'), ('^hamel', 'hamEl'), ('hef', 'hEf'), ('hek', 'hEk'), ('hengst', 'hEngst'), ('ijssel', 'ijssQl'), ('israel', 'israEl'), ('isra%el', 'israEl'), ('jacques', 'zaak'), ('jeanette', 'zaanEt'), ('jeanet', 'zaanEt'), ('jeanne$', 'zaan'), ('jockey', 'zoki'), ('johannes', 'johannEs'), ('^john$', 'zon'), ('jozef', 'jozEf'), ('^beken', 'bekEn'), ('beken{d|t}', 'bekEn'), ('^erken', 'erkEn'), ('erken{d|t}', 'erkEn'), ('^herken', 'herkEn'), ('^ontken', 'ontkEn'), ('ontken{d|t}', 'ontkEn'), ('^toeken', 'toekEn'), ('toeken{d|t}', 'toekEn'), ('^verken', 'verkEn'), ('klem{d|t}', 'klEm'), ('korthal', 'kortal'), ('leg{d|t}', 'lEg'), ('lingerie', 'lengzerie'), ('lingu%ist', 'linggu%ist'), ('^louis$', 'loei'), ('^louis', 'loeis'), ('lyonnet', 'lyonnE'), ('manuel', 'manuEl'), ('^margot$', 'margo'), ('^mari%e', 'mariE'), ('marth', 'mart'), ('^mary$', 'mery'), ('mathild', 'matild'), ('melk', 'mElk'), ('merk', 'mErk'), ('michael', 'mikaEl'), ('micha%el', 'mikaEl'), ('^michel$', 'misjEl'), ('michiel', 'mikiEl'), ('michi%el', 'mikiEl'), ('model', 'modEl'), ('monsieur', 'mQsieu'), ('nerf', 'nErf'), ('^nigel', 'naizel'), ('^no%e', 'noE'), ('ongerust', 'onggerust'), ('orkest', 'orkEst'), ('pech', 'pEch'), ('persoonsbed', 'persoonsbEd'), ('pierre', 'piEr'), ('pincher', 'pinsjer'), ('posthum', 'postum'), ('rafael', 'rafaEl'), ('rafa%el', 'rafaEl'), ('recept', 'recEpt'), ('reinier', 'reini%er'), ('rhijn', 'rijn'), ('richard', 'rikard'), ('rogier', 'rogi%er'), ('ryan', 'raien'), ('scherm', 'schErm'), ('sharon', 'sjaron'), ('spel', 'spEl'), ('spionage', 'spionaze'), ('streng', 'strEng'), ('student', 'studEnt'), ('term', 'tErm'), ('the{a|o}', 'te'), ('thierry', 'tiErry'), ('thijs', 'tijs'), ('thys', 'tys'), ('timoth', 'timot'), ('toilette', 'toealEt'), ('toilet', 'toealEt'), ('tref', 'trEf'), ('trek', 'trEk'), ('van/Gogh', 'wan/Gogh'), ('vel{d|t}', 'vEl'), ('vEldhoven', 'vEld/hoven'), ('^vera$', 'wera'), ('veroni', 'weroni'), ('victor', 'wictor'), ('vincent', 'wincEnt'), ('viol', 'wiol'), ('vlek', 'vlEk'), ('weg', 'wEg'), ('wenst', 'wEnst'), ('^wens', 'wEns'), ('werk', 'wErk'), ('wesley', 'wesly'), ('wet', 'wEt'), ('^wt', 'uwt'), ('zet', 'zEt'), ('szoon', 's/zoon'), ('echt', 'Echt'), ('egd', 'Egd'), ('ent', 'Ent'), ('eau', 'o'), # common French spellings ('%e{l|ls|t|ts|tt|tts}$', 'E'), ('air', 'Er'), ('oir$', 'oear'), ('^ti', 'tiF'), ('tie{f|k}', 'ti'), ('tie$', 'sie'), ('tieus', 'sieus'), ('{n|r}tie$', 'sie'), ('ti{eel|%el}', 'si'), ('ti{aal|al}', 'si'), ('tion$', 'sjon'), ('tion{eel|%el}', 'sjon'), ('tione{er|r}', 'sjone'), ('tion{ne|s}', 'sjon'), ('tium', 'sium'), ('F', None), ('{<cs>}ig$', 'Qg'), ('{<cs>}igd$', 'Qgd'), ('{<cs>}igde$', 'Qgde'), ('{<cs>}ige$', 'Qge'), ('{<cs>}igen$', 'Qgen'), ('{<cs>}igheid$', 'Qgheid'), ('{<cs>}iging$', 'Qging'), ('^over', 'ovQr'), ('sch{@}', 'sX'), ('sch', 's'), ('ch', 'X'), ('c{e|E|i|y}', 's'), ('c', 'k'), ('qq', 'q'), ('qu', 'kw'), ('q', 'k'), ('x', 'ks'), ('ng', 'N'), ('nk', 'Nk'), ('dt$', 't'), ('dt{<cs>}', 't'), ('gh', 'g'), ('ph', 'p'), ('^th', 't'), ('^kh', 'k'), ('h{<cs>}', None), ('h$', None), ('sj{@}', 'sJ'), ('sj', 'si'), ('sz$', 's'), ('sz{<cs>}', 's'), ('ts', 'C'), ('tz', 'C'), ('^v', 'f'), ('uw', 'uW'), ('v$', 'f'), ('^y{@}', 'j'), ('y', 'i%'), ('z$', 's'), ('bb', 'b'), ('dd', 'd'), ('ff', 'f'), ('fv', 'f'), ('gg', 'g'), ('hh', 'h'), ('kk', 'k'), ('ll', 'l'), ('mm', 'm'), ('nn', 'n'), ('pp', 'p'), ('rr', 'r'), ('ss', 's'), ('tt', 't'), ('mbt', 'mt'), ('mpt', 'mt'), ('b$', '-p'), ('d$', '-t'), ('ds{~@}', 'C'), ('ds$', 'C'), ('dz{~@}', 'C'), ('dz$', 'C'), ('^ie{<cs>}', 'i'), ('{<cs>}ie{<cs>}', 'i'), ('^oe{<cs>}', 'U'), ('{<cs>}oe{<cs>}', 'U'), ('b{@|<son>|j}', 'B'), ('{<son>}b', 'B'), ('^{(<short>)}b{<cs>}', 'P'), ('{(<cs>)(<short>)}b{<cs>}', 'P'), ('B', 'b'), ('d{@|<son>|j}', 'D'), ('{<son>}d', 'D'), ('^{(<short>)}d{<cs>}', 'T'), ('{(<cs>)(<short>)}d{<cs>}', 'T'), ('D', 'd'), ('p{@|<son>|j}', 'F'), ('{<son>}p', 'F'), ('^{(<short>)}p{<cs>}', 'P'), ('{(<cs>)(<short>)}p{<cs>}', 'P'), ('^{(<short>)}p$', 'P'), ('{(<cs>)(<short>)}p$', 'P'), ('F', 'p'), ('t{@|<son>|j}', 'F'), ('{<son>}t', 'F'), ('^{(<short)>}t{<cs>}', 'T'), ('{(<cs>)(<short>)}t{<cs>}', 'T'), ('^{(<short>)}t$', 'T'), ('{(<cs>)(<short>)}t$', 'T'), ('F', 't'), ('k{@|<son>|j|v}', 'F'), ('{<son>}k', 'F'), ('^{(<short>)}k{<cs>}', 'K'), ('{(<cs>)(<short>)}k{<cs>}', 'K'), ('^{(<short>)}k$', 'K'), ('{(<cs>)(<short>)}k$', 'K'), ('F', 'k'), ('{~@}bj', 'bi%'), ('^bj', 'bi%'), ('{~@}dj', 'di%'), ('^dj', 'di%'), ('{~@}pj', 'pi%'), ('^pj', 'pi%'), ('{~@}tj', 'ti%'), ('^tj', 'ti%'), ('{~@}kj', 'ki%'), ('^kj', 'ki%'), ('{~@}rj', 'ri%'), ('^rj', 'ri%'), ('{b|d|p|t|k|r}j', 'Yj'), ('{@}ie', 'i%e'), ('w', 'v'), ('ae', 'aa'), ('aa', 'a'), ('auW', 'aU%'), ('au', 'aU%'), ('ouW', 'aU%'), ('ou', 'aU%'), ('{@}iji', 'i'), ('{@}ij{@}', 'i%j'), ('{@}ij', 'i%'), ('ij', 'ei'), ('eeuW', 'eiU%'), ('ieuW', 'iU%'), ('euW', 'e-u%'), ('iee', 'i%ee'), ('ee', 'ei'), ('oo', 'o'), ('ui', 'au%'), ('uy', 'au%'), ('eu', 'O%'), ('uee', 'u%ee'), ('ue', 'uu'), ('uW', 'uu%'), ('uu', 'u'), ('i%i', 'i'), ('ie', 'i'), ('ii', 'i'), ('oe', 'U'), ('-', None), ('e$', 'Q'), ('^e{(<cs>)}$', 'E'), ('^{(<cs>)}e{(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)}e{(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)(<cs>)}e{(<cs>)}$', 'E'), ('^e{(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)}e{(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)}e{(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)(<cs>)}e{(<cs>)(<cs>)}$', 'E'), ('^e{(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)}e{(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)}e{(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)(<cs>)}e{(<cs>)(<cs>)(<cs>)}$', 'E'), ('^e{(<cs>)(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)}e{(<cs>)(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)}e{(<cs>)(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)(<cs>)}e{(<cs>)(<cs>)(<cs>)(<cs>)}$', 'E'), ('{<cs>}e{(<cs>)}$', 'Q'), ('{<cs>}e{(<cs>)(<cs>)}$', 'Q'), ('{<cs>}e{(<cs>)(<cs>)(<cs>)}$', 'Q'), ('{<cs>}e{(<cs>)(<cs>)(<cs>)(<cs>)}$', 'Q'), ('E', 'e'), ('P', 'p,'), ('T', 't,'), ('K', 'k,'), ('j{@}', 'J'), ('j', 'i'), ('{C|z}J', None), ('^l', 'l;'), ('^m', 'm;'), ('^n', 'n;'), ('l$', 'l,'), ('m$', 'm,'), ('n$', 'n,'), ('l{@|m,|n,|N}', 'l;'), ('{,}l', 'l;'), ('m{@}', 'm;'), ('n{@}', 'n;'), ('l', 'l,'), ('m', 'm,'), ('n', 'n,'), ('N', 'N,'), (',,', ','), (',;', None), (',l,', 'l,'), (',m,', 'm,'), (',n,', 'n,'), (',N,', 'N,'), ('l{m;|n;}', 'l,'), (';', None), ('^a', '&a'), ('^e', '&e'), ('^i', '&i'), ('^o', '&o'), ('^O', '&O'), ('^u', '&u'), ('^U', '&U'), ('^Q', '&Q'), ('^J', '&J'), ('b', Choseong(B)), ('C', Choseong(C)), ('d', Choseong(D)), ('f', Choseong(P)), ('g', Choseong(H)), ('G', Choseong(G)), ('h', Choseong(H)), ('k,', Jongseong(G)), ('k', Choseong(K)), ('^l', Choseong(L)), ('{,}l', Choseong(L)), ('l,', Jongseong(L)), ('l', Jongseong(L), Choseong(L)), ('m,', Jongseong(M)), ('m', Choseong(M)), ('n,', Jongseong(N)), ('n', Choseong(N)), ('N', Jongseong(NG)), ('p,', Jongseong(B)), ('p', Choseong(P)), ('r', Choseong(L)), ('s', Choseong(S)), ('t,', Jongseong(S)), ('t', Choseong(T)), ('v', Choseong(B)), ('X', Choseong(H)), ('z', Choseong(J)), ('&', Choseong(NG)), ('Ja', Jungseong(YA)), ('Je', Jungseong(YE)), ('Ji', Jungseong(I)), ('Jo', Jungseong(YO)), ('JO', Jungseong(YE)), ('Ju', Jungseong(YU)), ('JU', Jungseong(YU)), ('JQ', Jungseong(YEO)), ('a', Jungseong(A)), ('e', Jungseong(E)), ('i', Jungseong(I)), ('o', Jungseong(O)), ('O', Jungseong(OE)), ('u', Jungseong(WI)), ('U', Jungseong(U)), ('Q', Jungseong(EO)), ('Y', Jungseong(EU)), ]) def normalize(self, string): return normalize_roman(string, { u'Ä': u'ä', u'Ç': u'ç', u'Ë': u'ë', u'É': u'é', u'È': u'é', u'è': u'é', u'Ê': u'é', u'ê': u'é', u'Ï': u'ï', u'Ḯ': u'ï', u'Ḯ': u'ï', u'Ö': u'ö', u'IJ': u'ij', u'ij': u'ij', u'Ü': u'ü', u'Ÿ': u'ij', u'ÿ': u'ij' }) __lang__ = Dutch
hangulize/langs/nld/__init__.py
from hangulize import * class Dutch(Language): """For transcribing Dutch.""" __iso639__ = {1: 'nl', 2: 'dut', 3: 'nld'} __tmp__ = '%,;&' vowels = 'aeEioOuUyQ' cs = 'b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'j', 'J', \ 'k', 'K', 'l', 'm', 'n', 'N', 'p', 'P', 'q', 'r', 's', 't', 'T', \ 'v', 'w', 'x', 'X', 'z', '%' # consonants son = 'lmnNrw' # sonorants short = 'aeEiouU' # short vowels notation = Notation([ (u'’', '\''), (' aan ', '/aan/'), ('^aan ', 'aan/'), (' bij ', '/bij/'), ('^bij ', 'bij/'), (' boven ', '/boven/'), ('^boven ', 'boven/'), (' en ', '/en/'), ('^en ', 'en/'), (' in ', '/in/'), ('^in ', 'in/'), (' op ', '/op/'), ('^op ', 'op/'), (' over ', '/over/'), ('^over ', 'over/'), (' of ', '/of/'), ('^de ', 'de/'), ('^den ', 'den/'), ('^der ', 'der/'), ('^des ', 'des/'), ('^di ', 'di/'), ('^het ', 'het/'), ('^onder ', 'onder/'), ('^sint ', 'sint/'), ('^te ', 'te/'), ('^ten ', 'ten/'), ('^ter ', 'ter/'), ('^thoe ', 'thoe/'), ('^tot ', 'tot/'), ('^uit ', 'uit/'), ('^uijt ', 'uijt/'), ('^van ', 'van/'), ('^ver ', 'ver/'), ('^voor ', 'voor/'), ('-', '/'), ('^\'s ', 's/'), ('^\'t ', 'Qt,/'), ('^\'t', 'Qt,'), ('hoek van/holland', 'hoek/van/holland'), ('hof van/twente', 'hof/van/twente'), ('ronde venen', 'ronde/venen'), ('^midden ', 'midden/'), ('^neder ', 'neder/'), ('^nieuw ', 'nieuw/'), ('^nieuwe ', 'nieuwe/'), ('^noord ', 'noord/'), ('^oost ', 'oost/'), ('^west ', 'west/'), ('^zuid ', 'zuid/'), (u'aimé', u'emé'), (u'curaçao', 'curaso'), ('curacao', 'curaso'), (u'française', 'frangsEzY'), ('francaise', 'frangsEzY'), (u'français', 'frangsE'), ('francais', 'frangsE'), (u'françoise', 'frangsoeazY'), ('francoise', 'frangsoeazY'), (u'françois', 'frangsoea'), ('francois', 'frangsoea'), (u'ç', 's'), (u'{@}ä{@}', '%a%'), (u'{@}ä', '%a'), (u'ä{@}', 'a%'), (u'ä', 'e'), (u'{@}ë{@}', '%e%'), (u'{@}ë', '%e'), (u'ë{@}', 'e%'), (u'ë', 'E'), (u'ée', 'ee'), (u'é', 'E'), (u'{@}ï{@}', '%i%'), (u'{@}ï', '%i'), (u'ï{@}', 'i%'), (u'ï', 'i'), (u'{@}ö{@}', '%o%'), (u'{@}ö', '%o'), (u'ö{@}', 'o%'), (u'ö', 'eu'), (u'{@}ü{@}', '%u%'), (u'{@}ü', '%u'), (u'ü{@}', 'u%'), (u'ü', 'u'), ('^{<cs>}ig', 'igg'), ('^{(<cs>)(<cs>)}ig', 'igg'), ('^{(<cs>)(<cs>)(<cs>)}ig', 'igg'), ('aalbes', 'aalbEs'), ('^aang', 'aan-g'), ('aapmens', 'aapmEns'), ('^abc$', 'abece'), ('adelbert', 'adelbErt'), ('ademtest', 'ademtEst'), ('adres', 'adrEs'), ('adrien', 'adriEn'), ('advocaat', 'aDvocaat'), ('aequo', 'equo'), ('aftershave', 'aftQrsjeev'), ('afvalrace', 'afvalrees'), ('agaath', 'agaat'), ('agath', 'agat'), ('ageeth', 'ageet'), ('ageth', 'aget'), ('^aim{e|ee}', 'em'), ('allerbest', 'allerbEst'), ('altsaxo', 'altYsaxo'), ('amanuens', 'amanu%ens'), ('amulet', 'amulEt'), ('ancien', 'anciEn'), ('andelst', 'andElst'), ('angina', 'anggina'), ('angli{c|st}', 'anggli'), ('angol{a|ees}', 'anggol'), ('anouk', 'anoek'), ('anthon', 'anton'), ('apothe{ek|k}', 'apote'), ('^apropos$', 'apropo'), ('^a propos$', 'apropo'), ('aquarel', 'aquarEl'), ('archipel', 'archipEl'), ('architect', 'architEct'), ('arrest', 'arrEst'), ('aspect', 'aspEct'), ('asbest', 'asbEst'), ('autorace', 'autorees'), ('baby', 'beeby'), ('badge', 'bezi'), ('badminton', 'bedminton'), ('bagage', 'bagaze'), ('bagatel', 'bagatEl'), ('bajonet', 'bajonEt'), ('^balpen', 'balpEn'), ('balth', 'balt'), ('banket', 'bankEt'), ('bankstel', 'bankstEl'), ('baret', 'barEt'), ('barkeep', 'barkip'), ('barones', 'baronEs'), ('barrage', 'barraze'), ('barthol', 'bartol'), ('baseball', 'beesbol'), ('bassin', 'bassEng'), ('beautycase', 'bJoetykees'), ('bed', 'bEd'), ('bEdekt', 'bedEkt'), ('beige', 'beize'), ('^beken', 'bekEn'), ('bekend', 'bekEnd'), ('berg', 'bErg'), ('besef', 'besEf'), ('besmet', 'besmEt'), ('beste{k|l|m}', 'bestE'), ('bevlek', 'bevlEk'), ('bijec', 'bi-jec'), ('bijou', 'bizoe'), ('biljet', 'biljEt'), ('bingo', 'bingGo'), ('biscuit', 'biscu%i'), ('bordes', 'bordEs'), ('bosbes', 'bosbEs'), ('boudier', 'boediE'), ('boulevard', 'boelevar'), ('bourgogne', 'boergonje'), ('bourgond', 'boergond'), ('bouvier', 'boeviE'), ('bowl', 'bol'), ('braille', 'braje'), ('brek', 'brEk'), ('breng', 'brEng'), ('budget', 'buzEt'), ('buffet', 'buffEt'), ('bungalowtent', 'bungalowtEnt'), ('bungalow', 'bungGalo'), ('cabaretier', 'cabarEtiE'), ('cabaret', 'cabarE'), ('cabriolet', 'cabriolEt'), ('cadet', 'cadEt'), ('caissiEre', 'cassiEre'), ('cake', 'keek'), ('cahier', 'cajE'), ('camouflage', 'camoeflaze'), ('campagne', 'campanje'), ('cantharel', 'cantarEl'), ('capuchon', 'capusjon'), ('cari%es', 'cariEs'), ('carillon', 'cariljon'), ('cashew', 'kesjoe'), ('cash', 'kesj'), ('castagnet', 'castanjet'), ('catheter', 'cateter'), ('^cees', 'kees'), ('chalet', 'sjalE'), ('champagne', 'sjampanje'), ('champignon', 'sjampinjon'), ('chantage', 'sjantaze'), ('chante{er|re}', 'sjante'), ('chaperon', 'sjaperon'), ('charcuterie', 'sjarcuterie'), ('charles', 'sjarl'), ('^charl', 'sjarl'), ('charmant', 'sjarmant'), ('chauffeur', 'sjoffeur'), ('cheque', 'sjEk'), ('cheryl', 'sjeryl'), ('chris', 'kris'), ('cologne', 'colonje'), ('compagn{i|y}', 'compan'), ('compagn', 'companj'), ('concertza{al|l}', 'concert-za'), ('conci%erge', 'conciErze'), ('concours', 'concoer'), ('concurrent', 'concurrEnt'), ('condens', 'condEns'), ('conferencier', 'conferangsiE'), ('conference', 'conferangs'), ('congres', 'conggrEs'), ('consequent', 'consequEnt'), ('consignatie', 'consinjatie'), ('contactlens', 'contactlEns'), ('container', 'conteener'), ('continue{er|r}', 'continu%e'), ('contour', 'contoer'), ('copyright', 'copyrajt'), ('cornedbeef', 'cornedbif'), ('corps', 'cor'), ('correct', 'corrEct'), ('corrige', 'corrize'), ('corsage', 'corsaze'), ('coulant', 'coelant'), ('coulisse', 'coelisse'), ('coup', 'coep'), ('courant', 'coerant'), ('coureur', 'coereur'), ('courgette', 'coerzette'), ('courtage', 'coertaze'), ('couture', 'coeture'), ('couturier', 'coeturiE'), ('couveuse', 'coeveuse'), ('cowboy', 'cauboy'), ('crash', 'crEsj'), ('crawl', 'crol'), ('crEche', 'crEsj'), ('crEme', 'crEm'), ('crime', 'crim'), ('croissant', 'croeassang'), ('croque', 'crok'), ('cursusjaar', 'cursusYjaar'), ('damhert', 'damhErt'), ('daniel', 'daniEl'), ('dani%el', 'daniEl'), ('dashboard', 'desjbord'), ('davidster', 'davit,ster'), ('debet', 'debEt'), ('decadent', 'decadEnt'), ('decibel', 'decibEl'), ('defect', 'defEct'), ('depot$', 'depo'), ('depots', 'depos'), ('dessert', 'dessEr'), ('dessin', 'dessEng'), ('detaillist', 'detajist'), ('detail', 'detaj'), ('detective', 'ditectiv'), ('diligence', 'dilizangce'), ('direct', 'dirEct'), ('discothe', 'discote'), ('discretie', 'discreti'), ('display', 'displey'), ('divers', 'divErs'), ('dividend', 'dividEnd'), ('doodstraf', 'dood%straf'), ('doodziek', 'dood%ziek'), ('doodzonde', 'dood%zonde'), ('doroth', 'dorot'), ('dossier', 'dossiE'), ('douan{e|i}', 'doean'), ('doubl', 'doebl'), ('douche$', 'doesj'), ('douche', 'doesje'), ('drenthe', 'drente'), ('drinkyoghurt', 'drinkYJoghurt'), ('drukpers', 'drukpErs'), ('drumstel', 'drumstEl'), ('^dumas$', 'duma'), ('dyk', 'dijk'), ('eerhestel', 'eerhestEl'), ('effect', 'effEct'), ('eicel', 'eicEl'), ('eindhoven', 'einthoven'), ('elektricien', 'elektriciEng'), ('^eljero', 'elzero'), ('employE', 'amploeajE'), ('enschede', 'enschedE'), ('ernst', 'Ernst'), ('erwt', 'Ert'), ('esther', 'ester'), ('etage', 'etaze'), ('etalage', 'etalaze'), ('ether', 'eter'), ('ethiek', 'etiek'), ('ethiop', 'etiop'), ('ethisch', 'etisch'), ('eugene', 'euzEn'), ('eurocent', 'eurocEnt'), ('euthanas', 'eutanas'), ('evacue{er|r}', 'evacu%e'), ('evangel', 'evanggel'), ('evengoed', 'even-goed'), ('examengeld', 'examen-gEld'), ('exces', 'excEs'), ('{~@}ex', 'Ex'), ('floret', 'florEt'), ('foetus', 'feutus'), ('forel', 'forEl'), ('forfait', 'forfE'), ('fokstier', 'fokstir'), ('formulier', 'formulir'), ('foyer', 'foeajE'), ('franchise', 'fransjize'), ('frangipane', 'frangzipane'), ('freak', 'fri-k'), ('freelancer', 'frilangcer'), ('freelance', 'frilangs'), ('freudia', 'froidia'), ('frikadel', 'frikadEl'), ('frou-frou', 'froe-froe'), ('fulltime', 'foeltajm'), ('funest', 'funEst'), ('gabriel', 'GabriEl'), ('gabri%el', 'GabriEl'), ('^game$', 'Geem'), ('^games$', 'Geems'), ('gameboy', 'Geemboy'), ('gebrek', 'gebrEk'), ('gelukwens', 'gelukwEns'), ('gemenebest', 'gemenebEst'), ('gemengd', 'gemEngd'), ('gEnant', 'zEnant'), ('gendarme', 'zangdarme'), ('genEve', 'zenEve'), ('genie$', 'zenie'), ('genie{%en|tj}', 'zenie'), ('genre', 'zangrY'), ('^giovan', 'zovan'), ('gogh', 'Gogh'), ('grens', 'grEns'), ('greth{a|e}', 'gret'), ('^guido', 'gido'), ('^hamel', 'hamEl'), ('hef', 'hEf'), ('hek', 'hEk'), ('hengst', 'hEngst'), ('ijssel', 'ijssQl'), ('israel', 'israEl'), ('isra%el', 'israEl'), ('jacques', 'zaak'), ('jeanette', 'zaanEt'), ('jeanet', 'zaanEt'), ('jeanne$', 'zaan'), ('jockey', 'zoki'), ('johannes', 'johannEs'), ('^john$', 'zon'), ('jozef', 'jozEf'), ('^beken', 'bekEn'), ('beken{d|t}', 'bekEn'), ('^erken', 'erkEn'), ('erken{d|t}', 'erkEn'), ('^herken', 'herkEn'), ('^ontken', 'ontkEn'), ('ontken{d|t}', 'ontkEn'), ('^toeken', 'toekEn'), ('toeken{d|t}', 'toekEn'), ('^verken', 'verkEn'), ('klem{d|t}', 'klEm'), ('korthal', 'kortal'), ('leg{d|t}', 'lEg'), ('lingerie', 'lengzerie'), ('lingu%ist', 'linggu%ist'), ('^louis$', 'loei'), ('^louis', 'loeis'), ('lyonnet', 'lyonnE'), ('manuel', 'manuEl'), ('^margot$', 'margo'), ('^mari%e', 'mariE'), ('marth', 'mart'), ('^mary$', 'mery'), ('mathild', 'matild'), ('melk', 'mElk'), ('merk', 'mErk'), ('michael', 'mikaEl'), ('micha%el', 'mikaEl'), ('^michel$', 'misjEl'), ('michiel', 'mikiEl'), ('michi%el', 'mikiEl'), ('model', 'modEl'), ('monsieur', 'mQsieu'), ('nerf', 'nErf'), ('^nigel', 'naizel'), ('^no%e', 'noE'), ('ongerust', 'onggerust'), ('orkest', 'orkEst'), ('pech', 'pEch'), ('persoonsbed', 'persoonsbEd'), ('pierre', 'piEr'), ('pincher', 'pinsjer'), ('posthum', 'postum'), ('rafael', 'rafaEl'), ('rafa%el', 'rafaEl'), ('recept', 'recEpt'), ('reinier', 'reini%er'), ('rhijn', 'rijn'), ('richard', 'rikard'), ('rogier', 'rogi%er'), ('ryan', 'raien'), ('scherm', 'schErm'), ('sharon', 'sjaron'), ('spel', 'spEl'), ('spionage', 'spionaze'), ('streng', 'strEng'), ('student', 'studEnt'), ('term', 'tErm'), ('the{a|o}', 'te'), ('thierry', 'tiErry'), ('thijs', 'tijs'), ('thys', 'tys'), ('timoth', 'timot'), ('toilette', 'toealEt'), ('toilet', 'toealEt'), ('tref', 'trEf'), ('trek', 'trEk'), ('van/Gogh', 'wan/Gogh'), ('vel{d|t}', 'vEl'), ('vEldhoven', 'vEld/hoven'), ('^vera$', 'wera'), ('veroni', 'weroni'), ('victor', 'wictor'), ('vincent', 'wincEnt'), ('viol', 'wiol'), ('vlek', 'vlEk'), ('weg', 'wEg'), ('wenst', 'wEnst'), ('^wens', 'wEns'), ('werk', 'wErk'), ('wesley', 'wesly'), ('wet', 'wEt'), ('^wt', 'uwt'), ('zet', 'zEt'), ('szoon', 's/zoon'), ('echt', 'Echt'), ('egd', 'Egd'), ('ent', 'Ent'), ('eau', 'o'), # common French spellings ('%e{l|ls|t|ts|tt|tts}$', 'E'), ('air', 'Er'), ('oir$', 'oear'), ('^ti', 'tiF'), ('tie{f|k}', 'ti'), ('tie$', 'sie'), ('tieus', 'sieus'), ('{n|r}tie$', 'sie'), ('ti{eel|%el}', 'si'), ('ti{aal|al}', 'si'), ('tion$', 'sjon'), ('tion{eel|%el}', 'sjon'), ('tione{er|r}', 'sjone'), ('tion{ne|s}', 'sjon'), ('tium', 'sium'), ('F', None), ('{<cs>}ig$', 'Qg'), ('{<cs>}igd$', 'Qgd'), ('{<cs>}igde$', 'Qgde'), ('{<cs>}ige$', 'Qge'), ('{<cs>}igen$', 'Qgen'), ('{<cs>}igheid$', 'Qgheid'), ('{<cs>}iging$', 'Qging'), ('^over', 'ovQr'), ('sch{@}', 'sX'), ('sch', 's'), ('ch', 'X'), ('c{e|E|i|y}', 's'), ('c', 'k'), ('qq', 'q'), ('qu', 'kw'), ('q', 'k'), ('x', 'ks'), ('ng', 'N'), ('nk', 'Nk'), ('dt$', 't'), ('dt{<cs>}', 't'), ('gh', 'g'), ('ph', 'p'), ('^th', 't'), ('^kh', 'k'), ('h{<cs>}', None), ('h$', None), ('sj{@}', 'sJ'), ('sj', 'si'), ('sz$', 's'), ('sz{<cs>}', 's'), ('ts', 'C'), ('tz', 'C'), ('^v', 'f'), ('uw', 'uW'), ('v$', 'f'), ('^y{@}', 'j'), ('y', 'i%'), ('z$', 's'), ('bb', 'b'), ('dd', 'd'), ('ff', 'f'), ('fv', 'f'), ('gg', 'g'), ('hh', 'h'), ('kk', 'k'), ('ll', 'l'), ('mm', 'm'), ('nn', 'n'), ('pp', 'p'), ('rr', 'r'), ('ss', 's'), ('tt', 't'), ('mbt', 'mt'), ('mpt', 'mt'), ('b$', '-p'), ('d$', '-t'), ('ds{~@}', 'C'), ('ds$', 'C'), ('dz{~@}', 'C'), ('dz$', 'C'), ('^ie{<cs>}', 'i'), ('{<cs>}ie{<cs>}', 'i'), ('^oe{<cs>}', 'U'), ('{<cs>}oe{<cs>}', 'U'), ('b{@|<son>|j}', 'B'), ('{<son>}b', 'B'), ('^{(<short>)}b{<cs>}', 'P'), ('{(<cs>)(<short>)}b{<cs>}', 'P'), ('B', 'b'), ('d{@|<son>|j}', 'D'), ('{<son>}d', 'D'), ('^{(<short>)}d{<cs>}', 'T'), ('{(<cs>)(<short>)}d{<cs>}', 'T'), ('D', 'd'), ('p{@|<son>|j}', 'F'), ('{<son>}p', 'F'), ('^{(<short>)}p{<cs>}', 'P'), ('{(<cs>)(<short>)}p{<cs>}', 'P'), ('^{(<short>)}p$', 'P'), ('{(<cs>)(<short>)}p$', 'P'), ('F', 'p'), ('t{@|<son>|j}', 'F'), ('{<son>}t', 'F'), ('^{(<short)>}t{<cs>}', 'T'), ('{(<cs>)(<short>)}t{<cs>}', 'T'), ('^{(<short>)}t$', 'T'), ('{(<cs>)(<short>)}t$', 'T'), ('F', 't'), ('k{@|<son>|j|v}', 'F'), ('{<son>}k', 'F'), ('^{(<short>)}k{<cs>}', 'K'), ('{(<cs>)(<short>)}k{<cs>}', 'K'), ('^{(<short>)}k$', 'K'), ('{(<cs>)(<short>)}k$', 'K'), ('F', 'k'), ('{~@}bj', 'bi%'), ('^bj', 'bi%'), ('{~@}dj', 'di%'), ('^dj', 'di%'), ('{~@}pj', 'pi%'), ('^pj', 'pi%'), ('{~@}tj', 'ti%'), ('^tj', 'ti%'), ('{~@}kj', 'ki%'), ('^kj', 'ki%'), ('{~@}rj', 'ri%'), ('^rj', 'ri%'), ('{b|d|p|t|k|r}j', 'Yj'), ('{@}ie', 'i%e'), ('w', 'v'), ('ae', 'aa'), ('aa', 'a'), ('auW', 'aU%'), ('au', 'aU%'), ('ouW', 'aU%'), ('ou', 'aU%'), ('{@}iji', 'i'), ('{@}ij{@}', 'i%j'), ('{@}ij', 'i%'), ('ij', 'ei'), ('eeuW', 'eiU%'), ('ieuW', 'iU%'), ('euW', 'e-u%'), ('iee', 'i%ee'), ('ee', 'ei'), ('oo', 'o'), ('ui', 'au%'), ('uy', 'au%'), ('eu', 'O%'), ('uee', 'u%ee'), ('ue', 'uu'), ('uW', 'uu%'), ('uu', 'u'), ('i%i', 'i'), ('ie', 'i'), ('ii', 'i'), ('oe', 'U'), ('-', None), ('e$', 'Q'), ('^e{(<cs>)}$', 'E'), ('^{(<cs>)}e{(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)}e{(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)(<cs>)}e{(<cs>)}$', 'E'), ('^e{(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)}e{(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)}e{(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)(<cs>)}e{(<cs>)(<cs>)}$', 'E'), ('^e{(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)}e{(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)}e{(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)(<cs>)}e{(<cs>)(<cs>)(<cs>)}$', 'E'), ('^e{(<cs>)(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)}e{(<cs>)(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)}e{(<cs>)(<cs>)(<cs>)(<cs>)}$', 'E'), ('^{(<cs>)(<cs>)(<cs>)}e{(<cs>)(<cs>)(<cs>)(<cs>)}$', 'E'), ('{<cs>}e{(<cs>)}$', 'Q'), ('{<cs>}e{(<cs>)(<cs>)}$', 'Q'), ('{<cs>}e{(<cs>)(<cs>)(<cs>)}$', 'Q'), ('{<cs>}e{(<cs>)(<cs>)(<cs>)(<cs>)}$', 'Q'), ('E', 'e'), ('P', 'p,'), ('T', 't,'), ('K', 'k,'), ('j{@}', 'J'), ('j', 'i'), ('{C|z}J', None), ('^l', 'l;'), ('^m', 'm;'), ('^n', 'n;'), ('l$', 'l,'), ('m$', 'm,'), ('n$', 'n,'), ('l{@|m,|n,|N}', 'l;'), ('{,}l', 'l;'), ('m{@}', 'm;'), ('n{@}', 'n;'), ('l', 'l,'), ('m', 'm,'), ('n', 'n,'), ('N', 'N,'), (',,', ','), (',;', None), (',l,', 'l,'), (',m,', 'm,'), (',n,', 'n,'), (',N,', 'N,'), ('l{m;|n;}', 'l,'), (';', None), ('^a', '&a'), ('^e', '&e'), ('^i', '&i'), ('^o', '&o'), ('^O', '&O'), ('^u', '&u'), ('^U', '&U'), ('^Q', '&Q'), ('^J', '&J'), ('b', Choseong(B)), ('C', Choseong(C)), ('d', Choseong(D)), ('f', Choseong(P)), ('g', Choseong(H)), ('G', Choseong(G)), ('h', Choseong(H)), ('k,', Jongseong(G)), ('k', Choseong(K)), ('^l', Choseong(L)), ('{,}l', Choseong(L)), ('l,', Jongseong(L)), ('l', Jongseong(L), Choseong(L)), ('m,', Jongseong(M)), ('m', Choseong(M)), ('n,', Jongseong(N)), ('n', Choseong(N)), ('N', Jongseong(NG)), ('p,', Jongseong(B)), ('p', Choseong(P)), ('r', Choseong(L)), ('s', Choseong(S)), ('t,', Jongseong(S)), ('t', Choseong(T)), ('v', Choseong(B)), ('X', Choseong(H)), ('z', Choseong(J)), ('&', Choseong(NG)), ('Ja', Jungseong(YA)), ('Je', Jungseong(YE)), ('Ji', Jungseong(I)), ('Jo', Jungseong(YO)), ('JO', Jungseong(YE)), ('Ju', Jungseong(YU)), ('JU', Jungseong(YU)), ('JQ', Jungseong(YEO)), ('a', Jungseong(A)), ('e', Jungseong(E)), ('i', Jungseong(I)), ('o', Jungseong(O)), ('O', Jungseong(OE)), ('u', Jungseong(WI)), ('U', Jungseong(U)), ('Q', Jungseong(EO)), ('Y', Jungseong(EU)), ]) def normalize(self, string): return normalize_roman(string, { u'Ä': u'ä', u'Ç': u'ç', u'Ë': u'ë', u'É': u'é', u'È': u'é', u'è': u'é', u'Ê': u'é', u'ê': u'é', u'Ï': u'ï', u'Ḯ': u'ï', u'Ḯ': u'ï', u'Ö': u'ö', u'IJ': u'ij', u'ij': u'ij', u'Ü': u'ü', u'Ÿ': u'ij', u'ÿ': u'ij' }) __lang__ = Dutch
0.316369
0.221656
from units import unit from items import item import time going = True coins = 10 player_score = 0 player_round = 0 n_shop_items = 2 n_shop_units = 4 n_roster = 5 roster = [] for i in range(n_roster): roster.append(0) shop_units = [] shop_items = [] shop_units = [] for i in range(n_shop_units): shop_units.append(unit.random_unit()) shop_items = [] for i in range(n_shop_items): shop_items.append(item.random_item()) print("Coins: "+str(coins)) while going: time.sleep(0.1) action = input("Action: ") if action == "q": print("Exit") going = False elif action == "u": myunit = unit.Unit("Cow", 2, 3, 5, 2) print(myunit.to_str()) elif action == "i": myitem = item.Item("Revolver", 3, 1, 0, 3) print(myitem.to_str()) elif action == "rsi": shop_items = [] for i in range(n_shop_items): shop_items.append(item.random_item()) elif action == "rsu": shop_units = [] for i in range(n_shop_units): shop_units.append(unit.random_unit()) elif action == "lsi": for i in range(len(shop_items)): if shop_items[i] == 0: print(" - "+str(i)+" empty") else: print(" - "+str(i)+" "+shop_items[i].to_str()) elif action == "lsu": for i in range(len(shop_units)): if shop_units[i] == 0: print(" - "+str(i)+" empty") else: print(" - "+str(i)+" "+shop_units[i].to_str()) elif action == "r": for i in range(n_roster): if roster[i] != 0: print(str(i)+" "+roster[i].to_str()) else: print(str(i)+" empty") elif action == "c": print("Coins: "+str(coins)) elif action == "bi": print("Item store") for i in range(len(shop_items)): if shop_items[i] == 0: print(" - "+str(i)+" empty") else: print(" - "+str(i)+" "+shop_items[i].to_str()) item_buy = input("Buy item: ") if item_buy == "q": continue elif shop_items[int(item_buy)] != 0: if int(item_buy) >= 0 and int(item_buy) < len(shop_items) and coins >= shop_items[int(item_buy)].cost: for i in range(n_roster): if roster[i] != 0: print(str(i)+" "+roster[i].to_str()) else: print(str(i)+" empty") action = int(input("Equip: ")) if roster[action] != 0: coins -= shop_items[int(item_buy)].cost print("equip") roster[action].equip(shop_items[int(item_buy)]) shop_items[int(item_buy)] = 0 elif action == "bu": print("Unit store") for i in range(len(shop_units)): if shop_units[i] == 0: print(" - "+str(i)+" empty") else: print(" - "+str(i)+" "+shop_units[i].to_str()) unit_buy = input("Buy unit: ") if unit_buy == "q": continue elif int(unit_buy) >=0 and int(unit_buy) < len(shop_units) and coins >= shop_units[int(unit_buy)].cost: for i in range(n_roster): if roster[i] != 0: print(str(i)+" "+roster[i].to_str()) else: print(str(i)+" empty") action = int(input("Place: ")) if roster[action] == 0: coins -= shop_units[int(unit_buy)].cost roster[action] = shop_units[int(unit_buy)] shop_units[int(unit_buy)] = 0
main.py
from units import unit from items import item import time going = True coins = 10 player_score = 0 player_round = 0 n_shop_items = 2 n_shop_units = 4 n_roster = 5 roster = [] for i in range(n_roster): roster.append(0) shop_units = [] shop_items = [] shop_units = [] for i in range(n_shop_units): shop_units.append(unit.random_unit()) shop_items = [] for i in range(n_shop_items): shop_items.append(item.random_item()) print("Coins: "+str(coins)) while going: time.sleep(0.1) action = input("Action: ") if action == "q": print("Exit") going = False elif action == "u": myunit = unit.Unit("Cow", 2, 3, 5, 2) print(myunit.to_str()) elif action == "i": myitem = item.Item("Revolver", 3, 1, 0, 3) print(myitem.to_str()) elif action == "rsi": shop_items = [] for i in range(n_shop_items): shop_items.append(item.random_item()) elif action == "rsu": shop_units = [] for i in range(n_shop_units): shop_units.append(unit.random_unit()) elif action == "lsi": for i in range(len(shop_items)): if shop_items[i] == 0: print(" - "+str(i)+" empty") else: print(" - "+str(i)+" "+shop_items[i].to_str()) elif action == "lsu": for i in range(len(shop_units)): if shop_units[i] == 0: print(" - "+str(i)+" empty") else: print(" - "+str(i)+" "+shop_units[i].to_str()) elif action == "r": for i in range(n_roster): if roster[i] != 0: print(str(i)+" "+roster[i].to_str()) else: print(str(i)+" empty") elif action == "c": print("Coins: "+str(coins)) elif action == "bi": print("Item store") for i in range(len(shop_items)): if shop_items[i] == 0: print(" - "+str(i)+" empty") else: print(" - "+str(i)+" "+shop_items[i].to_str()) item_buy = input("Buy item: ") if item_buy == "q": continue elif shop_items[int(item_buy)] != 0: if int(item_buy) >= 0 and int(item_buy) < len(shop_items) and coins >= shop_items[int(item_buy)].cost: for i in range(n_roster): if roster[i] != 0: print(str(i)+" "+roster[i].to_str()) else: print(str(i)+" empty") action = int(input("Equip: ")) if roster[action] != 0: coins -= shop_items[int(item_buy)].cost print("equip") roster[action].equip(shop_items[int(item_buy)]) shop_items[int(item_buy)] = 0 elif action == "bu": print("Unit store") for i in range(len(shop_units)): if shop_units[i] == 0: print(" - "+str(i)+" empty") else: print(" - "+str(i)+" "+shop_units[i].to_str()) unit_buy = input("Buy unit: ") if unit_buy == "q": continue elif int(unit_buy) >=0 and int(unit_buy) < len(shop_units) and coins >= shop_units[int(unit_buy)].cost: for i in range(n_roster): if roster[i] != 0: print(str(i)+" "+roster[i].to_str()) else: print(str(i)+" empty") action = int(input("Place: ")) if roster[action] == 0: coins -= shop_units[int(unit_buy)].cost roster[action] = shop_units[int(unit_buy)] shop_units[int(unit_buy)] = 0
0.087474
0.238517
import pandas as pd import os # creating a class named Song class Song: def __init__(self, song_name, path): # initializing object self.song_name = song_name self.path = path # defining the function to return song info def getinfo(self): #handling none input type if self.song_name is None: return("None input type not accepted." + "\nPlease provide a string input.") song_name = self.song_name.lower().strip() # assigning the database to the variable "db" db = pd.read_csv(self.path) # creating a list with all song titles titles = list(db["track_name"].str.lower()) if song_name in titles: # assinging the index number to variable i i = titles.index(song_name) # returning info return ("\nThe song: '" + db.track_name[i] + "' is made by '" + db.track_artist[i] + "'.\nIt was released in the album '" + db.track_album_name[i] + "', in the date " + db.track_album_release_date[i] + ", and it appeared" + " in the spotify playlist named " + db.playlist_name[i] + ", with other song of genre " + db.playlist_genre[i] + ", and subgenre " + db.playlist_subgenre[i] + ".\nThe song has " + str(round(db.tempo[i])) + " bpm and it lasts " + str(round(db.duration_ms[i] / 1000)) + " seconds.\n") else: return (" The song you're looking for" + " is not present in our database. " + " Here you are some recommended songs we have:\n " + " 'Party Rock Anthem',\n " + " 'Symphony Of Destruction',\n " + " 'Some Nights'! ") # defining the function to create a karaoke def karaoke(self): #handling none input type if self.song_name is None: return("None input type not accepted." + "\nPlease provide a string input.") song_name = self.song_name.lower().strip() db = pd.read_csv(self.path) # creating a list with all song titles titles = list(db["track_name"].str.lower()) if song_name in titles: # assinging the index number to variable i i = titles.index(song_name) # returning song URL and song lyrics return (" \nType this in your favourite browser: 'spotify:track:" + str(db.track_id[i]) + "' and sing with our lyrics!\n\n " + db.track_name[i].upper() + " - " + db.track_artist[i].upper() + "\n\n" + str(db.lyrics[i])) else: # returning recommendations, if song not present return ("Not found!\nHere you are" + " some recommended songs we have:\n" + "'Party Rock Anthem',\n" + "'Symphony Of Destruction',\n" + "'Some Nights'!")
modules/getinfo.py
import pandas as pd import os # creating a class named Song class Song: def __init__(self, song_name, path): # initializing object self.song_name = song_name self.path = path # defining the function to return song info def getinfo(self): #handling none input type if self.song_name is None: return("None input type not accepted." + "\nPlease provide a string input.") song_name = self.song_name.lower().strip() # assigning the database to the variable "db" db = pd.read_csv(self.path) # creating a list with all song titles titles = list(db["track_name"].str.lower()) if song_name in titles: # assinging the index number to variable i i = titles.index(song_name) # returning info return ("\nThe song: '" + db.track_name[i] + "' is made by '" + db.track_artist[i] + "'.\nIt was released in the album '" + db.track_album_name[i] + "', in the date " + db.track_album_release_date[i] + ", and it appeared" + " in the spotify playlist named " + db.playlist_name[i] + ", with other song of genre " + db.playlist_genre[i] + ", and subgenre " + db.playlist_subgenre[i] + ".\nThe song has " + str(round(db.tempo[i])) + " bpm and it lasts " + str(round(db.duration_ms[i] / 1000)) + " seconds.\n") else: return (" The song you're looking for" + " is not present in our database. " + " Here you are some recommended songs we have:\n " + " 'Party Rock Anthem',\n " + " 'Symphony Of Destruction',\n " + " 'Some Nights'! ") # defining the function to create a karaoke def karaoke(self): #handling none input type if self.song_name is None: return("None input type not accepted." + "\nPlease provide a string input.") song_name = self.song_name.lower().strip() db = pd.read_csv(self.path) # creating a list with all song titles titles = list(db["track_name"].str.lower()) if song_name in titles: # assinging the index number to variable i i = titles.index(song_name) # returning song URL and song lyrics return (" \nType this in your favourite browser: 'spotify:track:" + str(db.track_id[i]) + "' and sing with our lyrics!\n\n " + db.track_name[i].upper() + " - " + db.track_artist[i].upper() + "\n\n" + str(db.lyrics[i])) else: # returning recommendations, if song not present return ("Not found!\nHere you are" + " some recommended songs we have:\n" + "'Party Rock Anthem',\n" + "'Symphony Of Destruction',\n" + "'Some Nights'!")
0.222109
0.120129
import os from distutils.util import convert_path from fnmatch import fnmatchcase from setuptools import find_packages, setup standard_exclude = ('*.pyc', '*~', '.*', '*.bak', '*.swp*') standard_exclude_directories = ( '.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info') def long_description(): this_directory = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f: return f.read() def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories): out = {} stack = [(convert_path(where), '', package)] while stack: where, prefix, package = stack.pop(0) for name in os.listdir(where): fn = os.path.join(where, name) if os.path.isdir(fn): bad_name = False for pattern in exclude_directories: if (fnmatchcase(name, pattern) or fn.lower() == pattern.lower()): bad_name = True break if bad_name: continue if os.path.isfile(os.path.join(fn, '__init__.py')): if not package: new_package = name else: new_package = package + '.' + name stack.append((fn, '', new_package)) else: stack.append((fn, prefix + name + '/', package)) else: bad_name = False for pattern in exclude: if (fnmatchcase(name, pattern) or fn.lower() == pattern.lower()): bad_name = True break if bad_name: continue out.setdefault(package, []).append(prefix + name) return out setup( name='docassemble.lmrhh', version='2.0.2', description=__doc__, long_description=long_description(), long_description_content_type='text/markdown', author='<NAME>', author_email='<EMAIL>', license='The MIT License (MIT)', url='https://github.com/lmr-hamburg/docassemble-lmrhh', packages=find_packages(), namespace_packages=['docassemble'], install_requires=[ 'requests', 'Flask-Mail', 'google-api-python-client', 'google-auth-oauthlib' ], zip_safe=False, package_data=find_package_data(where='docassemble/lmrhh/', package='docassemble.lmrhh'), )
setup.py
import os from distutils.util import convert_path from fnmatch import fnmatchcase from setuptools import find_packages, setup standard_exclude = ('*.pyc', '*~', '.*', '*.bak', '*.swp*') standard_exclude_directories = ( '.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info') def long_description(): this_directory = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f: return f.read() def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories): out = {} stack = [(convert_path(where), '', package)] while stack: where, prefix, package = stack.pop(0) for name in os.listdir(where): fn = os.path.join(where, name) if os.path.isdir(fn): bad_name = False for pattern in exclude_directories: if (fnmatchcase(name, pattern) or fn.lower() == pattern.lower()): bad_name = True break if bad_name: continue if os.path.isfile(os.path.join(fn, '__init__.py')): if not package: new_package = name else: new_package = package + '.' + name stack.append((fn, '', new_package)) else: stack.append((fn, prefix + name + '/', package)) else: bad_name = False for pattern in exclude: if (fnmatchcase(name, pattern) or fn.lower() == pattern.lower()): bad_name = True break if bad_name: continue out.setdefault(package, []).append(prefix + name) return out setup( name='docassemble.lmrhh', version='2.0.2', description=__doc__, long_description=long_description(), long_description_content_type='text/markdown', author='<NAME>', author_email='<EMAIL>', license='The MIT License (MIT)', url='https://github.com/lmr-hamburg/docassemble-lmrhh', packages=find_packages(), namespace_packages=['docassemble'], install_requires=[ 'requests', 'Flask-Mail', 'google-api-python-client', 'google-auth-oauthlib' ], zip_safe=False, package_data=find_package_data(where='docassemble/lmrhh/', package='docassemble.lmrhh'), )
0.329392
0.120206
### Python imports import pathlib ### Third Party imports import numpy as np import pandas as pd import pytest ### Project imports from t4.formats import FormatRegistry from t4.util import QuiltException ### Constants ### Code def test_buggy_parquet(): """ Test that T4 avoids crashing on bad Pandas metadata from old pyarrow libaries. """ path = pathlib.Path(__file__).parent for parquet_handler in FormatRegistry.for_format('parquet'): with open(path / 'data' / 'buggy_parquet.parquet', 'rb') as bad_parq: # Make sure this doesn't crash. parquet_handler.deserialize(bad_parq.read()) def test_formats_for_obj(): arr = np.ndarray(3) fmt = FormatRegistry.for_obj(arr)[0] assert 'npz' in fmt.handled_extensions assert FormatRegistry.for_ext('npy')[0] is fmt expected_string_fmt_names = ['utf-8', 'unicode', 'json'] found_string_fmt_names = list(f.name for f in FormatRegistry.for_obj('blah')) assert found_string_fmt_names == expected_string_fmt_names bytes_obj = fmt.serialize(arr)[0] assert np.array_equal(fmt.deserialize(bytes_obj, ), arr) def test_formats_for_ext(): fmt = FormatRegistry.for_ext('json')[0] assert fmt.serialize({'blah': 'blah'})[0] == b'{"blah": "blah"}' assert fmt.deserialize(b'{"meow": "mix"}', ) == {'meow': 'mix'} def test_formats_for_meta(): bytes_fmt = FormatRegistry.for_meta({'target': 'bytes'})[0] json_fmt = FormatRegistry.for_meta({'target': 'json'})[0] some_bytes = b'["phlipper", "piglet"]' assert bytes_fmt.serialize(some_bytes)[0] == some_bytes assert json_fmt.deserialize(some_bytes) == ['phlipper', 'piglet'] def test_formats_for_format(): bytes_fmt = FormatRegistry.for_format('bytes')[0] json_fmt = FormatRegistry.for_format('json')[0] some_bytes = b'["phlipper", "piglet"]' assert bytes_fmt.serialize(some_bytes)[0] == some_bytes assert json_fmt.deserialize(some_bytes) == ['phlipper', 'piglet'] def test_formats_serdes(): objects = [ {'blah': 'foo'}, b'blather', 'blip', ] metadata = [{} for o in objects] for obj, meta in zip(objects, metadata): data, format_meta = FormatRegistry.serialize(obj, meta) meta.update(format_meta) assert FormatRegistry.deserialize(data, meta) == obj meta = {} df1 = pd.DataFrame([[1, 2], [3, 4]]) data, format_meta = FormatRegistry.serialize(df1, meta) meta.update(format_meta) df2 = FormatRegistry.deserialize(data, meta) # we can't really get around this nicely -- if header is used, and header names are numeric, # once loaded from CSV, header names are now strings. This causes a bad comparison, so we # cast to int again. df2.columns = df2.columns.astype(int, copy=False) assert df1.equals(df2) def test_formats_csv_read(): csv_file = pathlib.Path(__file__).parent / 'data' / 'csv.csv' meta = {'format': {'name': 'csv'}} expected_bytes = b'a,b,c,d\n1,2,3,4\n5,6,7,8\n' expected_df = FormatRegistry.deserialize(expected_bytes, meta) df = FormatRegistry.deserialize(csv_file.read_bytes(), meta) assert df.equals(expected_df) assert expected_bytes == FormatRegistry.serialize(df, meta)[0] def test_formats_csv_roundtrip(): test_data = b'9,2,5\n7,2,6\n1,0,1\n' # roundtrip defaults. meta = {'format': {'name': 'csv'}} df1 = FormatRegistry.deserialize(test_data, meta) bin, format_meta = FormatRegistry.serialize(df1, meta) meta.update(format_meta) df2 = FormatRegistry.deserialize(bin, meta) assert test_data == bin assert df1.equals(df2) # interpret first row as header meta = {'format': {'name': 'csv', 'opts': {'use_header': True}}} df1 = FormatRegistry.deserialize(test_data, meta) bin, format_meta = FormatRegistry.serialize(df1, meta) meta.update(format_meta) df2 = FormatRegistry.deserialize(bin, meta) assert test_data == bin assert df1.equals(df2) # interpret first column as index meta = {'format': {'name': 'csv', 'opts': {'use_index': True}}} df1 = FormatRegistry.deserialize(test_data, meta) bin, format_meta = FormatRegistry.serialize(df1, meta) meta.update(format_meta) df2 = FormatRegistry.deserialize(bin, meta) assert test_data == bin assert df1.equals(df2) # interpret first row as header, and first column as index meta = {'format': {'name': 'csv', 'opts': {'use_index': True, 'use_header': True}}} df1 = FormatRegistry.deserialize(test_data, meta) bin, format_meta = FormatRegistry.serialize(df1, meta) meta.update(format_meta) df2 = FormatRegistry.deserialize(bin, meta) assert test_data == bin assert df1.equals(df2) def test_formats_search_fail_notfound(): # a search that finds nothing should raise with an explanation. class Foo: pass bad_kwargs = [ dict(obj_type=Foo, meta=None, ext=None), dict(obj_type=None, meta={}, ext=None), dict(obj_type=None, meta=None, ext='.fizz'), ] for args in bad_kwargs: with pytest.raises(QuiltException): FormatRegistry.search(**args)
api/python/tests/test_formats.py
### Python imports import pathlib ### Third Party imports import numpy as np import pandas as pd import pytest ### Project imports from t4.formats import FormatRegistry from t4.util import QuiltException ### Constants ### Code def test_buggy_parquet(): """ Test that T4 avoids crashing on bad Pandas metadata from old pyarrow libaries. """ path = pathlib.Path(__file__).parent for parquet_handler in FormatRegistry.for_format('parquet'): with open(path / 'data' / 'buggy_parquet.parquet', 'rb') as bad_parq: # Make sure this doesn't crash. parquet_handler.deserialize(bad_parq.read()) def test_formats_for_obj(): arr = np.ndarray(3) fmt = FormatRegistry.for_obj(arr)[0] assert 'npz' in fmt.handled_extensions assert FormatRegistry.for_ext('npy')[0] is fmt expected_string_fmt_names = ['utf-8', 'unicode', 'json'] found_string_fmt_names = list(f.name for f in FormatRegistry.for_obj('blah')) assert found_string_fmt_names == expected_string_fmt_names bytes_obj = fmt.serialize(arr)[0] assert np.array_equal(fmt.deserialize(bytes_obj, ), arr) def test_formats_for_ext(): fmt = FormatRegistry.for_ext('json')[0] assert fmt.serialize({'blah': 'blah'})[0] == b'{"blah": "blah"}' assert fmt.deserialize(b'{"meow": "mix"}', ) == {'meow': 'mix'} def test_formats_for_meta(): bytes_fmt = FormatRegistry.for_meta({'target': 'bytes'})[0] json_fmt = FormatRegistry.for_meta({'target': 'json'})[0] some_bytes = b'["phlipper", "piglet"]' assert bytes_fmt.serialize(some_bytes)[0] == some_bytes assert json_fmt.deserialize(some_bytes) == ['phlipper', 'piglet'] def test_formats_for_format(): bytes_fmt = FormatRegistry.for_format('bytes')[0] json_fmt = FormatRegistry.for_format('json')[0] some_bytes = b'["phlipper", "piglet"]' assert bytes_fmt.serialize(some_bytes)[0] == some_bytes assert json_fmt.deserialize(some_bytes) == ['phlipper', 'piglet'] def test_formats_serdes(): objects = [ {'blah': 'foo'}, b'blather', 'blip', ] metadata = [{} for o in objects] for obj, meta in zip(objects, metadata): data, format_meta = FormatRegistry.serialize(obj, meta) meta.update(format_meta) assert FormatRegistry.deserialize(data, meta) == obj meta = {} df1 = pd.DataFrame([[1, 2], [3, 4]]) data, format_meta = FormatRegistry.serialize(df1, meta) meta.update(format_meta) df2 = FormatRegistry.deserialize(data, meta) # we can't really get around this nicely -- if header is used, and header names are numeric, # once loaded from CSV, header names are now strings. This causes a bad comparison, so we # cast to int again. df2.columns = df2.columns.astype(int, copy=False) assert df1.equals(df2) def test_formats_csv_read(): csv_file = pathlib.Path(__file__).parent / 'data' / 'csv.csv' meta = {'format': {'name': 'csv'}} expected_bytes = b'a,b,c,d\n1,2,3,4\n5,6,7,8\n' expected_df = FormatRegistry.deserialize(expected_bytes, meta) df = FormatRegistry.deserialize(csv_file.read_bytes(), meta) assert df.equals(expected_df) assert expected_bytes == FormatRegistry.serialize(df, meta)[0] def test_formats_csv_roundtrip(): test_data = b'9,2,5\n7,2,6\n1,0,1\n' # roundtrip defaults. meta = {'format': {'name': 'csv'}} df1 = FormatRegistry.deserialize(test_data, meta) bin, format_meta = FormatRegistry.serialize(df1, meta) meta.update(format_meta) df2 = FormatRegistry.deserialize(bin, meta) assert test_data == bin assert df1.equals(df2) # interpret first row as header meta = {'format': {'name': 'csv', 'opts': {'use_header': True}}} df1 = FormatRegistry.deserialize(test_data, meta) bin, format_meta = FormatRegistry.serialize(df1, meta) meta.update(format_meta) df2 = FormatRegistry.deserialize(bin, meta) assert test_data == bin assert df1.equals(df2) # interpret first column as index meta = {'format': {'name': 'csv', 'opts': {'use_index': True}}} df1 = FormatRegistry.deserialize(test_data, meta) bin, format_meta = FormatRegistry.serialize(df1, meta) meta.update(format_meta) df2 = FormatRegistry.deserialize(bin, meta) assert test_data == bin assert df1.equals(df2) # interpret first row as header, and first column as index meta = {'format': {'name': 'csv', 'opts': {'use_index': True, 'use_header': True}}} df1 = FormatRegistry.deserialize(test_data, meta) bin, format_meta = FormatRegistry.serialize(df1, meta) meta.update(format_meta) df2 = FormatRegistry.deserialize(bin, meta) assert test_data == bin assert df1.equals(df2) def test_formats_search_fail_notfound(): # a search that finds nothing should raise with an explanation. class Foo: pass bad_kwargs = [ dict(obj_type=Foo, meta=None, ext=None), dict(obj_type=None, meta={}, ext=None), dict(obj_type=None, meta=None, ext='.fizz'), ] for args in bad_kwargs: with pytest.raises(QuiltException): FormatRegistry.search(**args)
0.672224
0.44071
class parser: """Parser for OpenFlow packets (C) Copyright Stanford University Date October 2009 Created by ykk """ def __init__(self, messages): """Initialize """ ##Internal reference to OpenFlow messages self.__messages = messages def describe(self, packet): """Parse OpenFlow packet and return string description """ dic = self.__messages.peek_from_front("ofp_header", packet) desc = self.header_describe(dic) if (dic["type"][0] == self.__messages.get_value("OFPT_HELLO")): pass elif (dic["type"][0] == self.__messages.get_value("OFPT_SET_CONFIG")): desc += "\n\t"+self.switch_config_describe(packet) elif (dic["type"][0] == self.__messages.get_value("OFPT_FLOW_MOD")): (fmdic, remaining) = self.__messages.unpack_from_front("ofp_flow_mod", packet) desc += self.flow_mod_describe(fmdic, "\n\t") desc += "\n\twith remaining "+str(len(remaining))+" bytes" else: desc += "\n\tUnparsed..." return desc def flow_mod_describe(self, packet, prefix=""): """Parse flow mod and return description """ dic = self.__assert_dic(packet, "ofp_flow_mod") if (dic == None): return "" return prefix+\ "Flow_mod of command "+self.__messages.get_enum_name("ofp_flow_mod_command", dic["command"][0])+\ " idle/hard timeout:"+str(dic["idle_timeout"][0])+"/"+str(dic["hard_timeout"][0])+\ self.match_describe(dic, "match.", "\n\t")+\ prefix+\ "(priority:"+str(dic["priority"][0])+\ "/buffer id:"+str(dic["buffer_id"][0])+\ "/out port:"+str(dic["out_port"][0])+")" def match_describe(self, dic, nameprefix="", prefix=""): """Return description for ofp match """ return prefix+"match wildcards:%x" % dic[nameprefix+"wildcards"][0]+\ " inport="+str(dic[nameprefix+"in_port"][0])+\ prefix+" "+\ " ethertype="+str(dic[nameprefix+"dl_type"][0])+\ " vlan="+str(dic[nameprefix+"dl_vlan"][0])+\ " "+self.eth_describe(dic[nameprefix+"dl_src"])+"->"+\ self.eth_describe(dic[nameprefix+"dl_dst"])+\ prefix+" "+\ " ipproto="+str(dic[nameprefix+"nw_proto"][0])+\ " "+self.ip_describe(dic[nameprefix+"nw_src"][0])+\ "->"+self.ip_describe(dic[nameprefix+"nw_src"][0])+\ prefix+" "+\ " transport "+str(dic[nameprefix+"tp_src"][0])+\ "->"+str(dic[nameprefix+"tp_dst"][0]) def switch_config_describe(self, packet): """Parse OpenFlow switch config and return description """ dic = self.__assert_dic(packet, "ofp_switch_config") if (dic == None): return "" return "with flag "+str(self.__messages.get_enum_name("ofp_config_flags", dic["flags"][0]))+\ " and miss send length "+str(dic["miss_send_len"][0]) def header_describe(self, packet): """Parse OpenFlow header and return string description """ dic = self.__assert_dic(packet, "ofp_header") if (dic == None): return "" return self.__messages.get_enum_name("ofp_type", dic["type"][0])+" packet "+\ "(length:"+str(dic["length"][0])+\ "/xid:"+str(dic["xid"][0])+")" def ip_describe(self, value): """Return string for ip address """ desc = "" for i in range(0,4): (value, cv) = divmod(value, 256) desc = str(cv).strip() +"." + desc return desc def eth_describe(self, etheraddr): """Return string for ethernet address """ desc = "" for value in etheraddr: desc += ":"+("%x" % value).zfill(2) return desc[1:] def __assert_dic(self, packet, typename): """Assert and ensure dictionary is given """ dic = None if (isinstance(packet, str)): dic = self.__messages.peek_from_front(typename, packet) elif (isinstance(packet, dict)): dic = packet return dic
utils/demo/pylibopenflow/of/msg.py
class parser: """Parser for OpenFlow packets (C) Copyright Stanford University Date October 2009 Created by ykk """ def __init__(self, messages): """Initialize """ ##Internal reference to OpenFlow messages self.__messages = messages def describe(self, packet): """Parse OpenFlow packet and return string description """ dic = self.__messages.peek_from_front("ofp_header", packet) desc = self.header_describe(dic) if (dic["type"][0] == self.__messages.get_value("OFPT_HELLO")): pass elif (dic["type"][0] == self.__messages.get_value("OFPT_SET_CONFIG")): desc += "\n\t"+self.switch_config_describe(packet) elif (dic["type"][0] == self.__messages.get_value("OFPT_FLOW_MOD")): (fmdic, remaining) = self.__messages.unpack_from_front("ofp_flow_mod", packet) desc += self.flow_mod_describe(fmdic, "\n\t") desc += "\n\twith remaining "+str(len(remaining))+" bytes" else: desc += "\n\tUnparsed..." return desc def flow_mod_describe(self, packet, prefix=""): """Parse flow mod and return description """ dic = self.__assert_dic(packet, "ofp_flow_mod") if (dic == None): return "" return prefix+\ "Flow_mod of command "+self.__messages.get_enum_name("ofp_flow_mod_command", dic["command"][0])+\ " idle/hard timeout:"+str(dic["idle_timeout"][0])+"/"+str(dic["hard_timeout"][0])+\ self.match_describe(dic, "match.", "\n\t")+\ prefix+\ "(priority:"+str(dic["priority"][0])+\ "/buffer id:"+str(dic["buffer_id"][0])+\ "/out port:"+str(dic["out_port"][0])+")" def match_describe(self, dic, nameprefix="", prefix=""): """Return description for ofp match """ return prefix+"match wildcards:%x" % dic[nameprefix+"wildcards"][0]+\ " inport="+str(dic[nameprefix+"in_port"][0])+\ prefix+" "+\ " ethertype="+str(dic[nameprefix+"dl_type"][0])+\ " vlan="+str(dic[nameprefix+"dl_vlan"][0])+\ " "+self.eth_describe(dic[nameprefix+"dl_src"])+"->"+\ self.eth_describe(dic[nameprefix+"dl_dst"])+\ prefix+" "+\ " ipproto="+str(dic[nameprefix+"nw_proto"][0])+\ " "+self.ip_describe(dic[nameprefix+"nw_src"][0])+\ "->"+self.ip_describe(dic[nameprefix+"nw_src"][0])+\ prefix+" "+\ " transport "+str(dic[nameprefix+"tp_src"][0])+\ "->"+str(dic[nameprefix+"tp_dst"][0]) def switch_config_describe(self, packet): """Parse OpenFlow switch config and return description """ dic = self.__assert_dic(packet, "ofp_switch_config") if (dic == None): return "" return "with flag "+str(self.__messages.get_enum_name("ofp_config_flags", dic["flags"][0]))+\ " and miss send length "+str(dic["miss_send_len"][0]) def header_describe(self, packet): """Parse OpenFlow header and return string description """ dic = self.__assert_dic(packet, "ofp_header") if (dic == None): return "" return self.__messages.get_enum_name("ofp_type", dic["type"][0])+" packet "+\ "(length:"+str(dic["length"][0])+\ "/xid:"+str(dic["xid"][0])+")" def ip_describe(self, value): """Return string for ip address """ desc = "" for i in range(0,4): (value, cv) = divmod(value, 256) desc = str(cv).strip() +"." + desc return desc def eth_describe(self, etheraddr): """Return string for ethernet address """ desc = "" for value in etheraddr: desc += ":"+("%x" % value).zfill(2) return desc[1:] def __assert_dic(self, packet, typename): """Assert and ensure dictionary is given """ dic = None if (isinstance(packet, str)): dic = self.__messages.peek_from_front(typename, packet) elif (isinstance(packet, dict)): dic = packet return dic
0.459804
0.331661
import inspect import os import random import string import time import pytest from fixedrec import RecordFile, RecordFileError DATADIR = os.path.join(os.path.split(__file__)[0], 'data') + '/blockfile-' def fname(d): fn_name = inspect.currentframe().f_back.f_code.co_name return d / fn_name def test_open(tmpdir): name = fname(tmpdir) ks = RecordFile(name, overwrite=True) assert len(ks) == 0 assert os.stat(name.strpath).st_size == 0 def test_open_small_block(tmpdir): name = fname(tmpdir) with pytest.raises(RecordFileError): RecordFile(name, blocksize=1, overwrite=True) def test_write(tmpdir): name = fname(tmpdir) bf = RecordFile(name, blocksize=4, overwrite=True) bf[-1] = 'aaaa' assert bf[0] == 'aaaa' def test_repr(tmpdir): name = fname(tmpdir) fp = RecordFile(name, blocksize=4, overwrite=True) fp[-1] = 'aaaa' fp[-1] = 'bbbb' assert repr(fp) == 'aaaa\nbbbb' assert str(fp) == 'aaaabbbb' def test_truncate(tmpdir): name = fname(tmpdir) fp = RecordFile(name, blocksize=4, overwrite=True) fp[-1] = 'aaaa' fp[-1] = 'bbbb' fp[-1] = 'cccc' fp.truncate(1) assert str(fp) == 'aaaa' def test_goto_recnum_relative(tmpdir): name = fname(tmpdir) fp = RecordFile(name, blocksize=4, overwrite=True) fp[-1] = 'aaaa' fp[-1] = 'bbbb' fp[-1] = 'cccc' fp.goto_recnum(1) fp.goto_recnum_relative(1) assert fp.read() == 'cccc' fp.goto_recnum(1) fp.goto_recnum_relative(-1) assert fp.read() == 'aaaa' fp.goto_last_record() fp.goto_recnum_relative(-1) assert fp.read() == 'bbbb' def test_swap(tmpdir): name = fname(tmpdir) fp = RecordFile(name, blocksize=4, overwrite=True) fp[-1] = 'aaaa' fp[-1] = 'bbbb' fp[-1] = 'cccc' fp.swap(0, 2) assert str(fp) == 'ccccbbbbaaaa' def test_delete(tmpdir): name = fname(tmpdir) fp = RecordFile(name, blocksize=4, overwrite=True) fp[-1] = 'aaaa' fp[-1] = 'bbbb' fp[-1] = 'cccc' del fp[1] assert str(fp) == 'aaaacccc' def test_read(tmpdir): name = fname(tmpdir) with RecordFile(name, blocksize=4, overwrite=True) as bf: bf[0] = 'aaaa' bf[1] = 'bbbb' bf[2] = 'cccc' bf[1] = 'xxxx' with RecordFile(name, blocksize=4) as b: assert b[0] == 'aaaa' assert b[1] == 'xxxx' assert b[2] == 'cccc' assert len(b) == 3 with RecordFile(name, blocksize=4) as c: assert list(c) == ['aaaa', 'xxxx', 'cccc'] def test_open_missing_file(tmpdir): name = fname(tmpdir) bf = RecordFile(name) assert os.path.exists(name.strpath) def test_out_of_bounds_write(tmpdir): name = fname(tmpdir) bf = RecordFile(name) bf[5] = 'abcd' assert bf[5] == 'abcd' assert len(bf) == 6 def test_err_blocksize(tmpdir): name = fname(tmpdir) with pytest.raises(RecordFileError) as e: bf = RecordFile(name, blocksize=4, overwrite=True) bf[-1] = 'a' * 5 assert "didn't fit" in e.value.message def test_err_no_filename(): with pytest.raises(RecordFileError) as e: bf = RecordFile("") assert e.value.message == 'Missing file name.' @pytest.mark.skipif("1") # skip if running coverage..? def test_speed(tmpdir): # pragma: no cover name = fname(tmpdir) start = time.time() blocksize = 250 records = 500 randpos = [random.randrange(0, records) for _i in range(100000)] bf = RecordFile(name, blocksize=blocksize) data = [] for i in range(blocksize * records): data.append(random.choice(string.letters)) data = ''.join(data) created = time.time() create_step = created - start assert create_step < 0.5 for i in range(records): bf[i] = data[i * blocksize:(i + 1) * blocksize] filled = time.time() filled_step = filled - created assert filled_step < 0.02 for i, p in enumerate(randpos[:10000]): n = i % records bf[p] = data[n * blocksize:(n + 1) * blocksize] writet = time.time() write_step = writet - filled assert write_step < 0.08 # 125K writes/sec for i, p in enumerate(randpos): v = bf[p] readt = time.time() read_step = readt - writet assert read_step < 0.55 # 180K+ reads/sec
tests/test_recordfile.py
import inspect import os import random import string import time import pytest from fixedrec import RecordFile, RecordFileError DATADIR = os.path.join(os.path.split(__file__)[0], 'data') + '/blockfile-' def fname(d): fn_name = inspect.currentframe().f_back.f_code.co_name return d / fn_name def test_open(tmpdir): name = fname(tmpdir) ks = RecordFile(name, overwrite=True) assert len(ks) == 0 assert os.stat(name.strpath).st_size == 0 def test_open_small_block(tmpdir): name = fname(tmpdir) with pytest.raises(RecordFileError): RecordFile(name, blocksize=1, overwrite=True) def test_write(tmpdir): name = fname(tmpdir) bf = RecordFile(name, blocksize=4, overwrite=True) bf[-1] = 'aaaa' assert bf[0] == 'aaaa' def test_repr(tmpdir): name = fname(tmpdir) fp = RecordFile(name, blocksize=4, overwrite=True) fp[-1] = 'aaaa' fp[-1] = 'bbbb' assert repr(fp) == 'aaaa\nbbbb' assert str(fp) == 'aaaabbbb' def test_truncate(tmpdir): name = fname(tmpdir) fp = RecordFile(name, blocksize=4, overwrite=True) fp[-1] = 'aaaa' fp[-1] = 'bbbb' fp[-1] = 'cccc' fp.truncate(1) assert str(fp) == 'aaaa' def test_goto_recnum_relative(tmpdir): name = fname(tmpdir) fp = RecordFile(name, blocksize=4, overwrite=True) fp[-1] = 'aaaa' fp[-1] = 'bbbb' fp[-1] = 'cccc' fp.goto_recnum(1) fp.goto_recnum_relative(1) assert fp.read() == 'cccc' fp.goto_recnum(1) fp.goto_recnum_relative(-1) assert fp.read() == 'aaaa' fp.goto_last_record() fp.goto_recnum_relative(-1) assert fp.read() == 'bbbb' def test_swap(tmpdir): name = fname(tmpdir) fp = RecordFile(name, blocksize=4, overwrite=True) fp[-1] = 'aaaa' fp[-1] = 'bbbb' fp[-1] = 'cccc' fp.swap(0, 2) assert str(fp) == 'ccccbbbbaaaa' def test_delete(tmpdir): name = fname(tmpdir) fp = RecordFile(name, blocksize=4, overwrite=True) fp[-1] = 'aaaa' fp[-1] = 'bbbb' fp[-1] = 'cccc' del fp[1] assert str(fp) == 'aaaacccc' def test_read(tmpdir): name = fname(tmpdir) with RecordFile(name, blocksize=4, overwrite=True) as bf: bf[0] = 'aaaa' bf[1] = 'bbbb' bf[2] = 'cccc' bf[1] = 'xxxx' with RecordFile(name, blocksize=4) as b: assert b[0] == 'aaaa' assert b[1] == 'xxxx' assert b[2] == 'cccc' assert len(b) == 3 with RecordFile(name, blocksize=4) as c: assert list(c) == ['aaaa', 'xxxx', 'cccc'] def test_open_missing_file(tmpdir): name = fname(tmpdir) bf = RecordFile(name) assert os.path.exists(name.strpath) def test_out_of_bounds_write(tmpdir): name = fname(tmpdir) bf = RecordFile(name) bf[5] = 'abcd' assert bf[5] == 'abcd' assert len(bf) == 6 def test_err_blocksize(tmpdir): name = fname(tmpdir) with pytest.raises(RecordFileError) as e: bf = RecordFile(name, blocksize=4, overwrite=True) bf[-1] = 'a' * 5 assert "didn't fit" in e.value.message def test_err_no_filename(): with pytest.raises(RecordFileError) as e: bf = RecordFile("") assert e.value.message == 'Missing file name.' @pytest.mark.skipif("1") # skip if running coverage..? def test_speed(tmpdir): # pragma: no cover name = fname(tmpdir) start = time.time() blocksize = 250 records = 500 randpos = [random.randrange(0, records) for _i in range(100000)] bf = RecordFile(name, blocksize=blocksize) data = [] for i in range(blocksize * records): data.append(random.choice(string.letters)) data = ''.join(data) created = time.time() create_step = created - start assert create_step < 0.5 for i in range(records): bf[i] = data[i * blocksize:(i + 1) * blocksize] filled = time.time() filled_step = filled - created assert filled_step < 0.02 for i, p in enumerate(randpos[:10000]): n = i % records bf[p] = data[n * blocksize:(n + 1) * blocksize] writet = time.time() write_step = writet - filled assert write_step < 0.08 # 125K writes/sec for i, p in enumerate(randpos): v = bf[p] readt = time.time() read_step = readt - writet assert read_step < 0.55 # 180K+ reads/sec
0.231875
0.40987
from inspect import cleandoc from testfixtures import compare from mlinspect._pipeline_inspector import PipelineInspector from mlinspect.inspections import CompletenessOfColumns def test_completeness_merge(): """ Tests whether CompletenessOfColumns works for joins """ test_code = cleandoc(""" import numpy as np import pandas as pd df_a = pd.DataFrame({'A': ['cat_a', None, 'cat_a', 'cat_c', None], 'B': [1, 2, 4, 5, 7]}) df_b = pd.DataFrame({'B': [1, 2, 3, 4, np.nan], 'C': [1, 5, 4, 11, None]}) df_merged = df_a.merge(df_b, on='B') """) inspector_result = PipelineInspector \ .on_pipeline_from_string(test_code) \ .add_required_inspection(CompletenessOfColumns(['A', 'B'])) \ .execute() inspection_results = list(inspector_result.dag_node_to_inspection_results.values()) completeness_output = inspection_results[0][CompletenessOfColumns(['A', 'B'])] expected_completeness = {'A': 0.6, 'B': 1.0} compare(completeness_output, expected_completeness) completeness_output = inspection_results[1][CompletenessOfColumns(['A', 'B'])] expected_completeness = {'B': 0.8} compare(completeness_output, expected_completeness) completeness_output = inspection_results[2][CompletenessOfColumns(['A', 'B'])] expected_completeness = {'A': 2/3, 'B': 1.0} compare(completeness_output, expected_completeness) def test_completeness_projection(): """ Tests whether CompletenessOfColumns works for projections """ test_code = cleandoc(""" import pandas as pd import numpy as np pandas_df = pd.DataFrame({'A': ['cat_a', 'cat_b', None, 'cat_c', 'cat_b'], 'B': [1, None, np.nan, None, 7], 'C': [2, 2, 10, 5, 7]}) pandas_df = pandas_df[['B', 'C']] pandas_df = pandas_df[['C']] """) inspector_result = PipelineInspector \ .on_pipeline_from_string(test_code) \ .add_required_inspection(CompletenessOfColumns(['A', 'B'])) \ .execute() inspection_results = list(inspector_result.dag_node_to_inspection_results.values()) completeness_output = inspection_results[0][CompletenessOfColumns(['A', 'B'])] expected_completeness = {'A': 0.8, 'B': 0.4} compare(completeness_output, expected_completeness) completeness_output = inspection_results[1][CompletenessOfColumns(['A', 'B'])] expected_completeness = {'B': 0.4} compare(completeness_output, expected_completeness) completeness_output = inspection_results[2][CompletenessOfColumns(['A', 'B'])] expected_completeness = {} compare(completeness_output, expected_completeness)
test/inspections/test_completeness_of_columns.py
from inspect import cleandoc from testfixtures import compare from mlinspect._pipeline_inspector import PipelineInspector from mlinspect.inspections import CompletenessOfColumns def test_completeness_merge(): """ Tests whether CompletenessOfColumns works for joins """ test_code = cleandoc(""" import numpy as np import pandas as pd df_a = pd.DataFrame({'A': ['cat_a', None, 'cat_a', 'cat_c', None], 'B': [1, 2, 4, 5, 7]}) df_b = pd.DataFrame({'B': [1, 2, 3, 4, np.nan], 'C': [1, 5, 4, 11, None]}) df_merged = df_a.merge(df_b, on='B') """) inspector_result = PipelineInspector \ .on_pipeline_from_string(test_code) \ .add_required_inspection(CompletenessOfColumns(['A', 'B'])) \ .execute() inspection_results = list(inspector_result.dag_node_to_inspection_results.values()) completeness_output = inspection_results[0][CompletenessOfColumns(['A', 'B'])] expected_completeness = {'A': 0.6, 'B': 1.0} compare(completeness_output, expected_completeness) completeness_output = inspection_results[1][CompletenessOfColumns(['A', 'B'])] expected_completeness = {'B': 0.8} compare(completeness_output, expected_completeness) completeness_output = inspection_results[2][CompletenessOfColumns(['A', 'B'])] expected_completeness = {'A': 2/3, 'B': 1.0} compare(completeness_output, expected_completeness) def test_completeness_projection(): """ Tests whether CompletenessOfColumns works for projections """ test_code = cleandoc(""" import pandas as pd import numpy as np pandas_df = pd.DataFrame({'A': ['cat_a', 'cat_b', None, 'cat_c', 'cat_b'], 'B': [1, None, np.nan, None, 7], 'C': [2, 2, 10, 5, 7]}) pandas_df = pandas_df[['B', 'C']] pandas_df = pandas_df[['C']] """) inspector_result = PipelineInspector \ .on_pipeline_from_string(test_code) \ .add_required_inspection(CompletenessOfColumns(['A', 'B'])) \ .execute() inspection_results = list(inspector_result.dag_node_to_inspection_results.values()) completeness_output = inspection_results[0][CompletenessOfColumns(['A', 'B'])] expected_completeness = {'A': 0.8, 'B': 0.4} compare(completeness_output, expected_completeness) completeness_output = inspection_results[1][CompletenessOfColumns(['A', 'B'])] expected_completeness = {'B': 0.4} compare(completeness_output, expected_completeness) completeness_output = inspection_results[2][CompletenessOfColumns(['A', 'B'])] expected_completeness = {} compare(completeness_output, expected_completeness)
0.660172
0.467879
import os, sys from pip.req import InstallRequirement, RequirementSet from pip.req import parse_requirements from pip.log import logger from pip.locations import build_prefix, src_prefix from pip.basecommand import Command from pip.index import PackageFinder from pip.exceptions import InstallationError class InstallCommand(Command): name = 'install' usage = '%prog [OPTIONS] PACKAGE_NAMES...' summary = 'Install packages' bundle = False def __init__(self): super(InstallCommand, self).__init__() self.parser.add_option( '-e', '--editable', dest='editables', action='append', default=[], metavar='VCS+REPOS_URL[@REV]#egg=PACKAGE', help='Install a package directly from a checkout. Source will be checked ' 'out into src/PACKAGE (lower-case) and installed in-place (using ' 'setup.py develop). You can run this on an existing directory/checkout (like ' 'pip install -e src/mycheckout). This option may be provided multiple times. ' 'Possible values for VCS are: svn, git, hg and bzr.') self.parser.add_option( '-r', '--requirement', dest='requirements', action='append', default=[], metavar='FILENAME', help='Install all the packages listed in the given requirements file. ' 'This option can be used multiple times.') self.parser.add_option( '-f', '--find-links', dest='find_links', action='append', default=[], metavar='URL', help='URL to look for packages at') self.parser.add_option( '-i', '--index-url', '--pypi-url', dest='index_url', metavar='URL', default='http://pypi.python.org/simple/', help='Base URL of Python Package Index (default %default)') self.parser.add_option( '--extra-index-url', dest='extra_index_urls', metavar='URL', action='append', default=[], help='Extra URLs of package indexes to use in addition to --index-url') self.parser.add_option( '--no-index', dest='no_index', action='store_true', default=False, help='Ignore package index (only looking at --find-links URLs instead)') self.parser.add_option( '-M', '--use-mirrors', dest='use_mirrors', action='store_true', default=False, help='Use the PyPI mirrors as a fallback in case the main index is down.') self.parser.add_option( '--mirrors', dest='mirrors', metavar='URL', action='append', default=[], help='Specific mirror URLs to query when --use-mirrors is used') self.parser.add_option( '-b', '--build', '--build-dir', '--build-directory', dest='build_dir', metavar='DIR', default=None, help='Unpack packages into DIR (default %s) and build from there' % build_prefix) self.parser.add_option( '-d', '--download', '--download-dir', '--download-directory', dest='download_dir', metavar='DIR', default=None, help='Download packages into DIR instead of installing them') self.parser.add_option( '--download-cache', dest='download_cache', metavar='DIR', default=None, help='Cache downloaded packages in DIR') self.parser.add_option( '--src', '--source', '--source-dir', '--source-directory', dest='src_dir', metavar='DIR', default=None, help='Check out --editable packages into DIR (default %s)' % src_prefix) self.parser.add_option( '-U', '--upgrade', dest='upgrade', action='store_true', help='Upgrade all packages to the newest available version') self.parser.add_option( '-I', '--ignore-installed', dest='ignore_installed', action='store_true', help='Ignore the installed packages (reinstalling instead)') self.parser.add_option( '--no-deps', '--no-dependencies', dest='ignore_dependencies', action='store_true', default=False, help='Ignore package dependencies') self.parser.add_option( '--no-install', dest='no_install', action='store_true', help="Download and unpack all packages, but don't actually install them") self.parser.add_option( '--no-download', dest='no_download', action="store_true", help="Don't download any packages, just install the ones already downloaded " "(completes an install run with --no-install)") self.parser.add_option( '--install-option', dest='install_options', action='append', help="Extra arguments to be supplied to the setup.py install " "command (use like --install-option=\"--install-scripts=/usr/local/bin\"). " "Use multiple --install-option options to pass multiple options to setup.py install. " "If you are using an option with a directory path, be sure to use absolute path.") self.parser.add_option( '--global-option', dest='global_options', action='append', help="Extra global options to be supplied to the setup.py" "call before the install command") self.parser.add_option( '--user', dest='use_user_site', action='store_true', help='Install to user-site') def _build_package_finder(self, options, index_urls): """ Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly. """ return PackageFinder(find_links=options.find_links, index_urls=index_urls, use_mirrors=options.use_mirrors, mirrors=options.mirrors) def run(self, options, args): if not options.build_dir: options.build_dir = build_prefix if not options.src_dir: options.src_dir = src_prefix if options.download_dir: options.no_install = True options.ignore_installed = True options.build_dir = os.path.abspath(options.build_dir) options.src_dir = os.path.abspath(options.src_dir) install_options = options.install_options or [] if options.use_user_site: install_options.append('--user') global_options = options.global_options or [] index_urls = [options.index_url] + options.extra_index_urls if options.no_index: logger.notify('Ignoring indexes: %s' % ','.join(index_urls)) index_urls = [] finder = self._build_package_finder(options, index_urls) requirement_set = RequirementSet( build_dir=options.build_dir, src_dir=options.src_dir, download_dir=options.download_dir, download_cache=options.download_cache, upgrade=options.upgrade, ignore_installed=options.ignore_installed, ignore_dependencies=options.ignore_dependencies) for name in args: requirement_set.add_requirement( InstallRequirement.from_line(name, None)) for name in options.editables: requirement_set.add_requirement( InstallRequirement.from_editable(name, default_vcs=options.default_vcs)) for filename in options.requirements: for req in parse_requirements(filename, finder=finder, options=options): requirement_set.add_requirement(req) if not requirement_set.has_requirements: if options.find_links: raise InstallationError('You must give at least one ' 'requirement to %s (maybe you meant "pip install %s"?)' % (self.name, " ".join(options.find_links))) raise InstallationError('You must give at least one requirement ' 'to %(name)s (see "pip help %(name)s")' % dict(name=self.name)) if (options.use_user_site and sys.version_info < (2, 6)): raise InstallationError('--user is only supported in Python version 2.6 and newer') import setuptools if (options.use_user_site and requirement_set.has_editables and not getattr(setuptools, '_distribute', False)): raise InstallationError('--user --editable not supported with setuptools, use distribute') if not options.no_download: requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) else: requirement_set.locate_files() if not options.no_install and not self.bundle: requirement_set.install(install_options, global_options) installed = ' '.join([req.name for req in requirement_set.successfully_installed]) if installed: logger.notify('Successfully installed %s' % installed) elif not self.bundle: downloaded = ' '.join([req.name for req in requirement_set.successfully_downloaded]) if downloaded: logger.notify('Successfully downloaded %s' % downloaded) elif self.bundle: requirement_set.create_bundle(self.bundle_filename) logger.notify('Created bundle in %s' % self.bundle_filename) # Clean up if not options.no_install: requirement_set.cleanup_files(bundle=self.bundle) return requirement_set InstallCommand()
docs/docs_env/Lib/site-packages/pip-1.0-py2.5.egg/pip/commands/install.py
import os, sys from pip.req import InstallRequirement, RequirementSet from pip.req import parse_requirements from pip.log import logger from pip.locations import build_prefix, src_prefix from pip.basecommand import Command from pip.index import PackageFinder from pip.exceptions import InstallationError class InstallCommand(Command): name = 'install' usage = '%prog [OPTIONS] PACKAGE_NAMES...' summary = 'Install packages' bundle = False def __init__(self): super(InstallCommand, self).__init__() self.parser.add_option( '-e', '--editable', dest='editables', action='append', default=[], metavar='VCS+REPOS_URL[@REV]#egg=PACKAGE', help='Install a package directly from a checkout. Source will be checked ' 'out into src/PACKAGE (lower-case) and installed in-place (using ' 'setup.py develop). You can run this on an existing directory/checkout (like ' 'pip install -e src/mycheckout). This option may be provided multiple times. ' 'Possible values for VCS are: svn, git, hg and bzr.') self.parser.add_option( '-r', '--requirement', dest='requirements', action='append', default=[], metavar='FILENAME', help='Install all the packages listed in the given requirements file. ' 'This option can be used multiple times.') self.parser.add_option( '-f', '--find-links', dest='find_links', action='append', default=[], metavar='URL', help='URL to look for packages at') self.parser.add_option( '-i', '--index-url', '--pypi-url', dest='index_url', metavar='URL', default='http://pypi.python.org/simple/', help='Base URL of Python Package Index (default %default)') self.parser.add_option( '--extra-index-url', dest='extra_index_urls', metavar='URL', action='append', default=[], help='Extra URLs of package indexes to use in addition to --index-url') self.parser.add_option( '--no-index', dest='no_index', action='store_true', default=False, help='Ignore package index (only looking at --find-links URLs instead)') self.parser.add_option( '-M', '--use-mirrors', dest='use_mirrors', action='store_true', default=False, help='Use the PyPI mirrors as a fallback in case the main index is down.') self.parser.add_option( '--mirrors', dest='mirrors', metavar='URL', action='append', default=[], help='Specific mirror URLs to query when --use-mirrors is used') self.parser.add_option( '-b', '--build', '--build-dir', '--build-directory', dest='build_dir', metavar='DIR', default=None, help='Unpack packages into DIR (default %s) and build from there' % build_prefix) self.parser.add_option( '-d', '--download', '--download-dir', '--download-directory', dest='download_dir', metavar='DIR', default=None, help='Download packages into DIR instead of installing them') self.parser.add_option( '--download-cache', dest='download_cache', metavar='DIR', default=None, help='Cache downloaded packages in DIR') self.parser.add_option( '--src', '--source', '--source-dir', '--source-directory', dest='src_dir', metavar='DIR', default=None, help='Check out --editable packages into DIR (default %s)' % src_prefix) self.parser.add_option( '-U', '--upgrade', dest='upgrade', action='store_true', help='Upgrade all packages to the newest available version') self.parser.add_option( '-I', '--ignore-installed', dest='ignore_installed', action='store_true', help='Ignore the installed packages (reinstalling instead)') self.parser.add_option( '--no-deps', '--no-dependencies', dest='ignore_dependencies', action='store_true', default=False, help='Ignore package dependencies') self.parser.add_option( '--no-install', dest='no_install', action='store_true', help="Download and unpack all packages, but don't actually install them") self.parser.add_option( '--no-download', dest='no_download', action="store_true", help="Don't download any packages, just install the ones already downloaded " "(completes an install run with --no-install)") self.parser.add_option( '--install-option', dest='install_options', action='append', help="Extra arguments to be supplied to the setup.py install " "command (use like --install-option=\"--install-scripts=/usr/local/bin\"). " "Use multiple --install-option options to pass multiple options to setup.py install. " "If you are using an option with a directory path, be sure to use absolute path.") self.parser.add_option( '--global-option', dest='global_options', action='append', help="Extra global options to be supplied to the setup.py" "call before the install command") self.parser.add_option( '--user', dest='use_user_site', action='store_true', help='Install to user-site') def _build_package_finder(self, options, index_urls): """ Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly. """ return PackageFinder(find_links=options.find_links, index_urls=index_urls, use_mirrors=options.use_mirrors, mirrors=options.mirrors) def run(self, options, args): if not options.build_dir: options.build_dir = build_prefix if not options.src_dir: options.src_dir = src_prefix if options.download_dir: options.no_install = True options.ignore_installed = True options.build_dir = os.path.abspath(options.build_dir) options.src_dir = os.path.abspath(options.src_dir) install_options = options.install_options or [] if options.use_user_site: install_options.append('--user') global_options = options.global_options or [] index_urls = [options.index_url] + options.extra_index_urls if options.no_index: logger.notify('Ignoring indexes: %s' % ','.join(index_urls)) index_urls = [] finder = self._build_package_finder(options, index_urls) requirement_set = RequirementSet( build_dir=options.build_dir, src_dir=options.src_dir, download_dir=options.download_dir, download_cache=options.download_cache, upgrade=options.upgrade, ignore_installed=options.ignore_installed, ignore_dependencies=options.ignore_dependencies) for name in args: requirement_set.add_requirement( InstallRequirement.from_line(name, None)) for name in options.editables: requirement_set.add_requirement( InstallRequirement.from_editable(name, default_vcs=options.default_vcs)) for filename in options.requirements: for req in parse_requirements(filename, finder=finder, options=options): requirement_set.add_requirement(req) if not requirement_set.has_requirements: if options.find_links: raise InstallationError('You must give at least one ' 'requirement to %s (maybe you meant "pip install %s"?)' % (self.name, " ".join(options.find_links))) raise InstallationError('You must give at least one requirement ' 'to %(name)s (see "pip help %(name)s")' % dict(name=self.name)) if (options.use_user_site and sys.version_info < (2, 6)): raise InstallationError('--user is only supported in Python version 2.6 and newer') import setuptools if (options.use_user_site and requirement_set.has_editables and not getattr(setuptools, '_distribute', False)): raise InstallationError('--user --editable not supported with setuptools, use distribute') if not options.no_download: requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) else: requirement_set.locate_files() if not options.no_install and not self.bundle: requirement_set.install(install_options, global_options) installed = ' '.join([req.name for req in requirement_set.successfully_installed]) if installed: logger.notify('Successfully installed %s' % installed) elif not self.bundle: downloaded = ' '.join([req.name for req in requirement_set.successfully_downloaded]) if downloaded: logger.notify('Successfully downloaded %s' % downloaded) elif self.bundle: requirement_set.create_bundle(self.bundle_filename) logger.notify('Created bundle in %s' % self.bundle_filename) # Clean up if not options.no_install: requirement_set.cleanup_files(bundle=self.bundle) return requirement_set InstallCommand()
0.341253
0.069795
from __future__ import absolute_import import bson import mock from st2common.constants.triggers import TIMER_TRIGGER_TYPES from st2common.models.db.trigger import TriggerDB from st2common.models.system.common import ResourceReference from st2common.persistence.trigger import TriggerType from st2common.persistence.trigger import Trigger from st2reactor.timer.base import St2Timer from st2tests.base import CleanDbTestCase class St2TimerTestCase(CleanDbTestCase): def test_trigger_types_are_registered_on_start(self): timer = St2Timer() timer._scheduler = mock.Mock() # Verify there are no TriggerType in the db when we start self.assertItemsEqual(TriggerType.get_all(), []) timer.start() # Verify TriggerType objects have been created trigger_type_dbs = TriggerType.get_all() self.assertEqual(len(trigger_type_dbs), len(TIMER_TRIGGER_TYPES)) timer_trigger_type_refs = list(TIMER_TRIGGER_TYPES.keys()) for trigger_type in trigger_type_dbs: ref = ResourceReference(pack=trigger_type.pack, name=trigger_type.name).ref self.assertIn(ref, timer_trigger_type_refs) def test_existing_rules_are_loaded_on_start(self): # Assert that we dispatch message for every existing Trigger object St2Timer._handle_create_trigger = mock.Mock() timer = St2Timer() timer._scheduler = mock.Mock() timer._trigger_watcher.run = mock.Mock() # Verify there are no Trigger and TriggerType in the db wh:w self.assertItemsEqual(Trigger.get_all(), []) self.assertItemsEqual(TriggerType.get_all(), []) # Add a dummy timer Trigger object type_ = list(TIMER_TRIGGER_TYPES.keys())[0] parameters = {'unit': 'seconds', 'delta': 1000} trigger_db = TriggerDB(id=bson.ObjectId(), name='test_trigger_1', pack='dummy', type=type_, parameters=parameters) trigger_db = Trigger.add_or_update(trigger_db) # Verify object has been added self.assertEqual(len(Trigger.get_all()), 1) timer.start() timer._trigger_watcher._load_thread.wait() # Verify handlers are called timer._handle_create_trigger.assert_called_with(trigger_db) @mock.patch('st2common.transport.reactor.TriggerDispatcher.dispatch') def test_timer_trace_tag_creation(self, dispatch_mock): timer = St2Timer() timer._scheduler = mock.Mock() timer._trigger_watcher = mock.Mock() # Add a dummy timer Trigger object type_ = list(TIMER_TRIGGER_TYPES.keys())[0] parameters = {'unit': 'seconds', 'delta': 1} trigger_db = TriggerDB(name='test_trigger_1', pack='dummy', type=type_, parameters=parameters) timer.add_trigger(trigger_db) timer._emit_trigger_instance(trigger=trigger_db.to_serializable_dict()) self.assertEqual(dispatch_mock.call_args[1]['trace_context'].trace_tag, '%s-%s' % (TIMER_TRIGGER_TYPES[type_]['name'], trigger_db.name))
st2reactor/tests/unit/test_timer.py
from __future__ import absolute_import import bson import mock from st2common.constants.triggers import TIMER_TRIGGER_TYPES from st2common.models.db.trigger import TriggerDB from st2common.models.system.common import ResourceReference from st2common.persistence.trigger import TriggerType from st2common.persistence.trigger import Trigger from st2reactor.timer.base import St2Timer from st2tests.base import CleanDbTestCase class St2TimerTestCase(CleanDbTestCase): def test_trigger_types_are_registered_on_start(self): timer = St2Timer() timer._scheduler = mock.Mock() # Verify there are no TriggerType in the db when we start self.assertItemsEqual(TriggerType.get_all(), []) timer.start() # Verify TriggerType objects have been created trigger_type_dbs = TriggerType.get_all() self.assertEqual(len(trigger_type_dbs), len(TIMER_TRIGGER_TYPES)) timer_trigger_type_refs = list(TIMER_TRIGGER_TYPES.keys()) for trigger_type in trigger_type_dbs: ref = ResourceReference(pack=trigger_type.pack, name=trigger_type.name).ref self.assertIn(ref, timer_trigger_type_refs) def test_existing_rules_are_loaded_on_start(self): # Assert that we dispatch message for every existing Trigger object St2Timer._handle_create_trigger = mock.Mock() timer = St2Timer() timer._scheduler = mock.Mock() timer._trigger_watcher.run = mock.Mock() # Verify there are no Trigger and TriggerType in the db wh:w self.assertItemsEqual(Trigger.get_all(), []) self.assertItemsEqual(TriggerType.get_all(), []) # Add a dummy timer Trigger object type_ = list(TIMER_TRIGGER_TYPES.keys())[0] parameters = {'unit': 'seconds', 'delta': 1000} trigger_db = TriggerDB(id=bson.ObjectId(), name='test_trigger_1', pack='dummy', type=type_, parameters=parameters) trigger_db = Trigger.add_or_update(trigger_db) # Verify object has been added self.assertEqual(len(Trigger.get_all()), 1) timer.start() timer._trigger_watcher._load_thread.wait() # Verify handlers are called timer._handle_create_trigger.assert_called_with(trigger_db) @mock.patch('st2common.transport.reactor.TriggerDispatcher.dispatch') def test_timer_trace_tag_creation(self, dispatch_mock): timer = St2Timer() timer._scheduler = mock.Mock() timer._trigger_watcher = mock.Mock() # Add a dummy timer Trigger object type_ = list(TIMER_TRIGGER_TYPES.keys())[0] parameters = {'unit': 'seconds', 'delta': 1} trigger_db = TriggerDB(name='test_trigger_1', pack='dummy', type=type_, parameters=parameters) timer.add_trigger(trigger_db) timer._emit_trigger_instance(trigger=trigger_db.to_serializable_dict()) self.assertEqual(dispatch_mock.call_args[1]['trace_context'].trace_tag, '%s-%s' % (TIMER_TRIGGER_TYPES[type_]['name'], trigger_db.name))
0.758332
0.267996
from django.conf import settings from django.shortcuts import redirect from django.urls import reverse, reverse_lazy from django.utils.http import is_safe_url from django.utils.translation import gettext_lazy as _ from django.views.generic import FormView, TemplateView from mtp_common.auth.api_client import get_api_session from security import hmpps_employee_flag, not_hmpps_employee_flag from security.forms.eligibility import HMPPSEmployeeForm from security.utils import save_user_flags class HMPPSEmployeeView(FormView): title = _('Confirm your eligibility') template_name = 'hmpps-employee.html' form_class = HMPPSEmployeeForm success_url = reverse_lazy(settings.LOGIN_REDIRECT_URL) not_employee_url = reverse_lazy('security:not_hmpps_employee') def dispatch(self, request, *args, **kwargs): if not request.can_access_security: return redirect(self.success_url) flags = request.user.user_data.get('flags') or [] if hmpps_employee_flag in flags: return redirect(self.success_url) if not_hmpps_employee_flag in flags: return redirect(self.not_employee_url) request.cannot_navigate_away = True return super().dispatch(request, *args, **kwargs) def get_initial(self): initial = super().get_initial() initial['next'] = self.request.META.get('HTTP_REFERER', '') return initial def form_valid(self, form): api_session = get_api_session(self.request) confirmation = form.cleaned_data['confirmation'] if confirmation == 'yes': save_user_flags(self.request, hmpps_employee_flag, api_session) success_url = form.cleaned_data['next'] if success_url and is_safe_url(success_url, allowed_hosts=self.request.get_host()): self.success_url = success_url return super().form_valid(form) else: save_user_flags(self.request, not_hmpps_employee_flag, api_session) api_session.delete('/users/%s/' % self.request.user.username) self.request.session.flush() return redirect(self.not_employee_url) class NotHMPPSEmployeeView(TemplateView): title = _('You can’t use this tool') template_name = 'not-hmpps-employee.html' def dispatch(self, request, *args, **kwargs): flags = request.user.user_data.get('flags') or [] if request.user.is_authenticated and not_hmpps_employee_flag not in flags: return redirect(reverse(settings.LOGIN_REDIRECT_URL)) request.cannot_navigate_away = True return super().dispatch(request, *args, **kwargs)
mtp_noms_ops/apps/security/views/eligibility.py
from django.conf import settings from django.shortcuts import redirect from django.urls import reverse, reverse_lazy from django.utils.http import is_safe_url from django.utils.translation import gettext_lazy as _ from django.views.generic import FormView, TemplateView from mtp_common.auth.api_client import get_api_session from security import hmpps_employee_flag, not_hmpps_employee_flag from security.forms.eligibility import HMPPSEmployeeForm from security.utils import save_user_flags class HMPPSEmployeeView(FormView): title = _('Confirm your eligibility') template_name = 'hmpps-employee.html' form_class = HMPPSEmployeeForm success_url = reverse_lazy(settings.LOGIN_REDIRECT_URL) not_employee_url = reverse_lazy('security:not_hmpps_employee') def dispatch(self, request, *args, **kwargs): if not request.can_access_security: return redirect(self.success_url) flags = request.user.user_data.get('flags') or [] if hmpps_employee_flag in flags: return redirect(self.success_url) if not_hmpps_employee_flag in flags: return redirect(self.not_employee_url) request.cannot_navigate_away = True return super().dispatch(request, *args, **kwargs) def get_initial(self): initial = super().get_initial() initial['next'] = self.request.META.get('HTTP_REFERER', '') return initial def form_valid(self, form): api_session = get_api_session(self.request) confirmation = form.cleaned_data['confirmation'] if confirmation == 'yes': save_user_flags(self.request, hmpps_employee_flag, api_session) success_url = form.cleaned_data['next'] if success_url and is_safe_url(success_url, allowed_hosts=self.request.get_host()): self.success_url = success_url return super().form_valid(form) else: save_user_flags(self.request, not_hmpps_employee_flag, api_session) api_session.delete('/users/%s/' % self.request.user.username) self.request.session.flush() return redirect(self.not_employee_url) class NotHMPPSEmployeeView(TemplateView): title = _('You can’t use this tool') template_name = 'not-hmpps-employee.html' def dispatch(self, request, *args, **kwargs): flags = request.user.user_data.get('flags') or [] if request.user.is_authenticated and not_hmpps_employee_flag not in flags: return redirect(reverse(settings.LOGIN_REDIRECT_URL)) request.cannot_navigate_away = True return super().dispatch(request, *args, **kwargs)
0.393152
0.064271
import os import urllib.request from PIL import Image import numpy as np import tensorflow as tf import tensorflow_hub as hub import config def save_image_from_message(message, telbot): cid = message.chat.id image_id = get_image_id_from_message(message) # prepare image for downloading file_path = telbot.get_file(image_id).file_path # generate image download url image_url = "https://api.telegram.org/file/bot{0}/{1}".format(config.TOKEN, file_path) # create folder to store image temporary, if it doesnt exist if not os.path.exists(config.result_storage_path): os.makedirs(config.result_storage_path) # retrieve and save image image_name = "{0}.jpg".format(image_id) urllib.request.urlretrieve(image_url, "{0}/{1}".format(config.result_storage_path, image_name)) return image_name def get_image_id_from_message(message): # there are multiple array of images, check the biggest return message.photo[len(message.photo) - 1].file_id def handle_image(image_name, cid): if config.dict_styles_established[cid] == 'standard style established': style_number = config.dict_styles[cid] del config.dict_styles[cid] style_image_name = "handled_style{0}.jpg".format(style_number) style_image = Image.open("{0}/{1}".format(config.result_storage_path, style_image_name)) else: style_image_name = config.dict_styles_established[cid] style_image = Image.open("{0}/{1}".format(config.result_storage_path, style_image_name)) style_image = image_to_square(style_image, 256) style_img = np.array(style_image) style_img = style_img.astype(np.float32)[np.newaxis, ...] / 255. content_image = Image.open("{0}/{1}".format(config.result_storage_path, image_name)) image_resized = image_reduce(content_image, 384) content_img = np.array(image_resized) content_img = content_img.astype(np.float32)[np.newaxis, ...] / 255. hub_module = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2') outputs = hub_module(tf.constant(content_img), tf.constant(style_img)) stylized_image = outputs[0] result_img = tf.squeeze(stylized_image) result_im = tf.cast(result_img * 255, tf.uint8) result_img_pillow = Image.fromarray(result_im.numpy()) image_name_new = "handled_image_" + image_name result_img_pillow.save("{0}/{1}".format(config.result_storage_path, image_name_new)) return image_name_new def cleanup_remove_images(image_name, image_name_new, style_image_name): os.remove('{0}/{1}'.format(config.result_storage_path, image_name)) os.remove('{0}/{1}'.format(config.result_storage_path, image_name_new)) if style_image_name != 'standard style established': os.remove('{0}/{1}'.format(config.result_storage_path, style_image_name)) def get_save_style_image(number): # create folder to store image temporary, if it doesnt exist if not os.path.exists(config.result_storage_path): os.makedirs(config.result_storage_path) if not os.path.exists("{0}/handled_style{1}.jpg".format(config.result_storage_path, number)): image_mame = "style{0}.jpg".format(number) image_path = "static/" + image_mame style_image = Image.open(image_path) image_square_resized = image_to_square(style_image, 256) style_image_name = "handled_" + image_mame image_square_resized.save("{0}/{1}".format(config.result_storage_path, style_image_name)) else: style_image_name = "handled_style{0}.jpg".format(number) return style_image_name def image_to_square(image_name, image_size): width = image_name.width height = image_name.height if width == height: image_square_resized = image_name.resize((image_size, image_size)) elif width > height: image_crop = image_name.crop(((width // 2 - height // 2), 0, (width // 2 - height // 2) + height, height)) image_square_resized = image_crop.resize((image_size, image_size)) else: image_crop = image_name.crop((0, (height // 2 - width // 2), width, (height // 2 - width // 2) + width)) image_square_resized = image_crop.resize((image_size, image_size)) return image_square_resized def image_reduce(image_name, width_size): width = image_name.width height = image_name.height if width == height & width > width_size: image_resized = image_name.resize((width_size, width_size)) elif width > width_size: factor = width / width_size image_resized = image_name.resize((width_size, round(height / factor))) else: image_resized = image_name return image_resized
image_utils.py
import os import urllib.request from PIL import Image import numpy as np import tensorflow as tf import tensorflow_hub as hub import config def save_image_from_message(message, telbot): cid = message.chat.id image_id = get_image_id_from_message(message) # prepare image for downloading file_path = telbot.get_file(image_id).file_path # generate image download url image_url = "https://api.telegram.org/file/bot{0}/{1}".format(config.TOKEN, file_path) # create folder to store image temporary, if it doesnt exist if not os.path.exists(config.result_storage_path): os.makedirs(config.result_storage_path) # retrieve and save image image_name = "{0}.jpg".format(image_id) urllib.request.urlretrieve(image_url, "{0}/{1}".format(config.result_storage_path, image_name)) return image_name def get_image_id_from_message(message): # there are multiple array of images, check the biggest return message.photo[len(message.photo) - 1].file_id def handle_image(image_name, cid): if config.dict_styles_established[cid] == 'standard style established': style_number = config.dict_styles[cid] del config.dict_styles[cid] style_image_name = "handled_style{0}.jpg".format(style_number) style_image = Image.open("{0}/{1}".format(config.result_storage_path, style_image_name)) else: style_image_name = config.dict_styles_established[cid] style_image = Image.open("{0}/{1}".format(config.result_storage_path, style_image_name)) style_image = image_to_square(style_image, 256) style_img = np.array(style_image) style_img = style_img.astype(np.float32)[np.newaxis, ...] / 255. content_image = Image.open("{0}/{1}".format(config.result_storage_path, image_name)) image_resized = image_reduce(content_image, 384) content_img = np.array(image_resized) content_img = content_img.astype(np.float32)[np.newaxis, ...] / 255. hub_module = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2') outputs = hub_module(tf.constant(content_img), tf.constant(style_img)) stylized_image = outputs[0] result_img = tf.squeeze(stylized_image) result_im = tf.cast(result_img * 255, tf.uint8) result_img_pillow = Image.fromarray(result_im.numpy()) image_name_new = "handled_image_" + image_name result_img_pillow.save("{0}/{1}".format(config.result_storage_path, image_name_new)) return image_name_new def cleanup_remove_images(image_name, image_name_new, style_image_name): os.remove('{0}/{1}'.format(config.result_storage_path, image_name)) os.remove('{0}/{1}'.format(config.result_storage_path, image_name_new)) if style_image_name != 'standard style established': os.remove('{0}/{1}'.format(config.result_storage_path, style_image_name)) def get_save_style_image(number): # create folder to store image temporary, if it doesnt exist if not os.path.exists(config.result_storage_path): os.makedirs(config.result_storage_path) if not os.path.exists("{0}/handled_style{1}.jpg".format(config.result_storage_path, number)): image_mame = "style{0}.jpg".format(number) image_path = "static/" + image_mame style_image = Image.open(image_path) image_square_resized = image_to_square(style_image, 256) style_image_name = "handled_" + image_mame image_square_resized.save("{0}/{1}".format(config.result_storage_path, style_image_name)) else: style_image_name = "handled_style{0}.jpg".format(number) return style_image_name def image_to_square(image_name, image_size): width = image_name.width height = image_name.height if width == height: image_square_resized = image_name.resize((image_size, image_size)) elif width > height: image_crop = image_name.crop(((width // 2 - height // 2), 0, (width // 2 - height // 2) + height, height)) image_square_resized = image_crop.resize((image_size, image_size)) else: image_crop = image_name.crop((0, (height // 2 - width // 2), width, (height // 2 - width // 2) + width)) image_square_resized = image_crop.resize((image_size, image_size)) return image_square_resized def image_reduce(image_name, width_size): width = image_name.width height = image_name.height if width == height & width > width_size: image_resized = image_name.resize((width_size, width_size)) elif width > width_size: factor = width / width_size image_resized = image_name.resize((width_size, round(height / factor))) else: image_resized = image_name return image_resized
0.385953
0.166743
import datetime from unittest import mock from django.db import ( IntegrityError, NotSupportedError, connection, transaction, ) from django.db.models import ( CheckConstraint, Deferrable, F, Func, Q, UniqueConstraint, ) from django.db.models.fields.json import KeyTextTransform from django.db.models.functions import Left from django.test import skipUnlessDBFeature from django.utils import timezone from . import PostgreSQLTestCase from .models import HotelReservation, RangesModel, Room, Scene try: from psycopg2.extras import DateRange, NumericRange from django.contrib.postgres.constraints import ExclusionConstraint from django.contrib.postgres.fields import ( DateTimeRangeField, RangeBoundary, RangeOperators, ) except ImportError: pass class SchemaTests(PostgreSQLTestCase): get_opclass_query = ''' SELECT opcname, c.relname FROM pg_opclass AS oc JOIN pg_index as i on oc.oid = ANY(i.indclass) JOIN pg_class as c on c.oid = i.indexrelid WHERE c.relname = %s ''' def get_constraints(self, table): """Get the constraints on the table using a new cursor.""" with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def test_check_constraint_range_value(self): constraint_name = 'ints_between' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = CheckConstraint( check=Q(ints__contained_by=NumericRange(10, 30)), name=constraint_name, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(20, 50)) RangesModel.objects.create(ints=(10, 30)) def test_check_constraint_daterange_contains(self): constraint_name = 'dates_contains' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = CheckConstraint( check=Q(dates__contains=F('dates_inner')), name=constraint_name, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) date_1 = datetime.date(2016, 1, 1) date_2 = datetime.date(2016, 1, 4) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create( dates=(date_1, date_2), dates_inner=(date_1, date_2.replace(day=5)), ) RangesModel.objects.create( dates=(date_1, date_2), dates_inner=(date_1, date_2), ) def test_check_constraint_datetimerange_contains(self): constraint_name = 'timestamps_contains' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = CheckConstraint( check=Q(timestamps__contains=F('timestamps_inner')), name=constraint_name, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) datetime_1 = datetime.datetime(2016, 1, 1) datetime_2 = datetime.datetime(2016, 1, 2, 12) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create( timestamps=(datetime_1, datetime_2), timestamps_inner=(datetime_1, datetime_2.replace(hour=13)), ) RangesModel.objects.create( timestamps=(datetime_1, datetime_2), timestamps_inner=(datetime_1, datetime_2), ) def test_opclass(self): constraint = UniqueConstraint( name='test_opclass', fields=['scene'], opclasses=['varchar_pattern_ops'], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) self.assertIn(constraint.name, self.get_constraints(Scene._meta.db_table)) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) self.assertEqual( cursor.fetchall(), [('varchar_pattern_ops', constraint.name)], ) # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(Scene, constraint) self.assertNotIn(constraint.name, self.get_constraints(Scene._meta.db_table)) def test_opclass_multiple_columns(self): constraint = UniqueConstraint( name='test_opclass_multiple', fields=['scene', 'setting'], opclasses=['varchar_pattern_ops', 'text_pattern_ops'], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) expected_opclasses = ( ('varchar_pattern_ops', constraint.name), ('text_pattern_ops', constraint.name), ) self.assertCountEqual(cursor.fetchall(), expected_opclasses) def test_opclass_partial(self): constraint = UniqueConstraint( name='test_opclass_partial', fields=['scene'], opclasses=['varchar_pattern_ops'], condition=Q(setting__contains="Sir Bedemir's Castle"), ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) self.assertCountEqual( cursor.fetchall(), [('varchar_pattern_ops', constraint.name)], ) @skipUnlessDBFeature('supports_covering_indexes') def test_opclass_include(self): constraint = UniqueConstraint( name='test_opclass_include', fields=['scene'], opclasses=['varchar_pattern_ops'], include=['setting'], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) self.assertCountEqual( cursor.fetchall(), [('varchar_pattern_ops', constraint.name)], ) class ExclusionConstraintTests(PostgreSQLTestCase): def get_constraints(self, table): """Get the constraints on the table using a new cursor.""" with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def test_invalid_condition(self): msg = 'ExclusionConstraint.condition must be a Q instance.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type='GIST', name='exclude_invalid_condition', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], condition=F('invalid'), ) def test_invalid_index_type(self): msg = 'Exclusion constraints only support GiST or SP-GiST indexes.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type='gin', name='exclude_invalid_index_type', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], ) def test_invalid_expressions(self): msg = 'The expressions must be a list of 2-tuples.' for expressions in (['foo'], [('foo')], [('foo_1', 'foo_2', 'foo_3')]): with self.subTest(expressions), self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type='GIST', name='exclude_invalid_expressions', expressions=expressions, ) def test_empty_expressions(self): msg = 'At least one expression is required to define an exclusion constraint.' for empty_expressions in (None, []): with self.subTest(empty_expressions), self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type='GIST', name='exclude_empty_expressions', expressions=empty_expressions, ) def test_invalid_deferrable(self): msg = 'ExclusionConstraint.deferrable must be a Deferrable instance.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_deferrable', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], deferrable='invalid', ) def test_deferrable_with_condition(self): msg = 'ExclusionConstraint with conditions cannot be deferred.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_condition', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], condition=Q(cancelled=False), deferrable=Deferrable.DEFERRED, ) def test_invalid_include_type(self): msg = 'ExclusionConstraint.include must be a list or tuple.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_include', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], include='invalid', ) def test_invalid_include_index_type(self): msg = 'Covering exclusion constraints only support GiST indexes.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_index_type', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], include=['cancelled'], index_type='spgist', ) def test_invalid_opclasses_type(self): msg = 'ExclusionConstraint.opclasses must be a list or tuple.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_opclasses', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], opclasses='invalid', ) def test_opclasses_and_expressions_same_length(self): msg = ( 'ExclusionConstraint.expressions and ' 'ExclusionConstraint.opclasses must have the same number of ' 'elements.' ) with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_expressions_opclasses_length', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], opclasses=['foo', 'bar'], ) def test_repr(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[ (F('datespan'), RangeOperators.OVERLAPS), (F('room'), RangeOperators.EQUAL), ], ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type=GIST, expressions=[" "(F(datespan), '&&'), (F(room), '=')]>", ) constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[(F('datespan'), RangeOperators.ADJACENT_TO)], condition=Q(cancelled=False), index_type='SPGiST', ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type=SPGiST, expressions=[" "(F(datespan), '-|-')], condition=(AND: ('cancelled', False))>", ) constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[(F('datespan'), RangeOperators.ADJACENT_TO)], deferrable=Deferrable.IMMEDIATE, ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type=GIST, expressions=[" "(F(datespan), '-|-')], deferrable=Deferrable.IMMEDIATE>", ) constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[(F('datespan'), RangeOperators.ADJACENT_TO)], include=['cancelled', 'room'], ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type=GIST, expressions=[" "(F(datespan), '-|-')], include=('cancelled', 'room')>", ) constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[(F('datespan'), RangeOperators.ADJACENT_TO)], opclasses=['range_ops'], ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type=GIST, expressions=[" "(F(datespan), '-|-')], opclasses=['range_ops']>", ) def test_eq(self): constraint_1 = ExclusionConstraint( name='exclude_overlapping', expressions=[ (F('datespan'), RangeOperators.OVERLAPS), (F('room'), RangeOperators.EQUAL), ], condition=Q(cancelled=False), ) constraint_2 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], ) constraint_3 = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS)], condition=Q(cancelled=False), ) constraint_4 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], deferrable=Deferrable.DEFERRED, ) constraint_5 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], deferrable=Deferrable.IMMEDIATE, ) constraint_6 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], deferrable=Deferrable.IMMEDIATE, include=['cancelled'], ) constraint_7 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], include=['cancelled'], ) constraint_8 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], include=['cancelled'], opclasses=['range_ops', 'range_ops'] ) constraint_9 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], opclasses=['range_ops', 'range_ops'] ) self.assertEqual(constraint_1, constraint_1) self.assertEqual(constraint_1, mock.ANY) self.assertNotEqual(constraint_1, constraint_2) self.assertNotEqual(constraint_1, constraint_3) self.assertNotEqual(constraint_1, constraint_4) self.assertNotEqual(constraint_2, constraint_3) self.assertNotEqual(constraint_2, constraint_4) self.assertNotEqual(constraint_2, constraint_7) self.assertNotEqual(constraint_2, constraint_9) self.assertNotEqual(constraint_4, constraint_5) self.assertNotEqual(constraint_5, constraint_6) self.assertNotEqual(constraint_7, constraint_8) self.assertNotEqual(constraint_1, object()) def test_deconstruct(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'expressions': [('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], }) def test_deconstruct_index_type(self): constraint = ExclusionConstraint( name='exclude_overlapping', index_type='SPGIST', expressions=[('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'index_type': 'SPGIST', 'expressions': [('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], }) def test_deconstruct_condition(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], condition=Q(cancelled=False), ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'expressions': [('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], 'condition': Q(cancelled=False), }) def test_deconstruct_deferrable(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS)], deferrable=Deferrable.DEFERRED, ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'expressions': [('datespan', RangeOperators.OVERLAPS)], 'deferrable': Deferrable.DEFERRED, }) def test_deconstruct_include(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS)], include=['cancelled', 'room'], ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'expressions': [('datespan', RangeOperators.OVERLAPS)], 'include': ('cancelled', 'room'), }) def test_deconstruct_opclasses(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS)], opclasses=['range_ops'], ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'expressions': [('datespan', RangeOperators.OVERLAPS)], 'opclasses': ['range_ops'], }) def _test_range_overlaps(self, constraint): # Create exclusion constraint. self.assertNotIn(constraint.name, self.get_constraints(HotelReservation._meta.db_table)) with connection.schema_editor() as editor: editor.add_constraint(HotelReservation, constraint) self.assertIn(constraint.name, self.get_constraints(HotelReservation._meta.db_table)) # Add initial reservations. room101 = Room.objects.create(number=101) room102 = Room.objects.create(number=102) datetimes = [ timezone.datetime(2018, 6, 20), timezone.datetime(2018, 6, 24), timezone.datetime(2018, 6, 26), timezone.datetime(2018, 6, 28), timezone.datetime(2018, 6, 29), ] HotelReservation.objects.create( datespan=DateRange(datetimes[0].date(), datetimes[1].date()), start=datetimes[0], end=datetimes[1], room=room102, ) HotelReservation.objects.create( datespan=DateRange(datetimes[1].date(), datetimes[3].date()), start=datetimes[1], end=datetimes[3], room=room102, ) # Overlap dates. with self.assertRaises(IntegrityError), transaction.atomic(): reservation = HotelReservation( datespan=(datetimes[1].date(), datetimes[2].date()), start=datetimes[1], end=datetimes[2], room=room102, ) reservation.save() # Valid range. HotelReservation.objects.bulk_create([ # Other room. HotelReservation( datespan=(datetimes[1].date(), datetimes[2].date()), start=datetimes[1], end=datetimes[2], room=room101, ), # Cancelled reservation. HotelReservation( datespan=(datetimes[1].date(), datetimes[1].date()), start=datetimes[1], end=datetimes[2], room=room102, cancelled=True, ), # Other adjacent dates. HotelReservation( datespan=(datetimes[3].date(), datetimes[4].date()), start=datetimes[3], end=datetimes[4], room=room102, ), ]) def test_range_overlaps_custom(self): class TsTzRange(Func): function = 'TSTZRANGE' output_field = DateTimeRangeField() constraint = ExclusionConstraint( name='exclude_overlapping_reservations_custom', expressions=[ (TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL) ], condition=Q(cancelled=False), opclasses=['range_ops', 'gist_int4_ops'], ) self._test_range_overlaps(constraint) def test_range_overlaps(self): constraint = ExclusionConstraint( name='exclude_overlapping_reservations', expressions=[ (F('datespan'), RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL) ], condition=Q(cancelled=False), ) self._test_range_overlaps(constraint) def test_range_adjacent(self): constraint_name = 'ints_adjacent' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(RangesModel, constraint) self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_expressions_with_params(self): constraint_name = 'scene_left_equal' self.assertNotIn(constraint_name, self.get_constraints(Scene._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[(Left('scene', 4), RangeOperators.EQUAL)], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) self.assertIn(constraint_name, self.get_constraints(Scene._meta.db_table)) def test_expressions_with_key_transform(self): constraint_name = 'exclude_overlapping_reservations_smoking' constraint = ExclusionConstraint( name=constraint_name, expressions=[ (F('datespan'), RangeOperators.OVERLAPS), (KeyTextTransform('smoking', 'requirements'), RangeOperators.EQUAL), ], ) with connection.schema_editor() as editor: editor.add_constraint(HotelReservation, constraint) self.assertIn( constraint_name, self.get_constraints(HotelReservation._meta.db_table), ) def test_range_adjacent_initially_deferred(self): constraint_name = 'ints_adjacent_deferred' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) adjacent_range = RangesModel.objects.create(ints=(10, 20)) # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name(constraint_name) cursor.execute('SET CONSTRAINTS %s IMMEDIATE' % quoted_name) # Remove adjacent range before the end of transaction. adjacent_range.delete() RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) @skipUnlessDBFeature('supports_covering_gist_indexes') def test_range_adjacent_include(self): constraint_name = 'ints_adjacent_include' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], include=['decimals', 'ints'], index_type='gist', ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) @skipUnlessDBFeature('supports_covering_gist_indexes') def test_range_adjacent_include_condition(self): constraint_name = 'ints_adjacent_include_condition' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], include=['decimals'], condition=Q(id__gte=100), ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) @skipUnlessDBFeature('supports_covering_gist_indexes') def test_range_adjacent_include_deferrable(self): constraint_name = 'ints_adjacent_include_deferrable' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], include=['decimals'], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_include_not_supported(self): constraint_name = 'ints_adjacent_include_not_supported' constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], include=['id'], ) msg = 'Covering exclusion constraints requires PostgreSQL 12+.' with connection.schema_editor() as editor: with mock.patch( 'django.db.backends.postgresql.features.DatabaseFeatures.supports_covering_gist_indexes', False, ): with self.assertRaisesMessage(NotSupportedError, msg): editor.add_constraint(RangesModel, constraint) def test_range_adjacent_opclasses(self): constraint_name = 'ints_adjacent_opclasses' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], opclasses=['range_ops'], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(RangesModel, constraint) self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_range_adjacent_opclasses_condition(self): constraint_name = 'ints_adjacent_opclasses_condition' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], opclasses=['range_ops'], condition=Q(id__gte=100), ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_range_adjacent_opclasses_deferrable(self): constraint_name = 'ints_adjacent_opclasses_deferrable' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], opclasses=['range_ops'], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) @skipUnlessDBFeature('supports_covering_gist_indexes') def test_range_adjacent_opclasses_include(self): constraint_name = 'ints_adjacent_opclasses_include' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], opclasses=['range_ops'], include=['decimals'], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table))
tests/postgres_tests/test_constraints.py
import datetime from unittest import mock from django.db import ( IntegrityError, NotSupportedError, connection, transaction, ) from django.db.models import ( CheckConstraint, Deferrable, F, Func, Q, UniqueConstraint, ) from django.db.models.fields.json import KeyTextTransform from django.db.models.functions import Left from django.test import skipUnlessDBFeature from django.utils import timezone from . import PostgreSQLTestCase from .models import HotelReservation, RangesModel, Room, Scene try: from psycopg2.extras import DateRange, NumericRange from django.contrib.postgres.constraints import ExclusionConstraint from django.contrib.postgres.fields import ( DateTimeRangeField, RangeBoundary, RangeOperators, ) except ImportError: pass class SchemaTests(PostgreSQLTestCase): get_opclass_query = ''' SELECT opcname, c.relname FROM pg_opclass AS oc JOIN pg_index as i on oc.oid = ANY(i.indclass) JOIN pg_class as c on c.oid = i.indexrelid WHERE c.relname = %s ''' def get_constraints(self, table): """Get the constraints on the table using a new cursor.""" with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def test_check_constraint_range_value(self): constraint_name = 'ints_between' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = CheckConstraint( check=Q(ints__contained_by=NumericRange(10, 30)), name=constraint_name, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(20, 50)) RangesModel.objects.create(ints=(10, 30)) def test_check_constraint_daterange_contains(self): constraint_name = 'dates_contains' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = CheckConstraint( check=Q(dates__contains=F('dates_inner')), name=constraint_name, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) date_1 = datetime.date(2016, 1, 1) date_2 = datetime.date(2016, 1, 4) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create( dates=(date_1, date_2), dates_inner=(date_1, date_2.replace(day=5)), ) RangesModel.objects.create( dates=(date_1, date_2), dates_inner=(date_1, date_2), ) def test_check_constraint_datetimerange_contains(self): constraint_name = 'timestamps_contains' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = CheckConstraint( check=Q(timestamps__contains=F('timestamps_inner')), name=constraint_name, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) datetime_1 = datetime.datetime(2016, 1, 1) datetime_2 = datetime.datetime(2016, 1, 2, 12) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create( timestamps=(datetime_1, datetime_2), timestamps_inner=(datetime_1, datetime_2.replace(hour=13)), ) RangesModel.objects.create( timestamps=(datetime_1, datetime_2), timestamps_inner=(datetime_1, datetime_2), ) def test_opclass(self): constraint = UniqueConstraint( name='test_opclass', fields=['scene'], opclasses=['varchar_pattern_ops'], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) self.assertIn(constraint.name, self.get_constraints(Scene._meta.db_table)) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) self.assertEqual( cursor.fetchall(), [('varchar_pattern_ops', constraint.name)], ) # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(Scene, constraint) self.assertNotIn(constraint.name, self.get_constraints(Scene._meta.db_table)) def test_opclass_multiple_columns(self): constraint = UniqueConstraint( name='test_opclass_multiple', fields=['scene', 'setting'], opclasses=['varchar_pattern_ops', 'text_pattern_ops'], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) expected_opclasses = ( ('varchar_pattern_ops', constraint.name), ('text_pattern_ops', constraint.name), ) self.assertCountEqual(cursor.fetchall(), expected_opclasses) def test_opclass_partial(self): constraint = UniqueConstraint( name='test_opclass_partial', fields=['scene'], opclasses=['varchar_pattern_ops'], condition=Q(setting__contains="Sir Bedemir's Castle"), ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) self.assertCountEqual( cursor.fetchall(), [('varchar_pattern_ops', constraint.name)], ) @skipUnlessDBFeature('supports_covering_indexes') def test_opclass_include(self): constraint = UniqueConstraint( name='test_opclass_include', fields=['scene'], opclasses=['varchar_pattern_ops'], include=['setting'], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) self.assertCountEqual( cursor.fetchall(), [('varchar_pattern_ops', constraint.name)], ) class ExclusionConstraintTests(PostgreSQLTestCase): def get_constraints(self, table): """Get the constraints on the table using a new cursor.""" with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def test_invalid_condition(self): msg = 'ExclusionConstraint.condition must be a Q instance.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type='GIST', name='exclude_invalid_condition', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], condition=F('invalid'), ) def test_invalid_index_type(self): msg = 'Exclusion constraints only support GiST or SP-GiST indexes.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type='gin', name='exclude_invalid_index_type', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], ) def test_invalid_expressions(self): msg = 'The expressions must be a list of 2-tuples.' for expressions in (['foo'], [('foo')], [('foo_1', 'foo_2', 'foo_3')]): with self.subTest(expressions), self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type='GIST', name='exclude_invalid_expressions', expressions=expressions, ) def test_empty_expressions(self): msg = 'At least one expression is required to define an exclusion constraint.' for empty_expressions in (None, []): with self.subTest(empty_expressions), self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type='GIST', name='exclude_empty_expressions', expressions=empty_expressions, ) def test_invalid_deferrable(self): msg = 'ExclusionConstraint.deferrable must be a Deferrable instance.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_deferrable', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], deferrable='invalid', ) def test_deferrable_with_condition(self): msg = 'ExclusionConstraint with conditions cannot be deferred.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_condition', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], condition=Q(cancelled=False), deferrable=Deferrable.DEFERRED, ) def test_invalid_include_type(self): msg = 'ExclusionConstraint.include must be a list or tuple.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_include', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], include='invalid', ) def test_invalid_include_index_type(self): msg = 'Covering exclusion constraints only support GiST indexes.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_index_type', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], include=['cancelled'], index_type='spgist', ) def test_invalid_opclasses_type(self): msg = 'ExclusionConstraint.opclasses must be a list or tuple.' with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_opclasses', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], opclasses='invalid', ) def test_opclasses_and_expressions_same_length(self): msg = ( 'ExclusionConstraint.expressions and ' 'ExclusionConstraint.opclasses must have the same number of ' 'elements.' ) with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name='exclude_invalid_expressions_opclasses_length', expressions=[(F('datespan'), RangeOperators.OVERLAPS)], opclasses=['foo', 'bar'], ) def test_repr(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[ (F('datespan'), RangeOperators.OVERLAPS), (F('room'), RangeOperators.EQUAL), ], ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type=GIST, expressions=[" "(F(datespan), '&&'), (F(room), '=')]>", ) constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[(F('datespan'), RangeOperators.ADJACENT_TO)], condition=Q(cancelled=False), index_type='SPGiST', ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type=SPGiST, expressions=[" "(F(datespan), '-|-')], condition=(AND: ('cancelled', False))>", ) constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[(F('datespan'), RangeOperators.ADJACENT_TO)], deferrable=Deferrable.IMMEDIATE, ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type=GIST, expressions=[" "(F(datespan), '-|-')], deferrable=Deferrable.IMMEDIATE>", ) constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[(F('datespan'), RangeOperators.ADJACENT_TO)], include=['cancelled', 'room'], ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type=GIST, expressions=[" "(F(datespan), '-|-')], include=('cancelled', 'room')>", ) constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[(F('datespan'), RangeOperators.ADJACENT_TO)], opclasses=['range_ops'], ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type=GIST, expressions=[" "(F(datespan), '-|-')], opclasses=['range_ops']>", ) def test_eq(self): constraint_1 = ExclusionConstraint( name='exclude_overlapping', expressions=[ (F('datespan'), RangeOperators.OVERLAPS), (F('room'), RangeOperators.EQUAL), ], condition=Q(cancelled=False), ) constraint_2 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], ) constraint_3 = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS)], condition=Q(cancelled=False), ) constraint_4 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], deferrable=Deferrable.DEFERRED, ) constraint_5 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], deferrable=Deferrable.IMMEDIATE, ) constraint_6 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], deferrable=Deferrable.IMMEDIATE, include=['cancelled'], ) constraint_7 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], include=['cancelled'], ) constraint_8 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], include=['cancelled'], opclasses=['range_ops', 'range_ops'] ) constraint_9 = ExclusionConstraint( name='exclude_overlapping', expressions=[ ('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL), ], opclasses=['range_ops', 'range_ops'] ) self.assertEqual(constraint_1, constraint_1) self.assertEqual(constraint_1, mock.ANY) self.assertNotEqual(constraint_1, constraint_2) self.assertNotEqual(constraint_1, constraint_3) self.assertNotEqual(constraint_1, constraint_4) self.assertNotEqual(constraint_2, constraint_3) self.assertNotEqual(constraint_2, constraint_4) self.assertNotEqual(constraint_2, constraint_7) self.assertNotEqual(constraint_2, constraint_9) self.assertNotEqual(constraint_4, constraint_5) self.assertNotEqual(constraint_5, constraint_6) self.assertNotEqual(constraint_7, constraint_8) self.assertNotEqual(constraint_1, object()) def test_deconstruct(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'expressions': [('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], }) def test_deconstruct_index_type(self): constraint = ExclusionConstraint( name='exclude_overlapping', index_type='SPGIST', expressions=[('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'index_type': 'SPGIST', 'expressions': [('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], }) def test_deconstruct_condition(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], condition=Q(cancelled=False), ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'expressions': [('datespan', RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL)], 'condition': Q(cancelled=False), }) def test_deconstruct_deferrable(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS)], deferrable=Deferrable.DEFERRED, ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'expressions': [('datespan', RangeOperators.OVERLAPS)], 'deferrable': Deferrable.DEFERRED, }) def test_deconstruct_include(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS)], include=['cancelled', 'room'], ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'expressions': [('datespan', RangeOperators.OVERLAPS)], 'include': ('cancelled', 'room'), }) def test_deconstruct_opclasses(self): constraint = ExclusionConstraint( name='exclude_overlapping', expressions=[('datespan', RangeOperators.OVERLAPS)], opclasses=['range_ops'], ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, 'django.contrib.postgres.constraints.ExclusionConstraint') self.assertEqual(args, ()) self.assertEqual(kwargs, { 'name': 'exclude_overlapping', 'expressions': [('datespan', RangeOperators.OVERLAPS)], 'opclasses': ['range_ops'], }) def _test_range_overlaps(self, constraint): # Create exclusion constraint. self.assertNotIn(constraint.name, self.get_constraints(HotelReservation._meta.db_table)) with connection.schema_editor() as editor: editor.add_constraint(HotelReservation, constraint) self.assertIn(constraint.name, self.get_constraints(HotelReservation._meta.db_table)) # Add initial reservations. room101 = Room.objects.create(number=101) room102 = Room.objects.create(number=102) datetimes = [ timezone.datetime(2018, 6, 20), timezone.datetime(2018, 6, 24), timezone.datetime(2018, 6, 26), timezone.datetime(2018, 6, 28), timezone.datetime(2018, 6, 29), ] HotelReservation.objects.create( datespan=DateRange(datetimes[0].date(), datetimes[1].date()), start=datetimes[0], end=datetimes[1], room=room102, ) HotelReservation.objects.create( datespan=DateRange(datetimes[1].date(), datetimes[3].date()), start=datetimes[1], end=datetimes[3], room=room102, ) # Overlap dates. with self.assertRaises(IntegrityError), transaction.atomic(): reservation = HotelReservation( datespan=(datetimes[1].date(), datetimes[2].date()), start=datetimes[1], end=datetimes[2], room=room102, ) reservation.save() # Valid range. HotelReservation.objects.bulk_create([ # Other room. HotelReservation( datespan=(datetimes[1].date(), datetimes[2].date()), start=datetimes[1], end=datetimes[2], room=room101, ), # Cancelled reservation. HotelReservation( datespan=(datetimes[1].date(), datetimes[1].date()), start=datetimes[1], end=datetimes[2], room=room102, cancelled=True, ), # Other adjacent dates. HotelReservation( datespan=(datetimes[3].date(), datetimes[4].date()), start=datetimes[3], end=datetimes[4], room=room102, ), ]) def test_range_overlaps_custom(self): class TsTzRange(Func): function = 'TSTZRANGE' output_field = DateTimeRangeField() constraint = ExclusionConstraint( name='exclude_overlapping_reservations_custom', expressions=[ (TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL) ], condition=Q(cancelled=False), opclasses=['range_ops', 'gist_int4_ops'], ) self._test_range_overlaps(constraint) def test_range_overlaps(self): constraint = ExclusionConstraint( name='exclude_overlapping_reservations', expressions=[ (F('datespan'), RangeOperators.OVERLAPS), ('room', RangeOperators.EQUAL) ], condition=Q(cancelled=False), ) self._test_range_overlaps(constraint) def test_range_adjacent(self): constraint_name = 'ints_adjacent' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(RangesModel, constraint) self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_expressions_with_params(self): constraint_name = 'scene_left_equal' self.assertNotIn(constraint_name, self.get_constraints(Scene._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[(Left('scene', 4), RangeOperators.EQUAL)], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) self.assertIn(constraint_name, self.get_constraints(Scene._meta.db_table)) def test_expressions_with_key_transform(self): constraint_name = 'exclude_overlapping_reservations_smoking' constraint = ExclusionConstraint( name=constraint_name, expressions=[ (F('datespan'), RangeOperators.OVERLAPS), (KeyTextTransform('smoking', 'requirements'), RangeOperators.EQUAL), ], ) with connection.schema_editor() as editor: editor.add_constraint(HotelReservation, constraint) self.assertIn( constraint_name, self.get_constraints(HotelReservation._meta.db_table), ) def test_range_adjacent_initially_deferred(self): constraint_name = 'ints_adjacent_deferred' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) adjacent_range = RangesModel.objects.create(ints=(10, 20)) # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name(constraint_name) cursor.execute('SET CONSTRAINTS %s IMMEDIATE' % quoted_name) # Remove adjacent range before the end of transaction. adjacent_range.delete() RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) @skipUnlessDBFeature('supports_covering_gist_indexes') def test_range_adjacent_include(self): constraint_name = 'ints_adjacent_include' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], include=['decimals', 'ints'], index_type='gist', ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) @skipUnlessDBFeature('supports_covering_gist_indexes') def test_range_adjacent_include_condition(self): constraint_name = 'ints_adjacent_include_condition' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], include=['decimals'], condition=Q(id__gte=100), ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) @skipUnlessDBFeature('supports_covering_gist_indexes') def test_range_adjacent_include_deferrable(self): constraint_name = 'ints_adjacent_include_deferrable' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], include=['decimals'], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_include_not_supported(self): constraint_name = 'ints_adjacent_include_not_supported' constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], include=['id'], ) msg = 'Covering exclusion constraints requires PostgreSQL 12+.' with connection.schema_editor() as editor: with mock.patch( 'django.db.backends.postgresql.features.DatabaseFeatures.supports_covering_gist_indexes', False, ): with self.assertRaisesMessage(NotSupportedError, msg): editor.add_constraint(RangesModel, constraint) def test_range_adjacent_opclasses(self): constraint_name = 'ints_adjacent_opclasses' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], opclasses=['range_ops'], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(RangesModel, constraint) self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_range_adjacent_opclasses_condition(self): constraint_name = 'ints_adjacent_opclasses_condition' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], opclasses=['range_ops'], condition=Q(id__gte=100), ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_range_adjacent_opclasses_deferrable(self): constraint_name = 'ints_adjacent_opclasses_deferrable' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], opclasses=['range_ops'], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) @skipUnlessDBFeature('supports_covering_gist_indexes') def test_range_adjacent_opclasses_include(self): constraint_name = 'ints_adjacent_opclasses_include' self.assertNotIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[('ints', RangeOperators.ADJACENT_TO)], opclasses=['range_ops'], include=['decimals'], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table))
0.645232
0.34679
import time import logging import json from sjsclient import client logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) sjs = client.Client("http://jobserver.ml-test-blog.internal:8090") myApp = sjs.apps.get("ml") myContext = sjs.contexts.get("ml-context") def testHandler(event, context): logger.info('got event{}'.format(event)) s3DataLocProtocol = "\"s3://{}\"".format(event['s3DataLoc']) s3ModelLocProtocol = "\"s3://{}\"".format(event['s3ModelLoc']) conf = '{'+'s3DataLoc:{},s3ModelLoc:{}'.format(s3DataLocProtocol,s3ModelLocProtocol)+'}' class_path = "com.amazonaws.proserv.ml.TestParams" myJob = sjs.jobs.create(myApp, class_path, conf = conf, ctx = myContext) myId = myJob.jobId while myJob.status != "FINISHED": time.sleep(2) myJob = sjs.jobs.get(myId) return { 'result' : sjs.jobs.get(myId).result } def loadHandler(event, context): logger.info('got event{}'.format(event)) s3DataLocProtocol = "\"s3://{}\"".format(event['s3DataLoc']) s3ModelLocProtocol = "\"s3://{}\"".format(event['s3ModelLoc']) conf = '{'+'s3DataLoc:{},s3ModelLoc:{}'.format(s3DataLocProtocol,s3ModelLocProtocol)+'}' class_path = "com.amazonaws.proserv.ml.LoadModelAndData" myJob = sjs.jobs.create(myApp, class_path, conf = conf, ctx = myContext) myId = myJob.jobId return { 'result' : 'Request Submitted with ID '+myJob.jobId+'. It should be ready shortly.' } def recommenderHandler(event, context): logger.info('got event{}'.format(event)) userId = event['userId'] conf = '{'+'userId:{}'.format(userId)+'}' class_path = "com.amazonaws.proserv.ml.MoviesRec" myJob = sjs.jobs.create(myApp, class_path, conf = conf, ctx = myContext) myId = myJob.jobId while myJob.status != "FINISHED": time.sleep(2) myJob = sjs.jobs.get(myId) return { 'result' : sjs.jobs.get(myId).result } def genreHandler(event, context): logger.info('got event{}'.format(event)) userId = event['userId'] genre = event['genre'] conf = '{'+'userId:{},genre:{}'.format(userId,genre)+'}' class_path = "com.amazonaws.proserv.ml.MoviesRecByGenre" myJob = sjs.jobs.create(myApp, class_path, conf = conf, ctx = myContext) myId = myJob.jobId while myJob.status != "FINISHED": time.sleep(2) myJob = sjs.jobs.get(myId) return { 'result' : sjs.jobs.get(myId).result, } if __name__ == '__main__': event = 'none' context = 'none' #Uncomment the follwing lines to test...one at a time #print(testHandler(event, context)) #print(loadHandler(event, context)) #print(recommenderHandler(event, context)) #print(genreHandler(event, context))
aws-blog-jobserver-emr/python_lambda/models.py
import time import logging import json from sjsclient import client logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) sjs = client.Client("http://jobserver.ml-test-blog.internal:8090") myApp = sjs.apps.get("ml") myContext = sjs.contexts.get("ml-context") def testHandler(event, context): logger.info('got event{}'.format(event)) s3DataLocProtocol = "\"s3://{}\"".format(event['s3DataLoc']) s3ModelLocProtocol = "\"s3://{}\"".format(event['s3ModelLoc']) conf = '{'+'s3DataLoc:{},s3ModelLoc:{}'.format(s3DataLocProtocol,s3ModelLocProtocol)+'}' class_path = "com.amazonaws.proserv.ml.TestParams" myJob = sjs.jobs.create(myApp, class_path, conf = conf, ctx = myContext) myId = myJob.jobId while myJob.status != "FINISHED": time.sleep(2) myJob = sjs.jobs.get(myId) return { 'result' : sjs.jobs.get(myId).result } def loadHandler(event, context): logger.info('got event{}'.format(event)) s3DataLocProtocol = "\"s3://{}\"".format(event['s3DataLoc']) s3ModelLocProtocol = "\"s3://{}\"".format(event['s3ModelLoc']) conf = '{'+'s3DataLoc:{},s3ModelLoc:{}'.format(s3DataLocProtocol,s3ModelLocProtocol)+'}' class_path = "com.amazonaws.proserv.ml.LoadModelAndData" myJob = sjs.jobs.create(myApp, class_path, conf = conf, ctx = myContext) myId = myJob.jobId return { 'result' : 'Request Submitted with ID '+myJob.jobId+'. It should be ready shortly.' } def recommenderHandler(event, context): logger.info('got event{}'.format(event)) userId = event['userId'] conf = '{'+'userId:{}'.format(userId)+'}' class_path = "com.amazonaws.proserv.ml.MoviesRec" myJob = sjs.jobs.create(myApp, class_path, conf = conf, ctx = myContext) myId = myJob.jobId while myJob.status != "FINISHED": time.sleep(2) myJob = sjs.jobs.get(myId) return { 'result' : sjs.jobs.get(myId).result } def genreHandler(event, context): logger.info('got event{}'.format(event)) userId = event['userId'] genre = event['genre'] conf = '{'+'userId:{},genre:{}'.format(userId,genre)+'}' class_path = "com.amazonaws.proserv.ml.MoviesRecByGenre" myJob = sjs.jobs.create(myApp, class_path, conf = conf, ctx = myContext) myId = myJob.jobId while myJob.status != "FINISHED": time.sleep(2) myJob = sjs.jobs.get(myId) return { 'result' : sjs.jobs.get(myId).result, } if __name__ == '__main__': event = 'none' context = 'none' #Uncomment the follwing lines to test...one at a time #print(testHandler(event, context)) #print(loadHandler(event, context)) #print(recommenderHandler(event, context)) #print(genreHandler(event, context))
0.158695
0.049543
WIDTH = 8 HEIGHT = 8 FIRST = 0x20 LAST = 0x7f _FONT =\ b'\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x18\x3c\x3c\x18\x18\x00\x18\x00'\ b'\x6c\x6c\x6c\x00\x00\x00\x00\x00'\ b'\x6c\x6c\xfe\x6c\xfe\x6c\x6c\x00'\ b'\x18\x7e\xc0\x7c\x06\xfc\x18\x00'\ b'\x00\xc6\xcc\x18\x30\x66\xc6\x00'\ b'\x38\x6c\x38\x76\xdc\xcc\x76\x00'\ b'\x30\x30\x60\x00\x00\x00\x00\x00'\ b'\x18\x30\x60\x60\x60\x30\x18\x00'\ b'\x60\x30\x18\x18\x18\x30\x60\x00'\ b'\x00\x66\x3c\xff\x3c\x66\x00\x00'\ b'\x00\x18\x18\x7e\x18\x18\x00\x00'\ b'\x00\x00\x00\x00\x00\x18\x18\x30'\ b'\x00\x00\x00\x7e\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x18\x18\x00'\ b'\x06\x0c\x18\x30\x60\xc0\x80\x00'\ b'\x7c\xce\xde\xf6\xe6\xc6\x7c\x00'\ b'\x30\x70\x30\x30\x30\x30\xfc\x00'\ b'\x78\xcc\x0c\x38\x60\xcc\xfc\x00'\ b'\x78\xcc\x0c\x38\x0c\xcc\x78\x00'\ b'\x1c\x3c\x6c\xcc\xfe\x0c\x1e\x00'\ b'\xfc\xc0\xf8\x0c\x0c\xcc\x78\x00'\ b'\x38\x60\xc0\xf8\xcc\xcc\x78\x00'\ b'\xfc\xcc\x0c\x18\x30\x30\x30\x00'\ b'\x78\xcc\xcc\x78\xcc\xcc\x78\x00'\ b'\x78\xcc\xcc\x7c\x0c\x18\x70\x00'\ b'\x00\x18\x18\x00\x00\x18\x18\x00'\ b'\x00\x18\x18\x00\x00\x18\x18\x30'\ b'\x18\x30\x60\xc0\x60\x30\x18\x00'\ b'\x00\x00\x7e\x00\x7e\x00\x00\x00'\ b'\x60\x30\x18\x0c\x18\x30\x60\x00'\ b'\x3c\x66\x0c\x18\x18\x00\x18\x00'\ b'\x7c\xc6\xde\xde\xdc\xc0\x7c\x00'\ b'\x30\x78\xcc\xcc\xfc\xcc\xcc\x00'\ b'\xfc\x66\x66\x7c\x66\x66\xfc\x00'\ b'\x3c\x66\xc0\xc0\xc0\x66\x3c\x00'\ b'\xf8\x6c\x66\x66\x66\x6c\xf8\x00'\ b'\xfe\x62\x68\x78\x68\x62\xfe\x00'\ b'\xfe\x62\x68\x78\x68\x60\xf0\x00'\ b'\x3c\x66\xc0\xc0\xce\x66\x3a\x00'\ b'\xcc\xcc\xcc\xfc\xcc\xcc\xcc\x00'\ b'\x78\x30\x30\x30\x30\x30\x78\x00'\ b'\x1e\x0c\x0c\x0c\xcc\xcc\x78\x00'\ b'\xe6\x66\x6c\x78\x6c\x66\xe6\x00'\ b'\xf0\x60\x60\x60\x62\x66\xfe\x00'\ b'\xc6\xee\xfe\xfe\xd6\xc6\xc6\x00'\ b'\xc6\xe6\xf6\xde\xce\xc6\xc6\x00'\ b'\x38\x6c\xc6\xc6\xc6\x6c\x38\x00'\ b'\xfc\x66\x66\x7c\x60\x60\xf0\x00'\ b'\x7c\xc6\xc6\xc6\xd6\x7c\x0e\x00'\ b'\xfc\x66\x66\x7c\x6c\x66\xe6\x00'\ b'\x7c\xc6\xe0\x78\x0e\xc6\x7c\x00'\ b'\xfc\xb4\x30\x30\x30\x30\x78\x00'\ b'\xcc\xcc\xcc\xcc\xcc\xcc\xfc\x00'\ b'\xcc\xcc\xcc\xcc\xcc\x78\x30\x00'\ b'\xc6\xc6\xc6\xc6\xd6\xfe\x6c\x00'\ b'\xc6\xc6\x6c\x38\x6c\xc6\xc6\x00'\ b'\xcc\xcc\xcc\x78\x30\x30\x78\x00'\ b'\xfe\xc6\x8c\x18\x32\x66\xfe\x00'\ b'\x78\x60\x60\x60\x60\x60\x78\x00'\ b'\xc0\x60\x30\x18\x0c\x06\x02\x00'\ b'\x78\x18\x18\x18\x18\x18\x78\x00'\ b'\x10\x38\x6c\xc6\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\xff'\ b'\x30\x30\x18\x00\x00\x00\x00\x00'\ b'\x00\x00\x78\x0c\x7c\xcc\x76\x00'\ b'\xe0\x60\x60\x7c\x66\x66\xdc\x00'\ b'\x00\x00\x78\xcc\xc0\xcc\x78\x00'\ b'\x1c\x0c\x0c\x7c\xcc\xcc\x76\x00'\ b'\x00\x00\x78\xcc\xfc\xc0\x78\x00'\ b'\x38\x6c\x64\xf0\x60\x60\xf0\x00'\ b'\x00\x00\x76\xcc\xcc\x7c\x0c\xf8'\ b'\xe0\x60\x6c\x76\x66\x66\xe6\x00'\ b'\x30\x00\x70\x30\x30\x30\x78\x00'\ b'\x0c\x00\x1c\x0c\x0c\xcc\xcc\x78'\ b'\xe0\x60\x66\x6c\x78\x6c\xe6\x00'\ b'\x70\x30\x30\x30\x30\x30\x78\x00'\ b'\x00\x00\xcc\xfe\xfe\xd6\xd6\x00'\ b'\x00\x00\xb8\xcc\xcc\xcc\xcc\x00'\ b'\x00\x00\x78\xcc\xcc\xcc\x78\x00'\ b'\x00\x00\xdc\x66\x66\x7c\x60\xf0'\ b'\x00\x00\x76\xcc\xcc\x7c\x0c\x1e'\ b'\x00\x00\xdc\x76\x62\x60\xf0\x00'\ b'\x00\x00\x7c\xc0\x70\x1c\xf8\x00'\ b'\x10\x30\xfc\x30\x30\x34\x18\x00'\ b'\x00\x00\xcc\xcc\xcc\xcc\x76\x00'\ b'\x00\x00\xcc\xcc\xcc\x78\x30\x00'\ b'\x00\x00\xc6\xc6\xd6\xfe\x6c\x00'\ b'\x00\x00\xc6\x6c\x38\x6c\xc6\x00'\ b'\x00\x00\xcc\xcc\xcc\x7c\x0c\xf8'\ b'\x00\x00\xfc\x98\x30\x64\xfc\x00'\ b'\x1c\x30\x30\xe0\x30\x30\x1c\x00'\ b'\x18\x18\x18\x00\x18\x18\x18\x00'\ b'\xe0\x30\x30\x1c\x30\x30\xe0\x00'\ b'\x76\xdc\x00\x00\x00\x00\x00\x00'\ b'\x00\x10\x38\x6c\xc6\xc6\xfe\x00'\ FONT = memoryview(_FONT)
fonts/diamonstealth64_8x8.py
WIDTH = 8 HEIGHT = 8 FIRST = 0x20 LAST = 0x7f _FONT =\ b'\x00\x00\x00\x00\x00\x00\x00\x00'\ b'\x18\x3c\x3c\x18\x18\x00\x18\x00'\ b'\x6c\x6c\x6c\x00\x00\x00\x00\x00'\ b'\x6c\x6c\xfe\x6c\xfe\x6c\x6c\x00'\ b'\x18\x7e\xc0\x7c\x06\xfc\x18\x00'\ b'\x00\xc6\xcc\x18\x30\x66\xc6\x00'\ b'\x38\x6c\x38\x76\xdc\xcc\x76\x00'\ b'\x30\x30\x60\x00\x00\x00\x00\x00'\ b'\x18\x30\x60\x60\x60\x30\x18\x00'\ b'\x60\x30\x18\x18\x18\x30\x60\x00'\ b'\x00\x66\x3c\xff\x3c\x66\x00\x00'\ b'\x00\x18\x18\x7e\x18\x18\x00\x00'\ b'\x00\x00\x00\x00\x00\x18\x18\x30'\ b'\x00\x00\x00\x7e\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x18\x18\x00'\ b'\x06\x0c\x18\x30\x60\xc0\x80\x00'\ b'\x7c\xce\xde\xf6\xe6\xc6\x7c\x00'\ b'\x30\x70\x30\x30\x30\x30\xfc\x00'\ b'\x78\xcc\x0c\x38\x60\xcc\xfc\x00'\ b'\x78\xcc\x0c\x38\x0c\xcc\x78\x00'\ b'\x1c\x3c\x6c\xcc\xfe\x0c\x1e\x00'\ b'\xfc\xc0\xf8\x0c\x0c\xcc\x78\x00'\ b'\x38\x60\xc0\xf8\xcc\xcc\x78\x00'\ b'\xfc\xcc\x0c\x18\x30\x30\x30\x00'\ b'\x78\xcc\xcc\x78\xcc\xcc\x78\x00'\ b'\x78\xcc\xcc\x7c\x0c\x18\x70\x00'\ b'\x00\x18\x18\x00\x00\x18\x18\x00'\ b'\x00\x18\x18\x00\x00\x18\x18\x30'\ b'\x18\x30\x60\xc0\x60\x30\x18\x00'\ b'\x00\x00\x7e\x00\x7e\x00\x00\x00'\ b'\x60\x30\x18\x0c\x18\x30\x60\x00'\ b'\x3c\x66\x0c\x18\x18\x00\x18\x00'\ b'\x7c\xc6\xde\xde\xdc\xc0\x7c\x00'\ b'\x30\x78\xcc\xcc\xfc\xcc\xcc\x00'\ b'\xfc\x66\x66\x7c\x66\x66\xfc\x00'\ b'\x3c\x66\xc0\xc0\xc0\x66\x3c\x00'\ b'\xf8\x6c\x66\x66\x66\x6c\xf8\x00'\ b'\xfe\x62\x68\x78\x68\x62\xfe\x00'\ b'\xfe\x62\x68\x78\x68\x60\xf0\x00'\ b'\x3c\x66\xc0\xc0\xce\x66\x3a\x00'\ b'\xcc\xcc\xcc\xfc\xcc\xcc\xcc\x00'\ b'\x78\x30\x30\x30\x30\x30\x78\x00'\ b'\x1e\x0c\x0c\x0c\xcc\xcc\x78\x00'\ b'\xe6\x66\x6c\x78\x6c\x66\xe6\x00'\ b'\xf0\x60\x60\x60\x62\x66\xfe\x00'\ b'\xc6\xee\xfe\xfe\xd6\xc6\xc6\x00'\ b'\xc6\xe6\xf6\xde\xce\xc6\xc6\x00'\ b'\x38\x6c\xc6\xc6\xc6\x6c\x38\x00'\ b'\xfc\x66\x66\x7c\x60\x60\xf0\x00'\ b'\x7c\xc6\xc6\xc6\xd6\x7c\x0e\x00'\ b'\xfc\x66\x66\x7c\x6c\x66\xe6\x00'\ b'\x7c\xc6\xe0\x78\x0e\xc6\x7c\x00'\ b'\xfc\xb4\x30\x30\x30\x30\x78\x00'\ b'\xcc\xcc\xcc\xcc\xcc\xcc\xfc\x00'\ b'\xcc\xcc\xcc\xcc\xcc\x78\x30\x00'\ b'\xc6\xc6\xc6\xc6\xd6\xfe\x6c\x00'\ b'\xc6\xc6\x6c\x38\x6c\xc6\xc6\x00'\ b'\xcc\xcc\xcc\x78\x30\x30\x78\x00'\ b'\xfe\xc6\x8c\x18\x32\x66\xfe\x00'\ b'\x78\x60\x60\x60\x60\x60\x78\x00'\ b'\xc0\x60\x30\x18\x0c\x06\x02\x00'\ b'\x78\x18\x18\x18\x18\x18\x78\x00'\ b'\x10\x38\x6c\xc6\x00\x00\x00\x00'\ b'\x00\x00\x00\x00\x00\x00\x00\xff'\ b'\x30\x30\x18\x00\x00\x00\x00\x00'\ b'\x00\x00\x78\x0c\x7c\xcc\x76\x00'\ b'\xe0\x60\x60\x7c\x66\x66\xdc\x00'\ b'\x00\x00\x78\xcc\xc0\xcc\x78\x00'\ b'\x1c\x0c\x0c\x7c\xcc\xcc\x76\x00'\ b'\x00\x00\x78\xcc\xfc\xc0\x78\x00'\ b'\x38\x6c\x64\xf0\x60\x60\xf0\x00'\ b'\x00\x00\x76\xcc\xcc\x7c\x0c\xf8'\ b'\xe0\x60\x6c\x76\x66\x66\xe6\x00'\ b'\x30\x00\x70\x30\x30\x30\x78\x00'\ b'\x0c\x00\x1c\x0c\x0c\xcc\xcc\x78'\ b'\xe0\x60\x66\x6c\x78\x6c\xe6\x00'\ b'\x70\x30\x30\x30\x30\x30\x78\x00'\ b'\x00\x00\xcc\xfe\xfe\xd6\xd6\x00'\ b'\x00\x00\xb8\xcc\xcc\xcc\xcc\x00'\ b'\x00\x00\x78\xcc\xcc\xcc\x78\x00'\ b'\x00\x00\xdc\x66\x66\x7c\x60\xf0'\ b'\x00\x00\x76\xcc\xcc\x7c\x0c\x1e'\ b'\x00\x00\xdc\x76\x62\x60\xf0\x00'\ b'\x00\x00\x7c\xc0\x70\x1c\xf8\x00'\ b'\x10\x30\xfc\x30\x30\x34\x18\x00'\ b'\x00\x00\xcc\xcc\xcc\xcc\x76\x00'\ b'\x00\x00\xcc\xcc\xcc\x78\x30\x00'\ b'\x00\x00\xc6\xc6\xd6\xfe\x6c\x00'\ b'\x00\x00\xc6\x6c\x38\x6c\xc6\x00'\ b'\x00\x00\xcc\xcc\xcc\x7c\x0c\xf8'\ b'\x00\x00\xfc\x98\x30\x64\xfc\x00'\ b'\x1c\x30\x30\xe0\x30\x30\x1c\x00'\ b'\x18\x18\x18\x00\x18\x18\x18\x00'\ b'\xe0\x30\x30\x1c\x30\x30\xe0\x00'\ b'\x76\xdc\x00\x00\x00\x00\x00\x00'\ b'\x00\x10\x38\x6c\xc6\xc6\xfe\x00'\ FONT = memoryview(_FONT)
0.130161
0.462109
import click from tripaille.cli import pass_context from tripaille.decorators import custom_exception, str_output @click.command('load_blast') @click.argument("name", type=str) @click.argument("program", type=str) @click.argument("programversion", type=str) @click.argument("sourcename", type=str) @click.argument("blast_output", type=str) @click.option( "--blast_ext", help="If looking for files in a directory, extension of the blast result files", type=str ) @click.option( "--blastdb", help="Name of the database blasted against (must be in the Chado db table)", type=str ) @click.option( "--blastdb_id", help="ID of the database blasted against (must be in the Chado db table)", type=str ) @click.option( "--blast_parameters", help="Blast parameters used to produce these results", type=str ) @click.option( "--query_re", help="The regular expression that can uniquely identify the query name. This parameters is required if the feature name is not the first word in the blast query name.", type=str ) @click.option( "--query_type", help="The feature type (e.g. 'gene', 'mRNA', 'contig') of the query. It must be a valid Sequence Ontology term.", type=str ) @click.option( "--query_uniquename", help="Use this if the --query-re regular expression matches unique names instead of names in the database.", is_flag=True ) @click.option( "--is_concat", help="If the blast result file is simply a list of concatenated blast results.", is_flag=True ) @click.option( "--search_keywords", help="Extract keywords for Tripal search", is_flag=True ) @click.option( "--no_parsed", help="Maximum number of hits to parse per feature. Default=all", default="all", show_default=True, type=str ) @click.option( "--no_wait", help="Do not wait for job to complete", is_flag=True ) @click.option( "--algorithm", help="analysis algorithm", type=str ) @click.option( "--sourceversion", help="analysis sourceversion", type=str ) @click.option( "--sourceuri", help="analysis sourceuri", type=str ) @click.option( "--description", help="analysis description", type=str ) @click.option( "--date_executed", help="analysis date_executed (yyyy-mm-dd)", type=str ) @pass_context @custom_exception @str_output def cli(ctx, name, program, programversion, sourcename, blast_output, blast_ext="", blastdb="", blastdb_id="", blast_parameters="", query_re="", query_type="", query_uniquename=False, is_concat=False, search_keywords=False, no_parsed="all", no_wait=False, algorithm="", sourceversion="", sourceuri="", description="", date_executed=""): """Create a Blast analysis Output: Loading information """ return ctx.gi.analysis.load_blast(name, program, programversion, sourcename, blast_output, blast_ext=blast_ext, blastdb=blastdb, blastdb_id=blastdb_id, blast_parameters=blast_parameters, query_re=query_re, query_type=query_type, query_uniquename=query_uniquename, is_concat=is_concat, search_keywords=search_keywords, no_parsed=no_parsed, no_wait=no_wait, algorithm=algorithm, sourceversion=sourceversion, sourceuri=sourceuri, description=description, date_executed=date_executed)
tripaille/commands/analysis/load_blast.py
import click from tripaille.cli import pass_context from tripaille.decorators import custom_exception, str_output @click.command('load_blast') @click.argument("name", type=str) @click.argument("program", type=str) @click.argument("programversion", type=str) @click.argument("sourcename", type=str) @click.argument("blast_output", type=str) @click.option( "--blast_ext", help="If looking for files in a directory, extension of the blast result files", type=str ) @click.option( "--blastdb", help="Name of the database blasted against (must be in the Chado db table)", type=str ) @click.option( "--blastdb_id", help="ID of the database blasted against (must be in the Chado db table)", type=str ) @click.option( "--blast_parameters", help="Blast parameters used to produce these results", type=str ) @click.option( "--query_re", help="The regular expression that can uniquely identify the query name. This parameters is required if the feature name is not the first word in the blast query name.", type=str ) @click.option( "--query_type", help="The feature type (e.g. 'gene', 'mRNA', 'contig') of the query. It must be a valid Sequence Ontology term.", type=str ) @click.option( "--query_uniquename", help="Use this if the --query-re regular expression matches unique names instead of names in the database.", is_flag=True ) @click.option( "--is_concat", help="If the blast result file is simply a list of concatenated blast results.", is_flag=True ) @click.option( "--search_keywords", help="Extract keywords for Tripal search", is_flag=True ) @click.option( "--no_parsed", help="Maximum number of hits to parse per feature. Default=all", default="all", show_default=True, type=str ) @click.option( "--no_wait", help="Do not wait for job to complete", is_flag=True ) @click.option( "--algorithm", help="analysis algorithm", type=str ) @click.option( "--sourceversion", help="analysis sourceversion", type=str ) @click.option( "--sourceuri", help="analysis sourceuri", type=str ) @click.option( "--description", help="analysis description", type=str ) @click.option( "--date_executed", help="analysis date_executed (yyyy-mm-dd)", type=str ) @pass_context @custom_exception @str_output def cli(ctx, name, program, programversion, sourcename, blast_output, blast_ext="", blastdb="", blastdb_id="", blast_parameters="", query_re="", query_type="", query_uniquename=False, is_concat=False, search_keywords=False, no_parsed="all", no_wait=False, algorithm="", sourceversion="", sourceuri="", description="", date_executed=""): """Create a Blast analysis Output: Loading information """ return ctx.gi.analysis.load_blast(name, program, programversion, sourcename, blast_output, blast_ext=blast_ext, blastdb=blastdb, blastdb_id=blastdb_id, blast_parameters=blast_parameters, query_re=query_re, query_type=query_type, query_uniquename=query_uniquename, is_concat=is_concat, search_keywords=search_keywords, no_parsed=no_parsed, no_wait=no_wait, algorithm=algorithm, sourceversion=sourceversion, sourceuri=sourceuri, description=description, date_executed=date_executed)
0.577138
0.181173
from .abstract_data_operation_config import AbstractDataOperationConfig from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class ReadOperationConfig(AbstractDataOperationConfig): """ The information about the read operation. """ def __init__(self, **kwargs): """ Initializes a new ReadOperationConfig object with values from keyword arguments. The default value of the :py:attr:`~oci.data_integration.models.ReadOperationConfig.model_type` attribute of this class is ``READ_OPERATION_CONFIG`` and it should not be changed. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param model_type: The value to assign to the model_type property of this ReadOperationConfig. Allowed values for this property are: "READ_OPERATION_CONFIG", "WRITE_OPERATION_CONFIG", 'UNKNOWN_ENUM_VALUE'. Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'. :type model_type: str :param key: The value to assign to the key property of this ReadOperationConfig. :type key: str :param model_version: The value to assign to the model_version property of this ReadOperationConfig. :type model_version: str :param parent_ref: The value to assign to the parent_ref property of this ReadOperationConfig. :type parent_ref: oci.data_integration.models.ParentReference :param operations: The value to assign to the operations property of this ReadOperationConfig. :type operations: list[oci.data_integration.models.PushDownOperation] :param data_format: The value to assign to the data_format property of this ReadOperationConfig. :type data_format: oci.data_integration.models.DataFormat :param partition_config: The value to assign to the partition_config property of this ReadOperationConfig. :type partition_config: oci.data_integration.models.PartitionConfig :param read_attribute: The value to assign to the read_attribute property of this ReadOperationConfig. :type read_attribute: oci.data_integration.models.AbstractReadAttribute :param object_status: The value to assign to the object_status property of this ReadOperationConfig. :type object_status: int """ self.swagger_types = { 'model_type': 'str', 'key': 'str', 'model_version': 'str', 'parent_ref': 'ParentReference', 'operations': 'list[PushDownOperation]', 'data_format': 'DataFormat', 'partition_config': 'PartitionConfig', 'read_attribute': 'AbstractReadAttribute', 'object_status': 'int' } self.attribute_map = { 'model_type': 'modelType', 'key': 'key', 'model_version': 'modelVersion', 'parent_ref': 'parentRef', 'operations': 'operations', 'data_format': 'dataFormat', 'partition_config': 'partitionConfig', 'read_attribute': 'readAttribute', 'object_status': 'objectStatus' } self._model_type = None self._key = None self._model_version = None self._parent_ref = None self._operations = None self._data_format = None self._partition_config = None self._read_attribute = None self._object_status = None self._model_type = 'READ_OPERATION_CONFIG' @property def key(self): """ Gets the key of this ReadOperationConfig. The object key. :return: The key of this ReadOperationConfig. :rtype: str """ return self._key @key.setter def key(self, key): """ Sets the key of this ReadOperationConfig. The object key. :param key: The key of this ReadOperationConfig. :type: str """ self._key = key @property def model_version(self): """ Gets the model_version of this ReadOperationConfig. The object's model version. :return: The model_version of this ReadOperationConfig. :rtype: str """ return self._model_version @model_version.setter def model_version(self, model_version): """ Sets the model_version of this ReadOperationConfig. The object's model version. :param model_version: The model_version of this ReadOperationConfig. :type: str """ self._model_version = model_version @property def parent_ref(self): """ Gets the parent_ref of this ReadOperationConfig. :return: The parent_ref of this ReadOperationConfig. :rtype: oci.data_integration.models.ParentReference """ return self._parent_ref @parent_ref.setter def parent_ref(self, parent_ref): """ Sets the parent_ref of this ReadOperationConfig. :param parent_ref: The parent_ref of this ReadOperationConfig. :type: oci.data_integration.models.ParentReference """ self._parent_ref = parent_ref @property def operations(self): """ Gets the operations of this ReadOperationConfig. An array of operations. :return: The operations of this ReadOperationConfig. :rtype: list[oci.data_integration.models.PushDownOperation] """ return self._operations @operations.setter def operations(self, operations): """ Sets the operations of this ReadOperationConfig. An array of operations. :param operations: The operations of this ReadOperationConfig. :type: list[oci.data_integration.models.PushDownOperation] """ self._operations = operations @property def data_format(self): """ Gets the data_format of this ReadOperationConfig. :return: The data_format of this ReadOperationConfig. :rtype: oci.data_integration.models.DataFormat """ return self._data_format @data_format.setter def data_format(self, data_format): """ Sets the data_format of this ReadOperationConfig. :param data_format: The data_format of this ReadOperationConfig. :type: oci.data_integration.models.DataFormat """ self._data_format = data_format @property def partition_config(self): """ Gets the partition_config of this ReadOperationConfig. :return: The partition_config of this ReadOperationConfig. :rtype: oci.data_integration.models.PartitionConfig """ return self._partition_config @partition_config.setter def partition_config(self, partition_config): """ Sets the partition_config of this ReadOperationConfig. :param partition_config: The partition_config of this ReadOperationConfig. :type: oci.data_integration.models.PartitionConfig """ self._partition_config = partition_config @property def read_attribute(self): """ Gets the read_attribute of this ReadOperationConfig. :return: The read_attribute of this ReadOperationConfig. :rtype: oci.data_integration.models.AbstractReadAttribute """ return self._read_attribute @read_attribute.setter def read_attribute(self, read_attribute): """ Sets the read_attribute of this ReadOperationConfig. :param read_attribute: The read_attribute of this ReadOperationConfig. :type: oci.data_integration.models.AbstractReadAttribute """ self._read_attribute = read_attribute @property def object_status(self): """ Gets the object_status of this ReadOperationConfig. The status of an object that can be set to value 1 for shallow references across objects, other values reserved. :return: The object_status of this ReadOperationConfig. :rtype: int """ return self._object_status @object_status.setter def object_status(self, object_status): """ Sets the object_status of this ReadOperationConfig. The status of an object that can be set to value 1 for shallow references across objects, other values reserved. :param object_status: The object_status of this ReadOperationConfig. :type: int """ self._object_status = object_status def __repr__(self): return formatted_flat_dict(self) def __eq__(self, other): if other is None: return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
src/oci/data_integration/models/read_operation_config.py
from .abstract_data_operation_config import AbstractDataOperationConfig from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class ReadOperationConfig(AbstractDataOperationConfig): """ The information about the read operation. """ def __init__(self, **kwargs): """ Initializes a new ReadOperationConfig object with values from keyword arguments. The default value of the :py:attr:`~oci.data_integration.models.ReadOperationConfig.model_type` attribute of this class is ``READ_OPERATION_CONFIG`` and it should not be changed. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param model_type: The value to assign to the model_type property of this ReadOperationConfig. Allowed values for this property are: "READ_OPERATION_CONFIG", "WRITE_OPERATION_CONFIG", 'UNKNOWN_ENUM_VALUE'. Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'. :type model_type: str :param key: The value to assign to the key property of this ReadOperationConfig. :type key: str :param model_version: The value to assign to the model_version property of this ReadOperationConfig. :type model_version: str :param parent_ref: The value to assign to the parent_ref property of this ReadOperationConfig. :type parent_ref: oci.data_integration.models.ParentReference :param operations: The value to assign to the operations property of this ReadOperationConfig. :type operations: list[oci.data_integration.models.PushDownOperation] :param data_format: The value to assign to the data_format property of this ReadOperationConfig. :type data_format: oci.data_integration.models.DataFormat :param partition_config: The value to assign to the partition_config property of this ReadOperationConfig. :type partition_config: oci.data_integration.models.PartitionConfig :param read_attribute: The value to assign to the read_attribute property of this ReadOperationConfig. :type read_attribute: oci.data_integration.models.AbstractReadAttribute :param object_status: The value to assign to the object_status property of this ReadOperationConfig. :type object_status: int """ self.swagger_types = { 'model_type': 'str', 'key': 'str', 'model_version': 'str', 'parent_ref': 'ParentReference', 'operations': 'list[PushDownOperation]', 'data_format': 'DataFormat', 'partition_config': 'PartitionConfig', 'read_attribute': 'AbstractReadAttribute', 'object_status': 'int' } self.attribute_map = { 'model_type': 'modelType', 'key': 'key', 'model_version': 'modelVersion', 'parent_ref': 'parentRef', 'operations': 'operations', 'data_format': 'dataFormat', 'partition_config': 'partitionConfig', 'read_attribute': 'readAttribute', 'object_status': 'objectStatus' } self._model_type = None self._key = None self._model_version = None self._parent_ref = None self._operations = None self._data_format = None self._partition_config = None self._read_attribute = None self._object_status = None self._model_type = 'READ_OPERATION_CONFIG' @property def key(self): """ Gets the key of this ReadOperationConfig. The object key. :return: The key of this ReadOperationConfig. :rtype: str """ return self._key @key.setter def key(self, key): """ Sets the key of this ReadOperationConfig. The object key. :param key: The key of this ReadOperationConfig. :type: str """ self._key = key @property def model_version(self): """ Gets the model_version of this ReadOperationConfig. The object's model version. :return: The model_version of this ReadOperationConfig. :rtype: str """ return self._model_version @model_version.setter def model_version(self, model_version): """ Sets the model_version of this ReadOperationConfig. The object's model version. :param model_version: The model_version of this ReadOperationConfig. :type: str """ self._model_version = model_version @property def parent_ref(self): """ Gets the parent_ref of this ReadOperationConfig. :return: The parent_ref of this ReadOperationConfig. :rtype: oci.data_integration.models.ParentReference """ return self._parent_ref @parent_ref.setter def parent_ref(self, parent_ref): """ Sets the parent_ref of this ReadOperationConfig. :param parent_ref: The parent_ref of this ReadOperationConfig. :type: oci.data_integration.models.ParentReference """ self._parent_ref = parent_ref @property def operations(self): """ Gets the operations of this ReadOperationConfig. An array of operations. :return: The operations of this ReadOperationConfig. :rtype: list[oci.data_integration.models.PushDownOperation] """ return self._operations @operations.setter def operations(self, operations): """ Sets the operations of this ReadOperationConfig. An array of operations. :param operations: The operations of this ReadOperationConfig. :type: list[oci.data_integration.models.PushDownOperation] """ self._operations = operations @property def data_format(self): """ Gets the data_format of this ReadOperationConfig. :return: The data_format of this ReadOperationConfig. :rtype: oci.data_integration.models.DataFormat """ return self._data_format @data_format.setter def data_format(self, data_format): """ Sets the data_format of this ReadOperationConfig. :param data_format: The data_format of this ReadOperationConfig. :type: oci.data_integration.models.DataFormat """ self._data_format = data_format @property def partition_config(self): """ Gets the partition_config of this ReadOperationConfig. :return: The partition_config of this ReadOperationConfig. :rtype: oci.data_integration.models.PartitionConfig """ return self._partition_config @partition_config.setter def partition_config(self, partition_config): """ Sets the partition_config of this ReadOperationConfig. :param partition_config: The partition_config of this ReadOperationConfig. :type: oci.data_integration.models.PartitionConfig """ self._partition_config = partition_config @property def read_attribute(self): """ Gets the read_attribute of this ReadOperationConfig. :return: The read_attribute of this ReadOperationConfig. :rtype: oci.data_integration.models.AbstractReadAttribute """ return self._read_attribute @read_attribute.setter def read_attribute(self, read_attribute): """ Sets the read_attribute of this ReadOperationConfig. :param read_attribute: The read_attribute of this ReadOperationConfig. :type: oci.data_integration.models.AbstractReadAttribute """ self._read_attribute = read_attribute @property def object_status(self): """ Gets the object_status of this ReadOperationConfig. The status of an object that can be set to value 1 for shallow references across objects, other values reserved. :return: The object_status of this ReadOperationConfig. :rtype: int """ return self._object_status @object_status.setter def object_status(self, object_status): """ Sets the object_status of this ReadOperationConfig. The status of an object that can be set to value 1 for shallow references across objects, other values reserved. :param object_status: The object_status of this ReadOperationConfig. :type: int """ self._object_status = object_status def __repr__(self): return formatted_flat_dict(self) def __eq__(self, other): if other is None: return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
0.812793
0.302436
import hashlib import json import pathlib from unittest import mock from gs_quant.api.gs.risk import GsRiskApi from gs_quant.json_encoder import JSONEncoder from gs_quant.markets import PricingContext from gs_quant.session import Environment, GsSession def _remove_unwanted(json_text): json_dict = json.loads(json_text) if "asOfTime" in json_dict: del json_dict["asOfTime"] return json_dict def load_json_from_resource(test_file_name, json_file_name): with open(pathlib.Path(__file__).parents[1] / f'resources/{test_file_name}/{json_file_name}') as json_data: return json.load(json_data) def mock_request(method, path, payload, test_file_name): queries = { 'assetsDataGSNWithRic': '{"asOfTime": "2019-05-16T21:18:18.294Z", "limit": 4, "where": {"ric": ["GS.N"]}, "fields": ["ric", "id"]}', 'assetsDataGSNWithId': '{"limit": 4, "fields": ["id", "ric"], "where": {"id": ["123456MW5E27U123456"]}}', 'assetsDataSPXWithRic': '{"where": {"ric": [".SPX"]}, "limit": 4, "fields": ["ric", "id"]}', 'assetsDataSPXWithId': '{"limit": 4, "fields": ["id", "ric"], "where": {"id": ["456123MW5E27U123456"]}}', 'dataQueryRic': '{"fields": ["adjustedTradePrice"],' ' "format": "MessagePack", "where": {"assetId": ["123456MW5E27U123456"]}}', 'dataQuerySPX': '{"fields": ["adjustedTradePrice"], "format": "MessagePack", "where": {"assetId": ["456123MW5E27U123456"]}}' } payload = _remove_unwanted(json.dumps(payload, cls=JSONEncoder) if payload else '{}') if method == 'GET': if path == '/data/datasets/TREOD': return load_json_from_resource(test_file_name, 'datasets_treod_response.json') elif method == 'POST': if path == '/assets/data/query': if payload == _remove_unwanted(queries['assetsDataGSNWithRic']) or \ payload == _remove_unwanted(queries['assetsDataGSNWithId']): return load_json_from_resource(test_file_name, 'assets_data_query_response_gsn.json') elif payload == _remove_unwanted(queries['assetsDataSPXWithRic']) or \ payload == _remove_unwanted(queries['assetsDataSPXWithId']): return load_json_from_resource(test_file_name, 'assets_data_query_response_spx.json') elif path == '/data/TREOD/query': if payload == _remove_unwanted(queries['dataQueryRic']): return load_json_from_resource(test_file_name, 'treod_query_response_gsn.json') elif payload == _remove_unwanted(queries['dataQuerySPX']): return load_json_from_resource(test_file_name, 'treod_query_response_spx.json') raise Exception(f'Unhandled request. Method: {method}, Path: {path}, payload: {payload} not recognized.') gs_risk_api_exec = GsRiskApi._exec def get_risk_request_id(requests): """ This is not a formal equality of the risk request as it covers only the names of core components. When a formal eq function is provided on risk_request then this should be replaced with something derived from that. :param requests: a collection of RiskRequests :type requests: tuple of RiskRequest :return: hash :rtype: str """ identifier = str(len(requests)) for request in requests: identifier += '_' identifier += '-'.join([pos.instrument.name for pos in request.positions]) identifier += '-'.join([r.__repr__() for r in request.measures]) date = request.pricing_and_market_data_as_of[0].pricing_date.strftime('%Y%b%d') today = PricingContext().pricing_date.strftime('%Y%b%d') identifier += 'today' if date == today else date if request.scenario is not None: scenario_identifier = [] for k, v in request.scenario.scenario.as_dict().items(): if k != 'shocks': scenario_identifier.append(str(k) + "=" + str(v)) else: shock_value = 'shock_value' + "=" + str(v[0].shock.value) pattern = v[0].pattern shock_pattern = 'shock_pattern' + "=" + '-'.join( [str(m) for m in [pattern.mkt_type, pattern.mkt_asset, pattern.mkt_class]]) scenario_identifier.append(shock_value + "+" + shock_pattern) identifier += '+'.join(sorted(scenario_identifier)) return hashlib.md5(identifier.encode('utf-8')).hexdigest() class MockCalc: def __init__(self, mocker, save_files=False, paths=pathlib.Path(__file__).parents[1], application='gs-quant'): # do not save tests with save_files = True self.save_files = save_files self.mocker = mocker self.paths = paths self.application = application def __enter__(self): if self.save_files: GsSession.use(Environment.PROD, None, None, application=self.application) self.mocker.patch.object(GsRiskApi, '_exec', side_effect=self.mock_calc_create_files) else: from gs_quant.session import OAuth2Session OAuth2Session.init = mock.MagicMock(return_value=None) GsSession.use(Environment.PROD, 'fake_client_id', 'fake_secret', application=self.application) self.mocker.patch.object(GsRiskApi, '_exec', side_effect=self.mock_calc) def mock_calc(self, *args, **kwargs): request = kwargs.get('request') or args[0] with open(self.paths / f'calc_cache/request{get_risk_request_id(request)}.json') \ as json_data: return json.load(json_data) def mock_calc_create_files(self, *args, **kwargs): # never leave a side_effect calling this function. Call it once to create the files, check them in # and switch to mock_calc def get_json(*i_args, **i_kwargs): this_json = gs_risk_api_exec(*i_args, **i_kwargs) return this_json result_json = get_json(*args, **kwargs) request = kwargs.get('request') or args[0] with open(self.paths / f'calc_cache/request{get_risk_request_id(request)}.json', 'w') as json_data: json.dump(result_json, json_data) return result_json def __exit__(self, exc_type, exc_val, exc_tb): pass
gs_quant/test/utils/test_utils.py
import hashlib import json import pathlib from unittest import mock from gs_quant.api.gs.risk import GsRiskApi from gs_quant.json_encoder import JSONEncoder from gs_quant.markets import PricingContext from gs_quant.session import Environment, GsSession def _remove_unwanted(json_text): json_dict = json.loads(json_text) if "asOfTime" in json_dict: del json_dict["asOfTime"] return json_dict def load_json_from_resource(test_file_name, json_file_name): with open(pathlib.Path(__file__).parents[1] / f'resources/{test_file_name}/{json_file_name}') as json_data: return json.load(json_data) def mock_request(method, path, payload, test_file_name): queries = { 'assetsDataGSNWithRic': '{"asOfTime": "2019-05-16T21:18:18.294Z", "limit": 4, "where": {"ric": ["GS.N"]}, "fields": ["ric", "id"]}', 'assetsDataGSNWithId': '{"limit": 4, "fields": ["id", "ric"], "where": {"id": ["123456MW5E27U123456"]}}', 'assetsDataSPXWithRic': '{"where": {"ric": [".SPX"]}, "limit": 4, "fields": ["ric", "id"]}', 'assetsDataSPXWithId': '{"limit": 4, "fields": ["id", "ric"], "where": {"id": ["456123MW5E27U123456"]}}', 'dataQueryRic': '{"fields": ["adjustedTradePrice"],' ' "format": "MessagePack", "where": {"assetId": ["123456MW5E27U123456"]}}', 'dataQuerySPX': '{"fields": ["adjustedTradePrice"], "format": "MessagePack", "where": {"assetId": ["456123MW5E27U123456"]}}' } payload = _remove_unwanted(json.dumps(payload, cls=JSONEncoder) if payload else '{}') if method == 'GET': if path == '/data/datasets/TREOD': return load_json_from_resource(test_file_name, 'datasets_treod_response.json') elif method == 'POST': if path == '/assets/data/query': if payload == _remove_unwanted(queries['assetsDataGSNWithRic']) or \ payload == _remove_unwanted(queries['assetsDataGSNWithId']): return load_json_from_resource(test_file_name, 'assets_data_query_response_gsn.json') elif payload == _remove_unwanted(queries['assetsDataSPXWithRic']) or \ payload == _remove_unwanted(queries['assetsDataSPXWithId']): return load_json_from_resource(test_file_name, 'assets_data_query_response_spx.json') elif path == '/data/TREOD/query': if payload == _remove_unwanted(queries['dataQueryRic']): return load_json_from_resource(test_file_name, 'treod_query_response_gsn.json') elif payload == _remove_unwanted(queries['dataQuerySPX']): return load_json_from_resource(test_file_name, 'treod_query_response_spx.json') raise Exception(f'Unhandled request. Method: {method}, Path: {path}, payload: {payload} not recognized.') gs_risk_api_exec = GsRiskApi._exec def get_risk_request_id(requests): """ This is not a formal equality of the risk request as it covers only the names of core components. When a formal eq function is provided on risk_request then this should be replaced with something derived from that. :param requests: a collection of RiskRequests :type requests: tuple of RiskRequest :return: hash :rtype: str """ identifier = str(len(requests)) for request in requests: identifier += '_' identifier += '-'.join([pos.instrument.name for pos in request.positions]) identifier += '-'.join([r.__repr__() for r in request.measures]) date = request.pricing_and_market_data_as_of[0].pricing_date.strftime('%Y%b%d') today = PricingContext().pricing_date.strftime('%Y%b%d') identifier += 'today' if date == today else date if request.scenario is not None: scenario_identifier = [] for k, v in request.scenario.scenario.as_dict().items(): if k != 'shocks': scenario_identifier.append(str(k) + "=" + str(v)) else: shock_value = 'shock_value' + "=" + str(v[0].shock.value) pattern = v[0].pattern shock_pattern = 'shock_pattern' + "=" + '-'.join( [str(m) for m in [pattern.mkt_type, pattern.mkt_asset, pattern.mkt_class]]) scenario_identifier.append(shock_value + "+" + shock_pattern) identifier += '+'.join(sorted(scenario_identifier)) return hashlib.md5(identifier.encode('utf-8')).hexdigest() class MockCalc: def __init__(self, mocker, save_files=False, paths=pathlib.Path(__file__).parents[1], application='gs-quant'): # do not save tests with save_files = True self.save_files = save_files self.mocker = mocker self.paths = paths self.application = application def __enter__(self): if self.save_files: GsSession.use(Environment.PROD, None, None, application=self.application) self.mocker.patch.object(GsRiskApi, '_exec', side_effect=self.mock_calc_create_files) else: from gs_quant.session import OAuth2Session OAuth2Session.init = mock.MagicMock(return_value=None) GsSession.use(Environment.PROD, 'fake_client_id', 'fake_secret', application=self.application) self.mocker.patch.object(GsRiskApi, '_exec', side_effect=self.mock_calc) def mock_calc(self, *args, **kwargs): request = kwargs.get('request') or args[0] with open(self.paths / f'calc_cache/request{get_risk_request_id(request)}.json') \ as json_data: return json.load(json_data) def mock_calc_create_files(self, *args, **kwargs): # never leave a side_effect calling this function. Call it once to create the files, check them in # and switch to mock_calc def get_json(*i_args, **i_kwargs): this_json = gs_risk_api_exec(*i_args, **i_kwargs) return this_json result_json = get_json(*args, **kwargs) request = kwargs.get('request') or args[0] with open(self.paths / f'calc_cache/request{get_risk_request_id(request)}.json', 'w') as json_data: json.dump(result_json, json_data) return result_json def __exit__(self, exc_type, exc_val, exc_tb): pass
0.441673
0.211722
import yaml import os try: from yaml import CLoader as Loader except ImportError: from yaml import Loader def load_config(config_file): """Load config file with yaml. Args: config_file: config_file Returns: config file """ with open(config_file, 'r') as stream: config = yaml.load(stream, Loader=Loader) return config def get_strict_filter_parameters(config_file): """Get strict filter from config file. Args: config_file: config_file Returns: strict filter """ config = load_config(config_file) return config['strict_filter'] def get_loose_filter_parameters(config_file): """Get loose filter from config file. Args: config_file: config_file Returns: loose filter """ config = load_config(config_file) return config['loose_filter'] def get_sample_ids(config_file): """Get sample ids from config file. Args: config_file: config_file Returns: sample ids """ config = load_config(config_file) return config['samples'].keys() def get_result_dir(config_file): """Get path to results directory from config file. Args: config_file: config_file Returns: results directory """ config = load_config(config_file) return os.path.join(config['working_dir'], config['results_dir']) def get_vcf_files(config_file): """Get path to vcf files from config file. Args: config_file: config_file Returns: path to vcf files """ vcf_files = {} config = load_config(config_file) for sample_id in get_sample_ids(config_file): if os.path.exists(config['samples'][sample_id]['vcf_file']): vcf_files[sample_id] = config['samples'][sample_id]['vcf_file'] else: vcf_files[sample_id] = os.path.join(config['working_dir'], config['samples'][sample_id]['vcf_file']) return vcf_files def get_maf_files(config_file): """Get path to maf files from config file. Args: config_file: config_file Returns: path to maf files """ maf_files = {} config = load_config(config_file) for sample_id in get_sample_ids(config_file): if os.path.exists(config['samples'][sample_id]['maf_file']): maf_files[sample_id] = config['samples'][sample_id]['maf_file'] else: maf_files[sample_id] = os.path.join(config['working_dir'], config['samples'][sample_id]['maf_file']) return maf_files def get_type(config_file): """Get sampel types from config file. Args: config_file: config_file Returns: sample types """ types = {} config = load_config(config_file) for sample_id in get_sample_ids(config_file): types[sample_id] = config['samples'][sample_id]['type'] return types
src/parameters.py
import yaml import os try: from yaml import CLoader as Loader except ImportError: from yaml import Loader def load_config(config_file): """Load config file with yaml. Args: config_file: config_file Returns: config file """ with open(config_file, 'r') as stream: config = yaml.load(stream, Loader=Loader) return config def get_strict_filter_parameters(config_file): """Get strict filter from config file. Args: config_file: config_file Returns: strict filter """ config = load_config(config_file) return config['strict_filter'] def get_loose_filter_parameters(config_file): """Get loose filter from config file. Args: config_file: config_file Returns: loose filter """ config = load_config(config_file) return config['loose_filter'] def get_sample_ids(config_file): """Get sample ids from config file. Args: config_file: config_file Returns: sample ids """ config = load_config(config_file) return config['samples'].keys() def get_result_dir(config_file): """Get path to results directory from config file. Args: config_file: config_file Returns: results directory """ config = load_config(config_file) return os.path.join(config['working_dir'], config['results_dir']) def get_vcf_files(config_file): """Get path to vcf files from config file. Args: config_file: config_file Returns: path to vcf files """ vcf_files = {} config = load_config(config_file) for sample_id in get_sample_ids(config_file): if os.path.exists(config['samples'][sample_id]['vcf_file']): vcf_files[sample_id] = config['samples'][sample_id]['vcf_file'] else: vcf_files[sample_id] = os.path.join(config['working_dir'], config['samples'][sample_id]['vcf_file']) return vcf_files def get_maf_files(config_file): """Get path to maf files from config file. Args: config_file: config_file Returns: path to maf files """ maf_files = {} config = load_config(config_file) for sample_id in get_sample_ids(config_file): if os.path.exists(config['samples'][sample_id]['maf_file']): maf_files[sample_id] = config['samples'][sample_id]['maf_file'] else: maf_files[sample_id] = os.path.join(config['working_dir'], config['samples'][sample_id]['maf_file']) return maf_files def get_type(config_file): """Get sampel types from config file. Args: config_file: config_file Returns: sample types """ types = {} config = load_config(config_file) for sample_id in get_sample_ids(config_file): types[sample_id] = config['samples'][sample_id]['type'] return types
0.579995
0.144179
from os import listdir from os.path import exists, join, isfile from argparse import ArgumentParser from tqdm import tqdm def load_label_map(file_path): action_names = [] with open(file_path) as input_stream: for line in input_stream: line_parts = line.strip().split(';') if len(line_parts) != 1: continue action_name = line_parts[0] action_names.append(action_name) assert len(action_names) > 0 unique_names = set(action_names) assert len(unique_names) == len(action_names) out_data = {name: label for label, name in enumerate(action_names)} return out_data def load_annotation(annot_path, label_map): out_data = [] with open(annot_path) as input_stream: for line in input_stream: line_parts = line.strip().split(';') if len(line_parts) != 2: continue rel_path, action_name = line_parts assert action_name in label_map action_id = label_map[action_name] out_data.append((rel_path, action_id)) return out_data def convert_annotation(src_annot, images_root, continuous_format): out_data = [] for rel_path, action_id in tqdm(src_annot): images_dir = join(images_root, rel_path) if not exists(images_dir): continue files = [f for f in listdir(images_dir) if isfile(join(images_dir, f))] if len(files) <= 1: continue frame_ids = [int(f.split('.')[0]) for f in files] assert min(frame_ids) == 1 assert len(frame_ids) == max(frame_ids) num_frames = len(frame_ids) if continuous_format: out_data.append((rel_path, action_id, 0, num_frames - 1, 0, num_frames - 1, 30.0)) else: out_data.append((rel_path, num_frames, action_id)) return out_data def dump_annotation(annot, out_path): with open(out_path, 'w') as output_stream: for record in annot: output_stream.write(' '.join([str(r) for r in record]) + '\n') def main(): parser = ArgumentParser() parser.add_argument('--label_map', '-lm', type=str, required=True) parser.add_argument('--images_root', '-im', type=str, required=True) parser.add_argument('--input_annot', '-ia', type=str, required=True) parser.add_argument('--out_annot', '-oa', type=str, required=True) args = parser.parse_args() assert exists(args.label_map) assert exists(args.images_root) assert exists(args.input_annot) label_map = load_label_map(args.label_map) print('Loaded names for {} labels'.format(len(label_map))) annot = load_annotation(args.input_annot, label_map) print('Found {} records'.format(len(annot))) converted_annot = convert_annotation(annot, args.images_root, continuous_format=True) print('Converted {} / {} records'.format(len(converted_annot), len(annot))) dump_annotation(converted_annot, args.out_annot) print('Converted annotation is stored at: {}'.format(args.out_annot)) if __name__ == '__main__': main()
models/action_recognition/model_templates/gesture-recognition/tools/data/prepare_jester_annot.py
from os import listdir from os.path import exists, join, isfile from argparse import ArgumentParser from tqdm import tqdm def load_label_map(file_path): action_names = [] with open(file_path) as input_stream: for line in input_stream: line_parts = line.strip().split(';') if len(line_parts) != 1: continue action_name = line_parts[0] action_names.append(action_name) assert len(action_names) > 0 unique_names = set(action_names) assert len(unique_names) == len(action_names) out_data = {name: label for label, name in enumerate(action_names)} return out_data def load_annotation(annot_path, label_map): out_data = [] with open(annot_path) as input_stream: for line in input_stream: line_parts = line.strip().split(';') if len(line_parts) != 2: continue rel_path, action_name = line_parts assert action_name in label_map action_id = label_map[action_name] out_data.append((rel_path, action_id)) return out_data def convert_annotation(src_annot, images_root, continuous_format): out_data = [] for rel_path, action_id in tqdm(src_annot): images_dir = join(images_root, rel_path) if not exists(images_dir): continue files = [f for f in listdir(images_dir) if isfile(join(images_dir, f))] if len(files) <= 1: continue frame_ids = [int(f.split('.')[0]) for f in files] assert min(frame_ids) == 1 assert len(frame_ids) == max(frame_ids) num_frames = len(frame_ids) if continuous_format: out_data.append((rel_path, action_id, 0, num_frames - 1, 0, num_frames - 1, 30.0)) else: out_data.append((rel_path, num_frames, action_id)) return out_data def dump_annotation(annot, out_path): with open(out_path, 'w') as output_stream: for record in annot: output_stream.write(' '.join([str(r) for r in record]) + '\n') def main(): parser = ArgumentParser() parser.add_argument('--label_map', '-lm', type=str, required=True) parser.add_argument('--images_root', '-im', type=str, required=True) parser.add_argument('--input_annot', '-ia', type=str, required=True) parser.add_argument('--out_annot', '-oa', type=str, required=True) args = parser.parse_args() assert exists(args.label_map) assert exists(args.images_root) assert exists(args.input_annot) label_map = load_label_map(args.label_map) print('Loaded names for {} labels'.format(len(label_map))) annot = load_annotation(args.input_annot, label_map) print('Found {} records'.format(len(annot))) converted_annot = convert_annotation(annot, args.images_root, continuous_format=True) print('Converted {} / {} records'.format(len(converted_annot), len(annot))) dump_annotation(converted_annot, args.out_annot) print('Converted annotation is stored at: {}'.format(args.out_annot)) if __name__ == '__main__': main()
0.454956
0.35928
import numpy as np def load_streamflow(path): """load streamflow into memory Args: path (str|DataFrame): path of streamflow csv file, or pandas DataFrame Returns: tuple: (date of np.datetime64, streamflow of float) """ if isinstance(path, str): date, Q = np.loadtxt( path, delimiter=",", skiprows=1, unpack=True, dtype=[("date", "datetime64[D]"), ("Q", float)], converters={0: np.datetime64}, encoding="utf8", ) year = date.astype("datetime64[Y]").astype(int) + int( str(np.datetime64(0, "Y")) ) month = date.astype("datetime64[M]").astype(int) % 12 + 1 day = (date - date.astype("datetime64[M]")).astype(int) + 1 date = np.rec.fromarrays( [year, month, day], dtype=[("Y", "i4"), ("M", "i4"), ("D", "i4")] ) else: df_date = path.iloc[:, 0].astype("datetime64") date = np.rec.fromarrays( [df_date.dt.year, df_date.dt.month, df_date.dt.day], dtype=[("Y", "i4"), ("M", "i4"), ("D", "i4")], ) Q = path.iloc[:, 1].values.astype(float) return clean_streamflow(date, Q) def clean_streamflow(date, Q): Q[np.isnan(Q)] = 0 Q = np.abs(Q) year = date["Y"] year_unique = np.unique(year) year_delete = clean_streamflow_jit(year, year_unique, Q) idx_delete = np.isin(year, year_delete) return Q[~idx_delete], date[~idx_delete] def clean_streamflow_jit(year, year_unique, Q): year_delete = [] for y in year_unique: if (Q[year == y] >= 0).sum() < 120: year_delete.append(y) return year_delete def moving_average(x, w): res = np.convolve(x, np.ones(w)) / w return res[w - 1 : -w + 1] def multi_arange_steps(starts, stops, steps): pos = 0 cnt = np.sum((stops - starts + steps - np.sign(steps)) // steps, dtype=np.int64) res = np.zeros((cnt,), dtype=np.int64) for i in range(starts.size): v, stop, step = starts[i], stops[i], steps[i] if step > 0: while v < stop: res[pos] = v pos += 1 v += step elif step < 0: while v > stop: res[pos] = v pos += 1 v += step assert pos == cnt return res def multi_arange(starts, stops): pos = 0 cnt = np.sum(stops - starts, dtype=np.int64) res = np.zeros((cnt,), dtype=np.int64) for i in range(starts.size): num = stops[i] - starts[i] res[pos : pos + num] = np.arange(starts[i], stops[i]) pos += num return res def NSE(Q_obs, Q_sim): SS_res = np.sum(np.square(Q_obs - Q_sim)) SS_tot = np.sum(np.square(Q_obs - np.mean(Q_obs))) return (1 - SS_res / (SS_tot + 1e-10)) - 1e-10
src/hydrotoolbox/baseflow/utils.py
import numpy as np def load_streamflow(path): """load streamflow into memory Args: path (str|DataFrame): path of streamflow csv file, or pandas DataFrame Returns: tuple: (date of np.datetime64, streamflow of float) """ if isinstance(path, str): date, Q = np.loadtxt( path, delimiter=",", skiprows=1, unpack=True, dtype=[("date", "datetime64[D]"), ("Q", float)], converters={0: np.datetime64}, encoding="utf8", ) year = date.astype("datetime64[Y]").astype(int) + int( str(np.datetime64(0, "Y")) ) month = date.astype("datetime64[M]").astype(int) % 12 + 1 day = (date - date.astype("datetime64[M]")).astype(int) + 1 date = np.rec.fromarrays( [year, month, day], dtype=[("Y", "i4"), ("M", "i4"), ("D", "i4")] ) else: df_date = path.iloc[:, 0].astype("datetime64") date = np.rec.fromarrays( [df_date.dt.year, df_date.dt.month, df_date.dt.day], dtype=[("Y", "i4"), ("M", "i4"), ("D", "i4")], ) Q = path.iloc[:, 1].values.astype(float) return clean_streamflow(date, Q) def clean_streamflow(date, Q): Q[np.isnan(Q)] = 0 Q = np.abs(Q) year = date["Y"] year_unique = np.unique(year) year_delete = clean_streamflow_jit(year, year_unique, Q) idx_delete = np.isin(year, year_delete) return Q[~idx_delete], date[~idx_delete] def clean_streamflow_jit(year, year_unique, Q): year_delete = [] for y in year_unique: if (Q[year == y] >= 0).sum() < 120: year_delete.append(y) return year_delete def moving_average(x, w): res = np.convolve(x, np.ones(w)) / w return res[w - 1 : -w + 1] def multi_arange_steps(starts, stops, steps): pos = 0 cnt = np.sum((stops - starts + steps - np.sign(steps)) // steps, dtype=np.int64) res = np.zeros((cnt,), dtype=np.int64) for i in range(starts.size): v, stop, step = starts[i], stops[i], steps[i] if step > 0: while v < stop: res[pos] = v pos += 1 v += step elif step < 0: while v > stop: res[pos] = v pos += 1 v += step assert pos == cnt return res def multi_arange(starts, stops): pos = 0 cnt = np.sum(stops - starts, dtype=np.int64) res = np.zeros((cnt,), dtype=np.int64) for i in range(starts.size): num = stops[i] - starts[i] res[pos : pos + num] = np.arange(starts[i], stops[i]) pos += num return res def NSE(Q_obs, Q_sim): SS_res = np.sum(np.square(Q_obs - Q_sim)) SS_tot = np.sum(np.square(Q_obs - np.mean(Q_obs))) return (1 - SS_res / (SS_tot + 1e-10)) - 1e-10
0.741487
0.582669
import numpy as np import pytest import autogalaxy as ag from autoarray.inversion import inversions from autogalaxy.mock.mock import MockLightProfile class MockFitImaging: def __init__(self, model_images_of_galaxies): self.model_images_of_galaxies = model_images_of_galaxies class TestFitImaging: class TestLikelihood: def test__1x2_image__no_psf_blurring__plane_fits_data_with_chi_sq_5(self): # The image plane image generated by the galaxy is [1.0, 1.0] # Thus the chi squared is 4.0**2.0 + 3.0**2.0 = 25.0 psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, ) imaging = ag.Imaging( image=5.0 * ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[6] = 4.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging(grid_class=ag.Grid2D, sub_size=1), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) assert ( fit.mask == np.array( [ [True, True, True, True], [True, False, False, True], [True, True, True, True], ] ) ).all() assert ( fit.image.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 5.0, 4.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.noise_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.model_image.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.residual_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 4.0, 3.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.normalized_residual_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 4.0, 3.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.chi_squared_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 16.0, 9.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert fit.chi_squared == 25.0 assert fit.reduced_chi_squared == 25.0 / 2.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 1.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 25.0 + 2.0 * np.log(2 * np.pi * 1.0 ** 2.0) ) def test__1x2_image__include_psf_blurring__plane_fits_data_with_chi_sq_4(self): # This PSF changes the blurred image plane image from [1.0, 1.0] to [1.0, 5.0] # Thus, the chi squared is 4.0**2.0 + 0.0**2.0 = 16.0 psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 3.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, renormalize=False, ) imaging = ag.Imaging( image=5.0 * ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[6] = 4.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging( grid_class=ag.Grid2D, renormalize_psf=False, sub_size=1 ), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) assert ( fit.mask == np.array( [ [True, True, True, True], [True, False, False, True], [True, True, True, True], ] ) ).all() assert ( fit.image.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 5.0, 4.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.noise_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.model_image.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 4.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.residual_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 4.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.normalized_residual_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 4.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.chi_squared_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 16.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert fit.chi_squared == 16.0 assert fit.reduced_chi_squared == 16.0 / 2.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 1.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 16.0 + 2.0 * np.log(2 * np.pi * 1.0 ** 2.0) ) def test__hyper_galaxy_changes_noise_above_from_1_to_2__reflected_in_likelihood( self, ): # This PSF changes the blurred image plane image from [1.0, 1.0] to [1.0, 5.0] # Thus, the chi squared is 4.0**2.0 + 0.0**2.0 = 16.0 # The hyper_galaxies galaxy increases the noise in both pixels by 1.0, to 2.0. # This reduces the chi squared to 2.0 instead of 4.0 psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 3.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, ) imaging = ag.Imaging( image=5.0 * ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[6] = 4.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging( grid_class=ag.Grid2D, renormalize_psf=False, sub_size=1 ), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2), hyper_galaxy=ag.HyperGalaxy( contribution_factor=1.0, noise_factor=1.0, noise_power=1.0 ), hyper_model_image=ag.Array2D.ones( shape_native=(1, 2), pixel_scales=1.0 ), hyper_galaxy_image=ag.Array2D.ones( shape_native=(1, 2), pixel_scales=1.0 ), hyper_minimum_value=0.0, ) plane = ag.Plane(galaxies=[g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) assert ( fit.noise_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 2.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.chi_squared_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 4.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert fit.chi_squared == 4.0 assert fit.reduced_chi_squared == 4.0 / 2.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 2.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 4.0 + 2.0 * np.log(2 * np.pi * 2.0 ** 2.0) ) def test__hyper_image_changes_background_sky__reflected_in_likelihood(self): psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, ) imaging = ag.Imaging( image=ag.Array2D.full( fill_value=4.0, shape_native=(3, 4), pixel_scales=1.0 ), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[5] = 5.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging(grid_class=ag.Grid2D, sub_size=1), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) hyper_image_sky = ag.hyper_data.HyperImageSky(sky_scale=1.0) fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_image_sky=hyper_image_sky, ) assert ( fit.mask == np.array( [ [True, True, True, True], [True, False, False, True], [True, True, True, True], ] ) ).all() assert ( fit.image.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 6.0, 5.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.chi_squared_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 25.0, 16.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert fit.chi_squared == 41.0 assert fit.reduced_chi_squared == 41.0 / 2.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 1.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 41.0 + 2.0 * np.log(2 * np.pi * 1.0 ** 2.0) ) def test__hyper_background_changes_background_noise_map__reflected_in_likelihood( self, ): psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, ) imaging = ag.Imaging( image=5.0 * ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[6] = 4.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging(grid_class=ag.Grid2D, sub_size=1), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_background_noise=hyper_background_noise, ) assert ( fit.noise_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 2.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert fit.chi_squared == 6.25 assert fit.reduced_chi_squared == 6.25 / 2.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 2.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 6.25 + 2.0 * np.log(2 * np.pi * 2.0 ** 2.0) ) def test__hyper_galaxy_changes_noise_above_hyper_noise_limit__rounded_down_to_limit( self, ): # This PSF changes the blurred image plane image from [1.0, 1.0] to [1.0, 5.0] # Thus, the chi squared is 4.0**2.0 + 0.0**2.0 = 16.0 # The hyper_galaxies galaxy increases the noise in both pixels by 1.0, to 2.0. # This reduces the chi squared to 2.0 instead of 4.0 psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 3.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, ) imaging = ag.Imaging( image=5.0 * ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[6] = 4.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging( grid_class=ag.Grid2D, renormalize_psf=False, sub_size=1 ), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2), hyper_galaxy=ag.HyperGalaxy( contribution_factor=1.0, noise_factor=1.0e9, noise_power=1.0 ), hyper_model_image=ag.Array2D.ones( shape_native=(1, 2), pixel_scales=1.0 ), hyper_galaxy_image=ag.Array2D.ones( shape_native=(1, 2), pixel_scales=1.0 ), hyper_minimum_value=0.0, ) plane = ag.Plane(galaxies=[g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) assert ( fit.noise_map.native == np.array( [ [0.0, 0.0, 0.0, 0.0], [0.0, 1.0e8, 1.0e8, 0.0], [0.0, 0.0, 0.0, 0.0], ] ) ).all() class TestCompareToManualProfilesOnly: def test___all_fit_quantities__no_hyper_methods(self, masked_imaging_7x7): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) assert masked_imaging_7x7.noise_map.native == pytest.approx( fit.noise_map.native ) model_image = plane.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) assert model_image.native == pytest.approx(fit.model_image.native) residual_map = ag.util.fit.residual_map_from( data=masked_imaging_7x7.image, model_data=model_image ) assert residual_map.native == pytest.approx(fit.residual_map.native) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert chi_squared_map.native == pytest.approx(fit.chi_squared_map.native) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=masked_imaging_7x7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) assert log_likelihood == fit.figure_of_merit def test___fit_galaxy_model_image_dict__corresponds_to_blurred_galaxy_images( self, masked_imaging_7x7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) g2 = ag.Galaxy(redshift=1.0) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, g2]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) g0_blurred_image = g0.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, blurring_grid=masked_imaging_7x7.blurring_grid, convolver=masked_imaging_7x7.convolver, ) g1_blurred_image = g1.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, blurring_grid=masked_imaging_7x7.blurring_grid, convolver=masked_imaging_7x7.convolver, ) assert fit.galaxy_model_image_dict[g0] == pytest.approx( g0_blurred_image, 1.0e-4 ) assert fit.galaxy_model_image_dict[g1] == pytest.approx( g1_blurred_image, 1.0e-4 ) assert (fit.galaxy_model_image_dict[g2].slim == np.zeros(9)).all() assert fit.model_image.native == pytest.approx( fit.galaxy_model_image_dict[g0].native + fit.galaxy_model_image_dict[g1].native, 1.0e-4, ) def test___all_fit_quantities__including_hyper_methods( self, masked_imaging_7x7 ): hyper_image_sky = ag.hyper_data.HyperImageSky(sky_scale=1.0) hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) image = hyper_image_sky.hyper_image_from_image( image=masked_imaging_7x7.image ) g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), hyper_galaxy=ag.HyperGalaxy( contribution_factor=1.0, noise_factor=1.0, noise_power=1.0 ), hyper_model_image=np.ones(9), hyper_galaxy_image=np.ones(9), hyper_minimum_value=0.0, ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_image_sky=hyper_image_sky, hyper_background_noise=hyper_background_noise, ) hyper_noise_map_background = hyper_background_noise.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) hyper_noise = plane.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) hyper_noise_map = hyper_noise_map_background + hyper_noise assert hyper_noise_map.native == pytest.approx(fit.noise_map.native) model_image = plane.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) assert model_image.native == pytest.approx(fit.model_image.native) residual_map = ag.util.fit.residual_map_from( data=image, model_data=model_image ) assert residual_map.native == pytest.approx(fit.residual_map.native) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert chi_squared_map.native == pytest.approx(fit.chi_squared_map.native) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=hyper_noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) assert log_likelihood == fit.figure_of_merit fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_image_sky=hyper_image_sky, hyper_background_noise=hyper_background_noise, use_hyper_scalings=False, ) assert fit.image == pytest.approx(masked_imaging_7x7.image, 1.0e-4) assert fit.noise_map == pytest.approx(masked_imaging_7x7.noise_map, 1.0e-4) def test___blurred_and_model_images_of_galaxies_and_unmasked_blurred_image_properties( self, masked_imaging_7x7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) blurred_images_of_galaxies = plane.blurred_images_of_galaxies_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) assert blurred_images_of_galaxies[0].native == pytest.approx( fit.model_images_of_galaxies[0].native, 1.0e-4 ) assert blurred_images_of_galaxies[1].native == pytest.approx( fit.model_images_of_galaxies[1].native, 1.0e-4 ) unmasked_blurred_image = plane.unmasked_blurred_image_from_grid_and_psf( grid=masked_imaging_7x7.grid, psf=masked_imaging_7x7.psf ) assert (unmasked_blurred_image == fit.unmasked_blurred_image).all() unmasked_blurred_image_of_galaxies = plane.unmasked_blurred_image_of_galaxies_from_grid_and_psf( grid=masked_imaging_7x7.grid, psf=masked_imaging_7x7.psf ) assert ( unmasked_blurred_image_of_galaxies[0] == fit.unmasked_blurred_image_of_galaxies[0] ).all() assert ( unmasked_blurred_image_of_galaxies[1] == fit.unmasked_blurred_image_of_galaxies[1] ).all() class TestCompareToManualInversionOnly: def test___all_quantities__no_hyper_methods(self, masked_imaging_7x7): # Ensures the inversion grid is used, as this would cause the test to fail. masked_imaging_7x7.grid[0, 0] = -100.0 pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy(redshift=0.5, pixelization=pix, regularization=reg) plane = ag.Plane(galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid_inversion, sparse_grid=None ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, image=masked_imaging_7x7.image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, ) assert inversion.mapped_reconstructed_image.native == pytest.approx( fit.model_image.native, 1.0e-4 ) residual_map = ag.util.fit.residual_map_from( data=masked_imaging_7x7.image, model_data=inversion.mapped_reconstructed_image, ) assert residual_map.native == pytest.approx(fit.residual_map.native, 1.0e-4) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native, 1.0e-4 ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert chi_squared_map.native == pytest.approx( fit.chi_squared_map.native, 1.0e-4 ) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=masked_imaging_7x7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit def test___fit_galaxy_model_image_dict__has_inversion_mapped_reconstructed_image( self, masked_imaging_7x7 ): pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy(redshift=0.5) g1 = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, sparse_grid=None ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, image=masked_imaging_7x7.image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, ) assert (fit.galaxy_model_image_dict[g0] == np.zeros(9)).all() assert fit.galaxy_model_image_dict[g1].native == pytest.approx( inversion.mapped_reconstructed_image.native, 1.0e-4 ) assert fit.model_image.native == pytest.approx( fit.galaxy_model_image_dict[g1].native, 1.0e-4 ) def test___all_fit_quantities__include_hyper_methods(self, masked_imaging_7x7): hyper_image_sky = ag.hyper_data.HyperImageSky(sky_scale=1.0) hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) image = hyper_image_sky.hyper_image_from_image( image=masked_imaging_7x7.image ) hyper_noise_map_background = hyper_background_noise.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy( redshift=0.5, pixelization=pix, regularization=reg, hyper_galaxy=ag.HyperGalaxy( contribution_factor=1.0, noise_factor=1.0, noise_power=1.0 ), hyper_model_image=np.ones(9), hyper_galaxy_image=np.ones(9), hyper_minimum_value=0.0, ) plane = ag.Plane(galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_image_sky=hyper_image_sky, hyper_background_noise=hyper_background_noise, ) hyper_noise = plane.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) hyper_noise_map = hyper_noise_map_background + hyper_noise assert hyper_noise_map.native == pytest.approx(fit.noise_map.native) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, image=image, noise_map=hyper_noise_map, convolver=masked_imaging_7x7.convolver, ) assert inversion.mapped_reconstructed_image.native == pytest.approx( fit.model_image.native, 1.0e-4 ) residual_map = ag.util.fit.residual_map_from( data=image, model_data=inversion.mapped_reconstructed_image ) assert residual_map.native == pytest.approx(fit.residual_map.native) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert chi_squared_map.native == pytest.approx(fit.chi_squared_map.native) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=hyper_noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit def test___blurred_and_model_images_of_galaxies_and_unmasked_blurred_image_properties( self, masked_imaging_7x7 ): pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, image=masked_imaging_7x7.image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, ) assert (fit.model_images_of_galaxies[0].native == np.zeros((7, 7))).all() assert inversion.mapped_reconstructed_image.native == pytest.approx( fit.model_images_of_galaxies[1].native, 1.0e-4 ) class TestCompareToManualProfilesAndInversion: def test___all_fit_quantities__no_hyper_methods(self, masked_imaging_7x7): galaxy_light = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[galaxy_light, galaxy_pix]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) blurred_image = plane.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) assert blurred_image.native == pytest.approx(fit.blurred_image.native) profile_subtracted_image = masked_imaging_7x7.image - blurred_image assert profile_subtracted_image.native == pytest.approx( fit.profile_subtracted_image.native ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( image=profile_subtracted_image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, mapper=mapper, regularization=reg, ) model_image = blurred_image + inversion.mapped_reconstructed_image assert model_image.native == pytest.approx(fit.model_image.native) residual_map = ag.util.fit.residual_map_from( data=masked_imaging_7x7.image, model_data=model_image ) assert residual_map.native == pytest.approx(fit.residual_map.native) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert chi_squared_map.native == pytest.approx(fit.chi_squared_map.native) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=masked_imaging_7x7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit def test___fit_galaxy_model_image_dict__has_blurred_images_and_inversion_mapped_reconstructed_image( self, masked_imaging_7x7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) g1 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=2.0) ) g2 = ag.Galaxy(redshift=0.5) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, g2, galaxy_pix]) masked_imaging_7x7.image[0] = 3.0 fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) g0_blurred_image = g0.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) g1_blurred_image = g1.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) blurred_image = g0_blurred_image + g1_blurred_image profile_subtracted_image = masked_imaging_7x7.image - blurred_image mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( image=profile_subtracted_image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, mapper=mapper, regularization=reg, ) assert (fit.galaxy_model_image_dict[g2] == np.zeros(9)).all() assert fit.galaxy_model_image_dict[g0].native == pytest.approx( g0_blurred_image.native, 1.0e-4 ) assert fit.galaxy_model_image_dict[g1].native == pytest.approx( g1_blurred_image.native, 1.0e-4 ) assert fit.galaxy_model_image_dict[galaxy_pix].native == pytest.approx( inversion.mapped_reconstructed_image.native, 1.0e-4 ) assert fit.model_image.native == pytest.approx( fit.galaxy_model_image_dict[g0].native + fit.galaxy_model_image_dict[g1].native + inversion.mapped_reconstructed_image.native, 1.0e-4, ) def test___all_fit_quantities__include_hyper_methods(self, masked_imaging_7x7): hyper_image_sky = ag.hyper_data.HyperImageSky(sky_scale=1.0) hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) image = hyper_image_sky.hyper_image_from_image( image=masked_imaging_7x7.image ) hyper_noise_map_background = hyper_background_noise.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) galaxy_light = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), hyper_galaxy=ag.HyperGalaxy( contribution_factor=1.0, noise_factor=1.0, noise_power=1.0 ), hyper_model_image=ag.Array2D.ones( shape_native=(3, 3), pixel_scales=1.0 ), hyper_galaxy_image=ag.Array2D.ones( shape_native=(3, 3), pixel_scales=1.0 ), hyper_minimum_value=0.0, ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[galaxy_light, galaxy_pix]) fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_image_sky=hyper_image_sky, hyper_background_noise=hyper_background_noise, ) hyper_noise = plane.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) hyper_noise_map = hyper_noise_map_background + hyper_noise assert hyper_noise_map.native == pytest.approx(fit.noise_map.native, 1.0e-4) blurred_image = plane.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) assert blurred_image.native == pytest.approx(fit.blurred_image.native) profile_subtracted_image = image - blurred_image assert profile_subtracted_image.native == pytest.approx( fit.profile_subtracted_image.native ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( image=profile_subtracted_image, noise_map=hyper_noise_map, convolver=masked_imaging_7x7.convolver, mapper=mapper, regularization=reg, ) model_image = blurred_image + inversion.mapped_reconstructed_image assert model_image.native == pytest.approx(fit.model_image.native, 1.0e-4) residual_map = ag.util.fit.residual_map_from( data=image, model_data=model_image ) assert residual_map.native == pytest.approx(fit.residual_map.native, 1.0e-4) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native, 1.0e-4 ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert chi_squared_map.native == pytest.approx( fit.chi_squared_map.native, 1.0e-4 ) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=hyper_noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit def test___blurred_and_model_images_of_galaxies_and_unmasked_blurred_image_properties( self, masked_imaging_7x7 ): galaxy_light = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[galaxy_light, galaxy_pix]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) blurred_image = plane.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) profile_subtracted_image = masked_imaging_7x7.image - blurred_image mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( image=profile_subtracted_image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, mapper=mapper, regularization=reg, ) assert blurred_image.native == pytest.approx( fit.model_images_of_galaxies[0].native, 1.0e-4 ) assert inversion.mapped_reconstructed_image.native == pytest.approx( fit.model_images_of_galaxies[1].native, 1.0e-4 ) class TestAttributes: def test__subtracted_images_of_galaxies(self, masked_imaging_no_blur_7x7): g0 = ag.Galaxy(redshift=0.5, light_profile=MockLightProfile(value=1.0)) g1 = ag.Galaxy(redshift=1.0, light_profile=MockLightProfile(value=2.0)) g2 = ag.Galaxy(redshift=1.0, light_profile=MockLightProfile(value=3.0)) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, g2]) fit = ag.FitImaging(masked_imaging=masked_imaging_no_blur_7x7, plane=plane) assert fit.subtracted_images_of_galaxies[0].slim[0] == -4.0 assert fit.subtracted_images_of_galaxies[1].slim[0] == -3.0 assert fit.subtracted_images_of_galaxies[2].slim[0] == -2.0 g0 = ag.Galaxy(redshift=0.5, light_profile=MockLightProfile(value=1.0)) g1 = ag.Galaxy(redshift=0.5) g2 = ag.Galaxy(redshift=1.0, light_profile=MockLightProfile(value=3.0)) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, g2]) fit = ag.FitImaging(masked_imaging=masked_imaging_no_blur_7x7, plane=plane) assert fit.subtracted_images_of_galaxies[0].slim[0] == -2.0 assert fit.subtracted_images_of_galaxies[1].slim[0] == -3.0 assert fit.subtracted_images_of_galaxies[2].slim[0] == 0.0 class TestFitInterferometer: class TestLikelihood: def test__1x2_image__1x2_visibilities__simple_fourier_transform(self): # The image plane image generated by the galaxy is [1.0, 1.0] # Thus the chi squared is 4.0**2.0 + 3.0**2.0 = 25.0 interferometer = ag.Interferometer( visibilities=ag.Visibilities.full(fill_value=5.0, shape_slim=(1,)), noise_map=ag.Visibilities.ones(shape_slim=(1,)), uv_wavelengths=np.array([[0.0, 0.0]]), ) interferometer.visibilities[0] = 5.0 + 4.0j visibilities_mask = np.full(fill_value=False, shape=(1,)) real_space_mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_interferometer = ag.MaskedInterferometer( interferometer=interferometer, visibilities_mask=visibilities_mask, real_space_mask=real_space_mask, settings=ag.SettingsMaskedInterferometer( grid_class=ag.Grid2D, sub_size=1, transformer_class=ag.TransformerDFT, ), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer, plane=plane ) assert (fit.visibilities_mask == np.array([False])).all() assert (fit.visibilities.slim == np.array([5.0 + 4.0j])).all() assert (fit.noise_map.slim == np.array([1.0 + 1.0j])).all() assert (fit.model_visibilities.slim == np.array([2.0 + 0.0j])).all() assert (fit.residual_map.slim == np.array([3.0 + 4.0j])).all() assert (fit.normalized_residual_map.slim == np.array([3.0 + 4.0j])).all() assert (fit.chi_squared_map.slim == np.array([9.0 + 16.0j])).all() assert fit.chi_squared == 25.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 1.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 25.0 + 2.0 * np.log(2 * np.pi * 1.0 ** 2.0) ) def test__hyper_background_changes_background_sky__reflected_in_likelihood( self, ): uv_wavelengths = np.array([[1.0, 0.0], [1.0, 1.0], [2.0, 2.0]]) interferometer = ag.Interferometer( visibilities=ag.Visibilities.full(fill_value=5.0, shape_slim=(3,)), noise_map=ag.Visibilities.full(fill_value=2.0, shape_slim=(3,)), uv_wavelengths=uv_wavelengths, ) visibilities_mask = np.full(fill_value=False, shape=(1,)) real_space_mask = ag.Mask2D.manual( mask=[ [True, True, True, True, True], [True, False, False, False, True], [True, True, True, True, True], ], pixel_scales=1.0, ) masked_interferometer = ag.MaskedInterferometer( interferometer=interferometer, visibilities_mask=visibilities_mask, real_space_mask=real_space_mask, settings=ag.SettingsMaskedInterferometer( grid_class=ag.Grid2D, sub_size=1 ), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer, plane=plane, hyper_background_noise=hyper_background_noise, ) assert ( fit.visibilities.slim == np.array([5.0 + 5.0j, 5.0 + 5.0j, 5.0 + 5.0j]) ).all() assert ( fit.noise_map.slim == np.array([3.0 + 3.0j, 3.0 + 3.0j, 3.0 + 3.0j]) ).all() class TestCompareToManualProfilesOnly: def test___all_fit_quantities__no_hyper_methods(self, masked_interferometer_7): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) assert masked_interferometer_7.noise_map == pytest.approx(fit.noise_map) model_visibilities = plane.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) assert model_visibilities == pytest.approx(fit.model_visibilities, 1e-4) residual_map = ag.util.fit.residual_map_from( data=masked_interferometer_7.visibilities, model_data=model_visibilities ) assert residual_map == pytest.approx(fit.residual_map, 1e-4) normalized_residual_map = ag.util.fit.normalized_residual_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert normalized_residual_map == pytest.approx( fit.normalized_residual_map, 1e-4 ) chi_squared_map = ag.util.fit.chi_squared_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert chi_squared_map == pytest.approx(fit.chi_squared_map, 1e-4) chi_squared = ag.util.fit.chi_squared_complex_from( chi_squared_map=fit.chi_squared_map ) noise_normalization = ag.util.fit.noise_normalization_complex_from( noise_map=masked_interferometer_7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) assert log_likelihood == fit.figure_of_merit def test___fit_galaxy_model_image_dict__corresponds_to_profile_galaxy_images( self, masked_interferometer_7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) g0_image = g0.image_from_grid(grid=masked_interferometer_7.grid) g1_image = g1.image_from_grid(grid=masked_interferometer_7.grid) assert fit.galaxy_model_image_dict[g0].slim == pytest.approx( g0_image, 1.0e-4 ) assert fit.galaxy_model_image_dict[g1].slim == pytest.approx( g1_image, 1.0e-4 ) def test___fit_galaxy_visibilities_dict__corresponds_to_galaxy_visibilities( self, masked_interferometer_7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) g0_profile_visibilities = g0.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) g1_profile_visibilities = g1.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) assert fit.galaxy_model_visibilities_dict[g0].slim == pytest.approx( g0_profile_visibilities, 1.0e-4 ) assert fit.galaxy_model_visibilities_dict[g1].slim == pytest.approx( g1_profile_visibilities, 1.0e-4 ) assert fit.model_visibilities.slim == pytest.approx( fit.galaxy_model_visibilities_dict[g0].slim + fit.galaxy_model_visibilities_dict[g1].slim, 1.0e-4, ) def test___all_fit_quantities__hyper_background_noise( self, masked_interferometer_7 ): hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) hyper_noise_map = hyper_background_noise.hyper_noise_map_from_complex_noise_map( noise_map=masked_interferometer_7.noise_map ) g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane, hyper_background_noise=hyper_background_noise, ) assert hyper_noise_map.slim == pytest.approx(fit.noise_map.slim) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane, hyper_background_noise=hyper_background_noise, use_hyper_scalings=False, ) assert fit.noise_map == pytest.approx( masked_interferometer_7.noise_map, 1.0e-4 ) assert fit.noise_map != pytest.approx(hyper_noise_map.slim, 1.0e-4) class TestCompareToManualInversionOnly: def test___all_fit_quantities__no_hyper_methods(self, masked_interferometer_7): # Ensures the inversion grid is used, as this would cause the test to fail. masked_interferometer_7.grid[0, 0] = -100.0 pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=0.01) g0 = ag.Galaxy(redshift=0.5, pixelization=pix, regularization=reg) plane = ag.Plane(galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid_inversion, sparse_grid=None ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, visibilities=masked_interferometer_7.visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, ) assert inversion.mapped_reconstructed_visibilities == pytest.approx( fit.model_visibilities, 1.0e-4 ) residual_map = ag.util.fit.residual_map_from( data=masked_interferometer_7.visibilities, model_data=inversion.mapped_reconstructed_visibilities, ) assert residual_map.slim == pytest.approx(fit.residual_map.slim, 1.0e-4) normalized_residual_map = ag.util.fit.normalized_residual_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert normalized_residual_map.slim == pytest.approx( fit.normalized_residual_map.slim, 1.0e-4 ) chi_squared_map = ag.util.fit.chi_squared_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert chi_squared_map.slim == pytest.approx( fit.chi_squared_map.slim, 1.0e-4 ) chi_squared = ag.util.fit.chi_squared_complex_from( chi_squared_map=chi_squared_map ) noise_normalization = ag.util.fit.noise_normalization_complex_from( noise_map=masked_interferometer_7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit mapped_reconstructed_image = ag.util.inversion.mapped_reconstructed_data_from( mapping_matrix=fit.inversion.mapper.mapping_matrix, reconstruction=fit.inversion.reconstruction, ) assert ( fit.inversion.mapped_reconstructed_image.slim == mapped_reconstructed_image ).all() def test___fit_galaxy_model_image_dict__images_and_inversion_mapped_reconstructed_image( self, masked_interferometer_7 ): pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy(redshift=0.5) g1 = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid, sparse_grid=None ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, visibilities=masked_interferometer_7.visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, ) assert (fit.galaxy_model_image_dict[g0].native == np.zeros((7, 7))).all() assert fit.galaxy_model_image_dict[g1].slim == pytest.approx( inversion.mapped_reconstructed_image.slim, 1.0e-4 ) def test___fit_galaxy_model_visibilities_dict__has_inversion_mapped_reconstructed_visibilities( self, masked_interferometer_7 ): pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy(redshift=0.5) g1 = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid, sparse_grid=None ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, visibilities=masked_interferometer_7.visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, ) assert ( fit.galaxy_model_visibilities_dict[g0] == 0.0 + 0.0j * np.zeros((7,)) ).all() assert fit.galaxy_model_visibilities_dict[g1].slim == pytest.approx( inversion.mapped_reconstructed_visibilities.slim, 1.0e-4 ) assert fit.model_visibilities.slim == pytest.approx( fit.galaxy_model_visibilities_dict[g1].slim, 1.0e-4 ) def test___all_fit_quantities__hyper_background_noise( self, masked_interferometer_7 ): hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) hyper_noise_map = hyper_background_noise.hyper_noise_map_from_complex_noise_map( noise_map=masked_interferometer_7.noise_map ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=0.01) g0 = ag.Galaxy(redshift=0.5, pixelization=pix, regularization=reg) plane = ag.Plane(galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane, hyper_background_noise=hyper_background_noise, ) assert hyper_noise_map.slim == pytest.approx( fit.inversion.noise_map, 1.0e-4 ) assert hyper_noise_map.slim == pytest.approx(fit.noise_map.slim) def test___all_fit_quantities__uses_linear_operator_inversion( self, masked_interferometer_7_lop ): # Ensures the inversion grid is used, as this would cause the test to fail. masked_interferometer_7_lop.grid[0, 0] = -100.0 pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=0.01) g0 = ag.Galaxy(redshift=0.5, pixelization=pix, regularization=reg) plane = ag.Plane(galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7_lop, plane=plane, settings_inversion=ag.SettingsInversion(use_linear_operators=True), ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7_lop.grid_inversion, sparse_grid=None ) inversion = inversions.InversionInterferometerLinearOperator.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, visibilities=masked_interferometer_7_lop.visibilities, noise_map=masked_interferometer_7_lop.noise_map, transformer=masked_interferometer_7_lop.transformer, settings=ag.SettingsInversion(use_linear_operators=True), ) assert inversion.mapped_reconstructed_visibilities == pytest.approx( fit.model_visibilities, 1.0e-4 ) residual_map = ag.util.fit.residual_map_from( data=masked_interferometer_7_lop.visibilities, model_data=inversion.mapped_reconstructed_visibilities, ) assert residual_map.slim == pytest.approx(fit.residual_map.slim, 1.0e-4) normalized_residual_map = ag.util.fit.normalized_residual_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7_lop.noise_map, ) assert normalized_residual_map.slim == pytest.approx( fit.normalized_residual_map.slim, 1.0e-4 ) chi_squared_map = ag.util.fit.chi_squared_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7_lop.noise_map, ) assert chi_squared_map.slim == pytest.approx( fit.chi_squared_map.slim, 1.0e-4 ) chi_squared = ag.util.fit.chi_squared_complex_from( chi_squared_map=chi_squared_map ) noise_normalization = ag.util.fit.noise_normalization_complex_from( noise_map=masked_interferometer_7_lop.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit mapped_reconstructed_image = ag.util.inversion.mapped_reconstructed_data_from( mapping_matrix=fit.inversion.mapper.mapping_matrix, reconstruction=fit.inversion.reconstruction, ) assert ( fit.inversion.mapped_reconstructed_image.slim == mapped_reconstructed_image ).all() class TestCompareToManualProfilesAndInversion: def test___all_fit_quantities__no_hyper_methods(self, masked_interferometer_7): galaxy_light = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[galaxy_light, galaxy_pix]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) profile_visibilities = plane.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) assert profile_visibilities.slim == pytest.approx( fit.profile_visibilities.slim ) profile_subtracted_visibilities = ( masked_interferometer_7.visibilities - profile_visibilities ) assert profile_subtracted_visibilities.slim == pytest.approx( fit.profile_subtracted_visibilities.slim ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( visibilities=profile_subtracted_visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, mapper=mapper, regularization=reg, ) model_visibilities = ( profile_visibilities + inversion.mapped_reconstructed_visibilities ) assert model_visibilities.slim == pytest.approx(fit.model_visibilities.slim) residual_map = ag.util.fit.residual_map_from( data=masked_interferometer_7.visibilities, model_data=model_visibilities ) assert residual_map.slim == pytest.approx(fit.residual_map.slim) normalized_residual_map = ag.util.fit.normalized_residual_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert normalized_residual_map.slim == pytest.approx( fit.normalized_residual_map.slim ) chi_squared_map = ag.util.fit.chi_squared_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert chi_squared_map.slim == pytest.approx(fit.chi_squared_map.slim) chi_squared = ag.util.fit.chi_squared_complex_from( chi_squared_map=chi_squared_map ) noise_normalization = ag.util.fit.noise_normalization_complex_from( noise_map=masked_interferometer_7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit mapped_reconstructed_image = ag.util.inversion.mapped_reconstructed_data_from( mapping_matrix=fit.inversion.mapper.mapping_matrix, reconstruction=fit.inversion.reconstruction, ) assert ( fit.inversion.mapped_reconstructed_image.slim == mapped_reconstructed_image ).all() def test___fit_galaxy_model_visibilities_dict__has_image_and_inversion_mapped_reconstructed_image( self, masked_interferometer_7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) g1 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=2.0) ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, galaxy_pix]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) g0_visibilities = g0.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) g1_visibilities = g1.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) profile_visibilities = g0_visibilities + g1_visibilities profile_subtracted_visibilities = ( masked_interferometer_7.visibilities - profile_visibilities ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( visibilities=profile_subtracted_visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, mapper=mapper, regularization=reg, ) g0_image = g0.image_from_grid(grid=masked_interferometer_7.grid) g1_image = g1.image_from_grid(grid=masked_interferometer_7.grid) assert fit.galaxy_model_image_dict[g0].slim == pytest.approx( g0_image.slim, 1.0e-4 ) assert fit.galaxy_model_image_dict[g1].slim == pytest.approx( g1_image.slim, 1.0e-4 ) assert fit.galaxy_model_image_dict[galaxy_pix].slim == pytest.approx( inversion.mapped_reconstructed_image.slim, 1.0e-4 ) def test___fit_galaxy_model_visibilities_dict__has_profile_visibilitiess_and_inversion_mapped_reconstructed_visibilities( self, masked_interferometer_7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) g1 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=2.0) ) g2 = ag.Galaxy(redshift=0.5) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, g2, galaxy_pix]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) g0_visibilities = g0.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) g1_visibilities = g1.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) profile_visibilities = g0_visibilities + g1_visibilities profile_subtracted_visibilities = ( masked_interferometer_7.visibilities - profile_visibilities ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( visibilities=profile_subtracted_visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, mapper=mapper, regularization=reg, ) assert ( fit.galaxy_model_visibilities_dict[g2] == 0.0 + 0.0j * np.zeros((7,)) ).all() assert fit.galaxy_model_visibilities_dict[g0].slim == pytest.approx( g0_visibilities.slim, 1.0e-4 ) assert fit.galaxy_model_visibilities_dict[g1].slim == pytest.approx( g1_visibilities.slim, 1.0e-4 ) assert fit.galaxy_model_visibilities_dict[galaxy_pix].slim == pytest.approx( inversion.mapped_reconstructed_visibilities.slim, 1.0e-4 ) assert fit.model_visibilities.slim == pytest.approx( fit.galaxy_model_visibilities_dict[g0].slim + fit.galaxy_model_visibilities_dict[g1].slim + inversion.mapped_reconstructed_visibilities.slim, 1.0e-4, ) def test___all_fit_quantities__hyper_background_noise( self, masked_interferometer_7 ): hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) hyper_noise_map = hyper_background_noise.hyper_noise_map_from_complex_noise_map( noise_map=masked_interferometer_7.noise_map ) galaxy_light = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[galaxy_light, galaxy_pix]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane, hyper_background_noise=hyper_background_noise, ) assert hyper_noise_map.slim == pytest.approx( fit.inversion.noise_map, 1.0e-4 ) assert hyper_noise_map.slim == pytest.approx(fit.noise_map.slim)
test_autogalaxy/unit/fit/test_fit.py
import numpy as np import pytest import autogalaxy as ag from autoarray.inversion import inversions from autogalaxy.mock.mock import MockLightProfile class MockFitImaging: def __init__(self, model_images_of_galaxies): self.model_images_of_galaxies = model_images_of_galaxies class TestFitImaging: class TestLikelihood: def test__1x2_image__no_psf_blurring__plane_fits_data_with_chi_sq_5(self): # The image plane image generated by the galaxy is [1.0, 1.0] # Thus the chi squared is 4.0**2.0 + 3.0**2.0 = 25.0 psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, ) imaging = ag.Imaging( image=5.0 * ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[6] = 4.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging(grid_class=ag.Grid2D, sub_size=1), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) assert ( fit.mask == np.array( [ [True, True, True, True], [True, False, False, True], [True, True, True, True], ] ) ).all() assert ( fit.image.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 5.0, 4.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.noise_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.model_image.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.residual_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 4.0, 3.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.normalized_residual_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 4.0, 3.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.chi_squared_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 16.0, 9.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert fit.chi_squared == 25.0 assert fit.reduced_chi_squared == 25.0 / 2.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 1.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 25.0 + 2.0 * np.log(2 * np.pi * 1.0 ** 2.0) ) def test__1x2_image__include_psf_blurring__plane_fits_data_with_chi_sq_4(self): # This PSF changes the blurred image plane image from [1.0, 1.0] to [1.0, 5.0] # Thus, the chi squared is 4.0**2.0 + 0.0**2.0 = 16.0 psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 3.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, renormalize=False, ) imaging = ag.Imaging( image=5.0 * ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[6] = 4.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging( grid_class=ag.Grid2D, renormalize_psf=False, sub_size=1 ), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) assert ( fit.mask == np.array( [ [True, True, True, True], [True, False, False, True], [True, True, True, True], ] ) ).all() assert ( fit.image.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 5.0, 4.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.noise_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.model_image.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 4.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.residual_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 4.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.normalized_residual_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 4.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.chi_squared_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 16.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert fit.chi_squared == 16.0 assert fit.reduced_chi_squared == 16.0 / 2.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 1.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 16.0 + 2.0 * np.log(2 * np.pi * 1.0 ** 2.0) ) def test__hyper_galaxy_changes_noise_above_from_1_to_2__reflected_in_likelihood( self, ): # This PSF changes the blurred image plane image from [1.0, 1.0] to [1.0, 5.0] # Thus, the chi squared is 4.0**2.0 + 0.0**2.0 = 16.0 # The hyper_galaxies galaxy increases the noise in both pixels by 1.0, to 2.0. # This reduces the chi squared to 2.0 instead of 4.0 psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 3.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, ) imaging = ag.Imaging( image=5.0 * ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[6] = 4.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging( grid_class=ag.Grid2D, renormalize_psf=False, sub_size=1 ), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2), hyper_galaxy=ag.HyperGalaxy( contribution_factor=1.0, noise_factor=1.0, noise_power=1.0 ), hyper_model_image=ag.Array2D.ones( shape_native=(1, 2), pixel_scales=1.0 ), hyper_galaxy_image=ag.Array2D.ones( shape_native=(1, 2), pixel_scales=1.0 ), hyper_minimum_value=0.0, ) plane = ag.Plane(galaxies=[g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) assert ( fit.noise_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 2.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.chi_squared_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 4.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert fit.chi_squared == 4.0 assert fit.reduced_chi_squared == 4.0 / 2.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 2.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 4.0 + 2.0 * np.log(2 * np.pi * 2.0 ** 2.0) ) def test__hyper_image_changes_background_sky__reflected_in_likelihood(self): psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, ) imaging = ag.Imaging( image=ag.Array2D.full( fill_value=4.0, shape_native=(3, 4), pixel_scales=1.0 ), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[5] = 5.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging(grid_class=ag.Grid2D, sub_size=1), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) hyper_image_sky = ag.hyper_data.HyperImageSky(sky_scale=1.0) fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_image_sky=hyper_image_sky, ) assert ( fit.mask == np.array( [ [True, True, True, True], [True, False, False, True], [True, True, True, True], ] ) ).all() assert ( fit.image.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 6.0, 5.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert ( fit.chi_squared_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 25.0, 16.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert fit.chi_squared == 41.0 assert fit.reduced_chi_squared == 41.0 / 2.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 1.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 41.0 + 2.0 * np.log(2 * np.pi * 1.0 ** 2.0) ) def test__hyper_background_changes_background_noise_map__reflected_in_likelihood( self, ): psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, ) imaging = ag.Imaging( image=5.0 * ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[6] = 4.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging(grid_class=ag.Grid2D, sub_size=1), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_background_noise=hyper_background_noise, ) assert ( fit.noise_map.native == np.array( [[0.0, 0.0, 0.0, 0.0], [0.0, 2.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]] ) ).all() assert fit.chi_squared == 6.25 assert fit.reduced_chi_squared == 6.25 / 2.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 2.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 6.25 + 2.0 * np.log(2 * np.pi * 2.0 ** 2.0) ) def test__hyper_galaxy_changes_noise_above_hyper_noise_limit__rounded_down_to_limit( self, ): # This PSF changes the blurred image plane image from [1.0, 1.0] to [1.0, 5.0] # Thus, the chi squared is 4.0**2.0 + 0.0**2.0 = 16.0 # The hyper_galaxies galaxy increases the noise in both pixels by 1.0, to 2.0. # This reduces the chi squared to 2.0 instead of 4.0 psf = ag.Kernel2D.manual_native( array=[[0.0, 0.0, 0.0], [0.0, 1.0, 3.0], [0.0, 0.0, 0.0]], pixel_scales=1.0, ) imaging = ag.Imaging( image=5.0 * ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), psf=psf, noise_map=ag.Array2D.ones(shape_native=(3, 4), pixel_scales=1.0), ) imaging.image[6] = 4.0 mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_imaging_7x7 = ag.MaskedImaging( imaging=imaging, mask=mask, settings=ag.SettingsMaskedImaging( grid_class=ag.Grid2D, renormalize_psf=False, sub_size=1 ), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2), hyper_galaxy=ag.HyperGalaxy( contribution_factor=1.0, noise_factor=1.0e9, noise_power=1.0 ), hyper_model_image=ag.Array2D.ones( shape_native=(1, 2), pixel_scales=1.0 ), hyper_galaxy_image=ag.Array2D.ones( shape_native=(1, 2), pixel_scales=1.0 ), hyper_minimum_value=0.0, ) plane = ag.Plane(galaxies=[g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) assert ( fit.noise_map.native == np.array( [ [0.0, 0.0, 0.0, 0.0], [0.0, 1.0e8, 1.0e8, 0.0], [0.0, 0.0, 0.0, 0.0], ] ) ).all() class TestCompareToManualProfilesOnly: def test___all_fit_quantities__no_hyper_methods(self, masked_imaging_7x7): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) assert masked_imaging_7x7.noise_map.native == pytest.approx( fit.noise_map.native ) model_image = plane.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) assert model_image.native == pytest.approx(fit.model_image.native) residual_map = ag.util.fit.residual_map_from( data=masked_imaging_7x7.image, model_data=model_image ) assert residual_map.native == pytest.approx(fit.residual_map.native) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert chi_squared_map.native == pytest.approx(fit.chi_squared_map.native) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=masked_imaging_7x7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) assert log_likelihood == fit.figure_of_merit def test___fit_galaxy_model_image_dict__corresponds_to_blurred_galaxy_images( self, masked_imaging_7x7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) g2 = ag.Galaxy(redshift=1.0) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, g2]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) g0_blurred_image = g0.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, blurring_grid=masked_imaging_7x7.blurring_grid, convolver=masked_imaging_7x7.convolver, ) g1_blurred_image = g1.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, blurring_grid=masked_imaging_7x7.blurring_grid, convolver=masked_imaging_7x7.convolver, ) assert fit.galaxy_model_image_dict[g0] == pytest.approx( g0_blurred_image, 1.0e-4 ) assert fit.galaxy_model_image_dict[g1] == pytest.approx( g1_blurred_image, 1.0e-4 ) assert (fit.galaxy_model_image_dict[g2].slim == np.zeros(9)).all() assert fit.model_image.native == pytest.approx( fit.galaxy_model_image_dict[g0].native + fit.galaxy_model_image_dict[g1].native, 1.0e-4, ) def test___all_fit_quantities__including_hyper_methods( self, masked_imaging_7x7 ): hyper_image_sky = ag.hyper_data.HyperImageSky(sky_scale=1.0) hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) image = hyper_image_sky.hyper_image_from_image( image=masked_imaging_7x7.image ) g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), hyper_galaxy=ag.HyperGalaxy( contribution_factor=1.0, noise_factor=1.0, noise_power=1.0 ), hyper_model_image=np.ones(9), hyper_galaxy_image=np.ones(9), hyper_minimum_value=0.0, ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_image_sky=hyper_image_sky, hyper_background_noise=hyper_background_noise, ) hyper_noise_map_background = hyper_background_noise.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) hyper_noise = plane.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) hyper_noise_map = hyper_noise_map_background + hyper_noise assert hyper_noise_map.native == pytest.approx(fit.noise_map.native) model_image = plane.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) assert model_image.native == pytest.approx(fit.model_image.native) residual_map = ag.util.fit.residual_map_from( data=image, model_data=model_image ) assert residual_map.native == pytest.approx(fit.residual_map.native) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert chi_squared_map.native == pytest.approx(fit.chi_squared_map.native) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=hyper_noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) assert log_likelihood == fit.figure_of_merit fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_image_sky=hyper_image_sky, hyper_background_noise=hyper_background_noise, use_hyper_scalings=False, ) assert fit.image == pytest.approx(masked_imaging_7x7.image, 1.0e-4) assert fit.noise_map == pytest.approx(masked_imaging_7x7.noise_map, 1.0e-4) def test___blurred_and_model_images_of_galaxies_and_unmasked_blurred_image_properties( self, masked_imaging_7x7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) blurred_images_of_galaxies = plane.blurred_images_of_galaxies_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) assert blurred_images_of_galaxies[0].native == pytest.approx( fit.model_images_of_galaxies[0].native, 1.0e-4 ) assert blurred_images_of_galaxies[1].native == pytest.approx( fit.model_images_of_galaxies[1].native, 1.0e-4 ) unmasked_blurred_image = plane.unmasked_blurred_image_from_grid_and_psf( grid=masked_imaging_7x7.grid, psf=masked_imaging_7x7.psf ) assert (unmasked_blurred_image == fit.unmasked_blurred_image).all() unmasked_blurred_image_of_galaxies = plane.unmasked_blurred_image_of_galaxies_from_grid_and_psf( grid=masked_imaging_7x7.grid, psf=masked_imaging_7x7.psf ) assert ( unmasked_blurred_image_of_galaxies[0] == fit.unmasked_blurred_image_of_galaxies[0] ).all() assert ( unmasked_blurred_image_of_galaxies[1] == fit.unmasked_blurred_image_of_galaxies[1] ).all() class TestCompareToManualInversionOnly: def test___all_quantities__no_hyper_methods(self, masked_imaging_7x7): # Ensures the inversion grid is used, as this would cause the test to fail. masked_imaging_7x7.grid[0, 0] = -100.0 pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy(redshift=0.5, pixelization=pix, regularization=reg) plane = ag.Plane(galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid_inversion, sparse_grid=None ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, image=masked_imaging_7x7.image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, ) assert inversion.mapped_reconstructed_image.native == pytest.approx( fit.model_image.native, 1.0e-4 ) residual_map = ag.util.fit.residual_map_from( data=masked_imaging_7x7.image, model_data=inversion.mapped_reconstructed_image, ) assert residual_map.native == pytest.approx(fit.residual_map.native, 1.0e-4) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native, 1.0e-4 ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert chi_squared_map.native == pytest.approx( fit.chi_squared_map.native, 1.0e-4 ) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=masked_imaging_7x7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit def test___fit_galaxy_model_image_dict__has_inversion_mapped_reconstructed_image( self, masked_imaging_7x7 ): pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy(redshift=0.5) g1 = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, sparse_grid=None ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, image=masked_imaging_7x7.image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, ) assert (fit.galaxy_model_image_dict[g0] == np.zeros(9)).all() assert fit.galaxy_model_image_dict[g1].native == pytest.approx( inversion.mapped_reconstructed_image.native, 1.0e-4 ) assert fit.model_image.native == pytest.approx( fit.galaxy_model_image_dict[g1].native, 1.0e-4 ) def test___all_fit_quantities__include_hyper_methods(self, masked_imaging_7x7): hyper_image_sky = ag.hyper_data.HyperImageSky(sky_scale=1.0) hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) image = hyper_image_sky.hyper_image_from_image( image=masked_imaging_7x7.image ) hyper_noise_map_background = hyper_background_noise.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy( redshift=0.5, pixelization=pix, regularization=reg, hyper_galaxy=ag.HyperGalaxy( contribution_factor=1.0, noise_factor=1.0, noise_power=1.0 ), hyper_model_image=np.ones(9), hyper_galaxy_image=np.ones(9), hyper_minimum_value=0.0, ) plane = ag.Plane(galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_image_sky=hyper_image_sky, hyper_background_noise=hyper_background_noise, ) hyper_noise = plane.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) hyper_noise_map = hyper_noise_map_background + hyper_noise assert hyper_noise_map.native == pytest.approx(fit.noise_map.native) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, image=image, noise_map=hyper_noise_map, convolver=masked_imaging_7x7.convolver, ) assert inversion.mapped_reconstructed_image.native == pytest.approx( fit.model_image.native, 1.0e-4 ) residual_map = ag.util.fit.residual_map_from( data=image, model_data=inversion.mapped_reconstructed_image ) assert residual_map.native == pytest.approx(fit.residual_map.native) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert chi_squared_map.native == pytest.approx(fit.chi_squared_map.native) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=hyper_noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit def test___blurred_and_model_images_of_galaxies_and_unmasked_blurred_image_properties( self, masked_imaging_7x7 ): pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, image=masked_imaging_7x7.image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, ) assert (fit.model_images_of_galaxies[0].native == np.zeros((7, 7))).all() assert inversion.mapped_reconstructed_image.native == pytest.approx( fit.model_images_of_galaxies[1].native, 1.0e-4 ) class TestCompareToManualProfilesAndInversion: def test___all_fit_quantities__no_hyper_methods(self, masked_imaging_7x7): galaxy_light = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[galaxy_light, galaxy_pix]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) blurred_image = plane.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) assert blurred_image.native == pytest.approx(fit.blurred_image.native) profile_subtracted_image = masked_imaging_7x7.image - blurred_image assert profile_subtracted_image.native == pytest.approx( fit.profile_subtracted_image.native ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( image=profile_subtracted_image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, mapper=mapper, regularization=reg, ) model_image = blurred_image + inversion.mapped_reconstructed_image assert model_image.native == pytest.approx(fit.model_image.native) residual_map = ag.util.fit.residual_map_from( data=masked_imaging_7x7.image, model_data=model_image ) assert residual_map.native == pytest.approx(fit.residual_map.native) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=masked_imaging_7x7.noise_map ) assert chi_squared_map.native == pytest.approx(fit.chi_squared_map.native) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=masked_imaging_7x7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit def test___fit_galaxy_model_image_dict__has_blurred_images_and_inversion_mapped_reconstructed_image( self, masked_imaging_7x7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) g1 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=2.0) ) g2 = ag.Galaxy(redshift=0.5) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, g2, galaxy_pix]) masked_imaging_7x7.image[0] = 3.0 fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) g0_blurred_image = g0.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) g1_blurred_image = g1.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) blurred_image = g0_blurred_image + g1_blurred_image profile_subtracted_image = masked_imaging_7x7.image - blurred_image mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( image=profile_subtracted_image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, mapper=mapper, regularization=reg, ) assert (fit.galaxy_model_image_dict[g2] == np.zeros(9)).all() assert fit.galaxy_model_image_dict[g0].native == pytest.approx( g0_blurred_image.native, 1.0e-4 ) assert fit.galaxy_model_image_dict[g1].native == pytest.approx( g1_blurred_image.native, 1.0e-4 ) assert fit.galaxy_model_image_dict[galaxy_pix].native == pytest.approx( inversion.mapped_reconstructed_image.native, 1.0e-4 ) assert fit.model_image.native == pytest.approx( fit.galaxy_model_image_dict[g0].native + fit.galaxy_model_image_dict[g1].native + inversion.mapped_reconstructed_image.native, 1.0e-4, ) def test___all_fit_quantities__include_hyper_methods(self, masked_imaging_7x7): hyper_image_sky = ag.hyper_data.HyperImageSky(sky_scale=1.0) hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) image = hyper_image_sky.hyper_image_from_image( image=masked_imaging_7x7.image ) hyper_noise_map_background = hyper_background_noise.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) galaxy_light = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), hyper_galaxy=ag.HyperGalaxy( contribution_factor=1.0, noise_factor=1.0, noise_power=1.0 ), hyper_model_image=ag.Array2D.ones( shape_native=(3, 3), pixel_scales=1.0 ), hyper_galaxy_image=ag.Array2D.ones( shape_native=(3, 3), pixel_scales=1.0 ), hyper_minimum_value=0.0, ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[galaxy_light, galaxy_pix]) fit = ag.FitImaging( masked_imaging=masked_imaging_7x7, plane=plane, hyper_image_sky=hyper_image_sky, hyper_background_noise=hyper_background_noise, ) hyper_noise = plane.hyper_noise_map_from_noise_map( noise_map=masked_imaging_7x7.noise_map ) hyper_noise_map = hyper_noise_map_background + hyper_noise assert hyper_noise_map.native == pytest.approx(fit.noise_map.native, 1.0e-4) blurred_image = plane.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) assert blurred_image.native == pytest.approx(fit.blurred_image.native) profile_subtracted_image = image - blurred_image assert profile_subtracted_image.native == pytest.approx( fit.profile_subtracted_image.native ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( image=profile_subtracted_image, noise_map=hyper_noise_map, convolver=masked_imaging_7x7.convolver, mapper=mapper, regularization=reg, ) model_image = blurred_image + inversion.mapped_reconstructed_image assert model_image.native == pytest.approx(fit.model_image.native, 1.0e-4) residual_map = ag.util.fit.residual_map_from( data=image, model_data=model_image ) assert residual_map.native == pytest.approx(fit.residual_map.native, 1.0e-4) normalized_residual_map = ag.util.fit.normalized_residual_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert normalized_residual_map.native == pytest.approx( fit.normalized_residual_map.native, 1.0e-4 ) chi_squared_map = ag.util.fit.chi_squared_map_from( residual_map=residual_map, noise_map=hyper_noise_map ) assert chi_squared_map.native == pytest.approx( fit.chi_squared_map.native, 1.0e-4 ) chi_squared = ag.util.fit.chi_squared_from(chi_squared_map=chi_squared_map) noise_normalization = ag.util.fit.noise_normalization_from( noise_map=hyper_noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit def test___blurred_and_model_images_of_galaxies_and_unmasked_blurred_image_properties( self, masked_imaging_7x7 ): galaxy_light = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[galaxy_light, galaxy_pix]) fit = ag.FitImaging(masked_imaging=masked_imaging_7x7, plane=plane) blurred_image = plane.blurred_image_from_grid_and_convolver( grid=masked_imaging_7x7.grid, convolver=masked_imaging_7x7.convolver, blurring_grid=masked_imaging_7x7.blurring_grid, ) profile_subtracted_image = masked_imaging_7x7.image - blurred_image mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_imaging_7x7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionImagingMatrix.from_data_mapper_and_regularization( image=profile_subtracted_image, noise_map=masked_imaging_7x7.noise_map, convolver=masked_imaging_7x7.convolver, mapper=mapper, regularization=reg, ) assert blurred_image.native == pytest.approx( fit.model_images_of_galaxies[0].native, 1.0e-4 ) assert inversion.mapped_reconstructed_image.native == pytest.approx( fit.model_images_of_galaxies[1].native, 1.0e-4 ) class TestAttributes: def test__subtracted_images_of_galaxies(self, masked_imaging_no_blur_7x7): g0 = ag.Galaxy(redshift=0.5, light_profile=MockLightProfile(value=1.0)) g1 = ag.Galaxy(redshift=1.0, light_profile=MockLightProfile(value=2.0)) g2 = ag.Galaxy(redshift=1.0, light_profile=MockLightProfile(value=3.0)) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, g2]) fit = ag.FitImaging(masked_imaging=masked_imaging_no_blur_7x7, plane=plane) assert fit.subtracted_images_of_galaxies[0].slim[0] == -4.0 assert fit.subtracted_images_of_galaxies[1].slim[0] == -3.0 assert fit.subtracted_images_of_galaxies[2].slim[0] == -2.0 g0 = ag.Galaxy(redshift=0.5, light_profile=MockLightProfile(value=1.0)) g1 = ag.Galaxy(redshift=0.5) g2 = ag.Galaxy(redshift=1.0, light_profile=MockLightProfile(value=3.0)) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, g2]) fit = ag.FitImaging(masked_imaging=masked_imaging_no_blur_7x7, plane=plane) assert fit.subtracted_images_of_galaxies[0].slim[0] == -2.0 assert fit.subtracted_images_of_galaxies[1].slim[0] == -3.0 assert fit.subtracted_images_of_galaxies[2].slim[0] == 0.0 class TestFitInterferometer: class TestLikelihood: def test__1x2_image__1x2_visibilities__simple_fourier_transform(self): # The image plane image generated by the galaxy is [1.0, 1.0] # Thus the chi squared is 4.0**2.0 + 3.0**2.0 = 25.0 interferometer = ag.Interferometer( visibilities=ag.Visibilities.full(fill_value=5.0, shape_slim=(1,)), noise_map=ag.Visibilities.ones(shape_slim=(1,)), uv_wavelengths=np.array([[0.0, 0.0]]), ) interferometer.visibilities[0] = 5.0 + 4.0j visibilities_mask = np.full(fill_value=False, shape=(1,)) real_space_mask = ag.Mask2D.manual( mask=[ [True, True, True, True], [True, False, False, True], [True, True, True, True], ], pixel_scales=1.0, ) masked_interferometer = ag.MaskedInterferometer( interferometer=interferometer, visibilities_mask=visibilities_mask, real_space_mask=real_space_mask, settings=ag.SettingsMaskedInterferometer( grid_class=ag.Grid2D, sub_size=1, transformer_class=ag.TransformerDFT, ), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer, plane=plane ) assert (fit.visibilities_mask == np.array([False])).all() assert (fit.visibilities.slim == np.array([5.0 + 4.0j])).all() assert (fit.noise_map.slim == np.array([1.0 + 1.0j])).all() assert (fit.model_visibilities.slim == np.array([2.0 + 0.0j])).all() assert (fit.residual_map.slim == np.array([3.0 + 4.0j])).all() assert (fit.normalized_residual_map.slim == np.array([3.0 + 4.0j])).all() assert (fit.chi_squared_map.slim == np.array([9.0 + 16.0j])).all() assert fit.chi_squared == 25.0 assert fit.noise_normalization == (2.0 * np.log(2 * np.pi * 1.0 ** 2.0)) assert fit.log_likelihood == -0.5 * ( 25.0 + 2.0 * np.log(2 * np.pi * 1.0 ** 2.0) ) def test__hyper_background_changes_background_sky__reflected_in_likelihood( self, ): uv_wavelengths = np.array([[1.0, 0.0], [1.0, 1.0], [2.0, 2.0]]) interferometer = ag.Interferometer( visibilities=ag.Visibilities.full(fill_value=5.0, shape_slim=(3,)), noise_map=ag.Visibilities.full(fill_value=2.0, shape_slim=(3,)), uv_wavelengths=uv_wavelengths, ) visibilities_mask = np.full(fill_value=False, shape=(1,)) real_space_mask = ag.Mask2D.manual( mask=[ [True, True, True, True, True], [True, False, False, False, True], [True, True, True, True, True], ], pixel_scales=1.0, ) masked_interferometer = ag.MaskedInterferometer( interferometer=interferometer, visibilities_mask=visibilities_mask, real_space_mask=real_space_mask, settings=ag.SettingsMaskedInterferometer( grid_class=ag.Grid2D, sub_size=1 ), ) # Setup as a ray trace instance, using a light profile for the galaxy g0 = ag.Galaxy( redshift=0.5, light_profile=MockLightProfile(value=1.0, size=2) ) plane = ag.Plane(galaxies=[g0]) hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer, plane=plane, hyper_background_noise=hyper_background_noise, ) assert ( fit.visibilities.slim == np.array([5.0 + 5.0j, 5.0 + 5.0j, 5.0 + 5.0j]) ).all() assert ( fit.noise_map.slim == np.array([3.0 + 3.0j, 3.0 + 3.0j, 3.0 + 3.0j]) ).all() class TestCompareToManualProfilesOnly: def test___all_fit_quantities__no_hyper_methods(self, masked_interferometer_7): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) assert masked_interferometer_7.noise_map == pytest.approx(fit.noise_map) model_visibilities = plane.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) assert model_visibilities == pytest.approx(fit.model_visibilities, 1e-4) residual_map = ag.util.fit.residual_map_from( data=masked_interferometer_7.visibilities, model_data=model_visibilities ) assert residual_map == pytest.approx(fit.residual_map, 1e-4) normalized_residual_map = ag.util.fit.normalized_residual_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert normalized_residual_map == pytest.approx( fit.normalized_residual_map, 1e-4 ) chi_squared_map = ag.util.fit.chi_squared_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert chi_squared_map == pytest.approx(fit.chi_squared_map, 1e-4) chi_squared = ag.util.fit.chi_squared_complex_from( chi_squared_map=fit.chi_squared_map ) noise_normalization = ag.util.fit.noise_normalization_complex_from( noise_map=masked_interferometer_7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) assert log_likelihood == fit.figure_of_merit def test___fit_galaxy_model_image_dict__corresponds_to_profile_galaxy_images( self, masked_interferometer_7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) g0_image = g0.image_from_grid(grid=masked_interferometer_7.grid) g1_image = g1.image_from_grid(grid=masked_interferometer_7.grid) assert fit.galaxy_model_image_dict[g0].slim == pytest.approx( g0_image, 1.0e-4 ) assert fit.galaxy_model_image_dict[g1].slim == pytest.approx( g1_image, 1.0e-4 ) def test___fit_galaxy_visibilities_dict__corresponds_to_galaxy_visibilities( self, masked_interferometer_7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) g0_profile_visibilities = g0.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) g1_profile_visibilities = g1.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) assert fit.galaxy_model_visibilities_dict[g0].slim == pytest.approx( g0_profile_visibilities, 1.0e-4 ) assert fit.galaxy_model_visibilities_dict[g1].slim == pytest.approx( g1_profile_visibilities, 1.0e-4 ) assert fit.model_visibilities.slim == pytest.approx( fit.galaxy_model_visibilities_dict[g0].slim + fit.galaxy_model_visibilities_dict[g1].slim, 1.0e-4, ) def test___all_fit_quantities__hyper_background_noise( self, masked_interferometer_7 ): hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) hyper_noise_map = hyper_background_noise.hyper_noise_map_from_complex_noise_map( noise_map=masked_interferometer_7.noise_map ) g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0), mass_profile=ag.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = ag.Galaxy( redshift=1.0, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane, hyper_background_noise=hyper_background_noise, ) assert hyper_noise_map.slim == pytest.approx(fit.noise_map.slim) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane, hyper_background_noise=hyper_background_noise, use_hyper_scalings=False, ) assert fit.noise_map == pytest.approx( masked_interferometer_7.noise_map, 1.0e-4 ) assert fit.noise_map != pytest.approx(hyper_noise_map.slim, 1.0e-4) class TestCompareToManualInversionOnly: def test___all_fit_quantities__no_hyper_methods(self, masked_interferometer_7): # Ensures the inversion grid is used, as this would cause the test to fail. masked_interferometer_7.grid[0, 0] = -100.0 pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=0.01) g0 = ag.Galaxy(redshift=0.5, pixelization=pix, regularization=reg) plane = ag.Plane(galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid_inversion, sparse_grid=None ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, visibilities=masked_interferometer_7.visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, ) assert inversion.mapped_reconstructed_visibilities == pytest.approx( fit.model_visibilities, 1.0e-4 ) residual_map = ag.util.fit.residual_map_from( data=masked_interferometer_7.visibilities, model_data=inversion.mapped_reconstructed_visibilities, ) assert residual_map.slim == pytest.approx(fit.residual_map.slim, 1.0e-4) normalized_residual_map = ag.util.fit.normalized_residual_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert normalized_residual_map.slim == pytest.approx( fit.normalized_residual_map.slim, 1.0e-4 ) chi_squared_map = ag.util.fit.chi_squared_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert chi_squared_map.slim == pytest.approx( fit.chi_squared_map.slim, 1.0e-4 ) chi_squared = ag.util.fit.chi_squared_complex_from( chi_squared_map=chi_squared_map ) noise_normalization = ag.util.fit.noise_normalization_complex_from( noise_map=masked_interferometer_7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit mapped_reconstructed_image = ag.util.inversion.mapped_reconstructed_data_from( mapping_matrix=fit.inversion.mapper.mapping_matrix, reconstruction=fit.inversion.reconstruction, ) assert ( fit.inversion.mapped_reconstructed_image.slim == mapped_reconstructed_image ).all() def test___fit_galaxy_model_image_dict__images_and_inversion_mapped_reconstructed_image( self, masked_interferometer_7 ): pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy(redshift=0.5) g1 = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid, sparse_grid=None ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, visibilities=masked_interferometer_7.visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, ) assert (fit.galaxy_model_image_dict[g0].native == np.zeros((7, 7))).all() assert fit.galaxy_model_image_dict[g1].slim == pytest.approx( inversion.mapped_reconstructed_image.slim, 1.0e-4 ) def test___fit_galaxy_model_visibilities_dict__has_inversion_mapped_reconstructed_visibilities( self, masked_interferometer_7 ): pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) g0 = ag.Galaxy(redshift=0.5) g1 = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid, sparse_grid=None ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, visibilities=masked_interferometer_7.visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, ) assert ( fit.galaxy_model_visibilities_dict[g0] == 0.0 + 0.0j * np.zeros((7,)) ).all() assert fit.galaxy_model_visibilities_dict[g1].slim == pytest.approx( inversion.mapped_reconstructed_visibilities.slim, 1.0e-4 ) assert fit.model_visibilities.slim == pytest.approx( fit.galaxy_model_visibilities_dict[g1].slim, 1.0e-4 ) def test___all_fit_quantities__hyper_background_noise( self, masked_interferometer_7 ): hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) hyper_noise_map = hyper_background_noise.hyper_noise_map_from_complex_noise_map( noise_map=masked_interferometer_7.noise_map ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=0.01) g0 = ag.Galaxy(redshift=0.5, pixelization=pix, regularization=reg) plane = ag.Plane(galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane, hyper_background_noise=hyper_background_noise, ) assert hyper_noise_map.slim == pytest.approx( fit.inversion.noise_map, 1.0e-4 ) assert hyper_noise_map.slim == pytest.approx(fit.noise_map.slim) def test___all_fit_quantities__uses_linear_operator_inversion( self, masked_interferometer_7_lop ): # Ensures the inversion grid is used, as this would cause the test to fail. masked_interferometer_7_lop.grid[0, 0] = -100.0 pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=0.01) g0 = ag.Galaxy(redshift=0.5, pixelization=pix, regularization=reg) plane = ag.Plane(galaxies=[ag.Galaxy(redshift=0.5), g0]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7_lop, plane=plane, settings_inversion=ag.SettingsInversion(use_linear_operators=True), ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7_lop.grid_inversion, sparse_grid=None ) inversion = inversions.InversionInterferometerLinearOperator.from_data_mapper_and_regularization( mapper=mapper, regularization=reg, visibilities=masked_interferometer_7_lop.visibilities, noise_map=masked_interferometer_7_lop.noise_map, transformer=masked_interferometer_7_lop.transformer, settings=ag.SettingsInversion(use_linear_operators=True), ) assert inversion.mapped_reconstructed_visibilities == pytest.approx( fit.model_visibilities, 1.0e-4 ) residual_map = ag.util.fit.residual_map_from( data=masked_interferometer_7_lop.visibilities, model_data=inversion.mapped_reconstructed_visibilities, ) assert residual_map.slim == pytest.approx(fit.residual_map.slim, 1.0e-4) normalized_residual_map = ag.util.fit.normalized_residual_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7_lop.noise_map, ) assert normalized_residual_map.slim == pytest.approx( fit.normalized_residual_map.slim, 1.0e-4 ) chi_squared_map = ag.util.fit.chi_squared_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7_lop.noise_map, ) assert chi_squared_map.slim == pytest.approx( fit.chi_squared_map.slim, 1.0e-4 ) chi_squared = ag.util.fit.chi_squared_complex_from( chi_squared_map=chi_squared_map ) noise_normalization = ag.util.fit.noise_normalization_complex_from( noise_map=masked_interferometer_7_lop.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit mapped_reconstructed_image = ag.util.inversion.mapped_reconstructed_data_from( mapping_matrix=fit.inversion.mapper.mapping_matrix, reconstruction=fit.inversion.reconstruction, ) assert ( fit.inversion.mapped_reconstructed_image.slim == mapped_reconstructed_image ).all() class TestCompareToManualProfilesAndInversion: def test___all_fit_quantities__no_hyper_methods(self, masked_interferometer_7): galaxy_light = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[galaxy_light, galaxy_pix]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) profile_visibilities = plane.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) assert profile_visibilities.slim == pytest.approx( fit.profile_visibilities.slim ) profile_subtracted_visibilities = ( masked_interferometer_7.visibilities - profile_visibilities ) assert profile_subtracted_visibilities.slim == pytest.approx( fit.profile_subtracted_visibilities.slim ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( visibilities=profile_subtracted_visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, mapper=mapper, regularization=reg, ) model_visibilities = ( profile_visibilities + inversion.mapped_reconstructed_visibilities ) assert model_visibilities.slim == pytest.approx(fit.model_visibilities.slim) residual_map = ag.util.fit.residual_map_from( data=masked_interferometer_7.visibilities, model_data=model_visibilities ) assert residual_map.slim == pytest.approx(fit.residual_map.slim) normalized_residual_map = ag.util.fit.normalized_residual_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert normalized_residual_map.slim == pytest.approx( fit.normalized_residual_map.slim ) chi_squared_map = ag.util.fit.chi_squared_map_complex_from( residual_map=residual_map, noise_map=masked_interferometer_7.noise_map ) assert chi_squared_map.slim == pytest.approx(fit.chi_squared_map.slim) chi_squared = ag.util.fit.chi_squared_complex_from( chi_squared_map=chi_squared_map ) noise_normalization = ag.util.fit.noise_normalization_complex_from( noise_map=masked_interferometer_7.noise_map ) log_likelihood = ag.util.fit.log_likelihood_from( chi_squared=chi_squared, noise_normalization=noise_normalization ) assert log_likelihood == pytest.approx(fit.log_likelihood, 1e-4) log_likelihood_with_regularization = ag.util.fit.log_likelihood_with_regularization_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, noise_normalization=noise_normalization, ) assert log_likelihood_with_regularization == pytest.approx( fit.log_likelihood_with_regularization, 1e-4 ) log_evidence = ag.util.fit.log_evidence_from( chi_squared=chi_squared, regularization_term=inversion.regularization_term, log_curvature_regularization_term=inversion.log_det_curvature_reg_matrix_term, log_regularization_term=inversion.log_det_regularization_matrix_term, noise_normalization=noise_normalization, ) assert log_evidence == fit.log_evidence assert log_evidence == fit.figure_of_merit mapped_reconstructed_image = ag.util.inversion.mapped_reconstructed_data_from( mapping_matrix=fit.inversion.mapper.mapping_matrix, reconstruction=fit.inversion.reconstruction, ) assert ( fit.inversion.mapped_reconstructed_image.slim == mapped_reconstructed_image ).all() def test___fit_galaxy_model_visibilities_dict__has_image_and_inversion_mapped_reconstructed_image( self, masked_interferometer_7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) g1 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=2.0) ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, galaxy_pix]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) g0_visibilities = g0.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) g1_visibilities = g1.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) profile_visibilities = g0_visibilities + g1_visibilities profile_subtracted_visibilities = ( masked_interferometer_7.visibilities - profile_visibilities ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( visibilities=profile_subtracted_visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, mapper=mapper, regularization=reg, ) g0_image = g0.image_from_grid(grid=masked_interferometer_7.grid) g1_image = g1.image_from_grid(grid=masked_interferometer_7.grid) assert fit.galaxy_model_image_dict[g0].slim == pytest.approx( g0_image.slim, 1.0e-4 ) assert fit.galaxy_model_image_dict[g1].slim == pytest.approx( g1_image.slim, 1.0e-4 ) assert fit.galaxy_model_image_dict[galaxy_pix].slim == pytest.approx( inversion.mapped_reconstructed_image.slim, 1.0e-4 ) def test___fit_galaxy_model_visibilities_dict__has_profile_visibilitiess_and_inversion_mapped_reconstructed_visibilities( self, masked_interferometer_7 ): g0 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) g1 = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=2.0) ) g2 = ag.Galaxy(redshift=0.5) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[g0, g1, g2, galaxy_pix]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane ) g0_visibilities = g0.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) g1_visibilities = g1.profile_visibilities_from_grid_and_transformer( grid=masked_interferometer_7.grid, transformer=masked_interferometer_7.transformer, ) profile_visibilities = g0_visibilities + g1_visibilities profile_subtracted_visibilities = ( masked_interferometer_7.visibilities - profile_visibilities ) mapper = pix.mapper_from_grid_and_sparse_grid( grid=masked_interferometer_7.grid, settings=ag.SettingsPixelization(use_border=False), ) inversion = inversions.InversionInterferometerMatrix.from_data_mapper_and_regularization( visibilities=profile_subtracted_visibilities, noise_map=masked_interferometer_7.noise_map, transformer=masked_interferometer_7.transformer, mapper=mapper, regularization=reg, ) assert ( fit.galaxy_model_visibilities_dict[g2] == 0.0 + 0.0j * np.zeros((7,)) ).all() assert fit.galaxy_model_visibilities_dict[g0].slim == pytest.approx( g0_visibilities.slim, 1.0e-4 ) assert fit.galaxy_model_visibilities_dict[g1].slim == pytest.approx( g1_visibilities.slim, 1.0e-4 ) assert fit.galaxy_model_visibilities_dict[galaxy_pix].slim == pytest.approx( inversion.mapped_reconstructed_visibilities.slim, 1.0e-4 ) assert fit.model_visibilities.slim == pytest.approx( fit.galaxy_model_visibilities_dict[g0].slim + fit.galaxy_model_visibilities_dict[g1].slim + inversion.mapped_reconstructed_visibilities.slim, 1.0e-4, ) def test___all_fit_quantities__hyper_background_noise( self, masked_interferometer_7 ): hyper_background_noise = ag.hyper_data.HyperBackgroundNoise(noise_scale=1.0) hyper_noise_map = hyper_background_noise.hyper_noise_map_from_complex_noise_map( noise_map=masked_interferometer_7.noise_map ) galaxy_light = ag.Galaxy( redshift=0.5, light_profile=ag.lp.EllipticalSersic(intensity=1.0) ) pix = ag.pix.Rectangular(shape=(3, 3)) reg = ag.reg.Constant(coefficient=1.0) galaxy_pix = ag.Galaxy(redshift=1.0, pixelization=pix, regularization=reg) plane = ag.Plane(redshift=0.75, galaxies=[galaxy_light, galaxy_pix]) fit = ag.FitInterferometer( masked_interferometer=masked_interferometer_7, plane=plane, hyper_background_noise=hyper_background_noise, ) assert hyper_noise_map.slim == pytest.approx( fit.inversion.noise_map, 1.0e-4 ) assert hyper_noise_map.slim == pytest.approx(fit.noise_map.slim)
0.799677
0.590484
import numpy as np import networkx as nx from networkx.utils import np_random_state def _process_params(G, center): if not isinstance(G, nx.Graph): empty_graph = nx.Graph() empty_graph.add_nodes_from(G) G = empty_graph center = np.zeros(2) if center is None else np.asarray(center) return G, center def spring_layout( G, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, weight="weight", scale=1, center=None, ): """Position nodes using Fruchterman-Reingold force-directed algorithm. The algorithm simulates a force-directed representation of the network treating edges as springs holding nodes close, while treating nodes as repelling objects, sometimes called an anti-gravity force. Simulation continues until the positions are close to an equilibrium. There are some hard-coded values: minimal distance between nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away. During the simulation, `k` helps determine the distance between nodes, though `scale` and `center` determine the size and place after rescaling occurs at the end of the simulation. Fixing some nodes doesn't allow them to move in the simulation. It also turns off the rescaling feature at the simulation's end. In addition, setting `scale` to `None` turns off rescaling. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. k : float (default=None) Optimal distance between nodes. If None the distance is set to 1/sqrt(n) where n is the number of nodes. Increase this value to move nodes farther apart. pos : dict or None optional (default=None) Initial positions for nodes as a dictionary with node as keys and values as a coordinate list or tuple. If None, then use random initial positions. fixed : list or None optional (default=None) Nodes to keep fixed at initial position. Nodes not in ``G.nodes`` are ignored. ValueError raised if `fixed` specified and `pos` not. iterations : int optional (default=50) Maximum number of iterations taken threshold: float optional (default = 1e-4) Threshold for relative error in node position changes. The iteration stops if the error is below this threshold. weight : string or None optional (default='weight') The edge attribute that holds the numerical value used for the edge weight. Larger means a stronger attractive force. If None, then all edge weights are 1. scale : number or None (default: 1) Scale factor for positions. Not used unless `fixed is None`. If scale is None, no rescaling is performed. center : array-like or None Coordinate pair around which to center the layout. Not used unless `fixed is None`. Returns ------- pos : dict A dictionary of positions keyed by node Examples -------- >>> G = nx.path_graph(4) >>> pos = nx.spring_layout(G) # The same using longer but equivalent function name >>> pos = nx.fruchterman_reingold_layout(G) """ G, center = _process_params(G, center) if fixed is not None: if pos is None: raise ValueError("nodes are fixed without positions given") for node in fixed: if node not in pos: raise ValueError("nodes are fixed without positions given") nfixed = {node: i for i, node in enumerate(G)} fixed = np.asarray([nfixed[node] for node in fixed if node in nfixed]) if pos is not None: # Determine size of existing domain to adjust initial positions dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup) if dom_size == 0: dom_size = 1 pos_arr = seed.rand(len(G), 2) * dom_size + center for i, n in enumerate(G): if n in pos: pos_arr[i] = np.asarray(pos[n]) else: pos_arr = None dom_size = 1 if len(G) == 0: return {} if len(G) == 1: return {nx.utils.arbitrary_element(G.nodes()): center} A = nx.to_numpy_array(G, weight=weight) # adjacency matrix, weighted if edges have 'weight' attribute if k is None and fixed is not None: # We must adjust k by domain size for layouts not near 1x1 nnodes, _ = A.shape k = dom_size / np.sqrt(nnodes) pos = _fruchterman_reingold( A, k, pos_arr, fixed, iterations, threshold, 2, 4 ) if fixed is None and scale is not None: pos = rescale_layout(pos, scale=scale) + center pos = dict(zip(G, pos)) return pos def rescale_layout(pos, scale=1): """Returns scaled position array to (-scale, scale) in all axes. The function acts on NumPy arrays which hold position information. Each position is one row of the array. The dimension of the space equals the number of columns. Each coordinate in one column. To rescale, the mean (center) is subtracted from each axis separately. Then all values are scaled so that the largest magnitude value from all axes equals `scale` (thus, the aspect ratio is preserved). The resulting NumPy Array is returned (order of rows unchanged). Parameters ---------- pos : numpy array positions to be scaled. Each row is a position. scale : number (default: 1) The size of the resulting extent in all directions. Returns ------- pos : numpy array scaled positions. Each row is a position. See Also -------- rescale_layout_dict """ # Find max length over all dimensions lim = 0 # max coordinate for all axes for i in range(pos.shape[1]): pos[:, i] -= pos[:, i].mean() lim = max(abs(pos[:, i]).max(), lim) # rescale to (-scale, scale) in all directions, preserves aspect if lim > 0: for i in range(pos.shape[1]): pos[:,i] *= scale / lim return pos # Position nodes in adjacency matrix A using Fruchterman-Reingold # Entry point for NetworkX graph is fruchterman_reingold_layout() @np_random_state(7) def _fruchterman_reingold( A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None ): assert isinstance(A, np.ndarray), "fruchterman_reingold() takes an adjacency matrix as input" nnodes, _ = A.shape # random initial positions; make sure positions are of same type as matrix pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype) if pos is None else pos.astype(A.dtype) # optimal distance between nodes if k is None: k = np.sqrt(1.0 / nnodes) # the initial "temperature" is about .1 of domain area (=1x1) <=> the largest step allowed in the dynamics. # This is needed in case the fixed positions force our domain to be much bigger than 1x1 t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1 # simple cooling scheme. # linearly step down by dt on each iteration so last iteration is size dt. dt = t / float(iterations + 1) delta = np.zeros((pos.shape[0], pos.shape[0], pos.shape[1]), dtype=A.dtype) for iteration in range(iterations): # matrix of difference between points delta = pos[:, np.newaxis, :] - pos[np.newaxis, :, :] # distance between points distance = np.linalg.norm(delta, axis=-1) # enforce minimum distance of 0.01 np.clip(distance, 0.01, None, out=distance) # displacement "force" displacement = np.einsum( "ijk,ij->ik", delta, (k * k / distance ** 2 - A * distance / k) ) # update positions length = np.linalg.norm(displacement, axis=-1) length = np.where(length < 0.01, 0.1, length) delta_pos = np.einsum("ij,i->ij", displacement, t / length) if fixed is not None: # don't change positions of fixed nodes delta_pos[fixed] = 0.0 pos += delta_pos # cool temperature t -= dt err = np.linalg.norm(delta_pos) / nnodes if err < threshold: break return pos class ForceLayout(): def __init__(self, graph, k = None, pos = None, fixed = None): assert isinstance(graph, nx.classes.graph.Graph) self.graph = graph self.nv = graph.number_of_nodes() self.fixed = fixed ## Adjacency matrix, positions, and difference, preallocated self._A = nx.to_numpy_array(self.graph, weight='weight') # adjacency matrix self._pos = np.asarray(np.random.uniform(size=(self.nv, 2)), dtype=self._A.dtype) if pos is None else pos.astype(self._A.dtype) self._delta = np.zeros((self.nv, self.nv, 2), dtype=self._A.dtype) # # optimal distance between nodes self.k = np.sqrt(1.0 / self.nv) if k is None else k # the initial "temperature" is about .1 of domain area (=1x1) <=> the largest step allowed in the dynamics. # This is needed in case the fixed positions force our domain to be much bigger than 1x1 self.temp = max(max(self._pos.T[0]) - min(self._pos.T[0]), max(self._pos.T[1]) - min(self._pos.T[1])) * 0.1 # Linear cooling scheme -- decrease temp by dt on each iteration so last iteration is size dt. self.dt = self.temp / float(250) # Informational self.error = np.inf def step_force(self, n_iter: int = 1, threshold = "default"): if self.temp < 1e-6 or isinstance(threshold, str) and self.error < 1e-6: return(self._pos) else: for iteration in range(n_iter): # matrix of difference between points delta = self._pos[:, np.newaxis, :] - self._pos[np.newaxis, :, :] # n x n x d # distance between points distance = np.linalg.norm(delta, axis=-1) # n x n np.clip(distance, 0.001, None, out=distance) # enforce minimum distance of 0.01 # displacement "force" displacement = np.einsum( "ijk,ij->ik", delta, (self.k * self.k / distance ** 2 - self._A * distance / self.k) ) # update positions length = np.linalg.norm(displacement, axis=-1) length = np.where(length < 1.0, 0.5, length) delta_pos = np.einsum("ij,i->ij", displacement, self.temp / length) if self.fixed is not None: delta_pos[self.fixed] = 0.0 # don't change positions of fixed nodes self._pos += delta_pos # cool temperature self.temp -= self.dt self.error = np.linalg.norm(delta_pos) / self.nv
fr_nx.py
import numpy as np import networkx as nx from networkx.utils import np_random_state def _process_params(G, center): if not isinstance(G, nx.Graph): empty_graph = nx.Graph() empty_graph.add_nodes_from(G) G = empty_graph center = np.zeros(2) if center is None else np.asarray(center) return G, center def spring_layout( G, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, weight="weight", scale=1, center=None, ): """Position nodes using Fruchterman-Reingold force-directed algorithm. The algorithm simulates a force-directed representation of the network treating edges as springs holding nodes close, while treating nodes as repelling objects, sometimes called an anti-gravity force. Simulation continues until the positions are close to an equilibrium. There are some hard-coded values: minimal distance between nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away. During the simulation, `k` helps determine the distance between nodes, though `scale` and `center` determine the size and place after rescaling occurs at the end of the simulation. Fixing some nodes doesn't allow them to move in the simulation. It also turns off the rescaling feature at the simulation's end. In addition, setting `scale` to `None` turns off rescaling. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. k : float (default=None) Optimal distance between nodes. If None the distance is set to 1/sqrt(n) where n is the number of nodes. Increase this value to move nodes farther apart. pos : dict or None optional (default=None) Initial positions for nodes as a dictionary with node as keys and values as a coordinate list or tuple. If None, then use random initial positions. fixed : list or None optional (default=None) Nodes to keep fixed at initial position. Nodes not in ``G.nodes`` are ignored. ValueError raised if `fixed` specified and `pos` not. iterations : int optional (default=50) Maximum number of iterations taken threshold: float optional (default = 1e-4) Threshold for relative error in node position changes. The iteration stops if the error is below this threshold. weight : string or None optional (default='weight') The edge attribute that holds the numerical value used for the edge weight. Larger means a stronger attractive force. If None, then all edge weights are 1. scale : number or None (default: 1) Scale factor for positions. Not used unless `fixed is None`. If scale is None, no rescaling is performed. center : array-like or None Coordinate pair around which to center the layout. Not used unless `fixed is None`. Returns ------- pos : dict A dictionary of positions keyed by node Examples -------- >>> G = nx.path_graph(4) >>> pos = nx.spring_layout(G) # The same using longer but equivalent function name >>> pos = nx.fruchterman_reingold_layout(G) """ G, center = _process_params(G, center) if fixed is not None: if pos is None: raise ValueError("nodes are fixed without positions given") for node in fixed: if node not in pos: raise ValueError("nodes are fixed without positions given") nfixed = {node: i for i, node in enumerate(G)} fixed = np.asarray([nfixed[node] for node in fixed if node in nfixed]) if pos is not None: # Determine size of existing domain to adjust initial positions dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup) if dom_size == 0: dom_size = 1 pos_arr = seed.rand(len(G), 2) * dom_size + center for i, n in enumerate(G): if n in pos: pos_arr[i] = np.asarray(pos[n]) else: pos_arr = None dom_size = 1 if len(G) == 0: return {} if len(G) == 1: return {nx.utils.arbitrary_element(G.nodes()): center} A = nx.to_numpy_array(G, weight=weight) # adjacency matrix, weighted if edges have 'weight' attribute if k is None and fixed is not None: # We must adjust k by domain size for layouts not near 1x1 nnodes, _ = A.shape k = dom_size / np.sqrt(nnodes) pos = _fruchterman_reingold( A, k, pos_arr, fixed, iterations, threshold, 2, 4 ) if fixed is None and scale is not None: pos = rescale_layout(pos, scale=scale) + center pos = dict(zip(G, pos)) return pos def rescale_layout(pos, scale=1): """Returns scaled position array to (-scale, scale) in all axes. The function acts on NumPy arrays which hold position information. Each position is one row of the array. The dimension of the space equals the number of columns. Each coordinate in one column. To rescale, the mean (center) is subtracted from each axis separately. Then all values are scaled so that the largest magnitude value from all axes equals `scale` (thus, the aspect ratio is preserved). The resulting NumPy Array is returned (order of rows unchanged). Parameters ---------- pos : numpy array positions to be scaled. Each row is a position. scale : number (default: 1) The size of the resulting extent in all directions. Returns ------- pos : numpy array scaled positions. Each row is a position. See Also -------- rescale_layout_dict """ # Find max length over all dimensions lim = 0 # max coordinate for all axes for i in range(pos.shape[1]): pos[:, i] -= pos[:, i].mean() lim = max(abs(pos[:, i]).max(), lim) # rescale to (-scale, scale) in all directions, preserves aspect if lim > 0: for i in range(pos.shape[1]): pos[:,i] *= scale / lim return pos # Position nodes in adjacency matrix A using Fruchterman-Reingold # Entry point for NetworkX graph is fruchterman_reingold_layout() @np_random_state(7) def _fruchterman_reingold( A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None ): assert isinstance(A, np.ndarray), "fruchterman_reingold() takes an adjacency matrix as input" nnodes, _ = A.shape # random initial positions; make sure positions are of same type as matrix pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype) if pos is None else pos.astype(A.dtype) # optimal distance between nodes if k is None: k = np.sqrt(1.0 / nnodes) # the initial "temperature" is about .1 of domain area (=1x1) <=> the largest step allowed in the dynamics. # This is needed in case the fixed positions force our domain to be much bigger than 1x1 t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1 # simple cooling scheme. # linearly step down by dt on each iteration so last iteration is size dt. dt = t / float(iterations + 1) delta = np.zeros((pos.shape[0], pos.shape[0], pos.shape[1]), dtype=A.dtype) for iteration in range(iterations): # matrix of difference between points delta = pos[:, np.newaxis, :] - pos[np.newaxis, :, :] # distance between points distance = np.linalg.norm(delta, axis=-1) # enforce minimum distance of 0.01 np.clip(distance, 0.01, None, out=distance) # displacement "force" displacement = np.einsum( "ijk,ij->ik", delta, (k * k / distance ** 2 - A * distance / k) ) # update positions length = np.linalg.norm(displacement, axis=-1) length = np.where(length < 0.01, 0.1, length) delta_pos = np.einsum("ij,i->ij", displacement, t / length) if fixed is not None: # don't change positions of fixed nodes delta_pos[fixed] = 0.0 pos += delta_pos # cool temperature t -= dt err = np.linalg.norm(delta_pos) / nnodes if err < threshold: break return pos class ForceLayout(): def __init__(self, graph, k = None, pos = None, fixed = None): assert isinstance(graph, nx.classes.graph.Graph) self.graph = graph self.nv = graph.number_of_nodes() self.fixed = fixed ## Adjacency matrix, positions, and difference, preallocated self._A = nx.to_numpy_array(self.graph, weight='weight') # adjacency matrix self._pos = np.asarray(np.random.uniform(size=(self.nv, 2)), dtype=self._A.dtype) if pos is None else pos.astype(self._A.dtype) self._delta = np.zeros((self.nv, self.nv, 2), dtype=self._A.dtype) # # optimal distance between nodes self.k = np.sqrt(1.0 / self.nv) if k is None else k # the initial "temperature" is about .1 of domain area (=1x1) <=> the largest step allowed in the dynamics. # This is needed in case the fixed positions force our domain to be much bigger than 1x1 self.temp = max(max(self._pos.T[0]) - min(self._pos.T[0]), max(self._pos.T[1]) - min(self._pos.T[1])) * 0.1 # Linear cooling scheme -- decrease temp by dt on each iteration so last iteration is size dt. self.dt = self.temp / float(250) # Informational self.error = np.inf def step_force(self, n_iter: int = 1, threshold = "default"): if self.temp < 1e-6 or isinstance(threshold, str) and self.error < 1e-6: return(self._pos) else: for iteration in range(n_iter): # matrix of difference between points delta = self._pos[:, np.newaxis, :] - self._pos[np.newaxis, :, :] # n x n x d # distance between points distance = np.linalg.norm(delta, axis=-1) # n x n np.clip(distance, 0.001, None, out=distance) # enforce minimum distance of 0.01 # displacement "force" displacement = np.einsum( "ijk,ij->ik", delta, (self.k * self.k / distance ** 2 - self._A * distance / self.k) ) # update positions length = np.linalg.norm(displacement, axis=-1) length = np.where(length < 1.0, 0.5, length) delta_pos = np.einsum("ij,i->ij", displacement, self.temp / length) if self.fixed is not None: delta_pos[self.fixed] = 0.0 # don't change positions of fixed nodes self._pos += delta_pos # cool temperature self.temp -= self.dt self.error = np.linalg.norm(delta_pos) / self.nv
0.79542
0.676112
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs __all__ = [ 'GetVirtualMachineScaleSetResult', 'AwaitableGetVirtualMachineScaleSetResult', 'get_virtual_machine_scale_set', ] @pulumi.output_type class GetVirtualMachineScaleSetResult: """ Describes a Virtual Machine Scale Set. """ def __init__(__self__, identity=None, location=None, name=None, over_provision=None, provisioning_state=None, sku=None, tags=None, type=None, upgrade_policy=None, virtual_machine_profile=None): if identity and not isinstance(identity, dict): raise TypeError("Expected argument 'identity' to be a dict") pulumi.set(__self__, "identity", identity) if location and not isinstance(location, str): raise TypeError("Expected argument 'location' to be a str") pulumi.set(__self__, "location", location) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if over_provision and not isinstance(over_provision, bool): raise TypeError("Expected argument 'over_provision' to be a bool") pulumi.set(__self__, "over_provision", over_provision) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if sku and not isinstance(sku, dict): raise TypeError("Expected argument 'sku' to be a dict") pulumi.set(__self__, "sku", sku) if tags and not isinstance(tags, dict): raise TypeError("Expected argument 'tags' to be a dict") pulumi.set(__self__, "tags", tags) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) if upgrade_policy and not isinstance(upgrade_policy, dict): raise TypeError("Expected argument 'upgrade_policy' to be a dict") pulumi.set(__self__, "upgrade_policy", upgrade_policy) if virtual_machine_profile and not isinstance(virtual_machine_profile, dict): raise TypeError("Expected argument 'virtual_machine_profile' to be a dict") pulumi.set(__self__, "virtual_machine_profile", virtual_machine_profile) @property @pulumi.getter def identity(self) -> Optional['outputs.VirtualMachineScaleSetIdentityResponse']: """ The identity of the virtual machine scale set, if configured. """ return pulumi.get(self, "identity") @property @pulumi.getter def location(self) -> str: """ Resource location """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> str: """ Resource name """ return pulumi.get(self, "name") @property @pulumi.getter(name="overProvision") def over_provision(self) -> Optional[bool]: """ Specifies whether the Virtual Machine Scale Set should be overprovisioned. """ return pulumi.get(self, "over_provision") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state, which only appears in the response. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def sku(self) -> Optional['outputs.SkuResponse']: """ The virtual machine scale set sku. """ return pulumi.get(self, "sku") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> str: """ Resource type """ return pulumi.get(self, "type") @property @pulumi.getter(name="upgradePolicy") def upgrade_policy(self) -> Optional['outputs.UpgradePolicyResponse']: """ The upgrade policy. """ return pulumi.get(self, "upgrade_policy") @property @pulumi.getter(name="virtualMachineProfile") def virtual_machine_profile(self) -> Optional['outputs.VirtualMachineScaleSetVMProfileResponse']: """ The virtual machine profile. """ return pulumi.get(self, "virtual_machine_profile") class AwaitableGetVirtualMachineScaleSetResult(GetVirtualMachineScaleSetResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetVirtualMachineScaleSetResult( identity=self.identity, location=self.location, name=self.name, over_provision=self.over_provision, provisioning_state=self.provisioning_state, sku=self.sku, tags=self.tags, type=self.type, upgrade_policy=self.upgrade_policy, virtual_machine_profile=self.virtual_machine_profile) def get_virtual_machine_scale_set(resource_group_name: Optional[str] = None, vm_scale_set_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVirtualMachineScaleSetResult: """ Use this data source to access information about an existing resource. :param str resource_group_name: The name of the resource group. :param str vm_scale_set_name: The name of the VM scale set. """ __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['vmScaleSetName'] = vm_scale_set_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:compute/v20160330:getVirtualMachineScaleSet', __args__, opts=opts, typ=GetVirtualMachineScaleSetResult).value return AwaitableGetVirtualMachineScaleSetResult( identity=__ret__.identity, location=__ret__.location, name=__ret__.name, over_provision=__ret__.over_provision, provisioning_state=__ret__.provisioning_state, sku=__ret__.sku, tags=__ret__.tags, type=__ret__.type, upgrade_policy=__ret__.upgrade_policy, virtual_machine_profile=__ret__.virtual_machine_profile)
sdk/python/pulumi_azure_nextgen/compute/v20160330/get_virtual_machine_scale_set.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs __all__ = [ 'GetVirtualMachineScaleSetResult', 'AwaitableGetVirtualMachineScaleSetResult', 'get_virtual_machine_scale_set', ] @pulumi.output_type class GetVirtualMachineScaleSetResult: """ Describes a Virtual Machine Scale Set. """ def __init__(__self__, identity=None, location=None, name=None, over_provision=None, provisioning_state=None, sku=None, tags=None, type=None, upgrade_policy=None, virtual_machine_profile=None): if identity and not isinstance(identity, dict): raise TypeError("Expected argument 'identity' to be a dict") pulumi.set(__self__, "identity", identity) if location and not isinstance(location, str): raise TypeError("Expected argument 'location' to be a str") pulumi.set(__self__, "location", location) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if over_provision and not isinstance(over_provision, bool): raise TypeError("Expected argument 'over_provision' to be a bool") pulumi.set(__self__, "over_provision", over_provision) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if sku and not isinstance(sku, dict): raise TypeError("Expected argument 'sku' to be a dict") pulumi.set(__self__, "sku", sku) if tags and not isinstance(tags, dict): raise TypeError("Expected argument 'tags' to be a dict") pulumi.set(__self__, "tags", tags) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) if upgrade_policy and not isinstance(upgrade_policy, dict): raise TypeError("Expected argument 'upgrade_policy' to be a dict") pulumi.set(__self__, "upgrade_policy", upgrade_policy) if virtual_machine_profile and not isinstance(virtual_machine_profile, dict): raise TypeError("Expected argument 'virtual_machine_profile' to be a dict") pulumi.set(__self__, "virtual_machine_profile", virtual_machine_profile) @property @pulumi.getter def identity(self) -> Optional['outputs.VirtualMachineScaleSetIdentityResponse']: """ The identity of the virtual machine scale set, if configured. """ return pulumi.get(self, "identity") @property @pulumi.getter def location(self) -> str: """ Resource location """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> str: """ Resource name """ return pulumi.get(self, "name") @property @pulumi.getter(name="overProvision") def over_provision(self) -> Optional[bool]: """ Specifies whether the Virtual Machine Scale Set should be overprovisioned. """ return pulumi.get(self, "over_provision") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state, which only appears in the response. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def sku(self) -> Optional['outputs.SkuResponse']: """ The virtual machine scale set sku. """ return pulumi.get(self, "sku") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> str: """ Resource type """ return pulumi.get(self, "type") @property @pulumi.getter(name="upgradePolicy") def upgrade_policy(self) -> Optional['outputs.UpgradePolicyResponse']: """ The upgrade policy. """ return pulumi.get(self, "upgrade_policy") @property @pulumi.getter(name="virtualMachineProfile") def virtual_machine_profile(self) -> Optional['outputs.VirtualMachineScaleSetVMProfileResponse']: """ The virtual machine profile. """ return pulumi.get(self, "virtual_machine_profile") class AwaitableGetVirtualMachineScaleSetResult(GetVirtualMachineScaleSetResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetVirtualMachineScaleSetResult( identity=self.identity, location=self.location, name=self.name, over_provision=self.over_provision, provisioning_state=self.provisioning_state, sku=self.sku, tags=self.tags, type=self.type, upgrade_policy=self.upgrade_policy, virtual_machine_profile=self.virtual_machine_profile) def get_virtual_machine_scale_set(resource_group_name: Optional[str] = None, vm_scale_set_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVirtualMachineScaleSetResult: """ Use this data source to access information about an existing resource. :param str resource_group_name: The name of the resource group. :param str vm_scale_set_name: The name of the VM scale set. """ __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['vmScaleSetName'] = vm_scale_set_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:compute/v20160330:getVirtualMachineScaleSet', __args__, opts=opts, typ=GetVirtualMachineScaleSetResult).value return AwaitableGetVirtualMachineScaleSetResult( identity=__ret__.identity, location=__ret__.location, name=__ret__.name, over_provision=__ret__.over_provision, provisioning_state=__ret__.provisioning_state, sku=__ret__.sku, tags=__ret__.tags, type=__ret__.type, upgrade_policy=__ret__.upgrade_policy, virtual_machine_profile=__ret__.virtual_machine_profile)
0.833155
0.074467
from tkinter import ttk from tkinter import filedialog from tkinter import messagebox import tkinter as tk from main import main, conversion import math import sys from onefile import * import os print (os.getcwd()) def center_window(win, width=300, height=200): # get screen width and height screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() # calculate position x and y coordinates x = (screen_width/2) - (width/2) y = (screen_height/2) - (height/2) win.geometry('%dx%d+%d+%d' % (width, height, x, y)) def selectRes(): root.withdraw() def convertionStart(): res_win.withdraw() conversion(res_r.get()) root.deiconify() center_window(root, 270, 120) messagebox.showinfo(title='success', message='Conversion is Done!') def selectPack(): global pack pack = filedialog.askopenfilename(initialdir = "./",title = "Select Pack",filetypes = (("resource pack","*.zip"),("all files","*.*"))) if(pack): root.withdraw() convert = main(pack[:-4]) if(convert == -1): print ("this pack is already compatible with 1.13") root.deiconify() center_window(root, 270, 120) messagebox.showwarning(title='warning', message="This pack is already compatible with 1.13, please select other!") elif(convert == 0): print ("please set it manually") res_win.deiconify() center_window(res_win, 270, 80) messagebox.showwarning(title='warning', message="Fail to detect the pack's resolution, please set it manually!") else: print ("next one?") root.deiconify() center_window(root, 270, 120) messagebox.showinfo(title='success', message='Conversion is Done!') return False else: print ('select pack to start conversion') def show_values(value=None): slider_label['text'] = text='resolution: '+ str(int(16 * math.pow(2, res_r.get()-1))) + 'X' #print (res_r.get()) root = tk.Tk() root.title("Resource Pack Converter") #root.geometry('500x300+500+200') root.iconbitmap(resource_path('favicon.ico')) root.resizable(width=False, height=False) center_window(root, 270, 120) btn_select = tk.Button( root, text='Select Pack', width=50, height=50, command=selectPack ) btn_select.pack() res_win = tk.Toplevel(root) res_win.title("Set Resolution") res_win.iconbitmap(resource_path('favicon.ico')) res_win.resizable(width=False, height=False) center_window(res_win, 270, 80) ''' resolution ratio set''' res_r = tk.IntVar() res_r.set(1) slider_res = tk.PanedWindow(res_win) slider_res.pack(fill = tk.BOTH, expand = 1) slider_label = tk.Label(res_win, text='resolution: 16X') slider_scale = tk.Scale( res_win, from_=0, to=6, orient=tk.HORIZONTAL, variable = res_r, command=show_values ) slider_res.add(slider_label) slider_res.add(slider_scale) btn_start = tk.Button( res_win, text='Confirm', width=60, command=convertionStart ) btn_start.pack() res_win.withdraw() root.mainloop()
src/convert_tool.py
from tkinter import ttk from tkinter import filedialog from tkinter import messagebox import tkinter as tk from main import main, conversion import math import sys from onefile import * import os print (os.getcwd()) def center_window(win, width=300, height=200): # get screen width and height screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() # calculate position x and y coordinates x = (screen_width/2) - (width/2) y = (screen_height/2) - (height/2) win.geometry('%dx%d+%d+%d' % (width, height, x, y)) def selectRes(): root.withdraw() def convertionStart(): res_win.withdraw() conversion(res_r.get()) root.deiconify() center_window(root, 270, 120) messagebox.showinfo(title='success', message='Conversion is Done!') def selectPack(): global pack pack = filedialog.askopenfilename(initialdir = "./",title = "Select Pack",filetypes = (("resource pack","*.zip"),("all files","*.*"))) if(pack): root.withdraw() convert = main(pack[:-4]) if(convert == -1): print ("this pack is already compatible with 1.13") root.deiconify() center_window(root, 270, 120) messagebox.showwarning(title='warning', message="This pack is already compatible with 1.13, please select other!") elif(convert == 0): print ("please set it manually") res_win.deiconify() center_window(res_win, 270, 80) messagebox.showwarning(title='warning', message="Fail to detect the pack's resolution, please set it manually!") else: print ("next one?") root.deiconify() center_window(root, 270, 120) messagebox.showinfo(title='success', message='Conversion is Done!') return False else: print ('select pack to start conversion') def show_values(value=None): slider_label['text'] = text='resolution: '+ str(int(16 * math.pow(2, res_r.get()-1))) + 'X' #print (res_r.get()) root = tk.Tk() root.title("Resource Pack Converter") #root.geometry('500x300+500+200') root.iconbitmap(resource_path('favicon.ico')) root.resizable(width=False, height=False) center_window(root, 270, 120) btn_select = tk.Button( root, text='Select Pack', width=50, height=50, command=selectPack ) btn_select.pack() res_win = tk.Toplevel(root) res_win.title("Set Resolution") res_win.iconbitmap(resource_path('favicon.ico')) res_win.resizable(width=False, height=False) center_window(res_win, 270, 80) ''' resolution ratio set''' res_r = tk.IntVar() res_r.set(1) slider_res = tk.PanedWindow(res_win) slider_res.pack(fill = tk.BOTH, expand = 1) slider_label = tk.Label(res_win, text='resolution: 16X') slider_scale = tk.Scale( res_win, from_=0, to=6, orient=tk.HORIZONTAL, variable = res_r, command=show_values ) slider_res.add(slider_label) slider_res.add(slider_scale) btn_start = tk.Button( res_win, text='Confirm', width=60, command=convertionStart ) btn_start.pack() res_win.withdraw() root.mainloop()
0.181118
0.088978
import logging from base64 import b64decode from pyramid.view import view_config from pyramid.security import NO_PERMISSION_REQUIRED from pyramid.security import authenticated_userid from pyramid.security import Authenticated from pyramid.httpexceptions import HTTPFound from six.moves.urllib.parse import urlparse from six.moves.urllib.parse import parse_qsl from six.moves.urllib.parse import ParseResult from six.moves.urllib.parse import urlencode from cryptography.hazmat.primitives.kdf.scrypt import Scrypt from cryptography.exceptions import InvalidKey from .models import DBSession as db from .models import Oauth2Token from .models import Oauth2Code from .models import Oauth2RedirectUri from .models import Oauth2Client from .models import backend from .errors import InvalidToken from .errors import InvalidClient from .errors import InvalidRequest from .errors import UnsupportedGrantType from .util import oauth2_settings from .util import getClientCredentials from .interfaces import IAuthCheck from .jsonerrors import HTTPBadRequest from .jsonerrors import HTTPUnauthorized from .jsonerrors import HTTPMethodNotAllowed def require_https(handler): """ This check should be taken care of via the authorization policy, but in case someone has configured a different policy, check again. HTTPS is required for all Oauth2 authenticated requests to ensure the security of client credentials and authorization tokens. """ def wrapped(request): if (request.scheme != 'https' and oauth2_settings('require_ssl', default=True)): log.info('rejected request due to unsupported scheme: %s' % request.scheme) return HTTPBadRequest(InvalidRequest( error_description='Oauth2 requires all requests' ' to be made via HTTPS.')) return handler(request) return wrapped log = logging.getLogger('pyramid_oauth2_provider.views') @view_config(route_name='oauth2_provider_authorize', renderer='json', permission=Authenticated) @require_https def oauth2_authorize(request): """ * In the case of a 'code' authorize request a GET or POST is made with the following structure. GET /authorize?response_type=code&client_id=aoiuer HTTP/1.1 Host: server.example.com POST /authorize HTTP/1.1 Host: server.example.com Content-Type: application/x-www-form-urlencoded response_type=code&client_id=aoiuer The response_type and client_id are required parameters. A redirect_uri and state parameters may also be supplied. The redirect_uri will be validated against the URI's registered for the client. The state is an opaque value that is simply passed through for security on the client's end. The response to a 'code' request will be a redirect to a registered URI with the authorization code and optional state values as query parameters. HTTP/1.1 302 Found Location: https://client.example.com/cb?code=AverTaer&state=efg """ request.client_id = request.params.get('client_id') client = db.query(Oauth2Client).filter_by( client_id=request.client_id).first() if not client: log.info('received invalid client credentials') return HTTPBadRequest(InvalidRequest( error_description='Invalid client credentials')) redirect_uri = request.params.get('redirect_uri') redirection_uri = None if len(client.redirect_uris) == 1 and ( not redirect_uri or redirect_uri == client.redirect_uris[0]): redirection_uri = client.redirect_uris[0] elif len(client.redirect_uris) > 0: redirection_uri = db.query(Oauth2RedirectUri)\ .filter_by(client_id=client.id, uri=redirect_uri).first() if redirection_uri is None: return HTTPBadRequest(InvalidRequest( error_description='Redirection URI validation failed')) resp = None response_type = request.params.get('response_type') state = request.params.get('state') if 'code' == response_type: resp = handle_authcode(request, client, redirection_uri, state) elif 'token' == response_type: resp = handle_implicit(request, client, redirection_uri, state) else: log.info('received invalid response_type %s') resp = HTTPBadRequest(InvalidRequest(error_description='Oauth2 unknown ' 'response_type not supported')) return resp def handle_authcode(request, client, redirection_uri, state=None): parts = urlparse(redirection_uri.uri) qparams = dict(parse_qsl(parts.query)) user_id = authenticated_userid(request) auth_code = Oauth2Code(client, user_id) db.add(auth_code) db.flush() qparams['code'] = auth_code.authcode if state: qparams['state'] = state parts = ParseResult( parts.scheme, parts.netloc, parts.path, parts.params, urlencode(qparams), '') return HTTPFound(location=parts.geturl()) def handle_implicit(request, client, redirection_uri, state=None): return HTTPBadRequest(InvalidRequest(error_description='Oauth2 ' 'response_type "implicit" not supported')) @view_config(route_name='oauth2_provider_token', renderer='json', permission=NO_PERMISSION_REQUIRED) @require_https def oauth2_token(request): """ * In the case of an incoming authentication request a POST is made with the following structure. POST /token HTTP/1.1 Host: server.example.com Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Content-Type: application/x-www-form-urlencoded grant_type=password&username=johndoe&password=<PASSWORD> The basic auth header contains the client_id:client_secret base64 encoded for client authentication. The username and password are form encoded as part of the body. This request *must* be made over https. The response to this request will be, assuming no error: HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"<KEY>", "token_type":"bearer", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKW", "user_id":1234, } * In the case of a token refresh request a POST with the following structure is required: POST /token HTTP/1.1 Host: server.example.com Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Content-Type: application/x-www-form-urlencoded grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKW&user_id=1234 The response will be the same as above with a new access_token and refresh_token. """ # Make sure this is a POST. if request.method != 'POST': log.info('rejected request due to invalid method: %s' % request.method) return HTTPMethodNotAllowed( 'This endpoint only supports the POST method.') getClientCredentials(request) # Make sure we got a client_id and secret through the authorization # policy. Note that you should only get here if not using the Oauth2 # authorization policy or access was granted through the AuthTKt policy. if (not hasattr(request, 'client_id') or not hasattr(request, 'client_secret')): log.info('did not receive client credentials') return HTTPUnauthorized('Invalid client credentials') client = db.query(Oauth2Client).filter_by( client_id=request.client_id).first() # Again, the authorization policy should catch this, but check again. if not oauth2_settings('salt'): raise ValueError('oauth2_provider.salt configuration required.') salt = b64decode(oauth2_settings('salt').encode('utf-8')) kdf = Scrypt( salt=salt, length=64, n=2 ** 14, r=8, p=1, backend=backend ) try: client_secret = request.client_secret try: client_secret = bytes(client_secret, 'utf-8') except TypeError: client_secret = client_secret.encode('utf-8') kdf.verify(client_secret, client.client_secret) bad_secret = False except (AttributeError, InvalidKey): bad_secret = True if not client or bad_secret: log.info('received invalid client credentials') return HTTPBadRequest(InvalidRequest( error_description='Invalid client credentials')) # Check for supported grant type. This is a required field of the form # submission. resp = None grant_type = request.POST.get('grant_type') if grant_type == 'password': resp = handle_password(request, client) elif grant_type == 'refresh_token': resp = handle_refresh_token(request, client) else: log.info('invalid grant type: %s' % grant_type) return HTTPBadRequest(UnsupportedGrantType(error_description='Only ' 'password and refresh_token grant types are supported by this ' 'authentication server')) add_cache_headers(request) return resp def handle_password(request, client): if 'username' not in request.POST or 'password' not in request.POST: log.info('missing username or password') return HTTPBadRequest(InvalidRequest(error_description='Both username ' 'and password are required to obtain a password based grant.')) auth_check = request.registry.queryUtility(IAuthCheck) user_id = auth_check().checkauth(request.POST.get('username'), request.POST.get('password')) if not user_id: log.info('could not validate user credentials') return HTTPUnauthorized(InvalidClient(error_description='Username and ' 'password are invalid.')) auth_token = Oauth2Token(client, user_id) db.add(auth_token) db.flush() return auth_token.asJSON(token_type='bearer') def handle_refresh_token(request, client): if 'refresh_token' not in request.POST: log.info('refresh_token field missing') return HTTPBadRequest(InvalidRequest(error_description='refresh_token ' 'field required')) if 'user_id' not in request.POST: log.info('user_id field missing') return HTTPBadRequest(InvalidRequest(error_description='user_id ' 'field required')) auth_token = db.query(Oauth2Token).filter_by( refresh_token=request.POST.get('refresh_token')).first() if not auth_token: log.info('invalid refresh_token') return HTTPUnauthorized(InvalidToken(error_description='Provided ' 'refresh_token is not valid.')) if auth_token.client.client_id != client.client_id: log.info('invalid client_id') return HTTPBadRequest(InvalidClient(error_description='Client does ' 'not own this refresh_token.')) if str(auth_token.user_id) != request.POST.get('user_id'): log.info('invalid user_id') return HTTPBadRequest(InvalidClient(error_description='The given ' 'user_id does not match the given refresh_token.')) new_token = auth_token.refresh() db.add(new_token) db.flush() return new_token.asJSON(token_type='bearer') def add_cache_headers(request): """ The Oauth2 draft spec requires that all token endpoint traffic be marked as uncacheable. """ resp = request.response resp.headerlist.append(('Cache-Control', 'no-store')) resp.headerlist.append(('Pragma', 'no-cache')) return request
pyramid_oauth2_provider/views.py
import logging from base64 import b64decode from pyramid.view import view_config from pyramid.security import NO_PERMISSION_REQUIRED from pyramid.security import authenticated_userid from pyramid.security import Authenticated from pyramid.httpexceptions import HTTPFound from six.moves.urllib.parse import urlparse from six.moves.urllib.parse import parse_qsl from six.moves.urllib.parse import ParseResult from six.moves.urllib.parse import urlencode from cryptography.hazmat.primitives.kdf.scrypt import Scrypt from cryptography.exceptions import InvalidKey from .models import DBSession as db from .models import Oauth2Token from .models import Oauth2Code from .models import Oauth2RedirectUri from .models import Oauth2Client from .models import backend from .errors import InvalidToken from .errors import InvalidClient from .errors import InvalidRequest from .errors import UnsupportedGrantType from .util import oauth2_settings from .util import getClientCredentials from .interfaces import IAuthCheck from .jsonerrors import HTTPBadRequest from .jsonerrors import HTTPUnauthorized from .jsonerrors import HTTPMethodNotAllowed def require_https(handler): """ This check should be taken care of via the authorization policy, but in case someone has configured a different policy, check again. HTTPS is required for all Oauth2 authenticated requests to ensure the security of client credentials and authorization tokens. """ def wrapped(request): if (request.scheme != 'https' and oauth2_settings('require_ssl', default=True)): log.info('rejected request due to unsupported scheme: %s' % request.scheme) return HTTPBadRequest(InvalidRequest( error_description='Oauth2 requires all requests' ' to be made via HTTPS.')) return handler(request) return wrapped log = logging.getLogger('pyramid_oauth2_provider.views') @view_config(route_name='oauth2_provider_authorize', renderer='json', permission=Authenticated) @require_https def oauth2_authorize(request): """ * In the case of a 'code' authorize request a GET or POST is made with the following structure. GET /authorize?response_type=code&client_id=aoiuer HTTP/1.1 Host: server.example.com POST /authorize HTTP/1.1 Host: server.example.com Content-Type: application/x-www-form-urlencoded response_type=code&client_id=aoiuer The response_type and client_id are required parameters. A redirect_uri and state parameters may also be supplied. The redirect_uri will be validated against the URI's registered for the client. The state is an opaque value that is simply passed through for security on the client's end. The response to a 'code' request will be a redirect to a registered URI with the authorization code and optional state values as query parameters. HTTP/1.1 302 Found Location: https://client.example.com/cb?code=AverTaer&state=efg """ request.client_id = request.params.get('client_id') client = db.query(Oauth2Client).filter_by( client_id=request.client_id).first() if not client: log.info('received invalid client credentials') return HTTPBadRequest(InvalidRequest( error_description='Invalid client credentials')) redirect_uri = request.params.get('redirect_uri') redirection_uri = None if len(client.redirect_uris) == 1 and ( not redirect_uri or redirect_uri == client.redirect_uris[0]): redirection_uri = client.redirect_uris[0] elif len(client.redirect_uris) > 0: redirection_uri = db.query(Oauth2RedirectUri)\ .filter_by(client_id=client.id, uri=redirect_uri).first() if redirection_uri is None: return HTTPBadRequest(InvalidRequest( error_description='Redirection URI validation failed')) resp = None response_type = request.params.get('response_type') state = request.params.get('state') if 'code' == response_type: resp = handle_authcode(request, client, redirection_uri, state) elif 'token' == response_type: resp = handle_implicit(request, client, redirection_uri, state) else: log.info('received invalid response_type %s') resp = HTTPBadRequest(InvalidRequest(error_description='Oauth2 unknown ' 'response_type not supported')) return resp def handle_authcode(request, client, redirection_uri, state=None): parts = urlparse(redirection_uri.uri) qparams = dict(parse_qsl(parts.query)) user_id = authenticated_userid(request) auth_code = Oauth2Code(client, user_id) db.add(auth_code) db.flush() qparams['code'] = auth_code.authcode if state: qparams['state'] = state parts = ParseResult( parts.scheme, parts.netloc, parts.path, parts.params, urlencode(qparams), '') return HTTPFound(location=parts.geturl()) def handle_implicit(request, client, redirection_uri, state=None): return HTTPBadRequest(InvalidRequest(error_description='Oauth2 ' 'response_type "implicit" not supported')) @view_config(route_name='oauth2_provider_token', renderer='json', permission=NO_PERMISSION_REQUIRED) @require_https def oauth2_token(request): """ * In the case of an incoming authentication request a POST is made with the following structure. POST /token HTTP/1.1 Host: server.example.com Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Content-Type: application/x-www-form-urlencoded grant_type=password&username=johndoe&password=<PASSWORD> The basic auth header contains the client_id:client_secret base64 encoded for client authentication. The username and password are form encoded as part of the body. This request *must* be made over https. The response to this request will be, assuming no error: HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"<KEY>", "token_type":"bearer", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKW", "user_id":1234, } * In the case of a token refresh request a POST with the following structure is required: POST /token HTTP/1.1 Host: server.example.com Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Content-Type: application/x-www-form-urlencoded grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKW&user_id=1234 The response will be the same as above with a new access_token and refresh_token. """ # Make sure this is a POST. if request.method != 'POST': log.info('rejected request due to invalid method: %s' % request.method) return HTTPMethodNotAllowed( 'This endpoint only supports the POST method.') getClientCredentials(request) # Make sure we got a client_id and secret through the authorization # policy. Note that you should only get here if not using the Oauth2 # authorization policy or access was granted through the AuthTKt policy. if (not hasattr(request, 'client_id') or not hasattr(request, 'client_secret')): log.info('did not receive client credentials') return HTTPUnauthorized('Invalid client credentials') client = db.query(Oauth2Client).filter_by( client_id=request.client_id).first() # Again, the authorization policy should catch this, but check again. if not oauth2_settings('salt'): raise ValueError('oauth2_provider.salt configuration required.') salt = b64decode(oauth2_settings('salt').encode('utf-8')) kdf = Scrypt( salt=salt, length=64, n=2 ** 14, r=8, p=1, backend=backend ) try: client_secret = request.client_secret try: client_secret = bytes(client_secret, 'utf-8') except TypeError: client_secret = client_secret.encode('utf-8') kdf.verify(client_secret, client.client_secret) bad_secret = False except (AttributeError, InvalidKey): bad_secret = True if not client or bad_secret: log.info('received invalid client credentials') return HTTPBadRequest(InvalidRequest( error_description='Invalid client credentials')) # Check for supported grant type. This is a required field of the form # submission. resp = None grant_type = request.POST.get('grant_type') if grant_type == 'password': resp = handle_password(request, client) elif grant_type == 'refresh_token': resp = handle_refresh_token(request, client) else: log.info('invalid grant type: %s' % grant_type) return HTTPBadRequest(UnsupportedGrantType(error_description='Only ' 'password and refresh_token grant types are supported by this ' 'authentication server')) add_cache_headers(request) return resp def handle_password(request, client): if 'username' not in request.POST or 'password' not in request.POST: log.info('missing username or password') return HTTPBadRequest(InvalidRequest(error_description='Both username ' 'and password are required to obtain a password based grant.')) auth_check = request.registry.queryUtility(IAuthCheck) user_id = auth_check().checkauth(request.POST.get('username'), request.POST.get('password')) if not user_id: log.info('could not validate user credentials') return HTTPUnauthorized(InvalidClient(error_description='Username and ' 'password are invalid.')) auth_token = Oauth2Token(client, user_id) db.add(auth_token) db.flush() return auth_token.asJSON(token_type='bearer') def handle_refresh_token(request, client): if 'refresh_token' not in request.POST: log.info('refresh_token field missing') return HTTPBadRequest(InvalidRequest(error_description='refresh_token ' 'field required')) if 'user_id' not in request.POST: log.info('user_id field missing') return HTTPBadRequest(InvalidRequest(error_description='user_id ' 'field required')) auth_token = db.query(Oauth2Token).filter_by( refresh_token=request.POST.get('refresh_token')).first() if not auth_token: log.info('invalid refresh_token') return HTTPUnauthorized(InvalidToken(error_description='Provided ' 'refresh_token is not valid.')) if auth_token.client.client_id != client.client_id: log.info('invalid client_id') return HTTPBadRequest(InvalidClient(error_description='Client does ' 'not own this refresh_token.')) if str(auth_token.user_id) != request.POST.get('user_id'): log.info('invalid user_id') return HTTPBadRequest(InvalidClient(error_description='The given ' 'user_id does not match the given refresh_token.')) new_token = auth_token.refresh() db.add(new_token) db.flush() return new_token.asJSON(token_type='bearer') def add_cache_headers(request): """ The Oauth2 draft spec requires that all token endpoint traffic be marked as uncacheable. """ resp = request.response resp.headerlist.append(('Cache-Control', 'no-store')) resp.headerlist.append(('Pragma', 'no-cache')) return request
0.752649
0.118385
from chainer.training import extension from chainer.training import trigger as trigger_module class LossSplit(extension.Extension): def __init__(self, trigger=(10000, 'iteration'), postprocess=None, segmentation_loss_key='main/loss/mask', detection_loss_loc_key='main/loss/loc', detection_loss_conf_key='main/loss/conf', smooth_alpha=0.85, split_alpha=0.15): # conduct the action of loss division self._trigger = trigger_module.get_trigger(trigger) self.alpha = smooth_alpha self.split_alpha = split_alpha self._postprocess = postprocess self._segmentation_loss_key = segmentation_loss_key self._detection_loss_conf_key = detection_loss_conf_key self._detection_loss_loc_key = detection_loss_loc_key self._max_loss_seg = None self._current_loss_seg = None self._max_loss_det_loc = None self._current_loss_det_loc = None self._max_loss_det_conf = None self._current_loss_det_conf = None self._current_loss_split = None def __call__(self, trainer): observation = trainer.observation current_loss_seg = observation[self._segmentation_loss_key].data current_loss_det_conf = observation[self._detection_loss_conf_key].data current_loss_det_loc = observation[self._detection_loss_loc_key].data if self._max_loss_seg is None: self._max_loss_seg = current_loss_seg if self._max_loss_det_conf is None: self._max_loss_det_conf = current_loss_det_conf if self._max_loss_det_loc is None: self._max_loss_det_loc = current_loss_det_loc self._current_loss_seg = self.__smooth(self._current_loss_seg, current_loss_seg) self._current_loss_det_conf = self.__smooth(self._current_loss_det_conf, current_loss_det_conf) self._current_loss_det_loc = self.__smooth(self._current_loss_det_loc, current_loss_det_loc) if self._trigger(trainer): # compute the rewward and modify the loss split reward_det, reward_seg = self._reward() loss_split = self._loss_split(reward_det, reward_seg) self._current_loss_split = self.__smooth(self._current_loss_split, loss_split, self.split_alpha) trainer.updater._optimizers['main'].target.loss_split = self._current_loss_split self._max_loss_seg = current_loss_seg self._max_loss_det_conf = current_loss_det_conf self._max_loss_det_loc = current_loss_det_loc # trainer def _focal_function(self, p, r): ''' -(1-p)**r*np.log(p) :param p: :param r: :return: ''' import numpy as np return -(1 - p) ** r * np.log(p) def _reward(self): loss_det_current = self._current_loss_det_conf + self._current_loss_det_loc loss_det_max = self._max_loss_det_conf + self._max_loss_det_loc reward_det = (loss_det_max - loss_det_current) / loss_det_max reward_seg = (self._max_loss_seg - self._current_loss_seg) / self._max_loss_seg return reward_det, reward_seg def _loss_split(self, reward_det, reward_seg): import numpy as np return np.round(np.exp(reward_seg) / (np.exp(reward_seg) + np.exp(reward_det)), 4) def __smooth(self, previous, current, alpha=None): if alpha is None: alpha = self.alpha if previous is None: return current else: return previous * alpha + current * (1 - alpha)
multi_task/extensions/loss_split.py
from chainer.training import extension from chainer.training import trigger as trigger_module class LossSplit(extension.Extension): def __init__(self, trigger=(10000, 'iteration'), postprocess=None, segmentation_loss_key='main/loss/mask', detection_loss_loc_key='main/loss/loc', detection_loss_conf_key='main/loss/conf', smooth_alpha=0.85, split_alpha=0.15): # conduct the action of loss division self._trigger = trigger_module.get_trigger(trigger) self.alpha = smooth_alpha self.split_alpha = split_alpha self._postprocess = postprocess self._segmentation_loss_key = segmentation_loss_key self._detection_loss_conf_key = detection_loss_conf_key self._detection_loss_loc_key = detection_loss_loc_key self._max_loss_seg = None self._current_loss_seg = None self._max_loss_det_loc = None self._current_loss_det_loc = None self._max_loss_det_conf = None self._current_loss_det_conf = None self._current_loss_split = None def __call__(self, trainer): observation = trainer.observation current_loss_seg = observation[self._segmentation_loss_key].data current_loss_det_conf = observation[self._detection_loss_conf_key].data current_loss_det_loc = observation[self._detection_loss_loc_key].data if self._max_loss_seg is None: self._max_loss_seg = current_loss_seg if self._max_loss_det_conf is None: self._max_loss_det_conf = current_loss_det_conf if self._max_loss_det_loc is None: self._max_loss_det_loc = current_loss_det_loc self._current_loss_seg = self.__smooth(self._current_loss_seg, current_loss_seg) self._current_loss_det_conf = self.__smooth(self._current_loss_det_conf, current_loss_det_conf) self._current_loss_det_loc = self.__smooth(self._current_loss_det_loc, current_loss_det_loc) if self._trigger(trainer): # compute the rewward and modify the loss split reward_det, reward_seg = self._reward() loss_split = self._loss_split(reward_det, reward_seg) self._current_loss_split = self.__smooth(self._current_loss_split, loss_split, self.split_alpha) trainer.updater._optimizers['main'].target.loss_split = self._current_loss_split self._max_loss_seg = current_loss_seg self._max_loss_det_conf = current_loss_det_conf self._max_loss_det_loc = current_loss_det_loc # trainer def _focal_function(self, p, r): ''' -(1-p)**r*np.log(p) :param p: :param r: :return: ''' import numpy as np return -(1 - p) ** r * np.log(p) def _reward(self): loss_det_current = self._current_loss_det_conf + self._current_loss_det_loc loss_det_max = self._max_loss_det_conf + self._max_loss_det_loc reward_det = (loss_det_max - loss_det_current) / loss_det_max reward_seg = (self._max_loss_seg - self._current_loss_seg) / self._max_loss_seg return reward_det, reward_seg def _loss_split(self, reward_det, reward_seg): import numpy as np return np.round(np.exp(reward_seg) / (np.exp(reward_seg) + np.exp(reward_det)), 4) def __smooth(self, previous, current, alpha=None): if alpha is None: alpha = self.alpha if previous is None: return current else: return previous * alpha + current * (1 - alpha)
0.925048
0.133472
from __future__ import absolute_import from __future__ import unicode_literals from pyramid.view import view_config from schematizer.api.decorators import log_api from schematizer.api.decorators import transform_api_response from schematizer.api.exceptions import exceptions_v1 from schematizer.api.requests import requests_v1 from schematizer.api.responses import responses_v1 from schematizer.logic import doc_tool from schematizer.logic import schema_repository from schematizer.models.note import ReferenceTypeEnum @view_config( route_name='api.v1.create_note', request_method='POST', renderer='json' ) @transform_api_response() @log_api() def create_note(request): req = requests_v1.CreateNoteRequest(**request.json_body) assert_reference_exists(req.reference_type, req.reference_id) note = doc_tool.create_note( reference_type=req.reference_type, reference_id=req.reference_id, note_text=req.note, last_updated_by=req.last_updated_by ) return responses_v1.get_note_response_from_note(note) def assert_reference_exists(reference_type, reference_id): """Checks to make sure that the reference for this note exists. If it does not, raise an exception """ if ( reference_type == ReferenceTypeEnum.SCHEMA and schema_repository.get_schema_by_id(reference_id) is not None ) or ( reference_type == ReferenceTypeEnum.SCHEMA_ELEMENT and schema_repository.get_schema_element_by_id(reference_id) is not None ): # Valid. Do nothing return raise exceptions_v1.reference_not_found_exception() @view_config( route_name='api.v1.update_note', request_method='POST', renderer='json' ) @transform_api_response() @log_api() def update_note(request): req = requests_v1.UpdateNoteRequest(**request.json_body) note_id_str = request.matchdict.get('note_id') note_id = int(note_id_str) note = doc_tool.get_note_by_id(note_id) # Raise an exception if the note cannot be found if note is None: raise exceptions_v1.note_not_found_exception() doc_tool.update_note( id=note_id, note_text=req.note, last_updated_by=req.last_updated_by ) return responses_v1.get_note_response_from_note(note)
schematizer/views/notes.py
from __future__ import absolute_import from __future__ import unicode_literals from pyramid.view import view_config from schematizer.api.decorators import log_api from schematizer.api.decorators import transform_api_response from schematizer.api.exceptions import exceptions_v1 from schematizer.api.requests import requests_v1 from schematizer.api.responses import responses_v1 from schematizer.logic import doc_tool from schematizer.logic import schema_repository from schematizer.models.note import ReferenceTypeEnum @view_config( route_name='api.v1.create_note', request_method='POST', renderer='json' ) @transform_api_response() @log_api() def create_note(request): req = requests_v1.CreateNoteRequest(**request.json_body) assert_reference_exists(req.reference_type, req.reference_id) note = doc_tool.create_note( reference_type=req.reference_type, reference_id=req.reference_id, note_text=req.note, last_updated_by=req.last_updated_by ) return responses_v1.get_note_response_from_note(note) def assert_reference_exists(reference_type, reference_id): """Checks to make sure that the reference for this note exists. If it does not, raise an exception """ if ( reference_type == ReferenceTypeEnum.SCHEMA and schema_repository.get_schema_by_id(reference_id) is not None ) or ( reference_type == ReferenceTypeEnum.SCHEMA_ELEMENT and schema_repository.get_schema_element_by_id(reference_id) is not None ): # Valid. Do nothing return raise exceptions_v1.reference_not_found_exception() @view_config( route_name='api.v1.update_note', request_method='POST', renderer='json' ) @transform_api_response() @log_api() def update_note(request): req = requests_v1.UpdateNoteRequest(**request.json_body) note_id_str = request.matchdict.get('note_id') note_id = int(note_id_str) note = doc_tool.get_note_by_id(note_id) # Raise an exception if the note cannot be found if note is None: raise exceptions_v1.note_not_found_exception() doc_tool.update_note( id=note_id, note_text=req.note, last_updated_by=req.last_updated_by ) return responses_v1.get_note_response_from_note(note)
0.663124
0.109658
import click import sys import traceback import os import opencc from lightnovel import LightNovel from utils import echo from provider import lk_new from provider import wenku8 from provider import lk_mobile echo.init_subroutine() @click.group() def cli(): pass @cli.command() # general options @click.option('--dump-path', type=click.Path(), default='./dump', help='directory for dumping files and caches') @click.option('--title', default=None, help='title of light novel') @click.option('--authors', default=None, help='authors\' names, separated by comma (,)') @click.option('--identifier', default=None, help='identifier of light novel') @click.option('--cover-link', default=None, help='cover link of light novel. cover link can either be web link or file path. if it is not beginned with "http", it would be recognized as file path. if nothing was given, then it will use the first picture of webpage.') @click.option('--cvt', default=None, help='OpenCC conversion configuration, used to convert between different Chinese characters. you can choose the value from "s2t", "t2s", "s2tw", "tw2s", "s2hk", "hk2s", "s2twp", "tw2sp", "t2tw", "hk2t", "t2hk", "t2jp", "jp2t", "tw2t". if nothing is provided, no conversion would be performed. for more information, please visit: https://github.com/BYVoid/OpenCC') @click.option('--path', type=click.Path(exists=True), default='./', help='directory for saving the light novel') # lightnovel.us @click.option('--lk-html-dump', type=click.Path(exists=True), default=None, help='(lightnovel.us) html content dump file path') # wenku8.net @click.option('--wenku8-volume', default=-1, help='(wenku8.net) identify the index of the volume to generate. -1 means every volume, which is also the default option. index starts from 1.') # lk mobile @click.option('--lk-mobile-top-area-height', default=325, help='(lk mobile) the height of the top area') @click.option('--lk-mobile-bottom-area-height', default=200, help='(lk mobile) the height of the bottom area') @click.option('--lk-mobile-image-equal-threshold', default=1, help='(lk mobile) the threshold of judging whether two images are equal') @click.option('--lk-mobile-safe-area-padding', default=20, help='(lk mobile) the padding of the safe area') @click.option('--lk-mobile-vert-dump', type=click.Path(exists=True), default=None, help='(lk mobile) vertical content dump file path') @click.option('--lk-mobile-horz-dump', type=click.Path(exists=True), default=None, help='(lk mobile) horizontal content dump file path') @click.option('--lk-mobile-html-dump', type=click.Path(exists=True), default=None, help='(lk mobile) html content dump file path') @click.option('--lk-mobile-conflict-mode', type=bool, default=False, help='(lk mobile) whether to resolve conflict manually') @click.option('--lk-mobile-ignore-newline', type=bool, default=True, help='(lk mobile) whether to ignore newline') # general arguments @click.argument('url') def download( dump_path, title: str, authors: str, identifier: str, cover_link: str, cvt: str, path: str, lk_html_dump, wenku8_volume: int, lk_mobile_top_area_height: int, lk_mobile_bottom_area_height: int, lk_mobile_image_equal_threshold: int, lk_mobile_safe_area_padding: int, lk_mobile_vert_dump, lk_mobile_horz_dump, lk_mobile_html_dump, lk_mobile_conflict_mode: bool, lk_mobile_ignore_newline: bool, url: str): ''' download the light novel ARGUMENTS: * URL: url of light novel to download ''' def convert_str(content, cvt): # chinese conversion if cvt in ["s2t", "t2s", "s2tw", "tw2s", "s2hk", "hk2s", "s2twp", "tw2sp", "t2tw", "hk2t", "t2hk", "t2jp", "jp2t", "tw2t"]: converter = opencc.OpenCC(f'{cvt}.json') return converter.convert(content) return content echo.push_subroutine(sys._getframe().f_code.co_name) try: # init directory if not os.path.exists(dump_path): os.mkdir(dump_path) if cover_link is None: cover_link = input('(Optional) Input cover_link of light novel (see --help for further explanation): ') if url.startswith('https://www.lightnovel.us/'): contents = lk_new.get_contents(url, dump_path, lk_html_dump) cover_link = lk_new.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link elif url.startswith('https://www.wenku8.net/'): source, authors, identifier, title, books, contents = wenku8.get_contents(url, dump_path, wenku8_volume) cover_link = wenku8.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link elif url == 'lk-mobile': contents = lk_mobile.get_contents(lk_mobile_top_area_height, lk_mobile_bottom_area_height, lk_mobile_image_equal_threshold, lk_mobile_safe_area_padding, dump_path, lk_mobile_vert_dump, lk_mobile_horz_dump, lk_mobile_html_dump, lk_mobile_conflict_mode, lk_mobile_ignore_newline) cover_link = lk_mobile.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link url = '轻之国度 APP' else: echo.cexit('unsupported url') if type(contents) == str: contents = convert_str(contents, cvt) elif type(contents) == list: for content in contents: content['title'] = convert_str(content['title'], cvt) content['content'] = convert_str(content['content'], cvt) else: echo.cexit('CONTENTS MUST BE STRING OR LIST') TITLE_INPUT_HINT = 'Input title of light novel: ' AUTHOR_INPUT_HINT = '(Optional) Input authors\' names, separated by comma (,): ' IDENTIFIER_INPUT_HINT = '(Optional) Input identifier of light novel: ' def isempty(instr) -> bool: if instr is None: return True if len(instr) == 0 or str.isspace(instr): return True return False if isempty(title): title = input(TITLE_INPUT_HINT) else: user_title = input(f'Current Title: {title}. (Optional) {TITLE_INPUT_HINT}') title = title if isempty(user_title) else user_title if isempty(authors): authors = input(AUTHOR_INPUT_HINT) else: user_authors = input(f'Current Authors: {authors}. {AUTHOR_INPUT_HINT}') authors = authors if isempty(user_authors) else user_authors if isempty(identifier): identifier = input(IDENTIFIER_INPUT_HINT) else: user_identifier = input(f'Current identifier: {identifier}. {IDENTIFIER_INPUT_HINT}') identifier = identifier if isempty(user_identifier) else user_identifier novel = LightNovel(source=url, authors=authors.split(','), identifier=identifier, title=title, cover_link=cover_link) novel.contents = contents novel.write_epub(path) except Exception as e: echo.cerr(f'Error: {repr(e)}') traceback.print_exc() echo.cexit('DOWNLOAD LIGHTNOVEL FAILED') finally: echo.pop_subroutine() if __name__ == '__main__': cli()
cli.py
import click import sys import traceback import os import opencc from lightnovel import LightNovel from utils import echo from provider import lk_new from provider import wenku8 from provider import lk_mobile echo.init_subroutine() @click.group() def cli(): pass @cli.command() # general options @click.option('--dump-path', type=click.Path(), default='./dump', help='directory for dumping files and caches') @click.option('--title', default=None, help='title of light novel') @click.option('--authors', default=None, help='authors\' names, separated by comma (,)') @click.option('--identifier', default=None, help='identifier of light novel') @click.option('--cover-link', default=None, help='cover link of light novel. cover link can either be web link or file path. if it is not beginned with "http", it would be recognized as file path. if nothing was given, then it will use the first picture of webpage.') @click.option('--cvt', default=None, help='OpenCC conversion configuration, used to convert between different Chinese characters. you can choose the value from "s2t", "t2s", "s2tw", "tw2s", "s2hk", "hk2s", "s2twp", "tw2sp", "t2tw", "hk2t", "t2hk", "t2jp", "jp2t", "tw2t". if nothing is provided, no conversion would be performed. for more information, please visit: https://github.com/BYVoid/OpenCC') @click.option('--path', type=click.Path(exists=True), default='./', help='directory for saving the light novel') # lightnovel.us @click.option('--lk-html-dump', type=click.Path(exists=True), default=None, help='(lightnovel.us) html content dump file path') # wenku8.net @click.option('--wenku8-volume', default=-1, help='(wenku8.net) identify the index of the volume to generate. -1 means every volume, which is also the default option. index starts from 1.') # lk mobile @click.option('--lk-mobile-top-area-height', default=325, help='(lk mobile) the height of the top area') @click.option('--lk-mobile-bottom-area-height', default=200, help='(lk mobile) the height of the bottom area') @click.option('--lk-mobile-image-equal-threshold', default=1, help='(lk mobile) the threshold of judging whether two images are equal') @click.option('--lk-mobile-safe-area-padding', default=20, help='(lk mobile) the padding of the safe area') @click.option('--lk-mobile-vert-dump', type=click.Path(exists=True), default=None, help='(lk mobile) vertical content dump file path') @click.option('--lk-mobile-horz-dump', type=click.Path(exists=True), default=None, help='(lk mobile) horizontal content dump file path') @click.option('--lk-mobile-html-dump', type=click.Path(exists=True), default=None, help='(lk mobile) html content dump file path') @click.option('--lk-mobile-conflict-mode', type=bool, default=False, help='(lk mobile) whether to resolve conflict manually') @click.option('--lk-mobile-ignore-newline', type=bool, default=True, help='(lk mobile) whether to ignore newline') # general arguments @click.argument('url') def download( dump_path, title: str, authors: str, identifier: str, cover_link: str, cvt: str, path: str, lk_html_dump, wenku8_volume: int, lk_mobile_top_area_height: int, lk_mobile_bottom_area_height: int, lk_mobile_image_equal_threshold: int, lk_mobile_safe_area_padding: int, lk_mobile_vert_dump, lk_mobile_horz_dump, lk_mobile_html_dump, lk_mobile_conflict_mode: bool, lk_mobile_ignore_newline: bool, url: str): ''' download the light novel ARGUMENTS: * URL: url of light novel to download ''' def convert_str(content, cvt): # chinese conversion if cvt in ["s2t", "t2s", "s2tw", "tw2s", "s2hk", "hk2s", "s2twp", "tw2sp", "t2tw", "hk2t", "t2hk", "t2jp", "jp2t", "tw2t"]: converter = opencc.OpenCC(f'{cvt}.json') return converter.convert(content) return content echo.push_subroutine(sys._getframe().f_code.co_name) try: # init directory if not os.path.exists(dump_path): os.mkdir(dump_path) if cover_link is None: cover_link = input('(Optional) Input cover_link of light novel (see --help for further explanation): ') if url.startswith('https://www.lightnovel.us/'): contents = lk_new.get_contents(url, dump_path, lk_html_dump) cover_link = lk_new.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link elif url.startswith('https://www.wenku8.net/'): source, authors, identifier, title, books, contents = wenku8.get_contents(url, dump_path, wenku8_volume) cover_link = wenku8.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link elif url == 'lk-mobile': contents = lk_mobile.get_contents(lk_mobile_top_area_height, lk_mobile_bottom_area_height, lk_mobile_image_equal_threshold, lk_mobile_safe_area_padding, dump_path, lk_mobile_vert_dump, lk_mobile_horz_dump, lk_mobile_html_dump, lk_mobile_conflict_mode, lk_mobile_ignore_newline) cover_link = lk_mobile.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link url = '轻之国度 APP' else: echo.cexit('unsupported url') if type(contents) == str: contents = convert_str(contents, cvt) elif type(contents) == list: for content in contents: content['title'] = convert_str(content['title'], cvt) content['content'] = convert_str(content['content'], cvt) else: echo.cexit('CONTENTS MUST BE STRING OR LIST') TITLE_INPUT_HINT = 'Input title of light novel: ' AUTHOR_INPUT_HINT = '(Optional) Input authors\' names, separated by comma (,): ' IDENTIFIER_INPUT_HINT = '(Optional) Input identifier of light novel: ' def isempty(instr) -> bool: if instr is None: return True if len(instr) == 0 or str.isspace(instr): return True return False if isempty(title): title = input(TITLE_INPUT_HINT) else: user_title = input(f'Current Title: {title}. (Optional) {TITLE_INPUT_HINT}') title = title if isempty(user_title) else user_title if isempty(authors): authors = input(AUTHOR_INPUT_HINT) else: user_authors = input(f'Current Authors: {authors}. {AUTHOR_INPUT_HINT}') authors = authors if isempty(user_authors) else user_authors if isempty(identifier): identifier = input(IDENTIFIER_INPUT_HINT) else: user_identifier = input(f'Current identifier: {identifier}. {IDENTIFIER_INPUT_HINT}') identifier = identifier if isempty(user_identifier) else user_identifier novel = LightNovel(source=url, authors=authors.split(','), identifier=identifier, title=title, cover_link=cover_link) novel.contents = contents novel.write_epub(path) except Exception as e: echo.cerr(f'Error: {repr(e)}') traceback.print_exc() echo.cexit('DOWNLOAD LIGHTNOVEL FAILED') finally: echo.pop_subroutine() if __name__ == '__main__': cli()
0.193833
0.073696
from CodaClient import Client, Currency, CurrencyFormat import os import schedule import time import urllib3 import random from requests.exceptions import ConnectionError from prometheus_client import Counter, start_http_server def getenv_default_map(env_var: str, f, default): value = os.getenv(env_var) if value == None: return default else: return f(value) def getenv_str(env_var: str, default: str) -> str: return os.getenv(env_var, default).strip() def getenv_int(env_var: str, default: int) -> int: return getenv_default_map(env_var, int, default) def getenv_currency(env_var: str, lower_bound: Currency, upper_bound: Currency) -> Currency: return getenv_default_map(env_var, Currency, Currency.random(lower_bound, upper_bound)) CODA_PUBLIC_KEY = getenv_str("CODA_PUBLIC_KEY", "<KEY>") MINA_PRIVKEY_PASS = getenv_str("MINA_PRIVKEY_PASS", "<PASSWORD>") AGENT_MIN_FEE = getenv_currency("AGENT_MIN_FEE", Currency("0.06"), Currency("0.1")) AGENT_MAX_FEE = getenv_currency("AGENT_MAX_FEE", AGENT_MIN_FEE, AGENT_MIN_FEE + Currency("0.2")) AGENT_MIN_TX = getenv_currency("AGENT_MIN_TX", Currency("0.0015"), Currency("0.005")) AGENT_MAX_TX = getenv_currency("AGENT_MAX_TX", AGENT_MIN_TX, AGENT_MIN_TX + Currency("0.01")) AGENT_TX_BATCH_SIZE = getenv_int("AGENT_TX_BATCH_SIZE", 1) AGENT_SEND_EVERY_MINS = getenv_int("AGENT_SEND_EVERY_MINS", random.randint(1, 5)) AGENT_METRICS_PORT = getenv_int("AGENT_METRICS_PORT", 8000) CODA_CLIENT_ARGS = { "graphql_host": getenv_str("CODA_HOST", "localhost"), "graphql_port": getenv_str("CODA_PORT", "3085") } ## Prometheus Metrics TRANSACTIONS_SENT = Counter('transactions_sent', 'Number of transactions agent has sent since boot.') TRANSACTION_ERRORS = Counter('transaction_errors', 'Number of errors that occurred while sending transactions.') class Agent(object): """Represents a generic agent that operates on the coda blockchain""" def __init__(self, client_args, public_key, privkey_pass, min_tx_amount=AGENT_MIN_TX, max_tx_amount=AGENT_MAX_TX, min_fee_amount=AGENT_MIN_FEE, max_fee_amount=AGENT_MAX_FEE): self.coda = Client(**client_args) self.public_key = public_key self.privkey_pass = privkey_pass self.min_tx_amount = min_tx_amount self.max_tx_amount = max_tx_amount self.min_fee_amount = min_fee_amount self.max_fee_amount = max_fee_amount self.to_account = None def get_to_account(self): if not self.to_account: print("Getting new wallet to send to...") response = self.coda.create_wallet(self.privkey_pass) self.to_account = response["createAccount"]["publicKey"] print("Public Key: {}".format(self.to_account)) return self.to_account def unlock_wallet(self): response = self.coda.unlock_wallet(self.public_key, self.privkey_pass) print("Unlocked Wallet!") return response def send_transaction(self): print("---Sending Transaction---") try: to_account = self.get_to_account() print("Trying to unlock Wallet!") self.unlock_wallet() except ConnectionError: print("Transaction Failed due to connection error... is the Daemon running?") TRANSACTION_ERRORS.inc() return None except Exception as e: print("Error unlocking wallet...") print(e) return None tx_amount = Currency.random(self.min_tx_amount, self.max_tx_amount) fee_amount = Currency.random(self.min_fee_amount, self.max_fee_amount) try: response = self.coda.send_payment(to_account, self.public_key, tx_amount, fee_amount, memo="BeepBoop") except Exception as e: print("Error sending transaction...", e) TRANSACTION_ERRORS.inc() return None if not response.get("errors", None): print("Sent a Transaction {}".format(response)) TRANSACTIONS_SENT.inc() else: print("Error sending transaction: Request: {} Response: {}".format(self.public_key, response)) TRANSACTION_ERRORS.inc() return response def send_transaction_batch(self): responses = [] for i in range(AGENT_TX_BATCH_SIZE): responses.append(self.send_transaction()) return responses def main(): agent = Agent(CODA_CLIENT_ARGS, CODA_PUBLIC_KEY, MINA_PRIVKEY_PASS) schedule.every(AGENT_SEND_EVERY_MINS).minutes.do(agent.send_transaction_batch) print("Sending a transaction every {} minutes.".format(AGENT_SEND_EVERY_MINS)) while True: schedule.run_pending() sleep_time = 10 print("Sleeping for {} seconds...".format(sleep_time)) time.sleep(sleep_time) if __name__ == "__main__": print("Starting up...") start_http_server(AGENT_METRICS_PORT) print("Metrics on Port {}".format(AGENT_METRICS_PORT)) print("Sleeping for 20 minutes...") time.sleep(60*20) main()
automation/services/coda-user-agent/agent.py
from CodaClient import Client, Currency, CurrencyFormat import os import schedule import time import urllib3 import random from requests.exceptions import ConnectionError from prometheus_client import Counter, start_http_server def getenv_default_map(env_var: str, f, default): value = os.getenv(env_var) if value == None: return default else: return f(value) def getenv_str(env_var: str, default: str) -> str: return os.getenv(env_var, default).strip() def getenv_int(env_var: str, default: int) -> int: return getenv_default_map(env_var, int, default) def getenv_currency(env_var: str, lower_bound: Currency, upper_bound: Currency) -> Currency: return getenv_default_map(env_var, Currency, Currency.random(lower_bound, upper_bound)) CODA_PUBLIC_KEY = getenv_str("CODA_PUBLIC_KEY", "<KEY>") MINA_PRIVKEY_PASS = getenv_str("MINA_PRIVKEY_PASS", "<PASSWORD>") AGENT_MIN_FEE = getenv_currency("AGENT_MIN_FEE", Currency("0.06"), Currency("0.1")) AGENT_MAX_FEE = getenv_currency("AGENT_MAX_FEE", AGENT_MIN_FEE, AGENT_MIN_FEE + Currency("0.2")) AGENT_MIN_TX = getenv_currency("AGENT_MIN_TX", Currency("0.0015"), Currency("0.005")) AGENT_MAX_TX = getenv_currency("AGENT_MAX_TX", AGENT_MIN_TX, AGENT_MIN_TX + Currency("0.01")) AGENT_TX_BATCH_SIZE = getenv_int("AGENT_TX_BATCH_SIZE", 1) AGENT_SEND_EVERY_MINS = getenv_int("AGENT_SEND_EVERY_MINS", random.randint(1, 5)) AGENT_METRICS_PORT = getenv_int("AGENT_METRICS_PORT", 8000) CODA_CLIENT_ARGS = { "graphql_host": getenv_str("CODA_HOST", "localhost"), "graphql_port": getenv_str("CODA_PORT", "3085") } ## Prometheus Metrics TRANSACTIONS_SENT = Counter('transactions_sent', 'Number of transactions agent has sent since boot.') TRANSACTION_ERRORS = Counter('transaction_errors', 'Number of errors that occurred while sending transactions.') class Agent(object): """Represents a generic agent that operates on the coda blockchain""" def __init__(self, client_args, public_key, privkey_pass, min_tx_amount=AGENT_MIN_TX, max_tx_amount=AGENT_MAX_TX, min_fee_amount=AGENT_MIN_FEE, max_fee_amount=AGENT_MAX_FEE): self.coda = Client(**client_args) self.public_key = public_key self.privkey_pass = privkey_pass self.min_tx_amount = min_tx_amount self.max_tx_amount = max_tx_amount self.min_fee_amount = min_fee_amount self.max_fee_amount = max_fee_amount self.to_account = None def get_to_account(self): if not self.to_account: print("Getting new wallet to send to...") response = self.coda.create_wallet(self.privkey_pass) self.to_account = response["createAccount"]["publicKey"] print("Public Key: {}".format(self.to_account)) return self.to_account def unlock_wallet(self): response = self.coda.unlock_wallet(self.public_key, self.privkey_pass) print("Unlocked Wallet!") return response def send_transaction(self): print("---Sending Transaction---") try: to_account = self.get_to_account() print("Trying to unlock Wallet!") self.unlock_wallet() except ConnectionError: print("Transaction Failed due to connection error... is the Daemon running?") TRANSACTION_ERRORS.inc() return None except Exception as e: print("Error unlocking wallet...") print(e) return None tx_amount = Currency.random(self.min_tx_amount, self.max_tx_amount) fee_amount = Currency.random(self.min_fee_amount, self.max_fee_amount) try: response = self.coda.send_payment(to_account, self.public_key, tx_amount, fee_amount, memo="BeepBoop") except Exception as e: print("Error sending transaction...", e) TRANSACTION_ERRORS.inc() return None if not response.get("errors", None): print("Sent a Transaction {}".format(response)) TRANSACTIONS_SENT.inc() else: print("Error sending transaction: Request: {} Response: {}".format(self.public_key, response)) TRANSACTION_ERRORS.inc() return response def send_transaction_batch(self): responses = [] for i in range(AGENT_TX_BATCH_SIZE): responses.append(self.send_transaction()) return responses def main(): agent = Agent(CODA_CLIENT_ARGS, CODA_PUBLIC_KEY, MINA_PRIVKEY_PASS) schedule.every(AGENT_SEND_EVERY_MINS).minutes.do(agent.send_transaction_batch) print("Sending a transaction every {} minutes.".format(AGENT_SEND_EVERY_MINS)) while True: schedule.run_pending() sleep_time = 10 print("Sleeping for {} seconds...".format(sleep_time)) time.sleep(sleep_time) if __name__ == "__main__": print("Starting up...") start_http_server(AGENT_METRICS_PORT) print("Metrics on Port {}".format(AGENT_METRICS_PORT)) print("Sleeping for 20 minutes...") time.sleep(60*20) main()
0.46393
0.111
from __future__ import absolute_import from collections import namedtuple from typing import (Any, Callable, Dict, # pylint: disable=unused-import Generator, Iterable, List, Text, Union, cast) from .errors import WorkflowException MutationState = namedtuple("MutationTracker", ["generation", "readers", "stepname"]) _generation = "http://commonwl.org/cwltool#generation" class MutationManager(object): """Lock manager for checking correctness of in-place update of files. Used to validate that in-place file updates happen sequentially, and that a file which is registered for in-place update cannot be read or updated by any other steps. """ def __init__(self): # type: () -> None self.generations = {} # type: Dict[Text, MutationState] def register_reader(self, stepname, obj): # type: (Text, Dict[Text, Any]) -> None loc = obj["location"] current = self.generations.get(loc, MutationState(0, [], "")) obj_generation = obj.get(_generation, 0) if obj_generation != current.generation: raise WorkflowException("[job %s] wants to read %s from generation %i but current generation is %s (last updated by %s)" % ( stepname, loc, obj_generation, current.generation, current.stepname)) current.readers.append(stepname) self.generations[loc] = current def release_reader(self, stepname, obj): # type: (Text, Dict[Text, Any]) -> None loc = obj["location"] current = self.generations.get(loc, MutationState(0, [], "")) obj_generation = obj.get(_generation, 0) if obj_generation != current.generation: raise WorkflowException("[job %s] wants to release reader on %s from generation %i but current generation is %s (last updated by %s)" % ( stepname, loc, obj_generation, current.generation, current.stepname)) self.generations[loc].readers.remove(stepname) def register_mutation(self, stepname, obj): # type: (Text, Dict[Text, Any]) -> None loc = obj["location"] current = self.generations.get(loc, MutationState(0,[], "")) obj_generation = obj.get(_generation, 0) if len(current.readers) > 0: raise WorkflowException("[job %s] wants to modify %s but has readers: %s" % ( stepname, loc, current.readers)) if obj_generation != current.generation: raise WorkflowException("[job %s] wants to modify %s from generation %i but current generation is %s (last updated by %s)" % ( stepname, loc, obj_generation, current.generation, current.stepname)) self.generations[loc] = MutationState(current.generation+1, current.readers, stepname) def set_generation(self, obj): # type: (Dict) -> None loc = obj["location"] current = self.generations.get(loc, MutationState(0,[], "")) obj[_generation] = current.generation def unset_generation(self, obj): # type: (Dict) -> None obj.pop(_generation, None)
cwltool/mutation.py
from __future__ import absolute_import from collections import namedtuple from typing import (Any, Callable, Dict, # pylint: disable=unused-import Generator, Iterable, List, Text, Union, cast) from .errors import WorkflowException MutationState = namedtuple("MutationTracker", ["generation", "readers", "stepname"]) _generation = "http://commonwl.org/cwltool#generation" class MutationManager(object): """Lock manager for checking correctness of in-place update of files. Used to validate that in-place file updates happen sequentially, and that a file which is registered for in-place update cannot be read or updated by any other steps. """ def __init__(self): # type: () -> None self.generations = {} # type: Dict[Text, MutationState] def register_reader(self, stepname, obj): # type: (Text, Dict[Text, Any]) -> None loc = obj["location"] current = self.generations.get(loc, MutationState(0, [], "")) obj_generation = obj.get(_generation, 0) if obj_generation != current.generation: raise WorkflowException("[job %s] wants to read %s from generation %i but current generation is %s (last updated by %s)" % ( stepname, loc, obj_generation, current.generation, current.stepname)) current.readers.append(stepname) self.generations[loc] = current def release_reader(self, stepname, obj): # type: (Text, Dict[Text, Any]) -> None loc = obj["location"] current = self.generations.get(loc, MutationState(0, [], "")) obj_generation = obj.get(_generation, 0) if obj_generation != current.generation: raise WorkflowException("[job %s] wants to release reader on %s from generation %i but current generation is %s (last updated by %s)" % ( stepname, loc, obj_generation, current.generation, current.stepname)) self.generations[loc].readers.remove(stepname) def register_mutation(self, stepname, obj): # type: (Text, Dict[Text, Any]) -> None loc = obj["location"] current = self.generations.get(loc, MutationState(0,[], "")) obj_generation = obj.get(_generation, 0) if len(current.readers) > 0: raise WorkflowException("[job %s] wants to modify %s but has readers: %s" % ( stepname, loc, current.readers)) if obj_generation != current.generation: raise WorkflowException("[job %s] wants to modify %s from generation %i but current generation is %s (last updated by %s)" % ( stepname, loc, obj_generation, current.generation, current.stepname)) self.generations[loc] = MutationState(current.generation+1, current.readers, stepname) def set_generation(self, obj): # type: (Dict) -> None loc = obj["location"] current = self.generations.get(loc, MutationState(0,[], "")) obj[_generation] = current.generation def unset_generation(self, obj): # type: (Dict) -> None obj.pop(_generation, None)
0.692538
0.128662
from .input_components.OneChannel import OneChannel from .input_components.TwoEmbChannel import TwoEmbChannel from .input_components.SixChannel import SixChannel from .input_components.OneChannel_DocLevel import OneChannel_DocLevel from .middle_components.parallel_conv import NParallelConvOnePoolNFC from .middle_components.parallel_size_joined_conv import NCrossSizeParallelConvNFC from .middle_components.parallel_joined_conv import ParallelJoinedConv from .middle_components.parallel_conv_DocLevel import NConvDocConvNFC from .middle_components.inception_like import InceptionLike from .middle_components.pure_rnn import PureRNN from .output_components.pan_output import PANOutput from .output_components.ml_output import MLOutput class TextCNN: """ A CNN for text classification. Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer. Works for both single label (PAN) and multilabel (ML) datasets """ def __init__( self, data, document_length, sequence_length, num_classes, embedding_size, filter_sizes, num_filters, input_component, middle_component, l2_reg_lambda, dropout, batch_normalize, elu, fc): word_vocab_size = len(data.vocab) # input component if input_component.endswith("One"): self.input_comp = OneChannel(sequence_length, num_classes, word_vocab_size, embedding_size, data.embed_matrix) elif input_component.endswith("One_DocLevel"): self.input_comp = OneChannel_DocLevel(document_length, sequence_length, num_classes, word_vocab_size, embedding_size, data.embed_matrix) elif input_component.endswith("2CH"): self.input_comp = TwoEmbChannel(sequence_length, num_classes, word_vocab_size, embedding_size, data.embed_matrix, data.embed_matrix_w2v) elif input_component.endswith("Six"): # self.input_comp = SixChannel(sequence_length, num_classes, word_vocab_size, embedding_size, # pref2_vocab_size, pref3_vocab_size, suff2_vocab_size, suff3_vocab_size, # pos_vocab_size, # init_embedding_glv) # TODO self.input_pref2 = self.input_comp.input_pref2 self.input_pref3 = self.input_comp.input_pref3 self.input_suff2 = self.input_comp.input_suff2 self.input_suff3 = self.input_comp.input_suff3 self.input_pos = self.input_comp.input_pos elif input_component.endswith("PAN11"): self.input_comp = TwoEmbChannel(sequence_length, num_classes, word_vocab_size, embedding_size, data.embed_matrix, data.embed_matrix_w2v) else: raise NotImplementedError self.input_x = self.input_comp.input_x self.input_y = self.input_comp.input_y self.dropout_keep_prob = self.input_comp.dropout_keep_prob # middle component if middle_component == 'NParallelConvOnePoolNFC': self.middle_comp = NParallelConvOnePoolNFC(sequence_length, embedding_size, filter_sizes, num_filters, previous_component=self.input_comp, dropout=dropout, batch_normalize=batch_normalize, elu=elu, n_conv=n_conv, fc=fc) elif middle_component == 'ParallelJoinedConv': self.middle_comp = ParallelJoinedConv(sequence_length, embedding_size, filter_sizes, num_filters, previous_component=self.input_comp, dropout=dropout, batch_normalize=batch_normalize, elu=elu, n_conv=n_conv, fc=fc) elif middle_component == 'NCrossSizeParallelConvNFC': self.middle_comp = NCrossSizeParallelConvNFC(sequence_length, embedding_size, filter_sizes, num_filters, previous_component=self.input_comp, dropout=dropout, batch_normalize=batch_normalize, elu=elu, fc=fc, l2_reg_lambda=l2_reg_lambda) elif middle_component == "NConvDocConvNFC": self.middle_comp = NConvDocConvNFC(document_length, sequence_length, embedding_size, filter_sizes, num_filters, previous_component=self.input_comp, dropout=dropout, batch_normalize=batch_normalize, elu=elu, fc=fc) elif middle_component == 'InceptionLike': self.middle_comp = InceptionLike(sequence_length, embedding_size, filter_sizes, num_filters, previous_component=self.input_comp, dropout=dropout, batch_normalize=batch_normalize, elu=elu, fc=fc) elif middle_component == 'PureRNN': self.middle_comp = PureRNN(sequence_length, embedding_size, previous_component=self.input_comp, num_layers=1, bidirectional=False, attn_length=50, attn_size=50, attn_vec_size=50) else: raise NotImplementedError self.is_training = self.middle_comp.is_training prev_layer, num_nodes = self.middle_comp.get_last_layer_info() l2_sum = self.middle_comp.l2_sum # output component if "ML" in data.name: output = MLOutput(self.input_comp.input_y, prev_layer, num_nodes, num_classes, l2_sum, l2_reg_lambda) elif "PAN" in data.name: output = PANOutput(self.input_comp.input_y, prev_layer, num_nodes, num_classes, l2_sum, l2_reg_lambda) # self.rate_percentage = output.rate_percentage else: raise NotImplementedError self.loss = output.loss self.scores = output.scores self.predictions = output.predictions self.accuracy = output.accuracy
networks/cnn.py
from .input_components.OneChannel import OneChannel from .input_components.TwoEmbChannel import TwoEmbChannel from .input_components.SixChannel import SixChannel from .input_components.OneChannel_DocLevel import OneChannel_DocLevel from .middle_components.parallel_conv import NParallelConvOnePoolNFC from .middle_components.parallel_size_joined_conv import NCrossSizeParallelConvNFC from .middle_components.parallel_joined_conv import ParallelJoinedConv from .middle_components.parallel_conv_DocLevel import NConvDocConvNFC from .middle_components.inception_like import InceptionLike from .middle_components.pure_rnn import PureRNN from .output_components.pan_output import PANOutput from .output_components.ml_output import MLOutput class TextCNN: """ A CNN for text classification. Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer. Works for both single label (PAN) and multilabel (ML) datasets """ def __init__( self, data, document_length, sequence_length, num_classes, embedding_size, filter_sizes, num_filters, input_component, middle_component, l2_reg_lambda, dropout, batch_normalize, elu, fc): word_vocab_size = len(data.vocab) # input component if input_component.endswith("One"): self.input_comp = OneChannel(sequence_length, num_classes, word_vocab_size, embedding_size, data.embed_matrix) elif input_component.endswith("One_DocLevel"): self.input_comp = OneChannel_DocLevel(document_length, sequence_length, num_classes, word_vocab_size, embedding_size, data.embed_matrix) elif input_component.endswith("2CH"): self.input_comp = TwoEmbChannel(sequence_length, num_classes, word_vocab_size, embedding_size, data.embed_matrix, data.embed_matrix_w2v) elif input_component.endswith("Six"): # self.input_comp = SixChannel(sequence_length, num_classes, word_vocab_size, embedding_size, # pref2_vocab_size, pref3_vocab_size, suff2_vocab_size, suff3_vocab_size, # pos_vocab_size, # init_embedding_glv) # TODO self.input_pref2 = self.input_comp.input_pref2 self.input_pref3 = self.input_comp.input_pref3 self.input_suff2 = self.input_comp.input_suff2 self.input_suff3 = self.input_comp.input_suff3 self.input_pos = self.input_comp.input_pos elif input_component.endswith("PAN11"): self.input_comp = TwoEmbChannel(sequence_length, num_classes, word_vocab_size, embedding_size, data.embed_matrix, data.embed_matrix_w2v) else: raise NotImplementedError self.input_x = self.input_comp.input_x self.input_y = self.input_comp.input_y self.dropout_keep_prob = self.input_comp.dropout_keep_prob # middle component if middle_component == 'NParallelConvOnePoolNFC': self.middle_comp = NParallelConvOnePoolNFC(sequence_length, embedding_size, filter_sizes, num_filters, previous_component=self.input_comp, dropout=dropout, batch_normalize=batch_normalize, elu=elu, n_conv=n_conv, fc=fc) elif middle_component == 'ParallelJoinedConv': self.middle_comp = ParallelJoinedConv(sequence_length, embedding_size, filter_sizes, num_filters, previous_component=self.input_comp, dropout=dropout, batch_normalize=batch_normalize, elu=elu, n_conv=n_conv, fc=fc) elif middle_component == 'NCrossSizeParallelConvNFC': self.middle_comp = NCrossSizeParallelConvNFC(sequence_length, embedding_size, filter_sizes, num_filters, previous_component=self.input_comp, dropout=dropout, batch_normalize=batch_normalize, elu=elu, fc=fc, l2_reg_lambda=l2_reg_lambda) elif middle_component == "NConvDocConvNFC": self.middle_comp = NConvDocConvNFC(document_length, sequence_length, embedding_size, filter_sizes, num_filters, previous_component=self.input_comp, dropout=dropout, batch_normalize=batch_normalize, elu=elu, fc=fc) elif middle_component == 'InceptionLike': self.middle_comp = InceptionLike(sequence_length, embedding_size, filter_sizes, num_filters, previous_component=self.input_comp, dropout=dropout, batch_normalize=batch_normalize, elu=elu, fc=fc) elif middle_component == 'PureRNN': self.middle_comp = PureRNN(sequence_length, embedding_size, previous_component=self.input_comp, num_layers=1, bidirectional=False, attn_length=50, attn_size=50, attn_vec_size=50) else: raise NotImplementedError self.is_training = self.middle_comp.is_training prev_layer, num_nodes = self.middle_comp.get_last_layer_info() l2_sum = self.middle_comp.l2_sum # output component if "ML" in data.name: output = MLOutput(self.input_comp.input_y, prev_layer, num_nodes, num_classes, l2_sum, l2_reg_lambda) elif "PAN" in data.name: output = PANOutput(self.input_comp.input_y, prev_layer, num_nodes, num_classes, l2_sum, l2_reg_lambda) # self.rate_percentage = output.rate_percentage else: raise NotImplementedError self.loss = output.loss self.scores = output.scores self.predictions = output.predictions self.accuracy = output.accuracy
0.675765
0.322046
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import math #https://github.com/ShichenLiu/CondenseNet class LearnedGroupConv(nn.Module): global_progress = 0.0 def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, condense_factor=None, dropout_rate=0.): super(LearnedGroupConv, self).__init__() self.norm = nn.BatchNorm2d(in_channels) self.relu = nn.ReLU(inplace=True) self.dropout_rate = dropout_rate if self.dropout_rate > 0: self.drop = nn.Dropout(dropout_rate, inplace=False) self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups=1, bias=False) self.in_channels = in_channels self.out_channels = out_channels self.groups = groups self.condense_factor = condense_factor if self.condense_factor is None: self.condense_factor = self.groups ### Parameters that should be carefully used self.register_buffer('_count', torch.zeros(1)) self.register_buffer('_stage', torch.zeros(1)) self.register_buffer('_mask', torch.ones(self.conv.weight.size())) ### Check if arguments are valid assert self.in_channels % self.groups == 0, "group number can not be divided by input channels" assert self.in_channels % self.condense_factor == 0, "condensation factor can not be divided by input channels" assert self.out_channels % self.groups == 0, "group number can not be divided by output channels" def forward(self, x): self._check_drop() x = self.norm(x) x = self.relu(x) if self.dropout_rate > 0: x = self.drop(x) ### Masked output weight = self.conv.weight * self.mask return F.conv2d(x, weight, None, self.conv.stride, self.conv.padding, self.conv.dilation, 1) def _check_drop(self): progress = LearnedGroupConv.global_progress delta = 0 ### Get current stage for i in range(self.condense_factor - 1): if progress * 2 < (i + 1) / (self.condense_factor - 1): stage = i break else: stage = self.condense_factor - 1 ### Check for dropping if not self._reach_stage(stage): self.stage = stage delta = self.in_channels // self.condense_factor if delta > 0: self._dropping(delta) return def _dropping(self, delta): weight = self.conv.weight * self.mask ### Sum up all kernels ### Assume only apply to 1x1 conv to speed up assert weight.size()[-1] == 1 weight = weight.abs().squeeze() assert weight.size()[0] == self.out_channels assert weight.size()[1] == self.in_channels d_out = self.out_channels // self.groups ### Shuffle weight weight = weight.view(d_out, self.groups, self.in_channels) weight = weight.transpose(0, 1).contiguous() weight = weight.view(self.out_channels, self.in_channels) ### Sort and drop for i in range(self.groups): wi = weight[i * d_out:(i + 1) * d_out, :] ### Take corresponding delta index di = wi.sum(0).sort()[1][self.count:self.count + delta] for d in di.data: self._mask[i::self.groups, d, :, :].fill_(0) self.count = self.count + delta @property def count(self): return int(self._count[0]) @count.setter def count(self, val): self._count.fill_(val) @property def stage(self): return int(self._stage[0]) @stage.setter def stage(self, val): self._stage.fill_(val) @property def mask(self): return Variable(self._mask) def _reach_stage(self, stage): return (self._stage >= stage).all() @property def lasso_loss(self): if self._reach_stage(self.groups - 1): return 0 weight = self.conv.weight * self.mask ### Assume only apply to 1x1 conv to speed up assert weight.size()[-1] == 1 weight = weight.squeeze().pow(2) d_out = self.out_channels // self.groups ### Shuffle weight weight = weight.view(d_out, self.groups, self.in_channels) weight = weight.sum(0).clamp(min=1e-6).sqrt() return weight.sum() def ShuffleLayer(x, groups): batchsize, num_channels, height, width = x.data.size() channels_per_group = num_channels // groups ### reshape x = x.view(batchsize, groups, channels_per_group, height, width) ### transpose x = torch.transpose(x, 1, 2).contiguous() ### flatten x = x.view(batchsize, -1, height, width) return x class CondensingLinear(nn.Module): def __init__(self, model, drop_rate=0.5): super(CondensingLinear, self).__init__() self.in_features = int(model.in_features*drop_rate) self.out_features = model.out_features self.linear = nn.Linear(self.in_features, self.out_features) self.register_buffer('index', torch.LongTensor(self.in_features)) _, index = model.weight.data.abs().sum(0).sort() index = index[model.in_features-self.in_features:] self.linear.bias.data = model.bias.data.clone() for i in range(self.in_features): self.index[i] = index[i] self.linear.weight.data[:, i] = model.weight.data[:, index[i]] def forward(self, x): x = torch.index_select(x, 1, Variable(self.index)) x = self.linear(x) return x class CondensingConv(nn.Module): def __init__(self, model): super(CondensingConv, self).__init__() self.in_channels = model.conv.in_channels \ * model.groups // model.condense_factor self.out_channels = model.conv.out_channels self.groups = model.groups self.condense_factor = model.condense_factor self.norm = nn.BatchNorm2d(self.in_channels) self.relu = nn.ReLU(inplace=True) self.conv = nn.Conv2d(self.in_channels, self.out_channels, kernel_size=model.conv.kernel_size, padding=model.conv.padding, groups=self.groups, bias=False, stride=model.conv.stride) self.register_buffer('index', torch.LongTensor(self.in_channels)) index = 0 mask = model._mask.mean(-1).mean(-1) for i in range(self.groups): for j in range(model.conv.in_channels): if index < (self.in_channels // self.groups) * (i + 1) \ and mask[i, j] == 1: for k in range(self.out_channels // self.groups): idx_i = int(k + i * (self.out_channels // self.groups)) idx_j = index % (self.in_channels // self.groups) self.conv.weight.data[idx_i, idx_j, :, :] = \ model.conv.weight.data[int(i + k * self.groups), j, :, :] self.norm.weight.data[index] = model.norm.weight.data[j] self.norm.bias.data[index] = model.norm.bias.data[j] self.norm.running_mean[index] = model.norm.running_mean[j] self.norm.running_var[index] = model.norm.running_var[j] self.index[index] = j index += 1 def forward(self, x): x = torch.index_select(x, 1, Variable(self.index)) x = self.norm(x) x = self.relu(x) x = self.conv(x) x = ShuffleLayer(x, self.groups) return x class CondenseLinear(nn.Module): def __init__(self, in_features, out_features, drop_rate=0.5): super(CondenseLinear, self).__init__() self.in_features = int(in_features*drop_rate) self.out_features = out_features self.linear = nn.Linear(self.in_features, self.out_features) self.register_buffer('index', torch.LongTensor(self.in_features)) def forward(self, x): x = torch.index_select(x, 1, Variable(self.index)) x = self.linear(x) return x class CondenseConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1): super(CondenseConv, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.groups = groups self.norm = nn.BatchNorm2d(self.in_channels) self.relu = nn.ReLU(inplace=True) self.conv = nn.Conv2d(self.in_channels, self.out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=self.groups, bias=False) self.register_buffer('index', torch.LongTensor(self.in_channels)) self.index.fill_(0) def forward(self, x): x = torch.index_select(x, 1, Variable(self.index)) x = self.norm(x) x = self.relu(x) x = self.conv(x) x = ShuffleLayer(x, self.groups) return x class Conv(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1): super(Conv, self).__init__() self.add_module('norm', nn.BatchNorm2d(in_channels)) self.add_module('relu', nn.ReLU(inplace=True)) self.add_module('conv', nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=False, groups=groups)) __all__ = ['CondenseNet'] class _DenseLayer(nn.Module): def __init__(self, in_channels, growth_rate, args): super(_DenseLayer, self).__init__() self.group_1x1 = args.group_1x1 self.group_3x3 = args.group_3x3 ### 1x1 conv i --> b*k self.conv_1 = LearnedGroupConv(in_channels, args.bottleneck * growth_rate, kernel_size=1, groups=self.group_1x1, condense_factor=args.condense_factor, dropout_rate=args.dropout_rate) ### 3x3 conv b*k --> k self.conv_2 = Conv(args.bottleneck * growth_rate, growth_rate, kernel_size=3, padding=1, groups=self.group_3x3) def forward(self, x): x_ = x x = self.conv_1(x) x = self.conv_2(x) return torch.cat([x_, x], 1) class _DenseBlock(nn.Sequential): def __init__(self, num_layers, in_channels, growth_rate, args): super(_DenseBlock, self).__init__() for i in range(num_layers): layer = _DenseLayer(in_channels + i * growth_rate, growth_rate, args) self.add_module('denselayer_%d' % (i + 1), layer) class _Transition(nn.Module): def __init__(self, in_channels, args): super(_Transition, self).__init__() self.pool = nn.AvgPool2d(kernel_size=2, stride=2) def forward(self, x): x = self.pool(x) return x class CondenseNet(nn.Module): def __init__(self, args): super(CondenseNet, self).__init__() self.stages = args.stages self.growth = args.growth assert len(self.stages) == len(self.growth) self.args = args self.progress = 0.0 if args.data in ['cifar10', 'cifar100']: self.init_stride = 1 self.pool_size = 8 else: self.init_stride = 2 self.pool_size = 7 self.features = nn.Sequential() ### Initial nChannels should be 3 self.num_features = 2 * self.growth[0] ### Dense-block 1 (224x224) self.features.add_module('init_conv', nn.Conv2d(3, self.num_features, kernel_size=3, stride=self.init_stride, padding=1, bias=False)) for i in range(len(self.stages)): ### Dense-block i self.add_block(i) ### Linear layer self.classifier = nn.Linear(self.num_features, args.num_classes) ### initialize for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.bias.data.zero_() return def add_block(self, i): ### Check if ith is the last one last = (i == len(self.stages) - 1) block = _DenseBlock( num_layers=self.stages[i], in_channels=self.num_features, growth_rate=self.growth[i], args=self.args, ) self.features.add_module('denseblock_%d' % (i + 1), block) self.num_features += self.stages[i] * self.growth[i] if not last: trans = _Transition(in_channels=self.num_features, args=self.args) self.features.add_module('transition_%d' % (i + 1), trans) else: self.features.add_module('norm_last', nn.BatchNorm2d(self.num_features)) self.features.add_module('relu_last', nn.ReLU(inplace=True)) self.features.add_module('pool_last', nn.AvgPool2d(self.pool_size)) def forward(self, x, progress=None): if progress: LearnedGroupConv.global_progress = progress features = self.features(x) out = features.view(features.size(0), -1) out = self.classifier(out) return out
modles/condensenet.py
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import math #https://github.com/ShichenLiu/CondenseNet class LearnedGroupConv(nn.Module): global_progress = 0.0 def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, condense_factor=None, dropout_rate=0.): super(LearnedGroupConv, self).__init__() self.norm = nn.BatchNorm2d(in_channels) self.relu = nn.ReLU(inplace=True) self.dropout_rate = dropout_rate if self.dropout_rate > 0: self.drop = nn.Dropout(dropout_rate, inplace=False) self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups=1, bias=False) self.in_channels = in_channels self.out_channels = out_channels self.groups = groups self.condense_factor = condense_factor if self.condense_factor is None: self.condense_factor = self.groups ### Parameters that should be carefully used self.register_buffer('_count', torch.zeros(1)) self.register_buffer('_stage', torch.zeros(1)) self.register_buffer('_mask', torch.ones(self.conv.weight.size())) ### Check if arguments are valid assert self.in_channels % self.groups == 0, "group number can not be divided by input channels" assert self.in_channels % self.condense_factor == 0, "condensation factor can not be divided by input channels" assert self.out_channels % self.groups == 0, "group number can not be divided by output channels" def forward(self, x): self._check_drop() x = self.norm(x) x = self.relu(x) if self.dropout_rate > 0: x = self.drop(x) ### Masked output weight = self.conv.weight * self.mask return F.conv2d(x, weight, None, self.conv.stride, self.conv.padding, self.conv.dilation, 1) def _check_drop(self): progress = LearnedGroupConv.global_progress delta = 0 ### Get current stage for i in range(self.condense_factor - 1): if progress * 2 < (i + 1) / (self.condense_factor - 1): stage = i break else: stage = self.condense_factor - 1 ### Check for dropping if not self._reach_stage(stage): self.stage = stage delta = self.in_channels // self.condense_factor if delta > 0: self._dropping(delta) return def _dropping(self, delta): weight = self.conv.weight * self.mask ### Sum up all kernels ### Assume only apply to 1x1 conv to speed up assert weight.size()[-1] == 1 weight = weight.abs().squeeze() assert weight.size()[0] == self.out_channels assert weight.size()[1] == self.in_channels d_out = self.out_channels // self.groups ### Shuffle weight weight = weight.view(d_out, self.groups, self.in_channels) weight = weight.transpose(0, 1).contiguous() weight = weight.view(self.out_channels, self.in_channels) ### Sort and drop for i in range(self.groups): wi = weight[i * d_out:(i + 1) * d_out, :] ### Take corresponding delta index di = wi.sum(0).sort()[1][self.count:self.count + delta] for d in di.data: self._mask[i::self.groups, d, :, :].fill_(0) self.count = self.count + delta @property def count(self): return int(self._count[0]) @count.setter def count(self, val): self._count.fill_(val) @property def stage(self): return int(self._stage[0]) @stage.setter def stage(self, val): self._stage.fill_(val) @property def mask(self): return Variable(self._mask) def _reach_stage(self, stage): return (self._stage >= stage).all() @property def lasso_loss(self): if self._reach_stage(self.groups - 1): return 0 weight = self.conv.weight * self.mask ### Assume only apply to 1x1 conv to speed up assert weight.size()[-1] == 1 weight = weight.squeeze().pow(2) d_out = self.out_channels // self.groups ### Shuffle weight weight = weight.view(d_out, self.groups, self.in_channels) weight = weight.sum(0).clamp(min=1e-6).sqrt() return weight.sum() def ShuffleLayer(x, groups): batchsize, num_channels, height, width = x.data.size() channels_per_group = num_channels // groups ### reshape x = x.view(batchsize, groups, channels_per_group, height, width) ### transpose x = torch.transpose(x, 1, 2).contiguous() ### flatten x = x.view(batchsize, -1, height, width) return x class CondensingLinear(nn.Module): def __init__(self, model, drop_rate=0.5): super(CondensingLinear, self).__init__() self.in_features = int(model.in_features*drop_rate) self.out_features = model.out_features self.linear = nn.Linear(self.in_features, self.out_features) self.register_buffer('index', torch.LongTensor(self.in_features)) _, index = model.weight.data.abs().sum(0).sort() index = index[model.in_features-self.in_features:] self.linear.bias.data = model.bias.data.clone() for i in range(self.in_features): self.index[i] = index[i] self.linear.weight.data[:, i] = model.weight.data[:, index[i]] def forward(self, x): x = torch.index_select(x, 1, Variable(self.index)) x = self.linear(x) return x class CondensingConv(nn.Module): def __init__(self, model): super(CondensingConv, self).__init__() self.in_channels = model.conv.in_channels \ * model.groups // model.condense_factor self.out_channels = model.conv.out_channels self.groups = model.groups self.condense_factor = model.condense_factor self.norm = nn.BatchNorm2d(self.in_channels) self.relu = nn.ReLU(inplace=True) self.conv = nn.Conv2d(self.in_channels, self.out_channels, kernel_size=model.conv.kernel_size, padding=model.conv.padding, groups=self.groups, bias=False, stride=model.conv.stride) self.register_buffer('index', torch.LongTensor(self.in_channels)) index = 0 mask = model._mask.mean(-1).mean(-1) for i in range(self.groups): for j in range(model.conv.in_channels): if index < (self.in_channels // self.groups) * (i + 1) \ and mask[i, j] == 1: for k in range(self.out_channels // self.groups): idx_i = int(k + i * (self.out_channels // self.groups)) idx_j = index % (self.in_channels // self.groups) self.conv.weight.data[idx_i, idx_j, :, :] = \ model.conv.weight.data[int(i + k * self.groups), j, :, :] self.norm.weight.data[index] = model.norm.weight.data[j] self.norm.bias.data[index] = model.norm.bias.data[j] self.norm.running_mean[index] = model.norm.running_mean[j] self.norm.running_var[index] = model.norm.running_var[j] self.index[index] = j index += 1 def forward(self, x): x = torch.index_select(x, 1, Variable(self.index)) x = self.norm(x) x = self.relu(x) x = self.conv(x) x = ShuffleLayer(x, self.groups) return x class CondenseLinear(nn.Module): def __init__(self, in_features, out_features, drop_rate=0.5): super(CondenseLinear, self).__init__() self.in_features = int(in_features*drop_rate) self.out_features = out_features self.linear = nn.Linear(self.in_features, self.out_features) self.register_buffer('index', torch.LongTensor(self.in_features)) def forward(self, x): x = torch.index_select(x, 1, Variable(self.index)) x = self.linear(x) return x class CondenseConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1): super(CondenseConv, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.groups = groups self.norm = nn.BatchNorm2d(self.in_channels) self.relu = nn.ReLU(inplace=True) self.conv = nn.Conv2d(self.in_channels, self.out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=self.groups, bias=False) self.register_buffer('index', torch.LongTensor(self.in_channels)) self.index.fill_(0) def forward(self, x): x = torch.index_select(x, 1, Variable(self.index)) x = self.norm(x) x = self.relu(x) x = self.conv(x) x = ShuffleLayer(x, self.groups) return x class Conv(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1): super(Conv, self).__init__() self.add_module('norm', nn.BatchNorm2d(in_channels)) self.add_module('relu', nn.ReLU(inplace=True)) self.add_module('conv', nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=False, groups=groups)) __all__ = ['CondenseNet'] class _DenseLayer(nn.Module): def __init__(self, in_channels, growth_rate, args): super(_DenseLayer, self).__init__() self.group_1x1 = args.group_1x1 self.group_3x3 = args.group_3x3 ### 1x1 conv i --> b*k self.conv_1 = LearnedGroupConv(in_channels, args.bottleneck * growth_rate, kernel_size=1, groups=self.group_1x1, condense_factor=args.condense_factor, dropout_rate=args.dropout_rate) ### 3x3 conv b*k --> k self.conv_2 = Conv(args.bottleneck * growth_rate, growth_rate, kernel_size=3, padding=1, groups=self.group_3x3) def forward(self, x): x_ = x x = self.conv_1(x) x = self.conv_2(x) return torch.cat([x_, x], 1) class _DenseBlock(nn.Sequential): def __init__(self, num_layers, in_channels, growth_rate, args): super(_DenseBlock, self).__init__() for i in range(num_layers): layer = _DenseLayer(in_channels + i * growth_rate, growth_rate, args) self.add_module('denselayer_%d' % (i + 1), layer) class _Transition(nn.Module): def __init__(self, in_channels, args): super(_Transition, self).__init__() self.pool = nn.AvgPool2d(kernel_size=2, stride=2) def forward(self, x): x = self.pool(x) return x class CondenseNet(nn.Module): def __init__(self, args): super(CondenseNet, self).__init__() self.stages = args.stages self.growth = args.growth assert len(self.stages) == len(self.growth) self.args = args self.progress = 0.0 if args.data in ['cifar10', 'cifar100']: self.init_stride = 1 self.pool_size = 8 else: self.init_stride = 2 self.pool_size = 7 self.features = nn.Sequential() ### Initial nChannels should be 3 self.num_features = 2 * self.growth[0] ### Dense-block 1 (224x224) self.features.add_module('init_conv', nn.Conv2d(3, self.num_features, kernel_size=3, stride=self.init_stride, padding=1, bias=False)) for i in range(len(self.stages)): ### Dense-block i self.add_block(i) ### Linear layer self.classifier = nn.Linear(self.num_features, args.num_classes) ### initialize for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.bias.data.zero_() return def add_block(self, i): ### Check if ith is the last one last = (i == len(self.stages) - 1) block = _DenseBlock( num_layers=self.stages[i], in_channels=self.num_features, growth_rate=self.growth[i], args=self.args, ) self.features.add_module('denseblock_%d' % (i + 1), block) self.num_features += self.stages[i] * self.growth[i] if not last: trans = _Transition(in_channels=self.num_features, args=self.args) self.features.add_module('transition_%d' % (i + 1), trans) else: self.features.add_module('norm_last', nn.BatchNorm2d(self.num_features)) self.features.add_module('relu_last', nn.ReLU(inplace=True)) self.features.add_module('pool_last', nn.AvgPool2d(self.pool_size)) def forward(self, x, progress=None): if progress: LearnedGroupConv.global_progress = progress features = self.features(x) out = features.view(features.size(0), -1) out = self.classifier(out) return out
0.939157
0.36659
import random import json from pygame.locals import * import os import pygame import pygameMenu from pygameMenu.locals import * WIDTH = 900 HEIGHT = 700 FPS = 60 pygame.init() os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("The Defender") clock = pygame.time.Clock() font_name = pygame.font.match_font('arial') def pontuacao(surf, text,size,x,y): font = pygame.font.Font(font_name,size) text_surface = font.render(text,True, (255,0,0)) text_rect = text_surface.get_rect() text_rect.midtop = (x,y) surf.blit(text_surface,text_rect) class Score(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.score = 0 self.dificuldade =1 def update(self): self.score += 1 if self.score ==10: self.dificuldade = 4 print(self.dificuldade) if self.score ==30: self.dificuldade = 6 print(self.dificuldade) if self.score == 70: self.dificuldade = 8 print(self.dificuldade) if self.score == 100: self.dificuldade = 10 print(self.dificuldade) if self.score == 130: self.dificuldade = 14 print(self.dificuldade) if self.score == 200: self.dificuldade = 18 print(self.dificuldade) class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('oldplayer.PNG') self.rect = self.image.get_rect() self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 self.col0 = 0 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -8 if keystate[pygame.K_RIGHT]: self.speedx = 8 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): pts = Score() if pts.score == 200: if self.col0 == 0: bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) self.col0 = 100 else: bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) if self.col0 > 0 : self.col0 -=1 class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('inimigo.PNG') self.image= pygame .transform.scale(self.image,(120,80)) self.rect = self.image.get_rect() self.rect.x = random.randrange(100 , 800) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 4) if self.rect.x < WIDTH/2: self.speedx = random.randrange(0, 1) else: self.speedx = random.randrange(-1, 0) def update(self): self.rect.x += self.speedx self.rect.y += self.speedy if self.rect.top > HEIGHT - 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 2) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('tiro.PNG') self.rect = self.image.get_rect() self.rect.bottom = y self.rect.centerx = x self.speedy = -10 def update(self): self.rect.y += self.speedy if self.rect.bottom < 0: self.kill() audio=pygame.mixer.Sound('boom.wav') audio_tiro= pygame.mixer.Sound('disparo.wav') audio_jogo = pygame.mixer.Sound('tema.wav') audio_gameOver = pygame.mixer.Sound('gameOver.wav') font = pygame.font.get_default_font() font2= pygame.font.SysFont(font,70) pygame.font.init() try: abre=open('pontuação.json','r') Mpts = json.load(abre) abre.close() except: Mpts = 0 coracao = pygame.image.load('vida.PNG') coracao = pygame.transform.scale(coracao,(30,20)) bg = pygame.image.load('fundo.PNG') bg = pygame.transform.scale(bg,(WIDTH,HEIGHT)) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() all_sprites.add(player) def jogo(): vida =3 score = 0 pts = Score() running = True col =0 col2 =0 audio_jogo.play(3) while running: if col2 == 0: for i in range(pts.dificuldade): m = Mob() all_sprites.add(m) mobs.add(m) mobs.draw(screen) col2 = 100 if pts.dificuldade == 8: col2 = 150 if pts.dificuldade == 14: col2 = 200 clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if pts.score == 200: pygame.key.set_repeat(10,50) press = pygame.key.get_pressed() if col == 0: if press[pygame.K_SPACE]: audio_tiro.play() player.shoot() col = 1000 elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: audio_tiro.play() player.shoot() all_sprites.update() hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: pts.update() score = pts.score hits = pygame.sprite.spritecollide(player, mobs, True) for hit in hits: audio.play() if hits: vida -= 1 if vida == 0: if score > Mpts: abre = open('pontuação.json','w') abre.write(str(score)) abre.close() running = False audio_jogo.stop() audio_gameOver.play(3) show_go_screen(score,Mpts,) if col >0: col -=0.1 if col2 >0: col2 -= 1 screen.blit(bg,(0,0)) screen.blit(coracao,(WIDTH/2 -400, 10)) all_sprites.draw(screen) pontuacao(screen,"PONTUAÇÃO: ", 18, WIDTH/2 -100, 10) pontuacao(screen, str(score),18,WIDTH/2 -30,10 ) pontuacao(screen,str(vida), 18, WIDTH/2 -360, 10) pontuacao(screen,"MELHOR PONTUAÇÃO:", 18, WIDTH/2 +250, 10) pontuacao(screen,str(Mpts), 18, WIDTH/2 +380, 10) pygame.display.flip() pygame.quit() def draw_text(surf, text, size, x, y): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, (255,255,255)) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) surf.blit(text_surface, text_rect) def draw_gameOver(surf, text, size, x, y): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, (255,0,0)) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) surf.blit(text_surface, text_rect) def show_go_screen(score,Mpts): screen.fill((0,0,0)) draw_gameOver(screen, 'Game Over',64,WIDTH/2,HEIGHT/4) draw_text(screen, 'Pontuação',25,WIDTH/2 -100,HEIGHT/4 + 100) draw_text(screen, str(score),25,WIDTH/2 -100,HEIGHT/4 + 150) if score > Mpts: draw_text(screen, 'Nova Melhor Pontuação',25,WIDTH/2 +100,HEIGHT/4 + 100) draw_text(screen, str(score),25,WIDTH/2 +100,HEIGHT/4 + 150) else: draw_text(screen, 'Melhor Pontuação',25,WIDTH/2 +100,HEIGHT/4 + 100) draw_text(screen, str(Mpts),25,WIDTH/2 +100,HEIGHT/4 + 150) draw_text(screen, 'Precione Esc para sair!',18,WIDTH/2,HEIGHT/4 + 450) draw_text(screen, 'Desenvolvido por: <NAME> e <NAME>',18,WIDTH/2 + 250,HEIGHT/4 + 500) pygame.display.flip() true = True while true: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() COLOR_BACKGROUND = (0, 0, 0) COLOR_BLACK = (0, 0, 0) COLOR_WHITE = (255, 255, 255) FPS = 60.0 MENU_BACKGROUND_COLOR = (3, 64, 137) WINDOW_SIZE = (WIDTH, HEIGHT) # ----------------------------------------------------------------------------- # Init pygame pygame.init() os.environ['SDL_VIDEO_CENTERED'] = '1' # Create pygame screen and objects surface = pygame.display.set_mode(WINDOW_SIZE) pygame.display.set_caption('MENU INICIAL') clock = pygame.time.Clock() dt = 1 / FPS def play_function(): jogo() main_menu.disable() main_menu.reset(1) while True: clock.tick(60) # Application events events = pygame.event.get() for e in events: if e.type == QUIT: exit() elif e.type == KEYDOWN: if e.key == K_ESCAPE and main_menu.is_disabled(): main_menu.enable() return main_menu.mainloop(events) pygame.display.flip() def main_background(): surface.fill(COLOR_BACKGROUND) # PLAY MENU play_menu= pygameMenu.Menu(surface, bgfun=main_background, color_selected=COLOR_WHITE, font=pygameMenu.fonts.FONT_BEBAS, font_color=COLOR_BLACK, font_size=30, menu_alpha=100, menu_color=MENU_BACKGROUND_COLOR, menu_height=int(WINDOW_SIZE[1]*1), menu_width=int(WINDOW_SIZE[0] *1), onclose=PYGAME_MENU_DISABLE_CLOSE, option_shadow=False, title='The defender', window_height=WINDOW_SIZE[1], window_width=WINDOW_SIZE[0] ) play_menu.add_option('Iniciar', play_function) play_menu.add_option('Retornar ao menu principal', PYGAME_MENU_BACK) # MAIN MENU main_menu = pygameMenu.Menu(surface, bgfun=main_background, color_selected=COLOR_WHITE, font=pygameMenu.fonts.FONT_BEBAS, font_color=COLOR_BLACK, font_size=30, menu_alpha=100, menu_color=MENU_BACKGROUND_COLOR, menu_height=int(WINDOW_SIZE[1] * 1), menu_width=int(WINDOW_SIZE[0] * 1), option_shadow= False, title='The defender', window_height=WINDOW_SIZE[1], window_width=WINDOW_SIZE[0] ) main_menu.add_option('Jogar', play_menu) main_menu.add_option('Sair', PYGAME_MENU_EXIT) # ----------------------------------------------------------------------------- # Main loop def menu(): while True: # Tick clock.tick(60) # Application events events = pygame.event.get() for event in events: if event.type == QUIT: exit() # Main menu main_menu.mainloop(events) # Flip surface pygame.display.flip() menu()
The Defender.py
import random import json from pygame.locals import * import os import pygame import pygameMenu from pygameMenu.locals import * WIDTH = 900 HEIGHT = 700 FPS = 60 pygame.init() os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("The Defender") clock = pygame.time.Clock() font_name = pygame.font.match_font('arial') def pontuacao(surf, text,size,x,y): font = pygame.font.Font(font_name,size) text_surface = font.render(text,True, (255,0,0)) text_rect = text_surface.get_rect() text_rect.midtop = (x,y) surf.blit(text_surface,text_rect) class Score(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.score = 0 self.dificuldade =1 def update(self): self.score += 1 if self.score ==10: self.dificuldade = 4 print(self.dificuldade) if self.score ==30: self.dificuldade = 6 print(self.dificuldade) if self.score == 70: self.dificuldade = 8 print(self.dificuldade) if self.score == 100: self.dificuldade = 10 print(self.dificuldade) if self.score == 130: self.dificuldade = 14 print(self.dificuldade) if self.score == 200: self.dificuldade = 18 print(self.dificuldade) class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('oldplayer.PNG') self.rect = self.image.get_rect() self.rect.centerx = WIDTH / 2 self.rect.bottom = HEIGHT - 10 self.speedx = 0 self.col0 = 0 def update(self): self.speedx = 0 keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.speedx = -8 if keystate[pygame.K_RIGHT]: self.speedx = 8 self.rect.x += self.speedx if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.left < 0: self.rect.left = 0 def shoot(self): pts = Score() if pts.score == 200: if self.col0 == 0: bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) self.col0 = 100 else: bullet = Bullet(self.rect.centerx, self.rect.top) all_sprites.add(bullet) bullets.add(bullet) if self.col0 > 0 : self.col0 -=1 class Mob(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('inimigo.PNG') self.image= pygame .transform.scale(self.image,(120,80)) self.rect = self.image.get_rect() self.rect.x = random.randrange(100 , 800) self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 4) if self.rect.x < WIDTH/2: self.speedx = random.randrange(0, 1) else: self.speedx = random.randrange(-1, 0) def update(self): self.rect.x += self.speedx self.rect.y += self.speedy if self.rect.top > HEIGHT - 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20: self.rect.y = random.randrange(-100, -40) self.speedy = random.randrange(1, 2) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('tiro.PNG') self.rect = self.image.get_rect() self.rect.bottom = y self.rect.centerx = x self.speedy = -10 def update(self): self.rect.y += self.speedy if self.rect.bottom < 0: self.kill() audio=pygame.mixer.Sound('boom.wav') audio_tiro= pygame.mixer.Sound('disparo.wav') audio_jogo = pygame.mixer.Sound('tema.wav') audio_gameOver = pygame.mixer.Sound('gameOver.wav') font = pygame.font.get_default_font() font2= pygame.font.SysFont(font,70) pygame.font.init() try: abre=open('pontuação.json','r') Mpts = json.load(abre) abre.close() except: Mpts = 0 coracao = pygame.image.load('vida.PNG') coracao = pygame.transform.scale(coracao,(30,20)) bg = pygame.image.load('fundo.PNG') bg = pygame.transform.scale(bg,(WIDTH,HEIGHT)) all_sprites = pygame.sprite.Group() mobs = pygame.sprite.Group() bullets = pygame.sprite.Group() player = Player() all_sprites.add(player) def jogo(): vida =3 score = 0 pts = Score() running = True col =0 col2 =0 audio_jogo.play(3) while running: if col2 == 0: for i in range(pts.dificuldade): m = Mob() all_sprites.add(m) mobs.add(m) mobs.draw(screen) col2 = 100 if pts.dificuldade == 8: col2 = 150 if pts.dificuldade == 14: col2 = 200 clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if pts.score == 200: pygame.key.set_repeat(10,50) press = pygame.key.get_pressed() if col == 0: if press[pygame.K_SPACE]: audio_tiro.play() player.shoot() col = 1000 elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: audio_tiro.play() player.shoot() all_sprites.update() hits = pygame.sprite.groupcollide(mobs, bullets, True, True) for hit in hits: pts.update() score = pts.score hits = pygame.sprite.spritecollide(player, mobs, True) for hit in hits: audio.play() if hits: vida -= 1 if vida == 0: if score > Mpts: abre = open('pontuação.json','w') abre.write(str(score)) abre.close() running = False audio_jogo.stop() audio_gameOver.play(3) show_go_screen(score,Mpts,) if col >0: col -=0.1 if col2 >0: col2 -= 1 screen.blit(bg,(0,0)) screen.blit(coracao,(WIDTH/2 -400, 10)) all_sprites.draw(screen) pontuacao(screen,"PONTUAÇÃO: ", 18, WIDTH/2 -100, 10) pontuacao(screen, str(score),18,WIDTH/2 -30,10 ) pontuacao(screen,str(vida), 18, WIDTH/2 -360, 10) pontuacao(screen,"MELHOR PONTUAÇÃO:", 18, WIDTH/2 +250, 10) pontuacao(screen,str(Mpts), 18, WIDTH/2 +380, 10) pygame.display.flip() pygame.quit() def draw_text(surf, text, size, x, y): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, (255,255,255)) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) surf.blit(text_surface, text_rect) def draw_gameOver(surf, text, size, x, y): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, (255,0,0)) text_rect = text_surface.get_rect() text_rect.midtop = (x, y) surf.blit(text_surface, text_rect) def show_go_screen(score,Mpts): screen.fill((0,0,0)) draw_gameOver(screen, 'Game Over',64,WIDTH/2,HEIGHT/4) draw_text(screen, 'Pontuação',25,WIDTH/2 -100,HEIGHT/4 + 100) draw_text(screen, str(score),25,WIDTH/2 -100,HEIGHT/4 + 150) if score > Mpts: draw_text(screen, 'Nova Melhor Pontuação',25,WIDTH/2 +100,HEIGHT/4 + 100) draw_text(screen, str(score),25,WIDTH/2 +100,HEIGHT/4 + 150) else: draw_text(screen, 'Melhor Pontuação',25,WIDTH/2 +100,HEIGHT/4 + 100) draw_text(screen, str(Mpts),25,WIDTH/2 +100,HEIGHT/4 + 150) draw_text(screen, 'Precione Esc para sair!',18,WIDTH/2,HEIGHT/4 + 450) draw_text(screen, 'Desenvolvido por: <NAME> e <NAME>',18,WIDTH/2 + 250,HEIGHT/4 + 500) pygame.display.flip() true = True while true: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() COLOR_BACKGROUND = (0, 0, 0) COLOR_BLACK = (0, 0, 0) COLOR_WHITE = (255, 255, 255) FPS = 60.0 MENU_BACKGROUND_COLOR = (3, 64, 137) WINDOW_SIZE = (WIDTH, HEIGHT) # ----------------------------------------------------------------------------- # Init pygame pygame.init() os.environ['SDL_VIDEO_CENTERED'] = '1' # Create pygame screen and objects surface = pygame.display.set_mode(WINDOW_SIZE) pygame.display.set_caption('MENU INICIAL') clock = pygame.time.Clock() dt = 1 / FPS def play_function(): jogo() main_menu.disable() main_menu.reset(1) while True: clock.tick(60) # Application events events = pygame.event.get() for e in events: if e.type == QUIT: exit() elif e.type == KEYDOWN: if e.key == K_ESCAPE and main_menu.is_disabled(): main_menu.enable() return main_menu.mainloop(events) pygame.display.flip() def main_background(): surface.fill(COLOR_BACKGROUND) # PLAY MENU play_menu= pygameMenu.Menu(surface, bgfun=main_background, color_selected=COLOR_WHITE, font=pygameMenu.fonts.FONT_BEBAS, font_color=COLOR_BLACK, font_size=30, menu_alpha=100, menu_color=MENU_BACKGROUND_COLOR, menu_height=int(WINDOW_SIZE[1]*1), menu_width=int(WINDOW_SIZE[0] *1), onclose=PYGAME_MENU_DISABLE_CLOSE, option_shadow=False, title='The defender', window_height=WINDOW_SIZE[1], window_width=WINDOW_SIZE[0] ) play_menu.add_option('Iniciar', play_function) play_menu.add_option('Retornar ao menu principal', PYGAME_MENU_BACK) # MAIN MENU main_menu = pygameMenu.Menu(surface, bgfun=main_background, color_selected=COLOR_WHITE, font=pygameMenu.fonts.FONT_BEBAS, font_color=COLOR_BLACK, font_size=30, menu_alpha=100, menu_color=MENU_BACKGROUND_COLOR, menu_height=int(WINDOW_SIZE[1] * 1), menu_width=int(WINDOW_SIZE[0] * 1), option_shadow= False, title='The defender', window_height=WINDOW_SIZE[1], window_width=WINDOW_SIZE[0] ) main_menu.add_option('Jogar', play_menu) main_menu.add_option('Sair', PYGAME_MENU_EXIT) # ----------------------------------------------------------------------------- # Main loop def menu(): while True: # Tick clock.tick(60) # Application events events = pygame.event.get() for event in events: if event.type == QUIT: exit() # Main menu main_menu.mainloop(events) # Flip surface pygame.display.flip() menu()
0.139338
0.116362
from flask import Flask from {{cookiecutter.app_name}} import auth, api from {{cookiecutter.app_name}}.extensions import db, jwt, migrate, apispec {%- if cookiecutter.use_celery == "yes"%}, celery{% endif%} def create_app(testing=False, cli=False): """Application factory, used to create application""" app = Flask("{{cookiecutter.app_name}}") app.config.from_object("{{cookiecutter.app_name}}.config") if testing is True: app.config["TESTING"] = True configure_extensions(app, cli) configure_apispec(app) register_blueprints(app) {%- if cookiecutter.use_celery == "yes" %} init_celery(app) {%- endif %} return app def configure_extensions(app, cli): """configure flask extensions""" db.init_app(app) jwt.init_app(app) if cli is True: migrate.init_app(app, db) def configure_apispec(app): """Configure APISpec for swagger support""" apispec.init_app(app, security=[{"jwt": []}]) apispec.spec.components.security_scheme( "jwt", {"type": "http", "scheme": "bearer", "bearerFormat": "JWT"} ) apispec.spec.components.schema( "PaginatedResult", { "properties": { "total": {"type": "integer"}, "pages": {"type": "integer"}, "next": {"type": "string"}, "prev": {"type": "string"}, } }, ) def register_blueprints(app): """register all blueprints for application""" app.register_blueprint(auth.views.blueprint) app.register_blueprint(api.views.blueprint) {%- if cookiecutter.use_celery == "yes" %} def init_celery(app=None): app = app or create_app() celery.conf.update(app.config.get("CELERY", {})) class ContextTask(celery.Task): """Make celery tasks work with Flask app context""" def __call__(self, *args, **kwargs): with app.app_context(): return self.run(*args, **kwargs) celery.Task = ContextTask return celery {%- endif %}
{{cookiecutter.project_name}}/{{cookiecutter.app_name}}/app.py
from flask import Flask from {{cookiecutter.app_name}} import auth, api from {{cookiecutter.app_name}}.extensions import db, jwt, migrate, apispec {%- if cookiecutter.use_celery == "yes"%}, celery{% endif%} def create_app(testing=False, cli=False): """Application factory, used to create application""" app = Flask("{{cookiecutter.app_name}}") app.config.from_object("{{cookiecutter.app_name}}.config") if testing is True: app.config["TESTING"] = True configure_extensions(app, cli) configure_apispec(app) register_blueprints(app) {%- if cookiecutter.use_celery == "yes" %} init_celery(app) {%- endif %} return app def configure_extensions(app, cli): """configure flask extensions""" db.init_app(app) jwt.init_app(app) if cli is True: migrate.init_app(app, db) def configure_apispec(app): """Configure APISpec for swagger support""" apispec.init_app(app, security=[{"jwt": []}]) apispec.spec.components.security_scheme( "jwt", {"type": "http", "scheme": "bearer", "bearerFormat": "JWT"} ) apispec.spec.components.schema( "PaginatedResult", { "properties": { "total": {"type": "integer"}, "pages": {"type": "integer"}, "next": {"type": "string"}, "prev": {"type": "string"}, } }, ) def register_blueprints(app): """register all blueprints for application""" app.register_blueprint(auth.views.blueprint) app.register_blueprint(api.views.blueprint) {%- if cookiecutter.use_celery == "yes" %} def init_celery(app=None): app = app or create_app() celery.conf.update(app.config.get("CELERY", {})) class ContextTask(celery.Task): """Make celery tasks work with Flask app context""" def __call__(self, *args, **kwargs): with app.app_context(): return self.run(*args, **kwargs) celery.Task = ContextTask return celery {%- endif %}
0.532425
0.093347
import copy from cinderclient import exceptions as cinder_exp import mock from oslo_config import cfg import six from heat.common import exception from heat.common import template_format from heat.engine.clients.os import cinder from heat.engine.clients.os import nova from heat.engine.resources.aws.ec2 import instance from heat.engine.resources.aws.ec2 import volume as aws_vol from heat.engine import rsrc_defn from heat.engine import scheduler from heat.tests.openstack.cinder import test_volume_utils as vt_base from heat.tests.openstack.nova import fakes as fakes_nova from heat.tests import utils volume_template = ''' { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "Volume Test", "Parameters" : {}, "Resources" : { "WikiDatabase": { "Type": "AWS::EC2::Instance", "Properties": { "ImageId" : "foo", "InstanceType" : "m1.large", "KeyName" : "test", "UserData" : "some data" } }, "DataVolume" : { "Type" : "AWS::EC2::Volume", "Properties" : { "Size" : "1", "AvailabilityZone" : {"Fn::GetAtt": ["WikiDatabase", "AvailabilityZone"]}, "Tags" : [{ "Key" : "Usage", "Value" : "Wiki Data Volume" }] } }, "MountPoint" : { "Type" : "AWS::EC2::VolumeAttachment", "Properties" : { "InstanceId" : { "Ref" : "WikiDatabase" }, "VolumeId" : { "Ref" : "DataVolume" }, "Device" : "/dev/vdc" } } } } ''' class VolumeTest(vt_base.VolumeTestCase): def setUp(self): super(VolumeTest, self).setUp() self.t = template_format.parse(volume_template) self.use_cinder = False def _mock_create_volume(self, fv, stack_name, final_status='available', mock_attachment=None): self.vol_name = utils.PhysName(stack_name, 'DataVolume') self.stack_name = stack_name self.cinder_fc.volumes.create.return_value = vt_base.FakeVolume(fv) fv_ready = vt_base.FakeVolume(final_status, id=fv.id) if mock_attachment is not None: results = [fv, fv_ready, mock_attachment] else: results = [fv, fv_ready, vt_base.FakeVolume('in-use')] self.cinder_fc.volumes.get.side_effect = results return fv_ready def test_volume(self): stack_name = 'test_volume_create_stack' # create script fv = self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name) # delete script self._mock_delete_volume(fv) stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') # delete script self._mock_delete_volume(fv) ex = self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(rsrc.destroy)) self.assertIn("Volume in use", six.text_type(ex)) self.cinder_fc.volumes.get.side_effect = [ vt_base.FakeVolume('available'), cinder_exp.NotFound('Not found')] scheduler.TaskRunner(rsrc.destroy)() def test_volume_default_az(self): fv = vt_base.FakeVolume('creating') stack_name = 'test_volume_defaultaz_stack' # create script self.patchobject(instance.Instance, 'handle_create') self.patchobject(instance.Instance, 'check_create_complete', return_value=True) self.patchobject(instance.Instance, '_resolve_attribute', return_value=None) self.patchobject(aws_vol.VolumeAttachment, 'handle_create') self.patchobject(aws_vol.VolumeAttachment, 'check_create_complete', return_value=True) cinder.CinderClientPlugin._create.return_value = self.cinder_fc self.stub_ImageConstraint_validate() self.stub_ServerConstraint_validate() self.stub_VolumeConstraint_validate() vol_name = utils.PhysName(stack_name, 'DataVolume') self.cinder_fc.volumes.create.return_value = fv fv_ready = vt_base.FakeVolume('available', id=fv.id) self.cinder_fc.volumes.get.side_effect = [ fv, fv_ready, cinder_exp.NotFound('Not found')] # delete script cookie = object() self.patchobject(instance.Instance, 'handle_delete') self.patchobject(aws_vol.VolumeAttachment, 'handle_delete', return_value=cookie) self.patchobject(aws_vol.VolumeAttachment, 'check_delete_complete', return_value=True) stack = utils.parse_stack(self.t, stack_name=stack_name) stack._update_all_resource_data(True, False) rsrc = stack['DataVolume'] self.assertIsNone(rsrc.validate()) scheduler.TaskRunner(stack.create)() self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state) scheduler.TaskRunner(stack.delete)() instance.Instance._resolve_attribute.assert_called_with( 'AvailabilityZone') self.cinder_fc.volumes.create.assert_called_once_with( size=1, availability_zone=None, description=vol_name, name=vol_name, metadata={u'Usage': u'Wiki Data Volume'}) self.cinder_fc.volumes.get.assert_called_with('vol-123') aws_vol.VolumeAttachment.check_delete_complete.assert_called_once_with( cookie) def test_volume_create_error(self): fv = vt_base.FakeVolume('creating') stack_name = 'test_volume_create_error_stack' cfg.CONF.set_override('action_retry_limit', 0) self._mock_create_volume(fv, stack_name, final_status='error') stack = utils.parse_stack(self.t, stack_name=stack_name) ex = self.assertRaises(exception.ResourceFailure, self.create_volume, self.t, stack, 'DataVolume') self.assertIn('Went to status error due to "Unknown"', six.text_type(ex)) def test_volume_bad_tags(self): stack_name = 'test_volume_bad_tags_stack' self.t['Resources']['DataVolume']['Properties'][ 'Tags'] = [{'Foo': 'bar'}] stack = utils.parse_stack(self.t, stack_name=stack_name) ex = self.assertRaises(exception.StackValidationFailed, self.create_volume, self.t, stack, 'DataVolume') self.assertEqual("Property error: " "Resources.DataVolume.Properties.Tags[0]: " "Unknown Property Foo", six.text_type(ex)) def test_volume_attachment_error(self): stack_name = 'test_volume_attach_error_stack' mock_attachment = self._mock_create_server_volume_script( vt_base.FakeVolume('attaching'), final_status='error') self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, mock_attachment=mock_attachment ) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') ex = self.assertRaises(exception.ResourceFailure, self.create_attachment, self.t, stack, 'MountPoint') self.assertIn("Volume attachment failed - Unknown status error", six.text_type(ex)) self.validate_mock_create_server_volume_script() def test_volume_attachment(self): stack_name = 'test_volume_attach_stack' fva = self._mock_create_server_volume_script( vt_base.FakeVolume('attaching')) self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, mock_attachment=fva) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script fva = vt_base.FakeVolume('in-use') self.cinder_fc.volumes.get.side_effect = [ fva, vt_base.FakeVolume('detaching', id=fva.id), vt_base.FakeVolume('available', id=fva.id) ] self.fc.volumes.delete_server_volume.return_value = None self.fc.volumes.get_server_volume.side_effect = [ fva, fva, fakes_nova.fake_exception()] scheduler.TaskRunner(rsrc.delete)() self.fc.volumes.get_server_volume.assert_called_with(u'WikiDatabase', 'vol-123') self.fc.volumes.delete_server_volume.assert_called_with( 'WikiDatabase', 'vol-123') self.fc.volumes.get_server_volume.assert_called_with( u'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_detachment_err(self): stack_name = 'test_volume_detach_err_stack' fva = self._mock_create_server_volume_script( vt_base.FakeVolume('attaching')) self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, mock_attachment=fva) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script fva = vt_base.FakeVolume('in-use') self.fc.volumes.get_server_volume.side_effect = [ fva, fva, fakes_nova.fake_exception()] self.cinder_fc.volumes.get.side_effect = [ fva, vt_base.FakeVolume('available', id=fva.id)] exc = fakes_nova.fake_exception(400) self.fc.volumes.delete_server_volume.side_effect = exc scheduler.TaskRunner(rsrc.delete)() self.fc.volumes.get_server_volume.assert_called_with( u'WikiDatabase', 'vol-123') self.fc.volumes.delete_server_volume.assert_called_once_with( 'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_detach_non_exist(self): fv = vt_base.FakeVolume('creating') fva = vt_base.FakeVolume('in-use') stack_name = 'test_volume_detach_nonexist_stack' mock_attachment = self._mock_create_server_volume_script(fva) self._mock_create_volume(fv, stack_name, mock_attachment=mock_attachment) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script self.fc.volumes.delete_server_volume.return_value = None self.cinder_fc.volumes.get.side_effect = cinder_exp.NotFound( 'Not found') exc = fakes_nova.fake_exception() self.fc.volumes.get_server_volume.side_effect = exc scheduler.TaskRunner(rsrc.delete)() self.fc.volumes.delete_server_volume.assert_called_once_with( u'WikiDatabase', 'vol-123') self.fc.volumes.get_server_volume.assert_called_with( u'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_detach_deleting_volume(self): fv = vt_base.FakeVolume('creating') fva = vt_base.FakeVolume('deleting') stack_name = 'test_volume_detach_deleting_volume_stack' mock_attachment = self._mock_create_server_volume_script(fva) self._mock_create_volume(fv, stack_name, mock_attachment=mock_attachment) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script self.cinder_fc.volumes.get.side_effect = [fva] exc = fakes_nova.fake_exception() self.fc.volumes.get_server_volume.side_effect = exc scheduler.TaskRunner(rsrc.delete)() self.fc.volumes.delete_server_volume.assert_called_once_with( u'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_detach_with_latency(self): stack_name = 'test_volume_detach_latency_stack' fva = self._mock_create_server_volume_script( vt_base.FakeVolume('attaching')) self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, mock_attachment=fva) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script self.fc.volumes.get_server_volume.side_effect = [ fva, fva, fakes_nova.fake_exception()] self.cinder_fc.volumes.get.side_effect = [ fva, vt_base.FakeVolume('in-use', id=fva.id), vt_base.FakeVolume('detaching', id=fva.id), vt_base.FakeVolume('available', id=fva.id)] scheduler.TaskRunner(rsrc.delete)() self.fc.volumes.delete_server_volume.assert_called_once_with( u'WikiDatabase', 'vol-123') self.fc.volumes.get_server_volume.assert_called_with( u'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_detach_with_error(self): stack_name = 'test_volume_detach_werr_stack' fva = self._mock_create_server_volume_script( vt_base.FakeVolume('attaching')) self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, mock_attachment=fva) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script self.fc.volumes.delete_server_volume.return_value = None fva = vt_base.FakeVolume('in-use') self.cinder_fc.volumes.get.side_effect = [ vt_base.FakeVolume('error', id=fva.id)] detach_task = scheduler.TaskRunner(rsrc.delete) ex = self.assertRaises(exception.ResourceFailure, detach_task) self.assertIn('Volume detachment failed - Unknown status error', six.text_type(ex)) self.fc.volumes.delete_server_volume.assert_called_once_with( u'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_delete(self): stack_name = 'test_volume_delete_stack' fv = vt_base.FakeVolume('creating') self._mock_create_volume(fv, stack_name) self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Delete' stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') m_hd = mock.Mock(return_value=None) rsrc.handle_delete = m_hd m_cdc = mock.Mock(return_value=True) rsrc.check_delete_complete = m_cdc scheduler.TaskRunner(rsrc.destroy)() m_cdc.assert_called_with(None) m_hd.assert_called_once_with() def test_volume_deleting_delete(self): vt_base.FakeVolume('creating') stack_name = 'test_volume_deleting_stack' self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name) stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') self.assertEqual(2, self.cinder_fc.volumes.get.call_count) # delete script self.cinder_fc.volumes.get.side_effect = [ vt_base.FakeVolume('deleting'), vt_base.FakeVolume('deleting'), cinder_exp.NotFound('NotFound')] scheduler.TaskRunner(rsrc.destroy)() self.assertEqual(5, self.cinder_fc.volumes.get.call_count) def test_volume_delete_error(self): fv = vt_base.FakeVolume('creating') stack_name = 'test_volume_deleting_stack' fv = self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name) stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') self.assertEqual(2, self.cinder_fc.volumes.get.call_count) self.cinder_fc.volumes.get.side_effect = [ fv, vt_base.FakeVolume('deleting'), vt_base.FakeVolume('error_deleting')] self.cinder_fc.volumes.delete.return_value = True deleter = scheduler.TaskRunner(rsrc.destroy) self.assertRaisesRegex(exception.ResourceFailure, ".*ResourceInError.*error_deleting.*delete", deleter) self.cinder_fc.volumes.delete.assert_called_once_with(fv.id) self.assertEqual(5, self.cinder_fc.volumes.get.call_count) def test_volume_update_not_supported(self): stack_name = 'test_volume_updnotsup_stack' fv = vt_base.FakeVolume('creating') self._mock_create_volume(fv, stack_name) t = template_format.parse(volume_template) stack = utils.parse_stack(t, stack_name=stack_name) rsrc = self.create_volume(t, stack, 'DataVolume') props = copy.deepcopy(rsrc.properties.data) props['Size'] = 2 props['Tags'] = None props['AvailabilityZone'] = 'other' after = rsrc_defn.ResourceDefinition(rsrc.name, rsrc.type(), props) updater = scheduler.TaskRunner(rsrc.update, after) ex = self.assertRaises(exception.ResourceFailure, updater) self.assertIn("NotSupported: resources.DataVolume: " "Update to properties " "AvailabilityZone, Size, Tags of DataVolume " "(AWS::EC2::Volume) is not supported", six.text_type(ex)) self.assertEqual((rsrc.UPDATE, rsrc.FAILED), rsrc.state) def test_volume_check(self): stack = utils.parse_stack(self.t, stack_name='volume_check') res = stack['DataVolume'] res.state_set(res.CREATE, res.COMPLETE) fake_volume = vt_base.FakeVolume('available') cinder = mock.Mock() cinder.volumes.get.return_value = fake_volume self.patchobject(res, 'client', return_value=cinder) scheduler.TaskRunner(res.check)() self.assertEqual((res.CHECK, res.COMPLETE), res.state) fake_volume = vt_base.FakeVolume('in-use') res.client().volumes.get.return_value = fake_volume scheduler.TaskRunner(res.check)() self.assertEqual((res.CHECK, res.COMPLETE), res.state) def test_volume_check_not_available(self): stack = utils.parse_stack(self.t, stack_name='volume_check_na') res = stack['DataVolume'] res.state_set(res.CREATE, res.COMPLETE) cinder = mock.Mock() fake_volume = vt_base.FakeVolume('foobar') cinder.volumes.get.return_value = fake_volume self.patchobject(res, 'client', return_value=cinder) self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(res.check)) self.assertEqual((res.CHECK, res.FAILED), res.state) self.assertIn('foobar', res.status_reason) def test_volume_check_fail(self): stack = utils.parse_stack(self.t, stack_name='volume_check_fail') res = stack['DataVolume'] res.state_set(res.CREATE, res.COMPLETE) cinder = mock.Mock() cinder.volumes.get.side_effect = Exception('boom') self.patchobject(res, 'client', return_value=cinder) self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(res.check)) self.assertEqual((res.CHECK, res.FAILED), res.state) self.assertIn('boom', res.status_reason) def test_snapshot(self): stack_name = 'test_volume_snapshot_stack' fv = vt_base.FakeVolume('creating') fv_ready = vt_base.FakeVolume('available', id=fv.id) fv = self._mock_create_volume(fv, stack_name, mock_attachment=fv_ready) # snapshot script fb = vt_base.FakeBackup('available') self.m_backups.create.return_value = fb self.m_backups.get.return_value = fb self._mock_delete_volume(fv) self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Snapshot' stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') self.cinder_fc.volumes.get.side_effect = [ fv, vt_base.FakeVolume('available'), cinder_exp.NotFound('Not found') ] scheduler.TaskRunner(rsrc.destroy)() self.m_backups.create.assert_called_once_with(fv.id) self.m_backups.get.assert_called_once_with(fb.id) def test_snapshot_error(self): stack_name = 'test_volume_snapshot_err_stack' fv = self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name) # snapshot script fb = vt_base.FakeBackup('error') self.m_backups.create.return_value = fb self.m_backups.get.return_value = fb self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Snapshot' stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') ex = self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(rsrc.destroy)) self.assertIn('Unknown status error', six.text_type(ex)) self.m_backups.create.assert_called_once_with(fv.id) self.m_backups.get.assert_called_once_with(fb.id) def test_snapshot_no_volume(self): """Test that backup does not start for failed resource.""" stack_name = 'test_volume_snapshot_novol_stack' cfg.CONF.set_override('action_retry_limit', 0) fva = vt_base.FakeVolume('error') fv = self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, final_status='error', mock_attachment=fva) self._mock_delete_volume(fv) self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Snapshot' self.t['Resources']['DataVolume']['Properties'][ 'AvailabilityZone'] = 'nova' stack = utils.parse_stack(self.t, stack_name=stack_name) resource_defns = stack.t.resource_definitions(stack) rsrc = aws_vol.Volume('DataVolume', resource_defns['DataVolume'], stack) create = scheduler.TaskRunner(rsrc.create) ex = self.assertRaises(exception.ResourceFailure, create) self.assertIn('Went to status error due to "Unknown"', six.text_type(ex)) self.cinder_fc.volumes.get.side_effect = [ fva, cinder_exp.NotFound('Not found') ] scheduler.TaskRunner(rsrc.destroy)() def test_create_from_snapshot(self): stack_name = 'test_volume_create_from_snapshot_stack' fv = vt_base.FakeVolume('restoring-backup') fvbr = vt_base.FakeBackupRestore('vol-123') # create script cinder.CinderClientPlugin._create.return_value = self.cinder_fc self.m_restore.return_value = fvbr fv2 = vt_base.FakeVolume('available') self.cinder_fc.volumes.get.side_effect = [fv, fv2] vol_name = utils.PhysName(stack_name, 'DataVolume') self.t['Resources']['DataVolume']['Properties'][ 'SnapshotId'] = 'backup-123' stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume', no_create=True) cinder.CinderClientPlugin._create.assert_called_once_with() self.m_restore.assert_called_once_with('backup-123') self.cinder_fc.volumes.get.assert_called_with('vol-123') self.cinder_fc.volumes.update.assert_called_once_with( 'vol-123', description=vol_name, name=vol_name) def test_create_from_snapshot_error(self): stack_name = 'test_volume_create_from_snap_err_stack' cfg.CONF.set_override('action_retry_limit', 0) fv = vt_base.FakeVolume('restoring-backup') fv2 = vt_base.FakeVolume('error') fvbr = vt_base.FakeBackupRestore('vol-123') # create script cinder.CinderClientPlugin._create.return_value = self.cinder_fc self.m_restore.return_value = fvbr self.cinder_fc.volumes.get.side_effect = [fv, fv2] vol_name = utils.PhysName(stack_name, 'DataVolume') self.t['Resources']['DataVolume']['Properties'][ 'SnapshotId'] = 'backup-123' stack = utils.parse_stack(self.t, stack_name=stack_name) ex = self.assertRaises(exception.ResourceFailure, self.create_volume, self.t, stack, 'DataVolume') self.assertIn('Went to status error due to "Unknown"', six.text_type(ex)) cinder.CinderClientPlugin._create.assert_called_once_with() self.m_restore.assert_called_once_with('backup-123') self.cinder_fc.volumes.update.assert_called_once_with( fv.id, description=vol_name, name=vol_name) def test_volume_size_constraint(self): self.t['Resources']['DataVolume']['Properties']['Size'] = '0' stack = utils.parse_stack(self.t) error = self.assertRaises(exception.StackValidationFailed, self.create_volume, self.t, stack, 'DataVolume') self.assertEqual( "Property error: Resources.DataVolume.Properties.Size: " "0 is out of range (min: 1, max: None)", six.text_type(error)) def test_volume_attachment_updates_not_supported(self): self.patchobject(nova.NovaClientPlugin, 'get_server') fv = vt_base.FakeVolume('creating') fva = vt_base.FakeVolume('attaching') stack_name = 'test_volume_attach_updnotsup_stack' mock_create_server_volume = self._mock_create_server_volume_script(fva) self._mock_create_volume(fv, stack_name, mock_attachment=mock_create_server_volume) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') props = copy.deepcopy(rsrc.properties.data) props['InstanceId'] = 'some_other_instance_id' props['VolumeId'] = 'some_other_volume_id' props['Device'] = '/dev/vdz' after = rsrc_defn.ResourceDefinition(rsrc.name, rsrc.type(), props) update_task = scheduler.TaskRunner(rsrc.update, after) ex = self.assertRaises(exception.ResourceFailure, update_task) self.assertIn('NotSupported: resources.MountPoint: ' 'Update to properties Device, InstanceId, ' 'VolumeId of MountPoint (AWS::EC2::VolumeAttachment)', six.text_type(ex)) self.assertEqual((rsrc.UPDATE, rsrc.FAILED), rsrc.state) self.validate_mock_create_server_volume_script() def test_validate_deletion_policy(self): cfg.CONF.set_override('backups_enabled', False, group='volumes') stack_name = 'test_volume_validate_deletion_policy' self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Snapshot' stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.get_volume(self.t, stack, 'DataVolume') self.assertRaisesRegex( exception.StackValidationFailed, 'volume backup service is not enabled', rsrc.validate)
heat/tests/aws/test_volume.py
import copy from cinderclient import exceptions as cinder_exp import mock from oslo_config import cfg import six from heat.common import exception from heat.common import template_format from heat.engine.clients.os import cinder from heat.engine.clients.os import nova from heat.engine.resources.aws.ec2 import instance from heat.engine.resources.aws.ec2 import volume as aws_vol from heat.engine import rsrc_defn from heat.engine import scheduler from heat.tests.openstack.cinder import test_volume_utils as vt_base from heat.tests.openstack.nova import fakes as fakes_nova from heat.tests import utils volume_template = ''' { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "Volume Test", "Parameters" : {}, "Resources" : { "WikiDatabase": { "Type": "AWS::EC2::Instance", "Properties": { "ImageId" : "foo", "InstanceType" : "m1.large", "KeyName" : "test", "UserData" : "some data" } }, "DataVolume" : { "Type" : "AWS::EC2::Volume", "Properties" : { "Size" : "1", "AvailabilityZone" : {"Fn::GetAtt": ["WikiDatabase", "AvailabilityZone"]}, "Tags" : [{ "Key" : "Usage", "Value" : "Wiki Data Volume" }] } }, "MountPoint" : { "Type" : "AWS::EC2::VolumeAttachment", "Properties" : { "InstanceId" : { "Ref" : "WikiDatabase" }, "VolumeId" : { "Ref" : "DataVolume" }, "Device" : "/dev/vdc" } } } } ''' class VolumeTest(vt_base.VolumeTestCase): def setUp(self): super(VolumeTest, self).setUp() self.t = template_format.parse(volume_template) self.use_cinder = False def _mock_create_volume(self, fv, stack_name, final_status='available', mock_attachment=None): self.vol_name = utils.PhysName(stack_name, 'DataVolume') self.stack_name = stack_name self.cinder_fc.volumes.create.return_value = vt_base.FakeVolume(fv) fv_ready = vt_base.FakeVolume(final_status, id=fv.id) if mock_attachment is not None: results = [fv, fv_ready, mock_attachment] else: results = [fv, fv_ready, vt_base.FakeVolume('in-use')] self.cinder_fc.volumes.get.side_effect = results return fv_ready def test_volume(self): stack_name = 'test_volume_create_stack' # create script fv = self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name) # delete script self._mock_delete_volume(fv) stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') # delete script self._mock_delete_volume(fv) ex = self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(rsrc.destroy)) self.assertIn("Volume in use", six.text_type(ex)) self.cinder_fc.volumes.get.side_effect = [ vt_base.FakeVolume('available'), cinder_exp.NotFound('Not found')] scheduler.TaskRunner(rsrc.destroy)() def test_volume_default_az(self): fv = vt_base.FakeVolume('creating') stack_name = 'test_volume_defaultaz_stack' # create script self.patchobject(instance.Instance, 'handle_create') self.patchobject(instance.Instance, 'check_create_complete', return_value=True) self.patchobject(instance.Instance, '_resolve_attribute', return_value=None) self.patchobject(aws_vol.VolumeAttachment, 'handle_create') self.patchobject(aws_vol.VolumeAttachment, 'check_create_complete', return_value=True) cinder.CinderClientPlugin._create.return_value = self.cinder_fc self.stub_ImageConstraint_validate() self.stub_ServerConstraint_validate() self.stub_VolumeConstraint_validate() vol_name = utils.PhysName(stack_name, 'DataVolume') self.cinder_fc.volumes.create.return_value = fv fv_ready = vt_base.FakeVolume('available', id=fv.id) self.cinder_fc.volumes.get.side_effect = [ fv, fv_ready, cinder_exp.NotFound('Not found')] # delete script cookie = object() self.patchobject(instance.Instance, 'handle_delete') self.patchobject(aws_vol.VolumeAttachment, 'handle_delete', return_value=cookie) self.patchobject(aws_vol.VolumeAttachment, 'check_delete_complete', return_value=True) stack = utils.parse_stack(self.t, stack_name=stack_name) stack._update_all_resource_data(True, False) rsrc = stack['DataVolume'] self.assertIsNone(rsrc.validate()) scheduler.TaskRunner(stack.create)() self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state) scheduler.TaskRunner(stack.delete)() instance.Instance._resolve_attribute.assert_called_with( 'AvailabilityZone') self.cinder_fc.volumes.create.assert_called_once_with( size=1, availability_zone=None, description=vol_name, name=vol_name, metadata={u'Usage': u'Wiki Data Volume'}) self.cinder_fc.volumes.get.assert_called_with('vol-123') aws_vol.VolumeAttachment.check_delete_complete.assert_called_once_with( cookie) def test_volume_create_error(self): fv = vt_base.FakeVolume('creating') stack_name = 'test_volume_create_error_stack' cfg.CONF.set_override('action_retry_limit', 0) self._mock_create_volume(fv, stack_name, final_status='error') stack = utils.parse_stack(self.t, stack_name=stack_name) ex = self.assertRaises(exception.ResourceFailure, self.create_volume, self.t, stack, 'DataVolume') self.assertIn('Went to status error due to "Unknown"', six.text_type(ex)) def test_volume_bad_tags(self): stack_name = 'test_volume_bad_tags_stack' self.t['Resources']['DataVolume']['Properties'][ 'Tags'] = [{'Foo': 'bar'}] stack = utils.parse_stack(self.t, stack_name=stack_name) ex = self.assertRaises(exception.StackValidationFailed, self.create_volume, self.t, stack, 'DataVolume') self.assertEqual("Property error: " "Resources.DataVolume.Properties.Tags[0]: " "Unknown Property Foo", six.text_type(ex)) def test_volume_attachment_error(self): stack_name = 'test_volume_attach_error_stack' mock_attachment = self._mock_create_server_volume_script( vt_base.FakeVolume('attaching'), final_status='error') self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, mock_attachment=mock_attachment ) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') ex = self.assertRaises(exception.ResourceFailure, self.create_attachment, self.t, stack, 'MountPoint') self.assertIn("Volume attachment failed - Unknown status error", six.text_type(ex)) self.validate_mock_create_server_volume_script() def test_volume_attachment(self): stack_name = 'test_volume_attach_stack' fva = self._mock_create_server_volume_script( vt_base.FakeVolume('attaching')) self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, mock_attachment=fva) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script fva = vt_base.FakeVolume('in-use') self.cinder_fc.volumes.get.side_effect = [ fva, vt_base.FakeVolume('detaching', id=fva.id), vt_base.FakeVolume('available', id=fva.id) ] self.fc.volumes.delete_server_volume.return_value = None self.fc.volumes.get_server_volume.side_effect = [ fva, fva, fakes_nova.fake_exception()] scheduler.TaskRunner(rsrc.delete)() self.fc.volumes.get_server_volume.assert_called_with(u'WikiDatabase', 'vol-123') self.fc.volumes.delete_server_volume.assert_called_with( 'WikiDatabase', 'vol-123') self.fc.volumes.get_server_volume.assert_called_with( u'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_detachment_err(self): stack_name = 'test_volume_detach_err_stack' fva = self._mock_create_server_volume_script( vt_base.FakeVolume('attaching')) self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, mock_attachment=fva) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script fva = vt_base.FakeVolume('in-use') self.fc.volumes.get_server_volume.side_effect = [ fva, fva, fakes_nova.fake_exception()] self.cinder_fc.volumes.get.side_effect = [ fva, vt_base.FakeVolume('available', id=fva.id)] exc = fakes_nova.fake_exception(400) self.fc.volumes.delete_server_volume.side_effect = exc scheduler.TaskRunner(rsrc.delete)() self.fc.volumes.get_server_volume.assert_called_with( u'WikiDatabase', 'vol-123') self.fc.volumes.delete_server_volume.assert_called_once_with( 'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_detach_non_exist(self): fv = vt_base.FakeVolume('creating') fva = vt_base.FakeVolume('in-use') stack_name = 'test_volume_detach_nonexist_stack' mock_attachment = self._mock_create_server_volume_script(fva) self._mock_create_volume(fv, stack_name, mock_attachment=mock_attachment) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script self.fc.volumes.delete_server_volume.return_value = None self.cinder_fc.volumes.get.side_effect = cinder_exp.NotFound( 'Not found') exc = fakes_nova.fake_exception() self.fc.volumes.get_server_volume.side_effect = exc scheduler.TaskRunner(rsrc.delete)() self.fc.volumes.delete_server_volume.assert_called_once_with( u'WikiDatabase', 'vol-123') self.fc.volumes.get_server_volume.assert_called_with( u'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_detach_deleting_volume(self): fv = vt_base.FakeVolume('creating') fva = vt_base.FakeVolume('deleting') stack_name = 'test_volume_detach_deleting_volume_stack' mock_attachment = self._mock_create_server_volume_script(fva) self._mock_create_volume(fv, stack_name, mock_attachment=mock_attachment) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script self.cinder_fc.volumes.get.side_effect = [fva] exc = fakes_nova.fake_exception() self.fc.volumes.get_server_volume.side_effect = exc scheduler.TaskRunner(rsrc.delete)() self.fc.volumes.delete_server_volume.assert_called_once_with( u'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_detach_with_latency(self): stack_name = 'test_volume_detach_latency_stack' fva = self._mock_create_server_volume_script( vt_base.FakeVolume('attaching')) self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, mock_attachment=fva) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script self.fc.volumes.get_server_volume.side_effect = [ fva, fva, fakes_nova.fake_exception()] self.cinder_fc.volumes.get.side_effect = [ fva, vt_base.FakeVolume('in-use', id=fva.id), vt_base.FakeVolume('detaching', id=fva.id), vt_base.FakeVolume('available', id=fva.id)] scheduler.TaskRunner(rsrc.delete)() self.fc.volumes.delete_server_volume.assert_called_once_with( u'WikiDatabase', 'vol-123') self.fc.volumes.get_server_volume.assert_called_with( u'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_detach_with_error(self): stack_name = 'test_volume_detach_werr_stack' fva = self._mock_create_server_volume_script( vt_base.FakeVolume('attaching')) self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, mock_attachment=fva) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') # delete script self.fc.volumes.delete_server_volume.return_value = None fva = vt_base.FakeVolume('in-use') self.cinder_fc.volumes.get.side_effect = [ vt_base.FakeVolume('error', id=fva.id)] detach_task = scheduler.TaskRunner(rsrc.delete) ex = self.assertRaises(exception.ResourceFailure, detach_task) self.assertIn('Volume detachment failed - Unknown status error', six.text_type(ex)) self.fc.volumes.delete_server_volume.assert_called_once_with( u'WikiDatabase', 'vol-123') self.validate_mock_create_server_volume_script() def test_volume_delete(self): stack_name = 'test_volume_delete_stack' fv = vt_base.FakeVolume('creating') self._mock_create_volume(fv, stack_name) self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Delete' stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') m_hd = mock.Mock(return_value=None) rsrc.handle_delete = m_hd m_cdc = mock.Mock(return_value=True) rsrc.check_delete_complete = m_cdc scheduler.TaskRunner(rsrc.destroy)() m_cdc.assert_called_with(None) m_hd.assert_called_once_with() def test_volume_deleting_delete(self): vt_base.FakeVolume('creating') stack_name = 'test_volume_deleting_stack' self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name) stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') self.assertEqual(2, self.cinder_fc.volumes.get.call_count) # delete script self.cinder_fc.volumes.get.side_effect = [ vt_base.FakeVolume('deleting'), vt_base.FakeVolume('deleting'), cinder_exp.NotFound('NotFound')] scheduler.TaskRunner(rsrc.destroy)() self.assertEqual(5, self.cinder_fc.volumes.get.call_count) def test_volume_delete_error(self): fv = vt_base.FakeVolume('creating') stack_name = 'test_volume_deleting_stack' fv = self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name) stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') self.assertEqual(2, self.cinder_fc.volumes.get.call_count) self.cinder_fc.volumes.get.side_effect = [ fv, vt_base.FakeVolume('deleting'), vt_base.FakeVolume('error_deleting')] self.cinder_fc.volumes.delete.return_value = True deleter = scheduler.TaskRunner(rsrc.destroy) self.assertRaisesRegex(exception.ResourceFailure, ".*ResourceInError.*error_deleting.*delete", deleter) self.cinder_fc.volumes.delete.assert_called_once_with(fv.id) self.assertEqual(5, self.cinder_fc.volumes.get.call_count) def test_volume_update_not_supported(self): stack_name = 'test_volume_updnotsup_stack' fv = vt_base.FakeVolume('creating') self._mock_create_volume(fv, stack_name) t = template_format.parse(volume_template) stack = utils.parse_stack(t, stack_name=stack_name) rsrc = self.create_volume(t, stack, 'DataVolume') props = copy.deepcopy(rsrc.properties.data) props['Size'] = 2 props['Tags'] = None props['AvailabilityZone'] = 'other' after = rsrc_defn.ResourceDefinition(rsrc.name, rsrc.type(), props) updater = scheduler.TaskRunner(rsrc.update, after) ex = self.assertRaises(exception.ResourceFailure, updater) self.assertIn("NotSupported: resources.DataVolume: " "Update to properties " "AvailabilityZone, Size, Tags of DataVolume " "(AWS::EC2::Volume) is not supported", six.text_type(ex)) self.assertEqual((rsrc.UPDATE, rsrc.FAILED), rsrc.state) def test_volume_check(self): stack = utils.parse_stack(self.t, stack_name='volume_check') res = stack['DataVolume'] res.state_set(res.CREATE, res.COMPLETE) fake_volume = vt_base.FakeVolume('available') cinder = mock.Mock() cinder.volumes.get.return_value = fake_volume self.patchobject(res, 'client', return_value=cinder) scheduler.TaskRunner(res.check)() self.assertEqual((res.CHECK, res.COMPLETE), res.state) fake_volume = vt_base.FakeVolume('in-use') res.client().volumes.get.return_value = fake_volume scheduler.TaskRunner(res.check)() self.assertEqual((res.CHECK, res.COMPLETE), res.state) def test_volume_check_not_available(self): stack = utils.parse_stack(self.t, stack_name='volume_check_na') res = stack['DataVolume'] res.state_set(res.CREATE, res.COMPLETE) cinder = mock.Mock() fake_volume = vt_base.FakeVolume('foobar') cinder.volumes.get.return_value = fake_volume self.patchobject(res, 'client', return_value=cinder) self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(res.check)) self.assertEqual((res.CHECK, res.FAILED), res.state) self.assertIn('foobar', res.status_reason) def test_volume_check_fail(self): stack = utils.parse_stack(self.t, stack_name='volume_check_fail') res = stack['DataVolume'] res.state_set(res.CREATE, res.COMPLETE) cinder = mock.Mock() cinder.volumes.get.side_effect = Exception('boom') self.patchobject(res, 'client', return_value=cinder) self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(res.check)) self.assertEqual((res.CHECK, res.FAILED), res.state) self.assertIn('boom', res.status_reason) def test_snapshot(self): stack_name = 'test_volume_snapshot_stack' fv = vt_base.FakeVolume('creating') fv_ready = vt_base.FakeVolume('available', id=fv.id) fv = self._mock_create_volume(fv, stack_name, mock_attachment=fv_ready) # snapshot script fb = vt_base.FakeBackup('available') self.m_backups.create.return_value = fb self.m_backups.get.return_value = fb self._mock_delete_volume(fv) self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Snapshot' stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') self.cinder_fc.volumes.get.side_effect = [ fv, vt_base.FakeVolume('available'), cinder_exp.NotFound('Not found') ] scheduler.TaskRunner(rsrc.destroy)() self.m_backups.create.assert_called_once_with(fv.id) self.m_backups.get.assert_called_once_with(fb.id) def test_snapshot_error(self): stack_name = 'test_volume_snapshot_err_stack' fv = self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name) # snapshot script fb = vt_base.FakeBackup('error') self.m_backups.create.return_value = fb self.m_backups.get.return_value = fb self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Snapshot' stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.create_volume(self.t, stack, 'DataVolume') ex = self.assertRaises(exception.ResourceFailure, scheduler.TaskRunner(rsrc.destroy)) self.assertIn('Unknown status error', six.text_type(ex)) self.m_backups.create.assert_called_once_with(fv.id) self.m_backups.get.assert_called_once_with(fb.id) def test_snapshot_no_volume(self): """Test that backup does not start for failed resource.""" stack_name = 'test_volume_snapshot_novol_stack' cfg.CONF.set_override('action_retry_limit', 0) fva = vt_base.FakeVolume('error') fv = self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name, final_status='error', mock_attachment=fva) self._mock_delete_volume(fv) self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Snapshot' self.t['Resources']['DataVolume']['Properties'][ 'AvailabilityZone'] = 'nova' stack = utils.parse_stack(self.t, stack_name=stack_name) resource_defns = stack.t.resource_definitions(stack) rsrc = aws_vol.Volume('DataVolume', resource_defns['DataVolume'], stack) create = scheduler.TaskRunner(rsrc.create) ex = self.assertRaises(exception.ResourceFailure, create) self.assertIn('Went to status error due to "Unknown"', six.text_type(ex)) self.cinder_fc.volumes.get.side_effect = [ fva, cinder_exp.NotFound('Not found') ] scheduler.TaskRunner(rsrc.destroy)() def test_create_from_snapshot(self): stack_name = 'test_volume_create_from_snapshot_stack' fv = vt_base.FakeVolume('restoring-backup') fvbr = vt_base.FakeBackupRestore('vol-123') # create script cinder.CinderClientPlugin._create.return_value = self.cinder_fc self.m_restore.return_value = fvbr fv2 = vt_base.FakeVolume('available') self.cinder_fc.volumes.get.side_effect = [fv, fv2] vol_name = utils.PhysName(stack_name, 'DataVolume') self.t['Resources']['DataVolume']['Properties'][ 'SnapshotId'] = 'backup-123' stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume', no_create=True) cinder.CinderClientPlugin._create.assert_called_once_with() self.m_restore.assert_called_once_with('backup-123') self.cinder_fc.volumes.get.assert_called_with('vol-123') self.cinder_fc.volumes.update.assert_called_once_with( 'vol-123', description=vol_name, name=vol_name) def test_create_from_snapshot_error(self): stack_name = 'test_volume_create_from_snap_err_stack' cfg.CONF.set_override('action_retry_limit', 0) fv = vt_base.FakeVolume('restoring-backup') fv2 = vt_base.FakeVolume('error') fvbr = vt_base.FakeBackupRestore('vol-123') # create script cinder.CinderClientPlugin._create.return_value = self.cinder_fc self.m_restore.return_value = fvbr self.cinder_fc.volumes.get.side_effect = [fv, fv2] vol_name = utils.PhysName(stack_name, 'DataVolume') self.t['Resources']['DataVolume']['Properties'][ 'SnapshotId'] = 'backup-123' stack = utils.parse_stack(self.t, stack_name=stack_name) ex = self.assertRaises(exception.ResourceFailure, self.create_volume, self.t, stack, 'DataVolume') self.assertIn('Went to status error due to "Unknown"', six.text_type(ex)) cinder.CinderClientPlugin._create.assert_called_once_with() self.m_restore.assert_called_once_with('backup-123') self.cinder_fc.volumes.update.assert_called_once_with( fv.id, description=vol_name, name=vol_name) def test_volume_size_constraint(self): self.t['Resources']['DataVolume']['Properties']['Size'] = '0' stack = utils.parse_stack(self.t) error = self.assertRaises(exception.StackValidationFailed, self.create_volume, self.t, stack, 'DataVolume') self.assertEqual( "Property error: Resources.DataVolume.Properties.Size: " "0 is out of range (min: 1, max: None)", six.text_type(error)) def test_volume_attachment_updates_not_supported(self): self.patchobject(nova.NovaClientPlugin, 'get_server') fv = vt_base.FakeVolume('creating') fva = vt_base.FakeVolume('attaching') stack_name = 'test_volume_attach_updnotsup_stack' mock_create_server_volume = self._mock_create_server_volume_script(fva) self._mock_create_volume(fv, stack_name, mock_attachment=mock_create_server_volume) self.stub_VolumeConstraint_validate() stack = utils.parse_stack(self.t, stack_name=stack_name) self.create_volume(self.t, stack, 'DataVolume') rsrc = self.create_attachment(self.t, stack, 'MountPoint') props = copy.deepcopy(rsrc.properties.data) props['InstanceId'] = 'some_other_instance_id' props['VolumeId'] = 'some_other_volume_id' props['Device'] = '/dev/vdz' after = rsrc_defn.ResourceDefinition(rsrc.name, rsrc.type(), props) update_task = scheduler.TaskRunner(rsrc.update, after) ex = self.assertRaises(exception.ResourceFailure, update_task) self.assertIn('NotSupported: resources.MountPoint: ' 'Update to properties Device, InstanceId, ' 'VolumeId of MountPoint (AWS::EC2::VolumeAttachment)', six.text_type(ex)) self.assertEqual((rsrc.UPDATE, rsrc.FAILED), rsrc.state) self.validate_mock_create_server_volume_script() def test_validate_deletion_policy(self): cfg.CONF.set_override('backups_enabled', False, group='volumes') stack_name = 'test_volume_validate_deletion_policy' self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Snapshot' stack = utils.parse_stack(self.t, stack_name=stack_name) rsrc = self.get_volume(self.t, stack, 'DataVolume') self.assertRaisesRegex( exception.StackValidationFailed, 'volume backup service is not enabled', rsrc.validate)
0.485112
0.25682
import collections import itertools from textwrap import dedent import pytest import pytablewriter as ptw from ..._common import print_test_result from ...data import ( float_header_list, float_value_matrix, headers, mix_header_list, mix_value_matrix, value_matrix, value_matrix_iter, value_matrix_with_none, ) Data = collections.namedtuple("Data", "col_delim header value expected") normal_test_data_list = [ Data( col_delim=",", header=headers, value=value_matrix, expected=dedent( """\ "a","b","c","dd","e" 1,123.1,"a",1,1 2,2.2,"bb",2.2,2.2 3,3.3,"ccc",3,"cccc" """ ), ), Data( col_delim=",", header=headers, value=[], expected=dedent( """\ "a","b","c","dd","e" """ ), ), Data( col_delim=",", header=[], value=value_matrix, expected=dedent( """\ 1,123.1,"a",1,1 2,2.2,"bb",2.2,2.2 3,3.3,"ccc",3,"cccc" """ ), ), Data( col_delim="\t", header=None, value=value_matrix, expected=dedent( """\ 1\t123.1\t"a"\t1\t1 2\t2.2\t"bb"\t2.2\t2.2 3\t3.3\t"ccc"\t3\t"cccc" """ ), ), Data( col_delim=",", header=headers, value=value_matrix_with_none, expected=dedent( """\ "a","b","c","dd","e" 1,,"a",1, ,2.2,,2.2,2.2 3,3.3,"ccc",,"cccc" ,,,, """ ), ), Data( col_delim=",", header=mix_header_list, value=mix_value_matrix, expected=dedent( """\ "i","f","c","if","ifc","bool","inf","nan","mix_num","time" 1,1.1,"aa",1,1,True,Infinity,NaN,1,"2017-01-01T00:00:00" 2,2.2,"bbb",2.2,2.2,False,Infinity,NaN,Infinity,"2017-01-02 03:04:05+09:00" 3,3.33,"cccc",-3,"ccc",True,Infinity,NaN,NaN,"2017-01-01T00:00:00" """ ), ), Data( col_delim=",", header=float_header_list, value=float_value_matrix, expected=dedent( """\ "a","b","c" 0.01,0.00125,0 1,99.9,0.01 1.2,999999.123,0.001 """ ), ), Data( col_delim=",", header=["a\nb", "c\n\nd", "e\r\nf"], value=[["v1\nv1", "v2\n\nv2", "v3\r\nv3"]], expected=dedent( """\ "a b","c d","e f" "v1 v1","v2 v2","v3 v3" """ ), ), ] exception_test_data_list = [ Data(col_delim=",", header=header, value=value, expected=ptw.EmptyTableDataError) for header, value in itertools.product([None, [], ""], [None, [], ""]) ] table_writer_class = ptw.CsvTableWriter class Test_CsvTableWriter_table_format: def test_normal(self): assert table_writer_class().table_format is ptw.TableFormat.CSV class Test_CsvTableWriter_write_new_line: def test_normal(self, capsys): writer = table_writer_class() writer.write_null_line() out, _err = capsys.readouterr() assert out == "\n" class Test_CsvTableWriter_from_csv: __CSV_TEXT_INPUT = dedent( """\ "a","b","c","dd","e" 1,1.1,"a",1.0, 2,2.2,,2.2,"2.2" 3,3.3,"ccc",,"cc\ncc" """ ) __CSV_EXPECTED = dedent( """\ "a","b","c","dd","e" 1,1.1,"a",1, 2,2.2,,2.2,2.2 3,3.3,"ccc",,"cc cc" """ ) def test_normal_from_text(self, capsys): writer = table_writer_class() writer.from_csv(self.__CSV_TEXT_INPUT) writer.write_table() out, _err = capsys.readouterr() assert writer.table_name == "" assert writer.headers == ["a", "b", "c", "dd", "e"] print_test_result(expected=self.__CSV_EXPECTED, actual=out) assert out == self.__CSV_EXPECTED def test_normal_from_file(self, capsys, tmpdir): file_path = str(tmpdir.join("test_data.csv")) with open(file_path, "w", encoding="utf-8") as f: f.write(self.__CSV_TEXT_INPUT) writer = table_writer_class() writer.from_csv(file_path) writer.write_table() out, _err = capsys.readouterr() assert writer.table_name == "test_data" assert writer.headers == ["a", "b", "c", "dd", "e"] print_test_result(expected=self.__CSV_EXPECTED, actual=out) assert out == self.__CSV_EXPECTED class Test_CsvTableWriter_write_table: @pytest.mark.parametrize( ["col_delim", "header", "value", "expected"], [ [data.col_delim, data.header, data.value, data.expected] for data in normal_test_data_list ], ) def test_normal(self, capsys, col_delim, header, value, expected): writer = table_writer_class() writer.column_delimiter = col_delim writer.headers = header writer.value_matrix = value writer.write_table() out, err = capsys.readouterr() print_test_result(expected=expected, actual=out, error=err) assert out == expected assert writer.dumps() == expected assert str(writer) == expected def test_normal_escape_formula_injection(self, capsys): writer = table_writer_class() writer.headers = ["a", "b", "c", "d", "e"] writer.value_matrix = [["a+b", "=a+b", "-a+b", "+a+b", "@a+b"]] writer.update_preprocessor(is_escape_formula_injection=True) writer.write_table() expected = r""""a","b","c","d","e" "a+b","\"=a+b","\"-a+b","\"+a+b","\"@a+b" """ out, err = capsys.readouterr() print_test_result(expected=expected, actual=out, error=err) assert out == expected @pytest.mark.parametrize( ["header", "value", "expected"], [[data.header, data.value, data.expected] for data in exception_test_data_list], ) def test_exception(self, header, value, expected): writer = table_writer_class() writer.headers = header writer.value_matrix = value assert writer.dumps() == "" assert str(writer) == "" class Test_CsvTableWriter_write_table_iter: @pytest.mark.parametrize( ["table", "header", "value", "expected"], [ [ "tablename", ["ha", "hb", "hc"], value_matrix_iter, dedent( """\ "ha","hb","hc" 1,2,3 11,12,13 1,2,3 11,12,13 101,102,103 1001,1002,1003 """ ), ] ], ) def test_normal(self, capsys, table, header, value, expected): writer = table_writer_class() writer.table_name = table writer.headers = header writer.value_matrix = value writer.iteration_length = len(value) writer.write_table_iter() out, err = capsys.readouterr() print_test_result(expected=expected, actual=out, error=err) assert out == expected @pytest.mark.parametrize( ["header", "value", "expected"], [[data.header, data.value, data.expected] for data in exception_test_data_list], ) def test_smoke_empty(self, header, value, expected): writer = table_writer_class() writer.headers = header writer.value_matrix = value writer.write_table_iter()
test/writer/text/test_csv_writer.py
import collections import itertools from textwrap import dedent import pytest import pytablewriter as ptw from ..._common import print_test_result from ...data import ( float_header_list, float_value_matrix, headers, mix_header_list, mix_value_matrix, value_matrix, value_matrix_iter, value_matrix_with_none, ) Data = collections.namedtuple("Data", "col_delim header value expected") normal_test_data_list = [ Data( col_delim=",", header=headers, value=value_matrix, expected=dedent( """\ "a","b","c","dd","e" 1,123.1,"a",1,1 2,2.2,"bb",2.2,2.2 3,3.3,"ccc",3,"cccc" """ ), ), Data( col_delim=",", header=headers, value=[], expected=dedent( """\ "a","b","c","dd","e" """ ), ), Data( col_delim=",", header=[], value=value_matrix, expected=dedent( """\ 1,123.1,"a",1,1 2,2.2,"bb",2.2,2.2 3,3.3,"ccc",3,"cccc" """ ), ), Data( col_delim="\t", header=None, value=value_matrix, expected=dedent( """\ 1\t123.1\t"a"\t1\t1 2\t2.2\t"bb"\t2.2\t2.2 3\t3.3\t"ccc"\t3\t"cccc" """ ), ), Data( col_delim=",", header=headers, value=value_matrix_with_none, expected=dedent( """\ "a","b","c","dd","e" 1,,"a",1, ,2.2,,2.2,2.2 3,3.3,"ccc",,"cccc" ,,,, """ ), ), Data( col_delim=",", header=mix_header_list, value=mix_value_matrix, expected=dedent( """\ "i","f","c","if","ifc","bool","inf","nan","mix_num","time" 1,1.1,"aa",1,1,True,Infinity,NaN,1,"2017-01-01T00:00:00" 2,2.2,"bbb",2.2,2.2,False,Infinity,NaN,Infinity,"2017-01-02 03:04:05+09:00" 3,3.33,"cccc",-3,"ccc",True,Infinity,NaN,NaN,"2017-01-01T00:00:00" """ ), ), Data( col_delim=",", header=float_header_list, value=float_value_matrix, expected=dedent( """\ "a","b","c" 0.01,0.00125,0 1,99.9,0.01 1.2,999999.123,0.001 """ ), ), Data( col_delim=",", header=["a\nb", "c\n\nd", "e\r\nf"], value=[["v1\nv1", "v2\n\nv2", "v3\r\nv3"]], expected=dedent( """\ "a b","c d","e f" "v1 v1","v2 v2","v3 v3" """ ), ), ] exception_test_data_list = [ Data(col_delim=",", header=header, value=value, expected=ptw.EmptyTableDataError) for header, value in itertools.product([None, [], ""], [None, [], ""]) ] table_writer_class = ptw.CsvTableWriter class Test_CsvTableWriter_table_format: def test_normal(self): assert table_writer_class().table_format is ptw.TableFormat.CSV class Test_CsvTableWriter_write_new_line: def test_normal(self, capsys): writer = table_writer_class() writer.write_null_line() out, _err = capsys.readouterr() assert out == "\n" class Test_CsvTableWriter_from_csv: __CSV_TEXT_INPUT = dedent( """\ "a","b","c","dd","e" 1,1.1,"a",1.0, 2,2.2,,2.2,"2.2" 3,3.3,"ccc",,"cc\ncc" """ ) __CSV_EXPECTED = dedent( """\ "a","b","c","dd","e" 1,1.1,"a",1, 2,2.2,,2.2,2.2 3,3.3,"ccc",,"cc cc" """ ) def test_normal_from_text(self, capsys): writer = table_writer_class() writer.from_csv(self.__CSV_TEXT_INPUT) writer.write_table() out, _err = capsys.readouterr() assert writer.table_name == "" assert writer.headers == ["a", "b", "c", "dd", "e"] print_test_result(expected=self.__CSV_EXPECTED, actual=out) assert out == self.__CSV_EXPECTED def test_normal_from_file(self, capsys, tmpdir): file_path = str(tmpdir.join("test_data.csv")) with open(file_path, "w", encoding="utf-8") as f: f.write(self.__CSV_TEXT_INPUT) writer = table_writer_class() writer.from_csv(file_path) writer.write_table() out, _err = capsys.readouterr() assert writer.table_name == "test_data" assert writer.headers == ["a", "b", "c", "dd", "e"] print_test_result(expected=self.__CSV_EXPECTED, actual=out) assert out == self.__CSV_EXPECTED class Test_CsvTableWriter_write_table: @pytest.mark.parametrize( ["col_delim", "header", "value", "expected"], [ [data.col_delim, data.header, data.value, data.expected] for data in normal_test_data_list ], ) def test_normal(self, capsys, col_delim, header, value, expected): writer = table_writer_class() writer.column_delimiter = col_delim writer.headers = header writer.value_matrix = value writer.write_table() out, err = capsys.readouterr() print_test_result(expected=expected, actual=out, error=err) assert out == expected assert writer.dumps() == expected assert str(writer) == expected def test_normal_escape_formula_injection(self, capsys): writer = table_writer_class() writer.headers = ["a", "b", "c", "d", "e"] writer.value_matrix = [["a+b", "=a+b", "-a+b", "+a+b", "@a+b"]] writer.update_preprocessor(is_escape_formula_injection=True) writer.write_table() expected = r""""a","b","c","d","e" "a+b","\"=a+b","\"-a+b","\"+a+b","\"@a+b" """ out, err = capsys.readouterr() print_test_result(expected=expected, actual=out, error=err) assert out == expected @pytest.mark.parametrize( ["header", "value", "expected"], [[data.header, data.value, data.expected] for data in exception_test_data_list], ) def test_exception(self, header, value, expected): writer = table_writer_class() writer.headers = header writer.value_matrix = value assert writer.dumps() == "" assert str(writer) == "" class Test_CsvTableWriter_write_table_iter: @pytest.mark.parametrize( ["table", "header", "value", "expected"], [ [ "tablename", ["ha", "hb", "hc"], value_matrix_iter, dedent( """\ "ha","hb","hc" 1,2,3 11,12,13 1,2,3 11,12,13 101,102,103 1001,1002,1003 """ ), ] ], ) def test_normal(self, capsys, table, header, value, expected): writer = table_writer_class() writer.table_name = table writer.headers = header writer.value_matrix = value writer.iteration_length = len(value) writer.write_table_iter() out, err = capsys.readouterr() print_test_result(expected=expected, actual=out, error=err) assert out == expected @pytest.mark.parametrize( ["header", "value", "expected"], [[data.header, data.value, data.expected] for data in exception_test_data_list], ) def test_smoke_empty(self, header, value, expected): writer = table_writer_class() writer.headers = header writer.value_matrix = value writer.write_table_iter()
0.378115
0.445047
import argparse import sys from pathlib import Path from typing import Callable, Dict from determined.common.declarative_argparse import Arg, BoolOptArg, Cmd, Group from . import cluster_utils from .preflight import check_docker_install def handle_cluster_up(args: argparse.Namespace) -> None: if not args.no_preflight_checks: check_docker_install() cluster_utils.cluster_up( num_agents=args.agents, port=args.master_port, master_config_path=args.master_config_path, storage_host_path=args.storage_host_path, cluster_name=args.cluster_name, image_repo_prefix=args.image_repo_prefix, version=args.det_version, db_password=<PASSWORD>, delete_db=args.delete_db, gpu=args.gpu, autorestart=(not args.no_autorestart), auto_work_dir=args.auto_work_dir, ) def handle_cluster_down(args: argparse.Namespace) -> None: cluster_utils.cluster_down(cluster_name=args.cluster_name, delete_db=args.delete_db) def handle_logs(args: argparse.Namespace) -> None: cluster_utils.logs(cluster_name=args.cluster_name, no_follow=args.no_follow) def handle_master_up(args: argparse.Namespace) -> None: cluster_utils.master_up( port=args.master_port, master_config_path=args.master_config_path, storage_host_path=args.storage_host_path, master_name=args.master_name, image_repo_prefix=args.image_repo_prefix, version=args.det_version, db_password=<PASSWORD>, delete_db=args.delete_db, autorestart=(not args.no_autorestart), cluster_name=args.cluster_name, auto_work_dir=args.auto_work_dir, ) def handle_master_down(args: argparse.Namespace) -> None: cluster_utils.master_down(master_name=args.master_name, delete_db=args.delete_db) def handle_agent_up(args: argparse.Namespace) -> None: cluster_utils.agent_up( master_host=args.master_host, master_port=args.master_port, agent_config_path=args.agent_config_path, gpu=args.gpu, agent_name=args.agent_name, agent_label=args.agent_label, agent_resource_pool=args.agent_resource_pool, image_repo_prefix=args.image_repo_prefix, version=args.det_version, labels=None, autorestart=(not args.no_autorestart), cluster_name=args.cluster_name, ) def handle_agent_down(args: argparse.Namespace) -> None: if args.all: cluster_utils.stop_all_agents() else: cluster_utils.stop_agent(agent_name=args.agent_name) def deploy_local(args: argparse.Namespace) -> None: OPERATION_TO_FN = { "agent-up": handle_agent_up, "agent-down": handle_agent_down, "cluster-up": handle_cluster_up, "cluster-down": handle_cluster_down, "logs": handle_logs, "master-up": handle_master_up, "master-down": handle_master_down, } # type: Dict[str, Callable[[argparse.Namespace], None]] OPERATION_TO_FN[args.command](args) args_description = Cmd( "local", None, "local help", [ Cmd( "cluster-up", handle_cluster_up, "Create a Determined cluster", [ Group( Arg( "--master-config-path", type=Path, default=None, help="path to master configuration", ), Arg( "--storage-host-path", type=Path, default=None, help="Storage location for cluster data (e.g. checkpoints)", ), ), Arg( "--agents", type=int, default=1, help="number of agents to start (on this machine)", ), Arg( "--master-port", type=int, default=cluster_utils.MASTER_PORT_DEFAULT, help="port to expose master on", ), Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), Arg("--det-version", type=str, default=None, help="version or commit to use"), Arg( "--db-password", type=str, default="<PASSWORD>", help="password for master database", ), Arg( "--delete-db", action="store_true", help="remove current master database", ), BoolOptArg( "--gpu", "--no-gpu", dest="gpu", default=("darwin" not in sys.platform), true_help="enable GPU support for agent", false_help="disable GPU support for agent", ), Arg( "--no-autorestart", help="disable container auto-restart (recommended for local development)", action="store_true", ), Arg( "--auto-work-dir", type=Path, default=None, help="the default work dir, used for interactive jobs", ), ], ), Cmd( "cluster-down", handle_cluster_down, "Stop a Determined cluster", [ Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), Arg( "--delete-db", action="store_true", help="remove current master database", ), ], ), Cmd( "master-up", handle_master_up, "Start a Determined master", [ Group( Arg( "--master-config-path", type=Path, default=None, help="path to master configuration", ), Arg( "--storage-host-path", type=Path, default=None, help="Storage location for cluster data (e.g. checkpoints)", ), ), Arg( "--master-port", type=int, default=cluster_utils.MASTER_PORT_DEFAULT, help="port to expose master on", ), Arg( "--master-name", type=str, default="determined", help="name for the cluster resources", ), Arg("--det-version", type=str, default=None, help="version or commit to use"), Arg( "--db-password", type=str, default="<PASSWORD>", help="password for master database", ), Arg( "--delete-db", action="store_true", help="remove current master database", ), Arg( "--no-autorestart", help="disable container auto-restart (recommended for local development)", action="store_true", ), Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), Arg( "--auto-work-dir", type=Path, default=None, help="the default work dir, used for interactive jobs", ), ], ), Cmd( "master-down", handle_master_down, "Stop a Determined master", [ Arg( "--master-name", type=str, default="determined", help="name for the cluster resources", ), Arg( "--delete-db", action="store_true", help="remove current master database", ), Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), ], ), Cmd( "logs", handle_logs, "Show the logs of a Determined cluster", [ Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), Arg("--no-follow", help="disable following logs", action="store_true"), ], ), Cmd( "agent-up", handle_agent_up, "Start a Determined agent", [ Arg("master_host", type=str, help="master hostname"), Arg( "--master-port", type=int, default=cluster_utils.MASTER_PORT_DEFAULT, help="master port", ), Arg( "--agent-config-path", type=Path, default=None, help="path to agent configuration", ), Arg("--det-version", type=str, default=None, help="version or commit to use"), Arg( "--agent-name", type=str, default=cluster_utils.AGENT_NAME_DEFAULT, help="agent name", ), Arg("--agent-label", type=str, default=None, help="agent label"), Arg("--agent-resource-pool", type=str, default=None, help="agent resource pool"), BoolOptArg( "--gpu", "--no-gpu", dest="gpu", default=("darwin" not in sys.platform), true_help="enable GPU support for agent", false_help="disable GPU support for agent", ), Arg( "--no-autorestart", help="disable container auto-restart (recommended for local development)", action="store_true", ), Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), ], ), Cmd( "agent-down", handle_agent_down, "Stop a Determined agent", [ Arg( "--agent-name", type=str, default=cluster_utils.AGENT_NAME_DEFAULT, help="agent name", ), Arg("--all", help="stop all running agents", action="store_true"), Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), ], ), ], )
harness/determined/deploy/local/cli.py
import argparse import sys from pathlib import Path from typing import Callable, Dict from determined.common.declarative_argparse import Arg, BoolOptArg, Cmd, Group from . import cluster_utils from .preflight import check_docker_install def handle_cluster_up(args: argparse.Namespace) -> None: if not args.no_preflight_checks: check_docker_install() cluster_utils.cluster_up( num_agents=args.agents, port=args.master_port, master_config_path=args.master_config_path, storage_host_path=args.storage_host_path, cluster_name=args.cluster_name, image_repo_prefix=args.image_repo_prefix, version=args.det_version, db_password=<PASSWORD>, delete_db=args.delete_db, gpu=args.gpu, autorestart=(not args.no_autorestart), auto_work_dir=args.auto_work_dir, ) def handle_cluster_down(args: argparse.Namespace) -> None: cluster_utils.cluster_down(cluster_name=args.cluster_name, delete_db=args.delete_db) def handle_logs(args: argparse.Namespace) -> None: cluster_utils.logs(cluster_name=args.cluster_name, no_follow=args.no_follow) def handle_master_up(args: argparse.Namespace) -> None: cluster_utils.master_up( port=args.master_port, master_config_path=args.master_config_path, storage_host_path=args.storage_host_path, master_name=args.master_name, image_repo_prefix=args.image_repo_prefix, version=args.det_version, db_password=<PASSWORD>, delete_db=args.delete_db, autorestart=(not args.no_autorestart), cluster_name=args.cluster_name, auto_work_dir=args.auto_work_dir, ) def handle_master_down(args: argparse.Namespace) -> None: cluster_utils.master_down(master_name=args.master_name, delete_db=args.delete_db) def handle_agent_up(args: argparse.Namespace) -> None: cluster_utils.agent_up( master_host=args.master_host, master_port=args.master_port, agent_config_path=args.agent_config_path, gpu=args.gpu, agent_name=args.agent_name, agent_label=args.agent_label, agent_resource_pool=args.agent_resource_pool, image_repo_prefix=args.image_repo_prefix, version=args.det_version, labels=None, autorestart=(not args.no_autorestart), cluster_name=args.cluster_name, ) def handle_agent_down(args: argparse.Namespace) -> None: if args.all: cluster_utils.stop_all_agents() else: cluster_utils.stop_agent(agent_name=args.agent_name) def deploy_local(args: argparse.Namespace) -> None: OPERATION_TO_FN = { "agent-up": handle_agent_up, "agent-down": handle_agent_down, "cluster-up": handle_cluster_up, "cluster-down": handle_cluster_down, "logs": handle_logs, "master-up": handle_master_up, "master-down": handle_master_down, } # type: Dict[str, Callable[[argparse.Namespace], None]] OPERATION_TO_FN[args.command](args) args_description = Cmd( "local", None, "local help", [ Cmd( "cluster-up", handle_cluster_up, "Create a Determined cluster", [ Group( Arg( "--master-config-path", type=Path, default=None, help="path to master configuration", ), Arg( "--storage-host-path", type=Path, default=None, help="Storage location for cluster data (e.g. checkpoints)", ), ), Arg( "--agents", type=int, default=1, help="number of agents to start (on this machine)", ), Arg( "--master-port", type=int, default=cluster_utils.MASTER_PORT_DEFAULT, help="port to expose master on", ), Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), Arg("--det-version", type=str, default=None, help="version or commit to use"), Arg( "--db-password", type=str, default="<PASSWORD>", help="password for master database", ), Arg( "--delete-db", action="store_true", help="remove current master database", ), BoolOptArg( "--gpu", "--no-gpu", dest="gpu", default=("darwin" not in sys.platform), true_help="enable GPU support for agent", false_help="disable GPU support for agent", ), Arg( "--no-autorestart", help="disable container auto-restart (recommended for local development)", action="store_true", ), Arg( "--auto-work-dir", type=Path, default=None, help="the default work dir, used for interactive jobs", ), ], ), Cmd( "cluster-down", handle_cluster_down, "Stop a Determined cluster", [ Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), Arg( "--delete-db", action="store_true", help="remove current master database", ), ], ), Cmd( "master-up", handle_master_up, "Start a Determined master", [ Group( Arg( "--master-config-path", type=Path, default=None, help="path to master configuration", ), Arg( "--storage-host-path", type=Path, default=None, help="Storage location for cluster data (e.g. checkpoints)", ), ), Arg( "--master-port", type=int, default=cluster_utils.MASTER_PORT_DEFAULT, help="port to expose master on", ), Arg( "--master-name", type=str, default="determined", help="name for the cluster resources", ), Arg("--det-version", type=str, default=None, help="version or commit to use"), Arg( "--db-password", type=str, default="<PASSWORD>", help="password for master database", ), Arg( "--delete-db", action="store_true", help="remove current master database", ), Arg( "--no-autorestart", help="disable container auto-restart (recommended for local development)", action="store_true", ), Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), Arg( "--auto-work-dir", type=Path, default=None, help="the default work dir, used for interactive jobs", ), ], ), Cmd( "master-down", handle_master_down, "Stop a Determined master", [ Arg( "--master-name", type=str, default="determined", help="name for the cluster resources", ), Arg( "--delete-db", action="store_true", help="remove current master database", ), Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), ], ), Cmd( "logs", handle_logs, "Show the logs of a Determined cluster", [ Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), Arg("--no-follow", help="disable following logs", action="store_true"), ], ), Cmd( "agent-up", handle_agent_up, "Start a Determined agent", [ Arg("master_host", type=str, help="master hostname"), Arg( "--master-port", type=int, default=cluster_utils.MASTER_PORT_DEFAULT, help="master port", ), Arg( "--agent-config-path", type=Path, default=None, help="path to agent configuration", ), Arg("--det-version", type=str, default=None, help="version or commit to use"), Arg( "--agent-name", type=str, default=cluster_utils.AGENT_NAME_DEFAULT, help="agent name", ), Arg("--agent-label", type=str, default=None, help="agent label"), Arg("--agent-resource-pool", type=str, default=None, help="agent resource pool"), BoolOptArg( "--gpu", "--no-gpu", dest="gpu", default=("darwin" not in sys.platform), true_help="enable GPU support for agent", false_help="disable GPU support for agent", ), Arg( "--no-autorestart", help="disable container auto-restart (recommended for local development)", action="store_true", ), Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), ], ), Cmd( "agent-down", handle_agent_down, "Stop a Determined agent", [ Arg( "--agent-name", type=str, default=cluster_utils.AGENT_NAME_DEFAULT, help="agent name", ), Arg("--all", help="stop all running agents", action="store_true"), Arg( "--cluster-name", type=str, default="determined", help="name for the cluster resources", ), ], ), ], )
0.378
0.118207
from typing import Dict from typing import Optional from typing import Type import asyncio import time import traceback try: from prometheus_client import Counter from prometheus_client import Histogram except ImportError: Counter = Histogram = None ERROR_NONE = "none" ERROR_GENERAL_EXCEPTION = "exception" class watch: start: float def __init__( self, *, counter: Optional[Counter] = None, histogram: Optional[Histogram] = None, error_mappings: Dict[str, Type[BaseException]] = None, labels: Optional[Dict[str, str]] = None, ): self.counter = counter self.histogram = histogram self.labels = labels or {} self.error_mappings = error_mappings or {} def __enter__(self): self.start = time.time() return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[Exception], exc_traceback: Optional[traceback.StackSummary], ): if Counter is None: return error = ERROR_NONE if self.histogram is not None: finished = time.time() if len(self.labels) > 0: self.histogram.labels(**self.labels).observe(finished - self.start) else: self.histogram.observe(finished - self.start) if self.counter is not None: if exc_value is None: error = ERROR_NONE else: for error_type, mapped_exc_type in self.error_mappings.items(): if isinstance(exc_value, mapped_exc_type): error = error_type break else: error = ERROR_GENERAL_EXCEPTION self.counter.labels(error=error, **self.labels).inc() class watch_lock: def __init__( self, histogram: Histogram, lock: asyncio.Lock, labels: Optional[Dict[str, str]] = None, ): self.histogram = histogram self.lock = lock self.labels = labels or {} async def __aenter__(self) -> None: start = time.time() await self.lock.acquire() if self.histogram is not None: finished = time.time() if len(self.labels) > 0: self.histogram.labels(**self.labels).observe(finished - start) else: self.histogram.observe(finished - start) async def __aexit__(self, exc_type, exc, tb): self.lock.release()
guillotina/metrics.py
from typing import Dict from typing import Optional from typing import Type import asyncio import time import traceback try: from prometheus_client import Counter from prometheus_client import Histogram except ImportError: Counter = Histogram = None ERROR_NONE = "none" ERROR_GENERAL_EXCEPTION = "exception" class watch: start: float def __init__( self, *, counter: Optional[Counter] = None, histogram: Optional[Histogram] = None, error_mappings: Dict[str, Type[BaseException]] = None, labels: Optional[Dict[str, str]] = None, ): self.counter = counter self.histogram = histogram self.labels = labels or {} self.error_mappings = error_mappings or {} def __enter__(self): self.start = time.time() return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[Exception], exc_traceback: Optional[traceback.StackSummary], ): if Counter is None: return error = ERROR_NONE if self.histogram is not None: finished = time.time() if len(self.labels) > 0: self.histogram.labels(**self.labels).observe(finished - self.start) else: self.histogram.observe(finished - self.start) if self.counter is not None: if exc_value is None: error = ERROR_NONE else: for error_type, mapped_exc_type in self.error_mappings.items(): if isinstance(exc_value, mapped_exc_type): error = error_type break else: error = ERROR_GENERAL_EXCEPTION self.counter.labels(error=error, **self.labels).inc() class watch_lock: def __init__( self, histogram: Histogram, lock: asyncio.Lock, labels: Optional[Dict[str, str]] = None, ): self.histogram = histogram self.lock = lock self.labels = labels or {} async def __aenter__(self) -> None: start = time.time() await self.lock.acquire() if self.histogram is not None: finished = time.time() if len(self.labels) > 0: self.histogram.labels(**self.labels).observe(finished - start) else: self.histogram.observe(finished - start) async def __aexit__(self, exc_type, exc, tb): self.lock.release()
0.795777
0.198763
import time import logging import requests from .tor_proxy import TorProxy, TOR_SOCKS_PROXIES from .free_proxy import FreeProxy # Timeout for web server response (seconds) TIMEOUT = 5 # Maximum retries count for executing request if an error occurred MAX_RETRIES = 3 # The delay after executing an HTTP request (seconds) # SLEEP_TIME = 1 SLEEP_TIME = 0.5 # HTTP headers for making the scraper more "human-like" HEADERS = { 'User-Agent': ('Mozilla/5.0 (Windows NT 6.1; rv:88.0)' ' Gecko/20100101 Firefox/88.0'), 'Accept': '*/*', } ICANHAZIP_URL = 'http://icanhazip.com' PROXY_TYPE_FREE = 'free' PROXY_TYPE_TOR = 'tor' class HttpRequest(): def __init__(self, headers: dict=HEADERS, max_retries: int=MAX_RETRIES, timeout: float=TIMEOUT, sleep_time: float=SLEEP_TIME, proxies=None, proxy_test_url: str=None): # These attributes may be changed directly self.headers = headers self.max_retries = max_retries self.timeout = timeout self.sleep_time = sleep_time self.proxies = proxies self.proxy_test_url = proxy_test_url # Don't change these atrributes from outside the class instance self.tor_proxy = TorProxy() self.free_proxy = FreeProxy() self.proxy_index = -1 self.proxy = self._get_next_proxy() def _get_next_proxy(self): if self.proxies == None: return None elif isinstance(self.proxies, dict): return self.proxies elif isinstance(self.proxies, list): self.proxy_index += 1 self.proxy_index = self.proxy_index % len(self.proxies) return self.proxies[self.proxy_index] elif self.proxies == PROXY_TYPE_FREE: logging.info('Searching for free proxies.') proxy = self.free_proxy.get_proxy(self.proxy_test_url) return {'http': proxy, 'https': proxy} elif self.proxies == PROXY_TYPE_TOR: logging.info('Starting TOR.') self.tor_proxy.restart() return TOR_SOCKS_PROXIES def rotate_proxy(self): logging.info('Changing proxy (if possible).') self.proxy = self._get_next_proxy() logging.info('Now using IP: ' + self.get_ip()) def _request(self, func, **args) -> requests.Response: args['headers'] = self.headers args['timeout'] = self.timeout args['proxies'] = self.proxy for attempt in range(0, self.max_retries): try: r = func(**args) except requests.exceptions.RequestException: time.sleep(self.sleep_time) else: time.sleep(self.sleep_time) if r.status_code != requests.codes.ok: logging.error(f'Error {r.status_code} ' + f'while accessing {args["url"]}.') return None return r logging.error("Can't execute HTTP request while accessing " + args['url']) return None def get(self, url: str, params: dict=None): args = { 'url': url, 'params': params, } func = requests.get return self._request(func=func, **args) def post(self, url: str, data: dict=None): args = { 'url': url, 'data': data, } func = requests.post return self._request(func=func, **args) def get_ip(self) -> str: ip = self.get(ICANHAZIP_URL) if ip == None: return None return ip.text.strip() # Retrieve an image from URL and save it to a file def save_image(self, url: str, filename: str) -> bool: r = self.get(url) try: with open(filename, 'wb') as f: f.write(r.content) except OSError: logging.exception(f"Can't save the image to the file {filename}.") return False except Exception: logging.exception(f'Failure while retrieving an image from {url}.') return False return True # For testing def main(): logging.basicConfig(level=logging.INFO) request = HttpRequest(proxies=PROXY_TYPE_FREE) print(request.get_ip()) if __name__ == '__main__': main()
utils/http_request.py
import time import logging import requests from .tor_proxy import TorProxy, TOR_SOCKS_PROXIES from .free_proxy import FreeProxy # Timeout for web server response (seconds) TIMEOUT = 5 # Maximum retries count for executing request if an error occurred MAX_RETRIES = 3 # The delay after executing an HTTP request (seconds) # SLEEP_TIME = 1 SLEEP_TIME = 0.5 # HTTP headers for making the scraper more "human-like" HEADERS = { 'User-Agent': ('Mozilla/5.0 (Windows NT 6.1; rv:88.0)' ' Gecko/20100101 Firefox/88.0'), 'Accept': '*/*', } ICANHAZIP_URL = 'http://icanhazip.com' PROXY_TYPE_FREE = 'free' PROXY_TYPE_TOR = 'tor' class HttpRequest(): def __init__(self, headers: dict=HEADERS, max_retries: int=MAX_RETRIES, timeout: float=TIMEOUT, sleep_time: float=SLEEP_TIME, proxies=None, proxy_test_url: str=None): # These attributes may be changed directly self.headers = headers self.max_retries = max_retries self.timeout = timeout self.sleep_time = sleep_time self.proxies = proxies self.proxy_test_url = proxy_test_url # Don't change these atrributes from outside the class instance self.tor_proxy = TorProxy() self.free_proxy = FreeProxy() self.proxy_index = -1 self.proxy = self._get_next_proxy() def _get_next_proxy(self): if self.proxies == None: return None elif isinstance(self.proxies, dict): return self.proxies elif isinstance(self.proxies, list): self.proxy_index += 1 self.proxy_index = self.proxy_index % len(self.proxies) return self.proxies[self.proxy_index] elif self.proxies == PROXY_TYPE_FREE: logging.info('Searching for free proxies.') proxy = self.free_proxy.get_proxy(self.proxy_test_url) return {'http': proxy, 'https': proxy} elif self.proxies == PROXY_TYPE_TOR: logging.info('Starting TOR.') self.tor_proxy.restart() return TOR_SOCKS_PROXIES def rotate_proxy(self): logging.info('Changing proxy (if possible).') self.proxy = self._get_next_proxy() logging.info('Now using IP: ' + self.get_ip()) def _request(self, func, **args) -> requests.Response: args['headers'] = self.headers args['timeout'] = self.timeout args['proxies'] = self.proxy for attempt in range(0, self.max_retries): try: r = func(**args) except requests.exceptions.RequestException: time.sleep(self.sleep_time) else: time.sleep(self.sleep_time) if r.status_code != requests.codes.ok: logging.error(f'Error {r.status_code} ' + f'while accessing {args["url"]}.') return None return r logging.error("Can't execute HTTP request while accessing " + args['url']) return None def get(self, url: str, params: dict=None): args = { 'url': url, 'params': params, } func = requests.get return self._request(func=func, **args) def post(self, url: str, data: dict=None): args = { 'url': url, 'data': data, } func = requests.post return self._request(func=func, **args) def get_ip(self) -> str: ip = self.get(ICANHAZIP_URL) if ip == None: return None return ip.text.strip() # Retrieve an image from URL and save it to a file def save_image(self, url: str, filename: str) -> bool: r = self.get(url) try: with open(filename, 'wb') as f: f.write(r.content) except OSError: logging.exception(f"Can't save the image to the file {filename}.") return False except Exception: logging.exception(f'Failure while retrieving an image from {url}.') return False return True # For testing def main(): logging.basicConfig(level=logging.INFO) request = HttpRequest(proxies=PROXY_TYPE_FREE) print(request.get_ip()) if __name__ == '__main__': main()
0.568296
0.082143
from insights import CommandParser, parser from insights.parsers import SkipException, parse_fixed_table from insights.specs import Specs class PodmanList(CommandParser): """ A general class for parsing tabular podman list information. Parsing rules are: * The first line is the header line. * The other lines are data lines. * All fields line up vertically. * Fields are separated from each other by at least three spaces. * Some fields can contain nothing, and this is shown as spaces, so we need to catch that and turn it into None. Why not just use hard-coded fields and columns? So that we can adapt to different output lists. Raises: NotImplementedError: If `key_field` or `attr_name` is not defined SkipException: If no data to parse """ key_field = '' heading_ignore = [] attr_name = '' substitutions = [] def parse_content(self, content): if not (self.key_field and self.attr_name): raise NotImplementedError("'key_field' or 'attr_name' is not defined") self.rows = parse_fixed_table(content, heading_ignore=self.heading_ignore, header_substitute=self.substitutions) if not self.rows: raise SkipException('No data.') data = {} for row in self.rows: k = row.get(self.key_field) for sub in self.substitutions: row[sub[0]] = row.pop(sub[1]) if k is not None and k != '<none>': data[k] = row setattr(self, self.attr_name, data) @parser(Specs.podman_list_images) class PodmanListImages(PodmanList): """ Handle the list of podman images using the PodmanList parser class. Sample output of command ``podman images --all --no-trunc --digests``:: REPOSITORY TAG DIGEST IMAGE ID CREATED SIZE rhel6_vsftpd latest <none> 412b684338a1178f0e5ad68a5fd00df01a10a18495959398b2cf92c2033d3d02 37 minutes ago 459.5 MB rhel7_imagemagick latest <none> 882ab98aae5394aebe91fe6d8a4297fa0387c3cfd421b2d892bddf218ac373b2 4 days ago 785.4 MB rhel6_nss-softokn latest <none> dd87dad2c7841a19263ae2dc96d32c501ee84a92f56aed75bb67f57efe4e48b5 5 days ago 449.7 MB Attributes: rows (list): List of row dictionaries. images (dict): Dictionary keyed on the value of the "REPOSITORY" fileld Examples: >>> images.rows[0]['REPOSITORY'] 'rhel6_vsftpd' >>> images.rows[1]['SIZE'] '785.4 MB' >>> images.images['rhel6_vsftpd']['CREATED'] '37 minutes ago' """ key_field = 'REPOSITORY' heading_ignore = [key_field] attr_name = 'images' substitutions = [("IMAGE ID", "IMAGE_ID")] @parser(Specs.podman_list_containers) class PodmanListContainers(PodmanList): """ Handle the list of podman containers using the PodmanList parser class. Sample output of command ``podman ps --all --no-trunc --size``:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZE 03e2861336a76e29155836113ff6560cb70780c32f95062642993b2b3d0fc216 rhel7_httpd "/usr/sbin/httpd -DFOREGROUND" 45 seconds ago Up 37 seconds 0.0.0.0:8080->80/tcp angry_saha 796 B (virtual 669.2 MB) 95516ea08b565e37e2a4bca3333af40a240c368131b77276da8dec629b7fe102 bd8638c869ea40a9269d87e9af6741574562af9ee013e03ac2745fb5f59e2478 "/bin/sh -c 'yum install -y vsftpd-2.2.2-6.el6'" 51 minutes ago Exited (137) 50 minutes ago tender_rosalind 4.751 MB (virtual 200.4 MB) Attributes: rows (list): List of row dictionaries. containers(dict): Dictionary keyed on the value of the "NAMES" field Examples: >>> containers.rows[0]['NAMES'] 'angry_saha' >>> containers.rows[0]['STATUS'] 'Up 37 seconds' >>> containers.containers['tender_rosalind']['STATUS'] 'Exited (137) 18 hours ago' """ key_field = 'NAMES' heading_ignore = ['CONTAINER'] attr_name = 'containers' substitutions = [("CONTAINER ID", "CONTAINER_ID")]
insights/parsers/podman_list.py
from insights import CommandParser, parser from insights.parsers import SkipException, parse_fixed_table from insights.specs import Specs class PodmanList(CommandParser): """ A general class for parsing tabular podman list information. Parsing rules are: * The first line is the header line. * The other lines are data lines. * All fields line up vertically. * Fields are separated from each other by at least three spaces. * Some fields can contain nothing, and this is shown as spaces, so we need to catch that and turn it into None. Why not just use hard-coded fields and columns? So that we can adapt to different output lists. Raises: NotImplementedError: If `key_field` or `attr_name` is not defined SkipException: If no data to parse """ key_field = '' heading_ignore = [] attr_name = '' substitutions = [] def parse_content(self, content): if not (self.key_field and self.attr_name): raise NotImplementedError("'key_field' or 'attr_name' is not defined") self.rows = parse_fixed_table(content, heading_ignore=self.heading_ignore, header_substitute=self.substitutions) if not self.rows: raise SkipException('No data.') data = {} for row in self.rows: k = row.get(self.key_field) for sub in self.substitutions: row[sub[0]] = row.pop(sub[1]) if k is not None and k != '<none>': data[k] = row setattr(self, self.attr_name, data) @parser(Specs.podman_list_images) class PodmanListImages(PodmanList): """ Handle the list of podman images using the PodmanList parser class. Sample output of command ``podman images --all --no-trunc --digests``:: REPOSITORY TAG DIGEST IMAGE ID CREATED SIZE rhel6_vsftpd latest <none> 412b684338a1178f0e5ad68a5fd00df01a10a18495959398b2cf92c2033d3d02 37 minutes ago 459.5 MB rhel7_imagemagick latest <none> 882ab98aae5394aebe91fe6d8a4297fa0387c3cfd421b2d892bddf218ac373b2 4 days ago 785.4 MB rhel6_nss-softokn latest <none> dd87dad2c7841a19263ae2dc96d32c501ee84a92f56aed75bb67f57efe4e48b5 5 days ago 449.7 MB Attributes: rows (list): List of row dictionaries. images (dict): Dictionary keyed on the value of the "REPOSITORY" fileld Examples: >>> images.rows[0]['REPOSITORY'] 'rhel6_vsftpd' >>> images.rows[1]['SIZE'] '785.4 MB' >>> images.images['rhel6_vsftpd']['CREATED'] '37 minutes ago' """ key_field = 'REPOSITORY' heading_ignore = [key_field] attr_name = 'images' substitutions = [("IMAGE ID", "IMAGE_ID")] @parser(Specs.podman_list_containers) class PodmanListContainers(PodmanList): """ Handle the list of podman containers using the PodmanList parser class. Sample output of command ``podman ps --all --no-trunc --size``:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZE 03e2861336a76e29155836113ff6560cb70780c32f95062642993b2b3d0fc216 rhel7_httpd "/usr/sbin/httpd -DFOREGROUND" 45 seconds ago Up 37 seconds 0.0.0.0:8080->80/tcp angry_saha 796 B (virtual 669.2 MB) 95516ea08b565e37e2a4bca3333af40a240c368131b77276da8dec629b7fe102 bd8638c869ea40a9269d87e9af6741574562af9ee013e03ac2745fb5f59e2478 "/bin/sh -c 'yum install -y vsftpd-2.2.2-6.el6'" 51 minutes ago Exited (137) 50 minutes ago tender_rosalind 4.751 MB (virtual 200.4 MB) Attributes: rows (list): List of row dictionaries. containers(dict): Dictionary keyed on the value of the "NAMES" field Examples: >>> containers.rows[0]['NAMES'] 'angry_saha' >>> containers.rows[0]['STATUS'] 'Up 37 seconds' >>> containers.containers['tender_rosalind']['STATUS'] 'Exited (137) 18 hours ago' """ key_field = 'NAMES' heading_ignore = ['CONTAINER'] attr_name = 'containers' substitutions = [("CONTAINER ID", "CONTAINER_ID")]
0.714429
0.445469
import os from flask import Flask, render_template, request, url_for, abort, redirect from flask_cloudy import Storage import pandas as pd import math port = int(os.getenv('PORT', 8000)) curr_file = None app = Flask(__name__) app.config.update({ "STORAGE_PROVIDER": "LOCAL", # Can also be S3, GOOGLE_STORAGE, etc... "STORAGE_KEY": "", "STORAGE_SECRET": "", "STORAGE_CONTAINER": "./files", # a directory path for local, bucket name of cloud "STORAGE_SERVER": True, "STORAGE_SERVER_URL": "/files" # The url endpoint to access files on LOCAL provider }) # Setup storage storage = Storage() storage.init_app(app) @app.route("/") def index(): csv_obj, other_obj = [], [] for obj in storage: fname = obj.name if fname.split('.')[-1]=='csv': csv_obj.append(obj) else: other_obj.append(obj) return render_template("index.html", csv_obj=csv_obj, other_obj=other_obj) @app.route("/view/<path:object_name>") def view(object_name): obj = storage.get(object_name) f_type = obj.name.split('.')[-1] if f_type=='csv': df = pd.read_csv('.'+obj.url, engine='python') global curr_file curr_file = '.'+obj.url img_list = df['Picture'].values.tolist() names = df['Name'].values.tolist() img_urls = ['./files/'+u for u in img_list if isinstance(u, str)] info = df.values.tolist() elif f_type=='jpg': info, img_urls, names = None, None, None else: info, img_urls, names = None, None, None return render_template("view.html", obj=obj, info=info, img_urls=img_urls, names=names) @app.route("/upload", methods=["POST"]) def upload(): usr_file = request.files.get("file") my_object = storage.upload(usr_file) return redirect(url_for("view", object_name=my_object.name)) @app.route("/people_by_grade", methods=['POST']) def search_people_by_grade(): low = request.form['low_grade'] high = request.form['high_grade'] df = pd.read_csv(curr_file, engine='python') resp = [] for _, line in df.iterrows(): if line[1] != ' ' and not math.isnan(float(line[1])): if int(low)<=int(line[1])<=int(high): if isinstance(line[4], str): resp.append([line[0], './files/'+line[4], line[3]]) return render_template("people_by_grade.html", grade_resp=resp) @app.route("/people_by_room", methods=['POST']) def search_people_by_room(): room_number = int(float(request.form['room_number'])) # print('daad', room_number, type(room_number)) df = pd.read_csv(curr_file, engine='python') resp = [] for _, line in df.iterrows(): if not math.isnan(line[2]): if int(line[2])==int(room_number): if isinstance(line[4], str): resp.append([line[0], './files/'+line[4]]) return render_template("people_by_room.html", people=resp) @app.route("/change_info", methods=['POST']) def change_people_info(): ppl = request.form['change_people'] area = request.form['change_area'] val = request.form['target_value'] df = pd.read_csv(curr_file, engine='python') df.at[df['Name']==ppl, area] = int(val) info = df.values.tolist() df.to_csv(curr_file, index=False) img_url = './files/'+ ppl + '.jpg' return render_template("change_info.html", info=info, img_url=img_url) if __name__ == '__main__': app.run(host="0.0.0.0", port=port, debug=True)
quiz0/main.py
import os from flask import Flask, render_template, request, url_for, abort, redirect from flask_cloudy import Storage import pandas as pd import math port = int(os.getenv('PORT', 8000)) curr_file = None app = Flask(__name__) app.config.update({ "STORAGE_PROVIDER": "LOCAL", # Can also be S3, GOOGLE_STORAGE, etc... "STORAGE_KEY": "", "STORAGE_SECRET": "", "STORAGE_CONTAINER": "./files", # a directory path for local, bucket name of cloud "STORAGE_SERVER": True, "STORAGE_SERVER_URL": "/files" # The url endpoint to access files on LOCAL provider }) # Setup storage storage = Storage() storage.init_app(app) @app.route("/") def index(): csv_obj, other_obj = [], [] for obj in storage: fname = obj.name if fname.split('.')[-1]=='csv': csv_obj.append(obj) else: other_obj.append(obj) return render_template("index.html", csv_obj=csv_obj, other_obj=other_obj) @app.route("/view/<path:object_name>") def view(object_name): obj = storage.get(object_name) f_type = obj.name.split('.')[-1] if f_type=='csv': df = pd.read_csv('.'+obj.url, engine='python') global curr_file curr_file = '.'+obj.url img_list = df['Picture'].values.tolist() names = df['Name'].values.tolist() img_urls = ['./files/'+u for u in img_list if isinstance(u, str)] info = df.values.tolist() elif f_type=='jpg': info, img_urls, names = None, None, None else: info, img_urls, names = None, None, None return render_template("view.html", obj=obj, info=info, img_urls=img_urls, names=names) @app.route("/upload", methods=["POST"]) def upload(): usr_file = request.files.get("file") my_object = storage.upload(usr_file) return redirect(url_for("view", object_name=my_object.name)) @app.route("/people_by_grade", methods=['POST']) def search_people_by_grade(): low = request.form['low_grade'] high = request.form['high_grade'] df = pd.read_csv(curr_file, engine='python') resp = [] for _, line in df.iterrows(): if line[1] != ' ' and not math.isnan(float(line[1])): if int(low)<=int(line[1])<=int(high): if isinstance(line[4], str): resp.append([line[0], './files/'+line[4], line[3]]) return render_template("people_by_grade.html", grade_resp=resp) @app.route("/people_by_room", methods=['POST']) def search_people_by_room(): room_number = int(float(request.form['room_number'])) # print('daad', room_number, type(room_number)) df = pd.read_csv(curr_file, engine='python') resp = [] for _, line in df.iterrows(): if not math.isnan(line[2]): if int(line[2])==int(room_number): if isinstance(line[4], str): resp.append([line[0], './files/'+line[4]]) return render_template("people_by_room.html", people=resp) @app.route("/change_info", methods=['POST']) def change_people_info(): ppl = request.form['change_people'] area = request.form['change_area'] val = request.form['target_value'] df = pd.read_csv(curr_file, engine='python') df.at[df['Name']==ppl, area] = int(val) info = df.values.tolist() df.to_csv(curr_file, index=False) img_url = './files/'+ ppl + '.jpg' return render_template("change_info.html", info=info, img_url=img_url) if __name__ == '__main__': app.run(host="0.0.0.0", port=port, debug=True)
0.105498
0.065098
"""This file implements the functionalities of a minitaur using pybullet.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import copy import math import re import numpy as np from locomotion.robots import minitaur_constants from locomotion.robots import minitaur_motor from locomotion.robots import robot_config from locomotion.robots import action_filter from locomotion.robots import kinematics INIT_POSITION = [0, 0, .2] INIT_RACK_POSITION = [0, 0, 1] INIT_ORIENTATION = [0, 0, 0, 1] KNEE_CONSTRAINT_POINT_RIGHT = [0, 0.005, 0.2] KNEE_CONSTRAINT_POINT_LEFT = [0, 0.01, 0.2] OVERHEAT_SHUTDOWN_TORQUE = 2.45 OVERHEAT_SHUTDOWN_TIME = 1.0 LEG_POSITION = ["front_left", "back_left", "front_right", "back_right"] MOTOR_NAMES = [ "motor_front_leftL_joint", "motor_front_leftR_joint", "motor_back_leftL_joint", "motor_back_leftR_joint", "motor_front_rightL_joint", "motor_front_rightR_joint", "motor_back_rightL_joint", "motor_back_rightR_joint" ] _CHASSIS_NAME_PATTERN = re.compile(r"chassis\D*center") _MOTOR_NAME_PATTERN = re.compile(r"motor\D*joint") _KNEE_NAME_PATTERN = re.compile(r"knee\D*") _BRACKET_NAME_PATTERN = re.compile(r"motor\D*_bracket_joint") _LEG_NAME_PATTERN1 = re.compile(r"hip\D*joint") _LEG_NAME_PATTERN2 = re.compile(r"hip\D*link") _LEG_NAME_PATTERN3 = re.compile(r"motor\D*link") SENSOR_NOISE_STDDEV = (0.0, 0.0, 0.0, 0.0, 0.0) MINITAUR_DEFAULT_MOTOR_DIRECTIONS = (-1, -1, -1, -1, 1, 1, 1, 1) MINITAUR_DEFAULT_MOTOR_OFFSETS = (0, 0, 0, 0, 0, 0, 0, 0) MINITAUR_NUM_MOTORS = 8 TWO_PI = 2 * math.pi MINITAUR_DOFS_PER_LEG = 2 def MapToMinusPiToPi(angles): """Maps a list of angles to [-pi, pi]. Args: angles: A list of angles in rad. Returns: A list of angle mapped to [-pi, pi]. """ mapped_angles = copy.deepcopy(angles) for i in range(len(angles)): mapped_angles[i] = math.fmod(angles[i], TWO_PI) if mapped_angles[i] >= math.pi: mapped_angles[i] -= TWO_PI elif mapped_angles[i] < -math.pi: mapped_angles[i] += TWO_PI return mapped_angles class Minitaur(object): """The minitaur class that simulates a quadruped robot from Ghost Robotics.""" def __init__(self, pybullet_client, num_motors=MINITAUR_NUM_MOTORS, dofs_per_leg=MINITAUR_DOFS_PER_LEG, time_step=0.01, action_repeat=1, self_collision_enabled=False, motor_control_mode=robot_config.MotorControlMode.POSITION, motor_model_class=minitaur_motor.MotorModel, motor_kp=1.0, motor_kd=0.02, motor_torque_limits=None, pd_latency=0.0, control_latency=0.0, observation_noise_stdev=SENSOR_NOISE_STDDEV, motor_overheat_protection=False, motor_direction=MINITAUR_DEFAULT_MOTOR_DIRECTIONS, motor_offset=MINITAUR_DEFAULT_MOTOR_OFFSETS, on_rack=False, reset_at_current_position=False, sensors=None, enable_action_interpolation=False, enable_action_filter=False, reset_time=-1): """Constructs a minitaur and reset it to the initial states. Args: pybullet_client: The instance of BulletClient to manage different simulations. num_motors: The number of the motors on the robot. dofs_per_leg: The number of degrees of freedom for each leg. time_step: The time step of the simulation. action_repeat: The number of ApplyAction() for each control step. self_collision_enabled: Whether to enable self collision. motor_control_mode: Enum. Can either be POSITION, TORQUE, or HYBRID. motor_model_class: We can choose from simple pd model to more accureate DC motor models. motor_kp: proportional gain for the motors. motor_kd: derivative gain for the motors. motor_torque_limits: Torque limits for the motors. Can be a single float or a list of floats specifying different limits for different robots. If not provided, the default limit of the robot is used. pd_latency: The latency of the observations (in seconds) used to calculate PD control. On the real hardware, it is the latency between the microcontroller and the motor controller. control_latency: The latency of the observations (in second) used to calculate action. On the real hardware, it is the latency from the motor controller, the microcontroller to the host (Nvidia TX2). observation_noise_stdev: The standard deviation of a Gaussian noise model for the sensor. It should be an array for separate sensors in the following order [motor_angle, motor_velocity, motor_torque, base_roll_pitch_yaw, base_angular_velocity] motor_overheat_protection: Whether to shutdown the motor that has exerted large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more details. motor_direction: A list of direction values, either 1 or -1, to compensate the axis difference of motors between the simulation and the real robot. motor_offset: A list of offset value for the motor angles. This is used to compensate the angle difference between the simulation and the real robot. on_rack: Whether to place the minitaur on rack. This is only used to debug the walking gait. In this mode, the minitaur's base is hanged midair so that its walking gait is clearer to visualize. reset_at_current_position: Whether to reset the minitaur at the current position and orientation. This is for simulating the reset behavior in the real world. sensors: a list of sensors that are attached to the robot. enable_action_interpolation: Whether to interpolate the current action with the previous action in order to produce smoother motions enable_action_filter: Boolean specifying if a lowpass filter should be used to smooth actions. """ self.num_motors = num_motors self.num_legs = self.num_motors // dofs_per_leg self._pybullet_client = pybullet_client self._action_repeat = action_repeat self._self_collision_enabled = self_collision_enabled self._motor_direction = motor_direction self._motor_offset = motor_offset self._observed_motor_torques = np.zeros(self.num_motors) self._applied_motor_torques = np.zeros(self.num_motors) self._max_force = 3.5 self._pd_latency = pd_latency self._control_latency = control_latency self._observation_noise_stdev = observation_noise_stdev self._observation_history = collections.deque(maxlen=100) self._control_observation = [] self._chassis_link_ids = [-1] self._leg_link_ids = [] self._motor_link_ids = [] self._foot_link_ids = [] self._motor_overheat_protection = motor_overheat_protection self._on_rack = on_rack self._reset_at_current_position = reset_at_current_position self.SetAllSensors(sensors if sensors is not None else list()) self._is_safe = True self._enable_action_interpolation = enable_action_interpolation self._enable_action_filter = enable_action_filter self._last_action = None if not motor_model_class: raise ValueError("Must provide a motor model class!") if self._on_rack and self._reset_at_current_position: raise ValueError("on_rack and reset_at_current_position " "cannot be enabled together") if isinstance(motor_kp, (collections.Sequence, np.ndarray)): self._motor_kps = np.asarray(motor_kp) else: self._motor_kps = np.full(num_motors, motor_kp) if isinstance(motor_kd, (collections.Sequence, np.ndarray)): self._motor_kds = np.asarray(motor_kd) else: self._motor_kds = np.full(num_motors, motor_kd) if isinstance(motor_torque_limits, (collections.Sequence, np.ndarray)): self._motor_torque_limits = np.asarray(motor_torque_limits) elif motor_torque_limits is None: self._motor_torque_limits = None else: self._motor_torque_limits = motor_torque_limits self._motor_control_mode = motor_control_mode self._motor_model = motor_model_class( kp=motor_kp, kd=motor_kd, torque_limits=self._motor_torque_limits, motor_control_mode=motor_control_mode) self.time_step = time_step self._step_counter = 0 # This also includes the time spent during the Reset motion. self._state_action_counter = 0 _, self._init_orientation_inv = self._pybullet_client.invertTransform( position=[0, 0, 0], orientation=self._GetDefaultInitOrientation()) if self._enable_action_filter: self._action_filter = self._BuildActionFilter() # reset_time=-1.0 means skipping the reset motion. # See Reset for more details. self.Reset(reset_time=reset_time) self.ReceiveObservation() def GetTimeSinceReset(self): return self._step_counter * self.time_step def _StepInternal(self, action, motor_control_mode=None): self.ApplyAction(action, motor_control_mode) self._pybullet_client.stepSimulation() self.ReceiveObservation() self._state_action_counter += 1 def Step(self, action, motor_control_mode=None): """Steps simulation.""" if self._enable_action_filter: action = self._FilterAction(action) for i in range(self._action_repeat): proc_action = self.ProcessAction(action, i) self._StepInternal(proc_action, motor_control_mode) self._step_counter += 1 self._last_action = action def Terminate(self): pass def GetFootLinkIDs(self): """Get list of IDs for all foot links.""" return self._foot_link_ids def _RecordMassInfoFromURDF(self): """Records the mass information from the URDF file.""" self._base_mass_urdf = [] for chassis_id in self._chassis_link_ids: self._base_mass_urdf.append( self._pybullet_client.getDynamicsInfo(self.quadruped, chassis_id)[0]) self._leg_masses_urdf = [] for leg_id in self._leg_link_ids: self._leg_masses_urdf.append( self._pybullet_client.getDynamicsInfo(self.quadruped, leg_id)[0]) for motor_id in self._motor_link_ids: self._leg_masses_urdf.append( self._pybullet_client.getDynamicsInfo(self.quadruped, motor_id)[0]) def _RecordInertiaInfoFromURDF(self): """Record the inertia of each body from URDF file.""" self._link_urdf = [] num_bodies = self._pybullet_client.getNumJoints(self.quadruped) for body_id in range(-1, num_bodies): # -1 is for the base link. inertia = self._pybullet_client.getDynamicsInfo(self.quadruped, body_id)[2] self._link_urdf.append(inertia) # We need to use id+1 to index self._link_urdf because it has the base # (index = -1) at the first element. self._base_inertia_urdf = [ self._link_urdf[chassis_id + 1] for chassis_id in self._chassis_link_ids ] self._leg_inertia_urdf = [ self._link_urdf[leg_id + 1] for leg_id in self._leg_link_ids ] self._leg_inertia_urdf.extend( [self._link_urdf[motor_id + 1] for motor_id in self._motor_link_ids]) def _BuildJointNameToIdDict(self): num_joints = self._pybullet_client.getNumJoints(self.quadruped) self._joint_name_to_id = {} for i in range(num_joints): joint_info = self._pybullet_client.getJointInfo(self.quadruped, i) self._joint_name_to_id[joint_info[1].decode("UTF-8")] = joint_info[0] def _BuildUrdfIds(self): """Build the link Ids from its name in the URDF file. Raises: ValueError: Unknown category of the joint name. """ num_joints = self._pybullet_client.getNumJoints(self.quadruped) self._chassis_link_ids = [-1] # The self._leg_link_ids include both the upper and lower links of the leg. self._leg_link_ids = [] self._motor_link_ids = [] self._foot_link_ids = [] self._bracket_link_ids = [] for i in range(num_joints): joint_info = self._pybullet_client.getJointInfo(self.quadruped, i) joint_name = joint_info[1].decode("UTF-8") joint_id = self._joint_name_to_id[joint_name] if _CHASSIS_NAME_PATTERN.match(joint_name): self._chassis_link_ids.append(joint_id) elif _BRACKET_NAME_PATTERN.match(joint_name): self._bracket_link_ids.append(joint_id) elif _MOTOR_NAME_PATTERN.match(joint_name): self._motor_link_ids.append(joint_id) elif _KNEE_NAME_PATTERN.match(joint_name): self._foot_link_ids.append(joint_id) elif (_LEG_NAME_PATTERN1.match(joint_name) or _LEG_NAME_PATTERN2.match(joint_name) or _LEG_NAME_PATTERN3.match(joint_name)): self._leg_link_ids.append(joint_id) else: raise ValueError("Unknown category of joint %s" % joint_name) self._leg_link_ids.extend(self._foot_link_ids) self._chassis_link_ids.sort() self._motor_link_ids.sort() self._foot_link_ids.sort() self._leg_link_ids.sort() self._bracket_link_ids.sort() def _RemoveDefaultJointDamping(self): num_joints = self._pybullet_client.getNumJoints(self.quadruped) for i in range(num_joints): joint_info = self._pybullet_client.getJointInfo(self.quadruped, i) self._pybullet_client.changeDynamics(joint_info[0], -1, linearDamping=0, angularDamping=0) def _BuildMotorIdList(self): self._motor_id_list = [ self._joint_name_to_id[motor_name] for motor_name in self._GetMotorNames() ] def _CreateRackConstraint(self, init_position, init_orientation): """Create a constraint that keeps the chassis at a fixed frame. This frame is defined by init_position and init_orientation. Args: init_position: initial position of the fixed frame. init_orientation: initial orientation of the fixed frame in quaternion format [x,y,z,w]. Returns: Return the constraint id. """ fixed_constraint = self._pybullet_client.createConstraint( parentBodyUniqueId=self.quadruped, parentLinkIndex=-1, childBodyUniqueId=-1, childLinkIndex=-1, jointType=self._pybullet_client.JOINT_FIXED, jointAxis=[0, 0, 0], parentFramePosition=[0, 0, 0], childFramePosition=init_position, childFrameOrientation=init_orientation) return fixed_constraint def IsObservationValid(self): """Whether the observation is valid for the current time step. In simulation, observations are always valid. In real hardware, it may not be valid from time to time when communication error happens between the Nvidia TX2 and the microcontroller. Returns: Whether the observation is valid for the current time step. """ return True def Reset(self, reload_urdf=True, default_motor_angles=None, reset_time=3.0): """Reset the minitaur to its initial states. Args: reload_urdf: Whether to reload the urdf file. If not, Reset() just place the minitaur back to its starting position. default_motor_angles: The default motor angles. If it is None, minitaur will hold a default pose (motor angle math.pi / 2) for 100 steps. In torque control mode, the phase of holding the default pose is skipped. reset_time: The duration (in seconds) to hold the default motor angles. If reset_time <= 0 or in torque control mode, the phase of holding the default pose is skipped. """ if reload_urdf: self._LoadRobotURDF() if self._on_rack: self.rack_constraint = (self._CreateRackConstraint( self._GetDefaultInitPosition(), self._GetDefaultInitOrientation())) self._BuildJointNameToIdDict() self._BuildUrdfIds() self._RemoveDefaultJointDamping() self._BuildMotorIdList() self._RecordMassInfoFromURDF() self._RecordInertiaInfoFromURDF() self.ResetPose(add_constraint=True) else: self._pybullet_client.resetBasePositionAndOrientation( self.quadruped, self._GetDefaultInitPosition(), self._GetDefaultInitOrientation()) self._pybullet_client.resetBaseVelocity(self.quadruped, [0, 0, 0], [0, 0, 0]) self.ResetPose(add_constraint=False) self._overheat_counter = np.zeros(self.num_motors) self._motor_enabled_list = [True] * self.num_motors self._observation_history.clear() self._step_counter = 0 self._state_action_counter = 0 self._is_safe = True self._last_action = None self._SettleDownForReset(default_motor_angles, reset_time) if self._enable_action_filter: self._ResetActionFilter() def _LoadRobotURDF(self): """Loads the URDF file for the robot.""" urdf_file = self.GetURDFFile() if self._self_collision_enabled: self.quadruped = self._pybullet_client.loadURDF( urdf_file, self._GetDefaultInitPosition(), self._GetDefaultInitOrientation(), flags=self._pybullet_client.URDF_USE_SELF_COLLISION) else: self.quadruped = self._pybullet_client.loadURDF( urdf_file, self._GetDefaultInitPosition(), self._GetDefaultInitOrientation()) def _SettleDownForReset(self, default_motor_angles, reset_time): """Sets the default motor angles and waits for the robot to settle down. The reset is skipped is reset_time is less than zereo. Args: default_motor_angles: A list of motor angles that the robot will achieve at the end of the reset phase. reset_time: The time duration for the reset phase. """ if reset_time <= 0: return # Important to fill the observation buffer. self.ReceiveObservation() for _ in range(100): self._StepInternal( [math.pi / 2] * self.num_motors, motor_control_mode=robot_config.MotorControlMode.POSITION) # Don't continue to reset if a safety error has occurred. if not self._is_safe: return if default_motor_angles is None: return num_steps_to_reset = int(reset_time / self.time_step) for _ in range(num_steps_to_reset): self._StepInternal( default_motor_angles, motor_control_mode=robot_config.MotorControlMode.POSITION) # Don't continue to reset if a safety error has occurred. if not self._is_safe: return def _SetMotorTorqueById(self, motor_id, torque): self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=motor_id, controlMode=self._pybullet_client.TORQUE_CONTROL, force=torque) def _SetMotorTorqueByIds(self, motor_ids, torques): self._pybullet_client.setJointMotorControlArray( bodyIndex=self.quadruped, jointIndices=motor_ids, controlMode=self._pybullet_client.TORQUE_CONTROL, forces=torques) def _SetDesiredMotorAngleByName(self, motor_name, desired_angle): self._SetDesiredMotorAngleById(self._joint_name_to_id[motor_name], desired_angle) def GetURDFFile(self): return "quadruped/minitaur.urdf" def ResetPose(self, add_constraint): """Reset the pose of the minitaur. Args: add_constraint: Whether to add a constraint at the joints of two feet. """ for i in range(self.num_legs): self._ResetPoseForLeg(i, add_constraint) def _ResetPoseForLeg(self, leg_id, add_constraint): """Reset the initial pose for the leg. Args: leg_id: It should be 0, 1, 2, or 3, which represents the leg at front_left, back_left, front_right and back_right. add_constraint: Whether to add a constraint at the joints of two feet. """ knee_friction_force = 0 half_pi = math.pi / 2.0 knee_angle = -2.1834 leg_position = LEG_POSITION[leg_id] self._pybullet_client.resetJointState( self.quadruped, self._joint_name_to_id["motor_" + leg_position + "L_joint"], self._motor_direction[2 * leg_id] * half_pi, targetVelocity=0) self._pybullet_client.resetJointState( self.quadruped, self._joint_name_to_id["knee_" + leg_position + "L_link"], self._motor_direction[2 * leg_id] * knee_angle, targetVelocity=0) self._pybullet_client.resetJointState( self.quadruped, self._joint_name_to_id["motor_" + leg_position + "R_joint"], self._motor_direction[2 * leg_id + 1] * half_pi, targetVelocity=0) self._pybullet_client.resetJointState( self.quadruped, self._joint_name_to_id["knee_" + leg_position + "R_link"], self._motor_direction[2 * leg_id + 1] * knee_angle, targetVelocity=0) if add_constraint: self._pybullet_client.createConstraint( self.quadruped, self._joint_name_to_id["knee_" + leg_position + "R_link"], self.quadruped, self._joint_name_to_id["knee_" + leg_position + "L_link"], self._pybullet_client.JOINT_POINT2POINT, [0, 0, 0], KNEE_CONSTRAINT_POINT_RIGHT, KNEE_CONSTRAINT_POINT_LEFT) # Disable the default motor in pybullet. self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["motor_" + leg_position + "L_joint"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["motor_" + leg_position + "R_joint"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["knee_" + leg_position + "L_link"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["knee_" + leg_position + "R_link"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) def GetBasePosition(self): """Get the position of minitaur's base. Returns: The position of minitaur's base. """ return self._base_position def GetBaseVelocity(self): """Get the linear velocity of minitaur's base. Returns: The velocity of minitaur's base. """ velocity, _ = self._pybullet_client.getBaseVelocity(self.quadruped) return velocity def GetTrueBaseRollPitchYaw(self): """Get minitaur's base orientation in euler angle in the world frame. Returns: A tuple (roll, pitch, yaw) of the base in world frame. """ orientation = self.GetTrueBaseOrientation() roll_pitch_yaw = self._pybullet_client.getEulerFromQuaternion(orientation) return np.asarray(roll_pitch_yaw) def GetBaseRollPitchYaw(self): """Get minitaur's base orientation in euler angle in the world frame. This function mimicks the noisy sensor reading and adds latency. Returns: A tuple (roll, pitch, yaw) of the base in world frame polluted by noise and latency. """ delayed_orientation = np.array( self._control_observation[3 * self.num_motors:3 * self.num_motors + 4]) delayed_roll_pitch_yaw = self._pybullet_client.getEulerFromQuaternion( delayed_orientation) roll_pitch_yaw = self._AddSensorNoise(np.array(delayed_roll_pitch_yaw), self._observation_noise_stdev[3]) return roll_pitch_yaw def GetHipPositionsInBaseFrame(self): """Get the hip joint positions of the robot within its base frame.""" raise NotImplementedError("Not implemented for Minitaur.") def ComputeMotorAnglesFromFootLocalPosition(self, leg_id, foot_local_position): """Use IK to compute the motor angles, given the foot link's local position. Args: leg_id: The leg index. foot_local_position: The foot link's position in the base frame. Returns: A tuple. The position indices and the angles for all joints along the leg. The position indices is consistent with the joint orders as returned by GetMotorAngles API. """ assert len(self._foot_link_ids) == self.num_legs toe_id = self._foot_link_ids[leg_id] motors_per_leg = self.num_motors // self.num_legs joint_position_idxs = list( range(leg_id * motors_per_leg, leg_id * motors_per_leg + motors_per_leg)) joint_angles = kinematics.joint_angles_from_link_position( robot=self, link_position=foot_local_position, link_id=toe_id, joint_ids=joint_position_idxs, ) # Joint offset is necessary for Laikago. joint_angles = np.multiply( np.asarray(joint_angles) - np.asarray(self._motor_offset)[joint_position_idxs], self._motor_direction[joint_position_idxs]) # Return the joing index (the same as when calling GetMotorAngles) as well # as the angles. return joint_position_idxs, joint_angles.tolist() def ComputeJacobian(self, leg_id): """Compute the Jacobian for a given leg.""" # Does not work for Minitaur which has the four bar mechanism for now. assert len(self._foot_link_ids) == self.num_legs full_jacobian = kinematics.compute_jacobian( robot=self, link_id=self._foot_link_ids[leg_id], ) motors_per_leg = self.num_motors // self.num_legs com_dof = 6 return full_jacobian[com_dof + leg_id * motors_per_leg:com_dof + (leg_id + 1) * motors_per_leg] def MapContactForceToJointTorques(self, leg_id, contact_force): """Maps the foot contact force to the leg joint torques.""" jv = self.ComputeJacobian(leg_id) motor_torques_list = np.matmul(contact_force, jv) motor_torques_dict = {} motors_per_leg = self.num_motors // self.num_legs for torque_id, joint_id in enumerate( range(leg_id * motors_per_leg, (leg_id + 1) * motors_per_leg)): motor_torques_dict[joint_id] = motor_torques_list[torque_id] return motor_torques_dict def GetFootContacts(self): """Get minitaur's foot contact situation with the ground. Returns: A list of 4 booleans. The ith boolean is True if leg i is in contact with ground. """ contacts = [] for leg_idx in range(MINITAUR_NUM_MOTORS // 2): link_id_1 = self._foot_link_ids[leg_idx * 2] link_id_2 = self._foot_link_ids[leg_idx * 2 + 1] contact_1 = bool( self._pybullet_client.getContactPoints(bodyA=0, bodyB=self.quadruped, linkIndexA=-1, linkIndexB=link_id_1)) contact_2 = bool( self._pybullet_client.getContactPoints(bodyA=0, bodyB=self.quadruped, linkIndexA=-1, linkIndexB=link_id_2)) contacts.append(contact_1 or contact_2) return contacts def GetFootPositionsInBaseFrame(self): """Get the robot's foot position in the base frame.""" assert len(self._foot_link_ids) == self.num_legs foot_positions = [] for foot_id in self.GetFootLinkIDs(): foot_positions.append( kinematics.link_position_in_base_frame( robot=self, link_id=foot_id, )) return np.array(foot_positions) def GetTrueMotorAngles(self): """Gets the eight motor angles at the current moment, mapped to [-pi, pi]. Returns: Motor angles, mapped to [-pi, pi]. """ motor_angles = [state[0] for state in self._joint_states] motor_angles = np.multiply( np.asarray(motor_angles) - np.asarray(self._motor_offset), self._motor_direction) return motor_angles def GetMotorAngles(self): """Gets the eight motor angles. This function mimicks the noisy sensor reading and adds latency. The motor angles that are delayed, noise polluted, and mapped to [-pi, pi]. Returns: Motor angles polluted by noise and latency, mapped to [-pi, pi]. """ motor_angles = self._AddSensorNoise( np.array(self._control_observation[0:self.num_motors]), self._observation_noise_stdev[0]) return MapToMinusPiToPi(motor_angles) def GetTrueMotorVelocities(self): """Get the velocity of all eight motors. Returns: Velocities of all eight motors. """ motor_velocities = [state[1] for state in self._joint_states] motor_velocities = np.multiply(motor_velocities, self._motor_direction) return motor_velocities def GetMotorVelocities(self): """Get the velocity of all eight motors. This function mimicks the noisy sensor reading and adds latency. Returns: Velocities of all eight motors polluted by noise and latency. """ return self._AddSensorNoise( np.array(self._control_observation[self.num_motors:2 * self.num_motors]), self._observation_noise_stdev[1]) def GetTrueMotorTorques(self): """Get the amount of torque the motors are exerting. Returns: Motor torques of all eight motors. """ return self._observed_motor_torques def GetMotorTorques(self): """Get the amount of torque the motors are exerting. This function mimicks the noisy sensor reading and adds latency. Returns: Motor torques of all eight motors polluted by noise and latency. """ return self._AddSensorNoise( np.array(self._control_observation[2 * self.num_motors:3 * self.num_motors]), self._observation_noise_stdev[2]) def GetEnergyConsumptionPerControlStep(self): """Get the amount of energy used in last one time step. Returns: Energy Consumption based on motor velocities and torques (Nm^2/s). """ return np.abs(np.dot( self.GetMotorTorques(), self.GetMotorVelocities())) * self.time_step * self._action_repeat def GetTrueBaseOrientation(self): """Get the orientation of minitaur's base, represented as quaternion. Returns: The orientation of minitaur's base. """ return self._base_orientation def GetBaseOrientation(self): """Get the orientation of minitaur's base, represented as quaternion. This function mimicks the noisy sensor reading and adds latency. Returns: The orientation of minitaur's base polluted by noise and latency. """ return self._pybullet_client.getQuaternionFromEuler( self.GetBaseRollPitchYaw()) def GetTrueBaseRollPitchYawRate(self): """Get the rate of orientation change of the minitaur's base in euler angle. Returns: rate of (roll, pitch, yaw) change of the minitaur's base. """ angular_velocity = self._pybullet_client.getBaseVelocity(self.quadruped)[1] orientation = self.GetTrueBaseOrientation() return self.TransformAngularVelocityToLocalFrame(angular_velocity, orientation) def TransformAngularVelocityToLocalFrame(self, angular_velocity, orientation): """Transform the angular velocity from world frame to robot's frame. Args: angular_velocity: Angular velocity of the robot in world frame. orientation: Orientation of the robot represented as a quaternion. Returns: angular velocity of based on the given orientation. """ # Treat angular velocity as a position vector, then transform based on the # orientation given by dividing (or multiplying with inverse). # Get inverse quaternion assuming the vector is at 0,0,0 origin. _, orientation_inversed = self._pybullet_client.invertTransform( [0, 0, 0], orientation) # Transform the angular_velocity at neutral orientation using a neutral # translation and reverse of the given orientation. relative_velocity, _ = self._pybullet_client.multiplyTransforms( [0, 0, 0], orientation_inversed, angular_velocity, self._pybullet_client.getQuaternionFromEuler([0, 0, 0])) return np.asarray(relative_velocity) def GetBaseRollPitchYawRate(self): """Get the rate of orientation change of the minitaur's base in euler angle. This function mimicks the noisy sensor reading and adds latency. Returns: rate of (roll, pitch, yaw) change of the minitaur's base polluted by noise and latency. """ return self._AddSensorNoise( np.array(self._control_observation[3 * self.num_motors + 4:3 * self.num_motors + 7]), self._observation_noise_stdev[4]) def GetActionDimension(self): """Get the length of the action list. Returns: The length of the action list. """ return self.num_motors def _ApplyOverheatProtection(self, actual_torque): if self._motor_overheat_protection: for i in range(self.num_motors): if abs(actual_torque[i]) > OVERHEAT_SHUTDOWN_TORQUE: self._overheat_counter[i] += 1 else: self._overheat_counter[i] = 0 if (self._overheat_counter[i] > OVERHEAT_SHUTDOWN_TIME / self.time_step): self._motor_enabled_list[i] = False def ApplyAction(self, motor_commands, motor_control_mode=None): """Apply the motor commands using the motor model. Args: motor_commands: np.array. Can be motor angles, torques, hybrid commands, or motor pwms (for Minitaur only). motor_control_mode: A MotorControlMode enum. """ self.last_action_time = self._state_action_counter * self.time_step control_mode = motor_control_mode if control_mode is None: control_mode = self._motor_control_mode motor_commands = np.asarray(motor_commands) q, qdot = self._GetPDObservation() qdot_true = self.GetTrueMotorVelocities() actual_torque, observed_torque = self._motor_model.convert_to_torque( motor_commands, q, qdot, qdot_true, control_mode) # May turn off the motor self._ApplyOverheatProtection(actual_torque) # The torque is already in the observation space because we use # GetMotorAngles and GetMotorVelocities. self._observed_motor_torques = observed_torque # Transform into the motor space when applying the torque. self._applied_motor_torque = np.multiply(actual_torque, self._motor_direction) motor_ids = [] motor_torques = [] for motor_id, motor_torque, motor_enabled in zip( self._motor_id_list, self._applied_motor_torque, self._motor_enabled_list): if motor_enabled: motor_ids.append(motor_id) motor_torques.append(motor_torque) else: motor_ids.append(motor_id) motor_torques.append(0) self._SetMotorTorqueByIds(motor_ids, motor_torques) def ConvertFromLegModel(self, actions): """Convert the actions that use leg model to the real motor actions. Args: actions: The theta, phi of the leg model. Returns: The eight desired motor angles that can be used in ApplyActions(). """ motor_angle = copy.deepcopy(actions) scale_for_singularity = 1 offset_for_singularity = 1.5 half_num_motors = self.num_motors // 2 quater_pi = math.pi / 4 for i in range(self.num_motors): action_idx = i // 2 forward_backward_component = ( -scale_for_singularity * quater_pi * (actions[action_idx + half_num_motors] + offset_for_singularity)) extension_component = (-1)**i * quater_pi * actions[action_idx] if i >= half_num_motors: extension_component = -extension_component motor_angle[i] = (math.pi + forward_backward_component + extension_component) return motor_angle def GetBaseMassesFromURDF(self): """Get the mass of the base from the URDF file.""" return self._base_mass_urdf def GetBaseInertiasFromURDF(self): """Get the inertia of the base from the URDF file.""" return self._base_inertia_urdf def GetLegMassesFromURDF(self): """Get the mass of the legs from the URDF file.""" return self._leg_masses_urdf def GetLegInertiasFromURDF(self): """Get the inertia of the legs from the URDF file.""" return self._leg_inertia_urdf def SetBaseMasses(self, base_mass): """Set the mass of minitaur's base. Args: base_mass: A list of masses of each body link in CHASIS_LINK_IDS. The length of this list should be the same as the length of CHASIS_LINK_IDS. Raises: ValueError: It is raised when the length of base_mass is not the same as the length of self._chassis_link_ids. """ if len(base_mass) != len(self._chassis_link_ids): raise ValueError( "The length of base_mass {} and self._chassis_link_ids {} are not " "the same.".format(len(base_mass), len(self._chassis_link_ids))) for chassis_id, chassis_mass in zip(self._chassis_link_ids, base_mass): self._pybullet_client.changeDynamics(self.quadruped, chassis_id, mass=chassis_mass) def SetLegMasses(self, leg_masses): """Set the mass of the legs. A leg includes leg_link and motor. 4 legs contain 16 links (4 links each) and 8 motors. First 16 numbers correspond to link masses, last 8 correspond to motor masses (24 total). Args: leg_masses: The leg and motor masses for all the leg links and motors. Raises: ValueError: It is raised when the length of masses is not equal to number of links + motors. """ if len(leg_masses) != len(self._leg_link_ids) + len(self._motor_link_ids): raise ValueError("The number of values passed to SetLegMasses are " "different than number of leg links and motors.") for leg_id, leg_mass in zip(self._leg_link_ids, leg_masses): self._pybullet_client.changeDynamics(self.quadruped, leg_id, mass=leg_mass) motor_masses = leg_masses[len(self._leg_link_ids):] for link_id, motor_mass in zip(self._motor_link_ids, motor_masses): self._pybullet_client.changeDynamics(self.quadruped, link_id, mass=motor_mass) def SetBaseInertias(self, base_inertias): """Set the inertias of minitaur's base. Args: base_inertias: A list of inertias of each body link in CHASIS_LINK_IDS. The length of this list should be the same as the length of CHASIS_LINK_IDS. Raises: ValueError: It is raised when the length of base_inertias is not the same as the length of self._chassis_link_ids and base_inertias contains negative values. """ if len(base_inertias) != len(self._chassis_link_ids): raise ValueError( "The length of base_inertias {} and self._chassis_link_ids {} are " "not the same.".format(len(base_inertias), len(self._chassis_link_ids))) for chassis_id, chassis_inertia in zip(self._chassis_link_ids, base_inertias): for inertia_value in chassis_inertia: if (np.asarray(inertia_value) < 0).any(): raise ValueError("Values in inertia matrix should be non-negative.") self._pybullet_client.changeDynamics( self.quadruped, chassis_id, localInertiaDiagonal=chassis_inertia) def SetLegInertias(self, leg_inertias): """Set the inertias of the legs. A leg includes leg_link and motor. 4 legs contain 16 links (4 links each) and 8 motors. First 16 numbers correspond to link inertia, last 8 correspond to motor inertia (24 total). Args: leg_inertias: The leg and motor inertias for all the leg links and motors. Raises: ValueError: It is raised when the length of inertias is not equal to the number of links + motors or leg_inertias contains negative values. """ if len(leg_inertias) != len(self._leg_link_ids) + len( self._motor_link_ids): raise ValueError("The number of values passed to SetLegMasses are " "different than number of leg links and motors.") for leg_id, leg_inertia in zip(self._leg_link_ids, leg_inertias): for inertia_value in leg_inertias: if (np.asarray(inertia_value) < 0).any(): raise ValueError("Values in inertia matrix should be non-negative.") self._pybullet_client.changeDynamics(self.quadruped, leg_id, localInertiaDiagonal=leg_inertia) motor_inertias = leg_inertias[len(self._leg_link_ids):] for link_id, motor_inertia in zip(self._motor_link_ids, motor_inertias): for inertia_value in motor_inertias: if (np.asarray(inertia_value) < 0).any(): raise ValueError("Values in inertia matrix should be non-negative.") self._pybullet_client.changeDynamics(self.quadruped, link_id, localInertiaDiagonal=motor_inertia) def SetFootFriction(self, foot_friction): """Set the lateral friction of the feet. Args: foot_friction: The lateral friction coefficient of the foot. This value is shared by all four feet. """ for link_id in self._foot_link_ids: self._pybullet_client.changeDynamics(self.quadruped, link_id, lateralFriction=foot_friction) def SetFootRestitution(self, foot_restitution): """Set the coefficient of restitution at the feet. Args: foot_restitution: The coefficient of restitution (bounciness) of the feet. This value is shared by all four feet. """ for link_id in self._foot_link_ids: self._pybullet_client.changeDynamics(self.quadruped, link_id, restitution=foot_restitution) def SetJointFriction(self, joint_frictions): for knee_joint_id, friction in zip(self._foot_link_ids, joint_frictions): self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=knee_joint_id, controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=friction) def GetNumKneeJoints(self): return len(self._foot_link_ids) def SetBatteryVoltage(self, voltage): self._motor_model.set_voltage(voltage) def SetMotorViscousDamping(self, viscous_damping): self._motor_model.set_viscous_damping(viscous_damping) def GetTrueObservation(self): observation = [] observation.extend(self.GetTrueMotorAngles()) observation.extend(self.GetTrueMotorVelocities()) observation.extend(self.GetTrueMotorTorques()) observation.extend(self.GetTrueBaseOrientation()) observation.extend(self.GetTrueBaseRollPitchYawRate()) return observation def ReceiveObservation(self): """Receive the observation from sensors. This function is called once per step. The observations are only updated when this function is called. """ self._joint_states = self._pybullet_client.getJointStates( self.quadruped, self._motor_id_list) self._base_position, orientation = ( self._pybullet_client.getBasePositionAndOrientation(self.quadruped)) # Computes the relative orientation relative to the robot's # initial_orientation. _, self._base_orientation = self._pybullet_client.multiplyTransforms( positionA=[0, 0, 0], orientationA=orientation, positionB=[0, 0, 0], orientationB=self._init_orientation_inv) self._observation_history.appendleft(self.GetTrueObservation()) self._control_observation = self._GetControlObservation() self.last_state_time = self._state_action_counter * self.time_step def _GetDelayedObservation(self, latency): """Get observation that is delayed by the amount specified in latency. Args: latency: The latency (in seconds) of the delayed observation. Returns: observation: The observation which was actually latency seconds ago. """ if latency <= 0 or len(self._observation_history) == 1: observation = self._observation_history[0] else: n_steps_ago = int(latency / self.time_step) if n_steps_ago + 1 >= len(self._observation_history): return self._observation_history[-1] remaining_latency = latency - n_steps_ago * self.time_step blend_alpha = remaining_latency / self.time_step observation = ( (1.0 - blend_alpha) * np.array(self._observation_history[n_steps_ago]) + blend_alpha * np.array(self._observation_history[n_steps_ago + 1])) return observation def _GetPDObservation(self): pd_delayed_observation = self._GetDelayedObservation(self._pd_latency) q = pd_delayed_observation[0:self.num_motors] qdot = pd_delayed_observation[self.num_motors:2 * self.num_motors] return (np.array(q), np.array(qdot)) def _GetControlObservation(self): control_delayed_observation = self._GetDelayedObservation( self._control_latency) return control_delayed_observation def _AddSensorNoise(self, sensor_values, noise_stdev): if noise_stdev <= 0: return sensor_values observation = sensor_values + np.random.normal(scale=noise_stdev, size=sensor_values.shape) return observation def SetControlLatency(self, latency): """Set the latency of the control loop. It measures the duration between sending an action from Nvidia TX2 and receiving the observation from microcontroller. Args: latency: The latency (in seconds) of the control loop. """ self._control_latency = latency def GetControlLatency(self): """Get the control latency. Returns: The latency (in seconds) between when the motor command is sent and when the sensor measurements are reported back to the controller. """ return self._control_latency def SetMotorGains(self, kp, kd): """Set the gains of all motors. These gains are PD gains for motor positional control. kp is the proportional gain and kd is the derivative gain. Args: kp: proportional gain(s) of the motors. kd: derivative gain(s) of the motors. """ if isinstance(kp, (collections.Sequence, np.ndarray)): self._motor_kps = np.asarray(kp) else: self._motor_kps = np.full(self.num_motors, kp) if isinstance(kd, (collections.Sequence, np.ndarray)): self._motor_kds = np.asarray(kd) else: self._motor_kds = np.full(self.num_motors, kd) self._motor_model.set_motor_gains(kp, kd) def GetMotorGains(self): """Get the gains of the motor. Returns: The proportional gain. The derivative gain. """ return self._motor_kps, self._motor_kds def GetMotorPositionGains(self): """Get the position gains of the motor. Returns: The proportional gain. """ return self._motor_kps def GetMotorVelocityGains(self): """Get the velocity gains of the motor. Returns: The derivative gain. """ return self._motor_kds def SetMotorStrengthRatio(self, ratio): """Set the strength of all motors relative to the default value. Args: ratio: The relative strength. A scalar range from 0.0 to 1.0. """ self._motor_model.set_strength_ratios([ratio] * self.num_motors) def SetMotorStrengthRatios(self, ratios): """Set the strength of each motor relative to the default value. Args: ratios: The relative strength. A numpy array ranging from 0.0 to 1.0. """ self._motor_model.set_strength_ratios(ratios) def SetTimeSteps(self, action_repeat, simulation_step): """Set the time steps of the control and simulation. Args: action_repeat: The number of simulation steps that the same action is repeated. simulation_step: The simulation time step. """ self.time_step = simulation_step self._action_repeat = action_repeat def _GetMotorNames(self): return MOTOR_NAMES def _GetDefaultInitPosition(self): """Returns the init position of the robot. It can be either 1) origin (INIT_POSITION), 2) origin with a rack (INIT_RACK_POSITION), or 3) the previous position. """ # If we want continuous resetting and is not the first episode. if self._reset_at_current_position and self._observation_history: x, y, _ = self.GetBasePosition() _, _, z = INIT_POSITION return [x, y, z] if self._on_rack: return INIT_RACK_POSITION else: return INIT_POSITION def _GetDefaultInitOrientation(self): """Returns the init position of the robot. It can be either 1) INIT_ORIENTATION or 2) the previous rotation in yaw. """ # If we want continuous resetting and is not the first episode. if self._reset_at_current_position and self._observation_history: _, _, yaw = self.GetBaseRollPitchYaw() return self._pybullet_client.getQuaternionFromEuler([0.0, 0.0, yaw]) return INIT_ORIENTATION @property def chassis_link_ids(self): return self._chassis_link_ids def SetAllSensors(self, sensors): """set all sensors to this robot and move the ownership to this robot. Args: sensors: a list of sensors to this robot. """ for s in sensors: s.set_robot(self) self._sensors = sensors def GetAllSensors(self): """get all sensors associated with this robot. Returns: sensors: a list of all sensors. """ return self._sensors def GetSensor(self, name): """get the first sensor with the given name. This function return None if a sensor with the given name does not exist. Args: name: the name of the sensor we are looking Returns: sensor: a sensor with the given name. None if not exists. """ for s in self._sensors: if s.get_name() == name: return s return None @property def is_safe(self): return self._is_safe @property def last_action(self): return self._last_action def ProcessAction(self, action, substep_count): """If enabled, interpolates between the current and previous actions. Args: action: current action. substep_count: the step count should be between [0, self.__action_repeat). Returns: If interpolation is enabled, returns interpolated action depending on the current action repeat substep. """ if self._enable_action_interpolation and self._last_action is not None: lerp = float(substep_count + 1) / self._action_repeat proc_action = self._last_action + lerp * (action - self._last_action) else: proc_action = action return proc_action def _BuildActionFilter(self): sampling_rate = 1 / (self.time_step * self._action_repeat) num_joints = self.GetActionDimension() a_filter = action_filter.ActionFilterButter(sampling_rate=sampling_rate, num_joints=num_joints) return a_filter def _ResetActionFilter(self): self._action_filter.reset() def _FilterAction(self, action): # initialize the filter history, since resetting the filter will fill # the history with zeros and this can cause sudden movements at the start # of each episode if self._step_counter == 0: default_action = self.GetMotorAngles() self._action_filter.init_history(default_action) filtered_action = self._action_filter.filter(action) return filtered_action @property def pybullet_client(self): return self._pybullet_client @property def joint_states(self): return self._joint_states @classmethod def GetConstants(cls): del cls return minitaur_constants
locomotion/robots/minitaur.py
"""This file implements the functionalities of a minitaur using pybullet.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import copy import math import re import numpy as np from locomotion.robots import minitaur_constants from locomotion.robots import minitaur_motor from locomotion.robots import robot_config from locomotion.robots import action_filter from locomotion.robots import kinematics INIT_POSITION = [0, 0, .2] INIT_RACK_POSITION = [0, 0, 1] INIT_ORIENTATION = [0, 0, 0, 1] KNEE_CONSTRAINT_POINT_RIGHT = [0, 0.005, 0.2] KNEE_CONSTRAINT_POINT_LEFT = [0, 0.01, 0.2] OVERHEAT_SHUTDOWN_TORQUE = 2.45 OVERHEAT_SHUTDOWN_TIME = 1.0 LEG_POSITION = ["front_left", "back_left", "front_right", "back_right"] MOTOR_NAMES = [ "motor_front_leftL_joint", "motor_front_leftR_joint", "motor_back_leftL_joint", "motor_back_leftR_joint", "motor_front_rightL_joint", "motor_front_rightR_joint", "motor_back_rightL_joint", "motor_back_rightR_joint" ] _CHASSIS_NAME_PATTERN = re.compile(r"chassis\D*center") _MOTOR_NAME_PATTERN = re.compile(r"motor\D*joint") _KNEE_NAME_PATTERN = re.compile(r"knee\D*") _BRACKET_NAME_PATTERN = re.compile(r"motor\D*_bracket_joint") _LEG_NAME_PATTERN1 = re.compile(r"hip\D*joint") _LEG_NAME_PATTERN2 = re.compile(r"hip\D*link") _LEG_NAME_PATTERN3 = re.compile(r"motor\D*link") SENSOR_NOISE_STDDEV = (0.0, 0.0, 0.0, 0.0, 0.0) MINITAUR_DEFAULT_MOTOR_DIRECTIONS = (-1, -1, -1, -1, 1, 1, 1, 1) MINITAUR_DEFAULT_MOTOR_OFFSETS = (0, 0, 0, 0, 0, 0, 0, 0) MINITAUR_NUM_MOTORS = 8 TWO_PI = 2 * math.pi MINITAUR_DOFS_PER_LEG = 2 def MapToMinusPiToPi(angles): """Maps a list of angles to [-pi, pi]. Args: angles: A list of angles in rad. Returns: A list of angle mapped to [-pi, pi]. """ mapped_angles = copy.deepcopy(angles) for i in range(len(angles)): mapped_angles[i] = math.fmod(angles[i], TWO_PI) if mapped_angles[i] >= math.pi: mapped_angles[i] -= TWO_PI elif mapped_angles[i] < -math.pi: mapped_angles[i] += TWO_PI return mapped_angles class Minitaur(object): """The minitaur class that simulates a quadruped robot from Ghost Robotics.""" def __init__(self, pybullet_client, num_motors=MINITAUR_NUM_MOTORS, dofs_per_leg=MINITAUR_DOFS_PER_LEG, time_step=0.01, action_repeat=1, self_collision_enabled=False, motor_control_mode=robot_config.MotorControlMode.POSITION, motor_model_class=minitaur_motor.MotorModel, motor_kp=1.0, motor_kd=0.02, motor_torque_limits=None, pd_latency=0.0, control_latency=0.0, observation_noise_stdev=SENSOR_NOISE_STDDEV, motor_overheat_protection=False, motor_direction=MINITAUR_DEFAULT_MOTOR_DIRECTIONS, motor_offset=MINITAUR_DEFAULT_MOTOR_OFFSETS, on_rack=False, reset_at_current_position=False, sensors=None, enable_action_interpolation=False, enable_action_filter=False, reset_time=-1): """Constructs a minitaur and reset it to the initial states. Args: pybullet_client: The instance of BulletClient to manage different simulations. num_motors: The number of the motors on the robot. dofs_per_leg: The number of degrees of freedom for each leg. time_step: The time step of the simulation. action_repeat: The number of ApplyAction() for each control step. self_collision_enabled: Whether to enable self collision. motor_control_mode: Enum. Can either be POSITION, TORQUE, or HYBRID. motor_model_class: We can choose from simple pd model to more accureate DC motor models. motor_kp: proportional gain for the motors. motor_kd: derivative gain for the motors. motor_torque_limits: Torque limits for the motors. Can be a single float or a list of floats specifying different limits for different robots. If not provided, the default limit of the robot is used. pd_latency: The latency of the observations (in seconds) used to calculate PD control. On the real hardware, it is the latency between the microcontroller and the motor controller. control_latency: The latency of the observations (in second) used to calculate action. On the real hardware, it is the latency from the motor controller, the microcontroller to the host (Nvidia TX2). observation_noise_stdev: The standard deviation of a Gaussian noise model for the sensor. It should be an array for separate sensors in the following order [motor_angle, motor_velocity, motor_torque, base_roll_pitch_yaw, base_angular_velocity] motor_overheat_protection: Whether to shutdown the motor that has exerted large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more details. motor_direction: A list of direction values, either 1 or -1, to compensate the axis difference of motors between the simulation and the real robot. motor_offset: A list of offset value for the motor angles. This is used to compensate the angle difference between the simulation and the real robot. on_rack: Whether to place the minitaur on rack. This is only used to debug the walking gait. In this mode, the minitaur's base is hanged midair so that its walking gait is clearer to visualize. reset_at_current_position: Whether to reset the minitaur at the current position and orientation. This is for simulating the reset behavior in the real world. sensors: a list of sensors that are attached to the robot. enable_action_interpolation: Whether to interpolate the current action with the previous action in order to produce smoother motions enable_action_filter: Boolean specifying if a lowpass filter should be used to smooth actions. """ self.num_motors = num_motors self.num_legs = self.num_motors // dofs_per_leg self._pybullet_client = pybullet_client self._action_repeat = action_repeat self._self_collision_enabled = self_collision_enabled self._motor_direction = motor_direction self._motor_offset = motor_offset self._observed_motor_torques = np.zeros(self.num_motors) self._applied_motor_torques = np.zeros(self.num_motors) self._max_force = 3.5 self._pd_latency = pd_latency self._control_latency = control_latency self._observation_noise_stdev = observation_noise_stdev self._observation_history = collections.deque(maxlen=100) self._control_observation = [] self._chassis_link_ids = [-1] self._leg_link_ids = [] self._motor_link_ids = [] self._foot_link_ids = [] self._motor_overheat_protection = motor_overheat_protection self._on_rack = on_rack self._reset_at_current_position = reset_at_current_position self.SetAllSensors(sensors if sensors is not None else list()) self._is_safe = True self._enable_action_interpolation = enable_action_interpolation self._enable_action_filter = enable_action_filter self._last_action = None if not motor_model_class: raise ValueError("Must provide a motor model class!") if self._on_rack and self._reset_at_current_position: raise ValueError("on_rack and reset_at_current_position " "cannot be enabled together") if isinstance(motor_kp, (collections.Sequence, np.ndarray)): self._motor_kps = np.asarray(motor_kp) else: self._motor_kps = np.full(num_motors, motor_kp) if isinstance(motor_kd, (collections.Sequence, np.ndarray)): self._motor_kds = np.asarray(motor_kd) else: self._motor_kds = np.full(num_motors, motor_kd) if isinstance(motor_torque_limits, (collections.Sequence, np.ndarray)): self._motor_torque_limits = np.asarray(motor_torque_limits) elif motor_torque_limits is None: self._motor_torque_limits = None else: self._motor_torque_limits = motor_torque_limits self._motor_control_mode = motor_control_mode self._motor_model = motor_model_class( kp=motor_kp, kd=motor_kd, torque_limits=self._motor_torque_limits, motor_control_mode=motor_control_mode) self.time_step = time_step self._step_counter = 0 # This also includes the time spent during the Reset motion. self._state_action_counter = 0 _, self._init_orientation_inv = self._pybullet_client.invertTransform( position=[0, 0, 0], orientation=self._GetDefaultInitOrientation()) if self._enable_action_filter: self._action_filter = self._BuildActionFilter() # reset_time=-1.0 means skipping the reset motion. # See Reset for more details. self.Reset(reset_time=reset_time) self.ReceiveObservation() def GetTimeSinceReset(self): return self._step_counter * self.time_step def _StepInternal(self, action, motor_control_mode=None): self.ApplyAction(action, motor_control_mode) self._pybullet_client.stepSimulation() self.ReceiveObservation() self._state_action_counter += 1 def Step(self, action, motor_control_mode=None): """Steps simulation.""" if self._enable_action_filter: action = self._FilterAction(action) for i in range(self._action_repeat): proc_action = self.ProcessAction(action, i) self._StepInternal(proc_action, motor_control_mode) self._step_counter += 1 self._last_action = action def Terminate(self): pass def GetFootLinkIDs(self): """Get list of IDs for all foot links.""" return self._foot_link_ids def _RecordMassInfoFromURDF(self): """Records the mass information from the URDF file.""" self._base_mass_urdf = [] for chassis_id in self._chassis_link_ids: self._base_mass_urdf.append( self._pybullet_client.getDynamicsInfo(self.quadruped, chassis_id)[0]) self._leg_masses_urdf = [] for leg_id in self._leg_link_ids: self._leg_masses_urdf.append( self._pybullet_client.getDynamicsInfo(self.quadruped, leg_id)[0]) for motor_id in self._motor_link_ids: self._leg_masses_urdf.append( self._pybullet_client.getDynamicsInfo(self.quadruped, motor_id)[0]) def _RecordInertiaInfoFromURDF(self): """Record the inertia of each body from URDF file.""" self._link_urdf = [] num_bodies = self._pybullet_client.getNumJoints(self.quadruped) for body_id in range(-1, num_bodies): # -1 is for the base link. inertia = self._pybullet_client.getDynamicsInfo(self.quadruped, body_id)[2] self._link_urdf.append(inertia) # We need to use id+1 to index self._link_urdf because it has the base # (index = -1) at the first element. self._base_inertia_urdf = [ self._link_urdf[chassis_id + 1] for chassis_id in self._chassis_link_ids ] self._leg_inertia_urdf = [ self._link_urdf[leg_id + 1] for leg_id in self._leg_link_ids ] self._leg_inertia_urdf.extend( [self._link_urdf[motor_id + 1] for motor_id in self._motor_link_ids]) def _BuildJointNameToIdDict(self): num_joints = self._pybullet_client.getNumJoints(self.quadruped) self._joint_name_to_id = {} for i in range(num_joints): joint_info = self._pybullet_client.getJointInfo(self.quadruped, i) self._joint_name_to_id[joint_info[1].decode("UTF-8")] = joint_info[0] def _BuildUrdfIds(self): """Build the link Ids from its name in the URDF file. Raises: ValueError: Unknown category of the joint name. """ num_joints = self._pybullet_client.getNumJoints(self.quadruped) self._chassis_link_ids = [-1] # The self._leg_link_ids include both the upper and lower links of the leg. self._leg_link_ids = [] self._motor_link_ids = [] self._foot_link_ids = [] self._bracket_link_ids = [] for i in range(num_joints): joint_info = self._pybullet_client.getJointInfo(self.quadruped, i) joint_name = joint_info[1].decode("UTF-8") joint_id = self._joint_name_to_id[joint_name] if _CHASSIS_NAME_PATTERN.match(joint_name): self._chassis_link_ids.append(joint_id) elif _BRACKET_NAME_PATTERN.match(joint_name): self._bracket_link_ids.append(joint_id) elif _MOTOR_NAME_PATTERN.match(joint_name): self._motor_link_ids.append(joint_id) elif _KNEE_NAME_PATTERN.match(joint_name): self._foot_link_ids.append(joint_id) elif (_LEG_NAME_PATTERN1.match(joint_name) or _LEG_NAME_PATTERN2.match(joint_name) or _LEG_NAME_PATTERN3.match(joint_name)): self._leg_link_ids.append(joint_id) else: raise ValueError("Unknown category of joint %s" % joint_name) self._leg_link_ids.extend(self._foot_link_ids) self._chassis_link_ids.sort() self._motor_link_ids.sort() self._foot_link_ids.sort() self._leg_link_ids.sort() self._bracket_link_ids.sort() def _RemoveDefaultJointDamping(self): num_joints = self._pybullet_client.getNumJoints(self.quadruped) for i in range(num_joints): joint_info = self._pybullet_client.getJointInfo(self.quadruped, i) self._pybullet_client.changeDynamics(joint_info[0], -1, linearDamping=0, angularDamping=0) def _BuildMotorIdList(self): self._motor_id_list = [ self._joint_name_to_id[motor_name] for motor_name in self._GetMotorNames() ] def _CreateRackConstraint(self, init_position, init_orientation): """Create a constraint that keeps the chassis at a fixed frame. This frame is defined by init_position and init_orientation. Args: init_position: initial position of the fixed frame. init_orientation: initial orientation of the fixed frame in quaternion format [x,y,z,w]. Returns: Return the constraint id. """ fixed_constraint = self._pybullet_client.createConstraint( parentBodyUniqueId=self.quadruped, parentLinkIndex=-1, childBodyUniqueId=-1, childLinkIndex=-1, jointType=self._pybullet_client.JOINT_FIXED, jointAxis=[0, 0, 0], parentFramePosition=[0, 0, 0], childFramePosition=init_position, childFrameOrientation=init_orientation) return fixed_constraint def IsObservationValid(self): """Whether the observation is valid for the current time step. In simulation, observations are always valid. In real hardware, it may not be valid from time to time when communication error happens between the Nvidia TX2 and the microcontroller. Returns: Whether the observation is valid for the current time step. """ return True def Reset(self, reload_urdf=True, default_motor_angles=None, reset_time=3.0): """Reset the minitaur to its initial states. Args: reload_urdf: Whether to reload the urdf file. If not, Reset() just place the minitaur back to its starting position. default_motor_angles: The default motor angles. If it is None, minitaur will hold a default pose (motor angle math.pi / 2) for 100 steps. In torque control mode, the phase of holding the default pose is skipped. reset_time: The duration (in seconds) to hold the default motor angles. If reset_time <= 0 or in torque control mode, the phase of holding the default pose is skipped. """ if reload_urdf: self._LoadRobotURDF() if self._on_rack: self.rack_constraint = (self._CreateRackConstraint( self._GetDefaultInitPosition(), self._GetDefaultInitOrientation())) self._BuildJointNameToIdDict() self._BuildUrdfIds() self._RemoveDefaultJointDamping() self._BuildMotorIdList() self._RecordMassInfoFromURDF() self._RecordInertiaInfoFromURDF() self.ResetPose(add_constraint=True) else: self._pybullet_client.resetBasePositionAndOrientation( self.quadruped, self._GetDefaultInitPosition(), self._GetDefaultInitOrientation()) self._pybullet_client.resetBaseVelocity(self.quadruped, [0, 0, 0], [0, 0, 0]) self.ResetPose(add_constraint=False) self._overheat_counter = np.zeros(self.num_motors) self._motor_enabled_list = [True] * self.num_motors self._observation_history.clear() self._step_counter = 0 self._state_action_counter = 0 self._is_safe = True self._last_action = None self._SettleDownForReset(default_motor_angles, reset_time) if self._enable_action_filter: self._ResetActionFilter() def _LoadRobotURDF(self): """Loads the URDF file for the robot.""" urdf_file = self.GetURDFFile() if self._self_collision_enabled: self.quadruped = self._pybullet_client.loadURDF( urdf_file, self._GetDefaultInitPosition(), self._GetDefaultInitOrientation(), flags=self._pybullet_client.URDF_USE_SELF_COLLISION) else: self.quadruped = self._pybullet_client.loadURDF( urdf_file, self._GetDefaultInitPosition(), self._GetDefaultInitOrientation()) def _SettleDownForReset(self, default_motor_angles, reset_time): """Sets the default motor angles and waits for the robot to settle down. The reset is skipped is reset_time is less than zereo. Args: default_motor_angles: A list of motor angles that the robot will achieve at the end of the reset phase. reset_time: The time duration for the reset phase. """ if reset_time <= 0: return # Important to fill the observation buffer. self.ReceiveObservation() for _ in range(100): self._StepInternal( [math.pi / 2] * self.num_motors, motor_control_mode=robot_config.MotorControlMode.POSITION) # Don't continue to reset if a safety error has occurred. if not self._is_safe: return if default_motor_angles is None: return num_steps_to_reset = int(reset_time / self.time_step) for _ in range(num_steps_to_reset): self._StepInternal( default_motor_angles, motor_control_mode=robot_config.MotorControlMode.POSITION) # Don't continue to reset if a safety error has occurred. if not self._is_safe: return def _SetMotorTorqueById(self, motor_id, torque): self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=motor_id, controlMode=self._pybullet_client.TORQUE_CONTROL, force=torque) def _SetMotorTorqueByIds(self, motor_ids, torques): self._pybullet_client.setJointMotorControlArray( bodyIndex=self.quadruped, jointIndices=motor_ids, controlMode=self._pybullet_client.TORQUE_CONTROL, forces=torques) def _SetDesiredMotorAngleByName(self, motor_name, desired_angle): self._SetDesiredMotorAngleById(self._joint_name_to_id[motor_name], desired_angle) def GetURDFFile(self): return "quadruped/minitaur.urdf" def ResetPose(self, add_constraint): """Reset the pose of the minitaur. Args: add_constraint: Whether to add a constraint at the joints of two feet. """ for i in range(self.num_legs): self._ResetPoseForLeg(i, add_constraint) def _ResetPoseForLeg(self, leg_id, add_constraint): """Reset the initial pose for the leg. Args: leg_id: It should be 0, 1, 2, or 3, which represents the leg at front_left, back_left, front_right and back_right. add_constraint: Whether to add a constraint at the joints of two feet. """ knee_friction_force = 0 half_pi = math.pi / 2.0 knee_angle = -2.1834 leg_position = LEG_POSITION[leg_id] self._pybullet_client.resetJointState( self.quadruped, self._joint_name_to_id["motor_" + leg_position + "L_joint"], self._motor_direction[2 * leg_id] * half_pi, targetVelocity=0) self._pybullet_client.resetJointState( self.quadruped, self._joint_name_to_id["knee_" + leg_position + "L_link"], self._motor_direction[2 * leg_id] * knee_angle, targetVelocity=0) self._pybullet_client.resetJointState( self.quadruped, self._joint_name_to_id["motor_" + leg_position + "R_joint"], self._motor_direction[2 * leg_id + 1] * half_pi, targetVelocity=0) self._pybullet_client.resetJointState( self.quadruped, self._joint_name_to_id["knee_" + leg_position + "R_link"], self._motor_direction[2 * leg_id + 1] * knee_angle, targetVelocity=0) if add_constraint: self._pybullet_client.createConstraint( self.quadruped, self._joint_name_to_id["knee_" + leg_position + "R_link"], self.quadruped, self._joint_name_to_id["knee_" + leg_position + "L_link"], self._pybullet_client.JOINT_POINT2POINT, [0, 0, 0], KNEE_CONSTRAINT_POINT_RIGHT, KNEE_CONSTRAINT_POINT_LEFT) # Disable the default motor in pybullet. self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["motor_" + leg_position + "L_joint"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["motor_" + leg_position + "R_joint"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["knee_" + leg_position + "L_link"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["knee_" + leg_position + "R_link"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) def GetBasePosition(self): """Get the position of minitaur's base. Returns: The position of minitaur's base. """ return self._base_position def GetBaseVelocity(self): """Get the linear velocity of minitaur's base. Returns: The velocity of minitaur's base. """ velocity, _ = self._pybullet_client.getBaseVelocity(self.quadruped) return velocity def GetTrueBaseRollPitchYaw(self): """Get minitaur's base orientation in euler angle in the world frame. Returns: A tuple (roll, pitch, yaw) of the base in world frame. """ orientation = self.GetTrueBaseOrientation() roll_pitch_yaw = self._pybullet_client.getEulerFromQuaternion(orientation) return np.asarray(roll_pitch_yaw) def GetBaseRollPitchYaw(self): """Get minitaur's base orientation in euler angle in the world frame. This function mimicks the noisy sensor reading and adds latency. Returns: A tuple (roll, pitch, yaw) of the base in world frame polluted by noise and latency. """ delayed_orientation = np.array( self._control_observation[3 * self.num_motors:3 * self.num_motors + 4]) delayed_roll_pitch_yaw = self._pybullet_client.getEulerFromQuaternion( delayed_orientation) roll_pitch_yaw = self._AddSensorNoise(np.array(delayed_roll_pitch_yaw), self._observation_noise_stdev[3]) return roll_pitch_yaw def GetHipPositionsInBaseFrame(self): """Get the hip joint positions of the robot within its base frame.""" raise NotImplementedError("Not implemented for Minitaur.") def ComputeMotorAnglesFromFootLocalPosition(self, leg_id, foot_local_position): """Use IK to compute the motor angles, given the foot link's local position. Args: leg_id: The leg index. foot_local_position: The foot link's position in the base frame. Returns: A tuple. The position indices and the angles for all joints along the leg. The position indices is consistent with the joint orders as returned by GetMotorAngles API. """ assert len(self._foot_link_ids) == self.num_legs toe_id = self._foot_link_ids[leg_id] motors_per_leg = self.num_motors // self.num_legs joint_position_idxs = list( range(leg_id * motors_per_leg, leg_id * motors_per_leg + motors_per_leg)) joint_angles = kinematics.joint_angles_from_link_position( robot=self, link_position=foot_local_position, link_id=toe_id, joint_ids=joint_position_idxs, ) # Joint offset is necessary for Laikago. joint_angles = np.multiply( np.asarray(joint_angles) - np.asarray(self._motor_offset)[joint_position_idxs], self._motor_direction[joint_position_idxs]) # Return the joing index (the same as when calling GetMotorAngles) as well # as the angles. return joint_position_idxs, joint_angles.tolist() def ComputeJacobian(self, leg_id): """Compute the Jacobian for a given leg.""" # Does not work for Minitaur which has the four bar mechanism for now. assert len(self._foot_link_ids) == self.num_legs full_jacobian = kinematics.compute_jacobian( robot=self, link_id=self._foot_link_ids[leg_id], ) motors_per_leg = self.num_motors // self.num_legs com_dof = 6 return full_jacobian[com_dof + leg_id * motors_per_leg:com_dof + (leg_id + 1) * motors_per_leg] def MapContactForceToJointTorques(self, leg_id, contact_force): """Maps the foot contact force to the leg joint torques.""" jv = self.ComputeJacobian(leg_id) motor_torques_list = np.matmul(contact_force, jv) motor_torques_dict = {} motors_per_leg = self.num_motors // self.num_legs for torque_id, joint_id in enumerate( range(leg_id * motors_per_leg, (leg_id + 1) * motors_per_leg)): motor_torques_dict[joint_id] = motor_torques_list[torque_id] return motor_torques_dict def GetFootContacts(self): """Get minitaur's foot contact situation with the ground. Returns: A list of 4 booleans. The ith boolean is True if leg i is in contact with ground. """ contacts = [] for leg_idx in range(MINITAUR_NUM_MOTORS // 2): link_id_1 = self._foot_link_ids[leg_idx * 2] link_id_2 = self._foot_link_ids[leg_idx * 2 + 1] contact_1 = bool( self._pybullet_client.getContactPoints(bodyA=0, bodyB=self.quadruped, linkIndexA=-1, linkIndexB=link_id_1)) contact_2 = bool( self._pybullet_client.getContactPoints(bodyA=0, bodyB=self.quadruped, linkIndexA=-1, linkIndexB=link_id_2)) contacts.append(contact_1 or contact_2) return contacts def GetFootPositionsInBaseFrame(self): """Get the robot's foot position in the base frame.""" assert len(self._foot_link_ids) == self.num_legs foot_positions = [] for foot_id in self.GetFootLinkIDs(): foot_positions.append( kinematics.link_position_in_base_frame( robot=self, link_id=foot_id, )) return np.array(foot_positions) def GetTrueMotorAngles(self): """Gets the eight motor angles at the current moment, mapped to [-pi, pi]. Returns: Motor angles, mapped to [-pi, pi]. """ motor_angles = [state[0] for state in self._joint_states] motor_angles = np.multiply( np.asarray(motor_angles) - np.asarray(self._motor_offset), self._motor_direction) return motor_angles def GetMotorAngles(self): """Gets the eight motor angles. This function mimicks the noisy sensor reading and adds latency. The motor angles that are delayed, noise polluted, and mapped to [-pi, pi]. Returns: Motor angles polluted by noise and latency, mapped to [-pi, pi]. """ motor_angles = self._AddSensorNoise( np.array(self._control_observation[0:self.num_motors]), self._observation_noise_stdev[0]) return MapToMinusPiToPi(motor_angles) def GetTrueMotorVelocities(self): """Get the velocity of all eight motors. Returns: Velocities of all eight motors. """ motor_velocities = [state[1] for state in self._joint_states] motor_velocities = np.multiply(motor_velocities, self._motor_direction) return motor_velocities def GetMotorVelocities(self): """Get the velocity of all eight motors. This function mimicks the noisy sensor reading and adds latency. Returns: Velocities of all eight motors polluted by noise and latency. """ return self._AddSensorNoise( np.array(self._control_observation[self.num_motors:2 * self.num_motors]), self._observation_noise_stdev[1]) def GetTrueMotorTorques(self): """Get the amount of torque the motors are exerting. Returns: Motor torques of all eight motors. """ return self._observed_motor_torques def GetMotorTorques(self): """Get the amount of torque the motors are exerting. This function mimicks the noisy sensor reading and adds latency. Returns: Motor torques of all eight motors polluted by noise and latency. """ return self._AddSensorNoise( np.array(self._control_observation[2 * self.num_motors:3 * self.num_motors]), self._observation_noise_stdev[2]) def GetEnergyConsumptionPerControlStep(self): """Get the amount of energy used in last one time step. Returns: Energy Consumption based on motor velocities and torques (Nm^2/s). """ return np.abs(np.dot( self.GetMotorTorques(), self.GetMotorVelocities())) * self.time_step * self._action_repeat def GetTrueBaseOrientation(self): """Get the orientation of minitaur's base, represented as quaternion. Returns: The orientation of minitaur's base. """ return self._base_orientation def GetBaseOrientation(self): """Get the orientation of minitaur's base, represented as quaternion. This function mimicks the noisy sensor reading and adds latency. Returns: The orientation of minitaur's base polluted by noise and latency. """ return self._pybullet_client.getQuaternionFromEuler( self.GetBaseRollPitchYaw()) def GetTrueBaseRollPitchYawRate(self): """Get the rate of orientation change of the minitaur's base in euler angle. Returns: rate of (roll, pitch, yaw) change of the minitaur's base. """ angular_velocity = self._pybullet_client.getBaseVelocity(self.quadruped)[1] orientation = self.GetTrueBaseOrientation() return self.TransformAngularVelocityToLocalFrame(angular_velocity, orientation) def TransformAngularVelocityToLocalFrame(self, angular_velocity, orientation): """Transform the angular velocity from world frame to robot's frame. Args: angular_velocity: Angular velocity of the robot in world frame. orientation: Orientation of the robot represented as a quaternion. Returns: angular velocity of based on the given orientation. """ # Treat angular velocity as a position vector, then transform based on the # orientation given by dividing (or multiplying with inverse). # Get inverse quaternion assuming the vector is at 0,0,0 origin. _, orientation_inversed = self._pybullet_client.invertTransform( [0, 0, 0], orientation) # Transform the angular_velocity at neutral orientation using a neutral # translation and reverse of the given orientation. relative_velocity, _ = self._pybullet_client.multiplyTransforms( [0, 0, 0], orientation_inversed, angular_velocity, self._pybullet_client.getQuaternionFromEuler([0, 0, 0])) return np.asarray(relative_velocity) def GetBaseRollPitchYawRate(self): """Get the rate of orientation change of the minitaur's base in euler angle. This function mimicks the noisy sensor reading and adds latency. Returns: rate of (roll, pitch, yaw) change of the minitaur's base polluted by noise and latency. """ return self._AddSensorNoise( np.array(self._control_observation[3 * self.num_motors + 4:3 * self.num_motors + 7]), self._observation_noise_stdev[4]) def GetActionDimension(self): """Get the length of the action list. Returns: The length of the action list. """ return self.num_motors def _ApplyOverheatProtection(self, actual_torque): if self._motor_overheat_protection: for i in range(self.num_motors): if abs(actual_torque[i]) > OVERHEAT_SHUTDOWN_TORQUE: self._overheat_counter[i] += 1 else: self._overheat_counter[i] = 0 if (self._overheat_counter[i] > OVERHEAT_SHUTDOWN_TIME / self.time_step): self._motor_enabled_list[i] = False def ApplyAction(self, motor_commands, motor_control_mode=None): """Apply the motor commands using the motor model. Args: motor_commands: np.array. Can be motor angles, torques, hybrid commands, or motor pwms (for Minitaur only). motor_control_mode: A MotorControlMode enum. """ self.last_action_time = self._state_action_counter * self.time_step control_mode = motor_control_mode if control_mode is None: control_mode = self._motor_control_mode motor_commands = np.asarray(motor_commands) q, qdot = self._GetPDObservation() qdot_true = self.GetTrueMotorVelocities() actual_torque, observed_torque = self._motor_model.convert_to_torque( motor_commands, q, qdot, qdot_true, control_mode) # May turn off the motor self._ApplyOverheatProtection(actual_torque) # The torque is already in the observation space because we use # GetMotorAngles and GetMotorVelocities. self._observed_motor_torques = observed_torque # Transform into the motor space when applying the torque. self._applied_motor_torque = np.multiply(actual_torque, self._motor_direction) motor_ids = [] motor_torques = [] for motor_id, motor_torque, motor_enabled in zip( self._motor_id_list, self._applied_motor_torque, self._motor_enabled_list): if motor_enabled: motor_ids.append(motor_id) motor_torques.append(motor_torque) else: motor_ids.append(motor_id) motor_torques.append(0) self._SetMotorTorqueByIds(motor_ids, motor_torques) def ConvertFromLegModel(self, actions): """Convert the actions that use leg model to the real motor actions. Args: actions: The theta, phi of the leg model. Returns: The eight desired motor angles that can be used in ApplyActions(). """ motor_angle = copy.deepcopy(actions) scale_for_singularity = 1 offset_for_singularity = 1.5 half_num_motors = self.num_motors // 2 quater_pi = math.pi / 4 for i in range(self.num_motors): action_idx = i // 2 forward_backward_component = ( -scale_for_singularity * quater_pi * (actions[action_idx + half_num_motors] + offset_for_singularity)) extension_component = (-1)**i * quater_pi * actions[action_idx] if i >= half_num_motors: extension_component = -extension_component motor_angle[i] = (math.pi + forward_backward_component + extension_component) return motor_angle def GetBaseMassesFromURDF(self): """Get the mass of the base from the URDF file.""" return self._base_mass_urdf def GetBaseInertiasFromURDF(self): """Get the inertia of the base from the URDF file.""" return self._base_inertia_urdf def GetLegMassesFromURDF(self): """Get the mass of the legs from the URDF file.""" return self._leg_masses_urdf def GetLegInertiasFromURDF(self): """Get the inertia of the legs from the URDF file.""" return self._leg_inertia_urdf def SetBaseMasses(self, base_mass): """Set the mass of minitaur's base. Args: base_mass: A list of masses of each body link in CHASIS_LINK_IDS. The length of this list should be the same as the length of CHASIS_LINK_IDS. Raises: ValueError: It is raised when the length of base_mass is not the same as the length of self._chassis_link_ids. """ if len(base_mass) != len(self._chassis_link_ids): raise ValueError( "The length of base_mass {} and self._chassis_link_ids {} are not " "the same.".format(len(base_mass), len(self._chassis_link_ids))) for chassis_id, chassis_mass in zip(self._chassis_link_ids, base_mass): self._pybullet_client.changeDynamics(self.quadruped, chassis_id, mass=chassis_mass) def SetLegMasses(self, leg_masses): """Set the mass of the legs. A leg includes leg_link and motor. 4 legs contain 16 links (4 links each) and 8 motors. First 16 numbers correspond to link masses, last 8 correspond to motor masses (24 total). Args: leg_masses: The leg and motor masses for all the leg links and motors. Raises: ValueError: It is raised when the length of masses is not equal to number of links + motors. """ if len(leg_masses) != len(self._leg_link_ids) + len(self._motor_link_ids): raise ValueError("The number of values passed to SetLegMasses are " "different than number of leg links and motors.") for leg_id, leg_mass in zip(self._leg_link_ids, leg_masses): self._pybullet_client.changeDynamics(self.quadruped, leg_id, mass=leg_mass) motor_masses = leg_masses[len(self._leg_link_ids):] for link_id, motor_mass in zip(self._motor_link_ids, motor_masses): self._pybullet_client.changeDynamics(self.quadruped, link_id, mass=motor_mass) def SetBaseInertias(self, base_inertias): """Set the inertias of minitaur's base. Args: base_inertias: A list of inertias of each body link in CHASIS_LINK_IDS. The length of this list should be the same as the length of CHASIS_LINK_IDS. Raises: ValueError: It is raised when the length of base_inertias is not the same as the length of self._chassis_link_ids and base_inertias contains negative values. """ if len(base_inertias) != len(self._chassis_link_ids): raise ValueError( "The length of base_inertias {} and self._chassis_link_ids {} are " "not the same.".format(len(base_inertias), len(self._chassis_link_ids))) for chassis_id, chassis_inertia in zip(self._chassis_link_ids, base_inertias): for inertia_value in chassis_inertia: if (np.asarray(inertia_value) < 0).any(): raise ValueError("Values in inertia matrix should be non-negative.") self._pybullet_client.changeDynamics( self.quadruped, chassis_id, localInertiaDiagonal=chassis_inertia) def SetLegInertias(self, leg_inertias): """Set the inertias of the legs. A leg includes leg_link and motor. 4 legs contain 16 links (4 links each) and 8 motors. First 16 numbers correspond to link inertia, last 8 correspond to motor inertia (24 total). Args: leg_inertias: The leg and motor inertias for all the leg links and motors. Raises: ValueError: It is raised when the length of inertias is not equal to the number of links + motors or leg_inertias contains negative values. """ if len(leg_inertias) != len(self._leg_link_ids) + len( self._motor_link_ids): raise ValueError("The number of values passed to SetLegMasses are " "different than number of leg links and motors.") for leg_id, leg_inertia in zip(self._leg_link_ids, leg_inertias): for inertia_value in leg_inertias: if (np.asarray(inertia_value) < 0).any(): raise ValueError("Values in inertia matrix should be non-negative.") self._pybullet_client.changeDynamics(self.quadruped, leg_id, localInertiaDiagonal=leg_inertia) motor_inertias = leg_inertias[len(self._leg_link_ids):] for link_id, motor_inertia in zip(self._motor_link_ids, motor_inertias): for inertia_value in motor_inertias: if (np.asarray(inertia_value) < 0).any(): raise ValueError("Values in inertia matrix should be non-negative.") self._pybullet_client.changeDynamics(self.quadruped, link_id, localInertiaDiagonal=motor_inertia) def SetFootFriction(self, foot_friction): """Set the lateral friction of the feet. Args: foot_friction: The lateral friction coefficient of the foot. This value is shared by all four feet. """ for link_id in self._foot_link_ids: self._pybullet_client.changeDynamics(self.quadruped, link_id, lateralFriction=foot_friction) def SetFootRestitution(self, foot_restitution): """Set the coefficient of restitution at the feet. Args: foot_restitution: The coefficient of restitution (bounciness) of the feet. This value is shared by all four feet. """ for link_id in self._foot_link_ids: self._pybullet_client.changeDynamics(self.quadruped, link_id, restitution=foot_restitution) def SetJointFriction(self, joint_frictions): for knee_joint_id, friction in zip(self._foot_link_ids, joint_frictions): self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=knee_joint_id, controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=friction) def GetNumKneeJoints(self): return len(self._foot_link_ids) def SetBatteryVoltage(self, voltage): self._motor_model.set_voltage(voltage) def SetMotorViscousDamping(self, viscous_damping): self._motor_model.set_viscous_damping(viscous_damping) def GetTrueObservation(self): observation = [] observation.extend(self.GetTrueMotorAngles()) observation.extend(self.GetTrueMotorVelocities()) observation.extend(self.GetTrueMotorTorques()) observation.extend(self.GetTrueBaseOrientation()) observation.extend(self.GetTrueBaseRollPitchYawRate()) return observation def ReceiveObservation(self): """Receive the observation from sensors. This function is called once per step. The observations are only updated when this function is called. """ self._joint_states = self._pybullet_client.getJointStates( self.quadruped, self._motor_id_list) self._base_position, orientation = ( self._pybullet_client.getBasePositionAndOrientation(self.quadruped)) # Computes the relative orientation relative to the robot's # initial_orientation. _, self._base_orientation = self._pybullet_client.multiplyTransforms( positionA=[0, 0, 0], orientationA=orientation, positionB=[0, 0, 0], orientationB=self._init_orientation_inv) self._observation_history.appendleft(self.GetTrueObservation()) self._control_observation = self._GetControlObservation() self.last_state_time = self._state_action_counter * self.time_step def _GetDelayedObservation(self, latency): """Get observation that is delayed by the amount specified in latency. Args: latency: The latency (in seconds) of the delayed observation. Returns: observation: The observation which was actually latency seconds ago. """ if latency <= 0 or len(self._observation_history) == 1: observation = self._observation_history[0] else: n_steps_ago = int(latency / self.time_step) if n_steps_ago + 1 >= len(self._observation_history): return self._observation_history[-1] remaining_latency = latency - n_steps_ago * self.time_step blend_alpha = remaining_latency / self.time_step observation = ( (1.0 - blend_alpha) * np.array(self._observation_history[n_steps_ago]) + blend_alpha * np.array(self._observation_history[n_steps_ago + 1])) return observation def _GetPDObservation(self): pd_delayed_observation = self._GetDelayedObservation(self._pd_latency) q = pd_delayed_observation[0:self.num_motors] qdot = pd_delayed_observation[self.num_motors:2 * self.num_motors] return (np.array(q), np.array(qdot)) def _GetControlObservation(self): control_delayed_observation = self._GetDelayedObservation( self._control_latency) return control_delayed_observation def _AddSensorNoise(self, sensor_values, noise_stdev): if noise_stdev <= 0: return sensor_values observation = sensor_values + np.random.normal(scale=noise_stdev, size=sensor_values.shape) return observation def SetControlLatency(self, latency): """Set the latency of the control loop. It measures the duration between sending an action from Nvidia TX2 and receiving the observation from microcontroller. Args: latency: The latency (in seconds) of the control loop. """ self._control_latency = latency def GetControlLatency(self): """Get the control latency. Returns: The latency (in seconds) between when the motor command is sent and when the sensor measurements are reported back to the controller. """ return self._control_latency def SetMotorGains(self, kp, kd): """Set the gains of all motors. These gains are PD gains for motor positional control. kp is the proportional gain and kd is the derivative gain. Args: kp: proportional gain(s) of the motors. kd: derivative gain(s) of the motors. """ if isinstance(kp, (collections.Sequence, np.ndarray)): self._motor_kps = np.asarray(kp) else: self._motor_kps = np.full(self.num_motors, kp) if isinstance(kd, (collections.Sequence, np.ndarray)): self._motor_kds = np.asarray(kd) else: self._motor_kds = np.full(self.num_motors, kd) self._motor_model.set_motor_gains(kp, kd) def GetMotorGains(self): """Get the gains of the motor. Returns: The proportional gain. The derivative gain. """ return self._motor_kps, self._motor_kds def GetMotorPositionGains(self): """Get the position gains of the motor. Returns: The proportional gain. """ return self._motor_kps def GetMotorVelocityGains(self): """Get the velocity gains of the motor. Returns: The derivative gain. """ return self._motor_kds def SetMotorStrengthRatio(self, ratio): """Set the strength of all motors relative to the default value. Args: ratio: The relative strength. A scalar range from 0.0 to 1.0. """ self._motor_model.set_strength_ratios([ratio] * self.num_motors) def SetMotorStrengthRatios(self, ratios): """Set the strength of each motor relative to the default value. Args: ratios: The relative strength. A numpy array ranging from 0.0 to 1.0. """ self._motor_model.set_strength_ratios(ratios) def SetTimeSteps(self, action_repeat, simulation_step): """Set the time steps of the control and simulation. Args: action_repeat: The number of simulation steps that the same action is repeated. simulation_step: The simulation time step. """ self.time_step = simulation_step self._action_repeat = action_repeat def _GetMotorNames(self): return MOTOR_NAMES def _GetDefaultInitPosition(self): """Returns the init position of the robot. It can be either 1) origin (INIT_POSITION), 2) origin with a rack (INIT_RACK_POSITION), or 3) the previous position. """ # If we want continuous resetting and is not the first episode. if self._reset_at_current_position and self._observation_history: x, y, _ = self.GetBasePosition() _, _, z = INIT_POSITION return [x, y, z] if self._on_rack: return INIT_RACK_POSITION else: return INIT_POSITION def _GetDefaultInitOrientation(self): """Returns the init position of the robot. It can be either 1) INIT_ORIENTATION or 2) the previous rotation in yaw. """ # If we want continuous resetting and is not the first episode. if self._reset_at_current_position and self._observation_history: _, _, yaw = self.GetBaseRollPitchYaw() return self._pybullet_client.getQuaternionFromEuler([0.0, 0.0, yaw]) return INIT_ORIENTATION @property def chassis_link_ids(self): return self._chassis_link_ids def SetAllSensors(self, sensors): """set all sensors to this robot and move the ownership to this robot. Args: sensors: a list of sensors to this robot. """ for s in sensors: s.set_robot(self) self._sensors = sensors def GetAllSensors(self): """get all sensors associated with this robot. Returns: sensors: a list of all sensors. """ return self._sensors def GetSensor(self, name): """get the first sensor with the given name. This function return None if a sensor with the given name does not exist. Args: name: the name of the sensor we are looking Returns: sensor: a sensor with the given name. None if not exists. """ for s in self._sensors: if s.get_name() == name: return s return None @property def is_safe(self): return self._is_safe @property def last_action(self): return self._last_action def ProcessAction(self, action, substep_count): """If enabled, interpolates between the current and previous actions. Args: action: current action. substep_count: the step count should be between [0, self.__action_repeat). Returns: If interpolation is enabled, returns interpolated action depending on the current action repeat substep. """ if self._enable_action_interpolation and self._last_action is not None: lerp = float(substep_count + 1) / self._action_repeat proc_action = self._last_action + lerp * (action - self._last_action) else: proc_action = action return proc_action def _BuildActionFilter(self): sampling_rate = 1 / (self.time_step * self._action_repeat) num_joints = self.GetActionDimension() a_filter = action_filter.ActionFilterButter(sampling_rate=sampling_rate, num_joints=num_joints) return a_filter def _ResetActionFilter(self): self._action_filter.reset() def _FilterAction(self, action): # initialize the filter history, since resetting the filter will fill # the history with zeros and this can cause sudden movements at the start # of each episode if self._step_counter == 0: default_action = self.GetMotorAngles() self._action_filter.init_history(default_action) filtered_action = self._action_filter.filter(action) return filtered_action @property def pybullet_client(self): return self._pybullet_client @property def joint_states(self): return self._joint_states @classmethod def GetConstants(cls): del cls return minitaur_constants
0.937683
0.497253
import os import sys import glog as log import json import pkg_resources import tempfile import struct import base64 import traceback import avro.schema from avro.datafile import DataFileReader, DataFileWriter from avro.io import DatumReader, DatumWriter, BinaryDecoder, BinaryEncoder from confluent_kafka.avro.cached_schema_registry_client import CachedSchemaRegistryClient from confluent_kafka.avro.serializer.message_serializer import ( MessageSerializer, ContextStringIO, MAGIC_BYTE, ) from confluent_kafka.avro.serializer import SerializerError from multivitamin.data.response import config class AvroIO: def __init__(self, schema_registry_url=None): """Public interface for Avro IO functionality Args: use_schema_registry (bool): flag to use schema registry via client ID and registry URL use_base64 (bool): encoding binary to base64 """ self.impl = None self.use_base64 = False if schema_registry_url: log.info(f"schema_registry_url: {schema_registry_url}") self.impl = _AvroIORegistry(schema_registry_url) else: log.warning("registry_url is None, using local schema and serializing w/o magic byte") self.impl = _AvroIOLocal() def get_schema(self): """Return schema Returns: avro.schema.RecordSchema: schema """ return self.impl.schema def get_schema_str(self): """Return schema as str Returns: str: schema as str """ return str(self.impl.schema).replace("\\", "") def decode_binary_file(self, file_path): """Decode an Avro Binary using the schema Args: file_path (str) : avro binary file Returns: dict: avro document """ if not os.path.exists(file_path): log.error("Missing: {}".format(file_path)) raise FileNotFoundError("Missing: {}".format(file_path)) log.info("Decoding file: {}".format(file_path)) return self.decode(open(file_path, "rb").read()) def decode(self, bytes, use_base64=False, binary_flag=True): """Decode an Avro Binary using the CV schema from bytes Args: bytes use_base64 binary_flag Returns: dict: """ if use_base64: bytes = base64.b64decode(bytes) if binary_flag: return self.impl.decode(bytes) else: return json.loads(str(bytes)) def write(self, doc, file, serialize=True, indent=None): """Write Avro doc Args: doc (dict): dict of the avro document file_path (str): avro binary file output serialize (bool): whether to serialize avro doc to a binary file indent (int): if serialize=False, write json with indentation=indent Returns: bool: True if successfully wrote file """ if serialize: try: bytes = self.encode(doc) with open(file, "wb") as wf: wf.write(bytes) except avro.io.AvroTypeException: log.error("avro.io.AvroTypeException: the datum is not an example of the schema") return False log.info("Encoded doc to file: {}".format(file)) else: if not self.is_valid_avro_doc(doc): log.error("datum is not an example of schema") return False with open(file, "w") as wf: json.dump(doc, wf, indent=indent) return True def encode(self, doc, use_base64=False): """Encode an avro doc to bytes """ bytes = self.impl.encode(doc) if use_base64: log.info(f"use_base64={use_base64}") bytes = base64.b64encode(bytes) return bytes def is_valid_avro_doc(self, doc): """Boolean test to validate json against a schema Args: doc (dict): avro doc as a dict Returns: boolean: True if json is an example of schema """ try: writer = DataFileWriter(tempfile.TemporaryFile(), DatumWriter(), self.impl.schema) writer.append(doc) writer.close() except: return False return True @staticmethod def is_valid_avro_doc_static(doc, schema): """Boolean test to validate json against a schema Args: doc (dict): avro doc as a dict schema (str or dict): schema as a string or dict Returns: boolean: True if json is an example of schema """ if isinstance(schema, str): avro_schema = avro.schema.Parse(schema) else: avro_schema = schema try: writer = DataFileWriter(tempfile.TemporaryFile(), DatumWriter(), avro_schema) writer.append(doc) writer.close() except: return False return True class _AvroIOLocal: def __init__(self): """Private implementation class for Avro IO of local files""" local_schema_file = pkg_resources.resource_filename( "multivitamin.data.response", config.SCHEMA_FILE ) log.debug("Using local schema file {}".format(local_schema_file)) if not os.path.exists(local_schema_file): raise FileNotFoundError("Schema file not found") self.schema = avro.schema.Parse(open(local_schema_file).read()) def decode(self, bytes): if len(bytes) <= 5: raise SerializerError("Message is too small to decode") with ContextStringIO(bytes) as payload: magic, schema_id = struct.unpack(">bI", payload.read(5)) if magic != MAGIC_BYTE: raise SerializerError("message does not start with magic byte") curr_pos = payload.tell() avro_reader = avro.io.DatumReader(self.schema) def decoder(p): bin_decoder = avro.io.BinaryDecoder(p) return avro_reader.read(bin_decoder) return decoder(payload) def encode(self, record): with ContextStringIO() as outf: outf.write(struct.pack("b", MAGIC_BYTE)) outf.write(struct.pack(">I", config.SCHEMA_ID)) encoder = avro.io.BinaryEncoder(outf) writer = avro.io.DatumWriter(self.schema) writer.write(record, encoder) return outf.getvalue() class _AvroIORegistry: def __init__(self, schema_registry_url): """Private implementation class for Avro IO using the registry""" log.info(f"Using registry with schema_url/id {schema_registry_url}/{config.SCHEMA_ID}") try: self.client = CachedSchemaRegistryClient(url=schema_registry_url) self.schema = self.client.get_by_id(config.SCHEMA_ID) self.serializer = MessageSerializer(self.client) except: raise ValueError("Client id or schema id not found") def decode(self, bytes): return self.serializer.decode_message(bytes) def encode(self, record): return self.serializer.encode_record_with_schema_id(config.SCHEMA_ID, record)
multivitamin/data/response/io.py
import os import sys import glog as log import json import pkg_resources import tempfile import struct import base64 import traceback import avro.schema from avro.datafile import DataFileReader, DataFileWriter from avro.io import DatumReader, DatumWriter, BinaryDecoder, BinaryEncoder from confluent_kafka.avro.cached_schema_registry_client import CachedSchemaRegistryClient from confluent_kafka.avro.serializer.message_serializer import ( MessageSerializer, ContextStringIO, MAGIC_BYTE, ) from confluent_kafka.avro.serializer import SerializerError from multivitamin.data.response import config class AvroIO: def __init__(self, schema_registry_url=None): """Public interface for Avro IO functionality Args: use_schema_registry (bool): flag to use schema registry via client ID and registry URL use_base64 (bool): encoding binary to base64 """ self.impl = None self.use_base64 = False if schema_registry_url: log.info(f"schema_registry_url: {schema_registry_url}") self.impl = _AvroIORegistry(schema_registry_url) else: log.warning("registry_url is None, using local schema and serializing w/o magic byte") self.impl = _AvroIOLocal() def get_schema(self): """Return schema Returns: avro.schema.RecordSchema: schema """ return self.impl.schema def get_schema_str(self): """Return schema as str Returns: str: schema as str """ return str(self.impl.schema).replace("\\", "") def decode_binary_file(self, file_path): """Decode an Avro Binary using the schema Args: file_path (str) : avro binary file Returns: dict: avro document """ if not os.path.exists(file_path): log.error("Missing: {}".format(file_path)) raise FileNotFoundError("Missing: {}".format(file_path)) log.info("Decoding file: {}".format(file_path)) return self.decode(open(file_path, "rb").read()) def decode(self, bytes, use_base64=False, binary_flag=True): """Decode an Avro Binary using the CV schema from bytes Args: bytes use_base64 binary_flag Returns: dict: """ if use_base64: bytes = base64.b64decode(bytes) if binary_flag: return self.impl.decode(bytes) else: return json.loads(str(bytes)) def write(self, doc, file, serialize=True, indent=None): """Write Avro doc Args: doc (dict): dict of the avro document file_path (str): avro binary file output serialize (bool): whether to serialize avro doc to a binary file indent (int): if serialize=False, write json with indentation=indent Returns: bool: True if successfully wrote file """ if serialize: try: bytes = self.encode(doc) with open(file, "wb") as wf: wf.write(bytes) except avro.io.AvroTypeException: log.error("avro.io.AvroTypeException: the datum is not an example of the schema") return False log.info("Encoded doc to file: {}".format(file)) else: if not self.is_valid_avro_doc(doc): log.error("datum is not an example of schema") return False with open(file, "w") as wf: json.dump(doc, wf, indent=indent) return True def encode(self, doc, use_base64=False): """Encode an avro doc to bytes """ bytes = self.impl.encode(doc) if use_base64: log.info(f"use_base64={use_base64}") bytes = base64.b64encode(bytes) return bytes def is_valid_avro_doc(self, doc): """Boolean test to validate json against a schema Args: doc (dict): avro doc as a dict Returns: boolean: True if json is an example of schema """ try: writer = DataFileWriter(tempfile.TemporaryFile(), DatumWriter(), self.impl.schema) writer.append(doc) writer.close() except: return False return True @staticmethod def is_valid_avro_doc_static(doc, schema): """Boolean test to validate json against a schema Args: doc (dict): avro doc as a dict schema (str or dict): schema as a string or dict Returns: boolean: True if json is an example of schema """ if isinstance(schema, str): avro_schema = avro.schema.Parse(schema) else: avro_schema = schema try: writer = DataFileWriter(tempfile.TemporaryFile(), DatumWriter(), avro_schema) writer.append(doc) writer.close() except: return False return True class _AvroIOLocal: def __init__(self): """Private implementation class for Avro IO of local files""" local_schema_file = pkg_resources.resource_filename( "multivitamin.data.response", config.SCHEMA_FILE ) log.debug("Using local schema file {}".format(local_schema_file)) if not os.path.exists(local_schema_file): raise FileNotFoundError("Schema file not found") self.schema = avro.schema.Parse(open(local_schema_file).read()) def decode(self, bytes): if len(bytes) <= 5: raise SerializerError("Message is too small to decode") with ContextStringIO(bytes) as payload: magic, schema_id = struct.unpack(">bI", payload.read(5)) if magic != MAGIC_BYTE: raise SerializerError("message does not start with magic byte") curr_pos = payload.tell() avro_reader = avro.io.DatumReader(self.schema) def decoder(p): bin_decoder = avro.io.BinaryDecoder(p) return avro_reader.read(bin_decoder) return decoder(payload) def encode(self, record): with ContextStringIO() as outf: outf.write(struct.pack("b", MAGIC_BYTE)) outf.write(struct.pack(">I", config.SCHEMA_ID)) encoder = avro.io.BinaryEncoder(outf) writer = avro.io.DatumWriter(self.schema) writer.write(record, encoder) return outf.getvalue() class _AvroIORegistry: def __init__(self, schema_registry_url): """Private implementation class for Avro IO using the registry""" log.info(f"Using registry with schema_url/id {schema_registry_url}/{config.SCHEMA_ID}") try: self.client = CachedSchemaRegistryClient(url=schema_registry_url) self.schema = self.client.get_by_id(config.SCHEMA_ID) self.serializer = MessageSerializer(self.client) except: raise ValueError("Client id or schema id not found") def decode(self, bytes): return self.serializer.decode_message(bytes) def encode(self, record): return self.serializer.encode_record_with_schema_id(config.SCHEMA_ID, record)
0.579281
0.111048
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'EndpointGroupEndpointConfigurationArgs', 'EndpointGroupPortOverridesArgs', 'ForwardingRuleRuleActionArgs', 'ForwardingRuleRuleActionForwardGroupConfigArgs', 'ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs', 'ForwardingRuleRuleConditionArgs', 'ForwardingRuleRuleConditionHostConfigArgs', 'ForwardingRuleRuleConditionPathConfigArgs', 'ListenerCertificateArgs', 'ListenerPortRangeArgs', ] @pulumi.input_type class EndpointGroupEndpointConfigurationArgs: def __init__(__self__, *, endpoint: pulumi.Input[str], type: pulumi.Input[str], weight: pulumi.Input[int], enable_clientip_preservation: Optional[pulumi.Input[bool]] = None): """ :param pulumi.Input[str] endpoint: The IP address or domain name of Endpoint N in the endpoint group. :param pulumi.Input[str] type: The type of Endpoint N in the endpoint group. Valid values: `Domain`: a custom domain name, `Ip`: a custom IP address, `PublicIp`: an Alibaba Cloud public IP address, `ECS`: an Alibaba Cloud Elastic Compute Service (ECS) instance, `SLB`: an Alibaba Cloud Server Load Balancer (SLB) instance. :param pulumi.Input[int] weight: The weight of Endpoint N in the endpoint group. Valid value is 0 to 255. :param pulumi.Input[bool] enable_clientip_preservation: Indicates whether client IP addresses are reserved. Valid values: `true`: Client IP addresses are reserved, `false`: Client IP addresses are not reserved. Default value is `false`. """ pulumi.set(__self__, "endpoint", endpoint) pulumi.set(__self__, "type", type) pulumi.set(__self__, "weight", weight) if enable_clientip_preservation is not None: pulumi.set(__self__, "enable_clientip_preservation", enable_clientip_preservation) @property @pulumi.getter def endpoint(self) -> pulumi.Input[str]: """ The IP address or domain name of Endpoint N in the endpoint group. """ return pulumi.get(self, "endpoint") @endpoint.setter def endpoint(self, value: pulumi.Input[str]): pulumi.set(self, "endpoint", value) @property @pulumi.getter def type(self) -> pulumi.Input[str]: """ The type of Endpoint N in the endpoint group. Valid values: `Domain`: a custom domain name, `Ip`: a custom IP address, `PublicIp`: an Alibaba Cloud public IP address, `ECS`: an Alibaba Cloud Elastic Compute Service (ECS) instance, `SLB`: an Alibaba Cloud Server Load Balancer (SLB) instance. """ return pulumi.get(self, "type") @type.setter def type(self, value: pulumi.Input[str]): pulumi.set(self, "type", value) @property @pulumi.getter def weight(self) -> pulumi.Input[int]: """ The weight of Endpoint N in the endpoint group. Valid value is 0 to 255. """ return pulumi.get(self, "weight") @weight.setter def weight(self, value: pulumi.Input[int]): pulumi.set(self, "weight", value) @property @pulumi.getter(name="enableClientipPreservation") def enable_clientip_preservation(self) -> Optional[pulumi.Input[bool]]: """ Indicates whether client IP addresses are reserved. Valid values: `true`: Client IP addresses are reserved, `false`: Client IP addresses are not reserved. Default value is `false`. """ return pulumi.get(self, "enable_clientip_preservation") @enable_clientip_preservation.setter def enable_clientip_preservation(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "enable_clientip_preservation", value) @pulumi.input_type class EndpointGroupPortOverridesArgs: def __init__(__self__, *, endpoint_port: Optional[pulumi.Input[int]] = None, listener_port: Optional[pulumi.Input[int]] = None): """ :param pulumi.Input[int] endpoint_port: Forwarding port. :param pulumi.Input[int] listener_port: Listener port. """ if endpoint_port is not None: pulumi.set(__self__, "endpoint_port", endpoint_port) if listener_port is not None: pulumi.set(__self__, "listener_port", listener_port) @property @pulumi.getter(name="endpointPort") def endpoint_port(self) -> Optional[pulumi.Input[int]]: """ Forwarding port. """ return pulumi.get(self, "endpoint_port") @endpoint_port.setter def endpoint_port(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "endpoint_port", value) @property @pulumi.getter(name="listenerPort") def listener_port(self) -> Optional[pulumi.Input[int]]: """ Listener port. """ return pulumi.get(self, "listener_port") @listener_port.setter def listener_port(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "listener_port", value) @pulumi.input_type class ForwardingRuleRuleActionArgs: def __init__(__self__, *, forward_group_config: pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigArgs'], order: pulumi.Input[int], rule_action_type: pulumi.Input[str]): """ :param pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigArgs'] forward_group_config: Forwarding configuration. :param pulumi.Input[int] order: Forwarding priority. :param pulumi.Input[str] rule_action_type: Forward action type. Default: forwardgroup. """ pulumi.set(__self__, "forward_group_config", forward_group_config) pulumi.set(__self__, "order", order) pulumi.set(__self__, "rule_action_type", rule_action_type) @property @pulumi.getter(name="forwardGroupConfig") def forward_group_config(self) -> pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigArgs']: """ Forwarding configuration. """ return pulumi.get(self, "forward_group_config") @forward_group_config.setter def forward_group_config(self, value: pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigArgs']): pulumi.set(self, "forward_group_config", value) @property @pulumi.getter def order(self) -> pulumi.Input[int]: """ Forwarding priority. """ return pulumi.get(self, "order") @order.setter def order(self, value: pulumi.Input[int]): pulumi.set(self, "order", value) @property @pulumi.getter(name="ruleActionType") def rule_action_type(self) -> pulumi.Input[str]: """ Forward action type. Default: forwardgroup. """ return pulumi.get(self, "rule_action_type") @rule_action_type.setter def rule_action_type(self, value: pulumi.Input[str]): pulumi.set(self, "rule_action_type", value) @pulumi.input_type class ForwardingRuleRuleActionForwardGroupConfigArgs: def __init__(__self__, *, server_group_tuples: pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs']]]): """ :param pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs']]] server_group_tuples: Terminal node group configuration. """ pulumi.set(__self__, "server_group_tuples", server_group_tuples) @property @pulumi.getter(name="serverGroupTuples") def server_group_tuples(self) -> pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs']]]: """ Terminal node group configuration. """ return pulumi.get(self, "server_group_tuples") @server_group_tuples.setter def server_group_tuples(self, value: pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs']]]): pulumi.set(self, "server_group_tuples", value) @pulumi.input_type class ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs: def __init__(__self__, *, endpoint_group_id: pulumi.Input[str]): """ :param pulumi.Input[str] endpoint_group_id: Terminal node group ID. """ pulumi.set(__self__, "endpoint_group_id", endpoint_group_id) @property @pulumi.getter(name="endpointGroupId") def endpoint_group_id(self) -> pulumi.Input[str]: """ Terminal node group ID. """ return pulumi.get(self, "endpoint_group_id") @endpoint_group_id.setter def endpoint_group_id(self, value: pulumi.Input[str]): pulumi.set(self, "endpoint_group_id", value) @pulumi.input_type class ForwardingRuleRuleConditionArgs: def __init__(__self__, *, rule_condition_type: pulumi.Input[str], host_configs: Optional[pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleConditionHostConfigArgs']]]] = None, path_config: Optional[pulumi.Input['ForwardingRuleRuleConditionPathConfigArgs']] = None): """ :param pulumi.Input[str] rule_condition_type: Forwarding condition type. Valid value: `Host`, `Path`. :param pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleConditionHostConfigArgs']]] host_configs: Domain name configuration information. :param pulumi.Input['ForwardingRuleRuleConditionPathConfigArgs'] path_config: Path configuration information. """ pulumi.set(__self__, "rule_condition_type", rule_condition_type) if host_configs is not None: pulumi.set(__self__, "host_configs", host_configs) if path_config is not None: pulumi.set(__self__, "path_config", path_config) @property @pulumi.getter(name="ruleConditionType") def rule_condition_type(self) -> pulumi.Input[str]: """ Forwarding condition type. Valid value: `Host`, `Path`. """ return pulumi.get(self, "rule_condition_type") @rule_condition_type.setter def rule_condition_type(self, value: pulumi.Input[str]): pulumi.set(self, "rule_condition_type", value) @property @pulumi.getter(name="hostConfigs") def host_configs(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleConditionHostConfigArgs']]]]: """ Domain name configuration information. """ return pulumi.get(self, "host_configs") @host_configs.setter def host_configs(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleConditionHostConfigArgs']]]]): pulumi.set(self, "host_configs", value) @property @pulumi.getter(name="pathConfig") def path_config(self) -> Optional[pulumi.Input['ForwardingRuleRuleConditionPathConfigArgs']]: """ Path configuration information. """ return pulumi.get(self, "path_config") @path_config.setter def path_config(self, value: Optional[pulumi.Input['ForwardingRuleRuleConditionPathConfigArgs']]): pulumi.set(self, "path_config", value) @pulumi.input_type class ForwardingRuleRuleConditionHostConfigArgs: def __init__(__self__, *, values: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None): """ :param pulumi.Input[Sequence[pulumi.Input[str]]] values: The domain name is 3-128 characters long, which can contain letters, numbers, dashes (-) and width period (.), and supports the use of asterisk (*) and width question mark (?) as wildcard characters. """ if values is not None: pulumi.set(__self__, "values", values) @property @pulumi.getter def values(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ The domain name is 3-128 characters long, which can contain letters, numbers, dashes (-) and width period (.), and supports the use of asterisk (*) and width question mark (?) as wildcard characters. """ return pulumi.get(self, "values") @values.setter def values(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "values", value) @pulumi.input_type class ForwardingRuleRuleConditionPathConfigArgs: def __init__(__self__, *, values: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None): """ :param pulumi.Input[Sequence[pulumi.Input[str]]] values: The domain name is 3-128 characters long, which can contain letters, numbers, dashes (-) and width period (.), and supports the use of asterisk (*) and width question mark (?) as wildcard characters. """ if values is not None: pulumi.set(__self__, "values", values) @property @pulumi.getter def values(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ The domain name is 3-128 characters long, which can contain letters, numbers, dashes (-) and width period (.), and supports the use of asterisk (*) and width question mark (?) as wildcard characters. """ return pulumi.get(self, "values") @values.setter def values(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "values", value) @pulumi.input_type class ListenerCertificateArgs: def __init__(__self__, *, id: Optional[pulumi.Input[str]] = None): """ :param pulumi.Input[str] id: The id of the certificate. """ if id is not None: pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ The id of the certificate. """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @pulumi.input_type class ListenerPortRangeArgs: def __init__(__self__, *, from_port: pulumi.Input[int], to_port: pulumi.Input[int]): """ :param pulumi.Input[int] from_port: The initial listening port used to receive requests and forward them to terminal nodes. :param pulumi.Input[int] to_port: The end listening port used to receive requests and forward them to terminal nodes. """ pulumi.set(__self__, "from_port", from_port) pulumi.set(__self__, "to_port", to_port) @property @pulumi.getter(name="fromPort") def from_port(self) -> pulumi.Input[int]: """ The initial listening port used to receive requests and forward them to terminal nodes. """ return pulumi.get(self, "from_port") @from_port.setter def from_port(self, value: pulumi.Input[int]): pulumi.set(self, "from_port", value) @property @pulumi.getter(name="toPort") def to_port(self) -> pulumi.Input[int]: """ The end listening port used to receive requests and forward them to terminal nodes. """ return pulumi.get(self, "to_port") @to_port.setter def to_port(self, value: pulumi.Input[int]): pulumi.set(self, "to_port", value)
sdk/python/pulumi_alicloud/ga/_inputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'EndpointGroupEndpointConfigurationArgs', 'EndpointGroupPortOverridesArgs', 'ForwardingRuleRuleActionArgs', 'ForwardingRuleRuleActionForwardGroupConfigArgs', 'ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs', 'ForwardingRuleRuleConditionArgs', 'ForwardingRuleRuleConditionHostConfigArgs', 'ForwardingRuleRuleConditionPathConfigArgs', 'ListenerCertificateArgs', 'ListenerPortRangeArgs', ] @pulumi.input_type class EndpointGroupEndpointConfigurationArgs: def __init__(__self__, *, endpoint: pulumi.Input[str], type: pulumi.Input[str], weight: pulumi.Input[int], enable_clientip_preservation: Optional[pulumi.Input[bool]] = None): """ :param pulumi.Input[str] endpoint: The IP address or domain name of Endpoint N in the endpoint group. :param pulumi.Input[str] type: The type of Endpoint N in the endpoint group. Valid values: `Domain`: a custom domain name, `Ip`: a custom IP address, `PublicIp`: an Alibaba Cloud public IP address, `ECS`: an Alibaba Cloud Elastic Compute Service (ECS) instance, `SLB`: an Alibaba Cloud Server Load Balancer (SLB) instance. :param pulumi.Input[int] weight: The weight of Endpoint N in the endpoint group. Valid value is 0 to 255. :param pulumi.Input[bool] enable_clientip_preservation: Indicates whether client IP addresses are reserved. Valid values: `true`: Client IP addresses are reserved, `false`: Client IP addresses are not reserved. Default value is `false`. """ pulumi.set(__self__, "endpoint", endpoint) pulumi.set(__self__, "type", type) pulumi.set(__self__, "weight", weight) if enable_clientip_preservation is not None: pulumi.set(__self__, "enable_clientip_preservation", enable_clientip_preservation) @property @pulumi.getter def endpoint(self) -> pulumi.Input[str]: """ The IP address or domain name of Endpoint N in the endpoint group. """ return pulumi.get(self, "endpoint") @endpoint.setter def endpoint(self, value: pulumi.Input[str]): pulumi.set(self, "endpoint", value) @property @pulumi.getter def type(self) -> pulumi.Input[str]: """ The type of Endpoint N in the endpoint group. Valid values: `Domain`: a custom domain name, `Ip`: a custom IP address, `PublicIp`: an Alibaba Cloud public IP address, `ECS`: an Alibaba Cloud Elastic Compute Service (ECS) instance, `SLB`: an Alibaba Cloud Server Load Balancer (SLB) instance. """ return pulumi.get(self, "type") @type.setter def type(self, value: pulumi.Input[str]): pulumi.set(self, "type", value) @property @pulumi.getter def weight(self) -> pulumi.Input[int]: """ The weight of Endpoint N in the endpoint group. Valid value is 0 to 255. """ return pulumi.get(self, "weight") @weight.setter def weight(self, value: pulumi.Input[int]): pulumi.set(self, "weight", value) @property @pulumi.getter(name="enableClientipPreservation") def enable_clientip_preservation(self) -> Optional[pulumi.Input[bool]]: """ Indicates whether client IP addresses are reserved. Valid values: `true`: Client IP addresses are reserved, `false`: Client IP addresses are not reserved. Default value is `false`. """ return pulumi.get(self, "enable_clientip_preservation") @enable_clientip_preservation.setter def enable_clientip_preservation(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "enable_clientip_preservation", value) @pulumi.input_type class EndpointGroupPortOverridesArgs: def __init__(__self__, *, endpoint_port: Optional[pulumi.Input[int]] = None, listener_port: Optional[pulumi.Input[int]] = None): """ :param pulumi.Input[int] endpoint_port: Forwarding port. :param pulumi.Input[int] listener_port: Listener port. """ if endpoint_port is not None: pulumi.set(__self__, "endpoint_port", endpoint_port) if listener_port is not None: pulumi.set(__self__, "listener_port", listener_port) @property @pulumi.getter(name="endpointPort") def endpoint_port(self) -> Optional[pulumi.Input[int]]: """ Forwarding port. """ return pulumi.get(self, "endpoint_port") @endpoint_port.setter def endpoint_port(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "endpoint_port", value) @property @pulumi.getter(name="listenerPort") def listener_port(self) -> Optional[pulumi.Input[int]]: """ Listener port. """ return pulumi.get(self, "listener_port") @listener_port.setter def listener_port(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "listener_port", value) @pulumi.input_type class ForwardingRuleRuleActionArgs: def __init__(__self__, *, forward_group_config: pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigArgs'], order: pulumi.Input[int], rule_action_type: pulumi.Input[str]): """ :param pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigArgs'] forward_group_config: Forwarding configuration. :param pulumi.Input[int] order: Forwarding priority. :param pulumi.Input[str] rule_action_type: Forward action type. Default: forwardgroup. """ pulumi.set(__self__, "forward_group_config", forward_group_config) pulumi.set(__self__, "order", order) pulumi.set(__self__, "rule_action_type", rule_action_type) @property @pulumi.getter(name="forwardGroupConfig") def forward_group_config(self) -> pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigArgs']: """ Forwarding configuration. """ return pulumi.get(self, "forward_group_config") @forward_group_config.setter def forward_group_config(self, value: pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigArgs']): pulumi.set(self, "forward_group_config", value) @property @pulumi.getter def order(self) -> pulumi.Input[int]: """ Forwarding priority. """ return pulumi.get(self, "order") @order.setter def order(self, value: pulumi.Input[int]): pulumi.set(self, "order", value) @property @pulumi.getter(name="ruleActionType") def rule_action_type(self) -> pulumi.Input[str]: """ Forward action type. Default: forwardgroup. """ return pulumi.get(self, "rule_action_type") @rule_action_type.setter def rule_action_type(self, value: pulumi.Input[str]): pulumi.set(self, "rule_action_type", value) @pulumi.input_type class ForwardingRuleRuleActionForwardGroupConfigArgs: def __init__(__self__, *, server_group_tuples: pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs']]]): """ :param pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs']]] server_group_tuples: Terminal node group configuration. """ pulumi.set(__self__, "server_group_tuples", server_group_tuples) @property @pulumi.getter(name="serverGroupTuples") def server_group_tuples(self) -> pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs']]]: """ Terminal node group configuration. """ return pulumi.get(self, "server_group_tuples") @server_group_tuples.setter def server_group_tuples(self, value: pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs']]]): pulumi.set(self, "server_group_tuples", value) @pulumi.input_type class ForwardingRuleRuleActionForwardGroupConfigServerGroupTupleArgs: def __init__(__self__, *, endpoint_group_id: pulumi.Input[str]): """ :param pulumi.Input[str] endpoint_group_id: Terminal node group ID. """ pulumi.set(__self__, "endpoint_group_id", endpoint_group_id) @property @pulumi.getter(name="endpointGroupId") def endpoint_group_id(self) -> pulumi.Input[str]: """ Terminal node group ID. """ return pulumi.get(self, "endpoint_group_id") @endpoint_group_id.setter def endpoint_group_id(self, value: pulumi.Input[str]): pulumi.set(self, "endpoint_group_id", value) @pulumi.input_type class ForwardingRuleRuleConditionArgs: def __init__(__self__, *, rule_condition_type: pulumi.Input[str], host_configs: Optional[pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleConditionHostConfigArgs']]]] = None, path_config: Optional[pulumi.Input['ForwardingRuleRuleConditionPathConfigArgs']] = None): """ :param pulumi.Input[str] rule_condition_type: Forwarding condition type. Valid value: `Host`, `Path`. :param pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleConditionHostConfigArgs']]] host_configs: Domain name configuration information. :param pulumi.Input['ForwardingRuleRuleConditionPathConfigArgs'] path_config: Path configuration information. """ pulumi.set(__self__, "rule_condition_type", rule_condition_type) if host_configs is not None: pulumi.set(__self__, "host_configs", host_configs) if path_config is not None: pulumi.set(__self__, "path_config", path_config) @property @pulumi.getter(name="ruleConditionType") def rule_condition_type(self) -> pulumi.Input[str]: """ Forwarding condition type. Valid value: `Host`, `Path`. """ return pulumi.get(self, "rule_condition_type") @rule_condition_type.setter def rule_condition_type(self, value: pulumi.Input[str]): pulumi.set(self, "rule_condition_type", value) @property @pulumi.getter(name="hostConfigs") def host_configs(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleConditionHostConfigArgs']]]]: """ Domain name configuration information. """ return pulumi.get(self, "host_configs") @host_configs.setter def host_configs(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ForwardingRuleRuleConditionHostConfigArgs']]]]): pulumi.set(self, "host_configs", value) @property @pulumi.getter(name="pathConfig") def path_config(self) -> Optional[pulumi.Input['ForwardingRuleRuleConditionPathConfigArgs']]: """ Path configuration information. """ return pulumi.get(self, "path_config") @path_config.setter def path_config(self, value: Optional[pulumi.Input['ForwardingRuleRuleConditionPathConfigArgs']]): pulumi.set(self, "path_config", value) @pulumi.input_type class ForwardingRuleRuleConditionHostConfigArgs: def __init__(__self__, *, values: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None): """ :param pulumi.Input[Sequence[pulumi.Input[str]]] values: The domain name is 3-128 characters long, which can contain letters, numbers, dashes (-) and width period (.), and supports the use of asterisk (*) and width question mark (?) as wildcard characters. """ if values is not None: pulumi.set(__self__, "values", values) @property @pulumi.getter def values(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ The domain name is 3-128 characters long, which can contain letters, numbers, dashes (-) and width period (.), and supports the use of asterisk (*) and width question mark (?) as wildcard characters. """ return pulumi.get(self, "values") @values.setter def values(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "values", value) @pulumi.input_type class ForwardingRuleRuleConditionPathConfigArgs: def __init__(__self__, *, values: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None): """ :param pulumi.Input[Sequence[pulumi.Input[str]]] values: The domain name is 3-128 characters long, which can contain letters, numbers, dashes (-) and width period (.), and supports the use of asterisk (*) and width question mark (?) as wildcard characters. """ if values is not None: pulumi.set(__self__, "values", values) @property @pulumi.getter def values(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: """ The domain name is 3-128 characters long, which can contain letters, numbers, dashes (-) and width period (.), and supports the use of asterisk (*) and width question mark (?) as wildcard characters. """ return pulumi.get(self, "values") @values.setter def values(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]): pulumi.set(self, "values", value) @pulumi.input_type class ListenerCertificateArgs: def __init__(__self__, *, id: Optional[pulumi.Input[str]] = None): """ :param pulumi.Input[str] id: The id of the certificate. """ if id is not None: pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ The id of the certificate. """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @pulumi.input_type class ListenerPortRangeArgs: def __init__(__self__, *, from_port: pulumi.Input[int], to_port: pulumi.Input[int]): """ :param pulumi.Input[int] from_port: The initial listening port used to receive requests and forward them to terminal nodes. :param pulumi.Input[int] to_port: The end listening port used to receive requests and forward them to terminal nodes. """ pulumi.set(__self__, "from_port", from_port) pulumi.set(__self__, "to_port", to_port) @property @pulumi.getter(name="fromPort") def from_port(self) -> pulumi.Input[int]: """ The initial listening port used to receive requests and forward them to terminal nodes. """ return pulumi.get(self, "from_port") @from_port.setter def from_port(self, value: pulumi.Input[int]): pulumi.set(self, "from_port", value) @property @pulumi.getter(name="toPort") def to_port(self) -> pulumi.Input[int]: """ The end listening port used to receive requests and forward them to terminal nodes. """ return pulumi.get(self, "to_port") @to_port.setter def to_port(self, value: pulumi.Input[int]): pulumi.set(self, "to_port", value)
0.856453
0.080647
import webapp2 import jinja2 from google.appengine.ext import db from google.appengine.api import users from data.models import Monster, Profile, Vote, Product import handlers.base import configuration.site import xml.etree.ElementTree as ET from google.appengine.ext import blobstore from google.appengine.ext.webapp import blobstore_handlers import logging class CreateHandler(handlers.base.LoggedInRequestHandler): """Creates a new product Given the name of the product, create a new product with the current user as the creator and a random access code.""" def get(self): """HTML GET handler. Render a form that has all the data to make a product.""" template_values = self.build_template_values() if not template_values[handlers.base.PROFILE_KEY]: return self.forbidden() elif not template_values[handlers.base.PROFILE_KEY].is_publisher: return self.forbidden() template = configuration.site.jinja_environment.get_template('product/create.html') self.response.write(template.render(template_values)) def post(self): """HTML POST handler. Check the query parameters for the name of the product, then make it.""" template_values = self.build_template_values() if not template_values[handlers.base.PROFILE_KEY]: return self.forbidden() elif not template_values[handlers.base.PROFILE_KEY].is_publisher: return self.forbidden() name = self.request.get('name') description = self.request.get('description') link = self.request.get('link') if (not name) or (not link) or (not description): return self.forbidden() product = Product() product.creator = template_values[handlers.base.PROFILE_KEY] product.name = name product.link = link product.description = description product.generate_access_code() product.put() template_values[handlers.base.PROFILE_KEY].products.append(product.key().id()) template_values[handlers.base.PROFILE_KEY].put() return self.redirect(self.uri_for('profile.edit')) class ViewHandler(handlers.base.LoggedInRequestHandler): """Renders a single product view page. Given the ID of a product to view, query for that prodict and display it using the standard product template.""" def get(self, entity_id=None): """HTML GET handler. Display the product with the specified ID""" template_values = self.build_template_values() if entity_id: try: product = Product.get_by_id(int(entity_id)) except ValueError: return self.not_found() if not product: self.not_found() return template_values['product'] = product else: self.redirect(self.uri_for('product.home')) return template = configuration.site.jinja_environment.get_template('product/view.html') self.response.write(template.render(template_values)) class UpdateHandler(handlers.base.LoggedInRequestHandler): """Updates the access code for a product. Given the ID of a product to update, generate a new access code for it, then redirect to the profile edit page.""" def get(self, entity_id=None): """HTML GET handler. Update the product with the specified ID""" template_values = self.build_template_values() if entity_id: try: product = Product.get_by_id(int(entity_id)) except ValueError: return self.not_found() if not product: self.not_found() return product.generate_access_code() product.put() else: self.redirect(self.uri_for('product.home')) return return self.redirect(self.uri_for('profile.edit')) class UploadHandler(handlers.base.LoggedInRequestHandler, blobstore_handlers.BlobstoreUploadHandler): """"Uploads a file and parses it for monsters. Templates used: upload.html""" class CoreProduct(object): name = "Core" class FakeKey(object): def id(self): return -1 def key(self): return self.FakeKey() def get(self): """HTML GET handler. Check the query parameters for the ID of the monster to be edited. If found, display that monster for editing.""" template_values = self.build_template_values() if not template_values[handlers.base.PROFILE_KEY].is_publisher: return self.forbidden() template_values['products'] = template_values[handlers.base.PROFILE_KEY].get_published_products() template_values['upload_url'] = blobstore.create_upload_url(self.uri_for('product.upload')) if users.is_current_user_admin(): template_values['products'].append(self.CoreProduct()) template = configuration.site.jinja_environment.get_template('product/upload.html') self.response.write(template.render(template_values)) def post(self): """HTML POST handler. Parse ALL THE MONSTERS.""" template_values = self.build_template_values() if not template_values[handlers.base.PROFILE_KEY].is_publisher: return self.forbidden() upload_files = self.get_uploads('file_upload') blob_info = upload_files[0] blob_key = blob_info.key() blob_reader = blobstore.BlobReader(blob_key) root = ET.parse(blob_reader) product = int(self.request.get('product')) for upload_monster in root.iter('monster'): monster = Monster() if product == -1: monster.is_core = True else: monster.product = product monster.creator = template_values[handlers.base.PROFILE_KEY] monster.name = upload_monster.findtext('name') monster.description = upload_monster.findtext('description') monster.instinct = upload_monster.findtext('instinct') tags = upload_monster.find('tags') if tags and len(tags): for tag in tags: monster.tags.append(tag.text.encode('utf-8')) monster.damage = upload_monster.findtext('damage') monster.hp = upload_monster.findtext('hp') monster.armor = upload_monster.findtext('armor') damage_tags = upload_monster.find('damage_tags') if damage_tags and len(damage_tags): for tag in damage_tags: monster.damage_tags.append(tag.text) special_qualities = upload_monster.find('special_qualities') if special_qualities and len(special_qualities): for special_quality in special_qualities: monster.special_qualities.append(special_quality.text) for move in upload_monster.find('moves'): monster.moves.append(move.text) try: monster.put() except: print monster raise if product == -1: return self.redirect(self.uri_for('home')) self.redirect(self.uri_for('product', entity_id=product))
handlers/product.py
import webapp2 import jinja2 from google.appengine.ext import db from google.appengine.api import users from data.models import Monster, Profile, Vote, Product import handlers.base import configuration.site import xml.etree.ElementTree as ET from google.appengine.ext import blobstore from google.appengine.ext.webapp import blobstore_handlers import logging class CreateHandler(handlers.base.LoggedInRequestHandler): """Creates a new product Given the name of the product, create a new product with the current user as the creator and a random access code.""" def get(self): """HTML GET handler. Render a form that has all the data to make a product.""" template_values = self.build_template_values() if not template_values[handlers.base.PROFILE_KEY]: return self.forbidden() elif not template_values[handlers.base.PROFILE_KEY].is_publisher: return self.forbidden() template = configuration.site.jinja_environment.get_template('product/create.html') self.response.write(template.render(template_values)) def post(self): """HTML POST handler. Check the query parameters for the name of the product, then make it.""" template_values = self.build_template_values() if not template_values[handlers.base.PROFILE_KEY]: return self.forbidden() elif not template_values[handlers.base.PROFILE_KEY].is_publisher: return self.forbidden() name = self.request.get('name') description = self.request.get('description') link = self.request.get('link') if (not name) or (not link) or (not description): return self.forbidden() product = Product() product.creator = template_values[handlers.base.PROFILE_KEY] product.name = name product.link = link product.description = description product.generate_access_code() product.put() template_values[handlers.base.PROFILE_KEY].products.append(product.key().id()) template_values[handlers.base.PROFILE_KEY].put() return self.redirect(self.uri_for('profile.edit')) class ViewHandler(handlers.base.LoggedInRequestHandler): """Renders a single product view page. Given the ID of a product to view, query for that prodict and display it using the standard product template.""" def get(self, entity_id=None): """HTML GET handler. Display the product with the specified ID""" template_values = self.build_template_values() if entity_id: try: product = Product.get_by_id(int(entity_id)) except ValueError: return self.not_found() if not product: self.not_found() return template_values['product'] = product else: self.redirect(self.uri_for('product.home')) return template = configuration.site.jinja_environment.get_template('product/view.html') self.response.write(template.render(template_values)) class UpdateHandler(handlers.base.LoggedInRequestHandler): """Updates the access code for a product. Given the ID of a product to update, generate a new access code for it, then redirect to the profile edit page.""" def get(self, entity_id=None): """HTML GET handler. Update the product with the specified ID""" template_values = self.build_template_values() if entity_id: try: product = Product.get_by_id(int(entity_id)) except ValueError: return self.not_found() if not product: self.not_found() return product.generate_access_code() product.put() else: self.redirect(self.uri_for('product.home')) return return self.redirect(self.uri_for('profile.edit')) class UploadHandler(handlers.base.LoggedInRequestHandler, blobstore_handlers.BlobstoreUploadHandler): """"Uploads a file and parses it for monsters. Templates used: upload.html""" class CoreProduct(object): name = "Core" class FakeKey(object): def id(self): return -1 def key(self): return self.FakeKey() def get(self): """HTML GET handler. Check the query parameters for the ID of the monster to be edited. If found, display that monster for editing.""" template_values = self.build_template_values() if not template_values[handlers.base.PROFILE_KEY].is_publisher: return self.forbidden() template_values['products'] = template_values[handlers.base.PROFILE_KEY].get_published_products() template_values['upload_url'] = blobstore.create_upload_url(self.uri_for('product.upload')) if users.is_current_user_admin(): template_values['products'].append(self.CoreProduct()) template = configuration.site.jinja_environment.get_template('product/upload.html') self.response.write(template.render(template_values)) def post(self): """HTML POST handler. Parse ALL THE MONSTERS.""" template_values = self.build_template_values() if not template_values[handlers.base.PROFILE_KEY].is_publisher: return self.forbidden() upload_files = self.get_uploads('file_upload') blob_info = upload_files[0] blob_key = blob_info.key() blob_reader = blobstore.BlobReader(blob_key) root = ET.parse(blob_reader) product = int(self.request.get('product')) for upload_monster in root.iter('monster'): monster = Monster() if product == -1: monster.is_core = True else: monster.product = product monster.creator = template_values[handlers.base.PROFILE_KEY] monster.name = upload_monster.findtext('name') monster.description = upload_monster.findtext('description') monster.instinct = upload_monster.findtext('instinct') tags = upload_monster.find('tags') if tags and len(tags): for tag in tags: monster.tags.append(tag.text.encode('utf-8')) monster.damage = upload_monster.findtext('damage') monster.hp = upload_monster.findtext('hp') monster.armor = upload_monster.findtext('armor') damage_tags = upload_monster.find('damage_tags') if damage_tags and len(damage_tags): for tag in damage_tags: monster.damage_tags.append(tag.text) special_qualities = upload_monster.find('special_qualities') if special_qualities and len(special_qualities): for special_quality in special_qualities: monster.special_qualities.append(special_quality.text) for move in upload_monster.find('moves'): monster.moves.append(move.text) try: monster.put() except: print monster raise if product == -1: return self.redirect(self.uri_for('home')) self.redirect(self.uri_for('product', entity_id=product))
0.403097
0.119974
import logging import os import subprocess from patroni.exceptions import PostgresException from patroni.utils import polling_loop from six import string_types from threading import Lock logger = logging.getLogger(__name__) class CancellableSubprocess(object): def __init__(self): self._is_cancelled = False self._process = None self._lock = Lock() def call(self, *args, **kwargs): for s in ('stdin', 'stdout', 'stderr'): kwargs.pop(s, None) communicate_input = 'communicate_input' in kwargs if communicate_input: input_data = kwargs.pop('communicate_input', None) if not isinstance(input_data, string_types): input_data = '' if input_data and input_data[-1] != '\n': input_data += '\n' kwargs['stdin'] = subprocess.PIPE kwargs['stdout'] = open(os.devnull, 'w') kwargs['stderr'] = subprocess.STDOUT try: with self._lock: if self._is_cancelled: raise PostgresException('cancelled') self._is_cancelled = False self._process = subprocess.Popen(*args, **kwargs) if communicate_input: if input_data: self._process.communicate(input_data) self._process.stdin.close() return self._process.wait() finally: with self._lock: self._process = None def reset_is_cancelled(self): with self._lock: self._is_cancelled = False @property def is_cancelled(self): with self._lock: return self._is_cancelled def cancel(self): with self._lock: self._is_cancelled = True if self._process is None or self._process.returncode is not None: return self._process.terminate() for _ in polling_loop(10): with self._lock: if self._process is None or self._process.returncode is not None: return with self._lock: if self._process is not None and self._process.returncode is None: self._process.kill()
patroni/postgresql/cancellable.py
import logging import os import subprocess from patroni.exceptions import PostgresException from patroni.utils import polling_loop from six import string_types from threading import Lock logger = logging.getLogger(__name__) class CancellableSubprocess(object): def __init__(self): self._is_cancelled = False self._process = None self._lock = Lock() def call(self, *args, **kwargs): for s in ('stdin', 'stdout', 'stderr'): kwargs.pop(s, None) communicate_input = 'communicate_input' in kwargs if communicate_input: input_data = kwargs.pop('communicate_input', None) if not isinstance(input_data, string_types): input_data = '' if input_data and input_data[-1] != '\n': input_data += '\n' kwargs['stdin'] = subprocess.PIPE kwargs['stdout'] = open(os.devnull, 'w') kwargs['stderr'] = subprocess.STDOUT try: with self._lock: if self._is_cancelled: raise PostgresException('cancelled') self._is_cancelled = False self._process = subprocess.Popen(*args, **kwargs) if communicate_input: if input_data: self._process.communicate(input_data) self._process.stdin.close() return self._process.wait() finally: with self._lock: self._process = None def reset_is_cancelled(self): with self._lock: self._is_cancelled = False @property def is_cancelled(self): with self._lock: return self._is_cancelled def cancel(self): with self._lock: self._is_cancelled = True if self._process is None or self._process.returncode is not None: return self._process.terminate() for _ in polling_loop(10): with self._lock: if self._process is None or self._process.returncode is not None: return with self._lock: if self._process is not None and self._process.returncode is None: self._process.kill()
0.350755
0.04653
import struct from typing import ClassVar, Optional import attr import marshmallow from marshmallow import post_load from elgas.parameters.enumerations import ParameterObjectType from elgas.utils import pop_many, pretty_text @attr.s(auto_attribs=True) class ErrorCounter: object_type: ClassVar[ParameterObjectType] = ParameterObjectType.ERROR_COUNTER value_length: ClassVar[int] = 4 number: int id: int address_in_actual_values: int address_in_data_archive_record: int bit_control: int in_data_archive: bool in_daily_archive: bool in_monthly_archive: bool in_factory_archive: bool is_metrological_quantity: bool name: str unit: str digit: float number_of_primary_counter: int address_in_daily_archive_record: int address_in_monthly_archive_record: int address_in_billing_archive_record: int decimals: Optional[int] @classmethod def from_bytes(cls, in_data: bytes): data = bytearray(in_data) number = int.from_bytes(pop_many(data, 2), "little") id = int.from_bytes(pop_many(data, 2), "little") address_in_actual_values = int.from_bytes(pop_many(data, 2), "little") address_in_data_archive_record = int.from_bytes(pop_many(data, 2), "little") bit_control = data.pop(0) in_data_archive = bool(bit_control & 0b00000001) in_daily_archive = bool(bit_control & 0b00000010) in_monthly_archive = bool(bit_control & 0b00000100) in_factory_archive = bool(bit_control & 0b00001000) is_metrological_quantity = bool(bit_control & 0b00010000) name = pretty_text(pop_many(data, 23)) unit = pretty_text(pop_many(data, 8)) digit = struct.unpack("<d", pop_many(data, 8))[0] number_of_primary_counter = data.pop(0) address_in_daily_archive_record = int.from_bytes(pop_many(data, 2), "little") address_in_monthly_archive_record = int.from_bytes(pop_many(data, 2), "little") address_in_billing_archive_record = int.from_bytes(pop_many(data, 2), "little") if data: decimals = data.pop(0) else: decimals = None return cls( number=number, id=id, address_in_actual_values=address_in_actual_values, address_in_data_archive_record=address_in_data_archive_record, bit_control=bit_control, in_data_archive=in_data_archive, in_daily_archive=in_daily_archive, in_monthly_archive=in_monthly_archive, in_factory_archive=in_factory_archive, is_metrological_quantity=is_metrological_quantity, name=name, unit=unit, digit=digit, number_of_primary_counter=number_of_primary_counter, address_in_daily_archive_record=address_in_daily_archive_record, address_in_monthly_archive_record=address_in_monthly_archive_record, address_in_billing_archive_record=address_in_billing_archive_record, decimals=decimals, ) class DoubleErrorCounter(ErrorCounter): object_type: ClassVar[ ParameterObjectType ] = ParameterObjectType.DOUBLE_ERROR_COUNTER value_length: ClassVar[int] = 8 class CorrectionCounter(ErrorCounter): object_type: ClassVar[ParameterObjectType] = ParameterObjectType.CORRECTION_COUNTER value_length: ClassVar[int] = 4 class ErrorCounterSchema(marshmallow.Schema): number = marshmallow.fields.Integer(required=True) id = marshmallow.fields.Integer(required=True) address_in_actual_values = marshmallow.fields.Integer(required=True) address_in_data_archive_record = marshmallow.fields.Integer(required=True) bit_control = marshmallow.fields.Integer(required=True) in_data_archive = marshmallow.fields.Boolean(required=True) in_daily_archive = marshmallow.fields.Boolean(required=True) in_monthly_archive = marshmallow.fields.Boolean(required=True) in_factory_archive = marshmallow.fields.Boolean(required=True) is_metrological_quantity = marshmallow.fields.Boolean(required=True) name = marshmallow.fields.String(required=True) unit = marshmallow.fields.String(required=True) digit = marshmallow.fields.Float(required=True, as_string=True) number_of_primary_counter = marshmallow.fields.Integer(required=True) address_in_daily_archive_record = marshmallow.fields.Integer(required=True) address_in_monthly_archive_record = marshmallow.fields.Integer(required=True) address_in_billing_archive_record = marshmallow.fields.Integer(required=True) decimals = marshmallow.fields.Integer(required=True, allow_none=True) @post_load def make_object(self, data, **kwargs): return ErrorCounter(**data) class DoubleErrorCounterSchema(ErrorCounterSchema): @post_load def make_object(self, data, **kwargs): return DoubleErrorCounter(**data) class CorrectionCounterSchema(ErrorCounterSchema): @post_load def make_object(self, data, **kwargs): return CorrectionCounter(**data)
elgas/parameters/error_counter.py
import struct from typing import ClassVar, Optional import attr import marshmallow from marshmallow import post_load from elgas.parameters.enumerations import ParameterObjectType from elgas.utils import pop_many, pretty_text @attr.s(auto_attribs=True) class ErrorCounter: object_type: ClassVar[ParameterObjectType] = ParameterObjectType.ERROR_COUNTER value_length: ClassVar[int] = 4 number: int id: int address_in_actual_values: int address_in_data_archive_record: int bit_control: int in_data_archive: bool in_daily_archive: bool in_monthly_archive: bool in_factory_archive: bool is_metrological_quantity: bool name: str unit: str digit: float number_of_primary_counter: int address_in_daily_archive_record: int address_in_monthly_archive_record: int address_in_billing_archive_record: int decimals: Optional[int] @classmethod def from_bytes(cls, in_data: bytes): data = bytearray(in_data) number = int.from_bytes(pop_many(data, 2), "little") id = int.from_bytes(pop_many(data, 2), "little") address_in_actual_values = int.from_bytes(pop_many(data, 2), "little") address_in_data_archive_record = int.from_bytes(pop_many(data, 2), "little") bit_control = data.pop(0) in_data_archive = bool(bit_control & 0b00000001) in_daily_archive = bool(bit_control & 0b00000010) in_monthly_archive = bool(bit_control & 0b00000100) in_factory_archive = bool(bit_control & 0b00001000) is_metrological_quantity = bool(bit_control & 0b00010000) name = pretty_text(pop_many(data, 23)) unit = pretty_text(pop_many(data, 8)) digit = struct.unpack("<d", pop_many(data, 8))[0] number_of_primary_counter = data.pop(0) address_in_daily_archive_record = int.from_bytes(pop_many(data, 2), "little") address_in_monthly_archive_record = int.from_bytes(pop_many(data, 2), "little") address_in_billing_archive_record = int.from_bytes(pop_many(data, 2), "little") if data: decimals = data.pop(0) else: decimals = None return cls( number=number, id=id, address_in_actual_values=address_in_actual_values, address_in_data_archive_record=address_in_data_archive_record, bit_control=bit_control, in_data_archive=in_data_archive, in_daily_archive=in_daily_archive, in_monthly_archive=in_monthly_archive, in_factory_archive=in_factory_archive, is_metrological_quantity=is_metrological_quantity, name=name, unit=unit, digit=digit, number_of_primary_counter=number_of_primary_counter, address_in_daily_archive_record=address_in_daily_archive_record, address_in_monthly_archive_record=address_in_monthly_archive_record, address_in_billing_archive_record=address_in_billing_archive_record, decimals=decimals, ) class DoubleErrorCounter(ErrorCounter): object_type: ClassVar[ ParameterObjectType ] = ParameterObjectType.DOUBLE_ERROR_COUNTER value_length: ClassVar[int] = 8 class CorrectionCounter(ErrorCounter): object_type: ClassVar[ParameterObjectType] = ParameterObjectType.CORRECTION_COUNTER value_length: ClassVar[int] = 4 class ErrorCounterSchema(marshmallow.Schema): number = marshmallow.fields.Integer(required=True) id = marshmallow.fields.Integer(required=True) address_in_actual_values = marshmallow.fields.Integer(required=True) address_in_data_archive_record = marshmallow.fields.Integer(required=True) bit_control = marshmallow.fields.Integer(required=True) in_data_archive = marshmallow.fields.Boolean(required=True) in_daily_archive = marshmallow.fields.Boolean(required=True) in_monthly_archive = marshmallow.fields.Boolean(required=True) in_factory_archive = marshmallow.fields.Boolean(required=True) is_metrological_quantity = marshmallow.fields.Boolean(required=True) name = marshmallow.fields.String(required=True) unit = marshmallow.fields.String(required=True) digit = marshmallow.fields.Float(required=True, as_string=True) number_of_primary_counter = marshmallow.fields.Integer(required=True) address_in_daily_archive_record = marshmallow.fields.Integer(required=True) address_in_monthly_archive_record = marshmallow.fields.Integer(required=True) address_in_billing_archive_record = marshmallow.fields.Integer(required=True) decimals = marshmallow.fields.Integer(required=True, allow_none=True) @post_load def make_object(self, data, **kwargs): return ErrorCounter(**data) class DoubleErrorCounterSchema(ErrorCounterSchema): @post_load def make_object(self, data, **kwargs): return DoubleErrorCounter(**data) class CorrectionCounterSchema(ErrorCounterSchema): @post_load def make_object(self, data, **kwargs): return CorrectionCounter(**data)
0.821295
0.33012
from mock import Mock, patch @patch('cvm.services.VRouterPortService._port_needs_an_update', Mock(return_value=True)) def test_create_port(vrouter_port_service, database, vrouter_api_client, vmi_model): database.ports_to_update.append(vmi_model) vrouter_port_service.sync_ports() vrouter_api_client.delete_port.assert_not_called() vrouter_api_client.add_port.assert_called_once_with(vmi_model) vrouter_api_client.enable_port.assert_called_once_with(vmi_model.uuid) @patch('cvm.services.VRouterPortService._port_needs_an_update', Mock(return_value=False)) def test_no_update(vrouter_port_service, database, vrouter_api_client, vmi_model): vrouter_api_client.read_port.return_value = {'dummy': 'dummy-value'} database.ports_to_update.append(vmi_model) vrouter_port_service.sync_ports() vrouter_api_client.delete_port.assert_not_called() vrouter_api_client.add_port.assert_not_called() assert database.ports_to_update == [] def test_delete_port(vrouter_port_service, database, vrouter_api_client): database.ports_to_delete.append('port-uuid') vrouter_port_service.sync_ports() vrouter_api_client.delete_port.assert_called_once_with('port-uuid') @patch('cvm.services.VRouterPortService._port_needs_an_update', Mock(return_value=False)) def test_enable_port(vrouter_port_service, database, vrouter_api_client, vmi_model): vmi_model.vm_model.update_power_state = True database.ports_to_update.append(vmi_model) vrouter_port_service.sync_ports() vrouter_api_client.enable_port.assert_called_once_with(vmi_model.uuid) vrouter_api_client.disable_port.assert_not_called() @patch('cvm.services.VRouterPortService._port_needs_an_update', Mock(return_value=False)) def test_disable_port(vrouter_port_service, database, vrouter_api_client, vmi_model): vmi_model.vm_model.update_power_state = False database.ports_to_update.append(vmi_model) vrouter_port_service.sync_ports() vrouter_api_client.enable_port.assert_called_once_with(vmi_model.uuid) vrouter_api_client.disable_port.assert_not_called()
tests/unit/services/test_vrouter_port_service.py
from mock import Mock, patch @patch('cvm.services.VRouterPortService._port_needs_an_update', Mock(return_value=True)) def test_create_port(vrouter_port_service, database, vrouter_api_client, vmi_model): database.ports_to_update.append(vmi_model) vrouter_port_service.sync_ports() vrouter_api_client.delete_port.assert_not_called() vrouter_api_client.add_port.assert_called_once_with(vmi_model) vrouter_api_client.enable_port.assert_called_once_with(vmi_model.uuid) @patch('cvm.services.VRouterPortService._port_needs_an_update', Mock(return_value=False)) def test_no_update(vrouter_port_service, database, vrouter_api_client, vmi_model): vrouter_api_client.read_port.return_value = {'dummy': 'dummy-value'} database.ports_to_update.append(vmi_model) vrouter_port_service.sync_ports() vrouter_api_client.delete_port.assert_not_called() vrouter_api_client.add_port.assert_not_called() assert database.ports_to_update == [] def test_delete_port(vrouter_port_service, database, vrouter_api_client): database.ports_to_delete.append('port-uuid') vrouter_port_service.sync_ports() vrouter_api_client.delete_port.assert_called_once_with('port-uuid') @patch('cvm.services.VRouterPortService._port_needs_an_update', Mock(return_value=False)) def test_enable_port(vrouter_port_service, database, vrouter_api_client, vmi_model): vmi_model.vm_model.update_power_state = True database.ports_to_update.append(vmi_model) vrouter_port_service.sync_ports() vrouter_api_client.enable_port.assert_called_once_with(vmi_model.uuid) vrouter_api_client.disable_port.assert_not_called() @patch('cvm.services.VRouterPortService._port_needs_an_update', Mock(return_value=False)) def test_disable_port(vrouter_port_service, database, vrouter_api_client, vmi_model): vmi_model.vm_model.update_power_state = False database.ports_to_update.append(vmi_model) vrouter_port_service.sync_ports() vrouter_api_client.enable_port.assert_called_once_with(vmi_model.uuid) vrouter_api_client.disable_port.assert_not_called()
0.690455
0.150465
import sqlite3 import os import re import json def all_files(d: str, ignore=None): rv = list() offset = len(os.path.dirname(d)) for root, subdirs, files in os.walk(d): root = root[offset:] root = root.lstrip('/') files = [f'{root}/{f}' for f in files] if ignore: files = [f for f in files if not ignore.match(f)] rv.extend(files) return rv def clean_db(db_path): if os.path.exists(db_path): os.remove(db_path) with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cursor.execute('CREATE TABLE Resources (ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Path TEXT NOT NULL UNIQUE, Data BLOB, MetaData TEXT);') def pack_assets(db_path): ase_json_undo = re.compile('.*\\.aseprite|.*~|.*\\.json') asset_paths = all_files('assets', ignore = ase_json_undo) with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cmd = 'INSERT INTO Resources (Path,Data,MetaData) VALUES (?,?,?);' cmd_nometa = 'INSERT INTO Resources (Path,Data) VALUES (?,?);' for asset_path in asset_paths: meta_path = asset_path+'.json' meta = None if os.path.exists(meta_path): with open(meta_path, 'r') as f: meta_json = json.load(f) meta = json.dumps(meta_json, separators=(',',':'), indent=None) with open(asset_path, 'rb') as f: asset = f.read() if meta: cursor.execute(cmd, (asset_path,asset, meta)) print(f'Packed asset "{asset_path}" with its meta data.') else: cursor.execute(cmd_nometa, (asset_path,asset)) print(f'Packed asset "{asset_path}".') def pack_rooms(db_path): not_json = re.compile('.*(?<!.json)$') room_paths = all_files('assets/rooms', ignore=not_json) with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cmd = 'INSERT INTO Resources (Path,MetaData) VALUES (?,?);' for room_path in room_paths: room_path = f'assets/{room_path}' with open(room_path, 'r') as f: room = f.read() cursor.execute(cmd, (room_path, room)) print(f'Packed room "{room_path}".') def pack_shaders(db_path): undo = re.compile('.*~') shader_paths = all_files('shaders', ignore=undo) with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cmd = 'INSERT INTO Resources (Path,Data) VALUES (?,?);' for shader_path in shader_paths: with open(shader_path, 'rb') as f: shader = f.read() cursor.execute(cmd, (shader_path,shader)) print(f'Packed shader "{shader_path}".') if __name__ == '__main__': db_path = 'geas_files.db' clean_db(db_path) pack_assets(db_path) pack_rooms(db_path) pack_shaders(db_path)
scripts/pack.py
import sqlite3 import os import re import json def all_files(d: str, ignore=None): rv = list() offset = len(os.path.dirname(d)) for root, subdirs, files in os.walk(d): root = root[offset:] root = root.lstrip('/') files = [f'{root}/{f}' for f in files] if ignore: files = [f for f in files if not ignore.match(f)] rv.extend(files) return rv def clean_db(db_path): if os.path.exists(db_path): os.remove(db_path) with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cursor.execute('CREATE TABLE Resources (ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Path TEXT NOT NULL UNIQUE, Data BLOB, MetaData TEXT);') def pack_assets(db_path): ase_json_undo = re.compile('.*\\.aseprite|.*~|.*\\.json') asset_paths = all_files('assets', ignore = ase_json_undo) with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cmd = 'INSERT INTO Resources (Path,Data,MetaData) VALUES (?,?,?);' cmd_nometa = 'INSERT INTO Resources (Path,Data) VALUES (?,?);' for asset_path in asset_paths: meta_path = asset_path+'.json' meta = None if os.path.exists(meta_path): with open(meta_path, 'r') as f: meta_json = json.load(f) meta = json.dumps(meta_json, separators=(',',':'), indent=None) with open(asset_path, 'rb') as f: asset = f.read() if meta: cursor.execute(cmd, (asset_path,asset, meta)) print(f'Packed asset "{asset_path}" with its meta data.') else: cursor.execute(cmd_nometa, (asset_path,asset)) print(f'Packed asset "{asset_path}".') def pack_rooms(db_path): not_json = re.compile('.*(?<!.json)$') room_paths = all_files('assets/rooms', ignore=not_json) with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cmd = 'INSERT INTO Resources (Path,MetaData) VALUES (?,?);' for room_path in room_paths: room_path = f'assets/{room_path}' with open(room_path, 'r') as f: room = f.read() cursor.execute(cmd, (room_path, room)) print(f'Packed room "{room_path}".') def pack_shaders(db_path): undo = re.compile('.*~') shader_paths = all_files('shaders', ignore=undo) with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cmd = 'INSERT INTO Resources (Path,Data) VALUES (?,?);' for shader_path in shader_paths: with open(shader_path, 'rb') as f: shader = f.read() cursor.execute(cmd, (shader_path,shader)) print(f'Packed shader "{shader_path}".') if __name__ == '__main__': db_path = 'geas_files.db' clean_db(db_path) pack_assets(db_path) pack_rooms(db_path) pack_shaders(db_path)
0.202917
0.084531
import json import requests import six from six.moves import urllib from firebase_admin import _auth_utils from firebase_admin import _user_import MAX_LIST_USERS_RESULTS = 1000 MAX_IMPORT_USERS_SIZE = 1000 class Sentinel(object): def __init__(self, description): self.description = description DELETE_ATTRIBUTE = Sentinel('Value used to delete an attribute from a user profile') class UserMetadata(object): """Contains additional metadata associated with a user account.""" def __init__(self, creation_timestamp=None, last_sign_in_timestamp=None): self._creation_timestamp = _auth_utils.validate_timestamp( creation_timestamp, 'creation_timestamp') self._last_sign_in_timestamp = _auth_utils.validate_timestamp( last_sign_in_timestamp, 'last_sign_in_timestamp') @property def creation_timestamp(self): """ Creation timestamp in milliseconds since the epoch. Returns: integer: The user creation timestamp in milliseconds since the epoch. """ return self._creation_timestamp @property def last_sign_in_timestamp(self): """ Last sign in timestamp in milliseconds since the epoch. Returns: integer: The last sign in timestamp in milliseconds since the epoch. """ return self._last_sign_in_timestamp class UserInfo(object): """A collection of standard profile information for a user. Used to expose profile information returned by an identity provider. """ @property def uid(self): """Returns the user ID of this user.""" raise NotImplementedError @property def display_name(self): """Returns the display name of this user.""" raise NotImplementedError @property def email(self): """Returns the email address associated with this user.""" raise NotImplementedError @property def phone_number(self): """Returns the phone number associated with this user.""" raise NotImplementedError @property def photo_url(self): """Returns the photo URL of this user.""" raise NotImplementedError @property def provider_id(self): """Returns the ID of the identity provider. This can be a short domain name (e.g. google.com), or the identity of an OpenID identity provider. """ raise NotImplementedError class UserRecord(UserInfo): """Contains metadata associated with a Firebase user account.""" def __init__(self, data): super(UserRecord, self).__init__() if not isinstance(data, dict): raise ValueError('Invalid data argument: {0}. Must be a dictionary.'.format(data)) if not data.get('localId'): raise ValueError('User ID must not be None or empty.') self._data = data @property def uid(self): """Returns the user ID of this user. Returns: string: A user ID string. This value is never None or empty. """ return self._data.get('localId') @property def display_name(self): """Returns the display name of this user. Returns: string: A display name string or None. """ return self._data.get('displayName') @property def email(self): """Returns the email address associated with this user. Returns: string: An email address string or None. """ return self._data.get('email') @property def phone_number(self): """Returns the phone number associated with this user. Returns: string: A phone number string or None. """ return self._data.get('phoneNumber') @property def photo_url(self): """Returns the photo URL of this user. Returns: string: A URL string or None. """ return self._data.get('photoUrl') @property def provider_id(self): """Returns the provider ID of this user. Returns: string: A constant provider ID value. """ return 'firebase' @property def email_verified(self): """Returns whether the email address of this user has been verified. Returns: bool: True if the email has been verified, and False otherwise. """ return bool(self._data.get('emailVerified')) @property def disabled(self): """Returns whether this user account is disabled. Returns: bool: True if the user account is disabled, and False otherwise. """ return bool(self._data.get('disabled')) @property def tokens_valid_after_timestamp(self): """Returns the time, in milliseconds since the epoch, before which tokens are invalid. Note: this is truncated to 1 second accuracy. Returns: int: Timestamp in milliseconds since the epoch, truncated to the second. All tokens issued before that time are considered revoked. """ valid_since = self._data.get('validSince') if valid_since is not None: return 1000 * int(valid_since) return 0 @property def user_metadata(self): """Returns additional metadata associated with this user. Returns: UserMetadata: A UserMetadata instance. Does not return None. """ def _int_or_none(key): if key in self._data: return int(self._data[key]) return None return UserMetadata(_int_or_none('createdAt'), _int_or_none('lastLoginAt')) @property def provider_data(self): """Returns a list of UserInfo instances. Each object represents an identity from an identity provider that is linked to this user. Returns: list: A list of UserInfo objects, which may be empty. """ providers = self._data.get('providerUserInfo', []) return [ProviderUserInfo(entry) for entry in providers] @property def custom_claims(self): """Returns any custom claims set on this user account. Returns: dict: A dictionary of claims or None. """ claims = self._data.get('customAttributes') if claims: parsed = json.loads(claims) if parsed != {}: return parsed return None class ExportedUserRecord(UserRecord): """Contains metadata associated with a user including password hash and salt.""" def __init__(self, data): super(ExportedUserRecord, self).__init__(data) @property def password_hash(self): """The user's password hash as a base64-encoded string. If the Firebase Auth hashing algorithm (SCRYPT) was used to create the user account, this is the base64-encoded password hash of the user. If a different hashing algorithm was used to create this user, as is typical when migrating from another Auth system, this is an empty string. If no password is set, this is ``None``. """ return self._data.get('passwordHash') @property def password_salt(self): """The user's password salt as a base64-encoded string. If the Firebase Auth hashing algorithm (SCRYPT) was used to create the user account, this is the base64-encoded password salt of the user. If a different hashing algorithm was used to create this user, as is typical when migrating from another Auth system, this is an empty string. If no password is set, this is ``None``. """ return self._data.get('salt') class ListUsersPage(object): """Represents a page of user records exported from a Firebase project. Provides methods for traversing the user accounts included in this page, as well as retrieving subsequent pages of users. The iterator returned by ``iterate_all()`` can be used to iterate through all users in the Firebase project starting from this page. """ def __init__(self, download, page_token, max_results): self._download = download self._max_results = max_results self._current = download(page_token, max_results) @property def users(self): """A list of ``ExportedUserRecord`` instances available in this page.""" return [ExportedUserRecord(user) for user in self._current.get('users', [])] @property def next_page_token(self): """Page token string for the next page (empty string indicates no more pages).""" return self._current.get('nextPageToken', '') @property def has_next_page(self): """A boolean indicating whether more pages are available.""" return bool(self.next_page_token) def get_next_page(self): """Retrieves the next page of user accounts, if available. Returns: ListUsersPage: Next page of users, or None if this is the last page. """ if self.has_next_page: return ListUsersPage(self._download, self.next_page_token, self._max_results) return None def iterate_all(self): """Retrieves an iterator for user accounts. Returned iterator will iterate through all the user accounts in the Firebase project starting from this page. The iterator will never buffer more than one page of users in memory at a time. Returns: iterator: An iterator of ExportedUserRecord instances. """ return _UserIterator(self) class ProviderUserInfo(UserInfo): """Contains metadata regarding how a user is known by a particular identity provider.""" def __init__(self, data): super(ProviderUserInfo, self).__init__() if not isinstance(data, dict): raise ValueError('Invalid data argument: {0}. Must be a dictionary.'.format(data)) if not data.get('rawId'): raise ValueError('User ID must not be None or empty.') self._data = data @property def uid(self): return self._data.get('rawId') @property def display_name(self): return self._data.get('displayName') @property def email(self): return self._data.get('email') @property def phone_number(self): return self._data.get('phoneNumber') @property def photo_url(self): return self._data.get('photoUrl') @property def provider_id(self): return self._data.get('providerId') class ActionCodeSettings(object): """Contains required continue/state URL with optional Android and iOS settings. Used when invoking the email action link generation APIs. """ def __init__(self, url, handle_code_in_app=None, dynamic_link_domain=None, ios_bundle_id=None, android_package_name=None, android_install_app=None, android_minimum_version=None): self.url = url self.handle_code_in_app = handle_code_in_app self.dynamic_link_domain = dynamic_link_domain self.ios_bundle_id = ios_bundle_id self.android_package_name = android_package_name self.android_install_app = android_install_app self.android_minimum_version = android_minimum_version def encode_action_code_settings(settings): """ Validates the provided action code settings for email link generation and populates the REST api parameters. settings - ``ActionCodeSettings`` object provided to be encoded returns - dict of parameters to be passed for link gereration. """ parameters = {} # url if not settings.url: raise ValueError("Dynamic action links url is mandatory") try: parsed = urllib.parse.urlparse(settings.url) if not parsed.netloc: raise ValueError('Malformed dynamic action links url: "{0}".'.format(settings.url)) parameters['continueUrl'] = settings.url except Exception: raise ValueError('Malformed dynamic action links url: "{0}".'.format(settings.url)) # handle_code_in_app if settings.handle_code_in_app is not None: if not isinstance(settings.handle_code_in_app, bool): raise ValueError('Invalid value provided for handle_code_in_app: {0}' .format(settings.handle_code_in_app)) parameters['canHandleCodeInApp'] = settings.handle_code_in_app # dynamic_link_domain if settings.dynamic_link_domain is not None: if not isinstance(settings.dynamic_link_domain, six.string_types): raise ValueError('Invalid value provided for dynamic_link_domain: {0}' .format(settings.dynamic_link_domain)) parameters['dynamicLinkDomain'] = settings.dynamic_link_domain # ios_bundle_id if settings.ios_bundle_id is not None: if not isinstance(settings.ios_bundle_id, six.string_types): raise ValueError('Invalid value provided for ios_bundle_id: {0}' .format(settings.ios_bundle_id)) parameters['iosBundleId'] = settings.ios_bundle_id # android_* attributes if (settings.android_minimum_version or settings.android_install_app) \ and not settings.android_package_name: raise ValueError("Android package name is required when specifying other Android settings") if settings.android_package_name is not None: if not isinstance(settings.android_package_name, six.string_types): raise ValueError('Invalid value provided for android_package_name: {0}' .format(settings.android_package_name)) parameters['androidPackageName'] = settings.android_package_name if settings.android_minimum_version is not None: if not isinstance(settings.android_minimum_version, six.string_types): raise ValueError('Invalid value provided for android_minimum_version: {0}' .format(settings.android_minimum_version)) parameters['androidMinimumVersion'] = settings.android_minimum_version if settings.android_install_app is not None: if not isinstance(settings.android_install_app, bool): raise ValueError('Invalid value provided for android_install_app: {0}' .format(settings.android_install_app)) parameters['androidInstallApp'] = settings.android_install_app return parameters class UserManager(object): """Provides methods for interacting with the Google Identity Toolkit.""" def __init__(self, client): self._client = client def get_user(self, **kwargs): """Gets the user data corresponding to the provided key.""" if 'uid' in kwargs: key, key_type = kwargs.pop('uid'), 'user ID' payload = {'localId' : [_auth_utils.validate_uid(key, required=True)]} elif 'email' in kwargs: key, key_type = kwargs.pop('email'), 'email' payload = {'email' : [_auth_utils.validate_email(key, required=True)]} elif 'phone_number' in kwargs: key, key_type = kwargs.pop('phone_number'), 'phone number' payload = {'phoneNumber' : [_auth_utils.validate_phone(key, required=True)]} else: raise TypeError('Unsupported keyword arguments: {0}.'.format(kwargs)) try: body, http_resp = self._client.body_and_response( 'post', '/accounts:lookup', json=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not body or not body.get('users'): raise _auth_utils.UserNotFoundError( 'No user record found for the provided {0}: {1}.'.format(key_type, key), http_response=http_resp) return body['users'][0] def list_users(self, page_token=None, max_results=MAX_LIST_USERS_RESULTS): """Retrieves a batch of users.""" if page_token is not None: if not isinstance(page_token, six.string_types) or not page_token: raise ValueError('Page token must be a non-empty string.') if not isinstance(max_results, int): raise ValueError('Max results must be an integer.') elif max_results < 1 or max_results > MAX_LIST_USERS_RESULTS: raise ValueError( 'Max results must be a positive integer less than ' '{0}.'.format(MAX_LIST_USERS_RESULTS)) payload = {'maxResults': max_results} if page_token: payload['nextPageToken'] = page_token try: return self._client.body('get', '/accounts:batchGet', params=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) def create_user(self, uid=None, display_name=None, email=None, phone_number=None, photo_url=None, password=<PASSWORD>, disabled=None, email_verified=None): """Creates a new user account with the specified properties.""" payload = { 'localId': _auth_utils.validate_uid(uid), 'displayName': _auth_utils.validate_display_name(display_name), 'email': _auth_utils.validate_email(email), 'phoneNumber': _auth_utils.validate_phone(phone_number), 'photoUrl': _auth_utils.validate_photo_url(photo_url), 'password': _auth_utils.validate_password(password), 'emailVerified': bool(email_verified) if email_verified is not None else None, 'disabled': bool(disabled) if disabled is not None else None, } payload = {k: v for k, v in payload.items() if v is not None} try: body, http_resp = self._client.body_and_response('post', '/accounts', json=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not body or not body.get('localId'): raise _auth_utils.UnexpectedResponseError( 'Failed to create new user.', http_response=http_resp) return body.get('localId') def update_user(self, uid, display_name=None, email=None, phone_number=None, photo_url=None, password=<PASSWORD>, disabled=None, email_verified=None, valid_since=None, custom_claims=None): """Updates an existing user account with the specified properties""" payload = { 'localId': _auth_utils.validate_uid(uid, required=True), 'email': _auth_utils.validate_email(email), 'password': _auth_<PASSWORD>(password), 'validSince': _auth_utils.validate_timestamp(valid_since, 'valid_since'), 'emailVerified': bool(email_verified) if email_verified is not None else None, 'disableUser': bool(disabled) if disabled is not None else None, } remove = [] if display_name is not None: if display_name is DELETE_ATTRIBUTE: remove.append('DISPLAY_NAME') else: payload['displayName'] = _auth_utils.validate_display_name(display_name) if photo_url is not None: if photo_url is DELETE_ATTRIBUTE: remove.append('PHOTO_URL') else: payload['photoUrl'] = _auth_utils.validate_photo_url(photo_url) if remove: payload['deleteAttribute'] = remove if phone_number is not None: if phone_number is DELETE_ATTRIBUTE: payload['deleteProvider'] = ['phone'] else: payload['phoneNumber'] = _auth_utils.validate_phone(phone_number) if custom_claims is not None: if custom_claims is DELETE_ATTRIBUTE: custom_claims = {} json_claims = json.dumps(custom_claims) if isinstance( custom_claims, dict) else custom_claims payload['customAttributes'] = _auth_utils.validate_custom_claims(json_claims) payload = {k: v for k, v in payload.items() if v is not None} try: body, http_resp = self._client.body_and_response( 'post', '/accounts:update', json=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not body or not body.get('localId'): raise _auth_utils.UnexpectedResponseError( 'Failed to update user: {0}.'.format(uid), http_response=http_resp) return body.get('localId') def delete_user(self, uid): """Deletes the user identified by the specified user ID.""" _auth_utils.validate_uid(uid, required=True) try: body, http_resp = self._client.body_and_response( 'post', '/accounts:delete', json={'localId' : uid}) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not body or not body.get('kind'): raise _auth_utils.UnexpectedResponseError( 'Failed to delete user: {0}.'.format(uid), http_response=http_resp) def import_users(self, users, hash_alg=None): """Imports the given list of users to Firebase Auth.""" try: if not users or len(users) > MAX_IMPORT_USERS_SIZE: raise ValueError( 'Users must be a non-empty list with no more than {0} elements.'.format( MAX_IMPORT_USERS_SIZE)) if any([not isinstance(u, _user_import.ImportUserRecord) for u in users]): raise ValueError('One or more user objects are invalid.') except TypeError: raise ValueError('users must be iterable') payload = {'users': [u.to_dict() for u in users]} if any(['passwordHash' in u for u in payload['users']]): if not isinstance(hash_alg, _user_import.UserImportHash): raise ValueError('A UserImportHash is required to import users with passwords.') payload.update(hash_alg.to_dict()) try: body, http_resp = self._client.body_and_response( 'post', '/accounts:batchCreate', json=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not isinstance(body, dict): raise _auth_utils.UnexpectedResponseError( 'Failed to import users.', http_response=http_resp) return body def generate_email_action_link(self, action_type, email, action_code_settings=None): """Fetches the email action links for types Args: action_type: String. Valid values ['VERIFY_EMAIL', 'EMAIL_SIGNIN', 'PASSWORD_RESET'] email: Email of the user for which the action is performed action_code_settings: ``ActionCodeSettings`` object or dict (optional). Defines whether the link is to be handled by a mobile app and the additional state information to be passed in the deep link, etc. Returns: link_url: action url to be emailed to the user Raises: FirebaseError: If an error occurs while generating the link ValueError: If the provided arguments are invalid """ payload = { 'requestType': _auth_utils.validate_action_type(action_type), 'email': _auth_utils.validate_email(email), 'returnOobLink': True } if action_code_settings: payload.update(encode_action_code_settings(action_code_settings)) try: body, http_resp = self._client.body_and_response( 'post', '/accounts:sendOobCode', json=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not body or not body.get('oobLink'): raise _auth_utils.UnexpectedResponseError( 'Failed to generate email action link.', http_response=http_resp) return body.get('oobLink') class _UserIterator(object): """An iterator that allows iterating over user accounts, one at a time. This implementation loads a page of users into memory, and iterates on them. When the whole page has been traversed, it loads another page. This class never keeps more than one page of entries in memory. """ def __init__(self, current_page): if not current_page: raise ValueError('Current page must not be None.') self._current_page = current_page self._index = 0 def next(self): if self._index == len(self._current_page.users): if self._current_page.has_next_page: self._current_page = self._current_page.get_next_page() self._index = 0 if self._index < len(self._current_page.users): result = self._current_page.users[self._index] self._index += 1 return result raise StopIteration def __next__(self): return self.next() def __iter__(self): return self
venv/lib/python3.7/site-packages/firebase_admin/_user_mgt.py
import json import requests import six from six.moves import urllib from firebase_admin import _auth_utils from firebase_admin import _user_import MAX_LIST_USERS_RESULTS = 1000 MAX_IMPORT_USERS_SIZE = 1000 class Sentinel(object): def __init__(self, description): self.description = description DELETE_ATTRIBUTE = Sentinel('Value used to delete an attribute from a user profile') class UserMetadata(object): """Contains additional metadata associated with a user account.""" def __init__(self, creation_timestamp=None, last_sign_in_timestamp=None): self._creation_timestamp = _auth_utils.validate_timestamp( creation_timestamp, 'creation_timestamp') self._last_sign_in_timestamp = _auth_utils.validate_timestamp( last_sign_in_timestamp, 'last_sign_in_timestamp') @property def creation_timestamp(self): """ Creation timestamp in milliseconds since the epoch. Returns: integer: The user creation timestamp in milliseconds since the epoch. """ return self._creation_timestamp @property def last_sign_in_timestamp(self): """ Last sign in timestamp in milliseconds since the epoch. Returns: integer: The last sign in timestamp in milliseconds since the epoch. """ return self._last_sign_in_timestamp class UserInfo(object): """A collection of standard profile information for a user. Used to expose profile information returned by an identity provider. """ @property def uid(self): """Returns the user ID of this user.""" raise NotImplementedError @property def display_name(self): """Returns the display name of this user.""" raise NotImplementedError @property def email(self): """Returns the email address associated with this user.""" raise NotImplementedError @property def phone_number(self): """Returns the phone number associated with this user.""" raise NotImplementedError @property def photo_url(self): """Returns the photo URL of this user.""" raise NotImplementedError @property def provider_id(self): """Returns the ID of the identity provider. This can be a short domain name (e.g. google.com), or the identity of an OpenID identity provider. """ raise NotImplementedError class UserRecord(UserInfo): """Contains metadata associated with a Firebase user account.""" def __init__(self, data): super(UserRecord, self).__init__() if not isinstance(data, dict): raise ValueError('Invalid data argument: {0}. Must be a dictionary.'.format(data)) if not data.get('localId'): raise ValueError('User ID must not be None or empty.') self._data = data @property def uid(self): """Returns the user ID of this user. Returns: string: A user ID string. This value is never None or empty. """ return self._data.get('localId') @property def display_name(self): """Returns the display name of this user. Returns: string: A display name string or None. """ return self._data.get('displayName') @property def email(self): """Returns the email address associated with this user. Returns: string: An email address string or None. """ return self._data.get('email') @property def phone_number(self): """Returns the phone number associated with this user. Returns: string: A phone number string or None. """ return self._data.get('phoneNumber') @property def photo_url(self): """Returns the photo URL of this user. Returns: string: A URL string or None. """ return self._data.get('photoUrl') @property def provider_id(self): """Returns the provider ID of this user. Returns: string: A constant provider ID value. """ return 'firebase' @property def email_verified(self): """Returns whether the email address of this user has been verified. Returns: bool: True if the email has been verified, and False otherwise. """ return bool(self._data.get('emailVerified')) @property def disabled(self): """Returns whether this user account is disabled. Returns: bool: True if the user account is disabled, and False otherwise. """ return bool(self._data.get('disabled')) @property def tokens_valid_after_timestamp(self): """Returns the time, in milliseconds since the epoch, before which tokens are invalid. Note: this is truncated to 1 second accuracy. Returns: int: Timestamp in milliseconds since the epoch, truncated to the second. All tokens issued before that time are considered revoked. """ valid_since = self._data.get('validSince') if valid_since is not None: return 1000 * int(valid_since) return 0 @property def user_metadata(self): """Returns additional metadata associated with this user. Returns: UserMetadata: A UserMetadata instance. Does not return None. """ def _int_or_none(key): if key in self._data: return int(self._data[key]) return None return UserMetadata(_int_or_none('createdAt'), _int_or_none('lastLoginAt')) @property def provider_data(self): """Returns a list of UserInfo instances. Each object represents an identity from an identity provider that is linked to this user. Returns: list: A list of UserInfo objects, which may be empty. """ providers = self._data.get('providerUserInfo', []) return [ProviderUserInfo(entry) for entry in providers] @property def custom_claims(self): """Returns any custom claims set on this user account. Returns: dict: A dictionary of claims or None. """ claims = self._data.get('customAttributes') if claims: parsed = json.loads(claims) if parsed != {}: return parsed return None class ExportedUserRecord(UserRecord): """Contains metadata associated with a user including password hash and salt.""" def __init__(self, data): super(ExportedUserRecord, self).__init__(data) @property def password_hash(self): """The user's password hash as a base64-encoded string. If the Firebase Auth hashing algorithm (SCRYPT) was used to create the user account, this is the base64-encoded password hash of the user. If a different hashing algorithm was used to create this user, as is typical when migrating from another Auth system, this is an empty string. If no password is set, this is ``None``. """ return self._data.get('passwordHash') @property def password_salt(self): """The user's password salt as a base64-encoded string. If the Firebase Auth hashing algorithm (SCRYPT) was used to create the user account, this is the base64-encoded password salt of the user. If a different hashing algorithm was used to create this user, as is typical when migrating from another Auth system, this is an empty string. If no password is set, this is ``None``. """ return self._data.get('salt') class ListUsersPage(object): """Represents a page of user records exported from a Firebase project. Provides methods for traversing the user accounts included in this page, as well as retrieving subsequent pages of users. The iterator returned by ``iterate_all()`` can be used to iterate through all users in the Firebase project starting from this page. """ def __init__(self, download, page_token, max_results): self._download = download self._max_results = max_results self._current = download(page_token, max_results) @property def users(self): """A list of ``ExportedUserRecord`` instances available in this page.""" return [ExportedUserRecord(user) for user in self._current.get('users', [])] @property def next_page_token(self): """Page token string for the next page (empty string indicates no more pages).""" return self._current.get('nextPageToken', '') @property def has_next_page(self): """A boolean indicating whether more pages are available.""" return bool(self.next_page_token) def get_next_page(self): """Retrieves the next page of user accounts, if available. Returns: ListUsersPage: Next page of users, or None if this is the last page. """ if self.has_next_page: return ListUsersPage(self._download, self.next_page_token, self._max_results) return None def iterate_all(self): """Retrieves an iterator for user accounts. Returned iterator will iterate through all the user accounts in the Firebase project starting from this page. The iterator will never buffer more than one page of users in memory at a time. Returns: iterator: An iterator of ExportedUserRecord instances. """ return _UserIterator(self) class ProviderUserInfo(UserInfo): """Contains metadata regarding how a user is known by a particular identity provider.""" def __init__(self, data): super(ProviderUserInfo, self).__init__() if not isinstance(data, dict): raise ValueError('Invalid data argument: {0}. Must be a dictionary.'.format(data)) if not data.get('rawId'): raise ValueError('User ID must not be None or empty.') self._data = data @property def uid(self): return self._data.get('rawId') @property def display_name(self): return self._data.get('displayName') @property def email(self): return self._data.get('email') @property def phone_number(self): return self._data.get('phoneNumber') @property def photo_url(self): return self._data.get('photoUrl') @property def provider_id(self): return self._data.get('providerId') class ActionCodeSettings(object): """Contains required continue/state URL with optional Android and iOS settings. Used when invoking the email action link generation APIs. """ def __init__(self, url, handle_code_in_app=None, dynamic_link_domain=None, ios_bundle_id=None, android_package_name=None, android_install_app=None, android_minimum_version=None): self.url = url self.handle_code_in_app = handle_code_in_app self.dynamic_link_domain = dynamic_link_domain self.ios_bundle_id = ios_bundle_id self.android_package_name = android_package_name self.android_install_app = android_install_app self.android_minimum_version = android_minimum_version def encode_action_code_settings(settings): """ Validates the provided action code settings for email link generation and populates the REST api parameters. settings - ``ActionCodeSettings`` object provided to be encoded returns - dict of parameters to be passed for link gereration. """ parameters = {} # url if not settings.url: raise ValueError("Dynamic action links url is mandatory") try: parsed = urllib.parse.urlparse(settings.url) if not parsed.netloc: raise ValueError('Malformed dynamic action links url: "{0}".'.format(settings.url)) parameters['continueUrl'] = settings.url except Exception: raise ValueError('Malformed dynamic action links url: "{0}".'.format(settings.url)) # handle_code_in_app if settings.handle_code_in_app is not None: if not isinstance(settings.handle_code_in_app, bool): raise ValueError('Invalid value provided for handle_code_in_app: {0}' .format(settings.handle_code_in_app)) parameters['canHandleCodeInApp'] = settings.handle_code_in_app # dynamic_link_domain if settings.dynamic_link_domain is not None: if not isinstance(settings.dynamic_link_domain, six.string_types): raise ValueError('Invalid value provided for dynamic_link_domain: {0}' .format(settings.dynamic_link_domain)) parameters['dynamicLinkDomain'] = settings.dynamic_link_domain # ios_bundle_id if settings.ios_bundle_id is not None: if not isinstance(settings.ios_bundle_id, six.string_types): raise ValueError('Invalid value provided for ios_bundle_id: {0}' .format(settings.ios_bundle_id)) parameters['iosBundleId'] = settings.ios_bundle_id # android_* attributes if (settings.android_minimum_version or settings.android_install_app) \ and not settings.android_package_name: raise ValueError("Android package name is required when specifying other Android settings") if settings.android_package_name is not None: if not isinstance(settings.android_package_name, six.string_types): raise ValueError('Invalid value provided for android_package_name: {0}' .format(settings.android_package_name)) parameters['androidPackageName'] = settings.android_package_name if settings.android_minimum_version is not None: if not isinstance(settings.android_minimum_version, six.string_types): raise ValueError('Invalid value provided for android_minimum_version: {0}' .format(settings.android_minimum_version)) parameters['androidMinimumVersion'] = settings.android_minimum_version if settings.android_install_app is not None: if not isinstance(settings.android_install_app, bool): raise ValueError('Invalid value provided for android_install_app: {0}' .format(settings.android_install_app)) parameters['androidInstallApp'] = settings.android_install_app return parameters class UserManager(object): """Provides methods for interacting with the Google Identity Toolkit.""" def __init__(self, client): self._client = client def get_user(self, **kwargs): """Gets the user data corresponding to the provided key.""" if 'uid' in kwargs: key, key_type = kwargs.pop('uid'), 'user ID' payload = {'localId' : [_auth_utils.validate_uid(key, required=True)]} elif 'email' in kwargs: key, key_type = kwargs.pop('email'), 'email' payload = {'email' : [_auth_utils.validate_email(key, required=True)]} elif 'phone_number' in kwargs: key, key_type = kwargs.pop('phone_number'), 'phone number' payload = {'phoneNumber' : [_auth_utils.validate_phone(key, required=True)]} else: raise TypeError('Unsupported keyword arguments: {0}.'.format(kwargs)) try: body, http_resp = self._client.body_and_response( 'post', '/accounts:lookup', json=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not body or not body.get('users'): raise _auth_utils.UserNotFoundError( 'No user record found for the provided {0}: {1}.'.format(key_type, key), http_response=http_resp) return body['users'][0] def list_users(self, page_token=None, max_results=MAX_LIST_USERS_RESULTS): """Retrieves a batch of users.""" if page_token is not None: if not isinstance(page_token, six.string_types) or not page_token: raise ValueError('Page token must be a non-empty string.') if not isinstance(max_results, int): raise ValueError('Max results must be an integer.') elif max_results < 1 or max_results > MAX_LIST_USERS_RESULTS: raise ValueError( 'Max results must be a positive integer less than ' '{0}.'.format(MAX_LIST_USERS_RESULTS)) payload = {'maxResults': max_results} if page_token: payload['nextPageToken'] = page_token try: return self._client.body('get', '/accounts:batchGet', params=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) def create_user(self, uid=None, display_name=None, email=None, phone_number=None, photo_url=None, password=<PASSWORD>, disabled=None, email_verified=None): """Creates a new user account with the specified properties.""" payload = { 'localId': _auth_utils.validate_uid(uid), 'displayName': _auth_utils.validate_display_name(display_name), 'email': _auth_utils.validate_email(email), 'phoneNumber': _auth_utils.validate_phone(phone_number), 'photoUrl': _auth_utils.validate_photo_url(photo_url), 'password': _auth_utils.validate_password(password), 'emailVerified': bool(email_verified) if email_verified is not None else None, 'disabled': bool(disabled) if disabled is not None else None, } payload = {k: v for k, v in payload.items() if v is not None} try: body, http_resp = self._client.body_and_response('post', '/accounts', json=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not body or not body.get('localId'): raise _auth_utils.UnexpectedResponseError( 'Failed to create new user.', http_response=http_resp) return body.get('localId') def update_user(self, uid, display_name=None, email=None, phone_number=None, photo_url=None, password=<PASSWORD>, disabled=None, email_verified=None, valid_since=None, custom_claims=None): """Updates an existing user account with the specified properties""" payload = { 'localId': _auth_utils.validate_uid(uid, required=True), 'email': _auth_utils.validate_email(email), 'password': _auth_<PASSWORD>(password), 'validSince': _auth_utils.validate_timestamp(valid_since, 'valid_since'), 'emailVerified': bool(email_verified) if email_verified is not None else None, 'disableUser': bool(disabled) if disabled is not None else None, } remove = [] if display_name is not None: if display_name is DELETE_ATTRIBUTE: remove.append('DISPLAY_NAME') else: payload['displayName'] = _auth_utils.validate_display_name(display_name) if photo_url is not None: if photo_url is DELETE_ATTRIBUTE: remove.append('PHOTO_URL') else: payload['photoUrl'] = _auth_utils.validate_photo_url(photo_url) if remove: payload['deleteAttribute'] = remove if phone_number is not None: if phone_number is DELETE_ATTRIBUTE: payload['deleteProvider'] = ['phone'] else: payload['phoneNumber'] = _auth_utils.validate_phone(phone_number) if custom_claims is not None: if custom_claims is DELETE_ATTRIBUTE: custom_claims = {} json_claims = json.dumps(custom_claims) if isinstance( custom_claims, dict) else custom_claims payload['customAttributes'] = _auth_utils.validate_custom_claims(json_claims) payload = {k: v for k, v in payload.items() if v is not None} try: body, http_resp = self._client.body_and_response( 'post', '/accounts:update', json=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not body or not body.get('localId'): raise _auth_utils.UnexpectedResponseError( 'Failed to update user: {0}.'.format(uid), http_response=http_resp) return body.get('localId') def delete_user(self, uid): """Deletes the user identified by the specified user ID.""" _auth_utils.validate_uid(uid, required=True) try: body, http_resp = self._client.body_and_response( 'post', '/accounts:delete', json={'localId' : uid}) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not body or not body.get('kind'): raise _auth_utils.UnexpectedResponseError( 'Failed to delete user: {0}.'.format(uid), http_response=http_resp) def import_users(self, users, hash_alg=None): """Imports the given list of users to Firebase Auth.""" try: if not users or len(users) > MAX_IMPORT_USERS_SIZE: raise ValueError( 'Users must be a non-empty list with no more than {0} elements.'.format( MAX_IMPORT_USERS_SIZE)) if any([not isinstance(u, _user_import.ImportUserRecord) for u in users]): raise ValueError('One or more user objects are invalid.') except TypeError: raise ValueError('users must be iterable') payload = {'users': [u.to_dict() for u in users]} if any(['passwordHash' in u for u in payload['users']]): if not isinstance(hash_alg, _user_import.UserImportHash): raise ValueError('A UserImportHash is required to import users with passwords.') payload.update(hash_alg.to_dict()) try: body, http_resp = self._client.body_and_response( 'post', '/accounts:batchCreate', json=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not isinstance(body, dict): raise _auth_utils.UnexpectedResponseError( 'Failed to import users.', http_response=http_resp) return body def generate_email_action_link(self, action_type, email, action_code_settings=None): """Fetches the email action links for types Args: action_type: String. Valid values ['VERIFY_EMAIL', 'EMAIL_SIGNIN', 'PASSWORD_RESET'] email: Email of the user for which the action is performed action_code_settings: ``ActionCodeSettings`` object or dict (optional). Defines whether the link is to be handled by a mobile app and the additional state information to be passed in the deep link, etc. Returns: link_url: action url to be emailed to the user Raises: FirebaseError: If an error occurs while generating the link ValueError: If the provided arguments are invalid """ payload = { 'requestType': _auth_utils.validate_action_type(action_type), 'email': _auth_utils.validate_email(email), 'returnOobLink': True } if action_code_settings: payload.update(encode_action_code_settings(action_code_settings)) try: body, http_resp = self._client.body_and_response( 'post', '/accounts:sendOobCode', json=payload) except requests.exceptions.RequestException as error: raise _auth_utils.handle_auth_backend_error(error) else: if not body or not body.get('oobLink'): raise _auth_utils.UnexpectedResponseError( 'Failed to generate email action link.', http_response=http_resp) return body.get('oobLink') class _UserIterator(object): """An iterator that allows iterating over user accounts, one at a time. This implementation loads a page of users into memory, and iterates on them. When the whole page has been traversed, it loads another page. This class never keeps more than one page of entries in memory. """ def __init__(self, current_page): if not current_page: raise ValueError('Current page must not be None.') self._current_page = current_page self._index = 0 def next(self): if self._index == len(self._current_page.users): if self._current_page.has_next_page: self._current_page = self._current_page.get_next_page() self._index = 0 if self._index < len(self._current_page.users): result = self._current_page.users[self._index] self._index += 1 return result raise StopIteration def __next__(self): return self.next() def __iter__(self): return self
0.849691
0.251269
r"""YAML backend: - Format to support: YAML, http://yaml.org - Requirements: PyYAML (yaml), http://pyyaml.org - Development Status :: 5 - Production/Stable - Limitations: ac_ordered is not effective and just ignored. - Special options: - All keyword options of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump should work. - Use 'ac_safe' boolean keyword option if you prefer to call yaml.safe_load and yaml.safe_dump instead of yaml.load and yaml.dump - See also: http://pyyaml.org/wiki/PyYAMLDocumentation Changelog: .. versionchanged:: 0.3 - Changed special keyword option 'ac_safe' from 'safe' to avoid possibility of option conflicts in the future. """ from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as Loader, CSafeDumper as Dumper except ImportError: from yaml import SafeLoader as Loader, SafeDumper as Dumper import anyconfig.backend.base import anyconfig.utils def _setup_loader_and_dumper(container, loader=Loader, dumper=Dumper): """ Force set container (dict, OrderedDict, ...) used to construct python object from yaml node internally. .. note:: It cannot be used with ac_safe keyword option at the same time yet. :param container: Set container used internally """ map_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG def construct_mapping(loader, node, deep=False): """Constructor to construct python object from yaml mapping node. :seealso: :meth:`yaml.BaseConstructor.construct_mapping` """ if not isinstance(node, yaml.MappingNode): msg = "expected a mapping node, but found %s" % node.id raise yaml.constructor.ConstructorError(None, None, msg, node.start_mark) mapping = container() for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: eargs = ("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) raise yaml.constructor.ConstructorError(*eargs) value = loader.construct_object(value_node, deep=deep) mapping[key] = value return mapping def container_representer(dumper, data): """Container representer. """ return dumper.represent_mapping(map_tag, data.items()) loader.add_constructor(map_tag, construct_mapping) dumper.add_representer(container, container_representer) def _yml_fnc(fname, *args, **kwargs): """An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump. :param fname: "load" or "dump", not checked but it should be OK. see also :func:`_yml_load` and :func:`_yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param kwargs: keyword args may contain "ac_safe" to load/dump safely """ key = "ac_safe" fnc = getattr(yaml, kwargs.get(key, False) and r"safe_" + fname or fname) kwargs = anyconfig.utils.filter_options([k for k in kwargs.keys() if k != key], kwargs) return fnc(*args, **kwargs) def _yml_load(stream, container, **kwargs): """An wrapper of yaml.safe_load and yaml.load. :param stream: a file or file-like object to load YAML content :param container: callble to make a container object """ if "ac_safe" in kwargs: # yaml.safe_load does not process Loader opts. kwargs = {} else: maybe_container = kwargs.get("ac_dict", None) loader = kwargs.get("Loader", Loader) dumper = kwargs.get("Dumper", Dumper) if maybe_container is not None and callable(maybe_container): _setup_loader_and_dumper(maybe_container, loader=loader, dumper=dumper) container = maybe_container return container(_yml_fnc("load", stream, **kwargs)) def _yml_dump(cnf, stream, **kwargs): """An wrapper of yaml.safe_dump and yaml.dump. :param cnf: Mapping object to dump :param stream: a file or file-like object to dump YAML data """ if kwargs.get("ac_safe", False): cnf = anyconfig.dicts.convert_to(cnf) return _yml_fnc("dump", cnf, stream, **kwargs) class Parser(anyconfig.backend.base.FromStreamLoader, anyconfig.backend.base.ToStreamDumper): """ Parser for YAML files. """ _type = "yaml" _extensions = ["yaml", "yml"] _load_opts = ["Loader", "ac_safe"] _dump_opts = ["stream", "ac_safe", "Dumper", "default_style", "default_flow_style", "canonical", "indent", "width", "allow_unicode", "line_break", "encoding", "explicit_start", "explicit_end", "version", "tags"] # _ordered = True # Not yet. load_from_stream = anyconfig.backend.base.to_method(_yml_load) dump_to_stream = anyconfig.backend.base.to_method(_yml_dump) # vim:sw=4:ts=4:et:
anyconfig/backend/yaml.py
r"""YAML backend: - Format to support: YAML, http://yaml.org - Requirements: PyYAML (yaml), http://pyyaml.org - Development Status :: 5 - Production/Stable - Limitations: ac_ordered is not effective and just ignored. - Special options: - All keyword options of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump should work. - Use 'ac_safe' boolean keyword option if you prefer to call yaml.safe_load and yaml.safe_dump instead of yaml.load and yaml.dump - See also: http://pyyaml.org/wiki/PyYAMLDocumentation Changelog: .. versionchanged:: 0.3 - Changed special keyword option 'ac_safe' from 'safe' to avoid possibility of option conflicts in the future. """ from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as Loader, CSafeDumper as Dumper except ImportError: from yaml import SafeLoader as Loader, SafeDumper as Dumper import anyconfig.backend.base import anyconfig.utils def _setup_loader_and_dumper(container, loader=Loader, dumper=Dumper): """ Force set container (dict, OrderedDict, ...) used to construct python object from yaml node internally. .. note:: It cannot be used with ac_safe keyword option at the same time yet. :param container: Set container used internally """ map_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG def construct_mapping(loader, node, deep=False): """Constructor to construct python object from yaml mapping node. :seealso: :meth:`yaml.BaseConstructor.construct_mapping` """ if not isinstance(node, yaml.MappingNode): msg = "expected a mapping node, but found %s" % node.id raise yaml.constructor.ConstructorError(None, None, msg, node.start_mark) mapping = container() for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: eargs = ("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) raise yaml.constructor.ConstructorError(*eargs) value = loader.construct_object(value_node, deep=deep) mapping[key] = value return mapping def container_representer(dumper, data): """Container representer. """ return dumper.represent_mapping(map_tag, data.items()) loader.add_constructor(map_tag, construct_mapping) dumper.add_representer(container, container_representer) def _yml_fnc(fname, *args, **kwargs): """An wrapper of yaml.safe_load, yaml.load, yaml.safe_dump and yaml.dump. :param fname: "load" or "dump", not checked but it should be OK. see also :func:`_yml_load` and :func:`_yml_dump` :param args: [stream] for load or [cnf, stream] for dump :param kwargs: keyword args may contain "ac_safe" to load/dump safely """ key = "ac_safe" fnc = getattr(yaml, kwargs.get(key, False) and r"safe_" + fname or fname) kwargs = anyconfig.utils.filter_options([k for k in kwargs.keys() if k != key], kwargs) return fnc(*args, **kwargs) def _yml_load(stream, container, **kwargs): """An wrapper of yaml.safe_load and yaml.load. :param stream: a file or file-like object to load YAML content :param container: callble to make a container object """ if "ac_safe" in kwargs: # yaml.safe_load does not process Loader opts. kwargs = {} else: maybe_container = kwargs.get("ac_dict", None) loader = kwargs.get("Loader", Loader) dumper = kwargs.get("Dumper", Dumper) if maybe_container is not None and callable(maybe_container): _setup_loader_and_dumper(maybe_container, loader=loader, dumper=dumper) container = maybe_container return container(_yml_fnc("load", stream, **kwargs)) def _yml_dump(cnf, stream, **kwargs): """An wrapper of yaml.safe_dump and yaml.dump. :param cnf: Mapping object to dump :param stream: a file or file-like object to dump YAML data """ if kwargs.get("ac_safe", False): cnf = anyconfig.dicts.convert_to(cnf) return _yml_fnc("dump", cnf, stream, **kwargs) class Parser(anyconfig.backend.base.FromStreamLoader, anyconfig.backend.base.ToStreamDumper): """ Parser for YAML files. """ _type = "yaml" _extensions = ["yaml", "yml"] _load_opts = ["Loader", "ac_safe"] _dump_opts = ["stream", "ac_safe", "Dumper", "default_style", "default_flow_style", "canonical", "indent", "width", "allow_unicode", "line_break", "encoding", "explicit_start", "explicit_end", "version", "tags"] # _ordered = True # Not yet. load_from_stream = anyconfig.backend.base.to_method(_yml_load) dump_to_stream = anyconfig.backend.base.to_method(_yml_dump) # vim:sw=4:ts=4:et:
0.810854
0.243929
from __future__ import unicode_literals from .. import util import soupsieve as sv from soupsieve import SelectorSyntaxError class TestNthChild(util.TestCase): """Test `nth` child selectors.""" def test_nth_child(self): """Test `nth` child.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-child(-2)", [], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(2)", ['1'], flags=util.HTML ) def test_nth_child_odd(self): """Test `nth` child odd.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-child(odd)", ['0', '8', '10'], flags=util.HTML ) def test_nth_child_even(self): """Test `nth` child even.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-child(even)", ['1', '7', '9'], flags=util.HTML ) def test_nth_child_complex(self): """Test `nth` child complex.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-child(2n-5)", ['0', '8', '10'], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(-2n+20)", ['1', '7', '9'], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(50n-20)", [], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(-2n-2)", [], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(9n - 1)", ['7'], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(2n + 1)", ['0', '8', '10'], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(-n+3)", ['0', '1'], flags=util.HTML ) self.assert_selector( markup, "span:nth-child(-n+3)", ['2'], flags=util.HTML ) self.assert_selector( markup, "body *:nth-child(-n+3)", ['0', '1', '2'], flags=util.HTML ) def test_nth_child_no_parent(self): """Test `nth` child with no parent.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ for parser in util.available_parsers('html.parser', 'lxml', 'html5lib'): # Paragraph is the root. There is no document. markup = """<p id="1">text</p>""" soup = self.soup(markup, parser) fragment = soup.p.extract() self.assertTrue(sv.match("p:nth-child(1)", fragment, flags=sv.DEBUG)) def test_nth_child_with_bad_parameters(self): """Test that pseudo class fails with bad parameters (basically it doesn't match).""" self.assert_raises(':nth-child(a)', SelectorSyntaxError) class TestNthChildQuirks(TestNthChild): """Test `nth` child selectors with quirks.""" def setUp(self): """Setup.""" self.purge() self.quirks = True
venv/lib/python3.6/site-packages/tests/test_level3/test_nth_child.py
from __future__ import unicode_literals from .. import util import soupsieve as sv from soupsieve import SelectorSyntaxError class TestNthChild(util.TestCase): """Test `nth` child selectors.""" def test_nth_child(self): """Test `nth` child.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-child(-2)", [], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(2)", ['1'], flags=util.HTML ) def test_nth_child_odd(self): """Test `nth` child odd.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-child(odd)", ['0', '8', '10'], flags=util.HTML ) def test_nth_child_even(self): """Test `nth` child even.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-child(even)", ['1', '7', '9'], flags=util.HTML ) def test_nth_child_complex(self): """Test `nth` child complex.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:nth-child(2n-5)", ['0', '8', '10'], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(-2n+20)", ['1', '7', '9'], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(50n-20)", [], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(-2n-2)", [], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(9n - 1)", ['7'], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(2n + 1)", ['0', '8', '10'], flags=util.HTML ) self.assert_selector( markup, "p:nth-child(-n+3)", ['0', '1'], flags=util.HTML ) self.assert_selector( markup, "span:nth-child(-n+3)", ['2'], flags=util.HTML ) self.assert_selector( markup, "body *:nth-child(-n+3)", ['0', '1', '2'], flags=util.HTML ) def test_nth_child_no_parent(self): """Test `nth` child with no parent.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ for parser in util.available_parsers('html.parser', 'lxml', 'html5lib'): # Paragraph is the root. There is no document. markup = """<p id="1">text</p>""" soup = self.soup(markup, parser) fragment = soup.p.extract() self.assertTrue(sv.match("p:nth-child(1)", fragment, flags=sv.DEBUG)) def test_nth_child_with_bad_parameters(self): """Test that pseudo class fails with bad parameters (basically it doesn't match).""" self.assert_raises(':nth-child(a)', SelectorSyntaxError) class TestNthChildQuirks(TestNthChild): """Test `nth` child selectors with quirks.""" def setUp(self): """Setup.""" self.purge() self.quirks = True
0.822153
0.430447
from __future__ import print_function from __future__ import unicode_literals import numpy as np import matplotlib.pyplot as plt from .utils import Utils class StructureFunction: """ This class provides methods for computing and analyzing struture functions Args: mrq (MultiResolutionQuantity): multiresolution quantity used to compute the structure function q (numpy.array) : list of exponents for which to compute the structure function j1 (int) : smallest scale analysis j2 (int) : largest scale analysis wtype (int) : 0 for ordinary regression, 1 for weighted regression values (numpy.array) : values[ind_q, ind_j] = values of S(j, q), with q = self.q[ind_q] and j = self.j[ind_j] logvalues (numpy.array) : logvalues[ind_q, ind_j] = values of log_2 (S(j, q)), with q = self.q[ind_q] and j = self.j[ind_j] """ def __init__(self, mrq, q, j1, j2, wtype): self.mrq = mrq self.q = q self.j1 = j1 self.j2 = j2 self.j = np.array(list(mrq.values)) self.wtype = wtype self.values = np.zeros( (len(self.q), len(self.j)) ) self.logvalues = np.zeros( (len(self.q), len(self.j)) ) self.zeta = [] self.utils = Utils() # used for linear regression self._compute() self._compute_zeta() def _compute(self): for ind_q, q in enumerate(self.q): for ind_j, j in enumerate(self.j): c_j = self.mrq.values[j] s_j_q = np.mean(np.abs(c_j)**q) self.values[ind_q, ind_j] = s_j_q self.logvalues = np.log2(self.values) def _compute_zeta(self): """ Compute the value of the scale function zeta(q) for all q """ self.zeta = np.zeros(len(self.q)) self.intercept = np.zeros(len(self.q)) x = np.arange(self.j1, self.j2+1) if self.wtype == 1: nj = self.mrq.get_nj_interv(self.j1, self.j2) else: nj = np.ones(len(x)) ind_j1 = self.j1-1 ind_j2 = self.j2-1 for ind_q, q in enumerate(self.q): y = self.logvalues[ind_q,ind_j1:ind_j2+1] slope, intercept = self.utils.linear_regression(x, y, nj) self.zeta[ind_q] = slope self.intercept[ind_q] = intercept def plot(self, figlabel_structure = None, figlabel_scaling = None): """ Plots the structure functions. Args: fignum(int): figure number; NOTE: fignum+1 can also be used to plot the scaling function """ if figlabel_structure is None: figlabel_structure = 'Structure Functions' if figlabel_scaling is None: figlabel_scaling = 'Scaling Function' if len(self.q) > 1: plot_dim_1 = 4 plot_dim_2 = int(np.ceil(len(self.q) / 4.0)) else: plot_dim_1 = 1 plot_dim_2 = 1 fig, axes = plt.subplots(plot_dim_1, plot_dim_2, num = figlabel_structure, squeeze = False) fig.suptitle(self.mrq.name + ' - structure functions log_2[S(j,q)]') x = self.j for ind_q, q in enumerate(self.q): y = self.logvalues[ind_q, :] ax = axes[ind_q % 4][ind_q // 4] ax.plot(x, y, 'r--.') ax.set_xlabel('j') ax.set_ylabel('q = ' + str(q)) ax.grid() plt.draw() if len(self.zeta) > 0: # plot regression line x0 = self.j1 x1 = self.j2 slope = self.zeta[ind_q] intercept = self.intercept[ind_q] y0 = slope*x0 + intercept y1 = slope*x1 + intercept legend = 'slope = '+'%.5f' % (slope) ax.plot([x0, x1], [y0, y1], color='k', linestyle='-', linewidth=2, label = legend) ax.legend() if len(self.q) > 1: plt.figure(figlabel_scaling) plt.plot(self.q, self.zeta, 'k--.') plt.xlabel('q') plt.ylabel('zeta(q)') plt.suptitle(self.mrq.name + ' - scaling function') plt.grid() plt.draw()
mfanalysis/structurefunction.py
from __future__ import print_function from __future__ import unicode_literals import numpy as np import matplotlib.pyplot as plt from .utils import Utils class StructureFunction: """ This class provides methods for computing and analyzing struture functions Args: mrq (MultiResolutionQuantity): multiresolution quantity used to compute the structure function q (numpy.array) : list of exponents for which to compute the structure function j1 (int) : smallest scale analysis j2 (int) : largest scale analysis wtype (int) : 0 for ordinary regression, 1 for weighted regression values (numpy.array) : values[ind_q, ind_j] = values of S(j, q), with q = self.q[ind_q] and j = self.j[ind_j] logvalues (numpy.array) : logvalues[ind_q, ind_j] = values of log_2 (S(j, q)), with q = self.q[ind_q] and j = self.j[ind_j] """ def __init__(self, mrq, q, j1, j2, wtype): self.mrq = mrq self.q = q self.j1 = j1 self.j2 = j2 self.j = np.array(list(mrq.values)) self.wtype = wtype self.values = np.zeros( (len(self.q), len(self.j)) ) self.logvalues = np.zeros( (len(self.q), len(self.j)) ) self.zeta = [] self.utils = Utils() # used for linear regression self._compute() self._compute_zeta() def _compute(self): for ind_q, q in enumerate(self.q): for ind_j, j in enumerate(self.j): c_j = self.mrq.values[j] s_j_q = np.mean(np.abs(c_j)**q) self.values[ind_q, ind_j] = s_j_q self.logvalues = np.log2(self.values) def _compute_zeta(self): """ Compute the value of the scale function zeta(q) for all q """ self.zeta = np.zeros(len(self.q)) self.intercept = np.zeros(len(self.q)) x = np.arange(self.j1, self.j2+1) if self.wtype == 1: nj = self.mrq.get_nj_interv(self.j1, self.j2) else: nj = np.ones(len(x)) ind_j1 = self.j1-1 ind_j2 = self.j2-1 for ind_q, q in enumerate(self.q): y = self.logvalues[ind_q,ind_j1:ind_j2+1] slope, intercept = self.utils.linear_regression(x, y, nj) self.zeta[ind_q] = slope self.intercept[ind_q] = intercept def plot(self, figlabel_structure = None, figlabel_scaling = None): """ Plots the structure functions. Args: fignum(int): figure number; NOTE: fignum+1 can also be used to plot the scaling function """ if figlabel_structure is None: figlabel_structure = 'Structure Functions' if figlabel_scaling is None: figlabel_scaling = 'Scaling Function' if len(self.q) > 1: plot_dim_1 = 4 plot_dim_2 = int(np.ceil(len(self.q) / 4.0)) else: plot_dim_1 = 1 plot_dim_2 = 1 fig, axes = plt.subplots(plot_dim_1, plot_dim_2, num = figlabel_structure, squeeze = False) fig.suptitle(self.mrq.name + ' - structure functions log_2[S(j,q)]') x = self.j for ind_q, q in enumerate(self.q): y = self.logvalues[ind_q, :] ax = axes[ind_q % 4][ind_q // 4] ax.plot(x, y, 'r--.') ax.set_xlabel('j') ax.set_ylabel('q = ' + str(q)) ax.grid() plt.draw() if len(self.zeta) > 0: # plot regression line x0 = self.j1 x1 = self.j2 slope = self.zeta[ind_q] intercept = self.intercept[ind_q] y0 = slope*x0 + intercept y1 = slope*x1 + intercept legend = 'slope = '+'%.5f' % (slope) ax.plot([x0, x1], [y0, y1], color='k', linestyle='-', linewidth=2, label = legend) ax.legend() if len(self.q) > 1: plt.figure(figlabel_scaling) plt.plot(self.q, self.zeta, 'k--.') plt.xlabel('q') plt.ylabel('zeta(q)') plt.suptitle(self.mrq.name + ' - scaling function') plt.grid() plt.draw()
0.773858
0.614799
import binascii import codecs import hashlib import struct import abc import dataclasses from typing import Dict, Callable, Any, Optional from keylime import config from keylime import keylime_logging from keylime.failure import Failure, Component logger = keylime_logging.init_logging("ima") TCG_EVENT_NAME_LEN_MAX = 255 SHA_DIGEST_LEN = 20 MD5_DIGEST_LEN = 16 START_HASH = (codecs.decode(b'0000000000000000000000000000000000000000', 'hex')) FF_HASH = (codecs.decode(b'ffffffffffffffffffffffffffffffffffffffff', 'hex')) NULL_BYTE = ord('\0') COLON_BYTE = ord(':') @dataclasses.dataclass class Validator: functions: Dict[Any, Callable] def get_validator(self, class_type) -> Callable: validator = self.functions.get(class_type, None) if validator is None: logger.warning(f"No validator was implemented for: {class_type} . Using always false validator!") failure = Failure(Component.IMA, ["validation"]) failure.add_event("no_validator", f"No validator was implemented for: {class_type} . Using always false validator!", True) return lambda *_: failure return validator class ParserError(TypeError): """Is thrown when a type could not be constructed successfully.""" class Mode(abc.ABC): @abc.abstractmethod def is_data_valid(self, validator: Validator): pass @abc.abstractmethod def hash(self) -> bytes: pass class Type(abc.ABC): @abc.abstractmethod def struct(self): pass class HexData(Type): data: bytes def __init__(self, data: str): try: self.data = codecs.decode(data.encode("utf-8"), "hex") except binascii.Error as e: raise ParserError(f"Provided data was not valid hex: {data}") from e def __str__(self): return self.data.decode("utf-8") def struct(self): return struct.pack(f"<I{len(self.data)}s", len(self.data), self.data) class Signature(HexData): """ Class for type "sig". """ def __init__(self, data: str): super().__init__(data) # basic checks on signature fmt = '>BBBIH' hdrlen = struct.calcsize(fmt) if len(self.data) < hdrlen: raise ParserError("Invalid signature: header too short") _, _, _, _, sig_size = struct.unpack(fmt, self.data[:hdrlen]) if hdrlen + sig_size != len(self.data): raise ParserError("Invalid signature: malformed header") class Buffer(HexData): """ Class for type "buf". """ class Name(Type): """ Class for type "n" and "n-ng". """ name: str legacy: bool = False def __init__(self, name: str, legacy=False): self.name = name self.legacy = legacy def __str__(self): return self.name def struct(self): # The old "n" option is fixed length. if self.legacy: return struct.pack(f"{len(self.name)}sB{TCG_EVENT_NAME_LEN_MAX - len(self.name)}s", self.name.encode("utf-8"), NULL_BYTE, bytearray(TCG_EVENT_NAME_LEN_MAX - len(self.name))) return struct.pack(f"<I{len(self.name)}sB", len(self.name) + 1, self.name.encode("utf-8"), NULL_BYTE) class Digest: """ Class for types "d" and "d-ng" with and without algorithm """ hash: bytes algorithm: Optional[str] = None legacy: bool = False def __init__(self, digest: str, legacy=False): self.legacy = legacy tokens = digest.split(":") if len(tokens) == 1: try: self.hash = codecs.decode(tokens[0].encode("utf-8"), "hex") except binascii.Error as e: raise ParserError(f"Digest hash is not valid hex. Got: {tokens[0]}") from e if not (len(self.hash) == SHA_DIGEST_LEN or len(self.hash) == MD5_DIGEST_LEN): raise ParserError( "Cannot create Digest. No hash algorithm is provided and hash does not belong to a md5 or sha1 hash.") elif len(tokens) == 2: try: self.hash = codecs.decode(tokens[1].encode("utf-8"), "hex") except binascii.Error as e: raise ParserError(f"Digest hash is not valid hex. Got: {tokens[1]}") from e self.algorithm = tokens[0] else: raise ParserError(f"Cannot create Digest expected 1 or 2 tokens got: {len(tokens)} for {digest}") def struct(self): # The legacy format "d" has fixed length, so it does not contain a length attribute if self.legacy: return struct.pack(f"<{len(self.hash)}s", self.hash) if self.algorithm is None: return struct.pack(f"<I{len(self.hash)}s", len(self.hash), self.hash) # After the ':' must be a '\O': # https://elixir.bootlin.com/linux/v5.12.10/source/security/integrity/ima/ima_template_lib.c#L230 return struct.pack(f"<I{len(self.algorithm)}sBB{len(self.hash)}s", len(self.algorithm) + 2 + len(self.hash), self.algorithm.encode("utf-8"), COLON_BYTE, NULL_BYTE, self.hash) class Ima(Mode): """ Class for "ima". Contains the digest and a path. """ digest: Digest path: Name def __init__(self, data: str): tokens = data.split() if len(tokens) != 2: raise ParserError() self.digest = Digest(tokens[0], legacy=True) self.path = Name(tokens[1], legacy=True) def hash(self): tohash = self.digest.struct() + self.path.struct() return hashlib.sha1(tohash).digest() def is_data_valid(self, validator: Validator): return validator.get_validator(type(self))(self.digest, self.path) class ImaNg(Mode): """ Class for "ima-ng". Contains the digest and a path. """ digest: Digest path: Name def __init__(self, data: str): tokens = data.split() if len(tokens) != 2: raise ParserError(f"Cannot create ImaSig expected 2 tokens got: {len(tokens)}.") self.digest = Digest(tokens[0]) self.path = Name(tokens[1]) def hash(self): tohash = self.digest.struct() + self.path.struct() return hashlib.sha1(tohash).digest() def is_data_valid(self, validator): return validator.get_validator(type(self))(self.digest, self.path) class ImaSig(Mode): """ Class for "ima-sig" template. Nearly the same as ImaNg but can contain a optional signature. """ digest: Digest path: Name signature: Optional[Signature] = None def __init__(self, data: str): tokens = data.split(maxsplit=4) num_tokens = len(tokens) if num_tokens == 2: self.digest = Digest(tokens[0]) self.path = Name(tokens[1]) elif num_tokens <= 1: raise ParserError(f"Cannot create ImaSig expected 2 or 3 tokens got: {len(tokens)}.") else: self.digest = Digest(tokens[0]) signature = self.create_Signature(tokens[-1]) if signature: self.signature = signature if num_tokens == 3: self.path = Name(tokens[1]) else: # first part of data is digest , last is signature, in between is path self.path = data.split(maxsplit=1)[1].rsplit(maxsplit=1)[0] else: # first part is data, last part is path self.path = data.split(maxsplit=1)[1] def create_Signature(self, hexstring): """ Create the Signature object if the hexstring is a valid signature """ try: return Signature(hexstring) except ParserError: pass return None def hash(self): tohash = self.digest.struct() + self.path.struct() # If no signature is there we sill have to add the entry for it if self.signature is None: tohash += struct.pack("<I0s", 0, b'') else: tohash += self.signature.struct() return hashlib.sha1(tohash).digest() def is_data_valid(self, validator): return validator.get_validator(type(self))(self.digest, self.path, self.signature) class ImaBuf(Mode): """ Class for "ima-buf". Contains a digest, buffer name and the buffer itself. For validation the buffer must be done based on the name because IMA only provides it as an byte array. """ digest: Digest name: Name data: Buffer def __init__(self, data: str): tokens = data.split(maxsplit=5) if len(tokens) != 3: raise ParserError(f"Cannot create ImaBuf expected 3 tokens got: {len(tokens)}.") self.digest = Digest(tokens[0]) self.name = Name(tokens[1]) self.data = Buffer(tokens[2]) def hash(self): tohash = self.digest.struct() + self.name.struct() + self.data.struct() return hashlib.sha1(tohash).digest() def is_data_valid(self, validator: Validator): return validator.get_validator(type(self))(self.digest, self.name, self.data) class Entry: """ IMA Entry. Contains the PCR, template hash and mode. """ pcr: str template_hash: bytes mode: Mode validator: Validator mode_lookup = { "ima": Ima, "ima-ng": ImaNg, "ima-sig": ImaSig, "ima-buf": ImaBuf } def __init__(self, data: str, validator=None): self.validator = validator tokens = data.split(maxsplit=3) if len(tokens) != 4: raise ParserError(f"Cannot create Entry expected 4 tokens got: {len(tokens)}.") self.pcr = tokens[0] try: self.template_hash = codecs.decode(tokens[1].encode(), "hex") except binascii.Error as e: raise ParserError(f"Cannot create Entry expected 4 tokens got: {len(tokens)}.") from e mode = self.mode_lookup.get(tokens[2], None) if mode is None: raise ParserError(f"No parser for mode {tokens[2]} implemented.") self.mode = mode(tokens[3]) # Set correct hash for time of measure, time of use (ToMToU) errors # and if a file is already opened for write. # https://elixir.bootlin.com/linux/v5.12.12/source/security/integrity/ima/ima_main.c#L101 if self.template_hash == START_HASH: self.template_hash = FF_HASH def invalid(self): failure = Failure(Component.IMA, ["validation"]) # Ignore template hash for ToMToU errors if self.template_hash == FF_HASH: logger.warning("Skipped template_hash validation entry with FF_HASH") # By default ToMToU errors are not treated as a failure if config.getboolean("cloud_verifier", "tomtou_errors", False): failure.add_event("tomtou", "hash validation was skipped", True) return failure if self.template_hash != self.mode.hash(): failure.add_event("ima_hash", {"message": "IMA hash does not match the calculated hash.", "expected": self.template_hash, "got": self.mode.hash()}, True) return failure if self.validator is None: failure.add_event("no_validator", "No validator specified", True) return failure failure.merge(self.mode.is_data_valid(self.validator)) return failure
keylime/ima_ast.py
import binascii import codecs import hashlib import struct import abc import dataclasses from typing import Dict, Callable, Any, Optional from keylime import config from keylime import keylime_logging from keylime.failure import Failure, Component logger = keylime_logging.init_logging("ima") TCG_EVENT_NAME_LEN_MAX = 255 SHA_DIGEST_LEN = 20 MD5_DIGEST_LEN = 16 START_HASH = (codecs.decode(b'0000000000000000000000000000000000000000', 'hex')) FF_HASH = (codecs.decode(b'ffffffffffffffffffffffffffffffffffffffff', 'hex')) NULL_BYTE = ord('\0') COLON_BYTE = ord(':') @dataclasses.dataclass class Validator: functions: Dict[Any, Callable] def get_validator(self, class_type) -> Callable: validator = self.functions.get(class_type, None) if validator is None: logger.warning(f"No validator was implemented for: {class_type} . Using always false validator!") failure = Failure(Component.IMA, ["validation"]) failure.add_event("no_validator", f"No validator was implemented for: {class_type} . Using always false validator!", True) return lambda *_: failure return validator class ParserError(TypeError): """Is thrown when a type could not be constructed successfully.""" class Mode(abc.ABC): @abc.abstractmethod def is_data_valid(self, validator: Validator): pass @abc.abstractmethod def hash(self) -> bytes: pass class Type(abc.ABC): @abc.abstractmethod def struct(self): pass class HexData(Type): data: bytes def __init__(self, data: str): try: self.data = codecs.decode(data.encode("utf-8"), "hex") except binascii.Error as e: raise ParserError(f"Provided data was not valid hex: {data}") from e def __str__(self): return self.data.decode("utf-8") def struct(self): return struct.pack(f"<I{len(self.data)}s", len(self.data), self.data) class Signature(HexData): """ Class for type "sig". """ def __init__(self, data: str): super().__init__(data) # basic checks on signature fmt = '>BBBIH' hdrlen = struct.calcsize(fmt) if len(self.data) < hdrlen: raise ParserError("Invalid signature: header too short") _, _, _, _, sig_size = struct.unpack(fmt, self.data[:hdrlen]) if hdrlen + sig_size != len(self.data): raise ParserError("Invalid signature: malformed header") class Buffer(HexData): """ Class for type "buf". """ class Name(Type): """ Class for type "n" and "n-ng". """ name: str legacy: bool = False def __init__(self, name: str, legacy=False): self.name = name self.legacy = legacy def __str__(self): return self.name def struct(self): # The old "n" option is fixed length. if self.legacy: return struct.pack(f"{len(self.name)}sB{TCG_EVENT_NAME_LEN_MAX - len(self.name)}s", self.name.encode("utf-8"), NULL_BYTE, bytearray(TCG_EVENT_NAME_LEN_MAX - len(self.name))) return struct.pack(f"<I{len(self.name)}sB", len(self.name) + 1, self.name.encode("utf-8"), NULL_BYTE) class Digest: """ Class for types "d" and "d-ng" with and without algorithm """ hash: bytes algorithm: Optional[str] = None legacy: bool = False def __init__(self, digest: str, legacy=False): self.legacy = legacy tokens = digest.split(":") if len(tokens) == 1: try: self.hash = codecs.decode(tokens[0].encode("utf-8"), "hex") except binascii.Error as e: raise ParserError(f"Digest hash is not valid hex. Got: {tokens[0]}") from e if not (len(self.hash) == SHA_DIGEST_LEN or len(self.hash) == MD5_DIGEST_LEN): raise ParserError( "Cannot create Digest. No hash algorithm is provided and hash does not belong to a md5 or sha1 hash.") elif len(tokens) == 2: try: self.hash = codecs.decode(tokens[1].encode("utf-8"), "hex") except binascii.Error as e: raise ParserError(f"Digest hash is not valid hex. Got: {tokens[1]}") from e self.algorithm = tokens[0] else: raise ParserError(f"Cannot create Digest expected 1 or 2 tokens got: {len(tokens)} for {digest}") def struct(self): # The legacy format "d" has fixed length, so it does not contain a length attribute if self.legacy: return struct.pack(f"<{len(self.hash)}s", self.hash) if self.algorithm is None: return struct.pack(f"<I{len(self.hash)}s", len(self.hash), self.hash) # After the ':' must be a '\O': # https://elixir.bootlin.com/linux/v5.12.10/source/security/integrity/ima/ima_template_lib.c#L230 return struct.pack(f"<I{len(self.algorithm)}sBB{len(self.hash)}s", len(self.algorithm) + 2 + len(self.hash), self.algorithm.encode("utf-8"), COLON_BYTE, NULL_BYTE, self.hash) class Ima(Mode): """ Class for "ima". Contains the digest and a path. """ digest: Digest path: Name def __init__(self, data: str): tokens = data.split() if len(tokens) != 2: raise ParserError() self.digest = Digest(tokens[0], legacy=True) self.path = Name(tokens[1], legacy=True) def hash(self): tohash = self.digest.struct() + self.path.struct() return hashlib.sha1(tohash).digest() def is_data_valid(self, validator: Validator): return validator.get_validator(type(self))(self.digest, self.path) class ImaNg(Mode): """ Class for "ima-ng". Contains the digest and a path. """ digest: Digest path: Name def __init__(self, data: str): tokens = data.split() if len(tokens) != 2: raise ParserError(f"Cannot create ImaSig expected 2 tokens got: {len(tokens)}.") self.digest = Digest(tokens[0]) self.path = Name(tokens[1]) def hash(self): tohash = self.digest.struct() + self.path.struct() return hashlib.sha1(tohash).digest() def is_data_valid(self, validator): return validator.get_validator(type(self))(self.digest, self.path) class ImaSig(Mode): """ Class for "ima-sig" template. Nearly the same as ImaNg but can contain a optional signature. """ digest: Digest path: Name signature: Optional[Signature] = None def __init__(self, data: str): tokens = data.split(maxsplit=4) num_tokens = len(tokens) if num_tokens == 2: self.digest = Digest(tokens[0]) self.path = Name(tokens[1]) elif num_tokens <= 1: raise ParserError(f"Cannot create ImaSig expected 2 or 3 tokens got: {len(tokens)}.") else: self.digest = Digest(tokens[0]) signature = self.create_Signature(tokens[-1]) if signature: self.signature = signature if num_tokens == 3: self.path = Name(tokens[1]) else: # first part of data is digest , last is signature, in between is path self.path = data.split(maxsplit=1)[1].rsplit(maxsplit=1)[0] else: # first part is data, last part is path self.path = data.split(maxsplit=1)[1] def create_Signature(self, hexstring): """ Create the Signature object if the hexstring is a valid signature """ try: return Signature(hexstring) except ParserError: pass return None def hash(self): tohash = self.digest.struct() + self.path.struct() # If no signature is there we sill have to add the entry for it if self.signature is None: tohash += struct.pack("<I0s", 0, b'') else: tohash += self.signature.struct() return hashlib.sha1(tohash).digest() def is_data_valid(self, validator): return validator.get_validator(type(self))(self.digest, self.path, self.signature) class ImaBuf(Mode): """ Class for "ima-buf". Contains a digest, buffer name and the buffer itself. For validation the buffer must be done based on the name because IMA only provides it as an byte array. """ digest: Digest name: Name data: Buffer def __init__(self, data: str): tokens = data.split(maxsplit=5) if len(tokens) != 3: raise ParserError(f"Cannot create ImaBuf expected 3 tokens got: {len(tokens)}.") self.digest = Digest(tokens[0]) self.name = Name(tokens[1]) self.data = Buffer(tokens[2]) def hash(self): tohash = self.digest.struct() + self.name.struct() + self.data.struct() return hashlib.sha1(tohash).digest() def is_data_valid(self, validator: Validator): return validator.get_validator(type(self))(self.digest, self.name, self.data) class Entry: """ IMA Entry. Contains the PCR, template hash and mode. """ pcr: str template_hash: bytes mode: Mode validator: Validator mode_lookup = { "ima": Ima, "ima-ng": ImaNg, "ima-sig": ImaSig, "ima-buf": ImaBuf } def __init__(self, data: str, validator=None): self.validator = validator tokens = data.split(maxsplit=3) if len(tokens) != 4: raise ParserError(f"Cannot create Entry expected 4 tokens got: {len(tokens)}.") self.pcr = tokens[0] try: self.template_hash = codecs.decode(tokens[1].encode(), "hex") except binascii.Error as e: raise ParserError(f"Cannot create Entry expected 4 tokens got: {len(tokens)}.") from e mode = self.mode_lookup.get(tokens[2], None) if mode is None: raise ParserError(f"No parser for mode {tokens[2]} implemented.") self.mode = mode(tokens[3]) # Set correct hash for time of measure, time of use (ToMToU) errors # and if a file is already opened for write. # https://elixir.bootlin.com/linux/v5.12.12/source/security/integrity/ima/ima_main.c#L101 if self.template_hash == START_HASH: self.template_hash = FF_HASH def invalid(self): failure = Failure(Component.IMA, ["validation"]) # Ignore template hash for ToMToU errors if self.template_hash == FF_HASH: logger.warning("Skipped template_hash validation entry with FF_HASH") # By default ToMToU errors are not treated as a failure if config.getboolean("cloud_verifier", "tomtou_errors", False): failure.add_event("tomtou", "hash validation was skipped", True) return failure if self.template_hash != self.mode.hash(): failure.add_event("ima_hash", {"message": "IMA hash does not match the calculated hash.", "expected": self.template_hash, "got": self.mode.hash()}, True) return failure if self.validator is None: failure.add_event("no_validator", "No validator specified", True) return failure failure.merge(self.mode.is_data_valid(self.validator)) return failure
0.797872
0.207074
import colorsys import sys # Color scheme formula: # dictionary of all the keys found in the color.conf file, with as value # a tuple of hue, saturation, and value adjustments recipe1 = { "dmenu color": { "c_m_normal_bg": (0, -0.5, -0.7), "c_m_normal_fg": (0, -0.8, 0), "c_m_selected_bg": (0, -0.3, 1), "c_m_selected_fg": (0, -1, -1), }, "window colors": { "c_c_focus_active_border": (0, -0.1, -0.1), "c_c_focus_active_bg": (0, -0.1, -0.1), "c_c_focus_active_text": (0, -1, -1), "c_c_focus_active_indic": (0, -1, 0), "c_c_focus_inactive_border": (0, -0.4, -0.4), "c_c_focus_inactive_bg": (0, -0.5, -0.5), "c_c_focus_inactive_text": (0, -0.6, 0), "c_c_focus_inactive_indic": (0, -0.559, 0.212), "c_c_focused_border": (0, -0.6, -0.6), "c_c_focused_bg": (0, -0.7, -0.7), "c_c_focused_text": (0, -0.8, -0.4), "c_c_focused_indic": (0, -0.5, -0.4), "c_c_urgent_border": (-0.5, 0.062, 0.169), "c_c_urgent_bg": (-0.5, 0.062, 0.169), "c_c_urgent_text": (-0.5, -0.590, 0.639), "c_c_urgent_indic": (-0.5, -0.205, 0.412), "c_c_placeholder_border": (0, -0.641, -0.361), "c_c_placeholder_bg": (0, -0.641, -0.314), "c_c_placeholder_text": (0, -0.641, 0.639), "c_c_placeholder_indic": (0, -0.641, -0.361), "c_c_bg": (0, 0.287, -0.196), }, "bar colors": { "c_b_bg": (0, -0.4, -0.9), "c_b_status_text": (0, -0.9, 0.8), "c_b_separator": (0, -0.5, -0.5), "c_b_focused_ws_border": (0, -0.1, -0.1), "c_b_focused_ws_bg": (0, -0.1, -0.1), "c_b_focused_ws_text": (0, -1, -1), "c_b_active_ws_border": (0, -0.5, -0.5), "c_b_active_ws_bg": (0, -0.6, -0.6), "c_b_active_ws_text": (0, -1, 1), "c_b_inactive_ws_border": (0, -0.8, -0.7), "c_b_inactive_ws_bg": (0, -0.8, -0.8), "c_b_inactive_ws_text": (0, -0.9, -0.3), "c_b_urgent_ws_border": (-0.5, 0, 0), "c_b_urgent_ws_bg": (-0.5, 0, -0.2), "c_b_urgent_ws_text": (-0.5, -0.8, 1), "c_b_binding_mode_border": (-0.5, 0, 0), "c_b_binding_mode_bg": (-0.5, 0, -0.2), "c_b_binding_mode_text": (-0.5, -0.8, 1), } } def main(): if len(sys.argv) < 2: print("Please provide a hex color to start from.") exit(1) base_color = sys.argv[1] # Trim leading '#' if base_color[0] == '#': base_color = base_color[1:] try: hex_to_rgb(base_color) except ValueError: print(f"Invalid base hex color #{base_color}") exit(1) base_color = normalize_color(base_color) if len(sys.argv) == 2: scheme = generate_scheme(base_color, recipe1) for l in scheme: print(l) elif sys.argv[2] == "reverse": if len(sys.argv) < 4: print("Please provide a filename with a colorscheme to reverse") exit(1) filename = sys.argv[3] reverse_scheme = reverse_engineer_scheme(base_color, filename) for l in reverse_scheme: print(l) def get_longest_color_name(recipe): longest_name_len = 1 for r_name, s_recipe in recipe.items(): local_longest = max([len(n) for n in s_recipe.keys()]) if local_longest > longest_name_len: longest_name_len = local_longest return longest_name_len def generate_scheme(base_hex_color, recipe): file_header = "# Colors " line_length = 79 longest_name_len = get_longest_color_name(recipe) scheme_lines = [ f"{file_header:-<{line_length}}", "", f"# This scheme was generated with #{base_hex_color} as a base color.", "" ] for section_heading, sub_recipe in recipe.items(): scheme_lines.append(f"# {section_heading}") scheme_lines.extend( generate_sub_scheme( base_hex_color, sub_recipe, longest_name_len)) scheme_lines.append("") return scheme_lines def generate_sub_scheme(base_hex_color, sub_recipe, longest_name_len): base_hsv = hex_to_hsv(base_hex_color) scheme_list = [] for color_name, adjustments in sub_recipe.items(): new_color = hsv_to_hex(*adjust_hsv(*base_hsv, *adjustments)) scheme_list.append( "set " \ f"${color_name: <{longest_name_len}} " f"{new_color}") return scheme_list def reverse_engineer_scheme(base_hex_color, filename): lines = [] with open(filename) as f: lines = f.readlines() lines = [l.strip() for l in lines] base_h, base_s, base_v = hex_to_hsv(base_hex_color) named_hex_colors = {} adjustments = [] for l in lines: if not l.startswith("set $"): continue name = l[5:-6].strip() hex_color = l[-6:] named_hex_colors[name] = hex_color for n, hex_color in named_hex_colors.items(): h, s, v = hex_to_hsv(hex_color) adjustments.append( f"\"${n}\": (" f"{(h - base_h):.3f}, " f"{(s - base_s):.3f}, " f"{(v - base_v):.3f}),") return adjustments def normalize_color(hex_color): h, s, v = hex_to_hsv(hex_color) return hsv_to_hex(h, 1.0 if s > 0 else 0, 1.0) def adjust_hsv(h, s, v, h_adj, s_adj, v_adj): h += h_adj # If it's over or under, wrap around h = h if h >= 0 else 1 - (abs(h) % 1) h = h if h <= 1 else h % 1 s += s_adj # Clip to 0..1.0 s = s if s >= 0 else 0 s = s if s <= 1.0 else 1.0 v += v_adj # Clip to 0..1.0 v = v if v >= 0 else 0 v = v if v <= 1.0 else 1.0 return h, s, v def hex_to_rgb(hex_color): return int(hex_color[0:2], 16) / 255.0,\ int(hex_color[2:4], 16) / 255.0,\ int(hex_color[4:6], 16) / 255.0 def rgb_to_hex(r, g, b): return f"{hex(int(r * 255))[2:].upper():0>2}" \ f"{hex(int(g * 255))[2:].upper():0>2}" \ f"{hex(int(b * 255))[2:].upper():0>2}" def hex_to_hsv(hex_color): return colorsys.rgb_to_hsv(*hex_to_rgb(hex_color)) def hsv_to_hex(h, s, v): return rgb_to_hex(*colorsys.hsv_to_rgb(h, s, v)) main()
.config/i3/config.d/available/colorgen.py
import colorsys import sys # Color scheme formula: # dictionary of all the keys found in the color.conf file, with as value # a tuple of hue, saturation, and value adjustments recipe1 = { "dmenu color": { "c_m_normal_bg": (0, -0.5, -0.7), "c_m_normal_fg": (0, -0.8, 0), "c_m_selected_bg": (0, -0.3, 1), "c_m_selected_fg": (0, -1, -1), }, "window colors": { "c_c_focus_active_border": (0, -0.1, -0.1), "c_c_focus_active_bg": (0, -0.1, -0.1), "c_c_focus_active_text": (0, -1, -1), "c_c_focus_active_indic": (0, -1, 0), "c_c_focus_inactive_border": (0, -0.4, -0.4), "c_c_focus_inactive_bg": (0, -0.5, -0.5), "c_c_focus_inactive_text": (0, -0.6, 0), "c_c_focus_inactive_indic": (0, -0.559, 0.212), "c_c_focused_border": (0, -0.6, -0.6), "c_c_focused_bg": (0, -0.7, -0.7), "c_c_focused_text": (0, -0.8, -0.4), "c_c_focused_indic": (0, -0.5, -0.4), "c_c_urgent_border": (-0.5, 0.062, 0.169), "c_c_urgent_bg": (-0.5, 0.062, 0.169), "c_c_urgent_text": (-0.5, -0.590, 0.639), "c_c_urgent_indic": (-0.5, -0.205, 0.412), "c_c_placeholder_border": (0, -0.641, -0.361), "c_c_placeholder_bg": (0, -0.641, -0.314), "c_c_placeholder_text": (0, -0.641, 0.639), "c_c_placeholder_indic": (0, -0.641, -0.361), "c_c_bg": (0, 0.287, -0.196), }, "bar colors": { "c_b_bg": (0, -0.4, -0.9), "c_b_status_text": (0, -0.9, 0.8), "c_b_separator": (0, -0.5, -0.5), "c_b_focused_ws_border": (0, -0.1, -0.1), "c_b_focused_ws_bg": (0, -0.1, -0.1), "c_b_focused_ws_text": (0, -1, -1), "c_b_active_ws_border": (0, -0.5, -0.5), "c_b_active_ws_bg": (0, -0.6, -0.6), "c_b_active_ws_text": (0, -1, 1), "c_b_inactive_ws_border": (0, -0.8, -0.7), "c_b_inactive_ws_bg": (0, -0.8, -0.8), "c_b_inactive_ws_text": (0, -0.9, -0.3), "c_b_urgent_ws_border": (-0.5, 0, 0), "c_b_urgent_ws_bg": (-0.5, 0, -0.2), "c_b_urgent_ws_text": (-0.5, -0.8, 1), "c_b_binding_mode_border": (-0.5, 0, 0), "c_b_binding_mode_bg": (-0.5, 0, -0.2), "c_b_binding_mode_text": (-0.5, -0.8, 1), } } def main(): if len(sys.argv) < 2: print("Please provide a hex color to start from.") exit(1) base_color = sys.argv[1] # Trim leading '#' if base_color[0] == '#': base_color = base_color[1:] try: hex_to_rgb(base_color) except ValueError: print(f"Invalid base hex color #{base_color}") exit(1) base_color = normalize_color(base_color) if len(sys.argv) == 2: scheme = generate_scheme(base_color, recipe1) for l in scheme: print(l) elif sys.argv[2] == "reverse": if len(sys.argv) < 4: print("Please provide a filename with a colorscheme to reverse") exit(1) filename = sys.argv[3] reverse_scheme = reverse_engineer_scheme(base_color, filename) for l in reverse_scheme: print(l) def get_longest_color_name(recipe): longest_name_len = 1 for r_name, s_recipe in recipe.items(): local_longest = max([len(n) for n in s_recipe.keys()]) if local_longest > longest_name_len: longest_name_len = local_longest return longest_name_len def generate_scheme(base_hex_color, recipe): file_header = "# Colors " line_length = 79 longest_name_len = get_longest_color_name(recipe) scheme_lines = [ f"{file_header:-<{line_length}}", "", f"# This scheme was generated with #{base_hex_color} as a base color.", "" ] for section_heading, sub_recipe in recipe.items(): scheme_lines.append(f"# {section_heading}") scheme_lines.extend( generate_sub_scheme( base_hex_color, sub_recipe, longest_name_len)) scheme_lines.append("") return scheme_lines def generate_sub_scheme(base_hex_color, sub_recipe, longest_name_len): base_hsv = hex_to_hsv(base_hex_color) scheme_list = [] for color_name, adjustments in sub_recipe.items(): new_color = hsv_to_hex(*adjust_hsv(*base_hsv, *adjustments)) scheme_list.append( "set " \ f"${color_name: <{longest_name_len}} " f"{new_color}") return scheme_list def reverse_engineer_scheme(base_hex_color, filename): lines = [] with open(filename) as f: lines = f.readlines() lines = [l.strip() for l in lines] base_h, base_s, base_v = hex_to_hsv(base_hex_color) named_hex_colors = {} adjustments = [] for l in lines: if not l.startswith("set $"): continue name = l[5:-6].strip() hex_color = l[-6:] named_hex_colors[name] = hex_color for n, hex_color in named_hex_colors.items(): h, s, v = hex_to_hsv(hex_color) adjustments.append( f"\"${n}\": (" f"{(h - base_h):.3f}, " f"{(s - base_s):.3f}, " f"{(v - base_v):.3f}),") return adjustments def normalize_color(hex_color): h, s, v = hex_to_hsv(hex_color) return hsv_to_hex(h, 1.0 if s > 0 else 0, 1.0) def adjust_hsv(h, s, v, h_adj, s_adj, v_adj): h += h_adj # If it's over or under, wrap around h = h if h >= 0 else 1 - (abs(h) % 1) h = h if h <= 1 else h % 1 s += s_adj # Clip to 0..1.0 s = s if s >= 0 else 0 s = s if s <= 1.0 else 1.0 v += v_adj # Clip to 0..1.0 v = v if v >= 0 else 0 v = v if v <= 1.0 else 1.0 return h, s, v def hex_to_rgb(hex_color): return int(hex_color[0:2], 16) / 255.0,\ int(hex_color[2:4], 16) / 255.0,\ int(hex_color[4:6], 16) / 255.0 def rgb_to_hex(r, g, b): return f"{hex(int(r * 255))[2:].upper():0>2}" \ f"{hex(int(g * 255))[2:].upper():0>2}" \ f"{hex(int(b * 255))[2:].upper():0>2}" def hex_to_hsv(hex_color): return colorsys.rgb_to_hsv(*hex_to_rgb(hex_color)) def hsv_to_hex(h, s, v): return rgb_to_hex(*colorsys.hsv_to_rgb(h, s, v)) main()
0.345436
0.214136
import signal import sys import unittest import warnings from unittest import mock import asyncio from asyncio import base_subprocess from asyncio import subprocess from test.test_asyncio import utils as test_utils from test import support if sys.platform != 'win32': from asyncio import unix_events # Program blocking PROGRAM_BLOCKED = [sys.executable, '-c', 'import time; time.sleep(3600)'] # Program copying input to output PROGRAM_CAT = [ sys.executable, '-c', ';'.join(('import sys', 'data = sys.stdin.buffer.read()', 'sys.stdout.buffer.write(data)'))] class TestSubprocessTransport(base_subprocess.BaseSubprocessTransport): def _start(self, *args, **kwargs): self._proc = mock.Mock() self._proc.stdin = None self._proc.stdout = None self._proc.stderr = None self._proc.pid = -1 class SubprocessTransportTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.set_event_loop(self.loop) def create_transport(self, waiter=None): protocol = mock.Mock() protocol.connection_made._is_coroutine = False protocol.process_exited._is_coroutine = False transport = TestSubprocessTransport( self.loop, protocol, ['test'], False, None, None, None, 0, waiter=waiter) return (transport, protocol) def test_proc_exited(self): waiter = asyncio.Future(loop=self.loop) transport, protocol = self.create_transport(waiter) transport._process_exited(6) self.loop.run_until_complete(waiter) self.assertEqual(transport.get_returncode(), 6) self.assertTrue(protocol.connection_made.called) self.assertTrue(protocol.process_exited.called) self.assertTrue(protocol.connection_lost.called) self.assertEqual(protocol.connection_lost.call_args[0], (None,)) self.assertFalse(transport.is_closing()) self.assertIsNone(transport._loop) self.assertIsNone(transport._proc) self.assertIsNone(transport._protocol) # methods must raise ProcessLookupError if the process exited self.assertRaises(ProcessLookupError, transport.send_signal, signal.SIGTERM) self.assertRaises(ProcessLookupError, transport.terminate) self.assertRaises(ProcessLookupError, transport.kill) transport.close() def test_subprocess_repr(self): waiter = asyncio.Future(loop=self.loop) transport, protocol = self.create_transport(waiter) transport._process_exited(6) self.loop.run_until_complete(waiter) self.assertEqual( repr(transport), "<TestSubprocessTransport pid=-1 returncode=6>" ) transport._returncode = None self.assertEqual( repr(transport), "<TestSubprocessTransport pid=-1 running>" ) transport._pid = None transport._returncode = None self.assertEqual( repr(transport), "<TestSubprocessTransport not started>" ) transport.close() class SubprocessMixin: def test_stdin_stdout(self): args = PROGRAM_CAT async def run(data): proc = await asyncio.create_subprocess_exec( *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, loop=self.loop) # feed data proc.stdin.write(data) await proc.stdin.drain() proc.stdin.close() # get output and exitcode data = await proc.stdout.read() exitcode = await proc.wait() return (exitcode, data) task = run(b'some data') task = asyncio.wait_for(task, 60.0, loop=self.loop) exitcode, stdout = self.loop.run_until_complete(task) self.assertEqual(exitcode, 0) self.assertEqual(stdout, b'some data') def test_communicate(self): args = PROGRAM_CAT async def run(data): proc = await asyncio.create_subprocess_exec( *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, loop=self.loop) stdout, stderr = await proc.communicate(data) return proc.returncode, stdout task = run(b'some data') task = asyncio.wait_for(task, 60.0, loop=self.loop) exitcode, stdout = self.loop.run_until_complete(task) self.assertEqual(exitcode, 0) self.assertEqual(stdout, b'some data') def test_shell(self): create = asyncio.create_subprocess_shell('exit 7', loop=self.loop) proc = self.loop.run_until_complete(create) exitcode = self.loop.run_until_complete(proc.wait()) self.assertEqual(exitcode, 7) def test_start_new_session(self): # start the new process in a new session create = asyncio.create_subprocess_shell('exit 8', start_new_session=True, loop=self.loop) proc = self.loop.run_until_complete(create) exitcode = self.loop.run_until_complete(proc.wait()) self.assertEqual(exitcode, 8) def test_kill(self): args = PROGRAM_BLOCKED create = asyncio.create_subprocess_exec(*args, loop=self.loop) proc = self.loop.run_until_complete(create) proc.kill() returncode = self.loop.run_until_complete(proc.wait()) if sys.platform == 'win32': self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGKILL, returncode) def test_terminate(self): args = PROGRAM_BLOCKED create = asyncio.create_subprocess_exec(*args, loop=self.loop) proc = self.loop.run_until_complete(create) proc.terminate() returncode = self.loop.run_until_complete(proc.wait()) if sys.platform == 'win32': self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGTERM, returncode) @unittest.skipIf(sys.platform == 'win32', "Don't have SIGHUP") def test_send_signal(self): # bpo-31034: Make sure that we get the default signal handler (killing # the process). The parent process may have decided to ignore SIGHUP, # and signal handlers are inherited. old_handler = signal.signal(signal.SIGHUP, signal.SIG_DFL) try: code = 'import time; print("sleeping", flush=True); time.sleep(3600)' args = [sys.executable, '-c', code] create = asyncio.create_subprocess_exec(*args, stdout=subprocess.PIPE, loop=self.loop) proc = self.loop.run_until_complete(create) async def send_signal(proc): # basic synchronization to wait until the program is sleeping line = await proc.stdout.readline() self.assertEqual(line, b'sleeping\n') proc.send_signal(signal.SIGHUP) returncode = await proc.wait() return returncode returncode = self.loop.run_until_complete(send_signal(proc)) self.assertEqual(-signal.SIGHUP, returncode) finally: signal.signal(signal.SIGHUP, old_handler) def prepare_broken_pipe_test(self): # buffer large enough to feed the whole pipe buffer large_data = b'x' * support.PIPE_MAX_SIZE # the program ends before the stdin can be feeded create = asyncio.create_subprocess_exec( sys.executable, '-c', 'pass', stdin=subprocess.PIPE, loop=self.loop) proc = self.loop.run_until_complete(create) return (proc, large_data) def test_stdin_broken_pipe(self): proc, large_data = self.prepare_broken_pipe_test() async def write_stdin(proc, data): await asyncio.sleep(0.5, loop=self.loop) proc.stdin.write(data) await proc.stdin.drain() coro = write_stdin(proc, large_data) # drain() must raise BrokenPipeError or ConnectionResetError with test_utils.disable_logger(): self.assertRaises((BrokenPipeError, ConnectionResetError), self.loop.run_until_complete, coro) self.loop.run_until_complete(proc.wait()) def test_communicate_ignore_broken_pipe(self): proc, large_data = self.prepare_broken_pipe_test() # communicate() must ignore BrokenPipeError when feeding stdin with test_utils.disable_logger(): self.loop.run_until_complete(proc.communicate(large_data)) self.loop.run_until_complete(proc.wait()) def test_pause_reading(self): limit = 10 size = (limit * 2 + 1) async def test_pause_reading(): code = '\n'.join(( 'import sys', 'sys.stdout.write("x" * %s)' % size, 'sys.stdout.flush()', )) connect_read_pipe = self.loop.connect_read_pipe async def connect_read_pipe_mock(*args, **kw): transport, protocol = await connect_read_pipe(*args, **kw) transport.pause_reading = mock.Mock() transport.resume_reading = mock.Mock() return (transport, protocol) self.loop.connect_read_pipe = connect_read_pipe_mock proc = await asyncio.create_subprocess_exec( sys.executable, '-c', code, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, limit=limit, loop=self.loop) stdout_transport = proc._transport.get_pipe_transport(1) stdout, stderr = await proc.communicate() # The child process produced more than limit bytes of output, # the stream reader transport should pause the protocol to not # allocate too much memory. return (stdout, stdout_transport) # Issue #22685: Ensure that the stream reader pauses the protocol # when the child process produces too much data stdout, transport = self.loop.run_until_complete(test_pause_reading()) self.assertEqual(stdout, b'x' * size) self.assertTrue(transport.pause_reading.called) self.assertTrue(transport.resume_reading.called) def test_stdin_not_inheritable(self): # asyncio issue #209: stdin must not be inheritable, otherwise # the Process.communicate() hangs async def len_message(message): code = 'import sys; data = sys.stdin.read(); print(len(data))' proc = await asyncio.create_subprocess_exec( sys.executable, '-c', code, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, close_fds=False, loop=self.loop) stdout, stderr = await proc.communicate(message) exitcode = await proc.wait() return (stdout, exitcode) output, exitcode = self.loop.run_until_complete(len_message(b'abc')) self.assertEqual(output.rstrip(), b'3') self.assertEqual(exitcode, 0) def test_empty_input(self): async def empty_input(): code = 'import sys; data = sys.stdin.read(); print(len(data))' proc = await asyncio.create_subprocess_exec( sys.executable, '-c', code, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, close_fds=False, loop=self.loop) stdout, stderr = await proc.communicate(b'') exitcode = await proc.wait() return (stdout, exitcode) output, exitcode = self.loop.run_until_complete(empty_input()) self.assertEqual(output.rstrip(), b'0') self.assertEqual(exitcode, 0) def test_cancel_process_wait(self): # Issue #23140: cancel Process.wait() async def cancel_wait(): proc = await asyncio.create_subprocess_exec( *PROGRAM_BLOCKED, loop=self.loop) # Create an internal future waiting on the process exit task = self.loop.create_task(proc.wait()) self.loop.call_soon(task.cancel) try: await task except asyncio.CancelledError: pass # Cancel the future task.cancel() # Kill the process and wait until it is done proc.kill() await proc.wait() self.loop.run_until_complete(cancel_wait()) def test_cancel_make_subprocess_transport_exec(self): async def cancel_make_transport(): coro = asyncio.create_subprocess_exec(*PROGRAM_BLOCKED, loop=self.loop) task = self.loop.create_task(coro) self.loop.call_soon(task.cancel) try: await task except asyncio.CancelledError: pass # ignore the log: # "Exception during subprocess creation, kill the subprocess" with test_utils.disable_logger(): self.loop.run_until_complete(cancel_make_transport()) def test_cancel_post_init(self): async def cancel_make_transport(): coro = self.loop.subprocess_exec(asyncio.SubprocessProtocol, *PROGRAM_BLOCKED) task = self.loop.create_task(coro) self.loop.call_soon(task.cancel) try: await task except asyncio.CancelledError: pass # ignore the log: # "Exception during subprocess creation, kill the subprocess" with test_utils.disable_logger(): self.loop.run_until_complete(cancel_make_transport()) test_utils.run_briefly(self.loop) def test_close_kill_running(self): async def kill_running(): create = self.loop.subprocess_exec(asyncio.SubprocessProtocol, *PROGRAM_BLOCKED) transport, protocol = await create kill_called = False def kill(): nonlocal kill_called kill_called = True orig_kill() proc = transport.get_extra_info('subprocess') orig_kill = proc.kill proc.kill = kill returncode = transport.get_returncode() transport.close() await transport._wait() return (returncode, kill_called) # Ignore "Close running child process: kill ..." log with test_utils.disable_logger(): returncode, killed = self.loop.run_until_complete(kill_running()) self.assertIsNone(returncode) # transport.close() must kill the process if it is still running self.assertTrue(killed) test_utils.run_briefly(self.loop) def test_close_dont_kill_finished(self): async def kill_running(): create = self.loop.subprocess_exec(asyncio.SubprocessProtocol, *PROGRAM_BLOCKED) transport, protocol = await create proc = transport.get_extra_info('subprocess') # kill the process (but asyncio is not notified immediately) proc.kill() proc.wait() proc.kill = mock.Mock() proc_returncode = proc.poll() transport_returncode = transport.get_returncode() transport.close() return (proc_returncode, transport_returncode, proc.kill.called) # Ignore "Unknown child process pid ..." log of SafeChildWatcher, # emitted because the test already consumes the exit status: # proc.wait() with test_utils.disable_logger(): result = self.loop.run_until_complete(kill_running()) test_utils.run_briefly(self.loop) proc_returncode, transport_return_code, killed = result self.assertIsNotNone(proc_returncode) self.assertIsNone(transport_return_code) # transport.close() must not kill the process if it finished, even if # the transport was not notified yet self.assertFalse(killed) # Unlike SafeChildWatcher, FastChildWatcher does not pop the # callbacks if waitpid() is called elsewhere. Let's clear them # manually to avoid a warning when the watcher is detached. if (sys.platform != 'win32' and isinstance(self, SubprocessFastWatcherTests)): asyncio.get_child_watcher()._callbacks.clear() def _test_popen_error(self, stdin): if sys.platform == 'win32': target = 'asyncio.windows_utils.Popen' else: target = 'subprocess.Popen' with mock.patch(target) as popen: exc = ZeroDivisionError popen.side_effect = exc create = asyncio.create_subprocess_exec(sys.executable, '-c', 'pass', stdin=stdin, loop=self.loop) with warnings.catch_warnings(record=True) as warns: with self.assertRaises(exc): self.loop.run_until_complete(create) self.assertEqual(warns, []) def test_popen_error(self): # Issue #24763: check that the subprocess transport is closed # when BaseSubprocessTransport fails self._test_popen_error(stdin=None) def test_popen_error_with_stdin_pipe(self): # Issue #35721: check that newly created socket pair is closed when # Popen fails self._test_popen_error(stdin=subprocess.PIPE) def test_read_stdout_after_process_exit(self): async def execute(): code = '\n'.join(['import sys', 'for _ in range(64):', ' sys.stdout.write("x" * 4096)', 'sys.stdout.flush()', 'sys.exit(1)']) fut = asyncio.create_subprocess_exec( sys.executable, '-c', code, stdout=asyncio.subprocess.PIPE, loop=self.loop) process = await fut while True: data = await process.stdout.read(65536) if data: await asyncio.sleep(0.3, loop=self.loop) else: break self.loop.run_until_complete(execute()) if sys.platform != 'win32': # Unix class SubprocessWatcherMixin(SubprocessMixin): Watcher = None def setUp(self): super().setUp() policy = asyncio.get_event_loop_policy() self.loop = policy.new_event_loop() self.set_event_loop(self.loop) watcher = self.Watcher() watcher.attach_loop(self.loop) policy.set_child_watcher(watcher) self.addCleanup(policy.set_child_watcher, None) class SubprocessSafeWatcherTests(SubprocessWatcherMixin, test_utils.TestCase): Watcher = unix_events.SafeChildWatcher class SubprocessFastWatcherTests(SubprocessWatcherMixin, test_utils.TestCase): Watcher = unix_events.FastChildWatcher else: # Windows class SubprocessProactorTests(SubprocessMixin, test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.ProactorEventLoop() self.set_event_loop(self.loop) if __name__ == '__main__': unittest.main()
toolchain/riscv/MSYS/python/Lib/test/test_asyncio/test_subprocess.py
import signal import sys import unittest import warnings from unittest import mock import asyncio from asyncio import base_subprocess from asyncio import subprocess from test.test_asyncio import utils as test_utils from test import support if sys.platform != 'win32': from asyncio import unix_events # Program blocking PROGRAM_BLOCKED = [sys.executable, '-c', 'import time; time.sleep(3600)'] # Program copying input to output PROGRAM_CAT = [ sys.executable, '-c', ';'.join(('import sys', 'data = sys.stdin.buffer.read()', 'sys.stdout.buffer.write(data)'))] class TestSubprocessTransport(base_subprocess.BaseSubprocessTransport): def _start(self, *args, **kwargs): self._proc = mock.Mock() self._proc.stdin = None self._proc.stdout = None self._proc.stderr = None self._proc.pid = -1 class SubprocessTransportTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.set_event_loop(self.loop) def create_transport(self, waiter=None): protocol = mock.Mock() protocol.connection_made._is_coroutine = False protocol.process_exited._is_coroutine = False transport = TestSubprocessTransport( self.loop, protocol, ['test'], False, None, None, None, 0, waiter=waiter) return (transport, protocol) def test_proc_exited(self): waiter = asyncio.Future(loop=self.loop) transport, protocol = self.create_transport(waiter) transport._process_exited(6) self.loop.run_until_complete(waiter) self.assertEqual(transport.get_returncode(), 6) self.assertTrue(protocol.connection_made.called) self.assertTrue(protocol.process_exited.called) self.assertTrue(protocol.connection_lost.called) self.assertEqual(protocol.connection_lost.call_args[0], (None,)) self.assertFalse(transport.is_closing()) self.assertIsNone(transport._loop) self.assertIsNone(transport._proc) self.assertIsNone(transport._protocol) # methods must raise ProcessLookupError if the process exited self.assertRaises(ProcessLookupError, transport.send_signal, signal.SIGTERM) self.assertRaises(ProcessLookupError, transport.terminate) self.assertRaises(ProcessLookupError, transport.kill) transport.close() def test_subprocess_repr(self): waiter = asyncio.Future(loop=self.loop) transport, protocol = self.create_transport(waiter) transport._process_exited(6) self.loop.run_until_complete(waiter) self.assertEqual( repr(transport), "<TestSubprocessTransport pid=-1 returncode=6>" ) transport._returncode = None self.assertEqual( repr(transport), "<TestSubprocessTransport pid=-1 running>" ) transport._pid = None transport._returncode = None self.assertEqual( repr(transport), "<TestSubprocessTransport not started>" ) transport.close() class SubprocessMixin: def test_stdin_stdout(self): args = PROGRAM_CAT async def run(data): proc = await asyncio.create_subprocess_exec( *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, loop=self.loop) # feed data proc.stdin.write(data) await proc.stdin.drain() proc.stdin.close() # get output and exitcode data = await proc.stdout.read() exitcode = await proc.wait() return (exitcode, data) task = run(b'some data') task = asyncio.wait_for(task, 60.0, loop=self.loop) exitcode, stdout = self.loop.run_until_complete(task) self.assertEqual(exitcode, 0) self.assertEqual(stdout, b'some data') def test_communicate(self): args = PROGRAM_CAT async def run(data): proc = await asyncio.create_subprocess_exec( *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, loop=self.loop) stdout, stderr = await proc.communicate(data) return proc.returncode, stdout task = run(b'some data') task = asyncio.wait_for(task, 60.0, loop=self.loop) exitcode, stdout = self.loop.run_until_complete(task) self.assertEqual(exitcode, 0) self.assertEqual(stdout, b'some data') def test_shell(self): create = asyncio.create_subprocess_shell('exit 7', loop=self.loop) proc = self.loop.run_until_complete(create) exitcode = self.loop.run_until_complete(proc.wait()) self.assertEqual(exitcode, 7) def test_start_new_session(self): # start the new process in a new session create = asyncio.create_subprocess_shell('exit 8', start_new_session=True, loop=self.loop) proc = self.loop.run_until_complete(create) exitcode = self.loop.run_until_complete(proc.wait()) self.assertEqual(exitcode, 8) def test_kill(self): args = PROGRAM_BLOCKED create = asyncio.create_subprocess_exec(*args, loop=self.loop) proc = self.loop.run_until_complete(create) proc.kill() returncode = self.loop.run_until_complete(proc.wait()) if sys.platform == 'win32': self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGKILL, returncode) def test_terminate(self): args = PROGRAM_BLOCKED create = asyncio.create_subprocess_exec(*args, loop=self.loop) proc = self.loop.run_until_complete(create) proc.terminate() returncode = self.loop.run_until_complete(proc.wait()) if sys.platform == 'win32': self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGTERM, returncode) @unittest.skipIf(sys.platform == 'win32', "Don't have SIGHUP") def test_send_signal(self): # bpo-31034: Make sure that we get the default signal handler (killing # the process). The parent process may have decided to ignore SIGHUP, # and signal handlers are inherited. old_handler = signal.signal(signal.SIGHUP, signal.SIG_DFL) try: code = 'import time; print("sleeping", flush=True); time.sleep(3600)' args = [sys.executable, '-c', code] create = asyncio.create_subprocess_exec(*args, stdout=subprocess.PIPE, loop=self.loop) proc = self.loop.run_until_complete(create) async def send_signal(proc): # basic synchronization to wait until the program is sleeping line = await proc.stdout.readline() self.assertEqual(line, b'sleeping\n') proc.send_signal(signal.SIGHUP) returncode = await proc.wait() return returncode returncode = self.loop.run_until_complete(send_signal(proc)) self.assertEqual(-signal.SIGHUP, returncode) finally: signal.signal(signal.SIGHUP, old_handler) def prepare_broken_pipe_test(self): # buffer large enough to feed the whole pipe buffer large_data = b'x' * support.PIPE_MAX_SIZE # the program ends before the stdin can be feeded create = asyncio.create_subprocess_exec( sys.executable, '-c', 'pass', stdin=subprocess.PIPE, loop=self.loop) proc = self.loop.run_until_complete(create) return (proc, large_data) def test_stdin_broken_pipe(self): proc, large_data = self.prepare_broken_pipe_test() async def write_stdin(proc, data): await asyncio.sleep(0.5, loop=self.loop) proc.stdin.write(data) await proc.stdin.drain() coro = write_stdin(proc, large_data) # drain() must raise BrokenPipeError or ConnectionResetError with test_utils.disable_logger(): self.assertRaises((BrokenPipeError, ConnectionResetError), self.loop.run_until_complete, coro) self.loop.run_until_complete(proc.wait()) def test_communicate_ignore_broken_pipe(self): proc, large_data = self.prepare_broken_pipe_test() # communicate() must ignore BrokenPipeError when feeding stdin with test_utils.disable_logger(): self.loop.run_until_complete(proc.communicate(large_data)) self.loop.run_until_complete(proc.wait()) def test_pause_reading(self): limit = 10 size = (limit * 2 + 1) async def test_pause_reading(): code = '\n'.join(( 'import sys', 'sys.stdout.write("x" * %s)' % size, 'sys.stdout.flush()', )) connect_read_pipe = self.loop.connect_read_pipe async def connect_read_pipe_mock(*args, **kw): transport, protocol = await connect_read_pipe(*args, **kw) transport.pause_reading = mock.Mock() transport.resume_reading = mock.Mock() return (transport, protocol) self.loop.connect_read_pipe = connect_read_pipe_mock proc = await asyncio.create_subprocess_exec( sys.executable, '-c', code, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, limit=limit, loop=self.loop) stdout_transport = proc._transport.get_pipe_transport(1) stdout, stderr = await proc.communicate() # The child process produced more than limit bytes of output, # the stream reader transport should pause the protocol to not # allocate too much memory. return (stdout, stdout_transport) # Issue #22685: Ensure that the stream reader pauses the protocol # when the child process produces too much data stdout, transport = self.loop.run_until_complete(test_pause_reading()) self.assertEqual(stdout, b'x' * size) self.assertTrue(transport.pause_reading.called) self.assertTrue(transport.resume_reading.called) def test_stdin_not_inheritable(self): # asyncio issue #209: stdin must not be inheritable, otherwise # the Process.communicate() hangs async def len_message(message): code = 'import sys; data = sys.stdin.read(); print(len(data))' proc = await asyncio.create_subprocess_exec( sys.executable, '-c', code, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, close_fds=False, loop=self.loop) stdout, stderr = await proc.communicate(message) exitcode = await proc.wait() return (stdout, exitcode) output, exitcode = self.loop.run_until_complete(len_message(b'abc')) self.assertEqual(output.rstrip(), b'3') self.assertEqual(exitcode, 0) def test_empty_input(self): async def empty_input(): code = 'import sys; data = sys.stdin.read(); print(len(data))' proc = await asyncio.create_subprocess_exec( sys.executable, '-c', code, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, close_fds=False, loop=self.loop) stdout, stderr = await proc.communicate(b'') exitcode = await proc.wait() return (stdout, exitcode) output, exitcode = self.loop.run_until_complete(empty_input()) self.assertEqual(output.rstrip(), b'0') self.assertEqual(exitcode, 0) def test_cancel_process_wait(self): # Issue #23140: cancel Process.wait() async def cancel_wait(): proc = await asyncio.create_subprocess_exec( *PROGRAM_BLOCKED, loop=self.loop) # Create an internal future waiting on the process exit task = self.loop.create_task(proc.wait()) self.loop.call_soon(task.cancel) try: await task except asyncio.CancelledError: pass # Cancel the future task.cancel() # Kill the process and wait until it is done proc.kill() await proc.wait() self.loop.run_until_complete(cancel_wait()) def test_cancel_make_subprocess_transport_exec(self): async def cancel_make_transport(): coro = asyncio.create_subprocess_exec(*PROGRAM_BLOCKED, loop=self.loop) task = self.loop.create_task(coro) self.loop.call_soon(task.cancel) try: await task except asyncio.CancelledError: pass # ignore the log: # "Exception during subprocess creation, kill the subprocess" with test_utils.disable_logger(): self.loop.run_until_complete(cancel_make_transport()) def test_cancel_post_init(self): async def cancel_make_transport(): coro = self.loop.subprocess_exec(asyncio.SubprocessProtocol, *PROGRAM_BLOCKED) task = self.loop.create_task(coro) self.loop.call_soon(task.cancel) try: await task except asyncio.CancelledError: pass # ignore the log: # "Exception during subprocess creation, kill the subprocess" with test_utils.disable_logger(): self.loop.run_until_complete(cancel_make_transport()) test_utils.run_briefly(self.loop) def test_close_kill_running(self): async def kill_running(): create = self.loop.subprocess_exec(asyncio.SubprocessProtocol, *PROGRAM_BLOCKED) transport, protocol = await create kill_called = False def kill(): nonlocal kill_called kill_called = True orig_kill() proc = transport.get_extra_info('subprocess') orig_kill = proc.kill proc.kill = kill returncode = transport.get_returncode() transport.close() await transport._wait() return (returncode, kill_called) # Ignore "Close running child process: kill ..." log with test_utils.disable_logger(): returncode, killed = self.loop.run_until_complete(kill_running()) self.assertIsNone(returncode) # transport.close() must kill the process if it is still running self.assertTrue(killed) test_utils.run_briefly(self.loop) def test_close_dont_kill_finished(self): async def kill_running(): create = self.loop.subprocess_exec(asyncio.SubprocessProtocol, *PROGRAM_BLOCKED) transport, protocol = await create proc = transport.get_extra_info('subprocess') # kill the process (but asyncio is not notified immediately) proc.kill() proc.wait() proc.kill = mock.Mock() proc_returncode = proc.poll() transport_returncode = transport.get_returncode() transport.close() return (proc_returncode, transport_returncode, proc.kill.called) # Ignore "Unknown child process pid ..." log of SafeChildWatcher, # emitted because the test already consumes the exit status: # proc.wait() with test_utils.disable_logger(): result = self.loop.run_until_complete(kill_running()) test_utils.run_briefly(self.loop) proc_returncode, transport_return_code, killed = result self.assertIsNotNone(proc_returncode) self.assertIsNone(transport_return_code) # transport.close() must not kill the process if it finished, even if # the transport was not notified yet self.assertFalse(killed) # Unlike SafeChildWatcher, FastChildWatcher does not pop the # callbacks if waitpid() is called elsewhere. Let's clear them # manually to avoid a warning when the watcher is detached. if (sys.platform != 'win32' and isinstance(self, SubprocessFastWatcherTests)): asyncio.get_child_watcher()._callbacks.clear() def _test_popen_error(self, stdin): if sys.platform == 'win32': target = 'asyncio.windows_utils.Popen' else: target = 'subprocess.Popen' with mock.patch(target) as popen: exc = ZeroDivisionError popen.side_effect = exc create = asyncio.create_subprocess_exec(sys.executable, '-c', 'pass', stdin=stdin, loop=self.loop) with warnings.catch_warnings(record=True) as warns: with self.assertRaises(exc): self.loop.run_until_complete(create) self.assertEqual(warns, []) def test_popen_error(self): # Issue #24763: check that the subprocess transport is closed # when BaseSubprocessTransport fails self._test_popen_error(stdin=None) def test_popen_error_with_stdin_pipe(self): # Issue #35721: check that newly created socket pair is closed when # Popen fails self._test_popen_error(stdin=subprocess.PIPE) def test_read_stdout_after_process_exit(self): async def execute(): code = '\n'.join(['import sys', 'for _ in range(64):', ' sys.stdout.write("x" * 4096)', 'sys.stdout.flush()', 'sys.exit(1)']) fut = asyncio.create_subprocess_exec( sys.executable, '-c', code, stdout=asyncio.subprocess.PIPE, loop=self.loop) process = await fut while True: data = await process.stdout.read(65536) if data: await asyncio.sleep(0.3, loop=self.loop) else: break self.loop.run_until_complete(execute()) if sys.platform != 'win32': # Unix class SubprocessWatcherMixin(SubprocessMixin): Watcher = None def setUp(self): super().setUp() policy = asyncio.get_event_loop_policy() self.loop = policy.new_event_loop() self.set_event_loop(self.loop) watcher = self.Watcher() watcher.attach_loop(self.loop) policy.set_child_watcher(watcher) self.addCleanup(policy.set_child_watcher, None) class SubprocessSafeWatcherTests(SubprocessWatcherMixin, test_utils.TestCase): Watcher = unix_events.SafeChildWatcher class SubprocessFastWatcherTests(SubprocessWatcherMixin, test_utils.TestCase): Watcher = unix_events.FastChildWatcher else: # Windows class SubprocessProactorTests(SubprocessMixin, test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.ProactorEventLoop() self.set_event_loop(self.loop) if __name__ == '__main__': unittest.main()
0.334481
0.183082
import argparse def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--world-size', default=-1, type=int, help='number of nodes for distributed training') parser.add_argument('--rank', default=-1, type=int, help='node rank for distributed training') parser.add_argument('--loca_rank', default=-1, type=int, help='node rank for distributed training') parser.add_argument('--dist-url', default='tcp://192.168.3.11:23456', type=str, help='url used to set up distributed training') parser.add_argument('--dist-backend', default='nccl', type=str, help='distributed backend') parser.add_argument('--seed', default=12345, type=int, help='seed for initializing training. ') parser.add_argument('--gpu', default=None, type=int, help='GPU id to use.') parser.add_argument('--multiprocessing-distributed', action='store_true', help='Use multi-processing distributed training to launch ' 'N processes per node, which has N GPUs. This is the ' 'fastest way to use PyTorch for either single node or ' 'multi node data parallel training') parser.add_argument( '--max_epoch', type=int, default=200, help='number of epochs of training') parser.add_argument( '--max_iter', type=int, default=None, help='set the max iteration number') parser.add_argument( '-gen_bs', '--gen_batch_size', type=int, default=64, help='size of the batches') parser.add_argument( '-dis_bs', '--dis_batch_size', type=int, default=64, help='size of the batches') parser.add_argument( '-bs', '--batch_size', type=int, default=64, help='size of the batches to load dataset') parser.add_argument( '--g_lr', type=float, default=0.0002, help='adam: gen learning rate') parser.add_argument( '--wd', type=float, default=0, help='adamw: gen weight decay') parser.add_argument( '--d_lr', type=float, default=0.0002, help='adam: disc learning rate') parser.add_argument( '--ctrl_lr', type=float, default=3.5e-4, help='adam: ctrl learning rate') parser.add_argument( '--lr_decay', action='store_true', help='learning rate decay or not') parser.add_argument( '--beta1', type=float, default=0.0, help='adam: decay of first order momentum of gradient') parser.add_argument( '--beta2', type=float, default=0.9, help='adam: decay of first order momentum of gradient') parser.add_argument( '--num_workers', type=int, default=8, help='number of cpu threads to use during batch generation') parser.add_argument( '--latent_dim', type=int, default=128, help='dimensionality of the latent space') parser.add_argument( '--img_size', type=int, default=32, help='size of each image dimension') parser.add_argument( '--channels', type=int, default=3, help='number of image channels') parser.add_argument( '--n_critic', type=int, default=1, help='number of training steps for discriminator per iter') parser.add_argument( '--val_freq', type=int, default=20, help='interval between each validation') parser.add_argument( '--print_freq', type=int, default=100, help='interval between each verbose') parser.add_argument( '--load_path', type=str, help='The reload model path') parser.add_argument( '--class_name', type=str, help='The class name to load in UniMiB dataset') parser.add_argument( '--augment_times', type=int, default=None, help='The times of augment signals compare to original data') parser.add_argument( '--exp_name', type=str, help='The name of exp') parser.add_argument( '--d_spectral_norm', type=str2bool, default=False, help='add spectral_norm on discriminator?') parser.add_argument( '--g_spectral_norm', type=str2bool, default=False, help='add spectral_norm on generator?') parser.add_argument( '--dataset', type=str, default='cifar10', help='dataset type') parser.add_argument( '--data_path', type=str, default='./data', help='The path of data set') parser.add_argument('--init_type', type=str, default='normal', choices=['normal', 'orth', 'xavier_uniform', 'false'], help='The init type') parser.add_argument('--gf_dim', type=int, default=64, help='The base channel num of gen') parser.add_argument('--df_dim', type=int, default=64, help='The base channel num of disc') parser.add_argument( '--gen_model', type=str, help='path of gen model') parser.add_argument( '--dis_model', type=str, help='path of dis model') parser.add_argument( '--controller', type=str, default='controller', help='path of controller') parser.add_argument('--eval_batch_size', type=int, default=100) parser.add_argument('--num_eval_imgs', type=int, default=50000) parser.add_argument( '--bottom_width', type=int, default=4, help="the base resolution of the GAN") parser.add_argument('--random_seed', type=int, default=12345) # search parser.add_argument('--shared_epoch', type=int, default=15, help='the number of epoch to train the shared gan at each search iteration') parser.add_argument('--grow_step1', type=int, default=25, help='which iteration to grow the image size from 8 to 16') parser.add_argument('--grow_step2', type=int, default=55, help='which iteration to grow the image size from 16 to 32') parser.add_argument('--max_search_iter', type=int, default=90, help='max search iterations of this algorithm') parser.add_argument('--ctrl_step', type=int, default=30, help='number of steps to train the controller at each search iteration') parser.add_argument('--ctrl_sample_batch', type=int, default=1, help='sample size of controller of each step') parser.add_argument('--hid_size', type=int, default=100, help='the size of hidden vector') parser.add_argument('--baseline_decay', type=float, default=0.9, help='baseline decay rate in RL') parser.add_argument('--rl_num_eval_img', type=int, default=5000, help='number of images to be sampled in order to get the reward') parser.add_argument('--num_candidate', type=int, default=10, help='number of candidate architectures to be sampled') parser.add_argument('--topk', type=int, default=5, help='preserve topk models architectures after each stage' ) parser.add_argument('--entropy_coeff', type=float, default=1e-3, help='to encourage the exploration') parser.add_argument('--dynamic_reset_threshold', type=float, default=1e-3, help='var threshold') parser.add_argument('--dynamic_reset_window', type=int, default=500, help='the window size') parser.add_argument('--arch', nargs='+', type=int, help='the vector of a discovered architecture') parser.add_argument('--optimizer', type=str, default="adam", help='optimizer') parser.add_argument('--loss', type=str, default="hinge", help='loss function') parser.add_argument('--n_classes', type=int, default=0, help='classes') parser.add_argument('--phi', type=float, default=1, help='wgan-gp phi') parser.add_argument('--grow_steps', nargs='+', type=int, help='the vector of a discovered architecture') parser.add_argument('--D_downsample', type=str, default="avg", help='downsampling type') parser.add_argument('--fade_in', type=float, default=1, help='fade in step') parser.add_argument('--d_depth', type=int, default=7, help='Discriminator Depth') parser.add_argument('--g_depth', type=str, default="5,4,2", help='Generator Depth') parser.add_argument('--g_norm', type=str, default="ln", help='Generator Normalization') parser.add_argument('--d_norm', type=str, default="ln", help='Discriminator Normalization') parser.add_argument('--g_act', type=str, default="gelu", help='Generator activation Layer') parser.add_argument('--d_act', type=str, default="gelu", help='Discriminator activation layer') parser.add_argument('--patch_size', type=int, default=4, help='Discriminator Depth') parser.add_argument('--fid_stat', type=str, default="None", help='Discriminator Depth') parser.add_argument('--diff_aug', type=str, default="None", help='differentiable augmentation type') parser.add_argument('--accumulated_times', type=int, default=1, help='gradient accumulation') parser.add_argument('--g_accumulated_times', type=int, default=1, help='gradient accumulation') parser.add_argument('--num_landmarks', type=int, default=64, help='number of landmarks') parser.add_argument('--d_heads', type=int, default=4, help='number of heads') parser.add_argument('--dropout', type=float, default=0., help='dropout ratio') parser.add_argument('--ema', type=float, default=0.995, help='ema') parser.add_argument('--ema_warmup', type=float, default=0., help='ema warm up') parser.add_argument('--ema_kimg', type=int, default=500, help='ema thousand images') parser.add_argument('--latent_norm',action='store_true', help='latent vector normalization') parser.add_argument('--ministd',action='store_true', help='mini batch std') parser.add_argument('--g_mlp', type=int, default=4, help='generator mlp ratio') parser.add_argument('--d_mlp', type=int, default=4, help='discriminator mlp ratio') parser.add_argument('--g_window_size', type=int, default=8, help='generator mlp ratio') parser.add_argument('--d_window_size', type=int, default=8, help='discriminator mlp ratio') parser.add_argument('--show', action='store_true', help='show') opt = parser.parse_args() return opt
cfg.py
import argparse def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--world-size', default=-1, type=int, help='number of nodes for distributed training') parser.add_argument('--rank', default=-1, type=int, help='node rank for distributed training') parser.add_argument('--loca_rank', default=-1, type=int, help='node rank for distributed training') parser.add_argument('--dist-url', default='tcp://192.168.3.11:23456', type=str, help='url used to set up distributed training') parser.add_argument('--dist-backend', default='nccl', type=str, help='distributed backend') parser.add_argument('--seed', default=12345, type=int, help='seed for initializing training. ') parser.add_argument('--gpu', default=None, type=int, help='GPU id to use.') parser.add_argument('--multiprocessing-distributed', action='store_true', help='Use multi-processing distributed training to launch ' 'N processes per node, which has N GPUs. This is the ' 'fastest way to use PyTorch for either single node or ' 'multi node data parallel training') parser.add_argument( '--max_epoch', type=int, default=200, help='number of epochs of training') parser.add_argument( '--max_iter', type=int, default=None, help='set the max iteration number') parser.add_argument( '-gen_bs', '--gen_batch_size', type=int, default=64, help='size of the batches') parser.add_argument( '-dis_bs', '--dis_batch_size', type=int, default=64, help='size of the batches') parser.add_argument( '-bs', '--batch_size', type=int, default=64, help='size of the batches to load dataset') parser.add_argument( '--g_lr', type=float, default=0.0002, help='adam: gen learning rate') parser.add_argument( '--wd', type=float, default=0, help='adamw: gen weight decay') parser.add_argument( '--d_lr', type=float, default=0.0002, help='adam: disc learning rate') parser.add_argument( '--ctrl_lr', type=float, default=3.5e-4, help='adam: ctrl learning rate') parser.add_argument( '--lr_decay', action='store_true', help='learning rate decay or not') parser.add_argument( '--beta1', type=float, default=0.0, help='adam: decay of first order momentum of gradient') parser.add_argument( '--beta2', type=float, default=0.9, help='adam: decay of first order momentum of gradient') parser.add_argument( '--num_workers', type=int, default=8, help='number of cpu threads to use during batch generation') parser.add_argument( '--latent_dim', type=int, default=128, help='dimensionality of the latent space') parser.add_argument( '--img_size', type=int, default=32, help='size of each image dimension') parser.add_argument( '--channels', type=int, default=3, help='number of image channels') parser.add_argument( '--n_critic', type=int, default=1, help='number of training steps for discriminator per iter') parser.add_argument( '--val_freq', type=int, default=20, help='interval between each validation') parser.add_argument( '--print_freq', type=int, default=100, help='interval between each verbose') parser.add_argument( '--load_path', type=str, help='The reload model path') parser.add_argument( '--class_name', type=str, help='The class name to load in UniMiB dataset') parser.add_argument( '--augment_times', type=int, default=None, help='The times of augment signals compare to original data') parser.add_argument( '--exp_name', type=str, help='The name of exp') parser.add_argument( '--d_spectral_norm', type=str2bool, default=False, help='add spectral_norm on discriminator?') parser.add_argument( '--g_spectral_norm', type=str2bool, default=False, help='add spectral_norm on generator?') parser.add_argument( '--dataset', type=str, default='cifar10', help='dataset type') parser.add_argument( '--data_path', type=str, default='./data', help='The path of data set') parser.add_argument('--init_type', type=str, default='normal', choices=['normal', 'orth', 'xavier_uniform', 'false'], help='The init type') parser.add_argument('--gf_dim', type=int, default=64, help='The base channel num of gen') parser.add_argument('--df_dim', type=int, default=64, help='The base channel num of disc') parser.add_argument( '--gen_model', type=str, help='path of gen model') parser.add_argument( '--dis_model', type=str, help='path of dis model') parser.add_argument( '--controller', type=str, default='controller', help='path of controller') parser.add_argument('--eval_batch_size', type=int, default=100) parser.add_argument('--num_eval_imgs', type=int, default=50000) parser.add_argument( '--bottom_width', type=int, default=4, help="the base resolution of the GAN") parser.add_argument('--random_seed', type=int, default=12345) # search parser.add_argument('--shared_epoch', type=int, default=15, help='the number of epoch to train the shared gan at each search iteration') parser.add_argument('--grow_step1', type=int, default=25, help='which iteration to grow the image size from 8 to 16') parser.add_argument('--grow_step2', type=int, default=55, help='which iteration to grow the image size from 16 to 32') parser.add_argument('--max_search_iter', type=int, default=90, help='max search iterations of this algorithm') parser.add_argument('--ctrl_step', type=int, default=30, help='number of steps to train the controller at each search iteration') parser.add_argument('--ctrl_sample_batch', type=int, default=1, help='sample size of controller of each step') parser.add_argument('--hid_size', type=int, default=100, help='the size of hidden vector') parser.add_argument('--baseline_decay', type=float, default=0.9, help='baseline decay rate in RL') parser.add_argument('--rl_num_eval_img', type=int, default=5000, help='number of images to be sampled in order to get the reward') parser.add_argument('--num_candidate', type=int, default=10, help='number of candidate architectures to be sampled') parser.add_argument('--topk', type=int, default=5, help='preserve topk models architectures after each stage' ) parser.add_argument('--entropy_coeff', type=float, default=1e-3, help='to encourage the exploration') parser.add_argument('--dynamic_reset_threshold', type=float, default=1e-3, help='var threshold') parser.add_argument('--dynamic_reset_window', type=int, default=500, help='the window size') parser.add_argument('--arch', nargs='+', type=int, help='the vector of a discovered architecture') parser.add_argument('--optimizer', type=str, default="adam", help='optimizer') parser.add_argument('--loss', type=str, default="hinge", help='loss function') parser.add_argument('--n_classes', type=int, default=0, help='classes') parser.add_argument('--phi', type=float, default=1, help='wgan-gp phi') parser.add_argument('--grow_steps', nargs='+', type=int, help='the vector of a discovered architecture') parser.add_argument('--D_downsample', type=str, default="avg", help='downsampling type') parser.add_argument('--fade_in', type=float, default=1, help='fade in step') parser.add_argument('--d_depth', type=int, default=7, help='Discriminator Depth') parser.add_argument('--g_depth', type=str, default="5,4,2", help='Generator Depth') parser.add_argument('--g_norm', type=str, default="ln", help='Generator Normalization') parser.add_argument('--d_norm', type=str, default="ln", help='Discriminator Normalization') parser.add_argument('--g_act', type=str, default="gelu", help='Generator activation Layer') parser.add_argument('--d_act', type=str, default="gelu", help='Discriminator activation layer') parser.add_argument('--patch_size', type=int, default=4, help='Discriminator Depth') parser.add_argument('--fid_stat', type=str, default="None", help='Discriminator Depth') parser.add_argument('--diff_aug', type=str, default="None", help='differentiable augmentation type') parser.add_argument('--accumulated_times', type=int, default=1, help='gradient accumulation') parser.add_argument('--g_accumulated_times', type=int, default=1, help='gradient accumulation') parser.add_argument('--num_landmarks', type=int, default=64, help='number of landmarks') parser.add_argument('--d_heads', type=int, default=4, help='number of heads') parser.add_argument('--dropout', type=float, default=0., help='dropout ratio') parser.add_argument('--ema', type=float, default=0.995, help='ema') parser.add_argument('--ema_warmup', type=float, default=0., help='ema warm up') parser.add_argument('--ema_kimg', type=int, default=500, help='ema thousand images') parser.add_argument('--latent_norm',action='store_true', help='latent vector normalization') parser.add_argument('--ministd',action='store_true', help='mini batch std') parser.add_argument('--g_mlp', type=int, default=4, help='generator mlp ratio') parser.add_argument('--d_mlp', type=int, default=4, help='discriminator mlp ratio') parser.add_argument('--g_window_size', type=int, default=8, help='generator mlp ratio') parser.add_argument('--d_window_size', type=int, default=8, help='discriminator mlp ratio') parser.add_argument('--show', action='store_true', help='show') opt = parser.parse_args() return opt
0.564098
0.155046
import os if os.sep==".": endsep = "/" else: endsep = "." def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ import struct # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + endsep + "pag", "rb") f.close() f = open(filename + endsep + "dir", "rb") f.close() return "dbm" except IOError: pass # Check for dumbdbm next -- this has a .dir and and a .dat file try: f = open(filename + endsep + "dat", "rb") f.close() f = open(filename + endsep + "dir", "rb") try: if f.read(1) in ["'", '"']: return "dumbdbm" finally: f.close() except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the start of the file -- the magic number s16 = f.read(16) f.close() s = s16[0:4] # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic in (0x00061561, 0x61150600): return "dbhash" # BSD hash v2 has a 12-byte NULL pad in front of the file type try: (magic,) = struct.unpack("=l", s16[-4:]) except struct.error: return "" # Check for BSD hash if magic in (0x00061561, 0x61150600): return "dbhash" # Unknown return ""
Lib/whichdb.py
import os if os.sep==".": endsep = "/" else: endsep = "." def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" or "gdbm") if recognized. Importing the given module may still fail, and opening the database using that module may still fail. """ import struct # Check for dbm first -- this has a .pag and a .dir file try: f = open(filename + endsep + "pag", "rb") f.close() f = open(filename + endsep + "dir", "rb") f.close() return "dbm" except IOError: pass # Check for dumbdbm next -- this has a .dir and and a .dat file try: f = open(filename + endsep + "dat", "rb") f.close() f = open(filename + endsep + "dir", "rb") try: if f.read(1) in ["'", '"']: return "dumbdbm" finally: f.close() except IOError: pass # See if the file exists, return None if not try: f = open(filename, "rb") except IOError: return None # Read the start of the file -- the magic number s16 = f.read(16) f.close() s = s16[0:4] # Return "" if not at least 4 bytes if len(s) != 4: return "" # Convert to 4-byte int in native byte order -- return "" if impossible try: (magic,) = struct.unpack("=l", s) except struct.error: return "" # Check for GNU dbm if magic == 0x13579ace: return "gdbm" # Check for BSD hash if magic in (0x00061561, 0x61150600): return "dbhash" # BSD hash v2 has a 12-byte NULL pad in front of the file type try: (magic,) = struct.unpack("=l", s16[-4:]) except struct.error: return "" # Check for BSD hash if magic in (0x00061561, 0x61150600): return "dbhash" # Unknown return ""
0.564819
0.143427
from __future__ import print_function import os import os.path from os.path import join import platform from setuptools import setup from setuptools import Extension from Cython.Build import cythonize home_dir = os.getenv('HOME') print('home_dir:', home_dir) torch_install_dir = os.getenv('TORCH_INSTALL') if torch_install_dir is None: raise Exception('Please ensure TORCH_INSTALL env var is defined') osfamily = platform.uname()[0] print('torch_install:', torch_install_dir) print('os family', osfamily) cython_present = True compile_options = [] osfamily = platform.uname()[0] if osfamily == 'Windows': compile_options.append('/EHsc') elif osfamily == 'Linux': compile_options.append('-std=c++0x') compile_options.append('-g') if 'DEBUG' in os.environ: compile_options.append('-O0') else: pass # put other options etc here if necessary runtime_library_dirs = [] libraries = [] # libraries.append('mylib') # libraries.append('clnnWrapper') libraries.append('TH') libraries.append('THCl') libraries.append('PyTorchNative') # libraries.append('PyTorch') library_dirs = [] library_dirs.append('cbuild') library_dirs.append(join(torch_install_dir, 'lib')) if osfamily == 'Linux': runtime_library_dirs = ['.'] if osfamily == 'Windows': libraries.append('winmm') sources = ["PyClTorch.cxx", "clnnWrapper.cpp"] if cython_present: sources = ["PyClTorch.pyx", "clnnWrapper.cpp"] ext_modules = [ Extension("PyClTorch", sources=sources, include_dirs=[ join(torch_install_dir, 'include'), join(torch_install_dir, 'include/TH'), join(torch_install_dir, 'include/THCl'), '/usr/include/lua5.1', 'pytorch/src'], library_dirs=library_dirs, libraries=libraries, extra_compile_args=compile_options, runtime_library_dirs=runtime_library_dirs, language="c++"), # Extension("GlobalState", # sources=['GlobalState.pyx'], # include_dirs=[ # home_dir + '/torch/install/include/TH', # home_dir + '/torch/install/include/THCl', # '../pytorch'], # library_dirs=library_dirs, # libraries=libraries, # extra_compile_args=compile_options, # runtime_library_dirs=runtime_library_dirs, # language="c++"), ] ext_modules = cythonize(ext_modules) setup( name='PyClTorch', version='SNAPSHOT', author="<NAME>", author_email="<EMAIL>", description=( 'Python wrappers for cltorch'), license='BSD2', url='https://github.com/hughperkins/pycltorch', long_description='', classifiers=[ ], install_requires=[], scripts=[], ext_modules=ext_modules, )
setup.py
from __future__ import print_function import os import os.path from os.path import join import platform from setuptools import setup from setuptools import Extension from Cython.Build import cythonize home_dir = os.getenv('HOME') print('home_dir:', home_dir) torch_install_dir = os.getenv('TORCH_INSTALL') if torch_install_dir is None: raise Exception('Please ensure TORCH_INSTALL env var is defined') osfamily = platform.uname()[0] print('torch_install:', torch_install_dir) print('os family', osfamily) cython_present = True compile_options = [] osfamily = platform.uname()[0] if osfamily == 'Windows': compile_options.append('/EHsc') elif osfamily == 'Linux': compile_options.append('-std=c++0x') compile_options.append('-g') if 'DEBUG' in os.environ: compile_options.append('-O0') else: pass # put other options etc here if necessary runtime_library_dirs = [] libraries = [] # libraries.append('mylib') # libraries.append('clnnWrapper') libraries.append('TH') libraries.append('THCl') libraries.append('PyTorchNative') # libraries.append('PyTorch') library_dirs = [] library_dirs.append('cbuild') library_dirs.append(join(torch_install_dir, 'lib')) if osfamily == 'Linux': runtime_library_dirs = ['.'] if osfamily == 'Windows': libraries.append('winmm') sources = ["PyClTorch.cxx", "clnnWrapper.cpp"] if cython_present: sources = ["PyClTorch.pyx", "clnnWrapper.cpp"] ext_modules = [ Extension("PyClTorch", sources=sources, include_dirs=[ join(torch_install_dir, 'include'), join(torch_install_dir, 'include/TH'), join(torch_install_dir, 'include/THCl'), '/usr/include/lua5.1', 'pytorch/src'], library_dirs=library_dirs, libraries=libraries, extra_compile_args=compile_options, runtime_library_dirs=runtime_library_dirs, language="c++"), # Extension("GlobalState", # sources=['GlobalState.pyx'], # include_dirs=[ # home_dir + '/torch/install/include/TH', # home_dir + '/torch/install/include/THCl', # '../pytorch'], # library_dirs=library_dirs, # libraries=libraries, # extra_compile_args=compile_options, # runtime_library_dirs=runtime_library_dirs, # language="c++"), ] ext_modules = cythonize(ext_modules) setup( name='PyClTorch', version='SNAPSHOT', author="<NAME>", author_email="<EMAIL>", description=( 'Python wrappers for cltorch'), license='BSD2', url='https://github.com/hughperkins/pycltorch', long_description='', classifiers=[ ], install_requires=[], scripts=[], ext_modules=ext_modules, )
0.239527
0.046747
import os import pickle from argparse import ArgumentParser import numpy as np import torch import torch.nn as nn import torch.optim as optim import tqdm from torch.nn.utils.rnn import pack_padded_sequence from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from utils.data import ECGDataset, pad_batch_sequence, save_ecg_example from utils.models import InverseCNNGenerator, DenseCritic from torch_two_sample.statistics_diff import MMDStatistic def get_argument_parser(): # TODO description to all params # parameters for training parser = ArgumentParser() parser.add_argument("--out_dir", help="Path to dir where models checkpoints, generated examples " "and tensorboard logs will be stored", type=str, default="./out") parser.add_argument("--model_name", default="dense_vs_dense_gan") # dataset params parser.add_argument("--real_dataset", help="Path to .pickle file with ecg data from prepare_data script", type=str) parser.add_argument("--real_labels", help="Path to .csv file with diagnosis labels from prepare_data script", type=str) parser.add_argument("--labels_dim", default=7, type=int) parser.add_argument("--lead_n", default=12, type=int) # general params parser.add_argument("--device", default=torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')) parser.add_argument("--n_epochs", default=2000, type=int) parser.add_argument("--batch_size", default=26, type=int) parser.add_argument("--lr", default=0.00005, type=float) # generator params parser.add_argument("--gen_h_dim", default=256, type=int) parser.add_argument("--gen_l_dim", default=100, type=int) # discriminator params parser.add_argument("--dis_h_dim", default=100, type=int) # parser.add_argument("--dis_encoder_h_dim", default=128, type=int) parser.add_argument("--continue_from", default=None, type=str) parser.add_argument("--seq_len", default=1500, type=int) return parser if __name__ == "__main__": args = get_argument_parser().parse_args() os.makedirs(os.path.join(args.out_dir, 'pictures'), exist_ok=True) os.makedirs(os.path.join(args.out_dir, 'models'), exist_ok=True) tb_path = os.path.join(args.out_dir, 'tensorboard') os.makedirs(tb_path, exist_ok=True) tb_writer = SummaryWriter(os.path.join(tb_path, args.model_name)) if torch.cuda.device_count() > 0: torch.cuda.manual_seed_all(123) torch.manual_seed(123) # init GAN models if args.continue_from: G = torch.load(open(args.continue_from, "rb"), map_location=args.device)['g_model'] G.device = args.device D = torch.load(open(args.continue_from, "rb"), map_location=args.device)['d_model'] D.device = args.device else: G = InverseCNNGenerator(noise_size=args.gen_l_dim, label_size=args.labels_dim, hidden_size=args.gen_h_dim, lead_n=args.lead_n, device=args.device) with torch.no_grad(): noise = torch.rand(args.batch_size, args.gen_l_dim, device=args.device) fake_seq = G(noise, torch.randint(low=0, high=1, size=(args.batch_size, 7),device=args.device).float()) D = DenseCritic(input_size=fake_seq.size(1), label_size=args.labels_dim, hidden_size=args.dis_h_dim, lead_n=args.lead_n, device=args.device) with torch.no_grad(): noise = torch.rand(args.batch_size, args.gen_l_dim, device=args.device) fake_seq = G(noise, torch.randint(low=0, high=1, size=(args.batch_size, 7),device=args.device).float()) # load our real examples real_data_dict = pickle.load(open(args.real_dataset, 'rb')) real_dataset = ECGDataset(real_data_dict, args.real_labels, seq_len=fake_seq.size(1)) # loss and data loader setup criterion = nn.BCELoss() mmd = MMDStatistic(args.batch_size, args.batch_size) real_data_loader = DataLoader(real_dataset, batch_size=args.batch_size, drop_last=True, shuffle=True) G_optimizer = optim.Adam(G.parameters(), lr=args.lr) D_optimizer = optim.Adam(D.parameters(), lr=args.lr) best_stat = None # train loop for epoch in tqdm.tqdm(range(args.n_epochs), position=0): # sequences in true_data_loader already padded thanks to pad_batch_sequence function stat_list = [] for real_seqs, real_labels in tqdm.tqdm(real_data_loader, position=1): torch.cuda.empty_cache() """------------------------------ Discriminator step --------------------------------------""" # Generate fake sample, real_seqs = real_seqs.to(args.device) real_labels = real_labels.to(args.device) noise = torch.rand(args.batch_size, args.gen_l_dim, device=args.device) fake_seq = G(noise, real_labels) # After that we can make predictions for our fake examples d_fake_predictions = D(fake_seq, real_labels) d_fake_target = torch.zeros_like(d_fake_predictions) # ... and real ones d_real_predictions = D(real_seqs, real_labels) d_real_target = torch.ones_like(d_real_predictions) # Now we can calculate loss for discriminator d_fake_loss = criterion(d_fake_predictions, d_fake_target) d_real_loss = criterion(d_real_predictions, d_real_target) d_loss = d_real_loss + d_fake_loss statistic = mmd(fake_seq.contiguous().view(args.batch_size, -1), real_seqs.view(args.batch_size, -1), [1.]) stat_list.append(statistic.item()) tb_writer.add_scalar("D_loss", d_loss.item(), global_step=epoch) # tb_writer.add_scalar("MMD", statistic.item(), global_step=epoch) # And make back-propagation according to calculated loss d_loss.backward() D_optimizer.step() # Housekeeping - reset gradient D_optimizer.zero_grad() G.zero_grad() """ ---------------------------- Generator step ---------------------------------------------""" # Generate fake sample noise = torch.rand(args.batch_size, args.gen_l_dim, device=args.device) fake_seq = G(noise, real_labels) # After that we can make predictions for our fake examples d_fake_predictions = D(fake_seq, real_labels) g_target = torch.ones_like(d_fake_predictions) # Now we can calculate loss for generator g_loss = criterion(d_fake_predictions, g_target) tb_writer.add_scalar("G_loss", g_loss.item(), global_step=epoch) # And make back-propagation according to calculated loss g_loss.backward() G_optimizer.step() # Housekeeping - reset gradient G_optimizer.zero_grad() D.zero_grad() # plot example and save checkpoint each odd epoch if best_stat is None: # print() best_stat = np.mean(stat_list) torch.save({ 'epoch': epoch, 'stat_value': best_stat, "d_model": D, "d_loss": d_loss, "d_optimizer": D_optimizer, "g_model": G, "g_loss": g_loss, "g_optimizer": G_optimizer, }, os.path.join(args.out_dir, f"models/{args.model_name}_best_for_mmd_checkpoint.pkl")) elif np.mean(stat_list) < best_stat: best_stat = np.mean(stat_list) torch.save({ 'epoch': epoch, 'stat_value': best_stat, "d_model": D, "d_loss": d_loss, "d_optimizer": D_optimizer, "g_model": G, "g_loss": g_loss, "g_optimizer": G_optimizer, }, os.path.join(args.out_dir, f"models/{args.model_name}_best_for_mmd_checkpoint.pkl")) tb_writer.add_scalar("MMD", np.mean(stat_list), global_step=epoch) if epoch % 50 == 0 or epoch == args.n_epochs: print(f'Epoch-{epoch}; D_loss: {d_loss.data.cpu().numpy()}; G_loss: {g_loss.data.cpu().numpy()}') torch.save({ 'epoch': epoch, 'stat_value': np.mean(stat_list), "d_model": D, "d_loss": d_loss, "d_optimizer": D_optimizer, "g_model": G, "g_loss": g_loss, "g_optimizer": G_optimizer, }, os.path.join(args.out_dir, f"models/{args.model_name}_epoch_{epoch}_checkpoint.pkl")) with torch.no_grad(): noise = torch.rand(args.batch_size, args.gen_l_dim, device=args.device) fake_seq = G(noise, real_labels) _seq = fake_seq[0].cpu().numpy() # batch_first :^) # _label = _labels[0].cpu().numpy() fig = save_ecg_example(_seq, f"pictures/{args.model_name}_epoch_{epoch}_example") tb_writer.add_figure("generated_example", fig, global_step=epoch) # TODO use visualize func here
experiments/training_scripts/cgan/cnn_vs_dense_gan_train.py
import os import pickle from argparse import ArgumentParser import numpy as np import torch import torch.nn as nn import torch.optim as optim import tqdm from torch.nn.utils.rnn import pack_padded_sequence from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from utils.data import ECGDataset, pad_batch_sequence, save_ecg_example from utils.models import InverseCNNGenerator, DenseCritic from torch_two_sample.statistics_diff import MMDStatistic def get_argument_parser(): # TODO description to all params # parameters for training parser = ArgumentParser() parser.add_argument("--out_dir", help="Path to dir where models checkpoints, generated examples " "and tensorboard logs will be stored", type=str, default="./out") parser.add_argument("--model_name", default="dense_vs_dense_gan") # dataset params parser.add_argument("--real_dataset", help="Path to .pickle file with ecg data from prepare_data script", type=str) parser.add_argument("--real_labels", help="Path to .csv file with diagnosis labels from prepare_data script", type=str) parser.add_argument("--labels_dim", default=7, type=int) parser.add_argument("--lead_n", default=12, type=int) # general params parser.add_argument("--device", default=torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')) parser.add_argument("--n_epochs", default=2000, type=int) parser.add_argument("--batch_size", default=26, type=int) parser.add_argument("--lr", default=0.00005, type=float) # generator params parser.add_argument("--gen_h_dim", default=256, type=int) parser.add_argument("--gen_l_dim", default=100, type=int) # discriminator params parser.add_argument("--dis_h_dim", default=100, type=int) # parser.add_argument("--dis_encoder_h_dim", default=128, type=int) parser.add_argument("--continue_from", default=None, type=str) parser.add_argument("--seq_len", default=1500, type=int) return parser if __name__ == "__main__": args = get_argument_parser().parse_args() os.makedirs(os.path.join(args.out_dir, 'pictures'), exist_ok=True) os.makedirs(os.path.join(args.out_dir, 'models'), exist_ok=True) tb_path = os.path.join(args.out_dir, 'tensorboard') os.makedirs(tb_path, exist_ok=True) tb_writer = SummaryWriter(os.path.join(tb_path, args.model_name)) if torch.cuda.device_count() > 0: torch.cuda.manual_seed_all(123) torch.manual_seed(123) # init GAN models if args.continue_from: G = torch.load(open(args.continue_from, "rb"), map_location=args.device)['g_model'] G.device = args.device D = torch.load(open(args.continue_from, "rb"), map_location=args.device)['d_model'] D.device = args.device else: G = InverseCNNGenerator(noise_size=args.gen_l_dim, label_size=args.labels_dim, hidden_size=args.gen_h_dim, lead_n=args.lead_n, device=args.device) with torch.no_grad(): noise = torch.rand(args.batch_size, args.gen_l_dim, device=args.device) fake_seq = G(noise, torch.randint(low=0, high=1, size=(args.batch_size, 7),device=args.device).float()) D = DenseCritic(input_size=fake_seq.size(1), label_size=args.labels_dim, hidden_size=args.dis_h_dim, lead_n=args.lead_n, device=args.device) with torch.no_grad(): noise = torch.rand(args.batch_size, args.gen_l_dim, device=args.device) fake_seq = G(noise, torch.randint(low=0, high=1, size=(args.batch_size, 7),device=args.device).float()) # load our real examples real_data_dict = pickle.load(open(args.real_dataset, 'rb')) real_dataset = ECGDataset(real_data_dict, args.real_labels, seq_len=fake_seq.size(1)) # loss and data loader setup criterion = nn.BCELoss() mmd = MMDStatistic(args.batch_size, args.batch_size) real_data_loader = DataLoader(real_dataset, batch_size=args.batch_size, drop_last=True, shuffle=True) G_optimizer = optim.Adam(G.parameters(), lr=args.lr) D_optimizer = optim.Adam(D.parameters(), lr=args.lr) best_stat = None # train loop for epoch in tqdm.tqdm(range(args.n_epochs), position=0): # sequences in true_data_loader already padded thanks to pad_batch_sequence function stat_list = [] for real_seqs, real_labels in tqdm.tqdm(real_data_loader, position=1): torch.cuda.empty_cache() """------------------------------ Discriminator step --------------------------------------""" # Generate fake sample, real_seqs = real_seqs.to(args.device) real_labels = real_labels.to(args.device) noise = torch.rand(args.batch_size, args.gen_l_dim, device=args.device) fake_seq = G(noise, real_labels) # After that we can make predictions for our fake examples d_fake_predictions = D(fake_seq, real_labels) d_fake_target = torch.zeros_like(d_fake_predictions) # ... and real ones d_real_predictions = D(real_seqs, real_labels) d_real_target = torch.ones_like(d_real_predictions) # Now we can calculate loss for discriminator d_fake_loss = criterion(d_fake_predictions, d_fake_target) d_real_loss = criterion(d_real_predictions, d_real_target) d_loss = d_real_loss + d_fake_loss statistic = mmd(fake_seq.contiguous().view(args.batch_size, -1), real_seqs.view(args.batch_size, -1), [1.]) stat_list.append(statistic.item()) tb_writer.add_scalar("D_loss", d_loss.item(), global_step=epoch) # tb_writer.add_scalar("MMD", statistic.item(), global_step=epoch) # And make back-propagation according to calculated loss d_loss.backward() D_optimizer.step() # Housekeeping - reset gradient D_optimizer.zero_grad() G.zero_grad() """ ---------------------------- Generator step ---------------------------------------------""" # Generate fake sample noise = torch.rand(args.batch_size, args.gen_l_dim, device=args.device) fake_seq = G(noise, real_labels) # After that we can make predictions for our fake examples d_fake_predictions = D(fake_seq, real_labels) g_target = torch.ones_like(d_fake_predictions) # Now we can calculate loss for generator g_loss = criterion(d_fake_predictions, g_target) tb_writer.add_scalar("G_loss", g_loss.item(), global_step=epoch) # And make back-propagation according to calculated loss g_loss.backward() G_optimizer.step() # Housekeeping - reset gradient G_optimizer.zero_grad() D.zero_grad() # plot example and save checkpoint each odd epoch if best_stat is None: # print() best_stat = np.mean(stat_list) torch.save({ 'epoch': epoch, 'stat_value': best_stat, "d_model": D, "d_loss": d_loss, "d_optimizer": D_optimizer, "g_model": G, "g_loss": g_loss, "g_optimizer": G_optimizer, }, os.path.join(args.out_dir, f"models/{args.model_name}_best_for_mmd_checkpoint.pkl")) elif np.mean(stat_list) < best_stat: best_stat = np.mean(stat_list) torch.save({ 'epoch': epoch, 'stat_value': best_stat, "d_model": D, "d_loss": d_loss, "d_optimizer": D_optimizer, "g_model": G, "g_loss": g_loss, "g_optimizer": G_optimizer, }, os.path.join(args.out_dir, f"models/{args.model_name}_best_for_mmd_checkpoint.pkl")) tb_writer.add_scalar("MMD", np.mean(stat_list), global_step=epoch) if epoch % 50 == 0 or epoch == args.n_epochs: print(f'Epoch-{epoch}; D_loss: {d_loss.data.cpu().numpy()}; G_loss: {g_loss.data.cpu().numpy()}') torch.save({ 'epoch': epoch, 'stat_value': np.mean(stat_list), "d_model": D, "d_loss": d_loss, "d_optimizer": D_optimizer, "g_model": G, "g_loss": g_loss, "g_optimizer": G_optimizer, }, os.path.join(args.out_dir, f"models/{args.model_name}_epoch_{epoch}_checkpoint.pkl")) with torch.no_grad(): noise = torch.rand(args.batch_size, args.gen_l_dim, device=args.device) fake_seq = G(noise, real_labels) _seq = fake_seq[0].cpu().numpy() # batch_first :^) # _label = _labels[0].cpu().numpy() fig = save_ecg_example(_seq, f"pictures/{args.model_name}_epoch_{epoch}_example") tb_writer.add_figure("generated_example", fig, global_step=epoch) # TODO use visualize func here
0.530723
0.137504
from __future__ import absolute_import, division, print_function, unicode_literals from urllib.parse import parse_qsl from django import forms from django.contrib import admin from django.db import connection, transaction from .constants import CHOICE_ATTRIBUTE_OPTIONS, SIMPLE_ATTRIBUTE_OPTIONS from .models import Attribute, AttributeGroup, AttributeOption, ChoiceAttribute, SimpleAttribute class AttributeGroupAdmin(admin.ModelAdmin): list_display = ('label', 'position') fields = ('label', 'position') ordering = ('position',) actions = None def has_delete_permission(self, request, obj=None): return False class AddFormMixin: def get_form(self, request, obj=None, **kwargs): """ Use special form during user creation """ defaults = {} if obj is None: if self.add_form: defaults['form'] = self.add_form else: raise ValueError('Missing `add_form` class attribute') defaults.update(kwargs) return super().get_form(request, obj, **defaults) class AttributeMixin: list_display = ('label', 'attribute_group', 'result_type', 'required', 'searchable', 'orderable', 'position') fields = ('attribute_group', 'label', 'result_type', 'position', 'required', 'searchable', 'orderable') list_filter = ('attribute_group', 'required', 'searchable', 'orderable') ordering = ('attribute_group', 'position', 'id') class AttributeAddForm(forms.ModelForm): class Meta: model = Attribute fields = () def __init__(self, *args, **kwargs): initial = kwargs.get('initial', {}) if '_changelist_filters' in initial: changelist_filters = parse_qsl(initial.get('_changelist_filters')) attribute_group_id = [ attr_id for key, attr_id in changelist_filters if key == 'attribute_group__id__exact' ][0] if attribute_group_id: attributegroup_obj = AttributeGroup.objects.get(id=attribute_group_id) kwargs['initial'].update({'attribute_group': attributegroup_obj}) super().__init__(*args, **kwargs) class SimpleAttributeAdmin(AddFormMixin, AttributeMixin, admin.ModelAdmin): add_form = AttributeAddForm actions = None def formfield_for_choice_field(self, db_field, request, **kwargs): if db_field.name == 'result_type': kwargs['choices'] = SIMPLE_ATTRIBUTE_OPTIONS return super().formfield_for_choice_field(db_field, request, **kwargs) class ChoiceAttributeAdmin(AddFormMixin, AttributeMixin, admin.ModelAdmin): add_form = AttributeAddForm actions = None def formfield_for_choice_field(self, db_field, request, **kwargs): if db_field.name == 'result_type': kwargs['choices'] = CHOICE_ATTRIBUTE_OPTIONS return super().formfield_for_choice_field(db_field, request, **kwargs) class AttributeOptionAddForm(forms.ModelForm): class Meta: model = AttributeOption fields = () def __init__(self, *args, **kwargs): initial = kwargs.get('initial', {}) if '_changelist_filters' in initial: changelist_filters = parse_qsl(initial.get('_changelist_filters')) attribute_id = [attr_id for key, attr_id in changelist_filters if key == 'attribute__id__exact'][0] if attribute_id: attribute_obj = Attribute.objects.get(id=attribute_id) kwargs['initial'].update({'attribute': attribute_obj}) super().__init__(*args, **kwargs) class AttributeOptionAdmin(AddFormMixin, admin.ModelAdmin): fields = ('attribute', 'option', 'value', 'description', 'position') list_filter = ('attribute', ) list_display = ('attribute', 'option', 'value', 'description', 'position') ordering = ('attribute', 'position') list_select_related = ('attribute', ) add_form = AttributeOptionAddForm actions = None def _perform_update(self, webuser_id, attr_name, current_option_val, new_option_val): with transaction.atomic(): with connection.cursor() as cursor: # get all features that match the criteria cursor.execute( 'select core_utils.update_dropdown_option_value(%s, %s, %s, %s);', (webuser_id, attr_name, current_option_val, new_option_val) ) def delete_model(self, request, obj): super().delete_model(request, obj) attr_name = obj.attribute.key current_option_val = obj.option new_option_val = None self._perform_update(request.user.pk, attr_name, current_option_val, new_option_val) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if change is True: attr_name = obj.attribute.key current_option_val = form.initial.get('option') new_option_val = obj.option if current_option_val != new_option_val: self._perform_update(request.user.pk, attr_name, current_option_val, new_option_val) admin.site.register(AttributeGroup, AttributeGroupAdmin) admin.site.register(SimpleAttribute, SimpleAttributeAdmin) admin.site.register(ChoiceAttribute, ChoiceAttributeAdmin) admin.site.register(AttributeOption, AttributeOptionAdmin)
django_project/src/attributes/admin.py
from __future__ import absolute_import, division, print_function, unicode_literals from urllib.parse import parse_qsl from django import forms from django.contrib import admin from django.db import connection, transaction from .constants import CHOICE_ATTRIBUTE_OPTIONS, SIMPLE_ATTRIBUTE_OPTIONS from .models import Attribute, AttributeGroup, AttributeOption, ChoiceAttribute, SimpleAttribute class AttributeGroupAdmin(admin.ModelAdmin): list_display = ('label', 'position') fields = ('label', 'position') ordering = ('position',) actions = None def has_delete_permission(self, request, obj=None): return False class AddFormMixin: def get_form(self, request, obj=None, **kwargs): """ Use special form during user creation """ defaults = {} if obj is None: if self.add_form: defaults['form'] = self.add_form else: raise ValueError('Missing `add_form` class attribute') defaults.update(kwargs) return super().get_form(request, obj, **defaults) class AttributeMixin: list_display = ('label', 'attribute_group', 'result_type', 'required', 'searchable', 'orderable', 'position') fields = ('attribute_group', 'label', 'result_type', 'position', 'required', 'searchable', 'orderable') list_filter = ('attribute_group', 'required', 'searchable', 'orderable') ordering = ('attribute_group', 'position', 'id') class AttributeAddForm(forms.ModelForm): class Meta: model = Attribute fields = () def __init__(self, *args, **kwargs): initial = kwargs.get('initial', {}) if '_changelist_filters' in initial: changelist_filters = parse_qsl(initial.get('_changelist_filters')) attribute_group_id = [ attr_id for key, attr_id in changelist_filters if key == 'attribute_group__id__exact' ][0] if attribute_group_id: attributegroup_obj = AttributeGroup.objects.get(id=attribute_group_id) kwargs['initial'].update({'attribute_group': attributegroup_obj}) super().__init__(*args, **kwargs) class SimpleAttributeAdmin(AddFormMixin, AttributeMixin, admin.ModelAdmin): add_form = AttributeAddForm actions = None def formfield_for_choice_field(self, db_field, request, **kwargs): if db_field.name == 'result_type': kwargs['choices'] = SIMPLE_ATTRIBUTE_OPTIONS return super().formfield_for_choice_field(db_field, request, **kwargs) class ChoiceAttributeAdmin(AddFormMixin, AttributeMixin, admin.ModelAdmin): add_form = AttributeAddForm actions = None def formfield_for_choice_field(self, db_field, request, **kwargs): if db_field.name == 'result_type': kwargs['choices'] = CHOICE_ATTRIBUTE_OPTIONS return super().formfield_for_choice_field(db_field, request, **kwargs) class AttributeOptionAddForm(forms.ModelForm): class Meta: model = AttributeOption fields = () def __init__(self, *args, **kwargs): initial = kwargs.get('initial', {}) if '_changelist_filters' in initial: changelist_filters = parse_qsl(initial.get('_changelist_filters')) attribute_id = [attr_id for key, attr_id in changelist_filters if key == 'attribute__id__exact'][0] if attribute_id: attribute_obj = Attribute.objects.get(id=attribute_id) kwargs['initial'].update({'attribute': attribute_obj}) super().__init__(*args, **kwargs) class AttributeOptionAdmin(AddFormMixin, admin.ModelAdmin): fields = ('attribute', 'option', 'value', 'description', 'position') list_filter = ('attribute', ) list_display = ('attribute', 'option', 'value', 'description', 'position') ordering = ('attribute', 'position') list_select_related = ('attribute', ) add_form = AttributeOptionAddForm actions = None def _perform_update(self, webuser_id, attr_name, current_option_val, new_option_val): with transaction.atomic(): with connection.cursor() as cursor: # get all features that match the criteria cursor.execute( 'select core_utils.update_dropdown_option_value(%s, %s, %s, %s);', (webuser_id, attr_name, current_option_val, new_option_val) ) def delete_model(self, request, obj): super().delete_model(request, obj) attr_name = obj.attribute.key current_option_val = obj.option new_option_val = None self._perform_update(request.user.pk, attr_name, current_option_val, new_option_val) def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) if change is True: attr_name = obj.attribute.key current_option_val = form.initial.get('option') new_option_val = obj.option if current_option_val != new_option_val: self._perform_update(request.user.pk, attr_name, current_option_val, new_option_val) admin.site.register(AttributeGroup, AttributeGroupAdmin) admin.site.register(SimpleAttribute, SimpleAttributeAdmin) admin.site.register(ChoiceAttribute, ChoiceAttributeAdmin) admin.site.register(AttributeOption, AttributeOptionAdmin)
0.631594
0.069038
from pathlib import Path import shutil import click import numpy as np import numpy.lib.format as fmt def get_header(files, axis): """get header for concatenated file Parameters ---------- files : path-like npy files to concatenate axis : int, default=0 axis to cocatenate along Returns ------- dict datatype descr, fortran order and shape, for concatenated file """ dtypes, shapes, forders = [], [], [] for file in files: f = np.load(file, 'r') dtypes.append(f.dtype) shapes.append(f.shape) forders.append(f.flags['F_CONTIGUOUS']) if all(dtype==dtypes[0] for dtype in dtypes): dtype = dtypes[0] else: raise ValueError('All files must have the same dtype') if all(forder==forders[0] for forder in forders): forder = forders[0] else: raise ValueError('All files must have the same fortran order') if all(len(shape)==len(shapes[0]) for shape in shapes): ndims = len(shapes[0]) else: raise ValueError('All files must have the same number of dimensions') if all( all(shape[axis_]==shapes[0][axis_] for shape in shapes) for axis_ in range(ndims) if axis_!=axis ): shape = list(shapes[0]) shape[axis] = sum(shape_[axis] for shape_ in shapes) shape = tuple(shape) else: raise ValueError('All files must have the same shape along the concatenation axis') header = {'descr': fmt.dtype_to_descr(dtype), 'fortran_order': forder, 'shape': shape} return header @click.command('concat') @click.argument('files', nargs=-1) @click.option('-o','--output', default='concat.bin') @click.option('-f','--force',is_flag=True,default=False) @click.option('-t','--type',default='raw',type=click.Choice(['raw','npy'])) @click.option('-a','--axis',default=0,type=int) def concat(files, output, force, type, axis): output = Path(output) files = [Path(file) for file in files] if any(not file.is_file() for file in files): raise FileNotFoundError('One or more files not found') if output.is_file() and not force: raise FileExistsError('Use -f to overwrite existing file') print('Concatenating') for idx, file in enumerate(files): print('\t', idx+1, file.name) print('Into','\n\t',output.name) with open(output, 'wb') as outputfile: if type=='npy': fmt.write_array_header_2_0(outputfile, get_header(files, axis)) for file in files: with open(file, 'rb') as inputfile: if type=='npy': inputfile.seek(128) shutil.copyfileobj(inputfile, outputfile) print('Concatenation complete')
simianpy/scripts/util/concat.py
from pathlib import Path import shutil import click import numpy as np import numpy.lib.format as fmt def get_header(files, axis): """get header for concatenated file Parameters ---------- files : path-like npy files to concatenate axis : int, default=0 axis to cocatenate along Returns ------- dict datatype descr, fortran order and shape, for concatenated file """ dtypes, shapes, forders = [], [], [] for file in files: f = np.load(file, 'r') dtypes.append(f.dtype) shapes.append(f.shape) forders.append(f.flags['F_CONTIGUOUS']) if all(dtype==dtypes[0] for dtype in dtypes): dtype = dtypes[0] else: raise ValueError('All files must have the same dtype') if all(forder==forders[0] for forder in forders): forder = forders[0] else: raise ValueError('All files must have the same fortran order') if all(len(shape)==len(shapes[0]) for shape in shapes): ndims = len(shapes[0]) else: raise ValueError('All files must have the same number of dimensions') if all( all(shape[axis_]==shapes[0][axis_] for shape in shapes) for axis_ in range(ndims) if axis_!=axis ): shape = list(shapes[0]) shape[axis] = sum(shape_[axis] for shape_ in shapes) shape = tuple(shape) else: raise ValueError('All files must have the same shape along the concatenation axis') header = {'descr': fmt.dtype_to_descr(dtype), 'fortran_order': forder, 'shape': shape} return header @click.command('concat') @click.argument('files', nargs=-1) @click.option('-o','--output', default='concat.bin') @click.option('-f','--force',is_flag=True,default=False) @click.option('-t','--type',default='raw',type=click.Choice(['raw','npy'])) @click.option('-a','--axis',default=0,type=int) def concat(files, output, force, type, axis): output = Path(output) files = [Path(file) for file in files] if any(not file.is_file() for file in files): raise FileNotFoundError('One or more files not found') if output.is_file() and not force: raise FileExistsError('Use -f to overwrite existing file') print('Concatenating') for idx, file in enumerate(files): print('\t', idx+1, file.name) print('Into','\n\t',output.name) with open(output, 'wb') as outputfile: if type=='npy': fmt.write_array_header_2_0(outputfile, get_header(files, axis)) for file in files: with open(file, 'rb') as inputfile: if type=='npy': inputfile.seek(128) shutil.copyfileobj(inputfile, outputfile) print('Concatenation complete')
0.592195
0.291371
'''Autogenerates mock interface implementations for MSHTML interfaces.''' import os import string import sys import com_mock # Adjust our module path so we can import com_mock. script_dir = os.path.abspath(os.path.dirname(__file__)) client_root = os.path.normpath(os.path.join(script_dir, '../../..')) # The interfaces we want mocked. These have to be declared in MsHTML.h, # and this will only work for IDispatch-derived interfaces. # Any interface "IFoo" named here will have a corresponding IFooMockImpl # mock implementation class in the generated output file. _INTERFACES = [ 'IHTMLDocument2', 'IHTMLDocument3', 'IHTMLDOMNode', 'IHTMLElement', 'IHTMLElementCollection', 'IHTMLStyleElement', 'IHTMLStyleSheet', 'IHTMLWindow2', ] # Find the path to the MSHTML.h include file. _MSHTML_PATH = None include_dirs = os.environ['INCLUDE'].split(';') for include_dir in include_dirs: candidate_path = os.path.join(include_dir, 'MsHTML.h') if os.path.exists(candidate_path): _MSHTML_PATH = candidate_path if not _MSHTML_PATH: print >> sys.stderr, "Could not find MsHTML.h in any INCLUDE path." sys.exit(2) # Template string for output file header. _HEADER_TEMPLATE = '''\ // This file is autogenerated by ${file} ** DO NOT EDIT ** ''' # Template string for output file footer. _FOOTER_TEMPLATE = '' # Template string for mock interface definition. _INTERFACE_TEMPLATE = '''\ class ${interface}MockImpl : public IDispatchImpl<${interface}, &IID_${interface}, &LIBID_MSHTML, 4, 0> { // Version 4.0 of the typelib. public: ${mocks} }; ''' def Main(): mocker = com_mock.Mocker() mocker.AddHeaders([_MSHTML_PATH]) header_template = string.Template(_HEADER_TEMPLATE) print header_template.substitute(file = __file__) interface_template = string.Template(_INTERFACE_TEMPLATE) for interface in _INTERFACES: mocks = '\n'.join(mocker.MockInterface(interface)) print interface_template.substitute(interface = interface, mocks = mocks) footer_template = string.Template(_FOOTER_TEMPLATE) print footer_template.substitute(file = os.path.abspath(__file__)) if __name__ == '__main__': Main()
ceee/testing/utils/mshtml_mocks.py
'''Autogenerates mock interface implementations for MSHTML interfaces.''' import os import string import sys import com_mock # Adjust our module path so we can import com_mock. script_dir = os.path.abspath(os.path.dirname(__file__)) client_root = os.path.normpath(os.path.join(script_dir, '../../..')) # The interfaces we want mocked. These have to be declared in MsHTML.h, # and this will only work for IDispatch-derived interfaces. # Any interface "IFoo" named here will have a corresponding IFooMockImpl # mock implementation class in the generated output file. _INTERFACES = [ 'IHTMLDocument2', 'IHTMLDocument3', 'IHTMLDOMNode', 'IHTMLElement', 'IHTMLElementCollection', 'IHTMLStyleElement', 'IHTMLStyleSheet', 'IHTMLWindow2', ] # Find the path to the MSHTML.h include file. _MSHTML_PATH = None include_dirs = os.environ['INCLUDE'].split(';') for include_dir in include_dirs: candidate_path = os.path.join(include_dir, 'MsHTML.h') if os.path.exists(candidate_path): _MSHTML_PATH = candidate_path if not _MSHTML_PATH: print >> sys.stderr, "Could not find MsHTML.h in any INCLUDE path." sys.exit(2) # Template string for output file header. _HEADER_TEMPLATE = '''\ // This file is autogenerated by ${file} ** DO NOT EDIT ** ''' # Template string for output file footer. _FOOTER_TEMPLATE = '' # Template string for mock interface definition. _INTERFACE_TEMPLATE = '''\ class ${interface}MockImpl : public IDispatchImpl<${interface}, &IID_${interface}, &LIBID_MSHTML, 4, 0> { // Version 4.0 of the typelib. public: ${mocks} }; ''' def Main(): mocker = com_mock.Mocker() mocker.AddHeaders([_MSHTML_PATH]) header_template = string.Template(_HEADER_TEMPLATE) print header_template.substitute(file = __file__) interface_template = string.Template(_INTERFACE_TEMPLATE) for interface in _INTERFACES: mocks = '\n'.join(mocker.MockInterface(interface)) print interface_template.substitute(interface = interface, mocks = mocks) footer_template = string.Template(_FOOTER_TEMPLATE) print footer_template.substitute(file = os.path.abspath(__file__)) if __name__ == '__main__': Main()
0.303525
0.050729
import torch import torch.nn as nn from torch.nn.utils import weight_norm from audio_zen.fvcore.nn import FlopCountAnalysis, flop_count_str class Chomp1d(nn.Module): def __init__(self, chomp_size): super(Chomp1d, self).__init__() self.chomp_size = chomp_size def forward(self, x): return x[:, :, :-self.chomp_size].contiguous() class TemporalBlock(nn.Module): def __init__(self, n_inputs, n_outputs, kernel_size, stride, dilation, padding, dropout=0.2): super(TemporalBlock, self).__init__() self.conv1 = weight_norm( nn.Conv1d(n_inputs, n_outputs, kernel_size, stride=stride, padding=padding, dilation=dilation) ) self.chomp1 = Chomp1d(padding) self.relu1 = nn.ReLU() self.dropout1 = nn.Dropout(dropout) self.conv2 = weight_norm(nn.Conv1d(n_outputs, n_outputs, kernel_size, stride=stride, padding=padding, dilation=dilation)) self.chomp2 = Chomp1d(padding) self.relu2 = nn.ReLU() self.dropout2 = nn.Dropout(dropout) self.net = nn.Sequential(self.conv1, self.chomp1, self.relu1, self.dropout1, self.conv2, self.chomp2, self.relu2, self.dropout2) self.downsample = nn.Conv1d(n_inputs, n_outputs, kernel_size=1) if n_inputs != n_outputs else None self.relu = nn.ReLU() self.init_weights() def init_weights(self): self.conv1.weight.data.normal_(0, 0.01) self.conv2.weight.data.normal_(0, 0.01) if self.downsample is not None: self.downsample.weight.data.normal_(0, 0.01) def forward(self, x): out = self.net(x) res = x if self.downsample is None else self.downsample(x) return self.relu(out + res) class TemporalConvNet(nn.Module): def __init__(self, num_inputs, num_channels, kernel_size=2, dropout=0.2): """ Args: num_inputs: num_channels: The list of all channels? kernel_size: dropout: Inputs: x - x: x has a dimension of [B, C, T] """ super(TemporalConvNet, self).__init__() layers = [] num_levels = len(num_channels) for i in range(num_levels): dilation_size = 2 ** i in_channels = num_inputs if i == 0 else num_channels[i - 1] out_channels = num_channels[i] layers += [TemporalBlock(in_channels, out_channels, kernel_size, stride=1, dilation=dilation_size, padding=(kernel_size-1) * dilation_size, dropout=dropout)] self.network = nn.Sequential(*layers) def forward(self, x): return self.network(x) class CausalConvBlock(nn.Module): def __init__(self, in_channels, out_channels, encoder_activate_function, **kwargs): """ Args: in_channels: out_channels: encoder_activate_function: **kwargs: """ super().__init__() self.conv = nn.Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 2), stride=(2, 1), padding=(0, 1), **kwargs # 这里不是左右 pad,而是上下 pad 为 0,左右分别 pad 1... ) self.norm = nn.BatchNorm2d(out_channels) self.activation = getattr(nn, encoder_activate_function)() def forward(self, x): """ 2D Causal convolution. Args: x: [B, C, F, T] Returns: [B, C, F, T] """ x = self.conv(x) x = x[:, :, :, :-1] # chomp size x = self.norm(x) x = self.activation(x) return x class CausalTransConvBlock(nn.Module): def __init__(self, in_channels, out_channels, is_last=False, output_padding=(0, 0)): super().__init__() self.conv = nn.ConvTranspose2d( in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 2), stride=(2, 1), output_padding=output_padding ) self.norm = nn.BatchNorm2d(out_channels) if is_last: self.activation = nn.ReLU() else: self.activation = nn.ELU() def forward(self, x): """ 2D Causal convolution. Args: x: [B, C, F, T] Returns: [B, C, F, T] """ x = self.conv(x) x = x[:, :, :, :-1] # chomp size x = self.norm(x) x = self.activation(x) return x
audio_zen/model/module/causal_conv.py
import torch import torch.nn as nn from torch.nn.utils import weight_norm from audio_zen.fvcore.nn import FlopCountAnalysis, flop_count_str class Chomp1d(nn.Module): def __init__(self, chomp_size): super(Chomp1d, self).__init__() self.chomp_size = chomp_size def forward(self, x): return x[:, :, :-self.chomp_size].contiguous() class TemporalBlock(nn.Module): def __init__(self, n_inputs, n_outputs, kernel_size, stride, dilation, padding, dropout=0.2): super(TemporalBlock, self).__init__() self.conv1 = weight_norm( nn.Conv1d(n_inputs, n_outputs, kernel_size, stride=stride, padding=padding, dilation=dilation) ) self.chomp1 = Chomp1d(padding) self.relu1 = nn.ReLU() self.dropout1 = nn.Dropout(dropout) self.conv2 = weight_norm(nn.Conv1d(n_outputs, n_outputs, kernel_size, stride=stride, padding=padding, dilation=dilation)) self.chomp2 = Chomp1d(padding) self.relu2 = nn.ReLU() self.dropout2 = nn.Dropout(dropout) self.net = nn.Sequential(self.conv1, self.chomp1, self.relu1, self.dropout1, self.conv2, self.chomp2, self.relu2, self.dropout2) self.downsample = nn.Conv1d(n_inputs, n_outputs, kernel_size=1) if n_inputs != n_outputs else None self.relu = nn.ReLU() self.init_weights() def init_weights(self): self.conv1.weight.data.normal_(0, 0.01) self.conv2.weight.data.normal_(0, 0.01) if self.downsample is not None: self.downsample.weight.data.normal_(0, 0.01) def forward(self, x): out = self.net(x) res = x if self.downsample is None else self.downsample(x) return self.relu(out + res) class TemporalConvNet(nn.Module): def __init__(self, num_inputs, num_channels, kernel_size=2, dropout=0.2): """ Args: num_inputs: num_channels: The list of all channels? kernel_size: dropout: Inputs: x - x: x has a dimension of [B, C, T] """ super(TemporalConvNet, self).__init__() layers = [] num_levels = len(num_channels) for i in range(num_levels): dilation_size = 2 ** i in_channels = num_inputs if i == 0 else num_channels[i - 1] out_channels = num_channels[i] layers += [TemporalBlock(in_channels, out_channels, kernel_size, stride=1, dilation=dilation_size, padding=(kernel_size-1) * dilation_size, dropout=dropout)] self.network = nn.Sequential(*layers) def forward(self, x): return self.network(x) class CausalConvBlock(nn.Module): def __init__(self, in_channels, out_channels, encoder_activate_function, **kwargs): """ Args: in_channels: out_channels: encoder_activate_function: **kwargs: """ super().__init__() self.conv = nn.Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 2), stride=(2, 1), padding=(0, 1), **kwargs # 这里不是左右 pad,而是上下 pad 为 0,左右分别 pad 1... ) self.norm = nn.BatchNorm2d(out_channels) self.activation = getattr(nn, encoder_activate_function)() def forward(self, x): """ 2D Causal convolution. Args: x: [B, C, F, T] Returns: [B, C, F, T] """ x = self.conv(x) x = x[:, :, :, :-1] # chomp size x = self.norm(x) x = self.activation(x) return x class CausalTransConvBlock(nn.Module): def __init__(self, in_channels, out_channels, is_last=False, output_padding=(0, 0)): super().__init__() self.conv = nn.ConvTranspose2d( in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 2), stride=(2, 1), output_padding=output_padding ) self.norm = nn.BatchNorm2d(out_channels) if is_last: self.activation = nn.ReLU() else: self.activation = nn.ELU() def forward(self, x): """ 2D Causal convolution. Args: x: [B, C, F, T] Returns: [B, C, F, T] """ x = self.conv(x) x = x[:, :, :, :-1] # chomp size x = self.norm(x) x = self.activation(x) return x
0.953449
0.419707
import cPickle from fltk import * Fl.scheme('plastic') class Subject: def __init__(self): self.observers = [] def attach(self, observer): self.observers.append(observer) def detach(self, observer): self.observers.remove(observer) def notify(self, event=None): for observer in self.observers: observer.update(event, self) class Observer: def update(self, event, subject): raise NotImplementedError("Must subclass me") class BaseSettings: def __init__(self): self.x = 100; self.y = 100; self.w = 800; self.h = 650 def load(self, fileName): try: self.__dict__.update(cPickle.load(open(fileName, 'r')).__dict__) except: pass def save(self, fileName): cPickle.dump(self, open(fileName, 'w')) def setToApp(self, window): window.position(self.x, self.y) window.size(self.w, self.h) def getFromApp(self, window): self.x = window.x(); self.y = window.y(); self.w = window.w(); self.h = window.h() class BaseWnd(Fl_Window): def __init__(self, rect=None, title='BaseWnd', settings=BaseSettings()): Fl_Window.__init__(self, 100, 100, 600, 400, title) self.settingsFile = '' if rect == None: self.settingsFile = title+'.settings' else: self.position(rect[0], rect[1]) self.size(rect[2], rect[3]) # self.settingsFile = title+'.settings' # if rect[0]!=None and rect[1]!=None: # self.position(rect[0], rect[1]) # if rect[2]!=None and rect[3]!=None: # self.size(rect[2], rect[3]) self.settings = settings self.callback(self.onClose) def show(self): if len(self.settingsFile)>0: self.settings.load(self.settingsFile) self.settings.setToApp(self) Fl_Window.show(self) def onClose(self, data): if len(self.settingsFile)>0: self.settings.getFromApp(self) self.settings.save(self.settingsFile) self.default_callback(self, data)
PyCommon/modules/GUI/ysBaseUI.py
import cPickle from fltk import * Fl.scheme('plastic') class Subject: def __init__(self): self.observers = [] def attach(self, observer): self.observers.append(observer) def detach(self, observer): self.observers.remove(observer) def notify(self, event=None): for observer in self.observers: observer.update(event, self) class Observer: def update(self, event, subject): raise NotImplementedError("Must subclass me") class BaseSettings: def __init__(self): self.x = 100; self.y = 100; self.w = 800; self.h = 650 def load(self, fileName): try: self.__dict__.update(cPickle.load(open(fileName, 'r')).__dict__) except: pass def save(self, fileName): cPickle.dump(self, open(fileName, 'w')) def setToApp(self, window): window.position(self.x, self.y) window.size(self.w, self.h) def getFromApp(self, window): self.x = window.x(); self.y = window.y(); self.w = window.w(); self.h = window.h() class BaseWnd(Fl_Window): def __init__(self, rect=None, title='BaseWnd', settings=BaseSettings()): Fl_Window.__init__(self, 100, 100, 600, 400, title) self.settingsFile = '' if rect == None: self.settingsFile = title+'.settings' else: self.position(rect[0], rect[1]) self.size(rect[2], rect[3]) # self.settingsFile = title+'.settings' # if rect[0]!=None and rect[1]!=None: # self.position(rect[0], rect[1]) # if rect[2]!=None and rect[3]!=None: # self.size(rect[2], rect[3]) self.settings = settings self.callback(self.onClose) def show(self): if len(self.settingsFile)>0: self.settings.load(self.settingsFile) self.settings.setToApp(self) Fl_Window.show(self) def onClose(self, data): if len(self.settingsFile)>0: self.settings.getFromApp(self) self.settings.save(self.settingsFile) self.default_callback(self, data)
0.18451
0.065247
class MkldnnTest(object): mkldnn_target_test_filename = 'mkl-dnn-c' def __init__(self, target): self.target = target def tear_down(self): self.target.run('rm /tmp/%s' % self.mkldnn_target_test_filename) def test_mkldnn_can_compile_and_execute(self): mkldnn_src_dir = '/usr/src/debug/onednn/' mkldnn_src_test_filename = 'api.c' mkldnn_src_test_file = '' (__, output) = self.target.run('cd %s; find -name %s' % (mkldnn_src_dir, mkldnn_src_test_filename)) if 'No such file or directory' in output: return -1, output mkldnn_src_test_file = os.path.join(mkldnn_src_dir, output) (status, output) = self.target.run('gcc %s -o /tmp/%s -ldnnl' % (mkldnn_src_test_file, self.mkldnn_target_test_filename)) if status: return status, output (status, output) = self.target.run('cd /tmp; ./%s' % self.mkldnn_target_test_filename) return status, output def test_mkldnn_benchdnn_package_available(self): (status, output) = self.target.run('ls /usr/bin/mkl-dnn/tests/benchdnn') return status, output def _run_mkldnn_benchdnn_test(self, cmd): (status, output) = self.target.run('cd /usr/bin/mkl-dnn/tests/benchdnn; %s' % cmd) return status, output def test_mkldnn_conv_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --conv --batch=inputs/conv/test_conv_3d') def test_mkldnn_bnorm_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --bnorm --batch=inputs/bnorm/test_bnorm_regressions') def test_mkldnn_deconv_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --deconv --batch=inputs/deconv/test_deconv_bfloat16') def test_mkldnn_ip_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --ip --batch=inputs/ip/test_ip_bfloat16') def test_mkldnn_reorder_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --reorder --batch=inputs/reorder/test_reorder_bfloat16') def test_mkldnn_rnn_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --rnn --batch=inputs/rnn/test_rnn_all') def test_mkldnn_shuffle_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --shuffle --batch=inputs/shuffle/test_shuffle_bfloat16')
lib/oeqa/runtime/miutils/tests/mkl_dnn_test.py
class MkldnnTest(object): mkldnn_target_test_filename = 'mkl-dnn-c' def __init__(self, target): self.target = target def tear_down(self): self.target.run('rm /tmp/%s' % self.mkldnn_target_test_filename) def test_mkldnn_can_compile_and_execute(self): mkldnn_src_dir = '/usr/src/debug/onednn/' mkldnn_src_test_filename = 'api.c' mkldnn_src_test_file = '' (__, output) = self.target.run('cd %s; find -name %s' % (mkldnn_src_dir, mkldnn_src_test_filename)) if 'No such file or directory' in output: return -1, output mkldnn_src_test_file = os.path.join(mkldnn_src_dir, output) (status, output) = self.target.run('gcc %s -o /tmp/%s -ldnnl' % (mkldnn_src_test_file, self.mkldnn_target_test_filename)) if status: return status, output (status, output) = self.target.run('cd /tmp; ./%s' % self.mkldnn_target_test_filename) return status, output def test_mkldnn_benchdnn_package_available(self): (status, output) = self.target.run('ls /usr/bin/mkl-dnn/tests/benchdnn') return status, output def _run_mkldnn_benchdnn_test(self, cmd): (status, output) = self.target.run('cd /usr/bin/mkl-dnn/tests/benchdnn; %s' % cmd) return status, output def test_mkldnn_conv_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --conv --batch=inputs/conv/test_conv_3d') def test_mkldnn_bnorm_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --bnorm --batch=inputs/bnorm/test_bnorm_regressions') def test_mkldnn_deconv_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --deconv --batch=inputs/deconv/test_deconv_bfloat16') def test_mkldnn_ip_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --ip --batch=inputs/ip/test_ip_bfloat16') def test_mkldnn_reorder_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --reorder --batch=inputs/reorder/test_reorder_bfloat16') def test_mkldnn_rnn_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --rnn --batch=inputs/rnn/test_rnn_all') def test_mkldnn_shuffle_api(self): return self._run_mkldnn_benchdnn_test('./benchdnn --shuffle --batch=inputs/shuffle/test_shuffle_bfloat16')
0.302906
0.147187
from django.db import models from archfinch.main.models import Item, SlicedRawManager from archfinch.users.models import User from archfinch.links.thresholds import * class LinkManager(SlicedRawManager): def recommended_generic(self, category=None, tags=None, new=False): ''' Fetches links recommended generally (not for a specific user). ''' where = [] params = {} if category is not None: where.append('mi.category_id = %(category_id)s') params['category_id'] = category.id if tags: for tag in tags: where.append('EXISTS (SELECT 1 FROM main_tagged mtgd WHERE mi.id = mtgd.item_id AND mtgd.tag_id = %d)' % (int(tag.id))) elif not new: # front page where.append('wilson_score(mi.id, true) >= %(threshold_frontpage)s') params['threshold_frontpage'] = threshold_frontpage if where: where = 'WHERE '+' AND '.join(where) else: where = '' # Select items in order of their recommendation to self # # recommendation = # sum (rating-3)*similarity for all similar users # # where # rating: what the user has rated the item # similarity: similarity between the user and self recommended = Link.objects.slicedraw(""" SELECT * FROM (SELECT mi.id, mi.category_id, mi.parent_id, mi.name, ll.item_ptr_id, ll.time, mc.element_singular AS category_element FROM main_item mi INNER JOIN main_category mc ON mc.id=mi.category_id INNER JOIN links_link ll ON ll.item_ptr_id=mi.id """+where+""" ORDER BY time DESC) AS recommended""", params) return recommended def recommended(self, user, category=None, category_id=None, tags=None, followed=False, new=False): ''' Fetches links recommended for the user. ''' where = '' joins = '' params = {'user_id': user.id} if category is not None and category: category_id = category.id if category_id is not None: where += ' AND mi.category_id = %(category_id)s' params['category_id'] = category_id followed_or = False show_submissions = False if tags: for tag in tags: where += ' AND EXISTS (SELECT 1 FROM main_tagged mtgd WHERE mi.id = mtgd.item_id AND mtgd.tag_id = %d)' % (int(tag.id)) elif not followed and not new: # front page where += ' AND wilson_score(mi.id, true) >= %(threshold_frontpage)s' params['threshold_frontpage'] = threshold_frontpage # add the user's follows to their frontpage followed = True followed_or = True show_submissions = True if followed and user.tagfollow_set.exists(): if followed_or: where += ' OR' else: where += ' AND' where += ' EXISTS (SELECT 1 FROM main_tagged mtgd WHERE mi.id = mtgd.item_id AND mtgd.tag_id in %(followed_tag_ids)s)' params['followed_tag_ids'] = tuple(map(lambda follow: follow.tag.id, user.tagfollow_set.all())) if show_submissions: where += ' OR mi.submitter_id = %(user_id)s' # Select items in order of their recommendation to self # # recommendation = # sum (rating-3)*similarity for all similar users # # where # rating: what the user has rated the item # similarity: similarity between the user and self recommended = Link.objects.slicedraw(""" SELECT mi.id, mi.category_id, mi.parent_id, mi.name, ll.item_ptr_id, ll.time, mis.comment_count, mis.popular_tags as _popular_tags, url, image, submitter_id, au.username AS submitter_username, COALESCE((SELECT rating FROM main_opinion mo WHERE mo.user_id=%(user_id)s AND mo.item_id=mi.id)) AS rating, mc.element_singular AS category_element FROM main_item mi INNER JOIN main_category mc ON mc.id=mi.category_id INNER JOIN links_link ll ON ll.item_ptr_id=mi.id INNER JOIN main_itemstats mis ON mi.id=mis.item_id INNER JOIN auth_user au ON au.id=mi.submitter_id WHERE NOT EXISTS (SELECT 1 FROM main_tagblock mtb, main_tagged mtgd WHERE mtgd.tag_id=mtb.tag_id AND mtb.user_id=%(user_id)s AND mtgd.item_id=ll.item_ptr_id) """+where+""" ORDER BY time DESC """, params) return recommended class ImageURLField(models.CharField): """Image URL field, stored as url,width,height in the database""" __metaclass__ = models.SubfieldBase def to_python(self, value): if value is None: return if not isinstance(value, basestring): return value fields = value.split(',') if len(fields) < 3: return {'url': fields[0]} return {'url': fields[0], 'width': int(fields[1]), 'height': int(fields[2])} def get_prep_value(self, value): if value is None: return try: return ','.join([value['url'], str(value['width']), str(value['height'])]) except KeyError: return value['url'] class Link(Item): url = models.URLField(verify_exists=False, max_length=1000, blank=True, null=True) time = models.DateTimeField(auto_now_add=True, unique=False) thumbnail = ImageURLField(max_length=1000, blank=True, null=True) image = ImageURLField(max_length=1000, blank=True, null=True) html = models.TextField(max_length=1000, blank=True, null=True) objects = LinkManager() def age(self): import datetime age = (datetime.datetime.now() - self.time) return age.seconds+age.days*60*60*24 def views(self): age = self.age() multiplier = 113 + self.id % 20 if age < 15*60: views = (age/900.)**2 * multiplier elif age < 60*60*24: views = (age/900.) * multiplier else: views = 96 * multiplier + age/360. return int(views)
links/models.py
from django.db import models from archfinch.main.models import Item, SlicedRawManager from archfinch.users.models import User from archfinch.links.thresholds import * class LinkManager(SlicedRawManager): def recommended_generic(self, category=None, tags=None, new=False): ''' Fetches links recommended generally (not for a specific user). ''' where = [] params = {} if category is not None: where.append('mi.category_id = %(category_id)s') params['category_id'] = category.id if tags: for tag in tags: where.append('EXISTS (SELECT 1 FROM main_tagged mtgd WHERE mi.id = mtgd.item_id AND mtgd.tag_id = %d)' % (int(tag.id))) elif not new: # front page where.append('wilson_score(mi.id, true) >= %(threshold_frontpage)s') params['threshold_frontpage'] = threshold_frontpage if where: where = 'WHERE '+' AND '.join(where) else: where = '' # Select items in order of their recommendation to self # # recommendation = # sum (rating-3)*similarity for all similar users # # where # rating: what the user has rated the item # similarity: similarity between the user and self recommended = Link.objects.slicedraw(""" SELECT * FROM (SELECT mi.id, mi.category_id, mi.parent_id, mi.name, ll.item_ptr_id, ll.time, mc.element_singular AS category_element FROM main_item mi INNER JOIN main_category mc ON mc.id=mi.category_id INNER JOIN links_link ll ON ll.item_ptr_id=mi.id """+where+""" ORDER BY time DESC) AS recommended""", params) return recommended def recommended(self, user, category=None, category_id=None, tags=None, followed=False, new=False): ''' Fetches links recommended for the user. ''' where = '' joins = '' params = {'user_id': user.id} if category is not None and category: category_id = category.id if category_id is not None: where += ' AND mi.category_id = %(category_id)s' params['category_id'] = category_id followed_or = False show_submissions = False if tags: for tag in tags: where += ' AND EXISTS (SELECT 1 FROM main_tagged mtgd WHERE mi.id = mtgd.item_id AND mtgd.tag_id = %d)' % (int(tag.id)) elif not followed and not new: # front page where += ' AND wilson_score(mi.id, true) >= %(threshold_frontpage)s' params['threshold_frontpage'] = threshold_frontpage # add the user's follows to their frontpage followed = True followed_or = True show_submissions = True if followed and user.tagfollow_set.exists(): if followed_or: where += ' OR' else: where += ' AND' where += ' EXISTS (SELECT 1 FROM main_tagged mtgd WHERE mi.id = mtgd.item_id AND mtgd.tag_id in %(followed_tag_ids)s)' params['followed_tag_ids'] = tuple(map(lambda follow: follow.tag.id, user.tagfollow_set.all())) if show_submissions: where += ' OR mi.submitter_id = %(user_id)s' # Select items in order of their recommendation to self # # recommendation = # sum (rating-3)*similarity for all similar users # # where # rating: what the user has rated the item # similarity: similarity between the user and self recommended = Link.objects.slicedraw(""" SELECT mi.id, mi.category_id, mi.parent_id, mi.name, ll.item_ptr_id, ll.time, mis.comment_count, mis.popular_tags as _popular_tags, url, image, submitter_id, au.username AS submitter_username, COALESCE((SELECT rating FROM main_opinion mo WHERE mo.user_id=%(user_id)s AND mo.item_id=mi.id)) AS rating, mc.element_singular AS category_element FROM main_item mi INNER JOIN main_category mc ON mc.id=mi.category_id INNER JOIN links_link ll ON ll.item_ptr_id=mi.id INNER JOIN main_itemstats mis ON mi.id=mis.item_id INNER JOIN auth_user au ON au.id=mi.submitter_id WHERE NOT EXISTS (SELECT 1 FROM main_tagblock mtb, main_tagged mtgd WHERE mtgd.tag_id=mtb.tag_id AND mtb.user_id=%(user_id)s AND mtgd.item_id=ll.item_ptr_id) """+where+""" ORDER BY time DESC """, params) return recommended class ImageURLField(models.CharField): """Image URL field, stored as url,width,height in the database""" __metaclass__ = models.SubfieldBase def to_python(self, value): if value is None: return if not isinstance(value, basestring): return value fields = value.split(',') if len(fields) < 3: return {'url': fields[0]} return {'url': fields[0], 'width': int(fields[1]), 'height': int(fields[2])} def get_prep_value(self, value): if value is None: return try: return ','.join([value['url'], str(value['width']), str(value['height'])]) except KeyError: return value['url'] class Link(Item): url = models.URLField(verify_exists=False, max_length=1000, blank=True, null=True) time = models.DateTimeField(auto_now_add=True, unique=False) thumbnail = ImageURLField(max_length=1000, blank=True, null=True) image = ImageURLField(max_length=1000, blank=True, null=True) html = models.TextField(max_length=1000, blank=True, null=True) objects = LinkManager() def age(self): import datetime age = (datetime.datetime.now() - self.time) return age.seconds+age.days*60*60*24 def views(self): age = self.age() multiplier = 113 + self.id % 20 if age < 15*60: views = (age/900.)**2 * multiplier elif age < 60*60*24: views = (age/900.) * multiplier else: views = 96 * multiplier + age/360. return int(views)
0.331877
0.122392
import traceback import sys import time import datetime import string import sqlite3 '''USER CONFIGURATION''' #TIMESTAMP = '%A %d %B %Y' TIMESTAMP = '%a %d %b %Y' #The time format. # "%A %d %B %Y" = "Wendesday 04 June 2014" #http://docs.python.org/2/library/time.html#time.strftime HEADER = "" #Put this at the top of the .txt file FORMAT = "_timestamp_: [_title_](_slink_) - /u/_author_ (+_score_)" FORMAT_HTML = "_timestamp_: <a href=\"_shortlink_\">[_flairtext_] _title_</a> - <a href=\"_authorlink_\">_author_</a> (+_score_)<br>" HTMLHEADER = '<html style="font-family:Consolas;font-size:10pt;">' TSFORMAT = "" #USE THESE INJECTORS TO CREATE CUSTOM OUTPUT #_timestamp_ which follows the TIMESTAMP format #_title_ #_url_ #_subreddit_ #_shortlink_ #_author_ #_authorlink_ #_numcomments_ #_score_ #_flairtext_ #_flaircss_ READ_FROM_FILE = "" PRINTFILE = "" SCORETHRESH = 0 HTMLMODE = False USERMODE = False BREAKDOWNMODE = False EXTENSION = '.txt' # Variables are input by user during the # inputvars() method '''All done!''' class Post: #Generic class to convert SQL columns into an object pass sql = None cur = None # 0 - idint # 1 - idstr # 2 - created # 3 - self # 4 - nsfw # 5 - author # 6 - title # 7 - url # 8 - selftext # 9 - score # 10 - subreddit # 11 - distinguished # 12 - textlen # 13 - num_comments # 14 - flair_text # 15 - flair_css_class def createpost(postdata): post = Post() post.id = postdata[1] if 't3_' in post.id or 't1_' in post.id: post.fullname = post.id post.id = post.id.split('_')[1] else: post.fullname = 't3_' + post.id post.type = int(post.fullname.split('_')[0][-1]) post.created_utc = postdata[2] post.is_self = postdata[3] post.over_18 = postdata[4] post.author = postdata[5] post.title = postdata[6] post.title = post.title.replace('\n', '') post.url = postdata[7] post.selftext = postdata[8] post.score = postdata[9] post.subreddit = postdata[10] post.distinguished = postdata[11] post.textlen = postdata[12] post.num_comments = postdata[13] post.link_flair_text = postdata[14] post.link_flair_css_class = postdata[15] post.short_link = 'http://redd.it/' + post.id return post def preparefile(filesuffix): filesuffix += EXTENSION listfile = open(PRINTFILE + filesuffix, 'w', encoding='utf-8') if HTMLMODE is True: print(HTMLHEADER, file=listfile) return listfile def closefile(listfile): if HTMLMODE is True: print('</html>', file=listfile) listfile.close() def work(listfile): if HEADER != '': print(HEADER, file=listfile) previous_timestamp = '' while True: post = cur.fetchone() if post is None: break post = createpost(post) if post.score < SCORETHRESH: continue if post.type != 3: continue timestamp = post.created_utc timestamp = datetime.datetime.fromtimestamp(int(timestamp)).strftime(TIMESTAMP) if HTMLMODE: final = FORMAT_HTML else: final = FORMAT if timestamp != previous_timestamp: final = TSFORMAT + final final = final.replace('_timestamp_', timestamp) final = final.replace('_title_', post.title) flair_text = post.link_flair_text if post.link_flair_text else "" flair_css = post.link_flair_css_class if post.link_flair_css_class else "" post.link_flair_text = flair_text post.link_flair_css_class = flair_css final = final.replace('_flairtext_', flair_text) final = final.replace('_flaircss_', flair_css) authorlink = 'http://reddit.com/u/' + post.author final = final.replace('_author_', post.author) final = final.replace('_authorlink_', authorlink) final = final.replace('_subreddit_', post.subreddit) url = post.url if url is None: url = post.short_link else: url = url.replace('http://www.reddit.com', 'http://np.reddit.com') final = final.replace('_url_', url) shortlink = post.short_link #slink = slink.replace('http://', 'http://np.') final = final.replace('_slink_', shortlink) final = final.replace('_flairtext_', flair_text) final = final.replace('_score_', str(post.score)) final = final.replace('_numcomments_', str(post.num_comments)) print(final, file=listfile) previous_timestamp = timestamp def writefiles(): print('Writing time files') listfile = preparefile('_date') cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY created DESC', [SCORETHRESH]) work(listfile) closefile(listfile) print('Writing title files') listfile = preparefile('_title') cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY title ASC', [SCORETHRESH]) work(listfile) closefile(listfile) print('Writing score files') listfile = preparefile('_score') cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY score DESC', [SCORETHRESH]) work(listfile) closefile(listfile) if USERMODE is False: print('Writing author files') listfile = preparefile('_author') cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY author ASC', [SCORETHRESH]) work(listfile) closefile(listfile) if USERMODE is True: print('Writing subreddit files') listfile = preparefile('_subreddit') cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY subreddit ASC', [SCORETHRESH]) work(listfile) closefile(listfile) print('Writing flair file') listfile = preparefile('_flair') cur.execute('SELECT * FROM posts WHERE score >= ? AND flair_text IS NOT NULL ORDER BY flair_text, created ASC', [SCORETHRESH]) work(listfile) cur.execute('SELECT * FROM posts WHERE score >= ? AND flair_text IS NULL ORDER BY flair_text, created ASC', [SCORETHRESH]) work(listfile) closefile(listfile) print('Done.') def breakdown(doreturn=False, mode='user'): print('\nBreaking it down...') listfile = preparefile('') if mode == 'subreddit': cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY author ASC', [SCORETHRESH]) if mode == 'user': cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY subreddit ASC', [SCORETHRESH]) count_submissions = 0 count_comments = 0 previous = '' breakdowndict = {} while True: post = cur.fetchone() if post is None: breakdowndict[previous] = {'submissions':count_submissions, 'comments':count_comments} break post = createpost(post) if mode == 'subreddit': relevant = post.author elif mode == 'user': relevant = post.subreddit if relevant != previous: breakdowndict[previous] = {'submissions':count_submissions, 'comments':count_comments} previous = relevant count_submissions = 0 count_comments = 0 if post.type == 1: count_comments += 1 if post.type == 3: count_submissions += 1 del breakdowndict[''] if doreturn is True: return breakdowndict keys = list(breakdowndict.keys()) longestkey = max([len(k) for k in keys]) keys.sort(key=lambda x: (breakdowndict[x]['submissions'] + breakdowndict[x]['comments'], x), reverse=True) out = [] for k in keys: relevant = (' '*(longestkey-len(k))) + ('"%s"' % k) submissions = breakdowndict[k]['submissions'] comments = breakdowndict[k]['comments'] o = '%s:{%s:%d, %s:%d}' % (relevant, '"submissions"', submissions, '"comments"', comments) out.append(o) out = ',\n'.join(out) out = '{\n' + out + '\n}' print(out, file=listfile) #json.dump(breakdowndict, listfile, sort_keys=True, indent=4) def inputvars(): global READ_FROM_FILE global PRINTFILE global SCORETHRESH global HTMLMODE global USERMODE global BREAKDOWNMODE global EXTENSION global sql global cur try: READ_FROM_FILE = sys.argv[1] except IndexError: READ_FROM_FILE = input('] Input database = ') if READ_FROM_FILE[-3:] != '.db': READ_FROM_FILE += '.db' filename = READ_FROM_FILE.replace('\\', '/') filename = filename.split('/')[-1] if filename[0] == '@': USERMODE = True try: PRINTFILE = sys.argv[2] except IndexError: PRINTFILE = input('] Output filename = ') try: SCORETHRESH = int(sys.argv[3]) except IndexError: SCORETHRESH = int(input('] Score threshold = ')) HTMLMODE = '.html' in PRINTFILE BREAKDOWNMODE = '.json' in PRINTFILE if HTMLMODE: EXTENSION = '.html' PRINTFILE = PRINTFILE.replace('.html', '') elif BREAKDOWNMODE: EXTENSION = '.json' PRINTFILE = PRINTFILE.replace('.json', '') else: EXTENSION = '.txt' PRINTFILE = PRINTFILE.replace('.txt', '') sql = sqlite3.connect(READ_FROM_FILE) cur = sql.cursor() def main(): inputvars() if BREAKDOWNMODE is False: writefiles() else: if USERMODE is True: breakdown(mode='user') else: breakdown(mode='subreddit') if __name__ == '__main__': main()
Redmash/redmash_db.py
import traceback import sys import time import datetime import string import sqlite3 '''USER CONFIGURATION''' #TIMESTAMP = '%A %d %B %Y' TIMESTAMP = '%a %d %b %Y' #The time format. # "%A %d %B %Y" = "Wendesday 04 June 2014" #http://docs.python.org/2/library/time.html#time.strftime HEADER = "" #Put this at the top of the .txt file FORMAT = "_timestamp_: [_title_](_slink_) - /u/_author_ (+_score_)" FORMAT_HTML = "_timestamp_: <a href=\"_shortlink_\">[_flairtext_] _title_</a> - <a href=\"_authorlink_\">_author_</a> (+_score_)<br>" HTMLHEADER = '<html style="font-family:Consolas;font-size:10pt;">' TSFORMAT = "" #USE THESE INJECTORS TO CREATE CUSTOM OUTPUT #_timestamp_ which follows the TIMESTAMP format #_title_ #_url_ #_subreddit_ #_shortlink_ #_author_ #_authorlink_ #_numcomments_ #_score_ #_flairtext_ #_flaircss_ READ_FROM_FILE = "" PRINTFILE = "" SCORETHRESH = 0 HTMLMODE = False USERMODE = False BREAKDOWNMODE = False EXTENSION = '.txt' # Variables are input by user during the # inputvars() method '''All done!''' class Post: #Generic class to convert SQL columns into an object pass sql = None cur = None # 0 - idint # 1 - idstr # 2 - created # 3 - self # 4 - nsfw # 5 - author # 6 - title # 7 - url # 8 - selftext # 9 - score # 10 - subreddit # 11 - distinguished # 12 - textlen # 13 - num_comments # 14 - flair_text # 15 - flair_css_class def createpost(postdata): post = Post() post.id = postdata[1] if 't3_' in post.id or 't1_' in post.id: post.fullname = post.id post.id = post.id.split('_')[1] else: post.fullname = 't3_' + post.id post.type = int(post.fullname.split('_')[0][-1]) post.created_utc = postdata[2] post.is_self = postdata[3] post.over_18 = postdata[4] post.author = postdata[5] post.title = postdata[6] post.title = post.title.replace('\n', '') post.url = postdata[7] post.selftext = postdata[8] post.score = postdata[9] post.subreddit = postdata[10] post.distinguished = postdata[11] post.textlen = postdata[12] post.num_comments = postdata[13] post.link_flair_text = postdata[14] post.link_flair_css_class = postdata[15] post.short_link = 'http://redd.it/' + post.id return post def preparefile(filesuffix): filesuffix += EXTENSION listfile = open(PRINTFILE + filesuffix, 'w', encoding='utf-8') if HTMLMODE is True: print(HTMLHEADER, file=listfile) return listfile def closefile(listfile): if HTMLMODE is True: print('</html>', file=listfile) listfile.close() def work(listfile): if HEADER != '': print(HEADER, file=listfile) previous_timestamp = '' while True: post = cur.fetchone() if post is None: break post = createpost(post) if post.score < SCORETHRESH: continue if post.type != 3: continue timestamp = post.created_utc timestamp = datetime.datetime.fromtimestamp(int(timestamp)).strftime(TIMESTAMP) if HTMLMODE: final = FORMAT_HTML else: final = FORMAT if timestamp != previous_timestamp: final = TSFORMAT + final final = final.replace('_timestamp_', timestamp) final = final.replace('_title_', post.title) flair_text = post.link_flair_text if post.link_flair_text else "" flair_css = post.link_flair_css_class if post.link_flair_css_class else "" post.link_flair_text = flair_text post.link_flair_css_class = flair_css final = final.replace('_flairtext_', flair_text) final = final.replace('_flaircss_', flair_css) authorlink = 'http://reddit.com/u/' + post.author final = final.replace('_author_', post.author) final = final.replace('_authorlink_', authorlink) final = final.replace('_subreddit_', post.subreddit) url = post.url if url is None: url = post.short_link else: url = url.replace('http://www.reddit.com', 'http://np.reddit.com') final = final.replace('_url_', url) shortlink = post.short_link #slink = slink.replace('http://', 'http://np.') final = final.replace('_slink_', shortlink) final = final.replace('_flairtext_', flair_text) final = final.replace('_score_', str(post.score)) final = final.replace('_numcomments_', str(post.num_comments)) print(final, file=listfile) previous_timestamp = timestamp def writefiles(): print('Writing time files') listfile = preparefile('_date') cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY created DESC', [SCORETHRESH]) work(listfile) closefile(listfile) print('Writing title files') listfile = preparefile('_title') cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY title ASC', [SCORETHRESH]) work(listfile) closefile(listfile) print('Writing score files') listfile = preparefile('_score') cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY score DESC', [SCORETHRESH]) work(listfile) closefile(listfile) if USERMODE is False: print('Writing author files') listfile = preparefile('_author') cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY author ASC', [SCORETHRESH]) work(listfile) closefile(listfile) if USERMODE is True: print('Writing subreddit files') listfile = preparefile('_subreddit') cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY subreddit ASC', [SCORETHRESH]) work(listfile) closefile(listfile) print('Writing flair file') listfile = preparefile('_flair') cur.execute('SELECT * FROM posts WHERE score >= ? AND flair_text IS NOT NULL ORDER BY flair_text, created ASC', [SCORETHRESH]) work(listfile) cur.execute('SELECT * FROM posts WHERE score >= ? AND flair_text IS NULL ORDER BY flair_text, created ASC', [SCORETHRESH]) work(listfile) closefile(listfile) print('Done.') def breakdown(doreturn=False, mode='user'): print('\nBreaking it down...') listfile = preparefile('') if mode == 'subreddit': cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY author ASC', [SCORETHRESH]) if mode == 'user': cur.execute('SELECT * FROM posts WHERE score >= ? ORDER BY subreddit ASC', [SCORETHRESH]) count_submissions = 0 count_comments = 0 previous = '' breakdowndict = {} while True: post = cur.fetchone() if post is None: breakdowndict[previous] = {'submissions':count_submissions, 'comments':count_comments} break post = createpost(post) if mode == 'subreddit': relevant = post.author elif mode == 'user': relevant = post.subreddit if relevant != previous: breakdowndict[previous] = {'submissions':count_submissions, 'comments':count_comments} previous = relevant count_submissions = 0 count_comments = 0 if post.type == 1: count_comments += 1 if post.type == 3: count_submissions += 1 del breakdowndict[''] if doreturn is True: return breakdowndict keys = list(breakdowndict.keys()) longestkey = max([len(k) for k in keys]) keys.sort(key=lambda x: (breakdowndict[x]['submissions'] + breakdowndict[x]['comments'], x), reverse=True) out = [] for k in keys: relevant = (' '*(longestkey-len(k))) + ('"%s"' % k) submissions = breakdowndict[k]['submissions'] comments = breakdowndict[k]['comments'] o = '%s:{%s:%d, %s:%d}' % (relevant, '"submissions"', submissions, '"comments"', comments) out.append(o) out = ',\n'.join(out) out = '{\n' + out + '\n}' print(out, file=listfile) #json.dump(breakdowndict, listfile, sort_keys=True, indent=4) def inputvars(): global READ_FROM_FILE global PRINTFILE global SCORETHRESH global HTMLMODE global USERMODE global BREAKDOWNMODE global EXTENSION global sql global cur try: READ_FROM_FILE = sys.argv[1] except IndexError: READ_FROM_FILE = input('] Input database = ') if READ_FROM_FILE[-3:] != '.db': READ_FROM_FILE += '.db' filename = READ_FROM_FILE.replace('\\', '/') filename = filename.split('/')[-1] if filename[0] == '@': USERMODE = True try: PRINTFILE = sys.argv[2] except IndexError: PRINTFILE = input('] Output filename = ') try: SCORETHRESH = int(sys.argv[3]) except IndexError: SCORETHRESH = int(input('] Score threshold = ')) HTMLMODE = '.html' in PRINTFILE BREAKDOWNMODE = '.json' in PRINTFILE if HTMLMODE: EXTENSION = '.html' PRINTFILE = PRINTFILE.replace('.html', '') elif BREAKDOWNMODE: EXTENSION = '.json' PRINTFILE = PRINTFILE.replace('.json', '') else: EXTENSION = '.txt' PRINTFILE = PRINTFILE.replace('.txt', '') sql = sqlite3.connect(READ_FROM_FILE) cur = sql.cursor() def main(): inputvars() if BREAKDOWNMODE is False: writefiles() else: if USERMODE is True: breakdown(mode='user') else: breakdown(mode='subreddit') if __name__ == '__main__': main()
0.104924
0.083143
import numpy as np from pathlib import Path import matplotlib.pyplot as plt import math from MiniFramework.NeuralNet_4_0 import * from MiniFramework.ActivationLayer import * from MiniFramework.ClassificationLayer import * from MiniFramework.DataReader_2_0 import * train_data_name = "../../Data/ch10.train.npz" test_data_name = "../../Data/ch10.test.npz" def DrawTwoCategoryPoints(X1, X2, Y, xlabel="x1", ylabel="x2", title=None, show=False, isPredicate=False): colors = ['b', 'r'] shapes = ['o', 'x'] assert(X1.shape[0] == X2.shape[0] == Y.shape[0]) count = X1.shape[0] for i in range(count): j = (int)(round(Y[i])) if j < 0: j = 0 if isPredicate: plt.scatter(X1[i], X2[i], color=colors[j], marker='^', s=200, zorder=10) else: plt.scatter(X1[i], X2[i], color=colors[j], marker=shapes[j], zorder=10) # end for plt.xlabel(xlabel) plt.ylabel(ylabel) if title is not None: plt.title(title) if show: plt.show() def ShowDataHelper(x1,x2,y,title,xlabel,ylabel,show,grid=True): fig = plt.figure(figsize=(6,6)) if grid: plt.grid() DrawTwoCategoryPoints(x1,x2,y,xlabel,ylabel,title,show) def Prepare3DData(net, count): x = np.linspace(0,1,count) y = np.linspace(0,1,count) X, Y = np.meshgrid(x, y) if net is not None: input = np.hstack((X.ravel().reshape(count*count,1),Y.ravel().reshape(count*count,1))) net.inference(input) return X, Y def ShowResult2D(net, dr): ShowDataHelper(dr.XTrain[:,0], dr.XTrain[:,1], dr.YTrain[:,0], "Classifier Result", "x1", "x2", False, False) count = 50 X,Y = Prepare3DData(net, count) Z = net.output.reshape(count,count) plt.contourf(X, Y, Z, cmap=plt.cm.Spectral, zorder=1) plt.show() #end def def load_data(): dataReader = DataReader_2_0(train_data_name, test_data_name) dataReader.ReadData() dataReader.NormalizeX() dataReader.Shuffle() dataReader.GenerateValidationSet() return dataReader def model(dataReader): num_input = 2 num_hidden = 3 num_output = 1 max_epoch = 1000 batch_size = 5 learning_rate = 0.1 params = HyperParameters_4_0( learning_rate, max_epoch, batch_size, net_type=NetType.BinaryClassifier, init_method=InitialMethod.Xavier, stopper=Stopper(StopCondition.StopLoss, 0.02)) net = NeuralNet_4_0(params, "Arc") fc1 = FcLayer_1_0(num_input, num_hidden, params) net.add_layer(fc1, "fc1") sigmoid1 = ActivationLayer(Sigmoid()) net.add_layer(sigmoid1, "sigmoid1") fc2 = FcLayer_1_0(num_hidden, num_output, params) net.add_layer(fc2, "fc2") logistic = ClassificationLayer(Logistic()) net.add_layer(logistic, "logistic") net.train(dataReader, checkpoint=10, need_test=True) return net if __name__ == '__main__': dr = load_data() net = model(dr) net.ShowLossHistory() ShowResult2D(net, dr)
基础教程/A2-神经网络基本原理/第7步 - 深度神经网络/src/ch14-DnnBasic/Level3_ch10.py
import numpy as np from pathlib import Path import matplotlib.pyplot as plt import math from MiniFramework.NeuralNet_4_0 import * from MiniFramework.ActivationLayer import * from MiniFramework.ClassificationLayer import * from MiniFramework.DataReader_2_0 import * train_data_name = "../../Data/ch10.train.npz" test_data_name = "../../Data/ch10.test.npz" def DrawTwoCategoryPoints(X1, X2, Y, xlabel="x1", ylabel="x2", title=None, show=False, isPredicate=False): colors = ['b', 'r'] shapes = ['o', 'x'] assert(X1.shape[0] == X2.shape[0] == Y.shape[0]) count = X1.shape[0] for i in range(count): j = (int)(round(Y[i])) if j < 0: j = 0 if isPredicate: plt.scatter(X1[i], X2[i], color=colors[j], marker='^', s=200, zorder=10) else: plt.scatter(X1[i], X2[i], color=colors[j], marker=shapes[j], zorder=10) # end for plt.xlabel(xlabel) plt.ylabel(ylabel) if title is not None: plt.title(title) if show: plt.show() def ShowDataHelper(x1,x2,y,title,xlabel,ylabel,show,grid=True): fig = plt.figure(figsize=(6,6)) if grid: plt.grid() DrawTwoCategoryPoints(x1,x2,y,xlabel,ylabel,title,show) def Prepare3DData(net, count): x = np.linspace(0,1,count) y = np.linspace(0,1,count) X, Y = np.meshgrid(x, y) if net is not None: input = np.hstack((X.ravel().reshape(count*count,1),Y.ravel().reshape(count*count,1))) net.inference(input) return X, Y def ShowResult2D(net, dr): ShowDataHelper(dr.XTrain[:,0], dr.XTrain[:,1], dr.YTrain[:,0], "Classifier Result", "x1", "x2", False, False) count = 50 X,Y = Prepare3DData(net, count) Z = net.output.reshape(count,count) plt.contourf(X, Y, Z, cmap=plt.cm.Spectral, zorder=1) plt.show() #end def def load_data(): dataReader = DataReader_2_0(train_data_name, test_data_name) dataReader.ReadData() dataReader.NormalizeX() dataReader.Shuffle() dataReader.GenerateValidationSet() return dataReader def model(dataReader): num_input = 2 num_hidden = 3 num_output = 1 max_epoch = 1000 batch_size = 5 learning_rate = 0.1 params = HyperParameters_4_0( learning_rate, max_epoch, batch_size, net_type=NetType.BinaryClassifier, init_method=InitialMethod.Xavier, stopper=Stopper(StopCondition.StopLoss, 0.02)) net = NeuralNet_4_0(params, "Arc") fc1 = FcLayer_1_0(num_input, num_hidden, params) net.add_layer(fc1, "fc1") sigmoid1 = ActivationLayer(Sigmoid()) net.add_layer(sigmoid1, "sigmoid1") fc2 = FcLayer_1_0(num_hidden, num_output, params) net.add_layer(fc2, "fc2") logistic = ClassificationLayer(Logistic()) net.add_layer(logistic, "logistic") net.train(dataReader, checkpoint=10, need_test=True) return net if __name__ == '__main__': dr = load_data() net = model(dr) net.ShowLossHistory() ShowResult2D(net, dr)
0.511717
0.461563
import os.path import random from os.path import join import numpy as np from bert4keras.backend import keras, K from bert4keras.layers import Loss from bert4keras.models import build_transformer_model from bert4keras.tokenizers import Tokenizer from bert4keras.optimizers import Adam, extend_with_weight_decay from bert4keras.snippets import DataGenerator, sequence_padding from bert4keras.snippets import text_segmentate, truncate_sequences from bert4keras.snippets import AutoRegressiveDecoder import jieba from shutil import copy jieba.initialize() # 基本信息 maxlen = 100 batch_size = 32 epochs = 50 save_dir = "./output/roformer_base" model_dir = "./model_data/public_model/chinese_roformer-char_L-12_H-768_A-12" # bert配置 config_path = join(model_dir, 'bert_config.json') checkpoint_path = join(model_dir, 'bert_model.ckpt') dict_path = join(model_dir, 'vocab.txt') steps_per_epoch = 90000 // batch_size # 建立分词器 tokenizer = Tokenizer(dict_path, do_lower_case=True) if not os.path.exists(save_dir): os.makedirs(save_dir) # 获取一部分待编码的句子 with open("./model_data/hold_out/dev.txt", "r", encoding="utf8") as fr: dev_data = [line.strip().split("\t")[::-1] for line in fr] # title,query def split(text): """分割句子 """ seps, strips = u'\n。!?!?;;,, ', u';;,, ' return text_segmentate(text, maxlen * 1.2, seps, strips) def corpus(): """读取语料 """ with open("./model_data/hold_out/train.txt", "r", encoding="utf8") as fr: data = [line.strip().split("\t")[::-1] for line in fr] print("data example:{}", data[0]) while True: random.shuffle(data) for item in data: yield item def masked_encode(text): """wwm随机mask """ words = jieba.lcut(text) rands = np.random.random(len(words)) source, target = [tokenizer._token_start_id], [0] for r, w in zip(rands, words): ids = tokenizer.encode(w)[0][1:-1] if r < 0.15 * 0.8: source.extend([tokenizer._token_mask_id] * len(ids)) target.extend(ids) elif r < 0.15 * 0.9: source.extend(ids) target.extend(ids) elif r < 0.15: source.extend( np.random.choice(tokenizer._vocab_size - 1, size=len(ids)) + 1 ) target.extend(ids) else: source.extend(ids) target.extend([0] * len(ids)) source = source[:maxlen - 1] + [tokenizer._token_end_id] target = target[:maxlen - 1] + [0] return source, target class data_generator(DataGenerator): """数据生成器 """ def __init__(self, *args, **kwargs): super(data_generator, self).__init__(*args, **kwargs) self.some_samples = [] def __iter__(self, random=False): batch_token_ids, batch_segment_ids = [], [] for is_end, (text, synonym) in self.sample(random): for i in range(2): if np.random.random() < 0.5: text_ids = masked_encode(text)[0] else: text_ids = tokenizer.encode(text)[0] synonym_ids = tokenizer.encode(synonym)[0][1:] truncate_sequences(maxlen * 2, -2, text_ids, synonym_ids) token_ids = text_ids + synonym_ids segment_ids = [0] * len(text_ids) + [1] * len(synonym_ids) batch_token_ids.append(token_ids) batch_segment_ids.append(segment_ids) self.some_samples.append(synonym) if len(self.some_samples) > 1000: self.some_samples.pop(0) text, synonym = synonym, text if len(batch_token_ids) == self.batch_size or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) yield [batch_token_ids, batch_segment_ids], None batch_token_ids, batch_segment_ids = [], [] class TotalLoss(Loss): """loss分两部分,一是seq2seq的交叉熵,二是相似度的交叉熵。 """ def compute_loss(self, inputs, mask=None): loss1 = self.compute_loss_of_seq2seq(inputs, mask) loss2 = self.compute_loss_of_similarity(inputs, mask) self.add_metric(loss1, name='seq2seq_loss') self.add_metric(loss2, name='similarity_loss') return loss1 + loss2 def compute_loss_of_seq2seq(self, inputs, mask=None): y_true, y_mask, _, y_pred = inputs y_true = y_true[:, 1:] # 目标token_ids y_mask = y_mask[:, 1:] # segment_ids,刚好指示了要预测的部分 y_pred = y_pred[:, :-1] # 预测序列,错开一位 loss = K.sparse_categorical_crossentropy( y_true, y_pred, from_logits=True ) loss = K.sum(loss * y_mask) / K.sum(y_mask) return loss def compute_loss_of_similarity(self, inputs, mask=None): _, _, y_pred, _ = inputs y_true = self.get_labels_of_similarity(y_pred) # 构建标签 y_pred = K.l2_normalize(y_pred, axis=1) # 句向量归一化 similarities = K.dot(y_pred, K.transpose(y_pred)) # 相似度矩阵 similarities = similarities - K.eye(K.shape(y_pred)[0]) * 1e12 # 排除对角线 similarities = similarities * 20 # scale loss = K.categorical_crossentropy( y_true, similarities, from_logits=True ) return loss def get_labels_of_similarity(self, y_pred): idxs = K.arange(0, K.shape(y_pred)[0]) idxs_1 = idxs[None, :] idxs_2 = (idxs + 1 - idxs % 2 * 2)[:, None] labels = K.equal(idxs_1, idxs_2) labels = K.cast(labels, K.floatx()) return labels # 建立加载模型 roformer = build_transformer_model( config_path, checkpoint_path, model='roformer', application='unilm', with_pool='linear', with_mlm='linear', dropout_rate=0.2, ignore_invalid_weights=True, return_keras_model=False, ) encoder = keras.models.Model(roformer.inputs, roformer.outputs[0]) seq2seq = keras.models.Model(roformer.inputs, roformer.outputs[1]) outputs = TotalLoss([2, 3])(roformer.inputs + roformer.outputs) model = keras.models.Model(roformer.inputs, outputs) AdamW = extend_with_weight_decay(Adam, 'AdamW') optimizer = AdamW(learning_rate=1e-5, weight_decay_rate=0.01) model.compile(optimizer=optimizer) model.summary() class SynonymsGenerator(AutoRegressiveDecoder): """seq2seq解码器 """ @AutoRegressiveDecoder.wraps(default_rtype='logits') def predict(self, inputs, output_ids, step): token_ids, segment_ids = inputs token_ids = np.concatenate([token_ids, output_ids], 1) segment_ids = np.concatenate([segment_ids, np.ones_like(output_ids)], 1) return self.last_token(seq2seq).predict([token_ids, segment_ids]) def generate(self, text, n=1, topp=0.95): token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen) output_ids = self.random_sample([token_ids, segment_ids], n, topp=topp) # 基于随机采样 return [tokenizer.decode(ids) for ids in output_ids] synonyms_generator = SynonymsGenerator( start_id=None, end_id=tokenizer._token_end_id, maxlen=maxlen ) def gen_synonyms(text, n=100, k=20): """"含义: 产生sent的n个相似句,然后返回最相似的k个。 做法:用seq2seq生成,并用encoder算相似度并排序。 效果: >>> gen_synonyms(u'微信和支付宝哪个好?') [ u'微信和支付宝,哪个好?', u'微信和支付宝哪个好', u'支付宝和微信哪个好', u'支付宝和微信哪个好啊', u'微信和支付宝那个好用?', u'微信和支付宝哪个好用', u'支付宝和微信那个更好', u'支付宝和微信哪个好用', u'微信和支付宝用起来哪个好?', u'微信和支付宝选哪个好', ] """ r = synonyms_generator.generate(text, n) r = [i for i in set(r) if i != text] r = [text] + r X, S = [], [] for t in r: x, s = tokenizer.encode(t) X.append(x) S.append(s) X = sequence_padding(X) S = sequence_padding(S) Z = encoder.predict([X, S]) Z /= (Z ** 2).sum(axis=1, keepdims=True) ** 0.5 argsort = np.dot(Z[1:], -Z[0]).argsort() return [r[i + 1] for i in argsort[:k]] def just_show(): """随机观察一些样本的效果 """ S = random.sample(dev_data, 3) for title, query in S: try: print(u'标题:%s' % title) print("标准问句:{}".format(query)) print(u'生成的问题:') print(gen_synonyms(title, 10, 10)) print() except: pass class Evaluate(keras.callbacks.Callback): """评估模型 """ def __init__(self): self.lowest = 1e10 def on_epoch_end(self, epoch, logs=None): # model.save_weights(join(save_dir, 'latest_model.weights')) if epoch % 4 == 0: roformer.save_weights_as_checkpoint(join(save_dir, "epoch-{}/bert_model.ckpt".format(epoch + 1))) copy(config_path, join(save_dir, "epoch-{}/bert_config.json".format(epoch + 1))) copy(dict_path, join(save_dir, "epoch-{}/vocab.txt".format(epoch + 1))) # 保存最优 if logs['loss'] <= self.lowest: self.lowest = logs['loss'] roformer.save_weights_as_checkpoint(join(save_dir, "best_model/bert_model.ckpt".format(epoch + 1))) copy(config_path, join(save_dir, "best_model/bert_config.json".format(epoch + 1))) copy(dict_path, join(save_dir, "best_model/vocab.txt".format(epoch + 1))) # 演示效果 just_show() if __name__ == '__main__': train_generator = data_generator(corpus(), batch_size) evaluator = Evaluate() model.fit_generator( train_generator.forfit(), steps_per_epoch=steps_per_epoch, epochs=epochs, callbacks=[evaluator] )
main.py
import os.path import random from os.path import join import numpy as np from bert4keras.backend import keras, K from bert4keras.layers import Loss from bert4keras.models import build_transformer_model from bert4keras.tokenizers import Tokenizer from bert4keras.optimizers import Adam, extend_with_weight_decay from bert4keras.snippets import DataGenerator, sequence_padding from bert4keras.snippets import text_segmentate, truncate_sequences from bert4keras.snippets import AutoRegressiveDecoder import jieba from shutil import copy jieba.initialize() # 基本信息 maxlen = 100 batch_size = 32 epochs = 50 save_dir = "./output/roformer_base" model_dir = "./model_data/public_model/chinese_roformer-char_L-12_H-768_A-12" # bert配置 config_path = join(model_dir, 'bert_config.json') checkpoint_path = join(model_dir, 'bert_model.ckpt') dict_path = join(model_dir, 'vocab.txt') steps_per_epoch = 90000 // batch_size # 建立分词器 tokenizer = Tokenizer(dict_path, do_lower_case=True) if not os.path.exists(save_dir): os.makedirs(save_dir) # 获取一部分待编码的句子 with open("./model_data/hold_out/dev.txt", "r", encoding="utf8") as fr: dev_data = [line.strip().split("\t")[::-1] for line in fr] # title,query def split(text): """分割句子 """ seps, strips = u'\n。!?!?;;,, ', u';;,, ' return text_segmentate(text, maxlen * 1.2, seps, strips) def corpus(): """读取语料 """ with open("./model_data/hold_out/train.txt", "r", encoding="utf8") as fr: data = [line.strip().split("\t")[::-1] for line in fr] print("data example:{}", data[0]) while True: random.shuffle(data) for item in data: yield item def masked_encode(text): """wwm随机mask """ words = jieba.lcut(text) rands = np.random.random(len(words)) source, target = [tokenizer._token_start_id], [0] for r, w in zip(rands, words): ids = tokenizer.encode(w)[0][1:-1] if r < 0.15 * 0.8: source.extend([tokenizer._token_mask_id] * len(ids)) target.extend(ids) elif r < 0.15 * 0.9: source.extend(ids) target.extend(ids) elif r < 0.15: source.extend( np.random.choice(tokenizer._vocab_size - 1, size=len(ids)) + 1 ) target.extend(ids) else: source.extend(ids) target.extend([0] * len(ids)) source = source[:maxlen - 1] + [tokenizer._token_end_id] target = target[:maxlen - 1] + [0] return source, target class data_generator(DataGenerator): """数据生成器 """ def __init__(self, *args, **kwargs): super(data_generator, self).__init__(*args, **kwargs) self.some_samples = [] def __iter__(self, random=False): batch_token_ids, batch_segment_ids = [], [] for is_end, (text, synonym) in self.sample(random): for i in range(2): if np.random.random() < 0.5: text_ids = masked_encode(text)[0] else: text_ids = tokenizer.encode(text)[0] synonym_ids = tokenizer.encode(synonym)[0][1:] truncate_sequences(maxlen * 2, -2, text_ids, synonym_ids) token_ids = text_ids + synonym_ids segment_ids = [0] * len(text_ids) + [1] * len(synonym_ids) batch_token_ids.append(token_ids) batch_segment_ids.append(segment_ids) self.some_samples.append(synonym) if len(self.some_samples) > 1000: self.some_samples.pop(0) text, synonym = synonym, text if len(batch_token_ids) == self.batch_size or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) yield [batch_token_ids, batch_segment_ids], None batch_token_ids, batch_segment_ids = [], [] class TotalLoss(Loss): """loss分两部分,一是seq2seq的交叉熵,二是相似度的交叉熵。 """ def compute_loss(self, inputs, mask=None): loss1 = self.compute_loss_of_seq2seq(inputs, mask) loss2 = self.compute_loss_of_similarity(inputs, mask) self.add_metric(loss1, name='seq2seq_loss') self.add_metric(loss2, name='similarity_loss') return loss1 + loss2 def compute_loss_of_seq2seq(self, inputs, mask=None): y_true, y_mask, _, y_pred = inputs y_true = y_true[:, 1:] # 目标token_ids y_mask = y_mask[:, 1:] # segment_ids,刚好指示了要预测的部分 y_pred = y_pred[:, :-1] # 预测序列,错开一位 loss = K.sparse_categorical_crossentropy( y_true, y_pred, from_logits=True ) loss = K.sum(loss * y_mask) / K.sum(y_mask) return loss def compute_loss_of_similarity(self, inputs, mask=None): _, _, y_pred, _ = inputs y_true = self.get_labels_of_similarity(y_pred) # 构建标签 y_pred = K.l2_normalize(y_pred, axis=1) # 句向量归一化 similarities = K.dot(y_pred, K.transpose(y_pred)) # 相似度矩阵 similarities = similarities - K.eye(K.shape(y_pred)[0]) * 1e12 # 排除对角线 similarities = similarities * 20 # scale loss = K.categorical_crossentropy( y_true, similarities, from_logits=True ) return loss def get_labels_of_similarity(self, y_pred): idxs = K.arange(0, K.shape(y_pred)[0]) idxs_1 = idxs[None, :] idxs_2 = (idxs + 1 - idxs % 2 * 2)[:, None] labels = K.equal(idxs_1, idxs_2) labels = K.cast(labels, K.floatx()) return labels # 建立加载模型 roformer = build_transformer_model( config_path, checkpoint_path, model='roformer', application='unilm', with_pool='linear', with_mlm='linear', dropout_rate=0.2, ignore_invalid_weights=True, return_keras_model=False, ) encoder = keras.models.Model(roformer.inputs, roformer.outputs[0]) seq2seq = keras.models.Model(roformer.inputs, roformer.outputs[1]) outputs = TotalLoss([2, 3])(roformer.inputs + roformer.outputs) model = keras.models.Model(roformer.inputs, outputs) AdamW = extend_with_weight_decay(Adam, 'AdamW') optimizer = AdamW(learning_rate=1e-5, weight_decay_rate=0.01) model.compile(optimizer=optimizer) model.summary() class SynonymsGenerator(AutoRegressiveDecoder): """seq2seq解码器 """ @AutoRegressiveDecoder.wraps(default_rtype='logits') def predict(self, inputs, output_ids, step): token_ids, segment_ids = inputs token_ids = np.concatenate([token_ids, output_ids], 1) segment_ids = np.concatenate([segment_ids, np.ones_like(output_ids)], 1) return self.last_token(seq2seq).predict([token_ids, segment_ids]) def generate(self, text, n=1, topp=0.95): token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen) output_ids = self.random_sample([token_ids, segment_ids], n, topp=topp) # 基于随机采样 return [tokenizer.decode(ids) for ids in output_ids] synonyms_generator = SynonymsGenerator( start_id=None, end_id=tokenizer._token_end_id, maxlen=maxlen ) def gen_synonyms(text, n=100, k=20): """"含义: 产生sent的n个相似句,然后返回最相似的k个。 做法:用seq2seq生成,并用encoder算相似度并排序。 效果: >>> gen_synonyms(u'微信和支付宝哪个好?') [ u'微信和支付宝,哪个好?', u'微信和支付宝哪个好', u'支付宝和微信哪个好', u'支付宝和微信哪个好啊', u'微信和支付宝那个好用?', u'微信和支付宝哪个好用', u'支付宝和微信那个更好', u'支付宝和微信哪个好用', u'微信和支付宝用起来哪个好?', u'微信和支付宝选哪个好', ] """ r = synonyms_generator.generate(text, n) r = [i for i in set(r) if i != text] r = [text] + r X, S = [], [] for t in r: x, s = tokenizer.encode(t) X.append(x) S.append(s) X = sequence_padding(X) S = sequence_padding(S) Z = encoder.predict([X, S]) Z /= (Z ** 2).sum(axis=1, keepdims=True) ** 0.5 argsort = np.dot(Z[1:], -Z[0]).argsort() return [r[i + 1] for i in argsort[:k]] def just_show(): """随机观察一些样本的效果 """ S = random.sample(dev_data, 3) for title, query in S: try: print(u'标题:%s' % title) print("标准问句:{}".format(query)) print(u'生成的问题:') print(gen_synonyms(title, 10, 10)) print() except: pass class Evaluate(keras.callbacks.Callback): """评估模型 """ def __init__(self): self.lowest = 1e10 def on_epoch_end(self, epoch, logs=None): # model.save_weights(join(save_dir, 'latest_model.weights')) if epoch % 4 == 0: roformer.save_weights_as_checkpoint(join(save_dir, "epoch-{}/bert_model.ckpt".format(epoch + 1))) copy(config_path, join(save_dir, "epoch-{}/bert_config.json".format(epoch + 1))) copy(dict_path, join(save_dir, "epoch-{}/vocab.txt".format(epoch + 1))) # 保存最优 if logs['loss'] <= self.lowest: self.lowest = logs['loss'] roformer.save_weights_as_checkpoint(join(save_dir, "best_model/bert_model.ckpt".format(epoch + 1))) copy(config_path, join(save_dir, "best_model/bert_config.json".format(epoch + 1))) copy(dict_path, join(save_dir, "best_model/vocab.txt".format(epoch + 1))) # 演示效果 just_show() if __name__ == '__main__': train_generator = data_generator(corpus(), batch_size) evaluator = Evaluate() model.fit_generator( train_generator.forfit(), steps_per_epoch=steps_per_epoch, epochs=epochs, callbacks=[evaluator] )
0.538012
0.17441
from widgets.MessageFrame import MessageFrame from widgets.ConsoleFrame import ConsoleFrame from widgets.PCANSettingsWindow import PCANSettingsWindow from lib.PCAN_RS_232 import PCAN_RS_232 from tkinter import * from widgets.InformationFrame import InformationFrame from widgets.ButtonFrame import ButtonFrame from serial import SerialException class App(Tk): def __init__(self): super().__init__() self.title("PCAN-RS-232 Interface") self.geometry('960x420') self.resizable(FALSE, FALSE) # Create main containers self.button_frame = ButtonFrame(self, bg="#004080", pady=3) self.center_frame = ConsoleFrame(self, padx=3, pady=3) self.can_msg_frame = MessageFrame(self, bg="#004080", pady=3) self.btm_frame = InformationFrame(self, bg="#004080", pady=3) # Layout containers self.button_frame.place(x=0, y=0, width=210, height=390) self.center_frame.place(x=210, y=0, width=540, height=390) self.can_msg_frame.place(x=750, y=0, width=210, height=390) self.btm_frame.place(x=0, y=390, width=960, height=30) # Initialize application variables self._PORT = StringVar(value="COM1") # Default: COM1 self._BAUDRATE = StringVar(value="57600") # Default: 57600 self._TIMEOUT = StringVar(value="1") # Default: 1 (s) try: self.pcan = PCAN_RS_232(self._PORT.get(), int(self._BAUDRATE.get()), int(self._TIMEOUT.get())) self.center_frame.begin(self.pcan) except SerialException: # Default device not found self.pcan_window = PCANSettingsWindow(self) # Open a window to configure PCAN settings # ===PCAN INTERACTION FUNCTIONS=== def update_pcan_settings(self): try: self.pcan = PCAN_RS_232(self._PORT.get(), int(self._BAUDRATE.get()), int(self._TIMEOUT.get())) self.center_frame.begin(self.pcan) return True except SerialException: return False # ===WIDGET INTERFACE FUNCTIONS=== def update_pcan_status(self): _stat = self.pcan.get_status_flags() if _stat != -1: self.btm_frame.pcan_status.set(_stat) self.btm_frame.cmd_feedback.set("Received PCAN status") else: self.btm_frame.cmd_feedback.set("FAILED to get PCAN status") def update_pcan_open(self, open): _res = self.pcan.open_channel() if open else self.pcan.close_channel() if _res != -1: # Channel successfully opened/closed _text = "Opened CAN Channel" if open else "Closed CAN channel" self.btm_frame.cmd_feedback.set(_text) return True else: _text = "FAILED to open CAN channel" if open else "FAILED to close CAN channel" self.btm_frame.cmd_feedback.set(_text) return False def update_pcan_info(self): _sn = self.pcan.get_serial_number() _info = self.pcan.get_version_info() print(_info) # DEBUG if _info != -1: self.btm_frame.pcan_sn.set(_sn) self.btm_frame.pcan_hw_version.set(_info[0]) self.btm_frame.pcan_sw_version.set(_info[1]) self.btm_frame.cmd_feedback.set("Received PCAN info") else: self.btm_frame.cmd_feedback.set("FAILED to get PCAN info") def update_acceptance_mask(self, mask): _res = self.pcan.set_acceptance_mask_register(mask) if _res != -1: # Acceptance mask register successfuly set self.btm_frame.cmd_feedback.set("Set mask to " + mask) else: self.btm_frame.cmd_feedback.set("FAILED to set acceptance mask") return _res def update_acceptance_code(self, code): _res = self.pcan.set_acceptance_code_register(code) if _res != -1: # Acceptance code register successfuly set self.btm_frame.cmd_feedback.set("Set code to "+ code) else: self.btm_frame.cmd_feedback.set("FAILED to set acceptance code") return _res def update_auto_poll(self, en: bool): _res = self.pcan.set_auto_poll(en) if _res != -1: # Auto poll successfully set _text = "ENABLED auto poll feature" if en else "DISABLED auto poll feature" self.btm_frame.cmd_feedback.set(_text) else: self.btm_frame.cmd_feedback.set("FAILED to set auto poll") return _res def update_auto_startup(self, en: bool): _res = self.pcan.set_auto_startup(en) if _res != -1: # Auto startup successfully set _text = "ENABLED auto startup feature" if en else "DISABLED auto startup feature" self.btm_frame.cmd_feedback.set(_text) else: self.btm_frame.cmd_feedback.set("FAILED to set auto startup") return _res def update_can_baudrate(self, n: str): _res = self.pcan.set_can_bitrate(n) if _res != -1: # CAN baudrate successfully set self.btm_frame.cmd_feedback.set("Set CAN baudrate") # TODO: Include baudrate else: self.btm_frame.cmd_feedback.set("FAILED to set CAN baudrate") return _res def update_uart_baudrate(self, n: str): _res = self.pcan.set_uart_bitrate(n) # TODO: Edit application baudrate to reflect new set baudrate!!!!!!!!!! if _res != -1: # UART baudrate successfully set self.btm_frame.cmd_feedback.set("Set UART baudrate") # TODO: Include baudrate else: self.btm_frame.cmd_feedback.set("FAILED to set UART baudrate") return _res def update_filter_mode(self, n: bool): _res = self.pcan.set_filter_mode(n) if _res != -1: # Filter mode successfully set _text = "Set mode to Single Filter" if n else "Set mode to Dual Filter" self.btm_frame.cmd_feedback.set(_text) else: self.btm_frame.cmd_feedback.set("FAILED to set filter mode") return _res def update_timestamp(self, n: bool): _res = self.pcan.enable_timestamps(n) if _res != -1: # Filter mode successfully set _text = "Enabled timestamp feature" if n else "Disabled timestamp feature" self.btm_frame.cmd_feedback.set(_text) else: self.btm_frame.cmd_feedback.set("FAILED to timestamp feature") return _res def update_eeprom(self, n: str): if self.pcan.write_to_eeprom(n) != -1: if n == '0': self.btm_frame.cmd_feedback.set("Saved settings to EEPROM") elif n == '1': self.btm_frame.cmd_feedback.set("Reloaded factory settings") elif n == '2': self.btm_frame.cmd_feedback.set("Deleted all settings") else: self.btm_frame.cmd_feedback.set("FAILED to command EEPROM") def transmit_message(self, msg): if self.pcan.send_message(msg) != -1: # Message successfully sent self.btm_frame.cmd_feedback.set("Sent message") else: self.btm_frame.cmd_feedback.set("FAILED to send message") _app = App() try: if __name__ == '__main__': _app.mainloop() # Begin interface application finally: # On app close try: _app.update_pcan_open(False) # Close CAN connection _app.update_eeprom('1') # Reset to factory-default settings except: pass
PCAN_Interface_Application.py
from widgets.MessageFrame import MessageFrame from widgets.ConsoleFrame import ConsoleFrame from widgets.PCANSettingsWindow import PCANSettingsWindow from lib.PCAN_RS_232 import PCAN_RS_232 from tkinter import * from widgets.InformationFrame import InformationFrame from widgets.ButtonFrame import ButtonFrame from serial import SerialException class App(Tk): def __init__(self): super().__init__() self.title("PCAN-RS-232 Interface") self.geometry('960x420') self.resizable(FALSE, FALSE) # Create main containers self.button_frame = ButtonFrame(self, bg="#004080", pady=3) self.center_frame = ConsoleFrame(self, padx=3, pady=3) self.can_msg_frame = MessageFrame(self, bg="#004080", pady=3) self.btm_frame = InformationFrame(self, bg="#004080", pady=3) # Layout containers self.button_frame.place(x=0, y=0, width=210, height=390) self.center_frame.place(x=210, y=0, width=540, height=390) self.can_msg_frame.place(x=750, y=0, width=210, height=390) self.btm_frame.place(x=0, y=390, width=960, height=30) # Initialize application variables self._PORT = StringVar(value="COM1") # Default: COM1 self._BAUDRATE = StringVar(value="57600") # Default: 57600 self._TIMEOUT = StringVar(value="1") # Default: 1 (s) try: self.pcan = PCAN_RS_232(self._PORT.get(), int(self._BAUDRATE.get()), int(self._TIMEOUT.get())) self.center_frame.begin(self.pcan) except SerialException: # Default device not found self.pcan_window = PCANSettingsWindow(self) # Open a window to configure PCAN settings # ===PCAN INTERACTION FUNCTIONS=== def update_pcan_settings(self): try: self.pcan = PCAN_RS_232(self._PORT.get(), int(self._BAUDRATE.get()), int(self._TIMEOUT.get())) self.center_frame.begin(self.pcan) return True except SerialException: return False # ===WIDGET INTERFACE FUNCTIONS=== def update_pcan_status(self): _stat = self.pcan.get_status_flags() if _stat != -1: self.btm_frame.pcan_status.set(_stat) self.btm_frame.cmd_feedback.set("Received PCAN status") else: self.btm_frame.cmd_feedback.set("FAILED to get PCAN status") def update_pcan_open(self, open): _res = self.pcan.open_channel() if open else self.pcan.close_channel() if _res != -1: # Channel successfully opened/closed _text = "Opened CAN Channel" if open else "Closed CAN channel" self.btm_frame.cmd_feedback.set(_text) return True else: _text = "FAILED to open CAN channel" if open else "FAILED to close CAN channel" self.btm_frame.cmd_feedback.set(_text) return False def update_pcan_info(self): _sn = self.pcan.get_serial_number() _info = self.pcan.get_version_info() print(_info) # DEBUG if _info != -1: self.btm_frame.pcan_sn.set(_sn) self.btm_frame.pcan_hw_version.set(_info[0]) self.btm_frame.pcan_sw_version.set(_info[1]) self.btm_frame.cmd_feedback.set("Received PCAN info") else: self.btm_frame.cmd_feedback.set("FAILED to get PCAN info") def update_acceptance_mask(self, mask): _res = self.pcan.set_acceptance_mask_register(mask) if _res != -1: # Acceptance mask register successfuly set self.btm_frame.cmd_feedback.set("Set mask to " + mask) else: self.btm_frame.cmd_feedback.set("FAILED to set acceptance mask") return _res def update_acceptance_code(self, code): _res = self.pcan.set_acceptance_code_register(code) if _res != -1: # Acceptance code register successfuly set self.btm_frame.cmd_feedback.set("Set code to "+ code) else: self.btm_frame.cmd_feedback.set("FAILED to set acceptance code") return _res def update_auto_poll(self, en: bool): _res = self.pcan.set_auto_poll(en) if _res != -1: # Auto poll successfully set _text = "ENABLED auto poll feature" if en else "DISABLED auto poll feature" self.btm_frame.cmd_feedback.set(_text) else: self.btm_frame.cmd_feedback.set("FAILED to set auto poll") return _res def update_auto_startup(self, en: bool): _res = self.pcan.set_auto_startup(en) if _res != -1: # Auto startup successfully set _text = "ENABLED auto startup feature" if en else "DISABLED auto startup feature" self.btm_frame.cmd_feedback.set(_text) else: self.btm_frame.cmd_feedback.set("FAILED to set auto startup") return _res def update_can_baudrate(self, n: str): _res = self.pcan.set_can_bitrate(n) if _res != -1: # CAN baudrate successfully set self.btm_frame.cmd_feedback.set("Set CAN baudrate") # TODO: Include baudrate else: self.btm_frame.cmd_feedback.set("FAILED to set CAN baudrate") return _res def update_uart_baudrate(self, n: str): _res = self.pcan.set_uart_bitrate(n) # TODO: Edit application baudrate to reflect new set baudrate!!!!!!!!!! if _res != -1: # UART baudrate successfully set self.btm_frame.cmd_feedback.set("Set UART baudrate") # TODO: Include baudrate else: self.btm_frame.cmd_feedback.set("FAILED to set UART baudrate") return _res def update_filter_mode(self, n: bool): _res = self.pcan.set_filter_mode(n) if _res != -1: # Filter mode successfully set _text = "Set mode to Single Filter" if n else "Set mode to Dual Filter" self.btm_frame.cmd_feedback.set(_text) else: self.btm_frame.cmd_feedback.set("FAILED to set filter mode") return _res def update_timestamp(self, n: bool): _res = self.pcan.enable_timestamps(n) if _res != -1: # Filter mode successfully set _text = "Enabled timestamp feature" if n else "Disabled timestamp feature" self.btm_frame.cmd_feedback.set(_text) else: self.btm_frame.cmd_feedback.set("FAILED to timestamp feature") return _res def update_eeprom(self, n: str): if self.pcan.write_to_eeprom(n) != -1: if n == '0': self.btm_frame.cmd_feedback.set("Saved settings to EEPROM") elif n == '1': self.btm_frame.cmd_feedback.set("Reloaded factory settings") elif n == '2': self.btm_frame.cmd_feedback.set("Deleted all settings") else: self.btm_frame.cmd_feedback.set("FAILED to command EEPROM") def transmit_message(self, msg): if self.pcan.send_message(msg) != -1: # Message successfully sent self.btm_frame.cmd_feedback.set("Sent message") else: self.btm_frame.cmd_feedback.set("FAILED to send message") _app = App() try: if __name__ == '__main__': _app.mainloop() # Begin interface application finally: # On app close try: _app.update_pcan_open(False) # Close CAN connection _app.update_eeprom('1') # Reset to factory-default settings except: pass
0.298287
0.075892
from __future__ import absolute_import, division, print_function, unicode_literals import sys import os import json import utility import re import requests sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib")) from splunklib.six.moves.urllib.parse import quote_plus from splunklib.searchcommands import dispatch, GeneratingCommand, Configuration, Option from splunklib.binding import HTTPError import logging import splunk def setup_logging(): """ setup_logging as found on http://dev.splunk.com/view/logging/SP-CAAAFCN """ logger = logging.getLogger('splunk.shareprivateobjects') SPLUNK_HOME = os.environ['SPLUNK_HOME'] LOGGING_DEFAULT_CONFIG_FILE = os.path.join(SPLUNK_HOME, 'etc', 'log.cfg') LOGGING_LOCAL_CONFIG_FILE = os.path.join(SPLUNK_HOME, 'etc', 'log-local.cfg') LOGGING_STANZA_NAME = 'python' LOGGING_FILE_NAME = "changedispatch.log" BASE_LOG_PATH = os.path.join('var', 'log', 'splunk') LOGGING_FORMAT = "%(asctime)s %(levelname)-s\t %(message)s" splunk_log_handler = logging.handlers.RotatingFileHandler(os.path.join(SPLUNK_HOME, BASE_LOG_PATH, LOGGING_FILE_NAME), mode='a') splunk_log_handler.setFormatter(logging.Formatter(LOGGING_FORMAT)) logger.addHandler(splunk_log_handler) splunk.setupSplunkLogger(logger, LOGGING_DEFAULT_CONFIG_FILE, LOGGING_LOCAL_CONFIG_FILE, LOGGING_STANZA_NAME) return logger logger = setup_logging() @Configuration(type='reporting') class ChangeDispatchTTLCommand(GeneratingCommand): appname = Option(require=True) newttl = Option(require=True) savedsearch = Option(require=True) owner = Option(require=False) sharing = Option(require=False) def generate(self): """ The logic is: If the requested savedsearch is owned by the current user, or the requesting user is an admin user, then change the dispatch.ttl value of the saved search to the requested newttl value passed in If the optional sharing level is not specified check for the savedsearch in the user context If the owner is specified run the REST call with the specified context, only someone with admin access can use this option """ (username, roles) = utility.determine_username(self.service) #Restricting this option to admin only use if self.owner is not None: if not 'admin' in roles: yield {'result': 'The owner passed in was %s but the user %s does not have the admin role. You may only change the TTL of your own saved searches' % (self.owner, username) } return if self.sharing is not None and self.sharing != 'user': context = 'nobody' else: if self.owner is not None: context = self.owner else: context = username url = 'https://localhost:8089/servicesNS/%s/%s/' % (context, self.appname) url = url + 'saved/searches/%s/?output_mode=json' % (quote_plus(self.savedsearch)) headers = { 'Authorization': 'Splunk ' + self._metadata.searchinfo.session_key } attempt = requests.get(url, verify=False, headers=headers) if attempt.status_code != 200: yield {'result': 'Unknown failure, received a non-200 response code of %s on the URL %s, text result is %s' % (attempt.status_code, url, attempt.text)} return #We received a response but we now need the details on owner, sharing level and the app context it came from acl = json.loads(attempt.text)['entry'][0]['acl'] obj_sharing = acl['sharing'] obj_owner = acl['owner'] obj_app = acl['app'] #We advised an explicit sharing level, but the saved search we found does not match the expected level if self.sharing is not None and obj_sharing != self.sharing: yield {'result': 'Object found but sharing level is %s, expected sharing level of %s, not changing dispatch.ttl in app %s' % (obj_sharing, self.sharing, self.appname) } return #Does the owner of the object match the person logged in? #While technically a user could change the dispatch.ttl if they have write access, we don't want to offer this option if obj_owner != username: #admins are allowed to change dispatch.ttl of any saved search they wish if not 'admin' in roles: yield {'result': 'Object found but owner is %s, user is %s, not changing dispatch.ttl in app %s as you do not have the admin role' % (obj_owner, username, self.appname) } return #Make sure the dispatch.ttl value looks valid if not re.match(r"^[0-9]+p?$", self.newttl): yield {'result': 'The requested new TTL value of %s did not match the regular expression, ttl values are in seconds and can end in a p for execution period.' % (self.newttl) } return #If the saved search is currently app level we must use the nobody context or we create an empty saved search in private context... if obj_sharing != 'user': #A globally shared object may appear to be in this app but could be from a different app #we must post the correct app context otherwise we create an empty saved search with a modified dispatch.ttl in the wrong app #To make it simple for the user we do this for them rather than request them to use the correct app name... if obj_app != self.appname: context = 'nobody/' + obj_app else: context = 'nobody/' + self.appname else: context = obj_owner + '/' + self.appname #At this point we have run our checks so are happy to change the dispatch.ttl value data = { 'dispatch.ttl': self.newttl, 'output_mode': 'json' } url = 'https://localhost:8089/servicesNS/%s/' % (context) url = url + 'saved/searches/%s' % (quote_plus(self.savedsearch)) attempt = requests.post(url, verify=False, data=data, headers=headers) if attempt.status_code != 200: yield {'result': 'Unknown failure, received a non-200 response code of %s on the URL %s, text result is %s' % (attempt.status_code, url, attempt.text)} return else: logger.info("app=%s savedsearch='%s' owner=%s has had the TTL value changed to newttl=%s via url='%s' sharing_arg=%s owner_arg=%s username=%s" % (self.appname, self.savedsearch, obj_owner, self.newttl, url, self.sharing, self.owner, username)) ttl = json.loads(attempt.text)['entry'][0]['content']['dispatch.ttl'] yield {'result': 'TTL updated, new value is showing as %s for saved search %s in app %s with owner %s' % (ttl, self.savedsearch, self.appname, obj_owner) } dispatch(ChangeDispatchTTLCommand, sys.argv, sys.stdin, sys.stdout, __name__)
bin/changedispatchttl.py
from __future__ import absolute_import, division, print_function, unicode_literals import sys import os import json import utility import re import requests sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib")) from splunklib.six.moves.urllib.parse import quote_plus from splunklib.searchcommands import dispatch, GeneratingCommand, Configuration, Option from splunklib.binding import HTTPError import logging import splunk def setup_logging(): """ setup_logging as found on http://dev.splunk.com/view/logging/SP-CAAAFCN """ logger = logging.getLogger('splunk.shareprivateobjects') SPLUNK_HOME = os.environ['SPLUNK_HOME'] LOGGING_DEFAULT_CONFIG_FILE = os.path.join(SPLUNK_HOME, 'etc', 'log.cfg') LOGGING_LOCAL_CONFIG_FILE = os.path.join(SPLUNK_HOME, 'etc', 'log-local.cfg') LOGGING_STANZA_NAME = 'python' LOGGING_FILE_NAME = "changedispatch.log" BASE_LOG_PATH = os.path.join('var', 'log', 'splunk') LOGGING_FORMAT = "%(asctime)s %(levelname)-s\t %(message)s" splunk_log_handler = logging.handlers.RotatingFileHandler(os.path.join(SPLUNK_HOME, BASE_LOG_PATH, LOGGING_FILE_NAME), mode='a') splunk_log_handler.setFormatter(logging.Formatter(LOGGING_FORMAT)) logger.addHandler(splunk_log_handler) splunk.setupSplunkLogger(logger, LOGGING_DEFAULT_CONFIG_FILE, LOGGING_LOCAL_CONFIG_FILE, LOGGING_STANZA_NAME) return logger logger = setup_logging() @Configuration(type='reporting') class ChangeDispatchTTLCommand(GeneratingCommand): appname = Option(require=True) newttl = Option(require=True) savedsearch = Option(require=True) owner = Option(require=False) sharing = Option(require=False) def generate(self): """ The logic is: If the requested savedsearch is owned by the current user, or the requesting user is an admin user, then change the dispatch.ttl value of the saved search to the requested newttl value passed in If the optional sharing level is not specified check for the savedsearch in the user context If the owner is specified run the REST call with the specified context, only someone with admin access can use this option """ (username, roles) = utility.determine_username(self.service) #Restricting this option to admin only use if self.owner is not None: if not 'admin' in roles: yield {'result': 'The owner passed in was %s but the user %s does not have the admin role. You may only change the TTL of your own saved searches' % (self.owner, username) } return if self.sharing is not None and self.sharing != 'user': context = 'nobody' else: if self.owner is not None: context = self.owner else: context = username url = 'https://localhost:8089/servicesNS/%s/%s/' % (context, self.appname) url = url + 'saved/searches/%s/?output_mode=json' % (quote_plus(self.savedsearch)) headers = { 'Authorization': 'Splunk ' + self._metadata.searchinfo.session_key } attempt = requests.get(url, verify=False, headers=headers) if attempt.status_code != 200: yield {'result': 'Unknown failure, received a non-200 response code of %s on the URL %s, text result is %s' % (attempt.status_code, url, attempt.text)} return #We received a response but we now need the details on owner, sharing level and the app context it came from acl = json.loads(attempt.text)['entry'][0]['acl'] obj_sharing = acl['sharing'] obj_owner = acl['owner'] obj_app = acl['app'] #We advised an explicit sharing level, but the saved search we found does not match the expected level if self.sharing is not None and obj_sharing != self.sharing: yield {'result': 'Object found but sharing level is %s, expected sharing level of %s, not changing dispatch.ttl in app %s' % (obj_sharing, self.sharing, self.appname) } return #Does the owner of the object match the person logged in? #While technically a user could change the dispatch.ttl if they have write access, we don't want to offer this option if obj_owner != username: #admins are allowed to change dispatch.ttl of any saved search they wish if not 'admin' in roles: yield {'result': 'Object found but owner is %s, user is %s, not changing dispatch.ttl in app %s as you do not have the admin role' % (obj_owner, username, self.appname) } return #Make sure the dispatch.ttl value looks valid if not re.match(r"^[0-9]+p?$", self.newttl): yield {'result': 'The requested new TTL value of %s did not match the regular expression, ttl values are in seconds and can end in a p for execution period.' % (self.newttl) } return #If the saved search is currently app level we must use the nobody context or we create an empty saved search in private context... if obj_sharing != 'user': #A globally shared object may appear to be in this app but could be from a different app #we must post the correct app context otherwise we create an empty saved search with a modified dispatch.ttl in the wrong app #To make it simple for the user we do this for them rather than request them to use the correct app name... if obj_app != self.appname: context = 'nobody/' + obj_app else: context = 'nobody/' + self.appname else: context = obj_owner + '/' + self.appname #At this point we have run our checks so are happy to change the dispatch.ttl value data = { 'dispatch.ttl': self.newttl, 'output_mode': 'json' } url = 'https://localhost:8089/servicesNS/%s/' % (context) url = url + 'saved/searches/%s' % (quote_plus(self.savedsearch)) attempt = requests.post(url, verify=False, data=data, headers=headers) if attempt.status_code != 200: yield {'result': 'Unknown failure, received a non-200 response code of %s on the URL %s, text result is %s' % (attempt.status_code, url, attempt.text)} return else: logger.info("app=%s savedsearch='%s' owner=%s has had the TTL value changed to newttl=%s via url='%s' sharing_arg=%s owner_arg=%s username=%s" % (self.appname, self.savedsearch, obj_owner, self.newttl, url, self.sharing, self.owner, username)) ttl = json.loads(attempt.text)['entry'][0]['content']['dispatch.ttl'] yield {'result': 'TTL updated, new value is showing as %s for saved search %s in app %s with owner %s' % (ttl, self.savedsearch, self.appname, obj_owner) } dispatch(ChangeDispatchTTLCommand, sys.argv, sys.stdin, sys.stdout, __name__)
0.390011
0.075551
import asyncio import voluptuous as vol from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice from homeassistant.const import CONF_NAME from homeassistant.core import callback import homeassistant.helpers.config_validation as cv CONF_ADDRESS = 'address' CONF_STATE_ADDRESS = 'state_address' DEFAULT_NAME = 'KNX Switch' DEPENDENCIES = ['knx'] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ADDRESS): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_STATE_ADDRESS): cv.string, }) @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up switch(es) for KNX platform.""" if discovery_info is not None: async_add_devices_discovery(hass, discovery_info, async_add_devices) else: async_add_devices_config(hass, config, async_add_devices) @callback def async_add_devices_discovery(hass, discovery_info, async_add_devices): """Set up switches for KNX platform configured via xknx.yaml.""" entities = [] for device_name in discovery_info[ATTR_DISCOVER_DEVICES]: device = hass.data[DATA_KNX].xknx.devices[device_name] entities.append(KNXSwitch(hass, device)) async_add_devices(entities) @callback def async_add_devices_config(hass, config, async_add_devices): """Set up switch for KNX platform configured within platform.""" import xknx switch = xknx.devices.Switch( hass.data[DATA_KNX].xknx, name=config.get(CONF_NAME), group_address=config.get(CONF_ADDRESS), group_address_state=config.get(CONF_STATE_ADDRESS)) hass.data[DATA_KNX].xknx.devices.add(switch) async_add_devices([KNXSwitch(hass, switch)]) class KNXSwitch(SwitchDevice): """Representation of a KNX switch.""" def __init__(self, hass, device): """Initialize of KNX switch.""" self.device = device self.hass = hass self.async_register_callbacks() @callback def async_register_callbacks(self): """Register callbacks to update hass after device was changed.""" @asyncio.coroutine def after_update_callback(device): """Call after device was updated.""" # pylint: disable=unused-argument yield from self.async_update_ha_state() self.device.register_device_updated_cb(after_update_callback) @property def name(self): """Return the name of the KNX device.""" return self.device.name @property def available(self): """Return true if entity is available.""" return self.hass.data[DATA_KNX].connected @property def should_poll(self): """Return the polling state. Not needed within KNX.""" return False @property def is_on(self): """Return true if device is on.""" return self.device.state @asyncio.coroutine def async_turn_on(self, **kwargs): """Turn the device on.""" yield from self.device.set_on() @asyncio.coroutine def async_turn_off(self, **kwargs): """Turn the device off.""" yield from self.device.set_off()
homeassistant/components/switch/knx.py
import asyncio import voluptuous as vol from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice from homeassistant.const import CONF_NAME from homeassistant.core import callback import homeassistant.helpers.config_validation as cv CONF_ADDRESS = 'address' CONF_STATE_ADDRESS = 'state_address' DEFAULT_NAME = 'KNX Switch' DEPENDENCIES = ['knx'] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ADDRESS): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_STATE_ADDRESS): cv.string, }) @asyncio.coroutine def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up switch(es) for KNX platform.""" if discovery_info is not None: async_add_devices_discovery(hass, discovery_info, async_add_devices) else: async_add_devices_config(hass, config, async_add_devices) @callback def async_add_devices_discovery(hass, discovery_info, async_add_devices): """Set up switches for KNX platform configured via xknx.yaml.""" entities = [] for device_name in discovery_info[ATTR_DISCOVER_DEVICES]: device = hass.data[DATA_KNX].xknx.devices[device_name] entities.append(KNXSwitch(hass, device)) async_add_devices(entities) @callback def async_add_devices_config(hass, config, async_add_devices): """Set up switch for KNX platform configured within platform.""" import xknx switch = xknx.devices.Switch( hass.data[DATA_KNX].xknx, name=config.get(CONF_NAME), group_address=config.get(CONF_ADDRESS), group_address_state=config.get(CONF_STATE_ADDRESS)) hass.data[DATA_KNX].xknx.devices.add(switch) async_add_devices([KNXSwitch(hass, switch)]) class KNXSwitch(SwitchDevice): """Representation of a KNX switch.""" def __init__(self, hass, device): """Initialize of KNX switch.""" self.device = device self.hass = hass self.async_register_callbacks() @callback def async_register_callbacks(self): """Register callbacks to update hass after device was changed.""" @asyncio.coroutine def after_update_callback(device): """Call after device was updated.""" # pylint: disable=unused-argument yield from self.async_update_ha_state() self.device.register_device_updated_cb(after_update_callback) @property def name(self): """Return the name of the KNX device.""" return self.device.name @property def available(self): """Return true if entity is available.""" return self.hass.data[DATA_KNX].connected @property def should_poll(self): """Return the polling state. Not needed within KNX.""" return False @property def is_on(self): """Return true if device is on.""" return self.device.state @asyncio.coroutine def async_turn_on(self, **kwargs): """Turn the device on.""" yield from self.device.set_on() @asyncio.coroutine def async_turn_off(self, **kwargs): """Turn the device off.""" yield from self.device.set_off()
0.668231
0.107017
"""Tests using pytest_resilient_circuits""" from __future__ import print_function import pytest from resilient_circuits.util import get_config_data, get_function_definition from resilient_circuits import SubmitTestFunction, FunctionResult PACKAGE_NAME = "fn_codegen_test" FUNCTION_NAME = "utilities_base64_to_artifact" # Read the default configuration-data section from the package config_data = get_config_data(PACKAGE_NAME) # Provide a simulation of the Resilient REST API (uncomment to connect to a real appliance) resilient_mock = "pytest_resilient_circuits.BasicResilientMock" def call_utilities_base64_to_artifact_function(circuits, function_params, timeout=10): # Fire a message to the function evt = SubmitTestFunction("utilities_base64_to_artifact", function_params) circuits.manager.fire(evt) event = circuits.watcher.wait("utilities_base64_to_artifact_result", parent=evt, timeout=timeout) assert event assert isinstance(event.kwargs["result"], FunctionResult) pytest.wait_for(event, "complete", True) return event.kwargs["result"].value class TestUtilitiesBase64ToArtifact: """ Tests for the utilities_base64_to_artifact function""" def test_function_definition(self): """ Test that the package provides customization_data that defines the function """ func = get_function_definition(PACKAGE_NAME, FUNCTION_NAME) assert func is not None @pytest.mark.parametrize("base64content, incident_id, artifact_file_type, file_name, content_type, description, expected_results", [ ("text", 123, 'Email Attachment', "text", "text", {"type": "text", "content": "line1\nline2"}, {"value": "xyz"}), ("text", 123, 'Malware Sample', "text", "text", {"type": "text", "content": "line1\nline2"}, {"value": "xyz"}) ]) def test_success(self, circuits_app, base64content, incident_id, artifact_file_type, file_name, content_type, description, expected_results): """ Test calling with sample values for the parameters """ function_params = { "base64content": base64content, "incident_id": incident_id, "artifact_file_type": artifact_file_type, "file_name": file_name, "content_type": content_type, "description": description } results = call_utilities_base64_to_artifact_function(circuits_app, function_params) assert(expected_results == results)
fn_codegen_test/tests/test_utilities_base64_to_artifact.py
"""Tests using pytest_resilient_circuits""" from __future__ import print_function import pytest from resilient_circuits.util import get_config_data, get_function_definition from resilient_circuits import SubmitTestFunction, FunctionResult PACKAGE_NAME = "fn_codegen_test" FUNCTION_NAME = "utilities_base64_to_artifact" # Read the default configuration-data section from the package config_data = get_config_data(PACKAGE_NAME) # Provide a simulation of the Resilient REST API (uncomment to connect to a real appliance) resilient_mock = "pytest_resilient_circuits.BasicResilientMock" def call_utilities_base64_to_artifact_function(circuits, function_params, timeout=10): # Fire a message to the function evt = SubmitTestFunction("utilities_base64_to_artifact", function_params) circuits.manager.fire(evt) event = circuits.watcher.wait("utilities_base64_to_artifact_result", parent=evt, timeout=timeout) assert event assert isinstance(event.kwargs["result"], FunctionResult) pytest.wait_for(event, "complete", True) return event.kwargs["result"].value class TestUtilitiesBase64ToArtifact: """ Tests for the utilities_base64_to_artifact function""" def test_function_definition(self): """ Test that the package provides customization_data that defines the function """ func = get_function_definition(PACKAGE_NAME, FUNCTION_NAME) assert func is not None @pytest.mark.parametrize("base64content, incident_id, artifact_file_type, file_name, content_type, description, expected_results", [ ("text", 123, 'Email Attachment', "text", "text", {"type": "text", "content": "line1\nline2"}, {"value": "xyz"}), ("text", 123, 'Malware Sample', "text", "text", {"type": "text", "content": "line1\nline2"}, {"value": "xyz"}) ]) def test_success(self, circuits_app, base64content, incident_id, artifact_file_type, file_name, content_type, description, expected_results): """ Test calling with sample values for the parameters """ function_params = { "base64content": base64content, "incident_id": incident_id, "artifact_file_type": artifact_file_type, "file_name": file_name, "content_type": content_type, "description": description } results = call_utilities_base64_to_artifact_function(circuits_app, function_params) assert(expected_results == results)
0.807157
0.418697
from __future__ import annotations # postpone evaluation of annotations import logging from typing import Any, Dict, List, Optional, Tuple import cv2 import numpy as np import numpy.typing as npt from pyquaternion import Quaternion from scipy import ndimage from scipy.spatial.transform import Rotation as R from sqlalchemy import Column, inspect from sqlalchemy.orm import relationship from sqlalchemy.schema import ForeignKey from sqlalchemy.types import Float, Integer from nuplan.database.common import sql_types from nuplan.database.common.utils import simple_repr from nuplan.database.maps_db.gpkg_mapsdb import GPKGMapsDB from nuplan.database.maps_db.utils import build_lane_segments_from_blps, connect_blp_predecessor, connect_blp_successor from nuplan.database.nuplan_db.models import Base, Image, generate_multi_scale_connections from nuplan.database.nuplan_db.utils import crop_rect, get_candidates from nuplan.database.nuplan_db.vector_map_np import VectorMapNp logger = logging.getLogger() class EgoPose(Base): """ Ego vehicle pose at a particular timestamp. Given with respect to global coordinate system. """ __tablename__ = "ego_pose" token = Column(sql_types.HexLen8, primary_key=True) # type: str timestamp = Column(Integer) # field type: int x = Column(Float) # type: float y = Column(Float) # type: float z = Column(Float) # type: float qw: float = Column(Float) qx: float = Column(Float) qy: float = Column(Float) qz: float = Column(Float) vx = Column(Float) # type: float vy = Column(Float) # type: float vz = Column(Float) # type: float acceleration_x = Column(Float) # type: float acceleration_y = Column(Float) # type: float acceleration_z = Column(Float) # type: float angular_rate_x = Column(Float) # type: float angular_rate_y = Column(Float) # type: float angular_rate_z = Column(Float) # type: float epsg = Column(Integer) # type: int log_token = Column(sql_types.HexLen8, ForeignKey("log.token"), nullable=False) # type: str image = relationship( "Image", foreign_keys="Image.ego_pose_token", back_populates="ego_pose", uselist=False ) # type: Image @property def _session(self) -> Any: """ Get the underlying session. :return: The underlying session. """ return inspect(self).session def __repr__(self) -> str: """ Return the string representation. :return: The string representation. """ desc: str = simple_repr(self) return desc @property def quaternion(self) -> Quaternion: """ Get the orientation of ego vehicle as quaternion respect to global coordinate system. :return: The orientation in quaternion. """ return Quaternion(self.qw, self.qx, self.qy, self.qz) @property def translation_np(self) -> npt.NDArray[np.float64]: """ Position of ego vehicle respect to global coordinate system. :return: <np.float: 3> Translation. """ return np.array([self.x, self.y, self.z]) @property def trans_matrix(self) -> npt.NDArray[np.float64]: """ Get the transformation matrix. :return: <np.float: 4, 4>. Transformation matrix. """ tm: npt.NDArray[np.float64] = self.quaternion.transformation_matrix tm[:3, 3] = self.translation_np return tm @property def trans_matrix_inv(self) -> npt.NDArray[np.float64]: """ Get the inverse transformation matrix. :return: <np.float: 4, 4>. Inverse transformation matrix. """ tm: npt.NDArray[np.float64] = np.eye(4) rot_inv = self.quaternion.rotation_matrix.T tm[:3, :3] = rot_inv tm[:3, 3] = rot_inv.dot(np.transpose(-self.translation_np)) return tm def rotate_2d_points2d_to_ego_vehicle_frame(self, points2d: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]: """ Rotate 2D points from global frame to ego-vehicle frame. :param points2d: <np.float: num_points, 2>. 2D points in global frame. :return: <np.float: num_points, 2>. 2D points rotated to ego-vehicle frame. """ # Add zeros to the z dimension to make them 3D points. points3d: npt.NDArray[np.float32] = np.concatenate((points2d, np.zeros_like(points2d[:, 0:1])), axis=-1) # We need to extract the rotation around the z-axis only. since we are cropping a 2D map. # Construct scipy rotation instance using the rotation matrix from quaternion. rotation = R.from_matrix(self.quaternion.rotation_matrix.T) # Extract the angle of rotation around z-axis from the rotation. ego_rotation_angle = rotation.as_euler('zxy', degrees=True)[0] # Construct scipy rotation instance using ego_rotation_angle. xy_rotation = R.from_euler('z', ego_rotation_angle, degrees=True) # Rotate the corner points of the desired map crop to align with ego pose. rotated_points3d = xy_rotation.apply(points3d) # Remove the z dimension. rotated_points2d: npt.NDArray[np.float64] = rotated_points3d[:, :2] return rotated_points2d def get_map_crop( self, maps_db: Optional[GPKGMapsDB], xrange: Tuple[float, float], yrange: Tuple[float, float], map_layer_name: str, rotate_face_up: bool, target_imsize_xy: Optional[Tuple[float, float]] = None, ) -> Tuple[Optional[npt.NDArray[np.float64]], npt.NDArray[np.float64], Tuple[float, ...]]: """ This function returns the crop of the map centered at the current ego-pose with the given xrange and yrange. :param maps_db: Map database associated with this database. :param xrange: The range in x direction in meters relative to the current ego-pose. Eg: (-60, 60]). :param yrange: The range in y direction in meters relative to the current ego-pose Eg: (-60, 60). :param map_layer_name: A relevant map layer. Eg: 'drivable_area' or 'intensity'. :param rotate_face_up: Boolean indicating whether to rotate the image face up with respect to ego-pose. :param target_imsize_xy: The target grid xy dimensions for the output array. The xy resolution in meters / grid may be scaled by zooming to the desired dimensions. :return: (map_crop, map_translation, map_scale). Where: map_crop: The desired crop of the map. map_translation: The translation in map coordinates from the origin to the ego-pose. map_scale: Map scale (inverse of the map precision). This will be a tuple specifying the zoom in both the x and y direction if the target_imsize_xy parameter was set, which causes the resolution to change. map_scale and map_translation are useful for transforming objects like pointcloud/boxes to the map_crop. Refer to render_on_map(). """ if maps_db is None: precision: float = 1 def to_pixel_coords(x: float, y: float) -> Tuple[float, float]: """ Get the image coordinates given the x-y coordinates of point. This implementation simply returns the same coordinates. :param x: Global x coordinate. :param y: Global y coordinate. :return: Pixel coordinates in map. """ return x, y else: map_layer = maps_db.load_layer(self.log.map_version, map_layer_name) precision = map_layer.precision to_pixel_coords = map_layer.to_pixel_coords map_scale: Tuple[float, ...] = (1.0 / precision, 1.0 / precision, 1.0) ego_translation = self.translation_np center_x, center_y = to_pixel_coords(ego_translation[0], ego_translation[1]) center_x, center_y = int(center_x), int(center_y) top_left = int(xrange[0] * map_scale[0]), int(yrange[0] * map_scale[1]) bottom_right = int(xrange[1] * map_scale[0]), int(yrange[1] * map_scale[1]) # We need to extract the rotation around the z-axis only. since we are cropping a 2D map. # Construct scipy rotation instance using the rotation matrix from quaternion. rotation = R.from_matrix(self.quaternion.rotation_matrix.T) # Extract the angle of rotation around z-axis from the rotation. ego_rotation_angle = rotation.as_euler('zxy', degrees=True)[0] # Construct scipy rotation instance using ego_rotation_angle. xy_rotation = R.from_euler('z', ego_rotation_angle, degrees=True) map_rotate = 0 # Rotate the corner points of the desired map crop to align with ego pose. rotated = xy_rotation.apply( [ [top_left[0], top_left[1], 0], [top_left[0], bottom_right[1], 0], [bottom_right[0], top_left[1], 0], [bottom_right[0], bottom_right[1], 0], ] )[:, :2] # Construct minAreaRect using 4 corner points rect = cv2.minAreaRect(np.hstack([rotated[:, :1] + center_x, rotated[:, 1:] + center_y]).astype(int)) rect_angle = rect[2] # Due to rounding error, the dimensions returned by cv2 may be off by 1, therefore it's better to manually # calculate the cropped dimensions instead of relying on the values returned by cv2 in rect[1] cropped_dimensions: npt.NDArray[np.float32] = np.array( [map_scale[0] * (xrange[1] - xrange[0]), map_scale[1] * (yrange[1] - yrange[0])] ) rect = (rect[0], cropped_dimensions, rect_angle) # In OpenCV 4.4, the angle returned by cv2.minAreaRect is [-90,0). In OpenCV 4.5, the angle returned # appears to be [0, 90), though this isn't documented anywhere. To be compatible with both versions, # we adjust the angle to be [-90,0) if it isn't already. rect_angle = rect[2] cropped_dimensions = np.array([map_scale[0] * (xrange[1] - xrange[0]), map_scale[1] * (yrange[1] - yrange[0])]) if rect_angle >= 0: rect = (rect[0], cropped_dimensions, rect_angle - 90) else: rect = (rect[0], cropped_dimensions, rect_angle) # We construct rect using cv2.minAreaRect, which takes only 4 unordered corner points, and can not consider # the angle of the required rect. The range of of 'angle' in cv2.minAreaRect is [-90,0). # A good explanation for the angle can be found at : # https://namkeenman.wordpress.com/2015/12/18/open-cv-determine-angle-of-rotatedrect-minarearect/ # Hence, we have to manually rotate the map after cropping based on the initial rotation angle. if ego_rotation_angle < -90: map_rotate = -90 if -90 < ego_rotation_angle < 0: map_rotate = 0 if 0 < ego_rotation_angle < 90: map_rotate = 90 if 90 < ego_rotation_angle < 180: map_rotate = 180 if map_layer is None: map_crop = None else: # Crop the rect using minAreaRect. map_crop = crop_rect(map_layer.data, rect) # Rotate the cropped map using adjusted angles, # since the angle is reset in cv2.minAreaRect every 90 degrees. map_crop = ndimage.rotate(map_crop, map_rotate, reshape=False) if rotate_face_up: # The map_crop is aligned with the ego_pose, but ego_pose is facing towards the right of the canvas, # but we need ego_pose to be facing up, hence rotating an extra 90 degrees. map_crop = np.rot90(map_crop) # These are in units of pixels, where x points to the right and y points *down*. if map_layer is None: map_upper_left_offset_from_global_coordinate_origin = np.zeros((2,)) else: map_upper_left_offset_from_global_coordinate_origin = np.array( [-map_layer.transform_matrix[0, -1], map_layer.transform_matrix[1, -1]] ) ego_offset_from_map_upper_left: npt.NDArray[np.float32] = np.array([center_x, -center_y]) crop_upper_left_offset_from_ego: npt.NDArray[np.float32] = np.array( [xrange[0] * map_scale[0], yrange[0] * map_scale[1]] ) map_translation: npt.NDArray[np.float64] = ( -map_upper_left_offset_from_global_coordinate_origin - ego_offset_from_map_upper_left - crop_upper_left_offset_from_ego ) map_translation_with_z: npt.NDArray[np.float64] = np.array( [map_translation[0], map_translation[1], 0] ) # add z-coordinate if target_imsize_xy is not None: zoom_size_x = target_imsize_xy[0] / cropped_dimensions[0] zoom_size_y = target_imsize_xy[1] / cropped_dimensions[1] map_crop = ndimage.zoom(map_crop, [zoom_size_x, zoom_size_y]) map_scale = (zoom_size_x, zoom_size_y) return map_crop, map_translation_with_z, map_scale def get_vector_map( self, maps_db: Optional[GPKGMapsDB], xrange: Tuple[float, float], yrange: Tuple[float, float], connection_scales: Optional[List[int]] = None, ) -> VectorMapNp: """ This function returns the crop of baseline paths (blps) map centered at the current ego-pose with the given xrange and yrange. :param maps_db: Map database associated with this database. :param xrange: The range in x direction in meters relative to the current ego-pose. Eg: [-60, 60]. :param yrange: The range in y direction in meters relative to the current ego-pose Eg: [-60, 60]. :param connection_scales: Connection scales to generate. Use the 1-hop connections if it's left empty. :return: Vector map data including lane segment coordinates and connections within the given range. """ # load geopandas data map_version = self.lidar_pc.log.map_version.replace('.gpkg', '') blps_gdf = maps_db.load_vector_layer(map_version, 'baseline_paths') # type: ignore lane_poly_gdf = maps_db.load_vector_layer(map_version, 'lanes_polygons') # type: ignore intersections_gdf = maps_db.load_vector_layer(map_version, 'intersections') # type: ignore lane_connectors_gdf = maps_db.load_vector_layer(map_version, 'lane_connectors') # type: ignore lane_groups_gdf = maps_db.load_vector_layer(map_version, 'lane_groups_polygons') # type: ignore if ( (blps_gdf is None) or (lane_poly_gdf is None) or (intersections_gdf is None) or (lane_connectors_gdf is None) or (lane_groups_gdf is None) ): # This sample has no vector map. coords: npt.NDArray[np.float32] = np.empty([0, 2, 2], dtype=np.float32) if not connection_scales: # Use the 1-hop connections if connection_scales is not specified. connection_scales = [1] multi_scale_connections: Dict[int, Any] = { scale: np.empty([0, 2], dtype=np.int64) for scale in connection_scales } return VectorMapNp( coords=coords, multi_scale_connections=multi_scale_connections, ) # data enhancement blps_in_lanes = blps_gdf[blps_gdf['lane_fid'].notna()] blps_in_intersections = blps_gdf[blps_gdf['lane_connector_fid'].notna()] # enhance blps_in_lanes lane_group_info = lane_poly_gdf[['lane_fid', 'lane_group_fid']] blps_in_lanes = blps_in_lanes.merge(lane_group_info, on='lane_fid', how='outer') # enhance blps_in_intersections lane_connectors_gdf['lane_connector_fid'] = lane_connectors_gdf['fid'] lane_conns_info = lane_connectors_gdf[ ['lane_connector_fid', 'intersection_fid', 'exit_lane_fid', 'entry_lane_fid'] ] # Convert the exit_fid field of both data frames to the same dtype for merging. lane_conns_info = lane_conns_info.astype({'lane_connector_fid': int}) blps_in_intersections = blps_in_intersections.astype({'lane_connector_fid': int}) blps_in_intersections = blps_in_intersections.merge(lane_conns_info, on='lane_connector_fid', how='outer') # enhance blps_connection info lane_blps_info = blps_in_lanes[['fid', 'lane_fid']] from_blps_info = lane_blps_info.rename(columns={'fid': 'from_blp', 'lane_fid': 'exit_lane_fid'}) to_blps_info = lane_blps_info.rename(columns={'fid': 'to_blp', 'lane_fid': 'entry_lane_fid'}) blps_in_intersections = blps_in_intersections.merge(from_blps_info, on='exit_lane_fid', how='inner') blps_in_intersections = blps_in_intersections.merge(to_blps_info, on='entry_lane_fid', how='inner') # Select in-range blps candidate_lane_groups, candidate_intersections = get_candidates( self.translation_np, xrange, yrange, lane_groups_gdf, intersections_gdf ) candidate_blps_in_lanes = blps_in_lanes[ blps_in_lanes['lane_group_fid'].isin(candidate_lane_groups['fid'].astype(int)) ] candidate_blps_in_intersections = blps_in_intersections[ blps_in_intersections['intersection_fid'].isin(candidate_intersections['fid'].astype(int)) ] ls_coordinates_list: List[List[List[float]]] = [] ls_connections_list: List[List[int]] = [] ls_groupings_list: List[List[int]] = [] cross_blp_connection: Dict[str, List[int]] = dict() # generate lane_segments from blps in lanes build_lane_segments_from_blps( candidate_blps_in_lanes, ls_coordinates_list, ls_connections_list, ls_groupings_list, cross_blp_connection ) # generate lane_segments from blps in intersections build_lane_segments_from_blps( candidate_blps_in_intersections, ls_coordinates_list, ls_connections_list, ls_groupings_list, cross_blp_connection, ) # generate connections between blps for blp_id, blp_info in cross_blp_connection.items(): # Add predecessors connect_blp_predecessor(blp_id, candidate_blps_in_intersections, cross_blp_connection, ls_connections_list) # Add successors connect_blp_successor(blp_id, candidate_blps_in_intersections, cross_blp_connection, ls_connections_list) ls_coordinates: npt.NDArray[np.float64] = np.asarray(ls_coordinates_list, self.translation_np.dtype) ls_connections: npt.NDArray[np.int64] = np.asarray(ls_connections_list, np.int64) # Transform the lane coordinates from global frame to ego vehicle frame. # Flatten ls_coordinates from (num_ls, 2, 2) to (num_ls * 2, 2) for easier processing. ls_coordinates = ls_coordinates.reshape(-1, 2) ls_coordinates = ls_coordinates - self.translation_np[:2] ls_coordinates = self.rotate_2d_points2d_to_ego_vehicle_frame(ls_coordinates) ls_coordinates = ls_coordinates.reshape(-1, 2, 2).astype(np.float32) if connection_scales: # Generate multi-scale connections. multi_scale_connections = generate_multi_scale_connections(ls_connections, connection_scales) else: # Use the 1-hop connections if connection_scales is not specified. multi_scale_connections = {1: ls_connections} return VectorMapNp( coords=ls_coordinates, multi_scale_connections=multi_scale_connections, ) Image.ego_pose = relationship("EgoPose", foreign_keys=[Image.ego_pose_token], back_populates="image")
nuplan/database/nuplan_db/ego_pose.py
from __future__ import annotations # postpone evaluation of annotations import logging from typing import Any, Dict, List, Optional, Tuple import cv2 import numpy as np import numpy.typing as npt from pyquaternion import Quaternion from scipy import ndimage from scipy.spatial.transform import Rotation as R from sqlalchemy import Column, inspect from sqlalchemy.orm import relationship from sqlalchemy.schema import ForeignKey from sqlalchemy.types import Float, Integer from nuplan.database.common import sql_types from nuplan.database.common.utils import simple_repr from nuplan.database.maps_db.gpkg_mapsdb import GPKGMapsDB from nuplan.database.maps_db.utils import build_lane_segments_from_blps, connect_blp_predecessor, connect_blp_successor from nuplan.database.nuplan_db.models import Base, Image, generate_multi_scale_connections from nuplan.database.nuplan_db.utils import crop_rect, get_candidates from nuplan.database.nuplan_db.vector_map_np import VectorMapNp logger = logging.getLogger() class EgoPose(Base): """ Ego vehicle pose at a particular timestamp. Given with respect to global coordinate system. """ __tablename__ = "ego_pose" token = Column(sql_types.HexLen8, primary_key=True) # type: str timestamp = Column(Integer) # field type: int x = Column(Float) # type: float y = Column(Float) # type: float z = Column(Float) # type: float qw: float = Column(Float) qx: float = Column(Float) qy: float = Column(Float) qz: float = Column(Float) vx = Column(Float) # type: float vy = Column(Float) # type: float vz = Column(Float) # type: float acceleration_x = Column(Float) # type: float acceleration_y = Column(Float) # type: float acceleration_z = Column(Float) # type: float angular_rate_x = Column(Float) # type: float angular_rate_y = Column(Float) # type: float angular_rate_z = Column(Float) # type: float epsg = Column(Integer) # type: int log_token = Column(sql_types.HexLen8, ForeignKey("log.token"), nullable=False) # type: str image = relationship( "Image", foreign_keys="Image.ego_pose_token", back_populates="ego_pose", uselist=False ) # type: Image @property def _session(self) -> Any: """ Get the underlying session. :return: The underlying session. """ return inspect(self).session def __repr__(self) -> str: """ Return the string representation. :return: The string representation. """ desc: str = simple_repr(self) return desc @property def quaternion(self) -> Quaternion: """ Get the orientation of ego vehicle as quaternion respect to global coordinate system. :return: The orientation in quaternion. """ return Quaternion(self.qw, self.qx, self.qy, self.qz) @property def translation_np(self) -> npt.NDArray[np.float64]: """ Position of ego vehicle respect to global coordinate system. :return: <np.float: 3> Translation. """ return np.array([self.x, self.y, self.z]) @property def trans_matrix(self) -> npt.NDArray[np.float64]: """ Get the transformation matrix. :return: <np.float: 4, 4>. Transformation matrix. """ tm: npt.NDArray[np.float64] = self.quaternion.transformation_matrix tm[:3, 3] = self.translation_np return tm @property def trans_matrix_inv(self) -> npt.NDArray[np.float64]: """ Get the inverse transformation matrix. :return: <np.float: 4, 4>. Inverse transformation matrix. """ tm: npt.NDArray[np.float64] = np.eye(4) rot_inv = self.quaternion.rotation_matrix.T tm[:3, :3] = rot_inv tm[:3, 3] = rot_inv.dot(np.transpose(-self.translation_np)) return tm def rotate_2d_points2d_to_ego_vehicle_frame(self, points2d: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]: """ Rotate 2D points from global frame to ego-vehicle frame. :param points2d: <np.float: num_points, 2>. 2D points in global frame. :return: <np.float: num_points, 2>. 2D points rotated to ego-vehicle frame. """ # Add zeros to the z dimension to make them 3D points. points3d: npt.NDArray[np.float32] = np.concatenate((points2d, np.zeros_like(points2d[:, 0:1])), axis=-1) # We need to extract the rotation around the z-axis only. since we are cropping a 2D map. # Construct scipy rotation instance using the rotation matrix from quaternion. rotation = R.from_matrix(self.quaternion.rotation_matrix.T) # Extract the angle of rotation around z-axis from the rotation. ego_rotation_angle = rotation.as_euler('zxy', degrees=True)[0] # Construct scipy rotation instance using ego_rotation_angle. xy_rotation = R.from_euler('z', ego_rotation_angle, degrees=True) # Rotate the corner points of the desired map crop to align with ego pose. rotated_points3d = xy_rotation.apply(points3d) # Remove the z dimension. rotated_points2d: npt.NDArray[np.float64] = rotated_points3d[:, :2] return rotated_points2d def get_map_crop( self, maps_db: Optional[GPKGMapsDB], xrange: Tuple[float, float], yrange: Tuple[float, float], map_layer_name: str, rotate_face_up: bool, target_imsize_xy: Optional[Tuple[float, float]] = None, ) -> Tuple[Optional[npt.NDArray[np.float64]], npt.NDArray[np.float64], Tuple[float, ...]]: """ This function returns the crop of the map centered at the current ego-pose with the given xrange and yrange. :param maps_db: Map database associated with this database. :param xrange: The range in x direction in meters relative to the current ego-pose. Eg: (-60, 60]). :param yrange: The range in y direction in meters relative to the current ego-pose Eg: (-60, 60). :param map_layer_name: A relevant map layer. Eg: 'drivable_area' or 'intensity'. :param rotate_face_up: Boolean indicating whether to rotate the image face up with respect to ego-pose. :param target_imsize_xy: The target grid xy dimensions for the output array. The xy resolution in meters / grid may be scaled by zooming to the desired dimensions. :return: (map_crop, map_translation, map_scale). Where: map_crop: The desired crop of the map. map_translation: The translation in map coordinates from the origin to the ego-pose. map_scale: Map scale (inverse of the map precision). This will be a tuple specifying the zoom in both the x and y direction if the target_imsize_xy parameter was set, which causes the resolution to change. map_scale and map_translation are useful for transforming objects like pointcloud/boxes to the map_crop. Refer to render_on_map(). """ if maps_db is None: precision: float = 1 def to_pixel_coords(x: float, y: float) -> Tuple[float, float]: """ Get the image coordinates given the x-y coordinates of point. This implementation simply returns the same coordinates. :param x: Global x coordinate. :param y: Global y coordinate. :return: Pixel coordinates in map. """ return x, y else: map_layer = maps_db.load_layer(self.log.map_version, map_layer_name) precision = map_layer.precision to_pixel_coords = map_layer.to_pixel_coords map_scale: Tuple[float, ...] = (1.0 / precision, 1.0 / precision, 1.0) ego_translation = self.translation_np center_x, center_y = to_pixel_coords(ego_translation[0], ego_translation[1]) center_x, center_y = int(center_x), int(center_y) top_left = int(xrange[0] * map_scale[0]), int(yrange[0] * map_scale[1]) bottom_right = int(xrange[1] * map_scale[0]), int(yrange[1] * map_scale[1]) # We need to extract the rotation around the z-axis only. since we are cropping a 2D map. # Construct scipy rotation instance using the rotation matrix from quaternion. rotation = R.from_matrix(self.quaternion.rotation_matrix.T) # Extract the angle of rotation around z-axis from the rotation. ego_rotation_angle = rotation.as_euler('zxy', degrees=True)[0] # Construct scipy rotation instance using ego_rotation_angle. xy_rotation = R.from_euler('z', ego_rotation_angle, degrees=True) map_rotate = 0 # Rotate the corner points of the desired map crop to align with ego pose. rotated = xy_rotation.apply( [ [top_left[0], top_left[1], 0], [top_left[0], bottom_right[1], 0], [bottom_right[0], top_left[1], 0], [bottom_right[0], bottom_right[1], 0], ] )[:, :2] # Construct minAreaRect using 4 corner points rect = cv2.minAreaRect(np.hstack([rotated[:, :1] + center_x, rotated[:, 1:] + center_y]).astype(int)) rect_angle = rect[2] # Due to rounding error, the dimensions returned by cv2 may be off by 1, therefore it's better to manually # calculate the cropped dimensions instead of relying on the values returned by cv2 in rect[1] cropped_dimensions: npt.NDArray[np.float32] = np.array( [map_scale[0] * (xrange[1] - xrange[0]), map_scale[1] * (yrange[1] - yrange[0])] ) rect = (rect[0], cropped_dimensions, rect_angle) # In OpenCV 4.4, the angle returned by cv2.minAreaRect is [-90,0). In OpenCV 4.5, the angle returned # appears to be [0, 90), though this isn't documented anywhere. To be compatible with both versions, # we adjust the angle to be [-90,0) if it isn't already. rect_angle = rect[2] cropped_dimensions = np.array([map_scale[0] * (xrange[1] - xrange[0]), map_scale[1] * (yrange[1] - yrange[0])]) if rect_angle >= 0: rect = (rect[0], cropped_dimensions, rect_angle - 90) else: rect = (rect[0], cropped_dimensions, rect_angle) # We construct rect using cv2.minAreaRect, which takes only 4 unordered corner points, and can not consider # the angle of the required rect. The range of of 'angle' in cv2.minAreaRect is [-90,0). # A good explanation for the angle can be found at : # https://namkeenman.wordpress.com/2015/12/18/open-cv-determine-angle-of-rotatedrect-minarearect/ # Hence, we have to manually rotate the map after cropping based on the initial rotation angle. if ego_rotation_angle < -90: map_rotate = -90 if -90 < ego_rotation_angle < 0: map_rotate = 0 if 0 < ego_rotation_angle < 90: map_rotate = 90 if 90 < ego_rotation_angle < 180: map_rotate = 180 if map_layer is None: map_crop = None else: # Crop the rect using minAreaRect. map_crop = crop_rect(map_layer.data, rect) # Rotate the cropped map using adjusted angles, # since the angle is reset in cv2.minAreaRect every 90 degrees. map_crop = ndimage.rotate(map_crop, map_rotate, reshape=False) if rotate_face_up: # The map_crop is aligned with the ego_pose, but ego_pose is facing towards the right of the canvas, # but we need ego_pose to be facing up, hence rotating an extra 90 degrees. map_crop = np.rot90(map_crop) # These are in units of pixels, where x points to the right and y points *down*. if map_layer is None: map_upper_left_offset_from_global_coordinate_origin = np.zeros((2,)) else: map_upper_left_offset_from_global_coordinate_origin = np.array( [-map_layer.transform_matrix[0, -1], map_layer.transform_matrix[1, -1]] ) ego_offset_from_map_upper_left: npt.NDArray[np.float32] = np.array([center_x, -center_y]) crop_upper_left_offset_from_ego: npt.NDArray[np.float32] = np.array( [xrange[0] * map_scale[0], yrange[0] * map_scale[1]] ) map_translation: npt.NDArray[np.float64] = ( -map_upper_left_offset_from_global_coordinate_origin - ego_offset_from_map_upper_left - crop_upper_left_offset_from_ego ) map_translation_with_z: npt.NDArray[np.float64] = np.array( [map_translation[0], map_translation[1], 0] ) # add z-coordinate if target_imsize_xy is not None: zoom_size_x = target_imsize_xy[0] / cropped_dimensions[0] zoom_size_y = target_imsize_xy[1] / cropped_dimensions[1] map_crop = ndimage.zoom(map_crop, [zoom_size_x, zoom_size_y]) map_scale = (zoom_size_x, zoom_size_y) return map_crop, map_translation_with_z, map_scale def get_vector_map( self, maps_db: Optional[GPKGMapsDB], xrange: Tuple[float, float], yrange: Tuple[float, float], connection_scales: Optional[List[int]] = None, ) -> VectorMapNp: """ This function returns the crop of baseline paths (blps) map centered at the current ego-pose with the given xrange and yrange. :param maps_db: Map database associated with this database. :param xrange: The range in x direction in meters relative to the current ego-pose. Eg: [-60, 60]. :param yrange: The range in y direction in meters relative to the current ego-pose Eg: [-60, 60]. :param connection_scales: Connection scales to generate. Use the 1-hop connections if it's left empty. :return: Vector map data including lane segment coordinates and connections within the given range. """ # load geopandas data map_version = self.lidar_pc.log.map_version.replace('.gpkg', '') blps_gdf = maps_db.load_vector_layer(map_version, 'baseline_paths') # type: ignore lane_poly_gdf = maps_db.load_vector_layer(map_version, 'lanes_polygons') # type: ignore intersections_gdf = maps_db.load_vector_layer(map_version, 'intersections') # type: ignore lane_connectors_gdf = maps_db.load_vector_layer(map_version, 'lane_connectors') # type: ignore lane_groups_gdf = maps_db.load_vector_layer(map_version, 'lane_groups_polygons') # type: ignore if ( (blps_gdf is None) or (lane_poly_gdf is None) or (intersections_gdf is None) or (lane_connectors_gdf is None) or (lane_groups_gdf is None) ): # This sample has no vector map. coords: npt.NDArray[np.float32] = np.empty([0, 2, 2], dtype=np.float32) if not connection_scales: # Use the 1-hop connections if connection_scales is not specified. connection_scales = [1] multi_scale_connections: Dict[int, Any] = { scale: np.empty([0, 2], dtype=np.int64) for scale in connection_scales } return VectorMapNp( coords=coords, multi_scale_connections=multi_scale_connections, ) # data enhancement blps_in_lanes = blps_gdf[blps_gdf['lane_fid'].notna()] blps_in_intersections = blps_gdf[blps_gdf['lane_connector_fid'].notna()] # enhance blps_in_lanes lane_group_info = lane_poly_gdf[['lane_fid', 'lane_group_fid']] blps_in_lanes = blps_in_lanes.merge(lane_group_info, on='lane_fid', how='outer') # enhance blps_in_intersections lane_connectors_gdf['lane_connector_fid'] = lane_connectors_gdf['fid'] lane_conns_info = lane_connectors_gdf[ ['lane_connector_fid', 'intersection_fid', 'exit_lane_fid', 'entry_lane_fid'] ] # Convert the exit_fid field of both data frames to the same dtype for merging. lane_conns_info = lane_conns_info.astype({'lane_connector_fid': int}) blps_in_intersections = blps_in_intersections.astype({'lane_connector_fid': int}) blps_in_intersections = blps_in_intersections.merge(lane_conns_info, on='lane_connector_fid', how='outer') # enhance blps_connection info lane_blps_info = blps_in_lanes[['fid', 'lane_fid']] from_blps_info = lane_blps_info.rename(columns={'fid': 'from_blp', 'lane_fid': 'exit_lane_fid'}) to_blps_info = lane_blps_info.rename(columns={'fid': 'to_blp', 'lane_fid': 'entry_lane_fid'}) blps_in_intersections = blps_in_intersections.merge(from_blps_info, on='exit_lane_fid', how='inner') blps_in_intersections = blps_in_intersections.merge(to_blps_info, on='entry_lane_fid', how='inner') # Select in-range blps candidate_lane_groups, candidate_intersections = get_candidates( self.translation_np, xrange, yrange, lane_groups_gdf, intersections_gdf ) candidate_blps_in_lanes = blps_in_lanes[ blps_in_lanes['lane_group_fid'].isin(candidate_lane_groups['fid'].astype(int)) ] candidate_blps_in_intersections = blps_in_intersections[ blps_in_intersections['intersection_fid'].isin(candidate_intersections['fid'].astype(int)) ] ls_coordinates_list: List[List[List[float]]] = [] ls_connections_list: List[List[int]] = [] ls_groupings_list: List[List[int]] = [] cross_blp_connection: Dict[str, List[int]] = dict() # generate lane_segments from blps in lanes build_lane_segments_from_blps( candidate_blps_in_lanes, ls_coordinates_list, ls_connections_list, ls_groupings_list, cross_blp_connection ) # generate lane_segments from blps in intersections build_lane_segments_from_blps( candidate_blps_in_intersections, ls_coordinates_list, ls_connections_list, ls_groupings_list, cross_blp_connection, ) # generate connections between blps for blp_id, blp_info in cross_blp_connection.items(): # Add predecessors connect_blp_predecessor(blp_id, candidate_blps_in_intersections, cross_blp_connection, ls_connections_list) # Add successors connect_blp_successor(blp_id, candidate_blps_in_intersections, cross_blp_connection, ls_connections_list) ls_coordinates: npt.NDArray[np.float64] = np.asarray(ls_coordinates_list, self.translation_np.dtype) ls_connections: npt.NDArray[np.int64] = np.asarray(ls_connections_list, np.int64) # Transform the lane coordinates from global frame to ego vehicle frame. # Flatten ls_coordinates from (num_ls, 2, 2) to (num_ls * 2, 2) for easier processing. ls_coordinates = ls_coordinates.reshape(-1, 2) ls_coordinates = ls_coordinates - self.translation_np[:2] ls_coordinates = self.rotate_2d_points2d_to_ego_vehicle_frame(ls_coordinates) ls_coordinates = ls_coordinates.reshape(-1, 2, 2).astype(np.float32) if connection_scales: # Generate multi-scale connections. multi_scale_connections = generate_multi_scale_connections(ls_connections, connection_scales) else: # Use the 1-hop connections if connection_scales is not specified. multi_scale_connections = {1: ls_connections} return VectorMapNp( coords=ls_coordinates, multi_scale_connections=multi_scale_connections, ) Image.ego_pose = relationship("EgoPose", foreign_keys=[Image.ego_pose_token], back_populates="image")
0.953286
0.389488
from pprint import pprint import pandas as pd import ccxt from model import Balance class ApiClient(ccxt.cryptopia): def __init__(self, apikey=None, secret=None, **config): super().__init__(config) if apikey is not None and secret is not None: self.apiKey = apikey self.secret = secret self.enableRateLimit = True def get_balance(self, currency=None): balance = self.fetch_balance() del balance['info'], balance['used'], balance['free'], balance['total'] result = {k: v for k, v in balance.items() if v['total'] > 0.0} if currency is not None: result = Balance(**balance.get(currency, {})) return result def get_ticker(self, symbol=None, hours=24): params = dict(params={'hours': hours}) result = dict() if symbol is None: data = self.fetch_tickers(params=params) for k, v in data.items(): base, quote = k.split('/') if quote in ['BTC', 'USDT']: min_volume = 25000 if 'USDT' in quote else 0.1 if v['quoteVolume'] > min_volume: del v['info'], v['askVolume'], v['bidVolume'], v['previousClose'] result.update({k: v}) else: data = self.fetch_ticker(symbol, params=params) del data['info'] return pd.DataFrame(result) def get_market_history(self, symbol=None, limit=100): params = dict(params={'limit': limit}) result = dict() if symbol is None: data = self.fetch_tickers(params=params) for k, v in data.items(): base, quote = k.split('/') if quote in ['BTC', 'USDT']: min_volume = 25000 if 'USDT' in quote else 0.1 if v['quoteVolume'] > min_volume: del v['info'], v['askVolume'], v['bidVolume'], v['previousClose'] result.update({k: v}) else: data = self.fetch_ticker(symbol, params=params) del data['info'] return pd.DataFrame(result) if __name__ == '__main__': pd.set_option('precision', 8) api = ApiClient() ticker = api.get_ticker() # btc_exchange = ticker.query('') print(ticker.sort_values(by='baseVolume', axis=1, ascending=False).first_valid_index()) # api.get_ticker('DGB/BTC')
clitopia/api.py
from pprint import pprint import pandas as pd import ccxt from model import Balance class ApiClient(ccxt.cryptopia): def __init__(self, apikey=None, secret=None, **config): super().__init__(config) if apikey is not None and secret is not None: self.apiKey = apikey self.secret = secret self.enableRateLimit = True def get_balance(self, currency=None): balance = self.fetch_balance() del balance['info'], balance['used'], balance['free'], balance['total'] result = {k: v for k, v in balance.items() if v['total'] > 0.0} if currency is not None: result = Balance(**balance.get(currency, {})) return result def get_ticker(self, symbol=None, hours=24): params = dict(params={'hours': hours}) result = dict() if symbol is None: data = self.fetch_tickers(params=params) for k, v in data.items(): base, quote = k.split('/') if quote in ['BTC', 'USDT']: min_volume = 25000 if 'USDT' in quote else 0.1 if v['quoteVolume'] > min_volume: del v['info'], v['askVolume'], v['bidVolume'], v['previousClose'] result.update({k: v}) else: data = self.fetch_ticker(symbol, params=params) del data['info'] return pd.DataFrame(result) def get_market_history(self, symbol=None, limit=100): params = dict(params={'limit': limit}) result = dict() if symbol is None: data = self.fetch_tickers(params=params) for k, v in data.items(): base, quote = k.split('/') if quote in ['BTC', 'USDT']: min_volume = 25000 if 'USDT' in quote else 0.1 if v['quoteVolume'] > min_volume: del v['info'], v['askVolume'], v['bidVolume'], v['previousClose'] result.update({k: v}) else: data = self.fetch_ticker(symbol, params=params) del data['info'] return pd.DataFrame(result) if __name__ == '__main__': pd.set_option('precision', 8) api = ApiClient() ticker = api.get_ticker() # btc_exchange = ticker.query('') print(ticker.sort_values(by='baseVolume', axis=1, ascending=False).first_valid_index()) # api.get_ticker('DGB/BTC')
0.251464
0.109301
REQUIREMENTS_MAP = { 'appengine': {'module_name': 'load_appengine_pipeline', 'depends_on': 'projects', 'api_name': 'appengine_api', 'dao_name': 'appengine_dao'}, 'backend_services': {'module_name': 'load_backend_services_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'backend_service_dao'}, 'bigquery_datasets': {'module_name': 'load_bigquery_datasets_pipeline', 'depends_on': 'projects', 'api_name': 'bigquery_api', 'dao_name': 'dao'}, 'buckets': {'module_name': 'load_projects_buckets_pipeline', 'depends_on': 'projects', 'api_name': 'gcs_api', 'dao_name': 'project_dao'}, 'buckets_acls': {'module_name': 'load_projects_buckets_acls_pipeline', 'depends_on': 'buckets', 'api_name': 'gcs_api', 'dao_name': 'bucket_dao'}, 'cloudsql': {'module_name': 'load_projects_cloudsql_pipeline', 'depends_on': 'projects', 'api_name': 'cloudsql_api', 'dao_name': 'cloudsql_dao'}, 'firewall_rules': {'module_name': 'load_firewall_rules_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'project_dao'}, 'folder_iam_policies': {'module_name': 'load_folder_iam_policies_pipeline', 'depends_on': 'folders', 'api_name': 'crm_api', 'dao_name': 'folder_dao'}, 'folders': {'module_name': 'load_folders_pipeline', 'depends_on': 'organizations', 'api_name': 'crm_api', 'dao_name': 'folder_dao'}, 'forwarding_rules': {'module_name': 'load_forwarding_rules_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'forwarding_rules_dao'}, 'ke': {'module_name': 'load_ke_pipeline', 'depends_on': 'projects', 'api_name': 'ke_api', 'dao_name': 'ke_dao'}, 'group_members': {'module_name': 'load_group_members_pipeline', 'depends_on': 'groups', 'api_name': 'admin_api', 'dao_name': 'dao'}, 'groups': {'module_name': 'load_groups_pipeline', 'depends_on': 'organizations', 'api_name': 'admin_api', 'dao_name': 'dao'}, 'instance_group_managers': {'module_name': 'load_instance_group_managers_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'instance_group_manager_dao'}, 'instance_groups': {'module_name': 'load_instance_groups_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'instance_group_dao'}, 'instance_templates': {'module_name': 'load_instance_templates_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'instance_template_dao'}, 'instances': {'module_name': 'load_instances_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'instance_dao'}, 'org_iam_policies': {'module_name': 'load_org_iam_policies_pipeline', 'depends_on': 'organizations', 'api_name': 'crm_api', 'dao_name': 'organization_dao'}, 'organizations': {'module_name': 'load_orgs_pipeline', 'depends_on': None, 'api_name': 'crm_api', 'dao_name': 'organization_dao'}, 'projects': {'module_name': 'load_projects_pipeline', 'depends_on': 'folders', 'api_name': 'crm_api', 'dao_name': 'project_dao'}, 'projects_iam_policies': {'module_name': 'load_projects_iam_policies_pipeline', 'depends_on': 'projects', 'api_name': 'crm_api', 'dao_name': 'project_dao'}, 'service_accounts': {'module_name': 'load_service_accounts_pipeline', 'depends_on': 'projects', 'api_name': 'iam_api', 'dao_name': 'service_account_dao'}, }
google/cloud/security/inventory/pipeline_requirements_map.py
REQUIREMENTS_MAP = { 'appengine': {'module_name': 'load_appengine_pipeline', 'depends_on': 'projects', 'api_name': 'appengine_api', 'dao_name': 'appengine_dao'}, 'backend_services': {'module_name': 'load_backend_services_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'backend_service_dao'}, 'bigquery_datasets': {'module_name': 'load_bigquery_datasets_pipeline', 'depends_on': 'projects', 'api_name': 'bigquery_api', 'dao_name': 'dao'}, 'buckets': {'module_name': 'load_projects_buckets_pipeline', 'depends_on': 'projects', 'api_name': 'gcs_api', 'dao_name': 'project_dao'}, 'buckets_acls': {'module_name': 'load_projects_buckets_acls_pipeline', 'depends_on': 'buckets', 'api_name': 'gcs_api', 'dao_name': 'bucket_dao'}, 'cloudsql': {'module_name': 'load_projects_cloudsql_pipeline', 'depends_on': 'projects', 'api_name': 'cloudsql_api', 'dao_name': 'cloudsql_dao'}, 'firewall_rules': {'module_name': 'load_firewall_rules_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'project_dao'}, 'folder_iam_policies': {'module_name': 'load_folder_iam_policies_pipeline', 'depends_on': 'folders', 'api_name': 'crm_api', 'dao_name': 'folder_dao'}, 'folders': {'module_name': 'load_folders_pipeline', 'depends_on': 'organizations', 'api_name': 'crm_api', 'dao_name': 'folder_dao'}, 'forwarding_rules': {'module_name': 'load_forwarding_rules_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'forwarding_rules_dao'}, 'ke': {'module_name': 'load_ke_pipeline', 'depends_on': 'projects', 'api_name': 'ke_api', 'dao_name': 'ke_dao'}, 'group_members': {'module_name': 'load_group_members_pipeline', 'depends_on': 'groups', 'api_name': 'admin_api', 'dao_name': 'dao'}, 'groups': {'module_name': 'load_groups_pipeline', 'depends_on': 'organizations', 'api_name': 'admin_api', 'dao_name': 'dao'}, 'instance_group_managers': {'module_name': 'load_instance_group_managers_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'instance_group_manager_dao'}, 'instance_groups': {'module_name': 'load_instance_groups_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'instance_group_dao'}, 'instance_templates': {'module_name': 'load_instance_templates_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'instance_template_dao'}, 'instances': {'module_name': 'load_instances_pipeline', 'depends_on': 'projects', 'api_name': 'compute_api', 'dao_name': 'instance_dao'}, 'org_iam_policies': {'module_name': 'load_org_iam_policies_pipeline', 'depends_on': 'organizations', 'api_name': 'crm_api', 'dao_name': 'organization_dao'}, 'organizations': {'module_name': 'load_orgs_pipeline', 'depends_on': None, 'api_name': 'crm_api', 'dao_name': 'organization_dao'}, 'projects': {'module_name': 'load_projects_pipeline', 'depends_on': 'folders', 'api_name': 'crm_api', 'dao_name': 'project_dao'}, 'projects_iam_policies': {'module_name': 'load_projects_iam_policies_pipeline', 'depends_on': 'projects', 'api_name': 'crm_api', 'dao_name': 'project_dao'}, 'service_accounts': {'module_name': 'load_service_accounts_pipeline', 'depends_on': 'projects', 'api_name': 'iam_api', 'dao_name': 'service_account_dao'}, }
0.276007
0.057679
import requests from tx.router import plugin_config, plugin from tx.router.logging import l import logging import connexion import sys from werkzeug.datastructures import Headers from flask import Response, request from tempfile import TemporaryFile logger = logging.getLogger() logger.setLevel(logging.INFO) def set_forwarded_path_header(f): def func(name, path, headers, *args, **kwargs): forwarded_path0_slash = connexion.request.headers.get("X-Forwarded-Path", "") forwarded_path0 = forwarded_path0_slash.rstrip("/") forwarded_path = f"{forwarded_path0}/v1/plugin/{name}" headers0 = {**headers, "X-Forwarded-Path": forwarded_path} logger.debug("headers0 = " + str(headers0)) return f(name, path, headers0, *args, **kwargs) return func @l("get", "backend") @set_forwarded_path_header def get_plugin(name, path, headers, kwargs={}): pc = plugin_config.get_plugin_config(name) if pc is None: return "not found", 404 port = pc.get("port", None) if port is None: raise RuntimeError("plugin doesn't have port") resp = requests.get("http://{host}:{port}/{path}".format(host=pc["name"], port=port, path=path), headers=headers, params=kwargs, stream=True) return Response(resp.iter_content(chunk_size=1024*1024), status=resp.status_code, headers=Headers(resp.headers.items())) @l("post", "backend") @set_forwarded_path_header def post_plugin(name, path, headers, stream, kwargs={}): return base_plugin(requests.post, name, path, headers, stream, kwargs) def base_plugin(method, name, path, headers, stream, kwargs): pc = plugin_config.get_plugin_config(name) if pc is None: return "not found", 404 port = pc.get("port", None) if port is None: raise RuntimeError("plugin doesn't have port") with TemporaryFile() as f: chunk_size = 4096 while True: chunk = stream.read(chunk_size) if len(chunk) == 0: break f.write(chunk) f.seek(0, 0) resp = method("http://{host}:{port}/{path}".format(host=pc["name"], port=port, path=path), headers=headers, params=kwargs, data=f, stream=True) return Response(resp.iter_content(chunk_size=1024*1024), status=resp.status_code, headers=Headers(resp.headers.items())) @l("delete", "backend") @set_forwarded_path_header def delete_plugin(name, path, headers, stream, kwargs={}): return base_plugin(requests.delete, name, path, headers, stream, kwargs) def get_plugin_config(name): pc = plugin_config.get_plugin_config(name) pc["_id"] = str(pc["_id"]) return pc def fil(name, name_regex): fils = [] if name_regex is not None: fils.append({"name": {"$regex": name_regex}}) if name is not None: fils.append({"name": name}) if len(fils) == 0: return {} else: return {"$and": fils} def get_plugin_configs(name=None, name_regex=None): ps = plugin_config.get_plugin_configs(fil(name, name_regex)) for pc in ps: pc["_id"] = str(pc["_id"]) return ps def add_plugin_configs(body): pc = plugin_config.add_plugin_configs(body) return len(pc) def delete_plugin_config(name=None, name_regex=None): return delete_plugin_configs(name=name, name_regex=name_regex) def delete_plugin_configs(name=None, name_regex=None): return plugin_config.delete_plugin_configs(fil(name, name_regex)) def update_plugin_config(name, body): plugin_config.replace_plugin_config(name, body) def get_plugin_container(name): pc = plugin_config.get_plugin_config(name) container = plugin.get_container(pc) if container is not None: return { "status": container.status } else: return None def add_plugin_container(name): pc = plugin_config.get_plugin_config(name) plugin.run_container(pc) def delete_plugin_container(name): pc = plugin_config.get_plugin_config(name) plugin.stop_container(pc) plugin.remove_container(pc) def get_containers(): containers = [] for pc in plugin_config.get_plugin_configs({}): container = plugin.get_container(pc) if container is not None: cs = { "status": container.status } else: cs = None containers.append({ "name": pc["name"], "container": cs }) return containers def add_containers(): for pc in plugin_config.get_plugin_configs({}): plugin.run_container(pc) def delete_containers(): for pc in plugin_config.get_plugin_configs({}): plugin.stop_container(pc) plugin.remove_container(pc)
api/__init__.py
import requests from tx.router import plugin_config, plugin from tx.router.logging import l import logging import connexion import sys from werkzeug.datastructures import Headers from flask import Response, request from tempfile import TemporaryFile logger = logging.getLogger() logger.setLevel(logging.INFO) def set_forwarded_path_header(f): def func(name, path, headers, *args, **kwargs): forwarded_path0_slash = connexion.request.headers.get("X-Forwarded-Path", "") forwarded_path0 = forwarded_path0_slash.rstrip("/") forwarded_path = f"{forwarded_path0}/v1/plugin/{name}" headers0 = {**headers, "X-Forwarded-Path": forwarded_path} logger.debug("headers0 = " + str(headers0)) return f(name, path, headers0, *args, **kwargs) return func @l("get", "backend") @set_forwarded_path_header def get_plugin(name, path, headers, kwargs={}): pc = plugin_config.get_plugin_config(name) if pc is None: return "not found", 404 port = pc.get("port", None) if port is None: raise RuntimeError("plugin doesn't have port") resp = requests.get("http://{host}:{port}/{path}".format(host=pc["name"], port=port, path=path), headers=headers, params=kwargs, stream=True) return Response(resp.iter_content(chunk_size=1024*1024), status=resp.status_code, headers=Headers(resp.headers.items())) @l("post", "backend") @set_forwarded_path_header def post_plugin(name, path, headers, stream, kwargs={}): return base_plugin(requests.post, name, path, headers, stream, kwargs) def base_plugin(method, name, path, headers, stream, kwargs): pc = plugin_config.get_plugin_config(name) if pc is None: return "not found", 404 port = pc.get("port", None) if port is None: raise RuntimeError("plugin doesn't have port") with TemporaryFile() as f: chunk_size = 4096 while True: chunk = stream.read(chunk_size) if len(chunk) == 0: break f.write(chunk) f.seek(0, 0) resp = method("http://{host}:{port}/{path}".format(host=pc["name"], port=port, path=path), headers=headers, params=kwargs, data=f, stream=True) return Response(resp.iter_content(chunk_size=1024*1024), status=resp.status_code, headers=Headers(resp.headers.items())) @l("delete", "backend") @set_forwarded_path_header def delete_plugin(name, path, headers, stream, kwargs={}): return base_plugin(requests.delete, name, path, headers, stream, kwargs) def get_plugin_config(name): pc = plugin_config.get_plugin_config(name) pc["_id"] = str(pc["_id"]) return pc def fil(name, name_regex): fils = [] if name_regex is not None: fils.append({"name": {"$regex": name_regex}}) if name is not None: fils.append({"name": name}) if len(fils) == 0: return {} else: return {"$and": fils} def get_plugin_configs(name=None, name_regex=None): ps = plugin_config.get_plugin_configs(fil(name, name_regex)) for pc in ps: pc["_id"] = str(pc["_id"]) return ps def add_plugin_configs(body): pc = plugin_config.add_plugin_configs(body) return len(pc) def delete_plugin_config(name=None, name_regex=None): return delete_plugin_configs(name=name, name_regex=name_regex) def delete_plugin_configs(name=None, name_regex=None): return plugin_config.delete_plugin_configs(fil(name, name_regex)) def update_plugin_config(name, body): plugin_config.replace_plugin_config(name, body) def get_plugin_container(name): pc = plugin_config.get_plugin_config(name) container = plugin.get_container(pc) if container is not None: return { "status": container.status } else: return None def add_plugin_container(name): pc = plugin_config.get_plugin_config(name) plugin.run_container(pc) def delete_plugin_container(name): pc = plugin_config.get_plugin_config(name) plugin.stop_container(pc) plugin.remove_container(pc) def get_containers(): containers = [] for pc in plugin_config.get_plugin_configs({}): container = plugin.get_container(pc) if container is not None: cs = { "status": container.status } else: cs = None containers.append({ "name": pc["name"], "container": cs }) return containers def add_containers(): for pc in plugin_config.get_plugin_configs({}): plugin.run_container(pc) def delete_containers(): for pc in plugin_config.get_plugin_configs({}): plugin.stop_container(pc) plugin.remove_container(pc)
0.308086
0.082033
from base.base_model import BaseModel import tensorflow as tf class Denoising(BaseModel): def __init__(self, config): super(Denoising, self).__init__(config) self.build_model() self.init_saver() def build_model(self): # Placeholders self.is_training = tf.placeholder(tf.bool) self.image_input = tf.placeholder( tf.float32, shape=[None] + self.config.trainer.image_dims, name="x" ) self.init_kernel = tf.random_normal_initializer(mean=0.0, stddev=0.02) # Full Model Scope with tf.variable_scope("Denoising", reuse=tf.AUTO_REUSE): # First Convolution + ReLU layer net = tf.layers.Conv2D( filters=63, kernel_size=3, strides=1, kernel_initializer=self.init_kernel, padding="same", )(self.image_input) net = tf.nn.relu(features=net) # 1 Convolution of the image net_input = tf.layers.Conv2D( filters=1, kernel_size=3, strides=1, kernel_initializer=self.init_kernel, padding="same", )(self.image_input) net_layer_1 = tf.layers.Conv2D( filters=1, kernel_size=3, strides=1, kernel_initializer=self.init_kernel, padding="same", )(net) # Add to the image self.output = net_input + net_layer_1 for i in range(19): net = tf.layers.Conv2D( filters=63, kernel_size=3, strides=1, kernel_initializer=self.init_kernel, padding="same", )(net) net = tf.nn.relu(features=net) net_1 = tf.layers.Conv2D( filters=1, kernel_size=3, strides=1, kernel_initializer=self.init_kernel, padding="same", )(net) self.output += net_1 self.output += self.image_input # Loss Function with tf.name_scope("Loss_Function"): delta = self.output - self.image_input delta = tf.layers.Flatten()(delta) self.loss = tf.reduce_mean(tf.norm(delta, ord=2, axis=1, keepdims=False)) # Optimizer with tf.name_scope("Optimizer"): self.optimizer = tf.train.AdamOptimizer( self.config.trainer.l_rate, beta1=self.config.trainer.optimizer_adam_beta1, beta2=self.config.trainer.optimizer_adam_beta2, ) # Collect All Variables all_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) self.update_ops = tf.get_collection( tf.GraphKeys.UPDATE_OPS, scope="Denoising" ) with tf.control_dependencies(self.update_ops): self.optimizer.minimize( self.loss, var_list=all_variables, global_step=self.global_step_tensor, ) # Summary with tf.name_scope("Summary"): with tf.name_scope("Loss"): tf.summary.scalar("Loss", self.loss, ["loss"]) with tf.name_scope("Image"): tf.summary.image("Input_Image", self.image_input, 3, ["image"]) tf.summary.image("Output_Image", self.output, 3, ["image"]) self.summary_op_im = tf.summary.merge_all("image") self.summary_op_loss = tf.summary.merge_all("loss") self.summary_all = tf.summary.merge([self.summary_op_im, self.summary_op_loss]) def init_saver(self): # here you initialize the tensorflow saver that will be used in saving the checkpoints. self.saver = tf.train.Saver(max_to_keep=self.config.log.max_to_keep)
models/denoising.py
from base.base_model import BaseModel import tensorflow as tf class Denoising(BaseModel): def __init__(self, config): super(Denoising, self).__init__(config) self.build_model() self.init_saver() def build_model(self): # Placeholders self.is_training = tf.placeholder(tf.bool) self.image_input = tf.placeholder( tf.float32, shape=[None] + self.config.trainer.image_dims, name="x" ) self.init_kernel = tf.random_normal_initializer(mean=0.0, stddev=0.02) # Full Model Scope with tf.variable_scope("Denoising", reuse=tf.AUTO_REUSE): # First Convolution + ReLU layer net = tf.layers.Conv2D( filters=63, kernel_size=3, strides=1, kernel_initializer=self.init_kernel, padding="same", )(self.image_input) net = tf.nn.relu(features=net) # 1 Convolution of the image net_input = tf.layers.Conv2D( filters=1, kernel_size=3, strides=1, kernel_initializer=self.init_kernel, padding="same", )(self.image_input) net_layer_1 = tf.layers.Conv2D( filters=1, kernel_size=3, strides=1, kernel_initializer=self.init_kernel, padding="same", )(net) # Add to the image self.output = net_input + net_layer_1 for i in range(19): net = tf.layers.Conv2D( filters=63, kernel_size=3, strides=1, kernel_initializer=self.init_kernel, padding="same", )(net) net = tf.nn.relu(features=net) net_1 = tf.layers.Conv2D( filters=1, kernel_size=3, strides=1, kernel_initializer=self.init_kernel, padding="same", )(net) self.output += net_1 self.output += self.image_input # Loss Function with tf.name_scope("Loss_Function"): delta = self.output - self.image_input delta = tf.layers.Flatten()(delta) self.loss = tf.reduce_mean(tf.norm(delta, ord=2, axis=1, keepdims=False)) # Optimizer with tf.name_scope("Optimizer"): self.optimizer = tf.train.AdamOptimizer( self.config.trainer.l_rate, beta1=self.config.trainer.optimizer_adam_beta1, beta2=self.config.trainer.optimizer_adam_beta2, ) # Collect All Variables all_variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) self.update_ops = tf.get_collection( tf.GraphKeys.UPDATE_OPS, scope="Denoising" ) with tf.control_dependencies(self.update_ops): self.optimizer.minimize( self.loss, var_list=all_variables, global_step=self.global_step_tensor, ) # Summary with tf.name_scope("Summary"): with tf.name_scope("Loss"): tf.summary.scalar("Loss", self.loss, ["loss"]) with tf.name_scope("Image"): tf.summary.image("Input_Image", self.image_input, 3, ["image"]) tf.summary.image("Output_Image", self.output, 3, ["image"]) self.summary_op_im = tf.summary.merge_all("image") self.summary_op_loss = tf.summary.merge_all("loss") self.summary_all = tf.summary.merge([self.summary_op_im, self.summary_op_loss]) def init_saver(self): # here you initialize the tensorflow saver that will be used in saving the checkpoints. self.saver = tf.train.Saver(max_to_keep=self.config.log.max_to_keep)
0.886899
0.191045
import requests import json import re import youtube_dl print("Youtube Pocket - youtube music/playlist downloader\n") USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36" VID_PATTERN = r"^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/(embed\/|v\/|(watch\?([a-zA-Z0-9_=;\-]+&)*v=))?(?P<video_id>[a-zA-Z0-9_\-]{11,})(\?[a-zA-Z0-9_=\-]+)?(?:&[a-zA-Z0-9_=;\-]+)*(?:\#[a-zA-Z0-9_=;\-]+)*$" LID_PATTERN = r"^(https?:\/\/)?(www\.)?youtube\.com\/(watch\?|playlist\?)([a-zA-Z0-9_=;\-]+&)*list=(?P<playlist_id>[a-zA-Z0-9_\-]{18,})(\?[a-zA-Z0-9_=\-]+)?(?:&[a-zA-Z0-9_=;\-]+)*(?:\#[a-zA-Z0-9_=;\-]+)*$" YT_DATA_PATTERN = r"var ytInitialData = (?P<JsonData>.*?);<\/script>" class Video(object): def __init__(self, vid = None, title = None, length_text = None): self.id = vid self.title = title self.length_text = length_text def get_data(url): global USER_AGENT, YT_DATA_PATTERN response = requests.get(url, headers = {"user-agent" : USER_AGENT}) if not response.ok: return None raw_content = response.text data = json.loads(re.search(YT_DATA_PATTERN, raw_content).group("JsonData")) return data def get_playlist_video(lid): url = "https://www.youtube.com/playlist?list=" + lid data = get_data(url) vid = data["contents"]["twoColumnBrowseResultsRenderer"]["tabs"][0]["tabRenderer"]["content"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"][0]["playlistVideoListRenderer"]["contents"][0]["playlistVideoRenderer"]["videoId"] return vid CRAWL_URL = input("URL: ") # CRAWL_URL = "https://www.youtube.com/watch?v=wvrQU9VCts0&list=PL2mVqrrF_bnn5qt_fqHZNRzWjKp4jqfyF" # CRAWL_URL = "https://www.youtube.com/playlist?list=PL2mVqrrF_bnn5qt_fqHZNRzWjKp4jqfyF" # CRAWL_URL = "https://www.youtube.com/watch?v=wvrQU9VCts0" prog_vid = re.compile(VID_PATTERN) prog_lid = re.compile(LID_PATTERN) video_id = None playlist_id = None while not prog_vid.match(CRAWL_URL) and not prog_lid.match(CRAWL_URL): print("Invalid URL") CRAWL_URL = input("URL: ") video_id = re.match(VID_PATTERN, CRAWL_URL) if video_id: video_id = video_id.group("video_id") playlist_id = re.match(LID_PATTERN, CRAWL_URL) if playlist_id: playlist_id = playlist_id.group("playlist_id") if playlist_id: if not video_id: video_id = get_playlist_video(playlist_id) CRAWL_URL = "https://www.youtube.com/watch?v=" + video_id + "&list=" + playlist_id elif video_id: CRAWL_URL = "https://www.youtube.com/watch?v=" + video_id else: exit() print("Requsteing: {}".format(CRAWL_URL)) DATA = get_data(CRAWL_URL) try: cur_video = DATA["contents"]["twoColumnWatchNextResults"]["results"]["results"]["contents"] cur_video_info = cur_video[0]["videoPrimaryInfoRenderer"] owner_info = cur_video[1]["videoSecondaryInfoRenderer"] recommend_video = DATA["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"]["results"] playlist = DATA["contents"]["twoColumnWatchNextResults"]["playlist"]["playlist"] except Exception as e: print(e) videos = [] for vi in playlist["contents"]: video_info = vi["playlistPanelVideoRenderer"] videos.append(Video(vid = video_info["videoId"], title = video_info["title"]["simpleText"], length_text = video_info["lengthText"]["simpleText"])) print("Downloading playlist: {0} with {1} videos\n".format(playlist["title"], playlist["totalVideos"])) i = 1 for vi in videos: print("# {0} [Processing] {1}".format(i, vi.title)) ydl_opts = {"format": "mp4", "outtmpl": "{0}-{1}.%(ext)s".format(vi.title, vi.length_text)} with youtube_dl.YoutubeDL(ydl_opts) as ydl: url = "https://www.youtube.com/watch?v=" + vi.id ydl.download([url]) i += 1 print("") print("Download complete!")
test_data/get_data_test.py
import requests import json import re import youtube_dl print("Youtube Pocket - youtube music/playlist downloader\n") USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36" VID_PATTERN = r"^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/(embed\/|v\/|(watch\?([a-zA-Z0-9_=;\-]+&)*v=))?(?P<video_id>[a-zA-Z0-9_\-]{11,})(\?[a-zA-Z0-9_=\-]+)?(?:&[a-zA-Z0-9_=;\-]+)*(?:\#[a-zA-Z0-9_=;\-]+)*$" LID_PATTERN = r"^(https?:\/\/)?(www\.)?youtube\.com\/(watch\?|playlist\?)([a-zA-Z0-9_=;\-]+&)*list=(?P<playlist_id>[a-zA-Z0-9_\-]{18,})(\?[a-zA-Z0-9_=\-]+)?(?:&[a-zA-Z0-9_=;\-]+)*(?:\#[a-zA-Z0-9_=;\-]+)*$" YT_DATA_PATTERN = r"var ytInitialData = (?P<JsonData>.*?);<\/script>" class Video(object): def __init__(self, vid = None, title = None, length_text = None): self.id = vid self.title = title self.length_text = length_text def get_data(url): global USER_AGENT, YT_DATA_PATTERN response = requests.get(url, headers = {"user-agent" : USER_AGENT}) if not response.ok: return None raw_content = response.text data = json.loads(re.search(YT_DATA_PATTERN, raw_content).group("JsonData")) return data def get_playlist_video(lid): url = "https://www.youtube.com/playlist?list=" + lid data = get_data(url) vid = data["contents"]["twoColumnBrowseResultsRenderer"]["tabs"][0]["tabRenderer"]["content"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"][0]["playlistVideoListRenderer"]["contents"][0]["playlistVideoRenderer"]["videoId"] return vid CRAWL_URL = input("URL: ") # CRAWL_URL = "https://www.youtube.com/watch?v=wvrQU9VCts0&list=PL2mVqrrF_bnn5qt_fqHZNRzWjKp4jqfyF" # CRAWL_URL = "https://www.youtube.com/playlist?list=PL2mVqrrF_bnn5qt_fqHZNRzWjKp4jqfyF" # CRAWL_URL = "https://www.youtube.com/watch?v=wvrQU9VCts0" prog_vid = re.compile(VID_PATTERN) prog_lid = re.compile(LID_PATTERN) video_id = None playlist_id = None while not prog_vid.match(CRAWL_URL) and not prog_lid.match(CRAWL_URL): print("Invalid URL") CRAWL_URL = input("URL: ") video_id = re.match(VID_PATTERN, CRAWL_URL) if video_id: video_id = video_id.group("video_id") playlist_id = re.match(LID_PATTERN, CRAWL_URL) if playlist_id: playlist_id = playlist_id.group("playlist_id") if playlist_id: if not video_id: video_id = get_playlist_video(playlist_id) CRAWL_URL = "https://www.youtube.com/watch?v=" + video_id + "&list=" + playlist_id elif video_id: CRAWL_URL = "https://www.youtube.com/watch?v=" + video_id else: exit() print("Requsteing: {}".format(CRAWL_URL)) DATA = get_data(CRAWL_URL) try: cur_video = DATA["contents"]["twoColumnWatchNextResults"]["results"]["results"]["contents"] cur_video_info = cur_video[0]["videoPrimaryInfoRenderer"] owner_info = cur_video[1]["videoSecondaryInfoRenderer"] recommend_video = DATA["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"]["results"] playlist = DATA["contents"]["twoColumnWatchNextResults"]["playlist"]["playlist"] except Exception as e: print(e) videos = [] for vi in playlist["contents"]: video_info = vi["playlistPanelVideoRenderer"] videos.append(Video(vid = video_info["videoId"], title = video_info["title"]["simpleText"], length_text = video_info["lengthText"]["simpleText"])) print("Downloading playlist: {0} with {1} videos\n".format(playlist["title"], playlist["totalVideos"])) i = 1 for vi in videos: print("# {0} [Processing] {1}".format(i, vi.title)) ydl_opts = {"format": "mp4", "outtmpl": "{0}-{1}.%(ext)s".format(vi.title, vi.length_text)} with youtube_dl.YoutubeDL(ydl_opts) as ydl: url = "https://www.youtube.com/watch?v=" + vi.id ydl.download([url]) i += 1 print("") print("Download complete!")
0.138258
0.096323
import os import sys import platform import re import argparse import threading import queue import webbrowser import logging import ipaddress from PIL import Image, ImageTk import tkinterdnd2 as tkdnd import tkinter as tk import tkinter.ttk as ttk from tkinter.simpledialog import Dialog as BaseDialog from tkinter.messagebox import showinfo from tkinter.filedialog import askdirectory, askopenfilenames from tkinter.scrolledtext import ScrolledText import appdirs from . import init_config, save_config, gConfig from . import hdpitk from . import about from . import hfs from .netdrop import NetDropServer, NetDropClient from .transport import get_broadcast_address, human_size logger = logging.getLogger(__name__) class GUIProgressBar(ttk.Progressbar): def __init__(self, parent, **kwargs): self.parent = parent self.style = ttk.Style() # add label in the layout self.style.layout( 'text.Horizontal.TProgressbar', [ ( 'Horizontal.Progressbar.trough', { 'children': [ ('Horizontal.Progressbar.pbar', {'side': 'left', 'sticky': 'ns'}) ], 'sticky': 'nswe' } ), ( 'Horizontal.Progressbar.label', {'sticky': ''} ), ] ) super().__init__(parent, style='text.Horizontal.TProgressbar', **kwargs) self.interval = 100 self.step_count = 0 self.time_index = 0 self.speed = '' self.count = [0] * (1000 // self.interval) self.parent.after(self.interval, self.on_timer_update) def on_timer_update(self): if self.step_count >= 0: self.parent.after(self.interval, self.on_timer_update) self.speed = f'{human_size(sum(self.count)):>9}/s' self.count[self.time_index] = self.step_count self.step_count = 0 # 0 ~ 9 self.time_index = (self.time_index + 1) % (1000 // self.interval) self.parent.on_progressbar_update_speed(self.speed) def update(self, step): self.step_count += step self.parent.on_progressbar_update(step) def write(self, message, file=None): logger.info(message) def close(self): if not self.speed: # transfer complete less than a second self.count[self.time_index] = self.step_count speed = sum(self.count) / (len([x for x in self.count if x != 0]) * self.interval / 1000) self.speed = f'{human_size(speed):>9}/s' self.step_count = -1 self.parent.on_progressbar_close(self.speed.strip()) class GUINetDropServer(NetDropServer): def __init__(self, parent, *args): self.parent = parent super().__init__(*args) def init_bar(self, max_value): progress = GUIProgressBar( self.parent.host_client, orient=tk.HORIZONTAL, maximum=max_value, mode='determinate') progress.grid(row=1, column=1, sticky='nsew') progress.lift() self.parent.host_client.progress = progress return progress def add_node(self, node): super().add_node(node) self.parent.on_add_node(node) def remove_node(self, node): super().remove_node(node) self.parent.on_remove_node(node) def recv_finish_text(self, from_addr): text = super().recv_finish_text(from_addr) self.parent.on_recv_text(text, from_addr) return text def recv_finish(self, from_addr, err): self.parent.host_client.result = (from_addr, err) super().recv_finish(from_addr, err) class GUINetDropClient(NetDropClient): def __init__(self, parent, ip, mode, cert=None, key=None): self.parent = parent super().__init__(ip, mode.lower(), ssl_ck=(cert, key)) def init_bar(self, max_value): progress = GUIProgressBar( self.parent, orient=tk.HORIZONTAL, maximum=max_value, mode='determinate') progress.grid(row=1, column=1, sticky='nsew') progress.lift() self.parent.progress = progress return progress def send_finish(self, err): self.parent.result = (None, err) super().send_finish(err) IMAGES = { 'back': 'BackTile.png', 'pc': 'PcLogo.png', 'android': 'AndroidLogo.png', 'apple': 'AppleLogo.png', 'darwin': 'AppleLogo.png', 'blackberry': 'BlackberryLogo.png', 'ip': 'IpLogo.png', 'linux': 'LinuxLogo.png', 'smartphone': 'SmartphoneLogo.png', 'unknown': 'UnknownLogo.png', 'windows': 'WindowsLogo.png', 'windowsphone': 'WindowsPhoneLogo.png', 'config': 'ConfigIcon.png', 'openfolder': 'OpenFolderIcon.png', 'hfs': 'hfs.png', } class NdropImage(): @classmethod def get_os_image(cls, name): image_dir = os.path.join(os.path.dirname(__file__), 'image') back_path = os.path.join(image_dir, IMAGES['back']) back_im = Image.open(back_path) fore_path = os.path.join( image_dir, IMAGES.get(name.lower()) or IMAGES['unknown'] ) fore_im = Image.open(fore_path) image = Image.new("RGBA", fore_im.size) image.alpha_composite(back_im.resize(fore_im.size)) image.alpha_composite(fore_im) return ImageTk.PhotoImage(image) @classmethod def get_image(cls, name, background=None): image_dir = os.path.join(os.path.dirname(__file__), 'image') fore_path = os.path.join(image_dir, IMAGES[name.lower()]) fore_im = Image.open(fore_path) background = background or 'white' image = Image.new("RGBA", fore_im.size, color=background) image.alpha_composite(fore_im) return ImageTk.PhotoImage(image) class AutoScrollbar(ttk.Scrollbar): # a scrollbar that hides itself if it's not needed. only # works if you use the grid geometry manager. def set(self, lo, hi): if float(lo) <= 0.0 and float(hi) >= 1.0: # grid_remove is currently missing from Tkinter! self.tk.call("grid", "remove", self) else: self.grid() super().set(lo, hi) def pack(self, **kw): raise tk.TclError("cannot use pack with this widget") def place(self, **kw): raise tk.TclError("cannot use place with this widget") class ScrolledWindow(ttk.Frame): """ https://stackoverflow.com/questions/16188420/tkinter-scrollbar-for-frame 1. Master widget gets scrollbars and a canvas. Scrollbars are connected to canvas scrollregion. 2. self.scrollwindow is created and inserted into canvas Usage Guideline: Assign any widgets as children of <ScrolledWindow instance>.scrollwindow to get them inserted into canvas __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs) docstring: Parent = master of scrolled window canv_w - width of canvas canv_h - height of canvas """ def __init__(self, parent, canv_w=400, canv_h=400, xbar=False, ybar=True, *args, **kwargs): """Parent=master of scrolled window canv_w - width of canvas canv_h - height of canvas """ super().__init__(parent, *args, **kwargs) # creating a canvas self.canv = tk.Canvas(self) self.canv.config( relief='flat', takefocus=0, borderwidth=0, highlightthickness=0, width=10, heigh=10) # placing a canvas into frame self.canv.columnconfigure(0, weight=1) self.canv.grid(column=0, row=0, sticky='nsew') self.canv.bind('<Configure>', self._configure_canvas) # creating a scrollbars if xbar: self.xscrlbr = AutoScrollbar(self, orient='horizontal', command=self.canv.xview) self.xscrlbr.grid(column=0, row=1, sticky='ew') self.canv.config(xscrollcommand=self.xscrlbr.set) if ybar: self.yscrlbr = AutoScrollbar(self, orient='vertical', command=self.canv.yview) self.yscrlbr.grid(column=1, row=0, sticky='ns') self.canv.config(yscrollcommand=self.yscrlbr.set) # creating a frame to inserto to canvas self.scrollwindow = ttk.Frame(self.canv) self.scrollwindow.bind('<Configure>', self._configure_window) self.scrollwindow.bind('<Enter>', self._bound_to_mousewheel) self.scrollwindow.bind('<Leave>', self._unbound_to_mousewheel) self.scrollwindow.columnconfigure(0, weight=1) self.item_window = self.canv.create_window(0, 0, window=self.scrollwindow, anchor='nw') if ybar: self.yscrlbr.lift(self.scrollwindow) if xbar: self.xscrlbr.lift(self.scrollwindow) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) def _bound_to_mousewheel(self, event): # windows, macos self.canv.bind_all("<MouseWheel>", self._on_mousewheel) # linux self.canv.bind_all("<Button-4>", self._on_mousewheel) self.canv.bind_all("<Button-5>", self._on_mousewheel) def _unbound_to_mousewheel(self, event): self.canv.unbind_all("<MouseWheel>") self.canv.unbind_all("<Button-4>") self.canv.unbind_all("<Button-5>") def _on_mousewheel(self, event): if sys.platform == 'darwin': # macos delta = -1 * event.delta elif event.num == 5: # linux up delta = 1 elif event.num == 4: # linux down delta = -1 else: # windows delta = -1 * (event.delta // 120) self.canv.yview_scroll(delta, "units") def _configure_window(self, event): # canvas will expand on both direction self.canv.configure(scrollregion=self.canv.bbox("all")) def _configure_canvas(self, event): self.canv.itemconfig(self.item_window, width=event.width) class Client(ttk.Frame): node = None progress = None agent = None def __init__(self, parent, node, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.parent = parent self.node = node self.queue = queue.SimpleQueue() self.virtual_event = '<<client_queue_event>>' self.bind(self.virtual_event, self.queue_handler) self.image = NdropImage.get_os_image(node['operating_system']) self.style = ttk.Style() self.style.configure('client.TLabel', background='white') self.label_image = ttk.Label(self, image=self.image, style='client.TLabel') self.label_image.grid(row=0, column=0, rowspan=2, sticky='w') if node['mode'] == '?': text = f'{node.get("user")}\n@{node["name"]}' else: text = f'{node.get("mode")}\n@{node["name"]}' label_text = ttk.Label( self, text=text, anchor='w', style='client.TLabel', justify=tk.LEFT) label_text.grid(row=0, column=1, sticky='ew') self.status = tk.StringVar() if self.node['ip'] == '?': self.status.set('ready') else: self.status.set(f'{self.node["ip"]} - ready') label_status = ttk.Label( self, textvariable=self.status, anchor='w', style='client.TLabel', justify=tk.LEFT) label_status.grid(row=1, column=1, sticky='nsew') self.rowconfigure(1, weight=1) self.columnconfigure(1, weight=1) if self.node['mode'] == 'NitroShare': self.dnd_types = [tkdnd.DND_FILES] else: # permit DND defaultly self.dnd_types = [tkdnd.DND_FILES, tkdnd.DND_TEXT] for widget in [self] + list(self.children.values()): widget.bind('<Button-1>', self.click) widget.drop_target_register(*self.dnd_types) widget.dnd_bind('<<DropEnter>>', self.drop_enter) widget.dnd_bind('<<DropPosition>>', self.drop_position) widget.dnd_bind('<<Drop:DND_Files>>', self.drop_files) widget.dnd_bind('<<Drop:DND_Text>>', self.drop_text) def bind_tree(self, widget, event, callback): widget.bind(event, callback) for child in widget.children.values(): bind_tree(child, event, callback) def queue_handler(self, event): item = self.queue.get_nowait() if self.progress: if item[0] == 'step': self.progress.step(item[1]) elif item[0] == 'speed': self.progress.style.configure('text.Horizontal.TProgressbar', text=item[1]) elif item[0] == 'close': self.progress.destroy() self.progress = None self.agent = None from_addr, err = self.result self.status.set(f'{self.node["ip"]} - {err} - {item[1]}') def on_progressbar_update_speed(self, speed): self.queue.put_nowait(('speed', speed)) self.event_generate(self.virtual_event) def on_progressbar_update(self, step): self.queue.put_nowait(('step', step)) self.event_generate(self.virtual_event) def on_progressbar_close(self, speed): self.queue.put_nowait(('close', speed)) self.event_generate(self.virtual_event) def click(self, event): if self.agent: logger.info('| => %(mode)s@%(name)s(%(ip)s)' % self.node) return if self.node['type'] == 'host': logger.info('%(mode)s@%(name)s(%(ip)s)' % self.node) return if self.node['type'] == 'ip': title = 'Send' else: title = 'Send to %(ip)s (%(mode)s)' % self.node dlg = SendDialog(self, title) dlg.show() if self.node['type'] == 'ip': if self.node['ip'] == '?': self.status.set('ready') if self.node['operating_system'] != 'Unknwon': self.node['operating_system'] = 'Unknwon' self.image = NdropImage.get_os_image(self.node['operating_system']) self.label_image.configure(image=self.image) else: self.status.set('%(ip)s - ready' % self.node) if self.node['operating_system'] != 'ip': self.node['operating_system'] = 'ip' self.image = NdropImage.get_os_image(self.node['operating_system']) self.label_image.configure(image=self.image) else: self.status.set(f'{self.node["ip"]} - ready') def in_dnd_types(self, dnd_type, dnd_types): for types in dnd_types: if dnd_type in types: return True def drop_position(self, event): if self.agent: # be trasfering return tkdnd.REFUSE_DROP if self.node['type'] == 'host': return tkdnd.REFUSE_DROP if self.node['ip'] == '?': return tkdnd.REFUSE_DROP # deny dnd_text for mode nitroshare if self.node['mode'] == 'NitroShare': if self.in_dnd_types('CF_UNICODETEXT', event.types) or \ self.in_dnd_types('CF_TEXT', event.types): return tkdnd.REFUSE_DROP return event.action def drop_enter(self, event): event.widget.focus_force() return event.action def drop_text(self, event): if event.data: self.send_text(event.data) return tkdnd.COPY def drop_files(self, event): if event.data: drop_files = self.tk.splitlist(event.data) self.send_files(drop_files) return tkdnd.COPY def send_text(self, text): if self.agent: return agent = GUINetDropClient(self, self.node['ip'], self.node['mode']) threading.Thread( name='Ndrop client', target=agent.send_text, args=(text, ), ).start() def send_files(self, files): self.agent = GUINetDropClient(self, self.node['ip'], self.node['mode']) threading.Thread( name='Ndrop client', target=self.agent.send_files, args=(files, ), ).start() class Dialog(BaseDialog): def __init__(self, parent, title=None): tk.Toplevel.__init__(self, parent) # remain invisible for now self.withdraw() # If the master is not viewable, don't # make the child transient, or else it # would be opened withdrawn if parent.winfo_viewable(): self.transient(parent) if title: self.title(title) self.parent = parent self.result = None body = ttk.Frame(self) self.initial_focus = self.body(body) body.pack(padx=5, pady=5) self.buttonbox() if not self.initial_focus: self.initial_focus = self self.protocol("WM_DELETE_WINDOW", self.cancel) if self.parent is not None: self.geometry("+%d+%d" % (parent.winfo_rootx() + 50, parent.winfo_rooty() + 50)) def show(self, modal=True): if self.is_visible(): return # become visible now self.deiconify() self.initial_focus.focus_set() # wait for window to appear on screen before calling grab_set self.wait_visibility() self.grab_set() if modal: self.wait_window(self) def hide(self): if not self.is_visible(): return self.withdraw() self.grab_release() if self.parent is not None: self.parent.focus_set() def is_visible(self): return self.state() == 'normal' class SettingDialog(Dialog): def __init__(self, master, title=None, **kwargs): target_dir = kwargs.get('target_dir', '') self.target_dir = tk.StringVar() self.target_dir.set(target_dir) hdpi = 1 if kwargs.get('enable_hdpi') else 0 self.hdpi = tk.IntVar() self.hdpi.set(hdpi) node_by_text = 1 if kwargs.get('create_node_by_text') else 0 self.node_by_text = tk.IntVar() self.node_by_text.set(node_by_text) super().__init__(master, title) def body(self, master): label = ttk.Label(master, text='Saved folder:') label.grid(row=0, sticky='w') entry = ttk.Entry(master, textvariable=self.target_dir, width=40) entry.grid(row=1, column=0, sticky='ew') button = ttk.Button(master, text='Change folder') button.grid(row=2, column=0, sticky='e') button.bind('<Button-1>', self.change_folder) checkbox = ttk.Checkbutton(master, text='Enable HDPI', variable=self.hdpi) checkbox.grid(row=3, column=0, sticky='ew') checkbox = ttk.Checkbutton(master, text='Create node by recving TEXT', variable=self.node_by_text) checkbox.grid(row=4, column=0, sticky='ew') master.rowconfigure(1, weight=1) master.columnconfigure(0, weight=1) master.pack(fill=tk.BOTH) def buttonbox(self): """replace origin wdiget with ttk""" box = ttk.Frame(self) w = ttk.Button(box, text="OK", width=10, command=self.ok, default=tk.ACTIVE) w.pack(side=tk.LEFT, padx=5, pady=5) w = ttk.Button(box, text="Cancel", width=10, command=self.cancel) w.pack(side=tk.LEFT, padx=5, pady=5) self.bind("<Return>", self.ok) self.bind("<Escape>", self.cancel) box.pack() def apply(self): target_dir = self.target_dir.get() hdpi = self.hdpi.get() node_by_text = self.node_by_text.get() self.result = ( os.path.normpath(target_dir), hdpi == 1, node_by_text == 1, ) def change_folder(self, event): folder = askdirectory(initialdir=self.target_dir.get()) if folder: self.target_dir.set(os.path.normpath(folder)) class SendDialog(Dialog): def __init__(self, parent, title=None, **kwargs): self.dest_ip = tk.StringVar() if parent.node['ip'] != '?': self.dest_ip.set(parent.node['ip']) self.mode = tk.StringVar() if parent.node['mode'] != '?': self.mode.set(parent.node['mode']) self.parent = parent super().__init__(parent, title) def body(self, master): label = ttk.Label(master, text='IP:') label.grid(row=0, column=0, sticky='w', padx=5, pady=5) entry = ttk.Entry(master, textvariable=self.dest_ip, width=20) entry.grid(row=0, column=1, sticky='ew', padx=5, pady=5) label = ttk.Label(master, text='Mode:') label.grid(row=0, column=2, sticky='w', padx=5, pady=5) choices = ['Dukto', 'NitroShare'] if not self.mode.get(): self.mode.set(choices[0]) combo = ttk.Combobox(master, values=choices, textvariable=self.mode, width=10, state="readonly") combo.grid(row=0, column=3, sticky='ew', padx=5, pady=5) combo.bind("<<ComboboxSelected>>", self.mode_selected) self.textbox = ScrolledText(master, width=60, height=10) self.textbox.grid(row=1, column=0, columnspan=4, sticky='nsew', padx=5, pady=5) self.btn_text = ttk.Button(master, text="Send TEXT", command=self.send_text) self.btn_text.grid(row=2, column=0, columnspan=4, sticky='ew', padx=5, pady=5) btn_files = ttk.Button(master, text="Send Files", command=self.send_files) btn_files.grid(row=3, column=0, columnspan=4, sticky='ew', padx=5, pady=5) btn_folder = ttk.Button(master, text="Send Folder", command=self.send_folder) btn_folder.grid(row=4, column=0, columnspan=4, sticky='ew', padx=5, pady=5) master.rowconfigure(1, weight=1) master.columnconfigure(1, weight=1) master.pack(fill=tk.BOTH, expand=1) if self.parent.node['type'] == 'guest': entry.configure(state='disabled') combo.configure(state='disabled') if self.mode.get() == 'NitroShare': self.textbox.configure(state='disabled') self.btn_text.configure(state='disabled') return entry def buttonbox(self): self.bind('<Escape>', self.cancel) def mode_selected(self, event): if self.mode.get() == 'NitroShare': self.textbox.configure(state='disabled') self.btn_text.configure(state='disabled') else: self.textbox.configure(state='normal') self.btn_text.configure(state='normal') def update_ip(self): if self.parent.node['type'] == 'ip': dest_ip = self.dest_ip.get() if dest_ip: try: ipaddr = ipaddress.ip_address(dest_ip) except ValueError: return self.parent.node['ip'] = str(ipaddr) else: self.parent.node['ip'] = '?' return mode = self.mode.get() self.parent.node['mode'] = mode return True def send_text(self): if self.update_ip(): text = self.textbox.get('1.0', 'end-1c') self.cancel() self.parent.send_text(text) def send_files(self): if self.update_ip(): files = askopenfilenames() if files: self.cancel() self.parent.send_files(files) def send_folder(self): if self.update_ip(): folder = askdirectory() if folder: self.cancel() self.parent.send_files([folder]) class MessageDialog(Dialog): def __init__(self, master, title=None, message=None, **kwargs): super().__init__(master, title) self.master = master self.message_queue = queue.Queue() self.queue_handler = QueueHandler(self.message_queue) if message: self.message_queue.put_nowait(message) self.master.after(100, self.poll_queue) def display(self, message): self.textbox.configure(state='normal') self.textbox.insert(tk.END, message + '\n') self.textbox.configure(state='disabled') # Autoscroll to the bottom self.textbox.yview(tk.END) def poll_queue(self): # Check every 100ms if there is a new message in the queue to display while True: try: message = self.message_queue.get(block=False) except queue.Empty: break else: self.display(message) self.master.after(100, self.poll_queue) def body(self, master): self.textbox = ScrolledText(master, width=60, height=10, state='disabled') self.textbox.grid(row=0, sticky='nsew') master.rowconfigure(0, weight=1) master.columnconfigure(0, weight=1) master.pack(fill=tk.BOTH, expand=1) def buttonbox(self): """replace origin wdiget with ttk""" box = ttk.Frame(self) w = ttk.Button(box, text="OK", width=10, command=self.hide, default=tk.ACTIVE) w.pack(side=tk.LEFT, padx=5, pady=5) self.bind("<Return>", self.hide) self.bind("<Escape>", self.hide) box.pack() class HFSDialog(Dialog): def __init__(self, master, title=None, **kwargs): # Create a logging handler using a queue self.log_queue = queue.Queue() self.queue_handler = QueueHandler(self.log_queue) formatter = logging.Formatter('%(message)s') self.queue_handler.setFormatter(formatter) hfs_logger = logging.getLogger('%s.hfs' % __name__.rpartition('.')[0]) hfs_logger.addHandler(self.queue_handler) logger.info('-- HFS server start --') listen = '0.0.0.0' cert = None key = None self.hfs_server = hfs.start(listen, root_path=gConfig.app['target_dir'], cert=cert, key=key, daemon=True) self.master = master self.master.after(100, self.poll_log_queue) super().__init__(master, title) def display(self, record): msg = self.queue_handler.format(record) self.scrolled_text.configure(state='normal') self.scrolled_text.insert(tk.END, msg + '\n', record.levelname) self.scrolled_text.configure(state='disabled') # Autoscroll to the bottom self.scrolled_text.yview(tk.END) def poll_log_queue(self): # Check every 100ms if there is a new message in the queue to display while True: try: record = self.log_queue.get(block=False) except queue.Empty: break else: self.display(record) if self.hfs_server: self.master.after(100, self.poll_log_queue) def body(self, master): self.scrolled_text = ScrolledText(master, width=60, height=10, state='disabled') self.scrolled_text.grid(row=0, sticky='nsew') master.rowconfigure(0, weight=1) master.columnconfigure(0, weight=1) master.pack(fill=tk.BOTH, expand=1) def buttonbox(self): box = ttk.Frame(self) w = ttk.Button(box, text="OK", width=10, command=self.ok, default=tk.ACTIVE) w.pack(side=tk.LEFT, padx=5, pady=5) self.bind("<Return>", self.ok) box.pack() def apply(self): self.result = None self.hfs_server.shutdown() self.hfs_server = None logger.info('-- HFS server close --') class QueueHandler(logging.Handler): def __init__(self, log_queue): super().__init__() self.log_queue = log_queue def emit(self, record): self.log_queue.put(record) def bind_tree(widget, event, callback): widget.bind(event, callback) for child in widget.children.values(): bind_tree(child, event, callback) class GuiApp(tkdnd.Tk): host_client = None ip_client = None message_box = None def __init__(self, *args): super().__init__(*args) self.title('%s v%s' % (about.name.capitalize(), about.version)) image_dir = os.path.join(os.path.dirname(__file__), 'image') icon_path = os.path.join(image_dir, 'ndrop.ico') self.iconphoto(True, ImageTk.PhotoImage(Image.open(icon_path))) self.geometry('320x360') self.queue = queue.SimpleQueue() uname = platform.uname() ipaddrs, _ = get_broadcast_address() host_node = {} host_node['user'] = 'You' host_node['name'] = uname.node host_node['operating_system'] = uname.system host_node['mode'] = '?' host_node['ip'] = ', '.join(ipaddrs) host_node['type'] = 'host' self.host_client = Client(self, host_node) self.host_client.grid(row=0, column=0, sticky='ew', padx=10, pady=10) sep = ttk.Separator(self) sep.grid(row=1, column=0, sticky='ew', padx=40, pady=0) frame = ScrolledWindow(self, xbar=False, ybar=True) frame.grid(sticky='ewns') self.frame = frame.scrollwindow ip_node = {} ip_node['user'] = 'IP connection' ip_node['name'] = 'Send data to a remote device.' ip_node['operating_system'] = 'Unknown' ip_node['mode'] = '?' ip_node['ip'] = '?' ip_node['type'] = 'ip' self.ip_client = Client(self.frame, ip_node) self.ip_client.grid(sticky='ew', padx=10, pady=5) s = ttk.Style() s.configure('footer.TFrame', background='green') s.configure('footer.TLabel', background='green') footer = ttk.Frame(self, style='footer.TFrame') footer.grid(sticky='ew') self.image_openfolder = NdropImage.get_image('openfolder', background='green') label = ttk.Label(footer, image=self.image_openfolder, style='footer.TLabel') label.grid(row=0, column=1, padx=10, pady=5) label.bind('<Button-1>', self.open_folder) self.image_config = NdropImage.get_image('config', background='green') label = ttk.Label(footer, image=self.image_config, style='footer.TLabel') label.grid(row=0, column=2, padx=10, pady=5) label.bind('<Button-1>', self.show_config) self.image_hfs = NdropImage.get_image('hfs', background='green') label = ttk.Label(footer, image=self.image_hfs, style='footer.TLabel') label.grid(row=0, column=3, padx=10, pady=5) label.bind('<Button-1>', self.show_hfs) footer.columnconfigure(0, weight=1) footer.columnconfigure(4, weight=1) self.rowconfigure(2, weight=1) self.columnconfigure(0, weight=1) self.bind('<<server_queue_event>>', self.queue_handler) def on_add_node(self, node): self.queue.put_nowait(('add_node', node)) self.event_generate('<<server_queue_event>>') def on_remove_node(self, node): self.queue.put_nowait(('remove_node', node)) self.event_generate('<<server_queue_event>>') def on_recv_text(self, text, from_addr): self.queue.put_nowait(('recv_text', text, from_addr)) self.event_generate('<<server_queue_event>>') def open_folder(self, event): webbrowser.open(gConfig.app['target_dir']) def show_config(self, event): dlg = SettingDialog( self, 'Settings', target_dir=gConfig.app['target_dir'], enable_hdpi=gConfig.app['enable_hdpi'], create_node_by_text=gConfig.app['create_node_by_text'], ) dlg.show() if dlg.result: target_dir, hdpi, node_by_text = dlg.result if gConfig.app['enable_hdpi'] != hdpi: showinfo('Information', 'Close and open app again for HDPI') gConfig.app['target_dir'] = target_dir gConfig.app['enable_hdpi'] = hdpi gConfig.app['create_node_by_text'] = node_by_text save_config() self.server.saved_to(gConfig.app['target_dir']) def show_hfs(self, event): dlg = HFSDialog(self, 'HFS') dlg.show() def queue_handler(self, event): item = self.queue.get_nowait() if item[0] == 'add_node': node = item[1] for client in self.frame.winfo_children(): if client.node['ip'] == node['ip'] and \ client.node['mode'] == node['mode']: if client.node['type'] == 'text' and node['type'] == 'guest': # destroy text client and create guest client client.destroy() else: return client = Client(self.frame, node) pad = (10, 5) client.grid(sticky='ew', padx=pad[0], pady=pad[1]) elif item[0] == 'remove_node': node = item[1] for client in self.frame.winfo_children(): if not client.progress and \ client.node['type'] == 'guest' and \ client.node['ip'] == node['ip'] and \ client.node['mode'] == node['mode']: client.destroy() elif item[0] == 'recv_text': text = item[1] from_addr = '%s:%s' % item[2] if gConfig.app['create_node_by_text']: # add node recv_node = {} recv_node['user'] = 'Unknown' recv_node['name'] = 'Unknown' recv_node['operating_system'] = 'ip' recv_node['mode'] = 'Dukto' recv_node['ip'] = item[2][0] recv_node['type'] = 'text' self.on_add_node(recv_node) message = f'{from_addr:21}: {text}' if not self.message_box: self.message_box = MessageDialog(self, title='Recv TEXT') self.message_box.message_queue.put_nowait(message) self.message_box.show(modal=False) def run(self): listen = '0.0.0.0' mode = None cert = None key = None self.server = GUINetDropServer(self, listen, mode, (cert, key)) self.server.saved_to(gConfig.app['target_dir']) threading.Thread( name='Ndrop server', target=self.server.wait_for_request, daemon=True, ).start() self.mainloop() def run(): print(about.banner) init_config() app_logger = logging.getLogger(__name__.rpartition('.')[0]) app_logger.setLevel(logging.INFO) FORMAT = ' * %(message)s' handler = logging.StreamHandler(sys.stderr) handler.setFormatter(logging.Formatter(fmt=FORMAT)) app_logger.addHandler(handler) app = GuiApp() if gConfig.app.get('enable_hdpi'): hdpitk.MakeTkDPIAware(app) app.run() if __name__ == '__main__': run()
ndrop/__main_tk__.py
import os import sys import platform import re import argparse import threading import queue import webbrowser import logging import ipaddress from PIL import Image, ImageTk import tkinterdnd2 as tkdnd import tkinter as tk import tkinter.ttk as ttk from tkinter.simpledialog import Dialog as BaseDialog from tkinter.messagebox import showinfo from tkinter.filedialog import askdirectory, askopenfilenames from tkinter.scrolledtext import ScrolledText import appdirs from . import init_config, save_config, gConfig from . import hdpitk from . import about from . import hfs from .netdrop import NetDropServer, NetDropClient from .transport import get_broadcast_address, human_size logger = logging.getLogger(__name__) class GUIProgressBar(ttk.Progressbar): def __init__(self, parent, **kwargs): self.parent = parent self.style = ttk.Style() # add label in the layout self.style.layout( 'text.Horizontal.TProgressbar', [ ( 'Horizontal.Progressbar.trough', { 'children': [ ('Horizontal.Progressbar.pbar', {'side': 'left', 'sticky': 'ns'}) ], 'sticky': 'nswe' } ), ( 'Horizontal.Progressbar.label', {'sticky': ''} ), ] ) super().__init__(parent, style='text.Horizontal.TProgressbar', **kwargs) self.interval = 100 self.step_count = 0 self.time_index = 0 self.speed = '' self.count = [0] * (1000 // self.interval) self.parent.after(self.interval, self.on_timer_update) def on_timer_update(self): if self.step_count >= 0: self.parent.after(self.interval, self.on_timer_update) self.speed = f'{human_size(sum(self.count)):>9}/s' self.count[self.time_index] = self.step_count self.step_count = 0 # 0 ~ 9 self.time_index = (self.time_index + 1) % (1000 // self.interval) self.parent.on_progressbar_update_speed(self.speed) def update(self, step): self.step_count += step self.parent.on_progressbar_update(step) def write(self, message, file=None): logger.info(message) def close(self): if not self.speed: # transfer complete less than a second self.count[self.time_index] = self.step_count speed = sum(self.count) / (len([x for x in self.count if x != 0]) * self.interval / 1000) self.speed = f'{human_size(speed):>9}/s' self.step_count = -1 self.parent.on_progressbar_close(self.speed.strip()) class GUINetDropServer(NetDropServer): def __init__(self, parent, *args): self.parent = parent super().__init__(*args) def init_bar(self, max_value): progress = GUIProgressBar( self.parent.host_client, orient=tk.HORIZONTAL, maximum=max_value, mode='determinate') progress.grid(row=1, column=1, sticky='nsew') progress.lift() self.parent.host_client.progress = progress return progress def add_node(self, node): super().add_node(node) self.parent.on_add_node(node) def remove_node(self, node): super().remove_node(node) self.parent.on_remove_node(node) def recv_finish_text(self, from_addr): text = super().recv_finish_text(from_addr) self.parent.on_recv_text(text, from_addr) return text def recv_finish(self, from_addr, err): self.parent.host_client.result = (from_addr, err) super().recv_finish(from_addr, err) class GUINetDropClient(NetDropClient): def __init__(self, parent, ip, mode, cert=None, key=None): self.parent = parent super().__init__(ip, mode.lower(), ssl_ck=(cert, key)) def init_bar(self, max_value): progress = GUIProgressBar( self.parent, orient=tk.HORIZONTAL, maximum=max_value, mode='determinate') progress.grid(row=1, column=1, sticky='nsew') progress.lift() self.parent.progress = progress return progress def send_finish(self, err): self.parent.result = (None, err) super().send_finish(err) IMAGES = { 'back': 'BackTile.png', 'pc': 'PcLogo.png', 'android': 'AndroidLogo.png', 'apple': 'AppleLogo.png', 'darwin': 'AppleLogo.png', 'blackberry': 'BlackberryLogo.png', 'ip': 'IpLogo.png', 'linux': 'LinuxLogo.png', 'smartphone': 'SmartphoneLogo.png', 'unknown': 'UnknownLogo.png', 'windows': 'WindowsLogo.png', 'windowsphone': 'WindowsPhoneLogo.png', 'config': 'ConfigIcon.png', 'openfolder': 'OpenFolderIcon.png', 'hfs': 'hfs.png', } class NdropImage(): @classmethod def get_os_image(cls, name): image_dir = os.path.join(os.path.dirname(__file__), 'image') back_path = os.path.join(image_dir, IMAGES['back']) back_im = Image.open(back_path) fore_path = os.path.join( image_dir, IMAGES.get(name.lower()) or IMAGES['unknown'] ) fore_im = Image.open(fore_path) image = Image.new("RGBA", fore_im.size) image.alpha_composite(back_im.resize(fore_im.size)) image.alpha_composite(fore_im) return ImageTk.PhotoImage(image) @classmethod def get_image(cls, name, background=None): image_dir = os.path.join(os.path.dirname(__file__), 'image') fore_path = os.path.join(image_dir, IMAGES[name.lower()]) fore_im = Image.open(fore_path) background = background or 'white' image = Image.new("RGBA", fore_im.size, color=background) image.alpha_composite(fore_im) return ImageTk.PhotoImage(image) class AutoScrollbar(ttk.Scrollbar): # a scrollbar that hides itself if it's not needed. only # works if you use the grid geometry manager. def set(self, lo, hi): if float(lo) <= 0.0 and float(hi) >= 1.0: # grid_remove is currently missing from Tkinter! self.tk.call("grid", "remove", self) else: self.grid() super().set(lo, hi) def pack(self, **kw): raise tk.TclError("cannot use pack with this widget") def place(self, **kw): raise tk.TclError("cannot use place with this widget") class ScrolledWindow(ttk.Frame): """ https://stackoverflow.com/questions/16188420/tkinter-scrollbar-for-frame 1. Master widget gets scrollbars and a canvas. Scrollbars are connected to canvas scrollregion. 2. self.scrollwindow is created and inserted into canvas Usage Guideline: Assign any widgets as children of <ScrolledWindow instance>.scrollwindow to get them inserted into canvas __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs) docstring: Parent = master of scrolled window canv_w - width of canvas canv_h - height of canvas """ def __init__(self, parent, canv_w=400, canv_h=400, xbar=False, ybar=True, *args, **kwargs): """Parent=master of scrolled window canv_w - width of canvas canv_h - height of canvas """ super().__init__(parent, *args, **kwargs) # creating a canvas self.canv = tk.Canvas(self) self.canv.config( relief='flat', takefocus=0, borderwidth=0, highlightthickness=0, width=10, heigh=10) # placing a canvas into frame self.canv.columnconfigure(0, weight=1) self.canv.grid(column=0, row=0, sticky='nsew') self.canv.bind('<Configure>', self._configure_canvas) # creating a scrollbars if xbar: self.xscrlbr = AutoScrollbar(self, orient='horizontal', command=self.canv.xview) self.xscrlbr.grid(column=0, row=1, sticky='ew') self.canv.config(xscrollcommand=self.xscrlbr.set) if ybar: self.yscrlbr = AutoScrollbar(self, orient='vertical', command=self.canv.yview) self.yscrlbr.grid(column=1, row=0, sticky='ns') self.canv.config(yscrollcommand=self.yscrlbr.set) # creating a frame to inserto to canvas self.scrollwindow = ttk.Frame(self.canv) self.scrollwindow.bind('<Configure>', self._configure_window) self.scrollwindow.bind('<Enter>', self._bound_to_mousewheel) self.scrollwindow.bind('<Leave>', self._unbound_to_mousewheel) self.scrollwindow.columnconfigure(0, weight=1) self.item_window = self.canv.create_window(0, 0, window=self.scrollwindow, anchor='nw') if ybar: self.yscrlbr.lift(self.scrollwindow) if xbar: self.xscrlbr.lift(self.scrollwindow) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) def _bound_to_mousewheel(self, event): # windows, macos self.canv.bind_all("<MouseWheel>", self._on_mousewheel) # linux self.canv.bind_all("<Button-4>", self._on_mousewheel) self.canv.bind_all("<Button-5>", self._on_mousewheel) def _unbound_to_mousewheel(self, event): self.canv.unbind_all("<MouseWheel>") self.canv.unbind_all("<Button-4>") self.canv.unbind_all("<Button-5>") def _on_mousewheel(self, event): if sys.platform == 'darwin': # macos delta = -1 * event.delta elif event.num == 5: # linux up delta = 1 elif event.num == 4: # linux down delta = -1 else: # windows delta = -1 * (event.delta // 120) self.canv.yview_scroll(delta, "units") def _configure_window(self, event): # canvas will expand on both direction self.canv.configure(scrollregion=self.canv.bbox("all")) def _configure_canvas(self, event): self.canv.itemconfig(self.item_window, width=event.width) class Client(ttk.Frame): node = None progress = None agent = None def __init__(self, parent, node, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.parent = parent self.node = node self.queue = queue.SimpleQueue() self.virtual_event = '<<client_queue_event>>' self.bind(self.virtual_event, self.queue_handler) self.image = NdropImage.get_os_image(node['operating_system']) self.style = ttk.Style() self.style.configure('client.TLabel', background='white') self.label_image = ttk.Label(self, image=self.image, style='client.TLabel') self.label_image.grid(row=0, column=0, rowspan=2, sticky='w') if node['mode'] == '?': text = f'{node.get("user")}\n@{node["name"]}' else: text = f'{node.get("mode")}\n@{node["name"]}' label_text = ttk.Label( self, text=text, anchor='w', style='client.TLabel', justify=tk.LEFT) label_text.grid(row=0, column=1, sticky='ew') self.status = tk.StringVar() if self.node['ip'] == '?': self.status.set('ready') else: self.status.set(f'{self.node["ip"]} - ready') label_status = ttk.Label( self, textvariable=self.status, anchor='w', style='client.TLabel', justify=tk.LEFT) label_status.grid(row=1, column=1, sticky='nsew') self.rowconfigure(1, weight=1) self.columnconfigure(1, weight=1) if self.node['mode'] == 'NitroShare': self.dnd_types = [tkdnd.DND_FILES] else: # permit DND defaultly self.dnd_types = [tkdnd.DND_FILES, tkdnd.DND_TEXT] for widget in [self] + list(self.children.values()): widget.bind('<Button-1>', self.click) widget.drop_target_register(*self.dnd_types) widget.dnd_bind('<<DropEnter>>', self.drop_enter) widget.dnd_bind('<<DropPosition>>', self.drop_position) widget.dnd_bind('<<Drop:DND_Files>>', self.drop_files) widget.dnd_bind('<<Drop:DND_Text>>', self.drop_text) def bind_tree(self, widget, event, callback): widget.bind(event, callback) for child in widget.children.values(): bind_tree(child, event, callback) def queue_handler(self, event): item = self.queue.get_nowait() if self.progress: if item[0] == 'step': self.progress.step(item[1]) elif item[0] == 'speed': self.progress.style.configure('text.Horizontal.TProgressbar', text=item[1]) elif item[0] == 'close': self.progress.destroy() self.progress = None self.agent = None from_addr, err = self.result self.status.set(f'{self.node["ip"]} - {err} - {item[1]}') def on_progressbar_update_speed(self, speed): self.queue.put_nowait(('speed', speed)) self.event_generate(self.virtual_event) def on_progressbar_update(self, step): self.queue.put_nowait(('step', step)) self.event_generate(self.virtual_event) def on_progressbar_close(self, speed): self.queue.put_nowait(('close', speed)) self.event_generate(self.virtual_event) def click(self, event): if self.agent: logger.info('| => %(mode)s@%(name)s(%(ip)s)' % self.node) return if self.node['type'] == 'host': logger.info('%(mode)s@%(name)s(%(ip)s)' % self.node) return if self.node['type'] == 'ip': title = 'Send' else: title = 'Send to %(ip)s (%(mode)s)' % self.node dlg = SendDialog(self, title) dlg.show() if self.node['type'] == 'ip': if self.node['ip'] == '?': self.status.set('ready') if self.node['operating_system'] != 'Unknwon': self.node['operating_system'] = 'Unknwon' self.image = NdropImage.get_os_image(self.node['operating_system']) self.label_image.configure(image=self.image) else: self.status.set('%(ip)s - ready' % self.node) if self.node['operating_system'] != 'ip': self.node['operating_system'] = 'ip' self.image = NdropImage.get_os_image(self.node['operating_system']) self.label_image.configure(image=self.image) else: self.status.set(f'{self.node["ip"]} - ready') def in_dnd_types(self, dnd_type, dnd_types): for types in dnd_types: if dnd_type in types: return True def drop_position(self, event): if self.agent: # be trasfering return tkdnd.REFUSE_DROP if self.node['type'] == 'host': return tkdnd.REFUSE_DROP if self.node['ip'] == '?': return tkdnd.REFUSE_DROP # deny dnd_text for mode nitroshare if self.node['mode'] == 'NitroShare': if self.in_dnd_types('CF_UNICODETEXT', event.types) or \ self.in_dnd_types('CF_TEXT', event.types): return tkdnd.REFUSE_DROP return event.action def drop_enter(self, event): event.widget.focus_force() return event.action def drop_text(self, event): if event.data: self.send_text(event.data) return tkdnd.COPY def drop_files(self, event): if event.data: drop_files = self.tk.splitlist(event.data) self.send_files(drop_files) return tkdnd.COPY def send_text(self, text): if self.agent: return agent = GUINetDropClient(self, self.node['ip'], self.node['mode']) threading.Thread( name='Ndrop client', target=agent.send_text, args=(text, ), ).start() def send_files(self, files): self.agent = GUINetDropClient(self, self.node['ip'], self.node['mode']) threading.Thread( name='Ndrop client', target=self.agent.send_files, args=(files, ), ).start() class Dialog(BaseDialog): def __init__(self, parent, title=None): tk.Toplevel.__init__(self, parent) # remain invisible for now self.withdraw() # If the master is not viewable, don't # make the child transient, or else it # would be opened withdrawn if parent.winfo_viewable(): self.transient(parent) if title: self.title(title) self.parent = parent self.result = None body = ttk.Frame(self) self.initial_focus = self.body(body) body.pack(padx=5, pady=5) self.buttonbox() if not self.initial_focus: self.initial_focus = self self.protocol("WM_DELETE_WINDOW", self.cancel) if self.parent is not None: self.geometry("+%d+%d" % (parent.winfo_rootx() + 50, parent.winfo_rooty() + 50)) def show(self, modal=True): if self.is_visible(): return # become visible now self.deiconify() self.initial_focus.focus_set() # wait for window to appear on screen before calling grab_set self.wait_visibility() self.grab_set() if modal: self.wait_window(self) def hide(self): if not self.is_visible(): return self.withdraw() self.grab_release() if self.parent is not None: self.parent.focus_set() def is_visible(self): return self.state() == 'normal' class SettingDialog(Dialog): def __init__(self, master, title=None, **kwargs): target_dir = kwargs.get('target_dir', '') self.target_dir = tk.StringVar() self.target_dir.set(target_dir) hdpi = 1 if kwargs.get('enable_hdpi') else 0 self.hdpi = tk.IntVar() self.hdpi.set(hdpi) node_by_text = 1 if kwargs.get('create_node_by_text') else 0 self.node_by_text = tk.IntVar() self.node_by_text.set(node_by_text) super().__init__(master, title) def body(self, master): label = ttk.Label(master, text='Saved folder:') label.grid(row=0, sticky='w') entry = ttk.Entry(master, textvariable=self.target_dir, width=40) entry.grid(row=1, column=0, sticky='ew') button = ttk.Button(master, text='Change folder') button.grid(row=2, column=0, sticky='e') button.bind('<Button-1>', self.change_folder) checkbox = ttk.Checkbutton(master, text='Enable HDPI', variable=self.hdpi) checkbox.grid(row=3, column=0, sticky='ew') checkbox = ttk.Checkbutton(master, text='Create node by recving TEXT', variable=self.node_by_text) checkbox.grid(row=4, column=0, sticky='ew') master.rowconfigure(1, weight=1) master.columnconfigure(0, weight=1) master.pack(fill=tk.BOTH) def buttonbox(self): """replace origin wdiget with ttk""" box = ttk.Frame(self) w = ttk.Button(box, text="OK", width=10, command=self.ok, default=tk.ACTIVE) w.pack(side=tk.LEFT, padx=5, pady=5) w = ttk.Button(box, text="Cancel", width=10, command=self.cancel) w.pack(side=tk.LEFT, padx=5, pady=5) self.bind("<Return>", self.ok) self.bind("<Escape>", self.cancel) box.pack() def apply(self): target_dir = self.target_dir.get() hdpi = self.hdpi.get() node_by_text = self.node_by_text.get() self.result = ( os.path.normpath(target_dir), hdpi == 1, node_by_text == 1, ) def change_folder(self, event): folder = askdirectory(initialdir=self.target_dir.get()) if folder: self.target_dir.set(os.path.normpath(folder)) class SendDialog(Dialog): def __init__(self, parent, title=None, **kwargs): self.dest_ip = tk.StringVar() if parent.node['ip'] != '?': self.dest_ip.set(parent.node['ip']) self.mode = tk.StringVar() if parent.node['mode'] != '?': self.mode.set(parent.node['mode']) self.parent = parent super().__init__(parent, title) def body(self, master): label = ttk.Label(master, text='IP:') label.grid(row=0, column=0, sticky='w', padx=5, pady=5) entry = ttk.Entry(master, textvariable=self.dest_ip, width=20) entry.grid(row=0, column=1, sticky='ew', padx=5, pady=5) label = ttk.Label(master, text='Mode:') label.grid(row=0, column=2, sticky='w', padx=5, pady=5) choices = ['Dukto', 'NitroShare'] if not self.mode.get(): self.mode.set(choices[0]) combo = ttk.Combobox(master, values=choices, textvariable=self.mode, width=10, state="readonly") combo.grid(row=0, column=3, sticky='ew', padx=5, pady=5) combo.bind("<<ComboboxSelected>>", self.mode_selected) self.textbox = ScrolledText(master, width=60, height=10) self.textbox.grid(row=1, column=0, columnspan=4, sticky='nsew', padx=5, pady=5) self.btn_text = ttk.Button(master, text="Send TEXT", command=self.send_text) self.btn_text.grid(row=2, column=0, columnspan=4, sticky='ew', padx=5, pady=5) btn_files = ttk.Button(master, text="Send Files", command=self.send_files) btn_files.grid(row=3, column=0, columnspan=4, sticky='ew', padx=5, pady=5) btn_folder = ttk.Button(master, text="Send Folder", command=self.send_folder) btn_folder.grid(row=4, column=0, columnspan=4, sticky='ew', padx=5, pady=5) master.rowconfigure(1, weight=1) master.columnconfigure(1, weight=1) master.pack(fill=tk.BOTH, expand=1) if self.parent.node['type'] == 'guest': entry.configure(state='disabled') combo.configure(state='disabled') if self.mode.get() == 'NitroShare': self.textbox.configure(state='disabled') self.btn_text.configure(state='disabled') return entry def buttonbox(self): self.bind('<Escape>', self.cancel) def mode_selected(self, event): if self.mode.get() == 'NitroShare': self.textbox.configure(state='disabled') self.btn_text.configure(state='disabled') else: self.textbox.configure(state='normal') self.btn_text.configure(state='normal') def update_ip(self): if self.parent.node['type'] == 'ip': dest_ip = self.dest_ip.get() if dest_ip: try: ipaddr = ipaddress.ip_address(dest_ip) except ValueError: return self.parent.node['ip'] = str(ipaddr) else: self.parent.node['ip'] = '?' return mode = self.mode.get() self.parent.node['mode'] = mode return True def send_text(self): if self.update_ip(): text = self.textbox.get('1.0', 'end-1c') self.cancel() self.parent.send_text(text) def send_files(self): if self.update_ip(): files = askopenfilenames() if files: self.cancel() self.parent.send_files(files) def send_folder(self): if self.update_ip(): folder = askdirectory() if folder: self.cancel() self.parent.send_files([folder]) class MessageDialog(Dialog): def __init__(self, master, title=None, message=None, **kwargs): super().__init__(master, title) self.master = master self.message_queue = queue.Queue() self.queue_handler = QueueHandler(self.message_queue) if message: self.message_queue.put_nowait(message) self.master.after(100, self.poll_queue) def display(self, message): self.textbox.configure(state='normal') self.textbox.insert(tk.END, message + '\n') self.textbox.configure(state='disabled') # Autoscroll to the bottom self.textbox.yview(tk.END) def poll_queue(self): # Check every 100ms if there is a new message in the queue to display while True: try: message = self.message_queue.get(block=False) except queue.Empty: break else: self.display(message) self.master.after(100, self.poll_queue) def body(self, master): self.textbox = ScrolledText(master, width=60, height=10, state='disabled') self.textbox.grid(row=0, sticky='nsew') master.rowconfigure(0, weight=1) master.columnconfigure(0, weight=1) master.pack(fill=tk.BOTH, expand=1) def buttonbox(self): """replace origin wdiget with ttk""" box = ttk.Frame(self) w = ttk.Button(box, text="OK", width=10, command=self.hide, default=tk.ACTIVE) w.pack(side=tk.LEFT, padx=5, pady=5) self.bind("<Return>", self.hide) self.bind("<Escape>", self.hide) box.pack() class HFSDialog(Dialog): def __init__(self, master, title=None, **kwargs): # Create a logging handler using a queue self.log_queue = queue.Queue() self.queue_handler = QueueHandler(self.log_queue) formatter = logging.Formatter('%(message)s') self.queue_handler.setFormatter(formatter) hfs_logger = logging.getLogger('%s.hfs' % __name__.rpartition('.')[0]) hfs_logger.addHandler(self.queue_handler) logger.info('-- HFS server start --') listen = '0.0.0.0' cert = None key = None self.hfs_server = hfs.start(listen, root_path=gConfig.app['target_dir'], cert=cert, key=key, daemon=True) self.master = master self.master.after(100, self.poll_log_queue) super().__init__(master, title) def display(self, record): msg = self.queue_handler.format(record) self.scrolled_text.configure(state='normal') self.scrolled_text.insert(tk.END, msg + '\n', record.levelname) self.scrolled_text.configure(state='disabled') # Autoscroll to the bottom self.scrolled_text.yview(tk.END) def poll_log_queue(self): # Check every 100ms if there is a new message in the queue to display while True: try: record = self.log_queue.get(block=False) except queue.Empty: break else: self.display(record) if self.hfs_server: self.master.after(100, self.poll_log_queue) def body(self, master): self.scrolled_text = ScrolledText(master, width=60, height=10, state='disabled') self.scrolled_text.grid(row=0, sticky='nsew') master.rowconfigure(0, weight=1) master.columnconfigure(0, weight=1) master.pack(fill=tk.BOTH, expand=1) def buttonbox(self): box = ttk.Frame(self) w = ttk.Button(box, text="OK", width=10, command=self.ok, default=tk.ACTIVE) w.pack(side=tk.LEFT, padx=5, pady=5) self.bind("<Return>", self.ok) box.pack() def apply(self): self.result = None self.hfs_server.shutdown() self.hfs_server = None logger.info('-- HFS server close --') class QueueHandler(logging.Handler): def __init__(self, log_queue): super().__init__() self.log_queue = log_queue def emit(self, record): self.log_queue.put(record) def bind_tree(widget, event, callback): widget.bind(event, callback) for child in widget.children.values(): bind_tree(child, event, callback) class GuiApp(tkdnd.Tk): host_client = None ip_client = None message_box = None def __init__(self, *args): super().__init__(*args) self.title('%s v%s' % (about.name.capitalize(), about.version)) image_dir = os.path.join(os.path.dirname(__file__), 'image') icon_path = os.path.join(image_dir, 'ndrop.ico') self.iconphoto(True, ImageTk.PhotoImage(Image.open(icon_path))) self.geometry('320x360') self.queue = queue.SimpleQueue() uname = platform.uname() ipaddrs, _ = get_broadcast_address() host_node = {} host_node['user'] = 'You' host_node['name'] = uname.node host_node['operating_system'] = uname.system host_node['mode'] = '?' host_node['ip'] = ', '.join(ipaddrs) host_node['type'] = 'host' self.host_client = Client(self, host_node) self.host_client.grid(row=0, column=0, sticky='ew', padx=10, pady=10) sep = ttk.Separator(self) sep.grid(row=1, column=0, sticky='ew', padx=40, pady=0) frame = ScrolledWindow(self, xbar=False, ybar=True) frame.grid(sticky='ewns') self.frame = frame.scrollwindow ip_node = {} ip_node['user'] = 'IP connection' ip_node['name'] = 'Send data to a remote device.' ip_node['operating_system'] = 'Unknown' ip_node['mode'] = '?' ip_node['ip'] = '?' ip_node['type'] = 'ip' self.ip_client = Client(self.frame, ip_node) self.ip_client.grid(sticky='ew', padx=10, pady=5) s = ttk.Style() s.configure('footer.TFrame', background='green') s.configure('footer.TLabel', background='green') footer = ttk.Frame(self, style='footer.TFrame') footer.grid(sticky='ew') self.image_openfolder = NdropImage.get_image('openfolder', background='green') label = ttk.Label(footer, image=self.image_openfolder, style='footer.TLabel') label.grid(row=0, column=1, padx=10, pady=5) label.bind('<Button-1>', self.open_folder) self.image_config = NdropImage.get_image('config', background='green') label = ttk.Label(footer, image=self.image_config, style='footer.TLabel') label.grid(row=0, column=2, padx=10, pady=5) label.bind('<Button-1>', self.show_config) self.image_hfs = NdropImage.get_image('hfs', background='green') label = ttk.Label(footer, image=self.image_hfs, style='footer.TLabel') label.grid(row=0, column=3, padx=10, pady=5) label.bind('<Button-1>', self.show_hfs) footer.columnconfigure(0, weight=1) footer.columnconfigure(4, weight=1) self.rowconfigure(2, weight=1) self.columnconfigure(0, weight=1) self.bind('<<server_queue_event>>', self.queue_handler) def on_add_node(self, node): self.queue.put_nowait(('add_node', node)) self.event_generate('<<server_queue_event>>') def on_remove_node(self, node): self.queue.put_nowait(('remove_node', node)) self.event_generate('<<server_queue_event>>') def on_recv_text(self, text, from_addr): self.queue.put_nowait(('recv_text', text, from_addr)) self.event_generate('<<server_queue_event>>') def open_folder(self, event): webbrowser.open(gConfig.app['target_dir']) def show_config(self, event): dlg = SettingDialog( self, 'Settings', target_dir=gConfig.app['target_dir'], enable_hdpi=gConfig.app['enable_hdpi'], create_node_by_text=gConfig.app['create_node_by_text'], ) dlg.show() if dlg.result: target_dir, hdpi, node_by_text = dlg.result if gConfig.app['enable_hdpi'] != hdpi: showinfo('Information', 'Close and open app again for HDPI') gConfig.app['target_dir'] = target_dir gConfig.app['enable_hdpi'] = hdpi gConfig.app['create_node_by_text'] = node_by_text save_config() self.server.saved_to(gConfig.app['target_dir']) def show_hfs(self, event): dlg = HFSDialog(self, 'HFS') dlg.show() def queue_handler(self, event): item = self.queue.get_nowait() if item[0] == 'add_node': node = item[1] for client in self.frame.winfo_children(): if client.node['ip'] == node['ip'] and \ client.node['mode'] == node['mode']: if client.node['type'] == 'text' and node['type'] == 'guest': # destroy text client and create guest client client.destroy() else: return client = Client(self.frame, node) pad = (10, 5) client.grid(sticky='ew', padx=pad[0], pady=pad[1]) elif item[0] == 'remove_node': node = item[1] for client in self.frame.winfo_children(): if not client.progress and \ client.node['type'] == 'guest' and \ client.node['ip'] == node['ip'] and \ client.node['mode'] == node['mode']: client.destroy() elif item[0] == 'recv_text': text = item[1] from_addr = '%s:%s' % item[2] if gConfig.app['create_node_by_text']: # add node recv_node = {} recv_node['user'] = 'Unknown' recv_node['name'] = 'Unknown' recv_node['operating_system'] = 'ip' recv_node['mode'] = 'Dukto' recv_node['ip'] = item[2][0] recv_node['type'] = 'text' self.on_add_node(recv_node) message = f'{from_addr:21}: {text}' if not self.message_box: self.message_box = MessageDialog(self, title='Recv TEXT') self.message_box.message_queue.put_nowait(message) self.message_box.show(modal=False) def run(self): listen = '0.0.0.0' mode = None cert = None key = None self.server = GUINetDropServer(self, listen, mode, (cert, key)) self.server.saved_to(gConfig.app['target_dir']) threading.Thread( name='Ndrop server', target=self.server.wait_for_request, daemon=True, ).start() self.mainloop() def run(): print(about.banner) init_config() app_logger = logging.getLogger(__name__.rpartition('.')[0]) app_logger.setLevel(logging.INFO) FORMAT = ' * %(message)s' handler = logging.StreamHandler(sys.stderr) handler.setFormatter(logging.Formatter(fmt=FORMAT)) app_logger.addHandler(handler) app = GuiApp() if gConfig.app.get('enable_hdpi'): hdpitk.MakeTkDPIAware(app) app.run() if __name__ == '__main__': run()
0.472683
0.082401