text:
Q: Превратить данные в словарь Python В процессе парсинга столкнулся вот с такими данными:
{'OPTIONS': {'table': {'CODE': 'table', 'SORT': '30', 'TITLE': 'Выберите стол', 'TITLE2': 'Без стола', 'ITEMS': {'0': {'ID': '310079', '~ID': '310079', 'IBLOCK_ID': '2', '~IBLOCK_ID': '2', 'NAME': 'Стол укороченный 80*54 см для машины A-8700', '~NAME': 'Стол укороченный 80*54 см для машины A-8700', 'XML_ID': '104614/0', '~XML_ID': '104614/0', 'DETAIL_PICTURE': {'width': 0, 'height': 0, 'size': None, 'SRC': '/upload/resize_cache/iblock/a8e/225_175_1/a8e733dac9fb5c89722140ed5d890dbc.jpg'}, '~DETAIL_PICTURE': '79772', 'DETAIL_PAGE_URL': '/catalog/stol-ukorochennyy-80-54-sm-dlya-mashiny-a-8700/', '~DETAIL_PAGE_URL': '/catalog/stol-ukorochennyy-80-54-sm-dlya-mashiny-a-8700/', 'PROPERTY_TYPE_COMPLECT_VALUE': 'стол', '~PROPERTY_TYPE_COMPLECT_VALUE': 'стол', 'PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', '~PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', 'PROPERTY_TYPE_COMPLECT_VALUE_ID': '17005679', '~PROPERTY_TYPE_COMPLECT_VALUE_ID': '17005679', 'PROPERTY_PRICE_TRANSIT_VALUE': None, '~PROPERTY_PRICE_TRANSIT_VALUE': None, 'PROPERTY_PRICE_TRANSIT_VALUE_ID': None, '~PROPERTY_PRICE_TRANSIT_VALUE_ID': None, 'PROPERTY_DIOH_VALUE': '30', '~PROPERTY_DIOH_VALUE': '30', 'PROPERTY_DIOH_VALUE_ID': '21174690', '~PROPERTY_DIOH_VALUE_ID': '21174690', 'LANG_DIR': '/', '~LANG_DIR': '/', 'CODE': 'stol-ukorochennyy-80-54-sm-dlya-mashiny-a-8700', '~CODE': 'stol-ukorochennyy-80-54-sm-dlya-mashiny-a-8700', 'EXTERNAL_ID': '104614/0', '~EXTERNAL_ID': '104614/0', 'IBLOCK_SECTION_ID': '2604', '~IBLOCK_SECTION_ID': '2604', 'IBLOCK_TYPE_ID': 'catalog', '~IBLOCK_TYPE_ID': 'catalog', 'IBLOCK_CODE': '', '~IBLOCK_CODE': '', 'IBLOCK_EXTERNAL_ID': '', '~IBLOCK_EXTERNAL_ID': '', 'LID': 's1', '~LID': 's1', 'QUANTITY': 12, 'QUANTITY_R': 1, 'PRICES': {'0': {'ID': '304603', 'PRODUCT_ID': '310079', 'PRICE': '62.00', 'CURRENCY': 'USD', 'CATALOG_GROUP_ID': '1'}}, 'AVAILABLE': 1, 'AVAILABLE_CLASS': 'in_stock', 'AVAILABLE_TITLE': 'в наличии', 'AVAILABLE_DIOH': '', 'PRICE_VALUE': 4574, 'PRICE_PRINT_VALUE': '4 574 Р', 'PRICE_DISCOUNT_VALUE': 4574, 'PRICE_PRINT_DISCOUNT_VALUE': '4 574 Р', 'PRICE_USD_DISCOUNT_VALUE': 62, 'PRICE_USD_PRINT_DISCOUNT_VALUE': '$62', 'BONUS_VALUE': None, 'BONUS_FORMATED': ''}, '1': {'ID': '310101', '~ID': '310101', 'IBLOCK_ID': '2', '~IBLOCK_ID': '2', 'NAME': 'Стол стандартный 120*54 см для машины A-8700', '~NAME': 'Стол стандартный 120*54 см для машины A-8700', 'XML_ID': '58508/0', '~XML_ID': '58508/0', 'DETAIL_PICTURE': {'width': 0, 'height': 0, 'size': None, 'SRC': '/upload/resize_cache/iblock/8a9/225_175_1/8a9291bd8e43d1e7659b947a73cf3725.jpg'}, '~DETAIL_PICTURE': '121976', 'DETAIL_PAGE_URL': '/catalog/stol-standartnyy-120-54-sm-dlya-mashiny-a-8700/', '~DETAIL_PAGE_URL': '/catalog/stol-standartnyy-120-54-sm-dlya-mashiny-a-8700/', 'PROPERTY_TYPE_COMPLECT_VALUE': 'стол', '~PROPERTY_TYPE_COMPLECT_VALUE': 'стол', 'PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', '~PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', 'PROPERTY_TYPE_COMPLECT_VALUE_ID': '17005747', '~PROPERTY_TYPE_COMPLECT_VALUE_ID': '17005747', 'PROPERTY_PRICE_TRANSIT_VALUE': None, '~PROPERTY_PRICE_TRANSIT_VALUE': None, 'PROPERTY_PRICE_TRANSIT_VALUE_ID': None, '~PROPERTY_PRICE_TRANSIT_VALUE_ID': None, 'PROPERTY_DIOH_VALUE': '0', '~PROPERTY_DIOH_VALUE': '0', 'PROPERTY_DIOH_VALUE_ID': '18461402', '~PROPERTY_DIOH_VALUE_ID': '18461402', 'LANG_DIR': '/', '~LANG_DIR': '/', 'CODE': 'stol-standartnyy-120-54-sm-dlya-mashiny-a-8700', '~CODE': 'stol-standartnyy-120-54-sm-dlya-mashiny-a-8700', 'EXTERNAL_ID': '58508/0', '~EXTERNAL_ID': '58508/0', 'IBLOCK_SECTION_ID': '2604', '~IBLOCK_SECTION_ID': '2604', 'IBLOCK_TYPE_ID': 'catalog', '~IBLOCK_TYPE_ID': 'catalog', 'IBLOCK_CODE': '', '~IBLOCK_CODE': '', 'IBLOCK_EXTERNAL_ID': '', '~IBLOCK_EXTERNAL_ID': '', 'LID': 's1', '~LID': 's1', 'QUANTITY': 2, 'QUANTITY_R': 0, 'PRICES': {'0': {'ID': '304604', 'PRODUCT_ID': '310101', 'PRICE': '62.00', 'CURRENCY': 'USD', 'CATALOG_GROUP_ID': '1'}}, 'AVAILABLE': 1, 'AVAILABLE_CLASS': 'in_stock', 'AVAILABLE_TITLE': 'в наличии', 'AVAILABLE_DIOH': '', 'PRICE_VALUE': 4574, 'PRICE_PRINT_VALUE': '4 574 Р', 'PRICE_DISCOUNT_VALUE': 4574, 'PRICE_PRINT_DISCOUNT_VALUE': '4 574 Р', 'PRICE_USD_DISCOUNT_VALUE': 62, 'PRICE_USD_PRINT_DISCOUNT_VALUE': '$62', 'BONUS_VALUE': None, 'BONUS_FORMATED': ''}, '3': {'ID': '538652', '~ID': '538652', 'IBLOCK_ID': '2', '~IBLOCK_ID': '2', 'NAME': 'Стол Aurora фирменный с вырезом под ремень для моделей А-8700/A-0302/A-0818', '~NAME': 'Стол Aurora фирменный с вырезом под ремень для моделей А-8700/A-0302/A-0818', 'XML_ID': '276376', '~XML_ID': '276376', 'DETAIL_PICTURE': None, '~DETAIL_PICTURE': None, 'DETAIL_PAGE_URL': '/catalog/stol-aurora-a-8700-a-0302-a-0818/', '~DETAIL_PAGE_URL': '/catalog/stol-aurora-a-8700-a-0302-a-0818/', 'PROPERTY_TYPE_COMPLECT_VALUE': 'стол', '~PROPERTY_TYPE_COMPLECT_VALUE': 'стол', 'PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', '~PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', 'PROPERTY_TYPE_COMPLECT_VALUE_ID': '16848683', '~PROPERTY_TYPE_COMPLECT_VALUE_ID': '16848683', 'PROPERTY_PRICE_TRANSIT_VALUE': '02/10/2021', '~PROPERTY_PRICE_TRANSIT_VALUE': '02/10/2021', 'PROPERTY_PRICE_TRANSIT_VALUE_ID': '21132669', '~PROPERTY_PRICE_TRANSIT_VALUE_ID': '21132669', 'PROPERTY_DIOH_VALUE': '113', '~PROPERTY_DIOH_VALUE': '113', 'PROPERTY_DIOH_VALUE_ID': '21186562', '~PROPERTY_DIOH_VALUE_ID': '21186562', 'LANG_DIR': '/', '~LANG_DIR': '/', 'CODE': 'stol-aurora-a-8700-a-0302-a-0818', '~CODE': 'stol-aurora-a-8700-a-0302-a-0818', 'EXTERNAL_ID': '276376', '~EXTERNAL_ID': '276376', 'IBLOCK_SECTION_ID': '2604', '~IBLOCK_SECTION_ID': '2604', 'IBLOCK_TYPE_ID': 'catalog', '~IBLOCK_TYPE_ID': 'catalog', 'IBLOCK_CODE': '', '~IBLOCK_CODE': '', 'IBLOCK_EXTERNAL_ID': '', '~IBLOCK_EXTERNAL_ID': '', 'LID': 's1', '~LID': 's1', 'QUANTITY': 651, 'QUANTITY_R': 115, 'PRICES': {'0': {'ID': '488624', 'PRODUCT_ID': '538652', 'PRICE': '62.00', 'CURRENCY': 'USD', 'CATALOG_GROUP_ID': '1'}}, 'AVAILABLE': 1, 'AVAILABLE_CLASS': 'in_stock', 'AVAILABLE_TITLE': 'в наличии', 'AVAILABLE_DIOH': '', 'PRICE_VALUE': 4574, 'PRICE_PRINT_VALUE': '4 574 Р', 'PRICE_DISCOUNT_VALUE': 4574, 'PRICE_PRINT_DISCOUNT_VALUE': '4 574 Р', 'PRICE_USD_DISCOUNT_VALUE': 62, 'PRICE_USD_PRINT_DISCOUNT_VALUE': '$62', 'BONUS_VALUE': None, 'BONUS_FORMATED': ''}, '2': {'ID': '400887', '~ID': '400887', 'IBLOCK_ID': '2', '~IBLOCK_ID': '2', 'NAME': 'Стол EURO1 для Juki DDL-8100/8700, DLN-5410, DU-1181', '~NAME': 'Стол EURO1 для Juki DDL-8100/8700, DLN-5410, DU-1181', 'XML_ID': '281969', '~XML_ID': '281969', 'DETAIL_PICTURE': {'width': 0, 'height': 0, 'size': None, 'SRC': '/upload/resize_cache/iblock/1cc/225_175_1/1cca5575d35210730f989c736263bf97.jpg'}, '~DETAIL_PICTURE': '124406', 'DETAIL_PAGE_URL': '/catalog/stol-euro1-dlya-juki-ddl-8100-8700/', '~DETAIL_PAGE_URL': '/catalog/stol-euro1-dlya-juki-ddl-8100-8700/', 'PROPERTY_TYPE_COMPLECT_VALUE': 'стол', '~PROPERTY_TYPE_COMPLECT_VALUE': 'стол', 'PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', '~PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', 'PROPERTY_TYPE_COMPLECT_VALUE_ID': '19751439', '~PROPERTY_TYPE_COMPLECT_VALUE_ID': '19751439', 'PROPERTY_PRICE_TRANSIT_VALUE': None, '~PROPERTY_PRICE_TRANSIT_VALUE': None, 'PROPERTY_PRICE_TRANSIT_VALUE_ID': None, '~PROPERTY_PRICE_TRANSIT_VALUE_ID': None, 'PROPERTY_DIOH_VALUE': '57', '~PROPERTY_DIOH_VALUE': '57', 'PROPERTY_DIOH_VALUE_ID': '21174884', '~PROPERTY_DIOH_VALUE_ID': '21174884', 'LANG_DIR': '/', '~LANG_DIR': '/', 'CODE': 'stol-euro1-dlya-juki-ddl-8100-8700', '~CODE': 'stol-euro1-dlya-juki-ddl-8100-8700', 'EXTERNAL_ID': '281969', '~EXTERNAL_ID': '281969', 'IBLOCK_SECTION_ID': '2604', '~IBLOCK_SECTION_ID': '2604', 'IBLOCK_TYPE_ID': 'catalog', '~IBLOCK_TYPE_ID': 'catalog', 'IBLOCK_CODE': '', '~IBLOCK_CODE': '', 'IBLOCK_EXTERNAL_ID': '', '~IBLOCK_EXTERNAL_ID': '', 'LID': 's1', '~LID': 's1', 'QUANTITY': 6, 'QUANTITY_R': 0, 'PRICES': {'0': {'ID': '305397', 'PRODUCT_ID': '400887', 'PRICE': '127.43', 'CURRENCY': 'USD', 'CATALOG_GROUP_ID': '1'}}, 'AVAILABLE': 1, 'AVAILABLE_CLASS': 'in_stock', 'AVAILABLE_TITLE': 'в наличии', 'AVAILABLE_DIOH': '', 'PRICE_VALUE': 9400, 'PRICE_PRINT_VALUE': '9 400 Р', 'PRICE_DISCOUNT_VALUE': 9400, 'PRICE_PRINT_DISCOUNT_VALUE': '9 400 Р', 'PRICE_USD_DISCOUNT_VALUE': 127.43, 'PRICE_USD_PRINT_DISCOUNT_VALUE': '$127.43', 'BONUS_VALUE': None, 'BONUS_FORMATED': ''}}}}, 'STATUS': 'OK'}

Перебрал несколько решений, но во всех получал ошибки (что-то про кавычки не те, ошибочные атрибуты и т.п.). Попытки исправить к успехам не привели.
Подскажите, пожалуйста, как это лучше распарсить с примером?
PS И еще вопрос: этот код - JSON?

A: data = {'OPTIONS': {'table': {'CODE': 'table', 'SORT': '30', 'TITLE': 'Выберите стол', 'TITLE2': 'Без стола', 'ITEMS': {'0': {'ID': '310079', '~ID': '310079', 'IBLOCK_ID': '2', '~IBLOCK_ID': '2', 'NAME': 'Стол укороченный 80*54 см для машины A-8700', '~NAME': 'Стол укороченный 80*54 см для машины A-8700', 'XML_ID': '104614/0', '~XML_ID': '104614/0', 'DETAIL_PICTURE': {'width': 0, 'height': 0, 'size': None, 'SRC': '/upload/resize_cache/iblock/a8e/225_175_1/a8e733dac9fb5c89722140ed5d890dbc.jpg'}, '~DETAIL_PICTURE': '79772', 'DETAIL_PAGE_URL': '/catalog/stol-ukorochennyy-80-54-sm-dlya-mashiny-a-8700/', '~DETAIL_PAGE_URL': '/catalog/stol-ukorochennyy-80-54-sm-dlya-mashiny-a-8700/', 'PROPERTY_TYPE_COMPLECT_VALUE': 'стол', '~PROPERTY_TYPE_COMPLECT_VALUE': 'стол', 'PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', '~PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', 'PROPERTY_TYPE_COMPLECT_VALUE_ID': '17005679', '~PROPERTY_TYPE_COMPLECT_VALUE_ID': '17005679', 'PROPERTY_PRICE_TRANSIT_VALUE': None, '~PROPERTY_PRICE_TRANSIT_VALUE': None, 'PROPERTY_PRICE_TRANSIT_VALUE_ID': None, '~PROPERTY_PRICE_TRANSIT_VALUE_ID': None, 'PROPERTY_DIOH_VALUE': '30', '~PROPERTY_DIOH_VALUE': '30', 'PROPERTY_DIOH_VALUE_ID': '21174690', '~PROPERTY_DIOH_VALUE_ID': '21174690', 'LANG_DIR': '/', '~LANG_DIR': '/', 'CODE': 'stol-ukorochennyy-80-54-sm-dlya-mashiny-a-8700', '~CODE': 'stol-ukorochennyy-80-54-sm-dlya-mashiny-a-8700', 'EXTERNAL_ID': '104614/0', '~EXTERNAL_ID': '104614/0', 'IBLOCK_SECTION_ID': '2604', '~IBLOCK_SECTION_ID': '2604', 'IBLOCK_TYPE_ID': 'catalog', '~IBLOCK_TYPE_ID': 'catalog', 'IBLOCK_CODE': '', '~IBLOCK_CODE': '', 'IBLOCK_EXTERNAL_ID': '', '~IBLOCK_EXTERNAL_ID': '', 'LID': 's1', '~LID': 's1', 'QUANTITY': 12, 'QUANTITY_R': 1, 'PRICES': {'0': {'ID': '304603', 'PRODUCT_ID': '310079', 'PRICE': '62.00', 'CURRENCY': 'USD', 'CATALOG_GROUP_ID': '1'}}, 'AVAILABLE': 1, 'AVAILABLE_CLASS': 'in_stock', 'AVAILABLE_TITLE': 'в наличии', 'AVAILABLE_DIOH': '', 'PRICE_VALUE': 4574, 'PRICE_PRINT_VALUE': '4 574 Р', 'PRICE_DISCOUNT_VALUE': 4574, 'PRICE_PRINT_DISCOUNT_VALUE': '4 574 Р', 'PRICE_USD_DISCOUNT_VALUE': 62, 'PRICE_USD_PRINT_DISCOUNT_VALUE': '$62', 'BONUS_VALUE': None, 'BONUS_FORMATED': ''}, '1': {'ID': '310101', '~ID': '310101', 'IBLOCK_ID': '2', '~IBLOCK_ID': '2', 'NAME': 'Стол стандартный 120*54 см для машины A-8700', '~NAME': 'Стол стандартный 120*54 см для машины A-8700', 'XML_ID': '58508/0', '~XML_ID': '58508/0', 'DETAIL_PICTURE': {'width': 0, 'height': 0, 'size': None, 'SRC': '/upload/resize_cache/iblock/8a9/225_175_1/8a9291bd8e43d1e7659b947a73cf3725.jpg'}, '~DETAIL_PICTURE': '121976', 'DETAIL_PAGE_URL': '/catalog/stol-standartnyy-120-54-sm-dlya-mashiny-a-8700/', '~DETAIL_PAGE_URL': '/catalog/stol-standartnyy-120-54-sm-dlya-mashiny-a-8700/', 'PROPERTY_TYPE_COMPLECT_VALUE': 'стол', '~PROPERTY_TYPE_COMPLECT_VALUE': 'стол', 'PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', '~PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', 'PROPERTY_TYPE_COMPLECT_VALUE_ID': '17005747', '~PROPERTY_TYPE_COMPLECT_VALUE_ID': '17005747', 'PROPERTY_PRICE_TRANSIT_VALUE': None, '~PROPERTY_PRICE_TRANSIT_VALUE': None, 'PROPERTY_PRICE_TRANSIT_VALUE_ID': None, '~PROPERTY_PRICE_TRANSIT_VALUE_ID': None, 'PROPERTY_DIOH_VALUE': '0', '~PROPERTY_DIOH_VALUE': '0', 'PROPERTY_DIOH_VALUE_ID': '18461402', '~PROPERTY_DIOH_VALUE_ID': '18461402', 'LANG_DIR': '/', '~LANG_DIR': '/', 'CODE': 'stol-standartnyy-120-54-sm-dlya-mashiny-a-8700', '~CODE': 'stol-standartnyy-120-54-sm-dlya-mashiny-a-8700', 'EXTERNAL_ID': '58508/0', '~EXTERNAL_ID': '58508/0', 'IBLOCK_SECTION_ID': '2604', '~IBLOCK_SECTION_ID': '2604', 'IBLOCK_TYPE_ID': 'catalog', '~IBLOCK_TYPE_ID': 'catalog', 'IBLOCK_CODE': '', '~IBLOCK_CODE': '', 'IBLOCK_EXTERNAL_ID': '', '~IBLOCK_EXTERNAL_ID': '', 'LID': 's1', '~LID': 's1', 'QUANTITY': 2, 'QUANTITY_R': 0, 'PRICES': {'0': {'ID': '304604', 'PRODUCT_ID': '310101', 'PRICE': '62.00', 'CURRENCY': 'USD', 'CATALOG_GROUP_ID': '1'}}, 'AVAILABLE': 1, 'AVAILABLE_CLASS': 'in_stock', 'AVAILABLE_TITLE': 'в наличии', 'AVAILABLE_DIOH': '', 'PRICE_VALUE': 4574, 'PRICE_PRINT_VALUE': '4 574 Р', 'PRICE_DISCOUNT_VALUE': 4574, 'PRICE_PRINT_DISCOUNT_VALUE': '4 574 Р', 'PRICE_USD_DISCOUNT_VALUE': 62, 'PRICE_USD_PRINT_DISCOUNT_VALUE': '$62', 'BONUS_VALUE': None, 'BONUS_FORMATED': ''}, '3': {'ID': '538652', '~ID': '538652', 'IBLOCK_ID': '2', '~IBLOCK_ID': '2', 'NAME': 'Стол Aurora фирменный с вырезом под ремень для моделей А-8700/A-0302/A-0818', '~NAME': 'Стол Aurora фирменный с вырезом под ремень для моделей А-8700/A-0302/A-0818', 'XML_ID': '276376', '~XML_ID': '276376', 'DETAIL_PICTURE': None, '~DETAIL_PICTURE': None, 'DETAIL_PAGE_URL': '/catalog/stol-aurora-a-8700-a-0302-a-0818/', '~DETAIL_PAGE_URL': '/catalog/stol-aurora-a-8700-a-0302-a-0818/', 'PROPERTY_TYPE_COMPLECT_VALUE': 'стол', '~PROPERTY_TYPE_COMPLECT_VALUE': 'стол', 'PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', '~PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', 'PROPERTY_TYPE_COMPLECT_VALUE_ID': '16848683', '~PROPERTY_TYPE_COMPLECT_VALUE_ID': '16848683', 'PROPERTY_PRICE_TRANSIT_VALUE': '02/10/2021', '~PROPERTY_PRICE_TRANSIT_VALUE': '02/10/2021', 'PROPERTY_PRICE_TRANSIT_VALUE_ID': '21132669', '~PROPERTY_PRICE_TRANSIT_VALUE_ID': '21132669', 'PROPERTY_DIOH_VALUE': '113', '~PROPERTY_DIOH_VALUE': '113', 'PROPERTY_DIOH_VALUE_ID': '21186562', '~PROPERTY_DIOH_VALUE_ID': '21186562', 'LANG_DIR': '/', '~LANG_DIR': '/', 'CODE': 'stol-aurora-a-8700-a-0302-a-0818', '~CODE': 'stol-aurora-a-8700-a-0302-a-0818', 'EXTERNAL_ID': '276376', '~EXTERNAL_ID': '276376', 'IBLOCK_SECTION_ID': '2604', '~IBLOCK_SECTION_ID': '2604', 'IBLOCK_TYPE_ID': 'catalog', '~IBLOCK_TYPE_ID': 'catalog', 'IBLOCK_CODE': '', '~IBLOCK_CODE': '', 'IBLOCK_EXTERNAL_ID': '', '~IBLOCK_EXTERNAL_ID': '', 'LID': 's1', '~LID': 's1', 'QUANTITY': 651, 'QUANTITY_R': 115, 'PRICES': {'0': {'ID': '488624', 'PRODUCT_ID': '538652', 'PRICE': '62.00', 'CURRENCY': 'USD', 'CATALOG_GROUP_ID': '1'}}, 'AVAILABLE': 1, 'AVAILABLE_CLASS': 'in_stock', 'AVAILABLE_TITLE': 'в наличии', 'AVAILABLE_DIOH': '', 'PRICE_VALUE': 4574, 'PRICE_PRINT_VALUE': '4 574 Р', 'PRICE_DISCOUNT_VALUE': 4574, 'PRICE_PRINT_DISCOUNT_VALUE': '4 574 Р', 'PRICE_USD_DISCOUNT_VALUE': 62, 'PRICE_USD_PRINT_DISCOUNT_VALUE': '$62', 'BONUS_VALUE': None, 'BONUS_FORMATED': ''}, '2': {'ID': '400887', '~ID': '400887', 'IBLOCK_ID': '2', '~IBLOCK_ID': '2', 'NAME': 'Стол EURO1 для Juki DDL-8100/8700, DLN-5410, DU-1181', '~NAME': 'Стол EURO1 для Juki DDL-8100/8700, DLN-5410, DU-1181', 'XML_ID': '281969', '~XML_ID': '281969', 'DETAIL_PICTURE': {'width': 0, 'height': 0, 'size': None, 'SRC': '/upload/resize_cache/iblock/1cc/225_175_1/1cca5575d35210730f989c736263bf97.jpg'}, '~DETAIL_PICTURE': '124406', 'DETAIL_PAGE_URL': '/catalog/stol-euro1-dlya-juki-ddl-8100-8700/', '~DETAIL_PAGE_URL': '/catalog/stol-euro1-dlya-juki-ddl-8100-8700/', 'PROPERTY_TYPE_COMPLECT_VALUE': 'стол', '~PROPERTY_TYPE_COMPLECT_VALUE': 'стол', 'PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', '~PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', 'PROPERTY_TYPE_COMPLECT_VALUE_ID': '19751439', '~PROPERTY_TYPE_COMPLECT_VALUE_ID': '19751439', 'PROPERTY_PRICE_TRANSIT_VALUE': None, '~PROPERTY_PRICE_TRANSIT_VALUE': None, 'PROPERTY_PRICE_TRANSIT_VALUE_ID': None, '~PROPERTY_PRICE_TRANSIT_VALUE_ID': None, 'PROPERTY_DIOH_VALUE': '57', '~PROPERTY_DIOH_VALUE': '57', 'PROPERTY_DIOH_VALUE_ID': '21174884', '~PROPERTY_DIOH_VALUE_ID': '21174884', 'LANG_DIR': '/', '~LANG_DIR': '/', 'CODE': 'stol-euro1-dlya-juki-ddl-8100-8700', '~CODE': 'stol-euro1-dlya-juki-ddl-8100-8700', 'EXTERNAL_ID': '281969', '~EXTERNAL_ID': '281969', 'IBLOCK_SECTION_ID': '2604', '~IBLOCK_SECTION_ID': '2604', 'IBLOCK_TYPE_ID': 'catalog', '~IBLOCK_TYPE_ID': 'catalog', 'IBLOCK_CODE': '', '~IBLOCK_CODE': '', 'IBLOCK_EXTERNAL_ID': '', '~IBLOCK_EXTERNAL_ID': '', 'LID': 's1', '~LID': 's1', 'QUANTITY': 6, 'QUANTITY_R': 0, 'PRICES': {'0': {'ID': '305397', 'PRODUCT_ID': '400887', 'PRICE': '127.43', 'CURRENCY': 'USD', 'CATALOG_GROUP_ID': '1'}}, 'AVAILABLE': 1, 'AVAILABLE_CLASS': 'in_stock', 'AVAILABLE_TITLE': 'в наличии', 'AVAILABLE_DIOH': '', 'PRICE_VALUE': 9400, 'PRICE_PRINT_VALUE': '9 400 Р', 'PRICE_DISCOUNT_VALUE': 9400, 'PRICE_PRINT_DISCOUNT_VALUE': '9 400 Р', 'PRICE_USD_DISCOUNT_VALUE': 127.43, 'PRICE_USD_PRINT_DISCOUNT_VALUE': '$127.43', 'BONUS_VALUE': None, 'BONUS_FORMATED': ''}}}}, 'STATUS': 'OK'}

тут готовый словарь:
>>> import pprint
>>> pprint.pprint(data, depth=4)

выведет:
{'OPTIONS': {'table': {'CODE': 'table',
                       'ITEMS': {'0': {...},
                                 '1': {...},
                                 '2': {...},
                                 '3': {...}},
                       'SORT': '30',
                       'TITLE': 'Выберите стол',
                       'TITLE2': 'Без стола'}},
 'STATUS': 'OK'}

вытащить содержимое по ключам:
>>> data['OPTIONS']['table']['ITEMS']['1']
{'ID': '310101', '~ID': '310101', 'IBLOCK_ID': '2', '~IBLOCK_ID': '2', 'NAME': 'Стол стандартный 120*54 см для машины A-8700', '~NAME': 'Стол стандартный 120*54 см для машины A-8700', 'XML_ID': '58508/0', '~XML_ID': '58508/0', 'DETAIL_PICTURE': {'width': 0, 'height': 0, 'size': None, 'SRC': '/upload/resize_cache/iblock/8a9/225_175_1/8a9291bd8e43d1e7659b947a73cf3725.jpg'}, '~DETAIL_PICTURE': '121976', 'DETAIL_PAGE_URL': '/catalog/stol-standartnyy-120-54-sm-dlya-mashiny-a-8700/', '~DETAIL_PAGE_URL': '/catalog/stol-standartnyy-120-54-sm-dlya-mashiny-a-8700/', 'PROPERTY_TYPE_COMPLECT_VALUE': 'стол', '~PROPERTY_TYPE_COMPLECT_VALUE': 'стол', 'PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', '~PROPERTY_TYPE_COMPLECT_ENUM_ID': '135', 'PROPERTY_TYPE_COMPLECT_VALUE_ID': '17005747', '~PROPERTY_TYPE_COMPLECT_VALUE_ID': '17005747', 'PROPERTY_PRICE_TRANSIT_VALUE': None, '~PROPERTY_PRICE_TRANSIT_VALUE': None, 'PROPERTY_PRICE_TRANSIT_VALUE_ID': None, '~PROPERTY_PRICE_TRANSIT_VALUE_ID': None, 'PROPERTY_DIOH_VALUE': '0', '~PROPERTY_DIOH_VALUE': '0', 'PROPERTY_DIOH_VALUE_ID': '18461402', '~PROPERTY_DIOH_VALUE_ID': '18461402', 'LANG_DIR': '/', '~LANG_DIR': '/', 'CODE': 'stol-standartnyy-120-54-sm-dlya-mashiny-a-8700', '~CODE': 'stol-standartnyy-120-54-sm-dlya-mashiny-a-8700', 'EXTERNAL_ID': '58508/0', '~EXTERNAL_ID': '58508/0', 'IBLOCK_SECTION_ID': '2604', '~IBLOCK_SECTION_ID': '2604', 'IBLOCK_TYPE_ID': 'catalog', '~IBLOCK_TYPE_ID': 'catalog', 'IBLOCK_CODE': '', '~IBLOCK_CODE': '', 'IBLOCK_EXTERNAL_ID': '', '~IBLOCK_EXTERNAL_ID': '', 'LID': 's1', '~LID': 's1', 'QUANTITY': 2, 'QUANTITY_R': 0, 'PRICES': {'0': {'ID': '304604', 'PRODUCT_ID': '310101', 'PRICE': '62.00', 'CURRENCY': 'USD', 'CATALOG_GROUP_ID': '1'}}, 'AVAILABLE': 1, 'AVAILABLE_CLASS': 'in_stock', 'AVAILABLE_TITLE': 'в наличии', 'AVAILABLE_DIOH': '', 'PRICE_VALUE': 4574, 'PRICE_PRINT_VALUE': '4 574 Р', 'PRICE_DISCOUNT_VALUE': 4574, 'PRICE_PRINT_DISCOUNT_VALUE': '4 574 Р', 'PRICE_USD_DISCOUNT_VALUE': 62, 'PRICE_USD_PRINT_DISCOUNT_VALUE': '$62', 'BONUS_VALUE': None, 'BONUS_FORMATED': ''}


text:
Q: How to send common header for auth in flassger (python swagger) Currently, I am using this type of docstring with Flassger which works fine:
"""End Point to create something
  ---
  parameters:
    - name: body
      in: body
      type: string
      required: true
    - name: token
      in: header
      description: an authorization header
      required: true
      type: string
  responses:
    200:
      description: Some description
  """

And I am able to send the request from ui like this:

But I need to make the token parameter global on this page, so that the user only need to fill this just once. What do I need to do to achieve that?

A: All you need to do is define the authorization token in the api definitions.
Try something like this:
  securityDefinitions:
  Token:
   type: apiKey
   name: Token
   in: header

And then put this code in the endpoint you want to secure with the token:
 security:
 -Token: []

In your example:
  parameters:
  - name: body
   in: body
   type: string
   required: true
   security
   - Token:[]
   responses:
     200:
      description: Some description

If you want to secure all the endpoints with the token do like this:
securityDefinitions:
  Token:
   type: apiKey
   name: Token
   in: header
security
   - Token:[]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simplifying RegionUnion call after CylindricalDecomposition I want to simplify unions of output from CylindricalDecomposition calls.
Consider:
decomp1 = CylindricalDecomposition[x > y && y >= 0, {x, y}]
decomp2 = CylindricalDecomposition[y >= x && x >= 0, {x, y}]

These yield, respectively:
x > 0 && 0 <= y < x
x >= 0 && y >= x

Pen and paper shows that their union is x >= 0 && y >= 0.  What Mathematica call returns this?
Unsuccessful attempts:

*

*Union[decomp1, decomp2] yields x > 0 && x >= 0 && y >= x && 0 <= y < x.

*RegionUnion[decomp1, decomp2] yields RegionUnion::reg: x>0&&0<=y<x is not a correctly specified region.

*RegionUnion[ImplicitRegion[decomp1, {x, y}], ImplicitRegion[decomp2, {x, y}]] yields ImplicitRegion[(x > 0 && 0 <= y < x) || (x >= 0 && y >= x), {x, y}].


text:
Q: Help in justifying that $f(a,b)$ is a global minimum Let $A,B,C,D,E,F\in\mathbb{R}$, such that $A>0$ and $B^2<AC$. Given
$f(x,y)= Ax^2+2Bxy +Cy^2 +2Dx + 2Ey + F$
show that it assumes a global minimum:
$f(a,b) = \frac{1}{\delta}\begin{vmatrix}
A & B & D \\
B & C & E \\
D & E & F \\
\end{vmatrix}$ = $Da+Eb+F$,
where $\delta =
\begin{vmatrix}
A & B \\
B & C \\
\end{vmatrix}$.
Attempt:
The gradient of $f$ is:
$\nabla f(x,y)= (2Ax + 2By + 2D, 2Bx + 2Cy + 2E)$.
Hence the Hessian of $f$:
$H(x)= \begin{bmatrix}
     2A      & 2B \\
    2B      & 2C \\
\end{bmatrix}$
Just note then that $det(H(x))= 4(AC-B^2)$. Since by hypothesis we have that $A>0$, $0<AC-B^2$, and the Hessian is independent of any point, this shows that $H(x)$ has a global minimum.
Now my problem is: how can i justifiy that the point of minimum is the one given? Should i use Cramer's rule?
Edit: Should i rotate it and transform into a quadratic form of a diagonal matrix? I may guess that the function defines a paraboloid. And supposing that i have found the point of global minimum of the rotated function, how can i plug it back in the original coordinate system and justify that it is the same as $(a,b)$?
Edit: I had some advances. Solving the linear system $\nabla f=0$, using cramer's rule we find that $a = (BE-DC)/\delta$ and $b=(DB-AE)/\delta.$ Now opening the determinant of $f(a,b)$ by cofactors, we find that $f(a,b)$ is exactly equal to $Da+Eb+F.$ This is a great advance, i think. But i don't think that it is totally conving, because i still have to show that pluging in $(a,b)$ in $f$  i shall  get the same value.

A:
Edit: I had some advances. Solving the linear system $\nabla f=0$, using cramer's rule we find that $a = (BE-DC)/\delta$ and $b=(DB-AE)/\delta.$ Now opening the determinant of $f(a,b)$ by cofactors, we find that $f(a,b)$ is exactly equal to $Da+Eb+F.$ This is a great advance, i think. But i don't think that it is totally conving, because i still have to show that pluging in $(a,b)$ in $f$  i shall  get the same value.

So you found (with $\delta = AC-B^2$):
$$a = \frac{BE-DC}{\delta} \quad \mbox{and} \quad b = \frac{DB-AE}{\delta}$$
Plugging into:
$$f(x,y)= Ax^2+2Bxy +Cy^2 +2Dx + 2Ey + F$$
gives you:
$$\color{blue}{f(a,b)=} \color{red}{A\left( \tfrac{BE-DC}{\delta} \right)^2+2B\tfrac{BE-DC}{\delta}\tfrac{DB-AE}{\delta} +C\left( \tfrac{DB-AE}{\delta} \right)^2 +D\tfrac{BE-DC}{\delta} + E\tfrac{DB-AE}{\delta}} \\ + \color{blue}{Da+Eb+ F}$$
Rewriting the red part:
$$\frac{1}{\delta^2} \bigl( A(BE-DC)^2+2B(BE-DC)(DB-AE)+C(DB-AE)^2 \\ +\delta D (BE-DC) + \delta E (DB-AE) \bigr)$$
Expanding all and simplifying gives you $0$, leaving you with the blue part for the minimal value.


text:
Q: Can't connect to Cassandra with SSL using cqlsh I am trying to get SSL (client to node) to work on Cassandra 2.1.2.
I have created the keystore and the truststore according to the instructions here. Then I have updated cassandra.yaml to this:
client_encryption_options:
    enabled: true
    keystore: /etc/cassandra/security/.keystore
    keystore_password: ********
    # require_client_auth: false
    # Set trustore and truststore_password if require_client_auth is true
    truststore: /etc/cassandra/security/.truststore
    truststore_password: ********
    # More advanced defaults below:
    # protocol: TLS
    # algorithm: SunX509
    # store_type: JKS
    # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]

I am trying to connect using cqlsh, however I get the following error:
 Connection error: ('Unable to connect to any servers', {'192.168.0.16': ConnectionShutdown('Connection <AsyncoreConnection(140569820674832) 192.168.0.16:9042 (closed)> is already closed',)})

My cqlshrc file looks like this:
[connection]
hostname = 192.168.0.16
port = 9042
factory = cqlshlib.ssl.ssl_transport_factory

[ssl]
validate = false
certfile = /home/flavien/localhost.pem

For the certfile, I have tried the pem and the crt file, this makes no difference.
There is no evidence in the Cassandra logs - no error, nothing.
My java version is this:
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

And I have installed the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.
I have also tried to connect using DevCenter and the C# driver, to no avail.
Any idea how I can make this work?

A: You have to use --ssl flag as described in the Documentation for 2.1


text:
Q: Bash script command not found error in while loop I have problem and cant still handle with it. :(
Here is my code
declare -i disk_usage_rate=$(df -h /appdata/SCT_CDR | cut -d '%' -f 1 | awk 'NR==2{print $5}')

while ["$disk_usage_rate" -gt 80]
do
...
...
done

I get the disk usage rate from df -h command. But in while loop I get the followig error. Btw it is bash script.

bash: [84: command not found

I tried so many things but I didnt solve yet.

A: You are missing space near square brackets used in while loop such as below -
declare -i disk_usage_rate=$(df -h /appdata/SCT_CDR | cut -d '%' -f 1 | awk 'NR==2{print $5}')

while [ "$disk_usage_rate" -gt 80 ]
do
...
...
done

A bit of history: this is because '[' was historically not a
  shell-built-in but a separate executable that received the expresson
  as arguments and returned a result. If you didn't surround the '['
  with space, the shell would be searching $PATH for a different
  filename (and not find it) . – Andrew Medico Jun 24 '09 at 1:13

Ref - bash shell script syntax error

A: I see one error : add a space after '[' and before ']' on your while line :
while [ "$disk_usage_rate" -gt 80 ]

Is it better ?


text:
Q: Adjusting the MAFFT command line algorithm to better account for gaps I've been attempting to use the MAFFT command line tool as a means to identify coding regions within a genome. My general process is to align the amino acid consensus sequence of a gene to a translated reading frame of a target sequence. My method has been largely successful. However, I've noticed some peculiar alignments which will unfortunately impede my annotation method. The following is one such example (Note - I've also included a pairwise alignment from the Pairwise2 Biopython module to demonstrate my desired output. Unfortunately, the computation time for Pairwise2 is nearly 20 times slower than MAFFT command line):
from time import *
from Bio.SubsMat import MatrixInfo as matlist
from Bio import pairwise2
from Bio.pairwise2 import format_alignment
from Bio.Align.Applications import MafftCommandline

startTime = time()

sample_tList = [['>Frame 1', 'RIGVGSIPRHLYCQELPLAQPKTCCAETPFRDSPLQGRLGVCPHLASGVALLYGLSTPLTMSGILDRCTCTPNARVFMAEGQVYCTRCLSARSLLPLNLQVPELGVLGLFYRPEEPLRWTLPRAFPTVECSPAGACWLSAIFPIARMTSGNLNFQQRMVRVAAEIYRAGQLTPAVLKVLQVYERGCRWYPIVGPVPGVGVYANSLHVSDKPFPGATHVLTNLPLPQRPKPEDFCPFECAMADVYDIGHGAVMFVAGGKVSWAPRGGDEVRFETVPEELKLIANRLHISFPPHHLVDMSKFAFIVPGSGVSLRVEHQHGCLPADIVPKGNCWWCLFDLLPPGVQNREIRYANQFGYQTKHGVSGKYLQRRLQINGLRAVTDTHGPIVVQYFSVKESWIRHFRLAGEPSLPGFEDLLRIRVESNTSPLADKDEKIFRFGSHKWYGAGKRARKARSGATTTVAHRASSARETRQAKKHEGVDANNAAHLEHYSPPAEGNCGWHCISAIVNRMVNSNFETTLPERVRPSDDWATDEDFVNTIQILRLPAALDRNGACKSAKYVLKLEGEHWTVSVAPGMSPSLLPLECVQGCCEHKGGLGSPDAVEVSGFDPTCLDRLAEVMHLPSSVIPAALAEMSNNSDRPASLVNTAWTVSQFYARHTGGNHRDQVRLGKIISLCQVIEECCCHQNKTNRATPEEVAAKIDQYLRGATSLEECLIKLERVSPPSAADTSFDWNVVLPGVEAAGPTTEQPHANQCCAPVPVVTQEPLDKDSVPLTAFSLSNCYYPAQGDEVRHRERLNSVLSKLEEVVLEEYGLMPTGLGPRPVLPSGLDELKDQMEEDLLKLANAQATSEMMALAAEQVDLKAWVKSYPRWIPPPPPPKVQPRRMKPVKSLPENKPVPAPRRKVRSDPGKSILAVGGPLNFSTPSELVTPLGEPVLMPASQHVSRPVTPLSEPAPVPAPRRIVSRPMTPLSEPTFVFAPWRKSQQVEEANPAAATLTCQDEPLDLSASSQTEYEAYPLAPLENIGVLEAGGQEAEEVLSGISDILDNTNPAPVSSSSSLSSVKITRPKYSAQAIIDSGGPCSGHLQKEKEACLRIMREACDAARLGDPATQEWLSHMWDRVDVLTWRNTSVYQAFRTLDGRFGFLPKMILETPPPYPCGFVMLPHTPTPSVSAESDLTIGSVATEDVPRILGKTENTGNVLNQKPLALFEEEPVCDQPAKDSRTLSRESGDSTTAPPVGTGGAGLPTDLPPLDGVDADGGGLLRTAKGKAERFFDQLSRQVFNIVSHLPVFFSHLFKSDSGYSPGDWGFAAFTLFCLFLCYSYPFFGFAPLLGVFSGSSRRVRMGVFGCWLAFAVGLFKPVSDPVGAACEFDSPECRNILHSFELLKPWDPVRSLVVGPVGLGLAILGRLLGGARYIWHFLLRLGIVADCILAGAYVLSQGRCKKCWGSCIRTAPNEIAFNVFPFTRATRSSLIDLCDRFCAPKGMDPIFLATGWRGCWTGQSPIEQPSEKPIAFAQLDEKRITARTVVSQPYDPNQAVKCLRVLQAGGAMVAEAVPKVVKVSAIPFRAPFFPTGVKVDPECRIVVDPDTFTTALRSGYSTTNLVLGVGDFAQLNGLKIRQISKPSGGGPHLIAALHVACSMVLHMLAGVYVTAVGSCGTGTSDPWCANPFAVPGYGPGSLCTSRLCISQHGLTLPLTALVAGFGLQEIALVVLIFVSIGGMAHRLSCKADMLCILLAIASYVWVPLTWLLCVFPCWLRWFSLHPLTILWLVFFLISVNMPSGILAVVLLVSLWLLGRYTNIAGLVTPYDIHHYTSGPRGVAALATAPDGTYLAAVRRAALTGRTMLFTPSQLGSLLEGAFRTRKPSLNTVNVVGSSMGSGGVFTIDGRIKCVTAAHVLTGNSARVSGVGFNQMLDFDVKGDFAIADCPNWQGVAPKTQFCGDGWTGRAYWLTSSGVEPGVIGDGFAFCFTACGDSGSPVITEAGELVGVHTGSNKQGGGIVTRPSGQFCNVTPIKLSELSEFFAGPKVPLGDVKVGSHIIKDTSEVPSDLCALLAAKPELEGGLSTVQLLCVFFLLWRMMGHAWTPLVAVGFFILNEVLPAVLVRSVFSFGMFALSWLTPWSAQVLMIRLLTAALNRNRVSLIFYSLGAVTGFVADLATTQGHPLQAVMNLSTYAFLPRMMVVTSPVPAIACGVVHLLAIILYLFKYRCLHHVLVGDGAFSAAFFLRYFAEGKLREGVSQSCGMSHESLTGALAIKLSDEDLDFLTKWTDFKCFVSASNMRNAAGQFIEAAYAKALRIELAQLVQVDKVRGTLAKLEAFADTVAPQLSPGDIVVALGHTPVGSIFDLKVGSTKHTLQAIETRVLAGSKMTVARVVDPTPAPPPAPVPIPLPPKVLENGPNAWGGEDRLNKRKRRRMEAVGIFVMDGKKYQKFWDKNSGDVFYEEVHNSTDEWECLRAGDPADFDPETGIQCGHVTIEDKVYNVFTSPSGRRFLVPANPENRRIQWEAARLSVEQALGMMNVDGELTAKELEKLKRIIDKLQGLTKEQCLNCPPVAPAVVAAAWLLLRQRKNFTTGPSPDLTKWPVRLSRTRSSTTNIRLPNRLMVVLCSCAPLFLRLMSSPALMHLLSYLPATGRETLGLMARFGILRPRPPKRKSHLVRKYRLVTLGAVTHLKLVSLISCTLLGATLSGKEFYRIQGLETYLTEPPVTLEAQCMRLPASRPMLLRLMGVPSWPQPCPPVLSCMYRPFQRPSLIILILGLTALNSQSTVVRMLLGTSPNTICPPKALFCLEFFALCGSTCLPMWVSARPFIGLPLTLPRILWLEMGTDFQPRIFRASLKSTFCAHRLCEKTGKLLLLVPSRSSIVGRRRLGQYLALITLRWPTGQRVVLPRASKRHSTRPSPSEKTNLRNYILQFAGALKLILHPAIDPHLQLSAGSLPIFFMNSPVLKSIYRRTCLTAVTTYWLRSPARLREAACRLATRLPPCQTPFTAYMHSTWCSVTLKVVTLMAFCFCKTSSLRTCSRFNPSSIQTTSCCMPSLPPCQITTGGLNITLCVSKRTQRRQPQTRHHFVAGMGVSSLTVTGFLRPSPTIRQAMSLNTTPRRLQYLWTAVLVSMILSGLKSSWLVRSAPARTVTASQARRSSCPCGKNSGPIMKGRSPECAGTAEPRLRTPLPVASTSVLTTPISTSIVLSSGVATRRVLALVVSVNLPWEKAQVLWMRCNKSRISLRGLSCMWSRVSPLLTQVDTKLAADSPLGVASGETKLTCQTVIMPVPPCSPLVKRSTWSLSPPTCCAAGSSSVPPALGKHTGSSNRSRMVMSFTRQLTRPCLTLGLWGCAGSTSQRVRRCNSLPPLVPARGFASWPAVGVLVRIPFWTKQRIAITLMSGFLAKPPLPAEISNNSTRWVLTLIAMFLTSCLRPNRPSGDSDRISVMPSNQITGTNLCPWSTQPVPRWTNLSGMGKSSPPTTGTERTAPSLSTPVKVPHLMWLHCICPLKIHSTGNEPLLLSPGQDMQSSCMTHTGNCRACLIFLRKAHPSTSQCSVTSSSYIEITKNARLLRLAMEINSGLQTSALILSAPFVQIWKGRAPRSPKLHITWGSISHLIHSLLNSQQNSHPTGPWQPRTMKSGLIGWLPAFAPSINIAARALVQAIWWAPRCFAPQGLCHTTSQNLLGARLKCFLRQSSAPAELRIAGSTSMIGSEKLLSPSHMPSLATSKALPVGDVITSPPDTFRASFLRNQLRSGFLAPEKLQRQFAHQMCTSQILKRTSTQRPSPSAGKCWILEKSDWSGKTRRPIFNLKAAISPGINLQATPHTSEFLLILQCIWTPAWALPFATGGLLGPPIGELTSRSPLMITVPKSFCLVHTMVKCLQGTKFWRARSSRLTTQGTNTLGDLNRIQRICTSLLGMVRTGRIIMKRFGRARKGKFIRLLPPASFIFPRALSLNQLATEMKWGLCRASLTKLVNFLWMLSRNFWCPLLISSYFWPFCLASPSPAGWWSFASDWFAPRYSVRALPFTLSNYRRSYEAFLSQCQVDIPTWGVKHPLGILWHHKVSTLIDEMVSRRMYRIMEKAGQAAWKQVVSEATLSRISNLDVVAHFQHLAAIEAETYKYLASRLPMLHNLRMTGSNVTIVYNSTLNQVFAIFPTSGSRPRLHDSQQWLIAVHSSIFSSVVASCTLFVVLWLRIPMLRSVFGFRWLGAIFLLNSRITRCVRLASPGRPLLRSMNPVGLFGAGGMTDAVRTTMTNGSWFRLASAKATPVFTPGWRSCHSATRPSSIPRYLGGTVKFMLTSRTNSFAPSTTGRTPPCLAMTTFQPYFRPTTNIRSTAVIGFTNGCAPSFPLGWFMFRGFSGVRLQAMFQFKSFRHQDQHYRSIRLCCPPGHQLPVWRLAPSDGSQELSVPHGDRDTRVHHHHSQCHRELFTFFSPHAFLLPFLCFDEKGIQSGIWQCVRHRGCVCLYQLRPTCQGVHPTLLGSRSCATASFHDTDHEVGNRFSLSFCHPTGNLNVQVCWGNAPRAVTRNCFLCGVSCRSVLLCSSTPAATAALIFSFITRYVSMAQIGWQKDLTGQWRLLSFFLCLTLFPMEHSPPAIFLTRLVSLCPPPGSITGGMSVVSMRSVLWLRFASSLGLRRTACPGATLVLDTPTSFWTLRADSIVGGRPLLRKGVRLKSRVTSTSKELCLMVPWQPLPEFQRNNGVVSRRLLPHGSTKGAFGVFHYLYASDDICSKGKSRPTARASAPFDLPELCFYLRVHDIRALSEHKGRAHYGGSSCTSLGGVLSHRNLEIHHLQMPFVLARPQVHSGPCPPRRKCRGLSSDCGKPRICRPASRLHYGRHIGARVEKPRVGWQKSCTGSGKPCQICQITTASSKRERRGTASQSISCARCWVRSSPNKTSPEARDRGRKIIREARRSPIFLRLKKMSGTTSPLVSGNCVCRRSRLPLTRAPGHVPCQIQGGVTLWSLVCRRIILCASASQHHPQHDELAFFGHLGVMIGRMCGEWHLTLCLVTYSIRATVWGSLIGENHAAAIKKKKKKKK'], ['>ORF2_GP2', 'MKWGLCKASLTKLANFLWMLSRSFWCPLLISSYFWPFCLASQSPVGWWSFASDWFAPRYSVRALPFTLSNYRRSYEAFLSQCQVDIPTWGVKHPLGVLWHHKVSTLIDEMVSRRMYRIMEKAGQAAWKQVVSEATLSRISGLDVVAHFQHLAAIEAETCKYLASRLPMLHNLRLTGSNVTIVYNSTLDQVFAIFPTPGSRPKLHDFQQWLIAVHSSIFSSVAASCTLFVVLWLRIPMLRSVFGFRWLGATFLLNSW']]

ex_file = open("newTempFile112233.fasta", "w")

for items in sample_tList:
    ex_file.write(items[0] + "\n")
    ex_file.write(items[1] + "\n")

ex_file.close()

in_file = '.../msa_example.fasta'
mafft_exe = '/usr/local/bin/mafft'

mafft_cline = MafftCommandline(mafft_exe, input=in_file) #have to change file path
#mafft_cline = MafftCommandline(mafft_exe, input=in_file, localpair=True, lexp=-1.5, lop=0.5)

stdout, stderr = mafft_cline()
print(stdout)
test_align = AlignIO.read(io.StringIO(stdout), "fasta")
#print(test_align)

os.remove("newTempFile112233.fasta")

print('Total time = ' + str(time() - startTime))
startTime = time()

matrix = matlist.blosum62

pWise_align = pairwise2.align.localds(sample_tList[0][1], sample_tList[1][1], matrix, -6, -1)
print(format_alignment(*pWise_align[0]))

print('Total time = ' + str(time() - startTime))

I've attempted to change the MAFFT command line alignment algorithm by referencing the help document (http://mafft.cbrc.jp/alignment/software/manual/manual.html). I don't get any error messages, but the alignment output does not change. I'm unsure what adjustments need to be made. I believe that by increasing the gap extension penalty (which is zero by default), the alignment will be improved. I haven't been able to find many documentation examples where custom variables are used when using MAFFT command line on this forum or through Google search. Help is much appreciated. For reference, documentation on the Pairwise2 alignment parameters can be found here: http://biopython.org/DIST/docs/api/Bio.pairwise2-module.html

A: Managed to figure out a possible solution. The alignment of the example sequences provided results in a long terminal/end gap which should not be present. Changing the MAFFT alignment algorithm using localpair, lexp, and lop had no effect (causing me a good deal of confusion). However, I have noticed differences in the alignment output when each input sequence is reversed. Oddly, the only way I was able to remove the terminal/end gap was to set the lop (gap opening penalty) to a lesser amount relative to lexp (gap extension penalty). I suspect my solution is niche and may not be applicable to other similar occurrences of terminal gaps. Changing the alignment settings also likely reduces the optimal alignment.
Going forward, I plan to use an automated process to run alignments of consensus sequences to raw sequences. In the event I detect irregularities with the alignment output (specifically terminal gaps), I'll attempt to reverse the input sequences and apply custom alignment settings. I suppose if that isn't a consistent solution, I'll figure out a way to refine the alignment output directly.
For anyone curious, I used a lexp value of -1.5 and lop value of 0.5 (now included in a hashed out line in my example code).


text:
Q: Can I find $a$ and $b$ so that $\cosh(ax) - \cosh(bx) = \cosh(cx)$? I want to find $a$ and $b$ in terms of $c \in \mathbb R$ that satisfy
$$\cosh(ax) - \cosh(bx) = \cosh(cx)$$
How can I? There are no restrictions on $a$ and $b$.

A: Put $x=0$ to see that such an equation cannot hold.


text:
Q: Laravel 5.4 - get translations from database instead of lang files I need to keep my translations in a database.
I have created a model with group, key and value and filled the database with all the values i currently have in my lang files. Now i wish to make the switch so if trans('group.key') or @lang('group.key') is called from my code i want it to get the value from database, not the lang file. How is it possible to achieve this?
PS. I looked through some of the available plugins that do something similar, but they dont quite fit me because i have my own complex models.

A: You can extend the Illuminate\Translation\Translator class and pass in a collection from the database as an array in place of $locale. The trans function is just a wrapper for this class.
That class uses all the common support classes when working with arrays, collections, etc.
use Countable;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Collection;


text:
Q: Hyperlink forces file download - how to save file on server? I want to build a website which mainly shows data in charts. Data for charts should come from MySQL database. Currently I don't know how to save a CSV file on my server to feed my database later.
The problem is that the file is saved on another server and only offered by hyperlink which references to an PHP file (f.e. www.asdf.com/fore_csv_download.php).
Is there a possibility to download the CSV file to my Server?
Once the File is saved I should be able to load data into the database with this: MYSQL automatically insert csv files from folder using mysqlimport
Later I'm thinking of automate this process with cron jobs.

A: If need retrieve file in other server use CURL, eg:
<?ph
$source = 'http://www.asdf.com/fore_csv_download.php';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);

file_put_contents('/var/www/data/file.csv', $data);

If need download for local, create a page like this (eg. download.php):
<?php
$file = FULL PATH CSV FILE from "Database" (only a example);

header('Content-Type: text/csv');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="' . basename($file) . '"');

echo file_get_contents($file);


text:
Q: letting a java function accept a collection or an array I am trying to write a function that takes some strings and does something with them.
The only thing I'm going to do that the set of strings is loop over them. Right now I end up with an awkward construct along the lines of
public void foo(String[] myStrings){
    foo(java.util.Arrays.asList(myStrings));
}

public void foo(Iterable<String> myStrings){
    for(String i : myStrings){
        bar(i);
    }
}

which feels redundant since
for(String i : myStrings){
    bar(i);
}

would be perfectly valid code for myStrings of type String[].
Is there a class that I can have foo accept which will allow both collections and arrays?

A: Unfortunately array does not implement Iterable, despite the for-each loop working on both.
You could exclusively only accept Iterable, as passing around arrays is a bit old school (the performance benefits of arrays over ArrayList is negligible). An existing array can be easily wrapped and converting to a List using Arrays.asList(T... a).

A: Although arrays can be used in a for-each loop, they do not implement Iterable. There are simply two possibilities, either overload the method as you've stated, or just provide only the iterable variant and force the client to call Arrays.asList().
In case you want to also provide the array overload, you might change its signature from simple array to varargs:
public void foo(String... myStrings){
    foo(java.util.Arrays.asList(myStrings));
}

In such case, beware of the incompatibility between primitive arrays and primitive-wrapper arrays:
static void foo(int... ints) {}
foo(new Integer[] {1, 2}); // compile error

and:
static void foo(Integer... integers) {}
foo(new int[] { 1, 2 }); // compile error

And the most obscure part, with generic varargs:
static <T> T[] foo(T... ts) {
    return ts;
}

If you pass an array of Integers:
Integer[] integers = { 1, 2 };
System.out.println(Arrays.deepToString(foo(integers)));
> [1, 2]

The value of ts is an array of Integers with 2 elements: 1 and 2.
However, if you pass an array of primitive ints, a funny thing happens:
int[] ints = { 1, 2 };
System.out.println(Arrays.deepToString(foo(ints)));
> [[1, 2]]

In this case, the value of ts is an array of int arrays (int[][]) with only one element, which is the originally passed array. The reason for this is that an int isn't an Object (autoboxing doesn't help here), while an array of ints is, so the value of the T type parameter becomes int[].

A: See Why is an array not assignable to Iterable?
Short answer: no. Array types are synthetic code, as I understand it, and thus do not implement Iterable or any other types. You need to provide an overloaded method or require clients to call Arrays.asList at the call site.


text:
Q: Limiting only specific emails to logIn with Gmail Oauth I was wondering if I could just simply do the following to limit logins, but I seem to run into a problem where the page just reloads constatly once I log in once.
function onSignIn(googleUser) {
    var profile = googleUser.getBasicProfile();
    console.log('Name: ' + profile.getName());
    console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.

    //list the emails that can login to the website using Gmail OAuth
    if (profile.getEmail() == "XXXXXXXX@gmail.com") {
        window.location.href = "./index.html"
    } else {
        let done = confirm("You don't have permission to access this.")
        if (done) {
            window.location.href = "https://www.HOMEPAGEco.uk/"
        } else {
            alert("Please try again.")
        }
    }

}

A: The line window.location.href = "./index.html" will always reload the page; if you want no action to be taken when they are in the whitelist, just check if they are NOT in the list.
if (profile.getEmail() !== "XXXXXXXX@gmail.com") {
    let done = confirm("You don't have permission to access this.")
    if (done) {
        window.location.href = "https://www.HOMEPAGEco.uk/"
    } else {
        alert("Please try again.")
    }
}


text:
Q: How can I Convert a ReadonlyArray to any[]? Some native angular functions return a ReadonlyArray. Some native angular callbacks pass ReadonlyArrays. Since my typescript code may be called in many ways, I don't want to require all arrays passed to my functions be ReadonlyArrays.
Hence I need to convert a ReadonlyArray to a javascript native array, [].

A: The simplest way to convert the ReadonlyArray to any[] is to use one of the available methods of ReadonlyArray.
For this we will use concat(). Calling concat with no parameters on a ReadonlyArray will return an [].
You can view other ReadonlyArray members here.


text:
Q: Altering combineLatest to emit the result without awaiting other observables I have this rxjs code where cobineLatest is used
cobineLatest(
  this.controls.toArray().map(c => c.changeEvent.asObservable())
).subscribe(x => {
  console.log(x);
});

The thing is that there won't be any result in subscription until all observables emits, I wonder how would you change that behavior so it will start emitting even if one single observable emits?

A: I suggest you to just pipe the single observables to start with null. This way you ensure that each observable has emitted at least one value:
cobineLatest(
  this.controls.toArray().map(c => c.changeEvent.asObservable().pipe(startWith(null)))
).subscribe(x => {
  console.log(x);
});

A: If your are interested in the emitted value only (not the array), then merge might be your friend.
merge(
  this.controls.toArray().map(c => c.changeEvent.asObservable())
).subscribe(x => {
  console.log(x); // x is not an array
});


text:
Q: Django how to get specific field with complex join in one-to-many relationship I have a database consists of 3 tables

*

*Project table

*Section table

*Task table

And the their relationships

*

*Project table have one-to-many relation ship with Section table.

*Section table have one-to-many relation ship with task table.

I have already queried a target task record by this code
 task = tasks.objects.filter(section_id=sectionID)

Assume that I have sectionID and then I would like to get project.id from a task object, what should I do?
Thank you.

A: I guess you models look like that:
class Project(models.Model):
    #...

class Section(models.Model):
    #...
    project = models.ForeignKey(Project)

class Task(models.Model):
    #...
    section = models.ForeignKey(Section)

So in order to get a task project you just have to follow the relation.
#when task is a single task object
project = task.section.project

Have in mind that this will make 2 queries (one to get the section and one to get the project) you can optimize this with select_related
tasks = Task.objects.filter(section_id=sectionID).select_related('section__project')
for task in tasks:
    project = task.section.project
    print project.id

ending with a single query.
I guess you can also want to know how to get a queryset of projects contained by some sectionID, in this case you can use the reverse relations like so:
projects = Project.objects.filter(section__id=sectionID)

A: You can reach it using task.section.project.id.


text:
Q: How can I load a three.js Blender 2.7 exported model without being on a HTTP server? Hi I and currently doing all my THREE.js things on file:///.
When I follow tutorials to load models they do
var myLoader = new THREE.JSONLoader();

myLoader.load( url-path-to-file );

The error:
XMLHttpRequest cannot load file:///C:/.../.../.../testmodel.js. Cross origin requests are only supported for HTTP. three.js:11996
THREE.JSONLoader: "./testmodel.js" seems to be unreachable or the file is empty. three.js:11952
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/.../.../.../testmodel.js'.

Because of the limitations of using the file protocol I cannot load things like this. I am wondering how to skip this? I am thinking of storing the exported blender as a JavaScript object and then maybe there is already a piece of THREE.js that can do the rest for me?

A: Run a python web server from your root directory is what I have done to avoid XSS related errors. I have python installed in windows.
Python version 3 in windows from directory that has your HTML file etc:
c:\Python33\python.exe -m http.server

then point your browser to:
http://localhost:8000/yourhtmlfile.html

For more info on running the server for various versions of python / OS see here:
https://github.com/mrdoob/three.js/wiki/How-to-run-things-locally

A: Check out this little project. It is a 3D file viewer and has the ability to load STL and Collada files locally in the client. Works both locally and on a server:
https://github.com/yomboprime/Visor3D
Deriving from the code a local JSON loader function is trivial. Yoy can start modifying the loadDAEFile() function (main.js), which reads local file as text.


text:
Q: Images are different sizes coming from a database Storing images in a database and outputting them to my website, however, they are coming out different sizes.
Tried to alter my CSS but not sure what I should be tagging to alter
$sql = "SELECT * FROM items WHERE category LIKE '%$search%'";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
    echo "
";
    echo "";
    echo "
" . $row['description']."
";
    echo "
" . $row['category']."
";
    echo "
";
}

A: Don't use the same ID for every image. Give them a class, and then set the height and width for the class.
?>

<?php
$sql = "SELECT * FROM items WHERE category LIKE '%$search%'";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
    echo "
";
    echo "";
    echo "
" . $row['description']."
";
    echo "
" . $row['category']."
";
    echo "
";
}


text:
Q: Multiple ScheduledExecutorServices or one with a ThreadPool for Fixed Rate Tasks Consider a hypothetical case in which multiple tasks will run permanently in fixed rates. The number of these tasks will not change as long as the application runs. For such a case, is there any difference between creating a thread pool with n tasks like this
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(n);
for (int i = 0; i < n; i++) {
    executorService.scheduleAtFixedRate(job, 0, 5, TimeUnit.MINUTES);
}

and creating single executor for each task as given below?
for (int i = 0; i < n; i++) {
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(job, 0, 5, TimeUnit.MINUTES);
}

If there is any difference, which one should be preferred and why?
Note: Aside from creating multiple executor instances

A: The executor is meant to handle a pool of threads. So you don't need to create N Executors with a single thread as you end up with N instances of executors and N threads. Just hold one Executor that handles the N threads and you saved some memory by having 1 executor and N threads.

A: *

*The first one will create one executor with fixed number of threads.

*The second one will create n executors each with single thread.

The difference is that later on you could re-configure number of threads in newScheduledThreadPool. You would not be able to change number of threads in newSingleThreadScheduledExecutor. Also when creating multiple executors you would end up with 5 objects instead of one (creating just one executor). Personally, I would go with 1st option.


text:
Q: Change White Pixels in a UIImage I have a UIImage which is an outline, and one which is filled, both were created from OpenCV, one from grab cut and the other from structuring element.
my two images are like this:

I am trying to change all of the white pixels in the outlined image because I want to merge the two images together so I end up with a red outline and a white filled area in the middle. I am using this to merge the two together, and I am aware instead of red it will be a pink kind of colour and a grey instead of white since I am just blending them together with alpha.
// Start an image context
UIGraphicsBeginImageContext(grabcutResult.size)

// Create rect for this draw session
let rect = CGRect(x: 0.0, y: 0.0, width: grabcutResult.size.width, height: grabcutResult.size.height)
grabcutResult.draw(in: rect)
redGrabcutOutline.draw(in: rect, blendMode: .normal, alpha: 0.5)

let finalImage = UIGraphicsGetImageFromCurrentImageContext()

and the idea is it should look something like this.

I want to be able to complete this operation quickly but the only solutions I have found are either for ImageView (which only affects how stuff is rendered not the underlying UIImage) or they involve looping over the entire image pixel by pixel.
I am trying to find a solution that will just mask all the white pixels in the outline to red without having to loop over the entire image pixel by pixel as it is too slow.
Ideally it would be good if I could get openCV to just return a red outline instead of white but I don't think its possible to change this (maybe im wrong).
Using swift btw... but any Help is appreciated, thanks in advance.

A: This may work for you - using only Swift code...
extension UIImage {

    func maskWithColor(color: UIColor) -> UIImage? {

        let maskingColors: [CGFloat] = [1, 255, 1, 255, 1, 255]
        let bounds = CGRect(origin: .zero, size: size)

        let maskImage = cgImage!
        var returnImage: UIImage?

        // make sure image has no alpha channel
        let rFormat = UIGraphicsImageRendererFormat()
        rFormat.opaque = true
        let renderer = UIGraphicsImageRenderer(size: size, format: rFormat)
        let noAlphaImage = renderer.image {
            (context) in
            self.draw(at: .zero)
        }

        let noAlphaCGRef = noAlphaImage.cgImage

        if let imgRefCopy = noAlphaCGRef?.copy(maskingColorComponents: maskingColors) {

            let rFormat = UIGraphicsImageRendererFormat()
            rFormat.opaque = false
            let renderer = UIGraphicsImageRenderer(size: size, format: rFormat)
            returnImage = renderer.image {
                (context) in
                context.cgContext.clip(to: bounds, mask: maskImage)
                context.cgContext.setFillColor(color.cgColor)
                context.cgContext.fill(bounds)
                context.cgContext.draw(imgRefCopy, in: bounds)
            }

        }
        return returnImage
    }

}

This extension returns a UIImage with white replaced with the passed UIColor, and the black "background" changed to transparent.
Use it in this manner:
// change filled white star to gray with transparent background
let modFilledImage = filledImage.maskWithColor(color: UIColor(red: 200, green: 200, blue: 200))

// change outlined white star to red with transparent background
let modOutlineImage = outlineImage.maskWithColor(color: UIColor.red)

// combine the images on a black background

Here is a full example, using your two original images (most of the code is setting up image views to show the results):
extension UIImage {

    func maskWithColor(color: UIColor) -> UIImage? {

        let maskingColors: [CGFloat] = [1, 255, 1, 255, 1, 255]
        let bounds = CGRect(origin: .zero, size: size)

        let maskImage = cgImage!
        var returnImage: UIImage?

        // make sure image has no alpha channel
        let rFormat = UIGraphicsImageRendererFormat()
        rFormat.opaque = true
        let renderer = UIGraphicsImageRenderer(size: size, format: rFormat)
        let noAlphaImage = renderer.image {
            (context) in
            self.draw(at: .zero)
        }

        let noAlphaCGRef = noAlphaImage.cgImage

        if let imgRefCopy = noAlphaCGRef?.copy(maskingColorComponents: maskingColors) {

            let rFormat = UIGraphicsImageRendererFormat()
            rFormat.opaque = false
            let renderer = UIGraphicsImageRenderer(size: size, format: rFormat)
            returnImage = renderer.image {
                (context) in
                context.cgContext.clip(to: bounds, mask: maskImage)
                context.cgContext.setFillColor(color.cgColor)
                context.cgContext.fill(bounds)
                context.cgContext.draw(imgRefCopy, in: bounds)
            }

        }
        return returnImage
    }

}

class MaskWorkViewController: UIViewController {

    let origFilledImgView: UIImageView = {
        let v = UIImageView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.contentMode = .center
        return v
    }()

    let origOutlineImgView: UIImageView = {
        let v = UIImageView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.contentMode = .center
        return v
    }()

    let modifiedFilledImgView: UIImageView = {
        let v = UIImageView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.contentMode = .center
        return v
    }()

    let modifiedOutlineImgView: UIImageView = {
        let v = UIImageView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.contentMode = .center
        return v
    }()

    let combinedImgView: UIImageView = {
        let v = UIImageView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.contentMode = .center
        return v
    }()

    let origStack: UIStackView = {
        let v = UIStackView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.axis = .horizontal
        v.spacing = 20
        return v
    }()

    let modifiedStack: UIStackView = {
        let v = UIStackView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.axis = .horizontal
        v.spacing = 20
        return v
    }()

    let mainStack: UIStackView = {
        let v = UIStackView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.axis = .vertical
        v.alignment = .center
        v.spacing = 10
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let filledImage = UIImage(named: "StarFill"),
            let outlineImage = UIImage(named: "StarEdge") else {
                return
        }

        var modifiedFilledImage: UIImage = UIImage()
        var modifiedOutlineImage: UIImage = UIImage()
        var combinedImage: UIImage = UIImage()

        // for both original images, replace white with color
        // and make black transparent
        if let modFilledImage = filledImage.maskWithColor(color: UIColor(red: 200, green: 200, blue: 200)),
            let modOutlineImage = outlineImage.maskWithColor(color: UIColor.red) {

            modifiedFilledImage = modFilledImage
            modifiedOutlineImage = modOutlineImage

            let rFormat = UIGraphicsImageRendererFormat()
            rFormat.opaque = true

            let renderer = UIGraphicsImageRenderer(size: modifiedFilledImage.size, format: rFormat)

            // combine modified images on black background
            combinedImage = renderer.image {
                (context) in
                context.cgContext.setFillColor(UIColor.black.cgColor)
                context.cgContext.fill(CGRect(origin: .zero, size: modifiedFilledImage.size))
                modifiedFilledImage.draw(at: .zero)
                modifiedOutlineImage.draw(at: .zero)
            }

        }

        // setup image views and set .image properties
        setupUI(filledImage.size)

        origFilledImgView.image = filledImage
        origOutlineImgView.image = outlineImage

        modifiedFilledImgView.image = modifiedFilledImage
        modifiedOutlineImgView.image = modifiedOutlineImage

        combinedImgView.image = combinedImage

    }

    func setupUI(_ imageSize: CGSize) -> Void {

        origStack.addArrangedSubview(origFilledImgView)
        origStack.addArrangedSubview(origOutlineImgView)

        modifiedStack.addArrangedSubview(modifiedFilledImgView)
        modifiedStack.addArrangedSubview(modifiedOutlineImgView)

        var lbl = UILabel()
        lbl.textAlignment = .center
        lbl.text = "Original Images"

        mainStack.addArrangedSubview(lbl)

        mainStack.addArrangedSubview(origStack)

        lbl = UILabel()
        lbl.textAlignment = .center
        lbl.numberOfLines = 0
        lbl.text = "Modified Images\n(UIImageViews have Green Background)"

        mainStack.addArrangedSubview(lbl)

        mainStack.addArrangedSubview(modifiedStack)

        lbl = UILabel()
        lbl.textAlignment = .center
        lbl.text = "Combined on Black Background"

        mainStack.addArrangedSubview(lbl)

        mainStack.addArrangedSubview(combinedImgView)

        view.addSubview(mainStack)

        NSLayoutConstraint.activate([

            mainStack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20.0),
            mainStack.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0),

        ])

        [origFilledImgView, origOutlineImgView, modifiedFilledImgView, modifiedOutlineImgView, combinedImgView].forEach {

            $0.backgroundColor = .green

            NSLayoutConstraint.activate([

                $0.widthAnchor.constraint(equalToConstant: imageSize.width),
                $0.heightAnchor.constraint(equalToConstant: imageSize.height),

            ])

        }

    }

}

And the result, showing the original, modified and final combined image... Image views have green backgrounds to show the transparent areas:

A: The idea is to bitwise-or the two masks together which "merges" the two masks. Since this new combined grayscale image is still a single (1-channel) image, we need to convert it to a 3-channel so we can apply color to the image. Finally, we color the outline mask with red to get our result

I implemented it in Python OpenCV but you can adapt the same idea with Swift
import cv2

# Read in images as grayscale
full = cv2.imread('1.png', 0)
outline = cv2.imread('2.png', 0)

# Bitwise-or masks
combine = cv2.bitwise_or(full, outline)

# Combine to 3 color channel and color outline red
combine = cv2.merge([combine, combine, combine])
combine[outline > 120] = (57,0,204)

cv2.imshow('combine', combine)
cv2.waitKey()

Benchmarks using IPython
In [3]: %timeit combine()
782 µs ± 10.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Using the Vectorized feature of Numpy, it seems to be pretty fast

A: try this:
public func maskWithColor2( color:UIColor) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
    let context = UIGraphicsGetCurrentContext()!

    color.setFill()

    context.translateBy(x: 0, y: self.size.height)
    context.scaleBy(x: 1.0, y: -1.0)

    let rect = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height)
    context.draw(self.cgImage!, in: rect)

    context.setBlendMode(CGBlendMode.sourceIn)
    context.addRect(rect)
    context.drawPath(using: CGPathDrawingMode.fill)

    let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return coloredImage!
}


text:
Q: Get highest column from worksheet phpexcel Hi I need to import data from excel. I'm using phpexcel library. When I'm trying to get the highest column using
$worksheet->getHighestColumn();

I always got AMK.But the actual value is O. Im trying with another method
getHighestDataColumn()

Unfortunately this will return 1. What is the solution? Im new to phpexcel
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
                $worksheetTitle     = $worksheet->getTitle();
                $highestRow         = $worksheet->getHighestRow();
                $highestColumn      = $worksheet->getHighestColumn();
                $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
                $nrColumns = ord($highestColumn) - 64;
}


text:
Q: How do I load a blurred images for product first then make it sharp using jquery I want my images are coming through 'blurred' on page load and only start to clear after maybe 1 or 2 seconds when they get progressively clearer until reaching the correct resolution.

A: Try this..
Fiddle is here http://jsfiddle.net/ws53byz6/
Suppose your image is something like below
<img src="https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" id="sampleImage" />

you should set the initial opacity value to less than 1 in our example it is 0.1
CSS
#sampleImage {
    -webkit-animation: sharp 5s; /* Chrome, Safari, Opera */
    animation: sharp 5s;
}

@-webkit-keyframes sharp {
    from {-webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);}
    to {-webkit-filter: none;
  -moz-filter: none;
  -o-filter: none;
  -ms-filter: none;
  filter: none;}
}

@keyframes sharp {
     from {-webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);}
    to {-webkit-filter: none;
  -moz-filter: none;
  -o-filter: none;
  -ms-filter: none;
  filter: none;}
}

no need of any javascript
let me if it is working


text:
Q: AP Calculus Homework Help Needed I am having another problem with basic math in my homework. Help is much appreciated.
The answer is: $\frac 1{\sqrt{4-x^2}}$
The problem is: Find $\frac {\mathrm{d}}{\mathrm dx} \sin^{-1} (x/2)$
What I have:
$\frac 1{\sqrt{1-(x/2)^2}} \cdot \frac12$
$\frac 1{\sqrt{4-x^2}} \cdot \frac 12$.
How do I move from what I have to the answer. Essentially, I don't know how to get rid of the 1/2. I typed in the answer in WolframAlpha and it gave me the answer. I clicked "Show Steps" and it showed my work until the last step putting a 2 in the denominator but not showing how to get rid of the two for the answer.
Thanks.

A: Just a bit of factoring:
$$\eqalign{
{1\over\sqrt{1-(x/2)^2}}\cdot{1\over 2} &={1\over\sqrt{1-{x^2\over4}}}\cdot{1\over 2} \cr
&={1\over\sqrt{{1\over 4}(4-{x^2})}}\cdot{1\over 2} \cr
&={1\over\sqrt{{1\over 4}}\sqrt{4-{x^2}}}\cdot{1\over 2} \cr
&={1\cdot {1\over 2}\over{1\over 2}{\sqrt{4-{x^2}}}} \cr
&={1\over {\sqrt{4-{x^2}}}}  .}
$$
The $1/2$'s cancelled in the last step.


text:
Q: How to open a doc and video file inside my react-native app without using any 3rd party software? I am building an app that can open any kind of document inside it like pdf, image, doc, video, and HTML without using any 3rd party software like VLC, google docs etc. I'm, able to open pdf and image file inside my app but could not find any solution for doc and video file.
Note:- All files are in base64 format.


text:
Q: Firebase Real Time Database Rule: allow in list uid to edit I try to allow write for a list of uid using, auth.uid in ['ciAujxIqXQSdaaaaaaaaaa', 'bbb'], but that's not the correct syntax, how can I do this?
{
     "rules": {
        "orders": {
            ".read": "auth != null",
            ".write":  "(data.child('uid').val() == auth.uid) || auth.uid in ['ciAujxIqXQSdaaaaaaaaaa', 'bbb']",
            ".indexOn": ["negative_epoch"]
        },
        "users": {
                ".read": "auth != null",
                ".write": "auth != null",
        },
     }

}

A: There is no in operation in the security rules language for the Realtime Database. So you'll have to do an or yourself:
"(data.child('uid').val() == auth.uid) || auth.uid == 'ciAujxIqXQSdaaaaaaaaaa' || auth.uid == 'bbb'"

I usually find that after adding 2 or 3 UIDs this way, I create a new top-level list in the database to hold these UID:
"admins": {
  "ciAujxIqXQSdaaaaaaaaaa": true,
  "bbb": true
}

And then check against that list in my rules:
"(data.child('uid').val() == auth.uid) || root.child('admins').child(auth.uid).exists()"


text:
Q: Convert &[u8] to String I have a byte array which I would like to return as std::string::String. The other answers and docs I found were converting Vectors to strings.
How would I convert a byte array &[u8] to a String?

A: It's working with std::str::from_utf8:
std::str::from_utf8(byte_array).unwrap().to_string();

Playground


text:
Q: Unexpected error "packet is too large", closing connection socketio flask After new update of python-engineio am receiving, "Unexpected error "packet is too large", closing connection socketio flask" in the python-engineio logs, when I try to send large amount of data.
It was working fine few days ago.
For server am using : flask_socketio
For client am using : python_socketio[client]
Any help is appreciated
Thanks

A: This is a security related change, to prevent DoS attacks. Set the max_http_buffer_size argument in your SocketIO constructor to your desired maximum size. The default is 1MB, same as the reference JavaScript implementation.


text:
Q: Flash - recording from user's webcam I've seen a few sites that have a flash app which takes video from the users webcam and manipulates it.  One example is the flash barcode reader http://www.renaun.com/flex2/BarcodeReader/BarcodeReader.html .
I want users to be able to submit 10-15 second clips which I can save to my server and then play back later via flash again.
Can you link to some example projects for this, or tell me what sections of which manuals I should be looking at?
-Adam

A: Try the Red5 RTMP server (Java) and Red5-Recorder for recording and playback. Demo here: http://www.red5-recorder.com/demo.php
(Both free)

A: There are several articles with sample code for this on adobes site. I would recommend you to go through this tutorial as it will guide you through all the necessary steps along with sample code:
http://www.adobe.com/devnet/flash/articles/webcam_motion.html

A: You can do it without any flash servers or Red5. Check on the net for some flash and action script books, because on the forums or google you can't find good tutorials about it.

A: What you need is Adobe Flash Media Interactive Server 3 . Just download it and take a look at "sample_guestbook" sample application.


text:
Q: What determines the number when excluding in Inclusion Exclusion problems My question might be a bit poorly articulated as I am not sure what I'm asking is actually called.
I am faced with an Exclusion/Inclusion problem that goes like this:
You have $25$ identical cakes that are distrubuted to $10$ children, every child must have atleast $1$ cake but no more than $4$.
After a bit of calculating you wind up with something like this:
$x_1 + x_2 +x_3 + x_4... + x_{10} = 15$ (removing the first argument of 1 cake each).
You wind up with your first number which in this case would be $(24,15)$. After that it seems that you remove 4 from this number $((20,11), (16,7)$ and finally $(12,3))$.
What I don't get is how you determine the number of which do exclude from here. My thought process would be that if each child gets 1 cake each, we then exclude the posibilites of children getting 3 more cakes, which would correspond with the argument of a lower bound of 1 and a highest bound of 4 cakes.
I hope this question makes sense and that someone out there can help me.
Thanks!


text:
Q: Close the current tab and go to parent Tab I want to create a link on a webpage that would close current active tab in a browser without closing other tabs in the browser. When user clicks close link, an alert message should appear asking user to confirm with two buttons, "YES" and "NO". If user clicks "YES", close that page and go to the parent tab and if press s no do nothing.?
It's kind of bad flow but i am searching for a solution.

A: try this:
this may close the current tab for you.

if (confirm("Close Window?")) {
    window.top.location.reload(true);
    window.top.close();
}else{
    // write down code the code that you want ot execute on clicking on " No ".
}

A: close the current tab and go to parent tab with reload
 window.opener.location.reload();
 window.top.close();


text:
Q: why I'm getting this error "Input 0 of layer "dense_30" is incompatible with the layer:expected min_ndim=2,found ndim=1. Full shape received: (None,)" Set random seed
print(np.__version__) tf.random.set_seed(42)

*

*Create a model using the Sequential Api
 model = tf.keras.Sequential([tf.keras.layers.Dense(1)])

*Compile the model
 model.compile(loss=tf.keras.losses.mae,# mae is short for mean absolute error
 optimizer = tf.keras.optimizers.SGD(), # sgd is short for stochastic gradient descent
 metrics=["mae"]

*Fit the model
 model.fit(X, y, epochs=5) // here the error

A: You need to add an input layer, ex:
model = tf.keras.Sequential([  tf.keras.layers.InputLayer(input_shape=(1,)),  tf.keras.layers.Dense(1) ])


text:
Q: Constructing a PHP array from separate files I am new to this but have tried to learn as much as I can before asking questions here. Unfortunately, it is unlikely that I have the vocabulary to ask a clear question. Apologies and thanks in advance.
Is it possible to build an array out of data from several files? Say I had a series of text files and the first line of each file was three tags, separated by commas, that I wanted to be stored in an array of all of the tags from all of the text files, how would I go about that?
For example my file might contain tags, the title of the page and its content:
social movements, handout, international

Haiti and the Politics of Resistance

Haiti, officially the Republic of Haiti, is a Caribbean country. It occupies the western, smaller portion of the island of Hispaniola, in the Greater Antillean archipelago, which it shares with the Dominican Republic. Ayiti (land of high mountains) was the indigenous Taíno or Amerindian name for the island. The country's highest point is Pic la Selle, at 2,680 metres (8,793 ft). The total area of Haiti is 27,750 square kilometres (10,714 sq mi) and its capital is Port-au-Prince. Haitian Creole and French are the official languages.

My desired outcome is a page containing all of the tags used in all of the text files that can each be clicked on to see list of all of the pages containing those tags.
Never mind, for now, that I want to remove duplicate tags. Do I need to read the first line of the first file, explode that line and then write those values to an array? And then do the same with the next file? I have attempted to do this with, firstly:
$content = file('mytextfilename.txt');
//First line: $content[0];
echo $content[0];

that I found here. Followed by stuff about explode that I found here.
$content = explode(",",$content);
print $content[0];

This did not work, probably obviously, but I am in no position to figure out why not. If I have not explained myself well then please ask so that I can attempt to clarify my question.
Thank you for your help, Adam.

A: You can try:
$tags = array_reduce(glob(__DIR__ . "/*.txt"), function ($a, $b) {
    $b = explode(",", (new SplFileObject($b, "r"))->fgets());
    return array_merge($a, $b);
}, array());

// To Remove Spaces
$tags = array_map("trim", $tags);

// To make it unique
$tags = array_unique($tags);

print_r($tags);

Since you are teething .. you can consider this version
$tags = array(); // Define tags
$files = glob(__DIR__ . "/*.txt"); // load all txt fules in current folder

foreach($files as $v) {
    $f = fopen($v, 'r'); // read file
    $line = fgets($f); // get first line
    $parts = explode(",", $line); // explode the tags
    $tags = array_merge($tags, $parts); // merge parts to tags
    fclose($f); // closr file
}

// To Remove Spaces
$tags = array_map("trim", $tags);

// To make it unique
$tags = array_unique($tags);

print_r($tags);


text:
Q: How to use both SELECT and INSERT query on single php prepared statement? I am trying to insert a record and get the id of that record using a prepared statement. For that, I write a query "INSERT INTO ". $natureFlight ."(typeFlight, dateTimeSubmit, emb, acType, reg, companyName, callSign, dateFlight) VALUES (?,?,?,?,?,?,?,?); SELECT LAST_INSERT_ID();" which works fine in MySQL console but doesn't work using a prepared statement. If I remove the SELECT LAST_INSERT_ID(); from the query then it can insert record using a prepared statement.
I search for the solution and I found this but does not work for me.
Here is a code
$natureFlight = $_POST['selectedNatureFlight'];
$typeFlight = $_POST['selectedTypeFlight'];
$dateTimeSubmit = $_POST['dateTime'];
$emb = $_POST['emb'];
$acType = $_POST['acType'];
$reg = $_POST['reg'];
$companyName = $_POST['companyName'];
$callSign = $_POST['callSign'];
$dateFlight = $_POST['dateFlight'];

$insertRecord = "INSERT INTO ". $natureFlight ."(`typeFlight`, `dateTimeSubmit`, `emb`, `acType`, `reg`, `companyName`, `callSign`, `dateFlight`) VALUES (?,?,?,?,?,?,?,?); SELECT LAST_INSERT_ID();";
$stmt = $conn->prepare($insertRecord);
$stmt->bind_param("ssssssss", $typeFlight, $dateTimeSubmit, $emb, $acType, $reg, $companyName, $callSign, $dateFlight);
if($stmt->execute()){
    $stmt->bind_result($id);
    while($stmt->fetch()) {
         echo $id;
        }
} else{
    $res['error'] = true;
    $res['message'] = $stmt->error;
}

After I run this I get an error
Fatal error: Uncaught Error: Call to a member function bind_param() on bool in
D:\xampp\htdocs\test\proc\flightPDF\src\body\user\records.php:40 Stack trace: #0 {main} thrown in
D:\xampp\htdocs\test\proc\flightPDF\src\body\user\records.php on line 40

Line 40 contain $stmt->bind_param("ssssssss", $typeFlight, $dateTimeSubmit, $emb, $acType, $reg, $companyName, $callSign, $dateFlight);

A: You can't prepare multiple statements. That is why your prepare is failing and $stmt is a boolean (false). To fix it, remove the SELECT LAST_INSERT_ID() from your INSERT query and change the code to this, using insert_id to get the last insert id:
$insertRecord = "INSERT INTO ". $natureFlight ."(`typeFlight`, `dateTimeSubmit`, `emb`, `acType`, `reg`, `companyName`, `callSign`, `dateFlight`) VALUES (?,?,?,?,?,?,?,?)";
$stmt = $conn->prepare($insertRecord);
$stmt->bind_param("ssssssss", $typeFlight, $dateTimeSubmit, $emb, $acType, $reg, $companyName, $callSign, $dateFlight);
if (!$stmt) {
    $res['error'] = true;
    $res['message'] = $conn->error;
}
elseif ($stmt->execute()) {
    echo $conn->insert_id;
}
else {
    $res['error'] = true;
    $res['message'] = $stmt->error;
}

A: Use lastInsertId Instead Of SELECT Statement
$last_id = $conn->lastInsertId;

Hope this will help you..!!


text:
Q: How to sort the items then sort again by another condition using SQL I'm using MySQL, and I want to sort a record or I want to group a record then sort it again by another condition like for example I have 6 items,
Names Group
Jack  G1
Dian  G2
Emily G2
Dean  G1
Teddy G2
Gabe  G1

So I want to sort this by group in alphabetized orby by name. Like,
Dean  G1
Gabe  G1
Jack  G1
Dian  G2
Emily G2
Teddy G2

So my problem is, how can I sort like this in MySQL?
Thanks.

A: So you want to order by one column first and then another? You can specify more than one column in the ORDER BY clause of a query - separate them by commas, and the first one will be the 'major' sort, then subsequent columns in the list will be sorted within that.

A: Select * from MyTable order by MyGroup, MyNames

A: Use two ORDER BYs.
ORDER BY Group ASC, Name ASC

A: select Names, Group
from MyTable
order by Group, Names

The order by list does not have to be in the same order as the select list columns.

A: SELECT Names, Group FROM 'table_name' ORDER BY Names DESC


text:
Q: Continuously 1-minute on / 1-minute off power setup Sorry for the strange title, I could not think of a better one.
I am working on a project, and basically what I need is a redstone torch that is one minute on, and the next minute off, and then a minute on again, and so one.
Ideally I want to have a switch that turns the whole thing off.
What would be the best way to go about this. Resources are no problem.

A: The simplest solution would likely be to make a Redstone Clock with enough Repeaters to have the clock cycle every minute. Repeaters can be set delays from 1 to 4 ticks, and each tick lasts 0.1 seconds, so you would need 150 Repeaters set to their full delay to last for one minute. Keep in mind that Redstone signals take 1 tick to propagate through Redstone Torches, so if timing is extremely important you will need to take this into account and adjust the timing of your Repeaters accordingly.
Alternatively, if you have enough space to create an area with no risk of entities obstructing the path, you could use a Minecart-based clock, with a detector rail connected to a T Flip-Flop as the output of the circuit. Minecarts travel at 8 metres per second at their top speed, so you would need a track 480 rails long to create a 1 minute delay (assuming the Minecart is moving at its top speed the entire time). This doesn't take into account the fact that Minecarts move faster along diagonals, so the Minecart would technically be traveling at 11.314m/s at any corners in the track. If the timing of the circuit is important, this will make the timer inaccurate after many loops of the clock. Also, this design would add complexity if you needed to be able to start and stop the timer.

A: There are a number of clock types you can use that will let you get longer periods without using many repeaters. Each type has its pros and cons. Here is a list, with desctions: http://www.minecraftwiki.net/wiki/Redstone_Circuits#Clock_generators
In particular, I have seen Piston Clocks used to generate very slow pulses, for things like monster traps. You can adjust the number of blocks being moved to change the pulse rate.

A: First you create a one minute timer using repeaters or some other method like Kevin said, then you attach one point in the clock to a T-flip flop so it alternates the output every cycle of the clock.
Alternatively you could set up a two minute timer, and connect one point to the Set input of a RS-NOR latch and another point to the Reset of the latch, this would be useful if you want the output to be on for a different amount of time (such as 1:30 on, 0:30 off)


text:
Q: System.DirectoryServices.Protocols.SearchRequest Ldap Query Execution Issue I am using DirectorySearcher class to query the active directory. It gives all the records in a single page (more than 5000). I want to get 100 records per page. So I moved to SearchRequest class. Using SearchRequest class I can get 100 records per page. But for particular query it is not working. I want to get all the users with their "samaccountname or displayname starts with 'a'" works fine. Then I want to get all the users with their "samaccountname and displayname starts with 'a'", this it is not working. I can guess the reason, some of the users starts their samaccountname with a not having any displayname. Any workaround for this issue? Please guide me
Please refer the following code
        //This query works fine
        //string filter = "(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(|(samaccountname=a*)(displayname=a*)))";

        /* Not works */
        string filter = "(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(&(samaccountname=a*)(displayname=a*)))";
        LdapConnection connection = new LdapConnection(serverName);
        string[] attribs = { "samaccountname", "displayname" };

        // create a SearchRequest object
        SearchRequest searchRequest = new SearchRequest
                                                (scope,
                                                 filter,
                                                 System.DirectoryServices.Protocols.SearchScope.Subtree,
                                                 attribs);

        SortRequestControl sortRequest = new SortRequestControl("samaccountname", false);
        searchRequest.Controls.Add(sortRequest);

        VlvRequestControl vlvRequest =
            new VlvRequestControl(0, numEntries, offsetVal);
        searchRequest.Controls.Add(vlvRequest);

        SearchResponse searchResponse =
            (SearchResponse)connection.SendRequest(searchRequest);

        if (searchResponse.Controls.Length != 2 ||
            !(searchResponse.Controls[0] is SortResponseControl))
        {
            Console.WriteLine("The server does not support VLV");
            return null;
        }

A: Do you really want displayName in Active Directory?  Perhaps fullName or CN would be a more accurate choice.


text:
Q: How to define/use endpoints to connect to Kubernetes from Javascript I have a doubt regarding how to structure my dockerized stack, simplified in two containers to get help here:

*

*static: NGINX serving static resources (JS/HTML).

*rest: express.js backend for the REST Api.

Without Kubernetes, just docker-compose on a node, rest is simply listening on a different port and, from Javascript, the requests go to same_host:rest_port, no problem here.
With Kubernetes, I understand that I need to use the service name from Kubernetes, something like "rest" (to make transparent the service itself), but that name would only be visible from the docker container serving the static resources.
My question: do I need to forward traffic from NGINX to the REST Api? Does Kubernetes expose a public service name usable from Javascript, for example?
Thank you.

A:
With Kubernetes, I understand that I need to use the service name from
  Kubernetes, something like "rest" (to make transparent the service
  itself), but that name would only be visible from the docker container
  serving the static resources.

Your understanding is correct. As long as you have a kube-dns add-on running in your cluster, your service name as Domain name is resolvable with in the same kubernetes cluster and namespace. In other words, as you said, "rest" will work only with in the kubernetes cluster.

My question: do I need to forward traffic from NGINX to the REST Api?
  Does Kubernetes expose a public service name usable from Javascript,
  for example?

This is one way to achieve this.
Advantage of this approach is, you will avoid all the Same Origin Policy/CORS headaches, your microservice (express) authentication details will be abstracted out from user's browser. (This is not necessarily an advantage).
Disadvantage of this approach is, your backend microservice (express) will have a tight coupling with front end (or vice-versa depending on how you look at it), This will make the scaling of backend dependent on front end. Your Backend is not exposed. So, if you have another consumer (let's just say an android app) it will not be able to access your service.
Another Solution
Create an ingress (and use an ingress controller in your cluster) and expose your Microservice(Express).


text:
Q: XPages: Opening a dropdown using "onclick " event of xpages link I am trying to call the popupMenu from a link within a datatable using the following clientSide code
 XSP.openMenu(thisEvent,'{javascript:getComponent("popupMenuNew").getMenuCtor()}');

but when ever i click on the link it just take me to the top of thesame pages, i notice it does not recognise the cleintside code as a link.
Its there any other way i could call the popupMenu from XPages link?
The link is in a data table with some boostrap table attribute:
   <xp:this.attrs>
        <xp:attr name="data-toggle" value="table"></xp:attr>
        <xp:attr name="data-show-columns" value="true"></xp:attr>
        <xp:attr name="data-mobile-responsive" value="true"></xp:attr>
        <xp:attr name="data-check-on-init" value="true"></xp:attr>
   </xp:this.attrs>

the complete link code:
<xp:link escape="true" id="link1"
                    title="Create Document">
                    Neu
    <xp:this.rendered><![CDATA[#{javascript:if (rowDataEntry.isDocument()){
return true;
}
else{
return false;
}}]]></xp:this.rendered>
    <xp:image id="image4" url="/actExpand.gif"></xp:image>
    <xp:eventHandler event="onclick" submit="false"
                        id="eventHandler2">
        <xp:this.script><![CDATA[var url = XSP.openMenu(thisEvent,'#{javascript:getComponent("popupMenuNew").getMenuCtor()}');
    var l = window.location;
    if (url != l) {
        window.location.replace(url);
    }

]]></xp:this.script>
    </xp:eventHandler>
</xp:link>

A: XSP.openMenu() does not require a reload of the page so try this instead:
<xp:link escape="true" id="link1" title="Create Document">
    Neu
    <xp:this.rendered>
        <![CDATA[#{javascript:
            if (rowDataEntry.isDocument()){
                return true;
            } else {
                return false;
            }
        }]]>
    </xp:this.rendered>
    <xp:image id="image4" url="/actExpand.gif"></xp:image>
    <xp:eventHandler event="onclick" submit="false" id="eventHandler2">
        <xp:this.script>
            <![CDATA[XSP.openMenu(thisEvent,'#{javascript:getComponent("popupMenuNew").getMenuCtor()}');]]>
        </xp:this.script>
    </xp:eventHandler>
</xp:link>


text:
Q: Error: Lost connection to MySQL en Servidor Tengo un problema con una consulta a mysql en php, estoy intentando ejecutar una consulta desde php a mysql en mi servidor, es una consulta simple, es un "DELETE FROM temp_sku", estoy intentando ejecutar esta consulta con un procedimiento almacenado pero me da el siguiente error:

Uncaught PDOException: SQLSTATE[HY000]: General error: 2013 Lost
connection to MySQL server during query

Entiendo que este error es como si se superara el tiempo de conexión o algo similar, el problema es que este DELETE realmente no pesa nada solo es una tabla con una sola columna que almacena sku's por lo cual no pesa en absoluto.
Mi conexión la creo de la siguiente forma:
try{
            $connect = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USERNAME, DB_PASSWORD,
            array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
            $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e){
            $error = $e->getMessage();
            exit("Error: " . $e->getMessage());
        }

he intentado cambiar mi consulta y no usar un procedimiento almacenado, la he cambiado a esta forma:
$stmt = $connect->prepare("DELETE FROM temp_sku");
$stmt->execute();

Pero sigo recibiendo el mismo error. No entiendo que puedo estar haciendo mal.


text:
Q: How to stop refresh Google maps? aspx :code:
        <asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick">
        </asp:Timer>
        <div id="map">
        <cc1:GMap ID="GMap1" runat="server" />
        </div>
    C# cod:
    protected void Timer1_Tick(object sender, EventArgs e)
    {
     GMap1.resetMarkers();
     Subgurim.Controles.GLatLng gLatLng = new  Subgurim.Controles.GLatLng(Convert.ToDouble(status.Rows[0][0]), Convert.ToDouble(status.Rows[0][1]));
     GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal);
     Subgurim.Controles.GMarker oMarker = new Subgurim.Controles.GMarker(gLatLng);
     GMap1.addGMarker(oMarker);
  }

for every 40 sec GMap getting refreshing here. i want without GMap refresh i set new lat and lang on GMap. how can i set this new points or markers on Gmap

A: Disconnect your computer from the internet
Sorry mate, had to do it :D:D:D

A: // Enable the visual refresh
google.maps.visualRefresh = true;

var map;
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);


text:
Q: How to import an SVG logo in Android Studio I designed a logo on Adobe Illustrator. After exporting it as SVG
I tried to create an XML file using Android Studio to use but Android Studio says that this file can't be used.
Should I use specific options like using RGB colors only or what?
Thanks

A: You need to import the  svg file by following this steps :

*

*In the project Right click on the drawable directory

*Go to New ⇒ Vector Asset

*Click on the radio button saying "Local File (SVG, PSD)"

*Click on the browse icon and navigate to your SVG or PSD file to select it

*Finally click Next ⇒ Finish.

then you will see the  code generated from svg in the drawable directory


text:
Q: Get the same result with ResizeObserver and media query I have globally defined breakpoints:
breakpoints: {
  xs: "0px",
  sm: "320px",
  md: "672px",
  lg: "1056px",
  xl: "1312px",
},

I also have media queries to define the padding-top and padding-bottom, based on previous breakpoints:
@media (min-width: 672px) {
    padding-top: 2rem;
    padding-bottom: 2rem;
}
@media (min-width: 0px) {
    padding-top: 1rem;
    padding-bottom: 1rem;
}

And finally, I am using ResizeObserver to observer document.body and set the paddingLeft, for example:
const observer = new ResizeObserver(([entry]) => {
  if (entry.contentRect.width >= Number.parseInt(breakpoints.xl)) {
    document.body.style.paddingLeft = "10em"
  } else if (entry.contentRect.width >= Number.parseInt(breakpoints.lg)) {
    document.body.style.paddingLeft = "10em"
  } else if (entry.contentRect.width >= Number.parseInt(breakpoints.md)) {
    document.body.style.paddingLeft = "10em"
  } else if (entry.contentRect.width >= Number.parseInt(breakpoints.xs)) {
    document.body.style.paddingLeft = "5em"
  }
})

observer.observe(document.body)

The trouble is that the padding-top or padding-bottom (media queries) don't change at same time that the paddingLeft (ResizeObserver) and I don't know why and how to solve.
--- EDITED ---
I hope it is better understood now:
Please see jsfiddle and resize the result to see how the div change the padding-top and the paddingLeft at a different time.

A: The contentRect is the element's content box, without paddings, border, and margins. Due to the body elements's default margin: 8px; and scrollbar width, the entry.contentRect.width will be 33px less than the window width.
16px (body margin) + 17px (scollbar width) = 33px

References
https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentRect
https://xebia.com/blog/resize-observer-api-detecting-element-size-change/
Alternatively, you can use MediaQueryList.onchange

A MediaQueryList object stores information on a media query applied to
a document, with support for both immediate and event-driven matching
against the state of the document.

Example with one breakpoint
const element = document.getElementById("test");

var mql = window.matchMedia('(min-width: 672px)');

mql.addEventListener("change", (e) => {
  if (e.matches) {
    element.style.paddingLeft = "10em"
  } else {
    element.style.paddingLeft = "unset"
  }
})

Demo


text:
Q: AWS codedeploy blue green deployment I have setup code pipeline for end to end automatic  deployment of revision on EC2 instances using cloudformation template, the deployment group is of type blue/green for codedploy.
But I dont understand how to keep the code deployment group in sync with newly created auto scaling group (green).
Do I have to create new lambda invoke action in pipeline after successful deployment to update the newly created auto scaling group name.

A: Unfortunately, CloudFormation does not support Blue/Green deployments for EC2 platform:

For blue/green deployments, AWS CloudFormation supports deployments on Lambda compute platforms only.

Support for ECS is very new.
To create deployment group for blue/green for EC2 platform you would have to create a custom resource in CloudFormation .
The custom resource would be based on a lambda function, and in that lambda function you would use create_deployment_group to define blue/green details for your EC2 instances. As part of this process, you will have an option to choose how to deal with AutoScaling group, e.g.
        "greenFleetProvisioningOption": {
             "action": "COPY_AUTO_SCALING_GROUP"
        }

For creation of custom resource, crhelper by AWS is very useful.
Hope this helps and hope Blue/Green for EC2 will be supported by CloudFormation soon.


text:
Q: Factoring a natural transformation through a functor This seems fairly similar to density. Suppose I have three categories $A,B,C$, and a functor $L: B \to C$ so that every natural transformation $f: L.F \Rightarrow L.G$, for a parallel pair $F,G: A \to B$ belonging to some class of functors $\mathcal{F}$, factors as a natural transformation $g:F \Rightarrow G$ so that $L.g = f$. This feels like a thing that would come up in 2-category theory, but I'm struggling to find a good reference.
Here is a diagram using the quiver app


text:
Q: Counting inner joined query I have two tables one with 'Avatars' and one with 'Children' the children table holds values of parent avatar ID and of child avatar ID. I'm trying to get from the table a list of avatars that have more than 2 children.
Tables:
CREATE TABLE avatars
    (avatarID NUMBER CONSTRAINT pk_avatars PRIMARY KEY,
    username VARCHAR2(20),
    gender CHAR(1),
    );

CREATE TABLE children
    (childID NUMBER CONSTRAINT pk_children PRIMARY KEY,
    childAvatarID NUMBER,
    parentAvatarID NUMBER,
    mainParent NUMBER(1,0)
    );

Relationships:
ALTER TABLE children
ADD FOREIGN KEY (parentAvatarID)
REFERENCES avatars(avatarID)
ON DELETE CASCADE;

ALTER TABLE children
ADD FOREIGN KEY (childAvatarID)
REFERENCES avatars(avatarID)
ON DELETE CASCADE;

My query:
SELECT count(children.avatarid), avatars.username
FROM avatars
INNER JOIN (
  SELECT *
  FROM avatars
  INNER JOIN children ON avatars.avatarID = children.childAvatarID
  WHERE avatars.gender = 'M'
) children ON avatars.avatarID = children.parentavatarID
WHERE avatars.gender = 'M'
GROUP By children.avatarid, avatars.username;

It shows for count(children.avatarid) always 1 no matter how many children an avatar has.

A: You are grouping by children.avatarid, avatars.username, try just grouping by avatars.username.
SELECT count(children.avatarid), avatars.username
FROM avatars
INNER JOIN (
  SELECT *
  FROM avatars
  INNER JOIN children ON avatars.avatarID = children.childAvatarID
  WHERE avatars.gender = 'M'
) children ON avatars.avatarID = children.parentavatarID
WHERE avatars.gender = 'M'
GROUP By avatars.username;

A:
list of avatars that have more than 2 children

Try this:
select a.*,
    c.child_count
from avatars a
join (
    select parentAvatarId,
        count(*) as child_count
    from children c
    join avatars a on a.avatarId = c.childAvatarId
    where a.gender = 'M'
    group by parentAvatarId
    having count(*) > 2
    ) c on a.avatarId = c.parentAvatarId
where a.gender = 'M'

A: select avatars.avatarID, count(children.childID) as numberOfChildren
from avatars
join children on children.parentAvatarID = avatars.avatarID
group by children.parentAvatarID
having numberOfChildren >= 2;