diff --git "a/test_data_with_all_columns.csv" "b/test_data_with_all_columns.csv" new file mode 100644--- /dev/null +++ "b/test_data_with_all_columns.csv" @@ -0,0 +1,53818 @@ +after_merge,before_merge,source code and errors,full_traceback,traceback_type +"def cmdb_get_mainline_object_topo(request, bk_biz_id, bk_supplier_account=''): + """""" + @summary: 获取配置平台业务拓扑模型 + @param request: + @param bk_biz_id: + @param bk_supplier_account: + @return: + """""" + kwargs = { + 'bk_biz_id': bk_biz_id, + 'bk_supplier_account': bk_supplier_account, + } + client = get_client_by_user(request.user.username) + cc_result = client.cc.get_mainline_object_topo(kwargs) + if not cc_result['result']: + message = handle_api_error(_(u""配置平台(CMDB)""), + 'cc.get_mainline_object_topo', + kwargs, + cc_result['message']) + return {'result': cc_result['result'], 'code': cc_result['code'], 'message': message} + data = cc_result['data'] + for bk_obj in data: + if bk_obj['bk_obj_id'] == 'host': + bk_obj['bk_obj_name'] = 'IP' + result = {'result': cc_result['result'], 'code': cc_result['code'], 'data': cc_result['data']} + return JsonResponse(result)","def cmdb_get_mainline_object_topo(request, bk_biz_id, bk_supplier_account=''): + """""" + @summary: 获取配置平台业务拓扑模型 + @param request: + @param bk_biz_id: + @param bk_supplier_account: + @return: + """""" + kwargs = { + 'bk_biz_id': bk_biz_id, + 'bk_supplier_account': bk_supplier_account, + } + client = get_client_by_request(request) + cc_result = client.cc.get_mainline_object_topo(kwargs) + if not cc_result['result']: + message = handle_api_error(_(u""配置平台(CMDB)""), + 'cc.get_mainline_object_topo', + kwargs, + cc_result['message']) + return {'result': cc_result['result'], 'code': cc_result['code'], 'message': message} + data = cc_result['data'] + for bk_obj in data: + if bk_obj['bk_obj_id'] == 'host': + bk_obj['bk_obj_name'] = 'IP' + result = {'result': cc_result['result'], 'code': cc_result['code'], 'data': cc_result['data']} + return JsonResponse(result)","[{'piece_type': 'error message', 'piece_content': '------STARTING: Migrate Database------\\nTraceback (most recent call last):\\nFile ""manage.py"", line 27, in \\nexecute_from_command_line(sys.argv)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line\\nutility.execute()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute\\ndjango.setup()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup\\napps.populate(settings.INSTALLED_APPS)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate\\napp_config = AppConfig.create(entry)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create\\nmod = import_module(mod_path)\\nFile ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module\\n__import__(name)\\nFile ""/data/app/code/pipeline/apps.py"", line 18, in \\nfrom rediscluster import StrictRedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in \\nfrom .client import StrictRedisCluster, RedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in \\nfrom .connection import (\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in \\nfrom .nodemanager import NodeManager\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in \\nfrom redis._compat import b, unicode, bytes, long, basestring\\nImportError: cannot import name b\\n------FAILURE: Migrate Database------'}]","------STARTING: Migrate Database------ +Traceback (most recent call last): +File ""manage.py"", line 27, in +execute_from_command_line(sys.argv) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line +utility.execute() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute +django.setup() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup +apps.populate(settings.INSTALLED_APPS) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate +app_config = AppConfig.create(entry) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create +mod = import_module(mod_path) +File ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module +__import__(name) +File ""/data/app/code/pipeline/apps.py"", line 18, in +from rediscluster import StrictRedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in +from .client import StrictRedisCluster, RedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in +from .connection import ( +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in +from .nodemanager import NodeManager +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in +from redis._compat import b, unicode, bytes, long, basestring +ImportError: cannot import name b +------FAILURE: Migrate Database------",ImportError +"def cc_search_object_attribute(request, obj_id, biz_cc_id, supplier_account): + """""" + @summary: 获取对象自定义属性 + @param request: + @param biz_cc_id: + @return: + """""" + client = get_client_by_user(request.user.username) + kwargs = { + 'bk_obj_id': obj_id, + 'bk_supplier_account': supplier_account + } + cc_result = client.cc.search_object_attribute(kwargs) + if not cc_result['result']: + message = handle_api_error('cc', 'cc.search_object_attribute', kwargs, cc_result['message']) + logger.error(message) + result = { + 'result': False, + 'data': [], + 'message': message + } + return JsonResponse(result) + + obj_property = [] + for item in cc_result['data']: + if item['editable']: + obj_property.append({ + 'value': item['bk_property_id'], + 'text': item['bk_property_name'] + }) + + return JsonResponse({'result': True, 'data': obj_property})","def cc_search_object_attribute(request, obj_id, biz_cc_id, supplier_account): + """""" + @summary: 获取对象自定义属性 + @param request: + @param biz_cc_id: + @return: + """""" + client = get_client_by_request(request) + kwargs = { + 'bk_obj_id': obj_id, + 'bk_supplier_account': supplier_account + } + cc_result = client.cc.search_object_attribute(kwargs) + if not cc_result['result']: + message = handle_api_error('cc', 'cc.search_object_attribute', kwargs, cc_result['message']) + logger.error(message) + result = { + 'result': False, + 'data': [], + 'message': message + } + return JsonResponse(result) + + obj_property = [] + for item in cc_result['data']: + if item['editable']: + obj_property.append({ + 'value': item['bk_property_id'], + 'text': item['bk_property_name'] + }) + + return JsonResponse({'result': True, 'data': obj_property})","[{'piece_type': 'error message', 'piece_content': '------STARTING: Migrate Database------\\nTraceback (most recent call last):\\nFile ""manage.py"", line 27, in \\nexecute_from_command_line(sys.argv)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line\\nutility.execute()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute\\ndjango.setup()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup\\napps.populate(settings.INSTALLED_APPS)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate\\napp_config = AppConfig.create(entry)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create\\nmod = import_module(mod_path)\\nFile ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module\\n__import__(name)\\nFile ""/data/app/code/pipeline/apps.py"", line 18, in \\nfrom rediscluster import StrictRedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in \\nfrom .client import StrictRedisCluster, RedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in \\nfrom .connection import (\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in \\nfrom .nodemanager import NodeManager\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in \\nfrom redis._compat import b, unicode, bytes, long, basestring\\nImportError: cannot import name b\\n------FAILURE: Migrate Database------'}]","------STARTING: Migrate Database------ +Traceback (most recent call last): +File ""manage.py"", line 27, in +execute_from_command_line(sys.argv) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line +utility.execute() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute +django.setup() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup +apps.populate(settings.INSTALLED_APPS) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate +app_config = AppConfig.create(entry) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create +mod = import_module(mod_path) +File ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module +__import__(name) +File ""/data/app/code/pipeline/apps.py"", line 18, in +from rediscluster import StrictRedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in +from .client import StrictRedisCluster, RedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in +from .connection import ( +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in +from .nodemanager import NodeManager +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in +from redis._compat import b, unicode, bytes, long, basestring +ImportError: cannot import name b +------FAILURE: Migrate Database------",ImportError +"def cc_search_create_object_attribute(request, obj_id, biz_cc_id, supplier_account): + client = get_client_by_user(request.user.username) + kwargs = { + 'bk_obj_id': obj_id, + 'bk_supplier_account': supplier_account + } + cc_result = client.cc.search_object_attribute(kwargs) + if not cc_result['result']: + message = handle_api_error('cc', 'cc.search_object_attribute', kwargs, cc_result['message']) + logger.error(message) + result = { + 'result': False, + 'data': [], + 'message': message + } + return JsonResponse(result) + + obj_property = [] + for item in cc_result['data']: + if item['editable']: + prop_dict = { + 'tag_code': item['bk_property_id'], + 'type': ""input"", + 'attrs': { + 'name': item['bk_property_name'], + 'editable': 'true', + }, + } + if item['bk_property_id'] in ['bk_set_name']: + prop_dict[""attrs""][""validation""] = [ + { + ""type"": ""required"" + } + ] + obj_property.append(prop_dict) + + return JsonResponse({'result': True, 'data': obj_property})","def cc_search_create_object_attribute(request, obj_id, biz_cc_id, supplier_account): + client = get_client_by_request(request) + kwargs = { + 'bk_obj_id': obj_id, + 'bk_supplier_account': supplier_account + } + cc_result = client.cc.search_object_attribute(kwargs) + if not cc_result['result']: + message = handle_api_error('cc', 'cc.search_object_attribute', kwargs, cc_result['message']) + logger.error(message) + result = { + 'result': False, + 'data': [], + 'message': message + } + return JsonResponse(result) + + obj_property = [] + for item in cc_result['data']: + if item['editable']: + prop_dict = { + 'tag_code': item['bk_property_id'], + 'type': ""input"", + 'attrs': { + 'name': item['bk_property_name'], + 'editable': 'true', + }, + } + if item['bk_property_id'] in ['bk_set_name']: + prop_dict[""attrs""][""validation""] = [ + { + ""type"": ""required"" + } + ] + obj_property.append(prop_dict) + + return JsonResponse({'result': True, 'data': obj_property})","[{'piece_type': 'error message', 'piece_content': '------STARTING: Migrate Database------\\nTraceback (most recent call last):\\nFile ""manage.py"", line 27, in \\nexecute_from_command_line(sys.argv)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line\\nutility.execute()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute\\ndjango.setup()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup\\napps.populate(settings.INSTALLED_APPS)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate\\napp_config = AppConfig.create(entry)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create\\nmod = import_module(mod_path)\\nFile ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module\\n__import__(name)\\nFile ""/data/app/code/pipeline/apps.py"", line 18, in \\nfrom rediscluster import StrictRedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in \\nfrom .client import StrictRedisCluster, RedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in \\nfrom .connection import (\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in \\nfrom .nodemanager import NodeManager\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in \\nfrom redis._compat import b, unicode, bytes, long, basestring\\nImportError: cannot import name b\\n------FAILURE: Migrate Database------'}]","------STARTING: Migrate Database------ +Traceback (most recent call last): +File ""manage.py"", line 27, in +execute_from_command_line(sys.argv) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line +utility.execute() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute +django.setup() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup +apps.populate(settings.INSTALLED_APPS) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate +app_config = AppConfig.create(entry) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create +mod = import_module(mod_path) +File ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module +__import__(name) +File ""/data/app/code/pipeline/apps.py"", line 18, in +from rediscluster import StrictRedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in +from .client import StrictRedisCluster, RedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in +from .connection import ( +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in +from .nodemanager import NodeManager +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in +from redis._compat import b, unicode, bytes, long, basestring +ImportError: cannot import name b +------FAILURE: Migrate Database------",ImportError +"def cc_search_topo(request, obj_id, category, biz_cc_id, supplier_account): + """""" + @summary: 查询对象拓扑 + @param request: + @param biz_cc_id: + @return: + """""" + client = get_client_by_user(request.user.username) + kwargs = { + 'bk_biz_id': biz_cc_id, + 'bk_supplier_account': supplier_account + } + cc_result = client.cc.search_biz_inst_topo(kwargs) + if not cc_result['result']: + message = handle_api_error('cc', 'cc.search_biz_inst_topo', kwargs, cc_result['message']) + logger.error(message) + result = { + 'result': False, + 'data': [], + 'message': message + } + return JsonResponse(result) + + if category in [""normal"", ""prev"", ""picker""]: + cc_topo = cc_format_topo_data(cc_result['data'], obj_id, category) + else: + cc_topo = [] + + return JsonResponse({'result': True, 'data': cc_topo})","def cc_search_topo(request, obj_id, category, biz_cc_id, supplier_account): + """""" + @summary: 查询对象拓扑 + @param request: + @param biz_cc_id: + @return: + """""" + client = get_client_by_request(request) + kwargs = { + 'bk_biz_id': biz_cc_id, + 'bk_supplier_account': supplier_account + } + cc_result = client.cc.search_biz_inst_topo(kwargs) + if not cc_result['result']: + message = handle_api_error('cc', 'cc.search_biz_inst_topo', kwargs, cc_result['message']) + logger.error(message) + result = { + 'result': False, + 'data': [], + 'message': message + } + return JsonResponse(result) + + if category in [""normal"", ""prev"", ""picker""]: + cc_topo = cc_format_topo_data(cc_result['data'], obj_id, category) + else: + cc_topo = [] + + return JsonResponse({'result': True, 'data': cc_topo})","[{'piece_type': 'error message', 'piece_content': '------STARTING: Migrate Database------\\nTraceback (most recent call last):\\nFile ""manage.py"", line 27, in \\nexecute_from_command_line(sys.argv)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line\\nutility.execute()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute\\ndjango.setup()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup\\napps.populate(settings.INSTALLED_APPS)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate\\napp_config = AppConfig.create(entry)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create\\nmod = import_module(mod_path)\\nFile ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module\\n__import__(name)\\nFile ""/data/app/code/pipeline/apps.py"", line 18, in \\nfrom rediscluster import StrictRedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in \\nfrom .client import StrictRedisCluster, RedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in \\nfrom .connection import (\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in \\nfrom .nodemanager import NodeManager\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in \\nfrom redis._compat import b, unicode, bytes, long, basestring\\nImportError: cannot import name b\\n------FAILURE: Migrate Database------'}]","------STARTING: Migrate Database------ +Traceback (most recent call last): +File ""manage.py"", line 27, in +execute_from_command_line(sys.argv) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line +utility.execute() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute +django.setup() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup +apps.populate(settings.INSTALLED_APPS) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate +app_config = AppConfig.create(entry) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create +mod = import_module(mod_path) +File ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module +__import__(name) +File ""/data/app/code/pipeline/apps.py"", line 18, in +from rediscluster import StrictRedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in +from .client import StrictRedisCluster, RedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in +from .connection import ( +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in +from .nodemanager import NodeManager +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in +from redis._compat import b, unicode, bytes, long, basestring +ImportError: cannot import name b +------FAILURE: Migrate Database------",ImportError +"def job_get_script_list(request, biz_cc_id): + """""" + 查询业务脚本列表 + :param request: + :param biz_cc_id: + :return: + """""" + # 查询脚本列表 + client = get_client_by_user(request.user.username) + script_type = request.GET.get('type') + kwargs = { + 'bk_biz_id': biz_cc_id, + 'is_public': True if script_type == 'public' else False + } + script_result = client.job.get_script_list(kwargs) + + if not script_result['result']: + message = handle_api_error('cc', 'job.get_script_list', kwargs, script_result['message']) + logger.error(message) + result = { + 'result': False, + 'message': message + } + return JsonResponse(result) + + script_dict = {} + for script in script_result['data']['data']: + script_dict.setdefault(script['name'], []).append(script['id']) + + version_data = [] + for name, version in script_dict.items(): + version_data.append({ + ""text"": name, + ""value"": max(version) + }) + + return JsonResponse({'result': True, 'data': version_data})","def job_get_script_list(request, biz_cc_id): + """""" + 查询业务脚本列表 + :param request: + :param biz_cc_id: + :return: + """""" + # 查询脚本列表 + client = get_client_by_request(request) + script_type = request.GET.get('type') + kwargs = { + 'bk_biz_id': biz_cc_id, + 'is_public': True if script_type == 'public' else False + } + script_result = client.job.get_script_list(kwargs) + + if not script_result['result']: + message = handle_api_error('cc', 'job.get_script_list', kwargs, script_result['message']) + logger.error(message) + result = { + 'result': False, + 'message': message + } + return JsonResponse(result) + + script_dict = {} + for script in script_result['data']['data']: + script_dict.setdefault(script['name'], []).append(script['id']) + + version_data = [] + for name, version in script_dict.items(): + version_data.append({ + ""text"": name, + ""value"": max(version) + }) + + return JsonResponse({'result': True, 'data': version_data})","[{'piece_type': 'error message', 'piece_content': '------STARTING: Migrate Database------\\nTraceback (most recent call last):\\nFile ""manage.py"", line 27, in \\nexecute_from_command_line(sys.argv)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line\\nutility.execute()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute\\ndjango.setup()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup\\napps.populate(settings.INSTALLED_APPS)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate\\napp_config = AppConfig.create(entry)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create\\nmod = import_module(mod_path)\\nFile ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module\\n__import__(name)\\nFile ""/data/app/code/pipeline/apps.py"", line 18, in \\nfrom rediscluster import StrictRedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in \\nfrom .client import StrictRedisCluster, RedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in \\nfrom .connection import (\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in \\nfrom .nodemanager import NodeManager\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in \\nfrom redis._compat import b, unicode, bytes, long, basestring\\nImportError: cannot import name b\\n------FAILURE: Migrate Database------'}]","------STARTING: Migrate Database------ +Traceback (most recent call last): +File ""manage.py"", line 27, in +execute_from_command_line(sys.argv) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line +utility.execute() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute +django.setup() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup +apps.populate(settings.INSTALLED_APPS) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate +app_config = AppConfig.create(entry) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create +mod = import_module(mod_path) +File ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module +__import__(name) +File ""/data/app/code/pipeline/apps.py"", line 18, in +from rediscluster import StrictRedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in +from .client import StrictRedisCluster, RedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in +from .connection import ( +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in +from .nodemanager import NodeManager +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in +from redis._compat import b, unicode, bytes, long, basestring +ImportError: cannot import name b +------FAILURE: Migrate Database------",ImportError +"def job_get_job_tasks_by_biz(request, biz_cc_id): + client = get_client_by_user(request.user.username) + job_result = client.job.get_job_list({'bk_biz_id': biz_cc_id}) + if not job_result['result']: + message = _(u""查询作业平台(JOB)的作业模板[app_id=%s]接口job.get_task返回失败: %s"") % ( + biz_cc_id, job_result['message']) + logger.error(message) + result = { + 'result': False, + 'data': [], + 'message': message + } + return JsonResponse(result) + task_list = [] + for task in job_result['data']: + task_list.append({ + 'value': task['bk_job_id'], + 'text': task['name'], + }) + return JsonResponse({'result': True, 'data': task_list})","def job_get_job_tasks_by_biz(request, biz_cc_id): + client = get_client_by_request(request) + job_result = client.job.get_job_list({'bk_biz_id': biz_cc_id}) + if not job_result['result']: + message = _(u""查询作业平台(JOB)的作业模板[app_id=%s]接口job.get_task返回失败: %s"") % ( + biz_cc_id, job_result['message']) + logger.error(message) + result = { + 'result': False, + 'data': [], + 'message': message + } + return JsonResponse(result) + task_list = [] + for task in job_result['data']: + task_list.append({ + 'value': task['bk_job_id'], + 'text': task['name'], + }) + return JsonResponse({'result': True, 'data': task_list})","[{'piece_type': 'error message', 'piece_content': '------STARTING: Migrate Database------\\nTraceback (most recent call last):\\nFile ""manage.py"", line 27, in \\nexecute_from_command_line(sys.argv)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line\\nutility.execute()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute\\ndjango.setup()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup\\napps.populate(settings.INSTALLED_APPS)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate\\napp_config = AppConfig.create(entry)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create\\nmod = import_module(mod_path)\\nFile ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module\\n__import__(name)\\nFile ""/data/app/code/pipeline/apps.py"", line 18, in \\nfrom rediscluster import StrictRedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in \\nfrom .client import StrictRedisCluster, RedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in \\nfrom .connection import (\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in \\nfrom .nodemanager import NodeManager\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in \\nfrom redis._compat import b, unicode, bytes, long, basestring\\nImportError: cannot import name b\\n------FAILURE: Migrate Database------'}]","------STARTING: Migrate Database------ +Traceback (most recent call last): +File ""manage.py"", line 27, in +execute_from_command_line(sys.argv) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line +utility.execute() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute +django.setup() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup +apps.populate(settings.INSTALLED_APPS) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate +app_config = AppConfig.create(entry) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create +mod = import_module(mod_path) +File ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module +__import__(name) +File ""/data/app/code/pipeline/apps.py"", line 18, in +from rediscluster import StrictRedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in +from .client import StrictRedisCluster, RedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in +from .connection import ( +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in +from .nodemanager import NodeManager +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in +from redis._compat import b, unicode, bytes, long, basestring +ImportError: cannot import name b +------FAILURE: Migrate Database------",ImportError +"def job_get_job_task_detail(request, biz_cc_id, task_id): + client = get_client_by_user(request.user.username) + job_result = client.job.get_job_detail({'bk_biz_id': biz_cc_id, + 'bk_job_id': task_id}) + if not job_result['result']: + message = _(u""查询作业平台(JOB)的作业模板详情[app_id=%s]接口job.get_task_detail返回失败: %s"") % ( + biz_cc_id, job_result['message']) + logger.error(message) + result = { + 'result': False, + 'data': [], + 'message': message + } + return JsonResponse(result) + + job_step_type_name = { + 1: _(u""脚本""), + 2: _(u""文件""), + 4: u""SQL"" + } + task_detail = job_result['data'] + global_var = [] + steps = [] + for var in task_detail.get('global_vars', []): + # 1-字符串, 2-IP, 3-索引数组, 4-关联数组 + if var['type'] in [JOB_VAR_TYPE_STR, JOB_VAR_TYPE_IP, JOB_VAR_TYPE_ARRAY]: + value = var.get('value', '') + else: + value = ['{plat_id}:{ip}'.format(plat_id=ip_item['bk_cloud_id'], ip=ip_item['ip']) + for ip_item in var.get('ip_list', [])] + global_var.append({ + 'id': var['id'], + # 全局变量类型:1:云参, 2:上下文参数,3:IP + 'category': var.get('category', 1), + 'name': var['name'], + 'type': var['type'], + 'value': value, + 'description': var['description'] + }) + for info in task_detail.get('steps', []): + # 1-执行脚本, 2-传文件, 4-传SQL + steps.append({ + 'stepId': info['step_id'], + 'name': info['name'], + 'scriptParams': info.get('script_param', ''), + 'account': info.get('account', ''), + 'ipList': '', + 'type': info['type'], + 'type_name': job_step_type_name.get(info['type'], info['type']) + }) + return JsonResponse({'result': True, 'data': {'global_var': global_var, 'steps': steps}})","def job_get_job_task_detail(request, biz_cc_id, task_id): + client = get_client_by_request(request) + job_result = client.job.get_job_detail({'bk_biz_id': biz_cc_id, + 'bk_job_id': task_id}) + if not job_result['result']: + message = _(u""查询作业平台(JOB)的作业模板详情[app_id=%s]接口job.get_task_detail返回失败: %s"") % ( + biz_cc_id, job_result['message']) + logger.error(message) + result = { + 'result': False, + 'data': [], + 'message': message + } + return JsonResponse(result) + + job_step_type_name = { + 1: _(u""脚本""), + 2: _(u""文件""), + 4: u""SQL"" + } + task_detail = job_result['data'] + global_var = [] + steps = [] + for var in task_detail.get('global_vars', []): + # 1-字符串, 2-IP, 3-索引数组, 4-关联数组 + if var['type'] in [JOB_VAR_TYPE_STR, JOB_VAR_TYPE_IP, JOB_VAR_TYPE_ARRAY]: + value = var.get('value', '') + else: + value = ['{plat_id}:{ip}'.format(plat_id=ip_item['bk_cloud_id'], ip=ip_item['ip']) + for ip_item in var.get('ip_list', [])] + global_var.append({ + 'id': var['id'], + # 全局变量类型:1:云参, 2:上下文参数,3:IP + 'category': var.get('category', 1), + 'name': var['name'], + 'type': var['type'], + 'value': value, + 'description': var['description'] + }) + for info in task_detail.get('steps', []): + # 1-执行脚本, 2-传文件, 4-传SQL + steps.append({ + 'stepId': info['step_id'], + 'name': info['name'], + 'scriptParams': info.get('script_param', ''), + 'account': info.get('account', ''), + 'ipList': '', + 'type': info['type'], + 'type_name': job_step_type_name.get(info['type'], info['type']) + }) + return JsonResponse({'result': True, 'data': {'global_var': global_var, 'steps': steps}})","[{'piece_type': 'error message', 'piece_content': '------STARTING: Migrate Database------\\nTraceback (most recent call last):\\nFile ""manage.py"", line 27, in \\nexecute_from_command_line(sys.argv)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line\\nutility.execute()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute\\ndjango.setup()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup\\napps.populate(settings.INSTALLED_APPS)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate\\napp_config = AppConfig.create(entry)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create\\nmod = import_module(mod_path)\\nFile ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module\\n__import__(name)\\nFile ""/data/app/code/pipeline/apps.py"", line 18, in \\nfrom rediscluster import StrictRedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in \\nfrom .client import StrictRedisCluster, RedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in \\nfrom .connection import (\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in \\nfrom .nodemanager import NodeManager\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in \\nfrom redis._compat import b, unicode, bytes, long, basestring\\nImportError: cannot import name b\\n------FAILURE: Migrate Database------'}]","------STARTING: Migrate Database------ +Traceback (most recent call last): +File ""manage.py"", line 27, in +execute_from_command_line(sys.argv) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line +utility.execute() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute +django.setup() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup +apps.populate(settings.INSTALLED_APPS) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate +app_config = AppConfig.create(entry) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create +mod = import_module(mod_path) +File ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module +__import__(name) +File ""/data/app/code/pipeline/apps.py"", line 18, in +from rediscluster import StrictRedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in +from .client import StrictRedisCluster, RedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in +from .connection import ( +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in +from .nodemanager import NodeManager +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in +from redis._compat import b, unicode, bytes, long, basestring +ImportError: cannot import name b +------FAILURE: Migrate Database------",ImportError +"def get_bk_user(request): + bkuser = None + if request.weixin_user and not isinstance(request.weixin_user, AnonymousUser): + user_model = get_user_model() + try: + user_property = UserProperty.objects.get(key='wx_userid', value=request.weixin_user.userid) + except UserProperty.DoesNotExist: + logger.warning('user[wx_userid=%s] not in UserProperty' % request.weixin_user.userid) + else: + bkuser = user_model.objects.get(username=user_property.user.username) + return bkuser or AnonymousUser()","def get_bk_user(request): + bkuser = None + if request.weixin_user and not isinstance(request.weixin_user, AnonymousUser): + try: + user_property = UserProperty.objects.get(key='wx_userid', value=request.weixin_user.userid) + bkuser = user_property.user + except UserProperty.DoesNotExist: + bkuser = None + return bkuser or AnonymousUser()","[{'piece_type': 'error message', 'piece_content': '------STARTING: Migrate Database------\\nTraceback (most recent call last):\\nFile ""manage.py"", line 27, in \\nexecute_from_command_line(sys.argv)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line\\nutility.execute()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute\\ndjango.setup()\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup\\napps.populate(settings.INSTALLED_APPS)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate\\napp_config = AppConfig.create(entry)\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create\\nmod = import_module(mod_path)\\nFile ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module\\n__import__(name)\\nFile ""/data/app/code/pipeline/apps.py"", line 18, in \\nfrom rediscluster import StrictRedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in \\nfrom .client import StrictRedisCluster, RedisCluster\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in \\nfrom .connection import (\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in \\nfrom .nodemanager import NodeManager\\nFile ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in \\nfrom redis._compat import b, unicode, bytes, long, basestring\\nImportError: cannot import name b\\n------FAILURE: Migrate Database------'}]","------STARTING: Migrate Database------ +Traceback (most recent call last): +File ""manage.py"", line 27, in +execute_from_command_line(sys.argv) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 354, in execute_from_command_line +utility.execute() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 328, in execute +django.setup() +File ""/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py"", line 18, in setup +apps.populate(settings.INSTALLED_APPS) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py"", line 85, in populate +app_config = AppConfig.create(entry) +File ""/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py"", line 112, in create +mod = import_module(mod_path) +File ""/cache/.bk/env/lib/python2.7/importlib/__init__.py"", line 37, in import_module +__import__(name) +File ""/data/app/code/pipeline/apps.py"", line 18, in +from rediscluster import StrictRedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py"", line 7, in +from .client import StrictRedisCluster, RedisCluster +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py"", line 10, in +from .connection import ( +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py"", line 11, in +from .nodemanager import NodeManager +File ""/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py"", line 12, in +from redis._compat import b, unicode, bytes, long, basestring +ImportError: cannot import name b +------FAILURE: Migrate Database------",ImportError +" def fit(self, dataset: Dataset): + """"""Calculates statistics for this workflow on the input dataset + + Parameters + ----------- + dataset: Dataset + The input dataset to calculate statistics for. If there is a train/test split this + data should be the training dataset only. + """""" + self._clear_worker_cache() + ddf = dataset.to_ddf(columns=self._input_columns()) + + # Get a dictionary mapping all StatOperators we need to fit to a set of any dependant + # StatOperators (having StatOperators that depend on the output of other StatOperators + # means that will have multiple phases in the fit cycle here) + stat_ops = {op: _get_stat_ops(op.parents) for op in _get_stat_ops([self.column_group])} + + while stat_ops: + # get all the StatOperators that we can currently call fit on (no outstanding + # dependencies) + current_phase = [op for op, dependencies in stat_ops.items() if not dependencies] + if not current_phase: + # this shouldn't happen, but lets not infinite loop just in case + raise RuntimeError(""failed to find dependency-free StatOperator to fit"") + + stats, ops = [], [] + for column_group in current_phase: + # apply transforms necessary for the inputs to the current column group, ignoring + # the transforms from the statop itself + transformed_ddf = _transform_ddf(ddf, column_group.parents) + + op = column_group.op + try: + stats.append(op.fit(column_group.input_column_names, transformed_ddf)) + ops.append(op) + except Exception: + LOG.exception(""Failed to fit operator %s"", column_group.op) + raise + + if self.client: + results = [r.result() for r in self.client.compute(stats)] + else: + results = dask.compute(stats, scheduler=""synchronous"")[0] + + for computed_stats, op in zip(results, ops): + op.fit_finalize(computed_stats) + + # Remove all the operators we processed in this phase, and remove + # from the dependencies of other ops too + for stat_op in current_phase: + stat_ops.pop(stat_op) + for dependencies in stat_ops.values(): + dependencies.difference_update(current_phase) + + # hack: store input/output dtypes here. We should have complete dtype + # information for each operator (like we do for column names), but as + # an interim solution this gets us what we need. + input_dtypes = dataset.to_ddf()[self._input_columns()].dtypes + self.input_dtypes = dict(zip(input_dtypes.index, input_dtypes)) + output_dtypes = self.transform(dataset).to_ddf().head(1).dtypes + self.output_dtypes = dict(zip(output_dtypes.index, output_dtypes))"," def fit(self, dataset: Dataset): + """"""Calculates statistics for this workflow on the input dataset + + Parameters + ----------- + dataset: Dataset + The input dataset to calculate statistics for. If there is a train/test split this + data should be the training dataset only. + """""" + self._clear_worker_cache() + ddf = dataset.to_ddf(columns=self._input_columns()) + + # Get a dictionary mapping all StatOperators we need to fit to a set of any dependant + # StatOperators (having StatOperators that depend on the output of other StatOperators + # means that will have multiple phases in the fit cycle here) + stat_ops = {op: _get_stat_ops(op.parents) for op in _get_stat_ops([self.column_group])} + + while stat_ops: + # get all the StatOperators that we can currently call fit on (no outstanding + # dependencies) + current_phase = [op for op, dependencies in stat_ops.items() if not dependencies] + if not current_phase: + # this shouldn't happen, but lets not infinite loop just in case + raise RuntimeError(""failed to find dependency-free StatOperator to fit"") + + stats, ops = [], [] + for column_group in current_phase: + # apply transforms necessary for the inputs to the current column group, ignoring + # the transforms from the statop itself + transformed_ddf = _transform_ddf(ddf, column_group.parents) + + op = column_group.op + try: + stats.append(op.fit(column_group.input_column_names, transformed_ddf)) + ops.append(op) + except Exception: + LOG.exception(""Failed to fit operator %s"", column_group.op) + raise + + if self.client: + results = [r.result() for r in self.client.compute(stats)] + else: + results = dask.compute(stats, scheduler=""synchronous"")[0] + + for computed_stats, op in zip(results, ops): + op.fit_finalize(computed_stats) + + # Remove all the operators we processed in this phase, and remove + # from the dependencies of other ops too + for stat_op in current_phase: + stat_ops.pop(stat_op) + for dependencies in stat_ops.values(): + dependencies.difference_update(current_phase) + + # hack: store input/output dtypes here. We should have complete dtype + # information for each operator (like we do for column names), but as + # an interim solution this gets us what we need. + input_dtypes = dataset.to_ddf().dtypes + self.input_dtypes = dict(zip(input_dtypes.index, input_dtypes)) + output_dtypes = self.transform(dataset).to_ddf().head(1).dtypes + self.output_dtypes = dict(zip(output_dtypes.index, output_dtypes))","[{'piece_type': 'error message', 'piece_content': 'E0224 15:58:10.330248 178 model_repository_manager.cc:963] failed to load \\'amazonreview_tf\\' version 1: Internal: unable to create stream: the provided PTX was compiled with an unsupported toolchain.\\n/nvtabular/nvtabular/workflow.py:236: UserWarning: Loading workflow generated with cudf version 0+untagged.1.gbd321d1 - but we are running cudf 0.18.0a+253.g53ed28e91c. This might cause issues\\nwarnings.warn(\\nE0224 15:58:20.534884 178 model_repository_manager.cc:963] failed to load \\'amazonreview_nvt\\' version 1: Internal: Traceback (most recent call last):\\nFile ""/opt/tritonserver/backends/python/startup.py"", line 197, in Init\\nself.backend.initialize(args)\\nFile ""/models/models/amazonreview_nvt/1/model.py"", line 57, in initialize\\nself.output_dtypes[name] = triton_string_to_numpy(conf[""data_type""])\\nTypeError: \\'NoneType\\' object is not subscriptable\\nI0224 15:58:20.535093 178 server.cc:490]'}]","E0224 15:58:10.330248 178 model_repository_manager.cc:963] failed to load 'amazonreview_tf' version 1: Internal: unable to create stream: the provided PTX was compiled with an unsupported toolchain. +/nvtabular/nvtabular/workflow.py:236: UserWarning: Loading workflow generated with cudf version 0+untagged.1.gbd321d1 - but we are running cudf 0.18.0a+253.g53ed28e91c. This might cause issues +warnings.warn( +E0224 15:58:20.534884 178 model_repository_manager.cc:963] failed to load 'amazonreview_nvt' version 1: Internal: Traceback (most recent call last): +File ""/opt/tritonserver/backends/python/startup.py"", line 197, in Init +self.backend.initialize(args) +File ""/models/models/amazonreview_nvt/1/model.py"", line 57, in initialize +self.output_dtypes[name] = triton_string_to_numpy(conf[""data_type""]) +TypeError: 'NoneType' object is not subscriptable +I0224 15:58:20.535093 178 server.cc:490]",TypeError +"def main(args): + """"""Multi-GPU Criteo/DLRM Preprocessing Benchmark + + This benchmark is designed to measure the time required to preprocess + the Criteo (1TB) dataset for Facebook’s DLRM model. The user must specify + the path of the raw dataset (using the `--data-path` flag), as well as the + output directory for all temporary/final data (using the `--out-path` flag) + + Example Usage + ------------- + + python dask-nvtabular-criteo-benchmark.py + --data-path /path/to/criteo_parquet --out-path /out/dir/` + + + Dataset Requirements (Parquet) + ------------------------------ + + This benchmark is designed with a parquet-formatted dataset in mind. + While a CSV-formatted dataset can be processed by NVTabular, converting + to parquet will yield significantly better performance. To convert your + dataset, try using the `optimize_criteo.ipynb` notebook (also located + in `NVTabular/examples/`) + + For a detailed parameter overview see `NVTabular/examples/MultiGPUBench.md` + """""" + + # Input + data_path = args.data_path[:-1] if args.data_path[-1] == ""/"" else args.data_path + freq_limit = args.freq_limit + out_files_per_proc = args.out_files_per_proc + high_card_columns = args.high_cards.split("","") + dashboard_port = args.dashboard_port + if args.protocol == ""ucx"": + UCX_TLS = os.environ.get(""UCX_TLS"", ""tcp,cuda_copy,cuda_ipc,sockcm"") + os.environ[""UCX_TLS""] = UCX_TLS + + # Cleanup output directory + base_dir = args.out_path[:-1] if args.out_path[-1] == ""/"" else args.out_path + dask_workdir = os.path.join(base_dir, ""workdir"") + output_path = os.path.join(base_dir, ""output"") + stats_path = os.path.join(base_dir, ""stats"") + setup_dirs(base_dir, dask_workdir, output_path, stats_path) + + # Use Criteo dataset by default (for now) + cont_names = ( + args.cont_names.split("","") if args.cont_names else [""I"" + str(x) for x in range(1, 14)] + ) + cat_names = ( + args.cat_names.split("","") if args.cat_names else [""C"" + str(x) for x in range(1, 27)] + ) + label_name = [""label""] + + # Specify Categorify/GroupbyStatistics options + tree_width = {} + cat_cache = {} + for col in cat_names: + if col in high_card_columns: + tree_width[col] = args.tree_width + cat_cache[col] = args.cat_cache_high + else: + tree_width[col] = 1 + cat_cache[col] = args.cat_cache_low + + # Use total device size to calculate args.device_limit_frac + device_size = device_mem_size(kind=""total"") + device_limit = int(args.device_limit_frac * device_size) + device_pool_size = int(args.device_pool_frac * device_size) + part_size = int(args.part_mem_frac * device_size) + + # Parse shuffle option + shuffle = None + if args.shuffle == ""PER_WORKER"": + shuffle = nvt_io.Shuffle.PER_WORKER + elif args.shuffle == ""PER_PARTITION"": + shuffle = nvt_io.Shuffle.PER_PARTITION + + # Check if any device memory is already occupied + for dev in args.devices.split("",""): + fmem = _pynvml_mem_size(kind=""free"", index=int(dev)) + used = (device_size - fmem) / 1e9 + if used > 1.0: + warnings.warn(f""BEWARE - {used} GB is already occupied on device {int(dev)}!"") + + # Setup LocalCUDACluster + if args.protocol == ""tcp"": + cluster = LocalCUDACluster( + protocol=args.protocol, + n_workers=args.n_workers, + CUDA_VISIBLE_DEVICES=args.devices, + device_memory_limit=device_limit, + local_directory=dask_workdir, + dashboard_address="":"" + dashboard_port, + ) + else: + cluster = LocalCUDACluster( + protocol=args.protocol, + n_workers=args.n_workers, + CUDA_VISIBLE_DEVICES=args.devices, + enable_nvlink=True, + device_memory_limit=device_limit, + local_directory=dask_workdir, + dashboard_address="":"" + dashboard_port, + ) + client = Client(cluster) + + # Setup RMM pool + if args.device_pool_frac > 0.01: + setup_rmm_pool(client, device_pool_size) + + # Define Dask NVTabular ""Workflow"" + if args.normalize: + cont_features = cont_names >> ops.FillMissing() >> ops.Normalize() + else: + cont_features = cont_names >> ops.FillMissing() >> ops.Clip(min_value=0) >> ops.LogOp() + + cat_features = cat_names >> ops.Categorify( + out_path=stats_path, + tree_width=tree_width, + cat_cache=cat_cache, + freq_threshold=freq_limit, + search_sorted=not freq_limit, + on_host=not args.cats_on_device, + ) + processor = Workflow(cat_features + cont_features + label_name, client=client) + + dataset = Dataset(data_path, ""parquet"", part_size=part_size) + + # Execute the dask graph + runtime = time.time() + + processor.fit(dataset) + + if args.profile is not None: + with performance_report(filename=args.profile): + processor.transform(dataset).to_parquet( + output_path=output_path, + num_threads=args.num_io_threads, + shuffle=shuffle, + out_files_per_proc=out_files_per_proc, + ) + else: + processor.transform(dataset).to_parquet( + output_path=output_path, + num_threads=args.num_io_threads, + shuffle=shuffle, + out_files_per_proc=out_files_per_proc, + ) + runtime = time.time() - runtime + + print(""\\nDask-NVTabular DLRM/Criteo benchmark"") + print(""--------------------------------------"") + print(f""partition size | {part_size}"") + print(f""protocol | {args.protocol}"") + print(f""device(s) | {args.devices}"") + print(f""rmm-pool-frac | {(args.device_pool_frac)}"") + print(f""out-files-per-proc | {args.out_files_per_proc}"") + print(f""num_io_threads | {args.num_io_threads}"") + print(f""shuffle | {args.shuffle}"") + print(f""cats-on-device | {args.cats_on_device}"") + print(""======================================"") + print(f""Runtime[s] | {runtime}"") + print(""======================================\\n"") + + client.close()","def main(args): + """"""Multi-GPU Criteo/DLRM Preprocessing Benchmark + + This benchmark is designed to measure the time required to preprocess + the Criteo (1TB) dataset for Facebook’s DLRM model. The user must specify + the path of the raw dataset (using the `--data-path` flag), as well as the + output directory for all temporary/final data (using the `--out-path` flag) + + Example Usage + ------------- + + python dask-nvtabular-criteo-benchmark.py + --data-path /path/to/criteo_parquet --out-path /out/dir/` + + + Dataset Requirements (Parquet) + ------------------------------ + + This benchmark is designed with a parquet-formatted dataset in mind. + While a CSV-formatted dataset can be processed by NVTabular, converting + to parquet will yield significantly better performance. To convert your + dataset, try using the `optimize_criteo.ipynb` notebook (also located + in `NVTabular/examples/`) + + For a detailed parameter overview see `NVTabular/examples/MultiGPUBench.md` + """""" + + # Input + data_path = args.data_path + freq_limit = args.freq_limit + out_files_per_proc = args.out_files_per_proc + high_card_columns = args.high_cards.split("","") + dashboard_port = args.dashboard_port + if args.protocol == ""ucx"": + UCX_TLS = os.environ.get(""UCX_TLS"", ""tcp,cuda_copy,cuda_ipc,sockcm"") + os.environ[""UCX_TLS""] = UCX_TLS + + # Cleanup output directory + BASE_DIR = args.out_path + dask_workdir = os.path.join(BASE_DIR, ""workdir"") + output_path = os.path.join(BASE_DIR, ""output"") + stats_path = os.path.join(BASE_DIR, ""stats"") + if not os.path.isdir(BASE_DIR): + os.mkdir(BASE_DIR) + for dir_path in (dask_workdir, output_path, stats_path): + if os.path.isdir(dir_path): + shutil.rmtree(dir_path) + os.mkdir(dir_path) + + # Use Criteo dataset by default (for now) + cont_names = ( + args.cont_names.split("","") if args.cont_names else [""I"" + str(x) for x in range(1, 14)] + ) + cat_names = ( + args.cat_names.split("","") if args.cat_names else [""C"" + str(x) for x in range(1, 27)] + ) + label_name = [""label""] + + # Specify Categorify/GroupbyStatistics options + tree_width = {} + cat_cache = {} + for col in cat_names: + if col in high_card_columns: + tree_width[col] = args.tree_width + cat_cache[col] = args.cat_cache_high + else: + tree_width[col] = 1 + cat_cache[col] = args.cat_cache_low + + # Use total device size to calculate args.device_limit_frac + device_size = device_mem_size(kind=""total"") + device_limit = int(args.device_limit_frac * device_size) + device_pool_size = int(args.device_pool_frac * device_size) + part_size = int(args.part_mem_frac * device_size) + + # Parse shuffle option + shuffle = None + if args.shuffle == ""PER_WORKER"": + shuffle = nvt_io.Shuffle.PER_WORKER + elif args.shuffle == ""PER_PARTITION"": + shuffle = nvt_io.Shuffle.PER_PARTITION + + # Check if any device memory is already occupied + for dev in args.devices.split("",""): + fmem = _pynvml_mem_size(kind=""free"", index=int(dev)) + used = (device_size - fmem) / 1e9 + if used > 1.0: + warnings.warn(f""BEWARE - {used} GB is already occupied on device {int(dev)}!"") + + # Setup LocalCUDACluster + if args.protocol == ""tcp"": + cluster = LocalCUDACluster( + protocol=args.protocol, + n_workers=args.n_workers, + CUDA_VISIBLE_DEVICES=args.devices, + device_memory_limit=device_limit, + local_directory=dask_workdir, + dashboard_address="":"" + dashboard_port, + ) + else: + cluster = LocalCUDACluster( + protocol=args.protocol, + n_workers=args.n_workers, + CUDA_VISIBLE_DEVICES=args.devices, + enable_nvlink=True, + device_memory_limit=device_limit, + local_directory=dask_workdir, + dashboard_address="":"" + dashboard_port, + ) + client = Client(cluster) + + # Setup RMM pool + if args.device_pool_frac > 0.01: + setup_rmm_pool(client, device_pool_size) + + # Define Dask NVTabular ""Workflow"" + if args.normalize: + cont_features = cont_names >> ops.FillMissing() >> ops.Normalize() + else: + cont_features = cont_names >> ops.FillMissing() >> ops.Clip(min_value=0) >> ops.LogOp() + + cat_features = cat_names >> ops.Categorify( + out_path=stats_path, + tree_width=tree_width, + cat_cache=cat_cache, + freq_threshold=freq_limit, + search_sorted=not freq_limit, + on_host=not args.cats_on_device, + ) + processor = Workflow(cat_features + cont_features + label_name, client=client) + + dataset = Dataset(data_path, ""parquet"", part_size=part_size) + + # Execute the dask graph + runtime = time.time() + + processor.fit(dataset) + + if args.profile is not None: + with performance_report(filename=args.profile): + processor.transform(dataset).to_parquet( + output_path=output_path, + num_threads=args.num_io_threads, + shuffle=shuffle, + out_files_per_proc=out_files_per_proc, + ) + else: + processor.transform(dataset).to_parquet( + output_path=output_path, + num_threads=args.num_io_threads, + shuffle=shuffle, + out_files_per_proc=out_files_per_proc, + ) + runtime = time.time() - runtime + + print(""\\nDask-NVTabular DLRM/Criteo benchmark"") + print(""--------------------------------------"") + print(f""partition size | {part_size}"") + print(f""protocol | {args.protocol}"") + print(f""device(s) | {args.devices}"") + print(f""rmm-pool-frac | {(args.device_pool_frac)}"") + print(f""out-files-per-proc | {args.out_files_per_proc}"") + print(f""num_io_threads | {args.num_io_threads}"") + print(f""shuffle | {args.shuffle}"") + print(f""cats-on-device | {args.cats_on_device}"") + print(""======================================"") + print(f""Runtime[s] | {runtime}"") + print(""======================================\\n"") + + client.close()","[{'piece_type': 'error message', 'piece_content': '(rapids) root@dafff4b22f48:/nvtabular# python examples/dask-nvtabular-criteo-benchmark.py -d 0,1,2,3,4,5,6,7 --data-path gs://merlin-datasets/crit_int_pq --out-path gs://merlin-datasets/output --freq-limit 0 --part-mem-frac 0.12 --device-limit-f\\nrac 0.7 --device-pool-frac 0.8\\ndistributed.worker - WARNING - Compute Failed\\nFunction: subgraph_callable\\nargs: ( label I1 I2 I3 I4 I5 I6 I7 I8 I9 ... C17 C18 C19 C20 C21 C22 C23 C24 C25 C26\\n0 0 2.772589 5.808143 1.609438 2.397895 3.332205 0.000000 1.098612 4.442651 0.000000 ... -771205462 -1206449222 -864387787 359448199 -1761877609 357969245 -740331133 44548210 -842849922 -507617550\\n1 0 0.000000 5.147494 1.945910 4.584968 1.098612 0.000000 0.000000 4.394449 2.302585 ... -1206449222 -1793932789 -1441487878 809724924 -1775758394\\n2 0 2.639057 0.693147 0.693147 2.890372 0.000000 1.791759 0.000000 2.302585 2.833213 ... 1966974451 -1578429167 -1264946531 -2019528747 870435994 -322370806 -1701803791 2093085390 809724924 -317696227\\n3 0 4.110874 7.392032 0.693147 5.937536 3.610918 0.000\\nkwargs: {}\\nException: FileNotFoundError(2, \\'No such file or directory\\')\\n\\nTraceback (most recent call last):\\nFile ""examples/dask-nvtabular-criteo-benchmark.py"", line 373, in \\nmain(parse_args())\\nFile ""examples/dask-nvtabular-criteo-benchmark.py"", line 195, in main\\noutput_path=output_path,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 876, in apply\\ndtypes=dtypes,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 991, in build_and_process_graph\\nnum_threads=num_io_threads,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 1080, in ddf_to_dataset\\nnum_threads,\\nFile ""/nvtabular/nvtabular/io/dask.py"", line 110, in _ddf_to_dataset\\nout = client.compute(out).result()\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/distributed/client.py"", line 225, in result\\nraise exc.with_traceback(tb)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/optimization.py"", line 961, in __call__\\nreturn core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 151, in get\\nresult = _execute_task(task, cache)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 121, in _execute_task\\nreturn func(*(_execute_task(a, cache) for a in args))\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/utils.py"", line 29, in apply\\nreturn func(*args, **kwargs)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/core.py"", line 5298, in apply_and_enforce\\ndf = func(*args, **kwargs)\\nFile ""/nvtabular/nvtabular/workflow.py"", line 723, in _aggregated_op\\ngdf = logic(gdf, columns_ctx, cols_grp, target_cols, stats_context)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/contextlib.py"", line 74, in inner\\nreturn func(*args, **kwds)\\nFile ""/nvtabular/nvtabular/ops/categorify.py"", line 365, in apply_op\\ncat_names=cat_names,\\nFile ""/nvtabular/nvtabular/ops/categorify.py"", line 871, in _encode\\ncache, path, columns=selection_r, cache=cat_cache, cats_only=True\\nFile ""/nvtabular/nvtabular/worker.py"", line 84, in fetch_table_data\\nwith open(path, ""rb"") as f:\\nFileNotFoundError: [Errno 2] No such file or directory: \\'gs://merlin-datasets/output/stats/categories/unique.C1.parquet\\''}]","(rapids) root@dafff4b22f48:/nvtabular# python examples/dask-nvtabular-criteo-benchmark.py -d 0,1,2,3,4,5,6,7 --data-path gs://merlin-datasets/crit_int_pq --out-path gs://merlin-datasets/output --freq-limit 0 --part-mem-frac 0.12 --device-limit-f +rac 0.7 --device-pool-frac 0.8 +distributed.worker - WARNING - Compute Failed +Function: subgraph_callable +args: ( label I1 I2 I3 I4 I5 I6 I7 I8 I9 ... C17 C18 C19 C20 C21 C22 C23 C24 C25 C26 +0 0 2.772589 5.808143 1.609438 2.397895 3.332205 0.000000 1.098612 4.442651 0.000000 ... -771205462 -1206449222 -864387787 359448199 -1761877609 357969245 -740331133 44548210 -842849922 -507617550 +1 0 0.000000 5.147494 1.945910 4.584968 1.098612 0.000000 0.000000 4.394449 2.302585 ... -1206449222 -1793932789 -1441487878 809724924 -1775758394 +2 0 2.639057 0.693147 0.693147 2.890372 0.000000 1.791759 0.000000 2.302585 2.833213 ... 1966974451 -1578429167 -1264946531 -2019528747 870435994 -322370806 -1701803791 2093085390 809724924 -317696227 +3 0 4.110874 7.392032 0.693147 5.937536 3.610918 0.000 +kwargs: {} +Exception: FileNotFoundError(2, 'No such file or directory') + +Traceback (most recent call last): +File ""examples/dask-nvtabular-criteo-benchmark.py"", line 373, in +main(parse_args()) +File ""examples/dask-nvtabular-criteo-benchmark.py"", line 195, in main +output_path=output_path, +File ""/nvtabular/nvtabular/workflow.py"", line 876, in apply +dtypes=dtypes, +File ""/nvtabular/nvtabular/workflow.py"", line 991, in build_and_process_graph +num_threads=num_io_threads, +File ""/nvtabular/nvtabular/workflow.py"", line 1080, in ddf_to_dataset +num_threads, +File ""/nvtabular/nvtabular/io/dask.py"", line 110, in _ddf_to_dataset +out = client.compute(out).result() +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/distributed/client.py"", line 225, in result +raise exc.with_traceback(tb) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/optimization.py"", line 961, in __call__ +return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args))) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 151, in get +result = _execute_task(task, cache) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 121, in _execute_task +return func(*(_execute_task(a, cache) for a in args)) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/utils.py"", line 29, in apply +return func(*args, **kwargs) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/core.py"", line 5298, in apply_and_enforce +df = func(*args, **kwargs) +File ""/nvtabular/nvtabular/workflow.py"", line 723, in _aggregated_op +gdf = logic(gdf, columns_ctx, cols_grp, target_cols, stats_context) +File ""/opt/conda/envs/rapids/lib/python3.7/contextlib.py"", line 74, in inner +return func(*args, **kwds) +File ""/nvtabular/nvtabular/ops/categorify.py"", line 365, in apply_op +cat_names=cat_names, +File ""/nvtabular/nvtabular/ops/categorify.py"", line 871, in _encode +cache, path, columns=selection_r, cache=cat_cache, cats_only=True +File ""/nvtabular/nvtabular/worker.py"", line 84, in fetch_table_data +with open(path, ""rb"") as f: +FileNotFoundError: [Errno 2] No such file or directory: 'gs://merlin-datasets/output/stats/categories/unique.C1.parquet'",FileNotFoundError +" def __init__(self, out_dir, **kwargs): + super().__init__(out_dir, **kwargs) + self.data_paths = [] + self.data_files = [] + self.data_writers = [] + self.data_bios = [] + self._lock = threading.RLock() + self.pwriter = self._pwriter + self.pwriter_kwargs = {}"," def __init__(self, out_dir, **kwargs): + super().__init__(out_dir, **kwargs) + self.data_paths = [] + self.data_writers = [] + self.data_bios = [] + self._lock = threading.RLock() + self.pwriter = self._pwriter + self.pwriter_kwargs = {}","[{'piece_type': 'error message', 'piece_content': '(rapids) root@dafff4b22f48:/nvtabular# python examples/dask-nvtabular-criteo-benchmark.py -d 0,1,2,3,4,5,6,7 --data-path gs://merlin-datasets/crit_int_pq --out-path gs://merlin-datasets/output --freq-limit 0 --part-mem-frac 0.12 --device-limit-f\\nrac 0.7 --device-pool-frac 0.8\\ndistributed.worker - WARNING - Compute Failed\\nFunction: subgraph_callable\\nargs: ( label I1 I2 I3 I4 I5 I6 I7 I8 I9 ... C17 C18 C19 C20 C21 C22 C23 C24 C25 C26\\n0 0 2.772589 5.808143 1.609438 2.397895 3.332205 0.000000 1.098612 4.442651 0.000000 ... -771205462 -1206449222 -864387787 359448199 -1761877609 357969245 -740331133 44548210 -842849922 -507617550\\n1 0 0.000000 5.147494 1.945910 4.584968 1.098612 0.000000 0.000000 4.394449 2.302585 ... -1206449222 -1793932789 -1441487878 809724924 -1775758394\\n2 0 2.639057 0.693147 0.693147 2.890372 0.000000 1.791759 0.000000 2.302585 2.833213 ... 1966974451 -1578429167 -1264946531 -2019528747 870435994 -322370806 -1701803791 2093085390 809724924 -317696227\\n3 0 4.110874 7.392032 0.693147 5.937536 3.610918 0.000\\nkwargs: {}\\nException: FileNotFoundError(2, \\'No such file or directory\\')\\n\\nTraceback (most recent call last):\\nFile ""examples/dask-nvtabular-criteo-benchmark.py"", line 373, in \\nmain(parse_args())\\nFile ""examples/dask-nvtabular-criteo-benchmark.py"", line 195, in main\\noutput_path=output_path,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 876, in apply\\ndtypes=dtypes,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 991, in build_and_process_graph\\nnum_threads=num_io_threads,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 1080, in ddf_to_dataset\\nnum_threads,\\nFile ""/nvtabular/nvtabular/io/dask.py"", line 110, in _ddf_to_dataset\\nout = client.compute(out).result()\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/distributed/client.py"", line 225, in result\\nraise exc.with_traceback(tb)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/optimization.py"", line 961, in __call__\\nreturn core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 151, in get\\nresult = _execute_task(task, cache)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 121, in _execute_task\\nreturn func(*(_execute_task(a, cache) for a in args))\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/utils.py"", line 29, in apply\\nreturn func(*args, **kwargs)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/core.py"", line 5298, in apply_and_enforce\\ndf = func(*args, **kwargs)\\nFile ""/nvtabular/nvtabular/workflow.py"", line 723, in _aggregated_op\\ngdf = logic(gdf, columns_ctx, cols_grp, target_cols, stats_context)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/contextlib.py"", line 74, in inner\\nreturn func(*args, **kwds)\\nFile ""/nvtabular/nvtabular/ops/categorify.py"", line 365, in apply_op\\ncat_names=cat_names,\\nFile ""/nvtabular/nvtabular/ops/categorify.py"", line 871, in _encode\\ncache, path, columns=selection_r, cache=cat_cache, cats_only=True\\nFile ""/nvtabular/nvtabular/worker.py"", line 84, in fetch_table_data\\nwith open(path, ""rb"") as f:\\nFileNotFoundError: [Errno 2] No such file or directory: \\'gs://merlin-datasets/output/stats/categories/unique.C1.parquet\\''}]","(rapids) root@dafff4b22f48:/nvtabular# python examples/dask-nvtabular-criteo-benchmark.py -d 0,1,2,3,4,5,6,7 --data-path gs://merlin-datasets/crit_int_pq --out-path gs://merlin-datasets/output --freq-limit 0 --part-mem-frac 0.12 --device-limit-f +rac 0.7 --device-pool-frac 0.8 +distributed.worker - WARNING - Compute Failed +Function: subgraph_callable +args: ( label I1 I2 I3 I4 I5 I6 I7 I8 I9 ... C17 C18 C19 C20 C21 C22 C23 C24 C25 C26 +0 0 2.772589 5.808143 1.609438 2.397895 3.332205 0.000000 1.098612 4.442651 0.000000 ... -771205462 -1206449222 -864387787 359448199 -1761877609 357969245 -740331133 44548210 -842849922 -507617550 +1 0 0.000000 5.147494 1.945910 4.584968 1.098612 0.000000 0.000000 4.394449 2.302585 ... -1206449222 -1793932789 -1441487878 809724924 -1775758394 +2 0 2.639057 0.693147 0.693147 2.890372 0.000000 1.791759 0.000000 2.302585 2.833213 ... 1966974451 -1578429167 -1264946531 -2019528747 870435994 -322370806 -1701803791 2093085390 809724924 -317696227 +3 0 4.110874 7.392032 0.693147 5.937536 3.610918 0.000 +kwargs: {} +Exception: FileNotFoundError(2, 'No such file or directory') + +Traceback (most recent call last): +File ""examples/dask-nvtabular-criteo-benchmark.py"", line 373, in +main(parse_args()) +File ""examples/dask-nvtabular-criteo-benchmark.py"", line 195, in main +output_path=output_path, +File ""/nvtabular/nvtabular/workflow.py"", line 876, in apply +dtypes=dtypes, +File ""/nvtabular/nvtabular/workflow.py"", line 991, in build_and_process_graph +num_threads=num_io_threads, +File ""/nvtabular/nvtabular/workflow.py"", line 1080, in ddf_to_dataset +num_threads, +File ""/nvtabular/nvtabular/io/dask.py"", line 110, in _ddf_to_dataset +out = client.compute(out).result() +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/distributed/client.py"", line 225, in result +raise exc.with_traceback(tb) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/optimization.py"", line 961, in __call__ +return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args))) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 151, in get +result = _execute_task(task, cache) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 121, in _execute_task +return func(*(_execute_task(a, cache) for a in args)) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/utils.py"", line 29, in apply +return func(*args, **kwargs) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/core.py"", line 5298, in apply_and_enforce +df = func(*args, **kwargs) +File ""/nvtabular/nvtabular/workflow.py"", line 723, in _aggregated_op +gdf = logic(gdf, columns_ctx, cols_grp, target_cols, stats_context) +File ""/opt/conda/envs/rapids/lib/python3.7/contextlib.py"", line 74, in inner +return func(*args, **kwds) +File ""/nvtabular/nvtabular/ops/categorify.py"", line 365, in apply_op +cat_names=cat_names, +File ""/nvtabular/nvtabular/ops/categorify.py"", line 871, in _encode +cache, path, columns=selection_r, cache=cat_cache, cats_only=True +File ""/nvtabular/nvtabular/worker.py"", line 84, in fetch_table_data +with open(path, ""rb"") as f: +FileNotFoundError: [Errno 2] No such file or directory: 'gs://merlin-datasets/output/stats/categories/unique.C1.parquet'",FileNotFoundError +" def _append_writer(self, path, schema=None, add_args=None, add_kwargs=None): + # Add additional args and kwargs + _args = add_args or [] + _kwargs = tlz.merge(self.pwriter_kwargs, add_kwargs or {}) + + if self.bytes_io: + bio = BytesIO() + self.data_bios.append(bio) + self.data_writers.append(self.pwriter(bio, *_args, **_kwargs)) + else: + f = fsspec.open(path, mode=""wb"").open() + self.data_files.append(f) + self.data_writers.append(self.pwriter(f, *_args, **_kwargs))"," def _append_writer(self, path, schema=None, add_args=None, add_kwargs=None): + # Add additional args and kwargs + _args = add_args or [] + _kwargs = tlz.merge(self.pwriter_kwargs, add_kwargs or {}) + + if self.bytes_io: + bio = BytesIO() + self.data_bios.append(bio) + self.data_writers.append(self.pwriter(bio, *_args, **_kwargs)) + else: + self.data_writers.append(self.pwriter(path, *_args, **_kwargs))","[{'piece_type': 'error message', 'piece_content': '(rapids) root@dafff4b22f48:/nvtabular# python examples/dask-nvtabular-criteo-benchmark.py -d 0,1,2,3,4,5,6,7 --data-path gs://merlin-datasets/crit_int_pq --out-path gs://merlin-datasets/output --freq-limit 0 --part-mem-frac 0.12 --device-limit-f\\nrac 0.7 --device-pool-frac 0.8\\ndistributed.worker - WARNING - Compute Failed\\nFunction: subgraph_callable\\nargs: ( label I1 I2 I3 I4 I5 I6 I7 I8 I9 ... C17 C18 C19 C20 C21 C22 C23 C24 C25 C26\\n0 0 2.772589 5.808143 1.609438 2.397895 3.332205 0.000000 1.098612 4.442651 0.000000 ... -771205462 -1206449222 -864387787 359448199 -1761877609 357969245 -740331133 44548210 -842849922 -507617550\\n1 0 0.000000 5.147494 1.945910 4.584968 1.098612 0.000000 0.000000 4.394449 2.302585 ... -1206449222 -1793932789 -1441487878 809724924 -1775758394\\n2 0 2.639057 0.693147 0.693147 2.890372 0.000000 1.791759 0.000000 2.302585 2.833213 ... 1966974451 -1578429167 -1264946531 -2019528747 870435994 -322370806 -1701803791 2093085390 809724924 -317696227\\n3 0 4.110874 7.392032 0.693147 5.937536 3.610918 0.000\\nkwargs: {}\\nException: FileNotFoundError(2, \\'No such file or directory\\')\\n\\nTraceback (most recent call last):\\nFile ""examples/dask-nvtabular-criteo-benchmark.py"", line 373, in \\nmain(parse_args())\\nFile ""examples/dask-nvtabular-criteo-benchmark.py"", line 195, in main\\noutput_path=output_path,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 876, in apply\\ndtypes=dtypes,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 991, in build_and_process_graph\\nnum_threads=num_io_threads,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 1080, in ddf_to_dataset\\nnum_threads,\\nFile ""/nvtabular/nvtabular/io/dask.py"", line 110, in _ddf_to_dataset\\nout = client.compute(out).result()\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/distributed/client.py"", line 225, in result\\nraise exc.with_traceback(tb)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/optimization.py"", line 961, in __call__\\nreturn core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 151, in get\\nresult = _execute_task(task, cache)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 121, in _execute_task\\nreturn func(*(_execute_task(a, cache) for a in args))\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/utils.py"", line 29, in apply\\nreturn func(*args, **kwargs)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/core.py"", line 5298, in apply_and_enforce\\ndf = func(*args, **kwargs)\\nFile ""/nvtabular/nvtabular/workflow.py"", line 723, in _aggregated_op\\ngdf = logic(gdf, columns_ctx, cols_grp, target_cols, stats_context)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/contextlib.py"", line 74, in inner\\nreturn func(*args, **kwds)\\nFile ""/nvtabular/nvtabular/ops/categorify.py"", line 365, in apply_op\\ncat_names=cat_names,\\nFile ""/nvtabular/nvtabular/ops/categorify.py"", line 871, in _encode\\ncache, path, columns=selection_r, cache=cat_cache, cats_only=True\\nFile ""/nvtabular/nvtabular/worker.py"", line 84, in fetch_table_data\\nwith open(path, ""rb"") as f:\\nFileNotFoundError: [Errno 2] No such file or directory: \\'gs://merlin-datasets/output/stats/categories/unique.C1.parquet\\''}]","(rapids) root@dafff4b22f48:/nvtabular# python examples/dask-nvtabular-criteo-benchmark.py -d 0,1,2,3,4,5,6,7 --data-path gs://merlin-datasets/crit_int_pq --out-path gs://merlin-datasets/output --freq-limit 0 --part-mem-frac 0.12 --device-limit-f +rac 0.7 --device-pool-frac 0.8 +distributed.worker - WARNING - Compute Failed +Function: subgraph_callable +args: ( label I1 I2 I3 I4 I5 I6 I7 I8 I9 ... C17 C18 C19 C20 C21 C22 C23 C24 C25 C26 +0 0 2.772589 5.808143 1.609438 2.397895 3.332205 0.000000 1.098612 4.442651 0.000000 ... -771205462 -1206449222 -864387787 359448199 -1761877609 357969245 -740331133 44548210 -842849922 -507617550 +1 0 0.000000 5.147494 1.945910 4.584968 1.098612 0.000000 0.000000 4.394449 2.302585 ... -1206449222 -1793932789 -1441487878 809724924 -1775758394 +2 0 2.639057 0.693147 0.693147 2.890372 0.000000 1.791759 0.000000 2.302585 2.833213 ... 1966974451 -1578429167 -1264946531 -2019528747 870435994 -322370806 -1701803791 2093085390 809724924 -317696227 +3 0 4.110874 7.392032 0.693147 5.937536 3.610918 0.000 +kwargs: {} +Exception: FileNotFoundError(2, 'No such file or directory') + +Traceback (most recent call last): +File ""examples/dask-nvtabular-criteo-benchmark.py"", line 373, in +main(parse_args()) +File ""examples/dask-nvtabular-criteo-benchmark.py"", line 195, in main +output_path=output_path, +File ""/nvtabular/nvtabular/workflow.py"", line 876, in apply +dtypes=dtypes, +File ""/nvtabular/nvtabular/workflow.py"", line 991, in build_and_process_graph +num_threads=num_io_threads, +File ""/nvtabular/nvtabular/workflow.py"", line 1080, in ddf_to_dataset +num_threads, +File ""/nvtabular/nvtabular/io/dask.py"", line 110, in _ddf_to_dataset +out = client.compute(out).result() +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/distributed/client.py"", line 225, in result +raise exc.with_traceback(tb) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/optimization.py"", line 961, in __call__ +return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args))) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 151, in get +result = _execute_task(task, cache) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 121, in _execute_task +return func(*(_execute_task(a, cache) for a in args)) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/utils.py"", line 29, in apply +return func(*args, **kwargs) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/core.py"", line 5298, in apply_and_enforce +df = func(*args, **kwargs) +File ""/nvtabular/nvtabular/workflow.py"", line 723, in _aggregated_op +gdf = logic(gdf, columns_ctx, cols_grp, target_cols, stats_context) +File ""/opt/conda/envs/rapids/lib/python3.7/contextlib.py"", line 74, in inner +return func(*args, **kwds) +File ""/nvtabular/nvtabular/ops/categorify.py"", line 365, in apply_op +cat_names=cat_names, +File ""/nvtabular/nvtabular/ops/categorify.py"", line 871, in _encode +cache, path, columns=selection_r, cache=cat_cache, cats_only=True +File ""/nvtabular/nvtabular/worker.py"", line 84, in fetch_table_data +with open(path, ""rb"") as f: +FileNotFoundError: [Errno 2] No such file or directory: 'gs://merlin-datasets/output/stats/categories/unique.C1.parquet'",FileNotFoundError +" def _close_writers(self): + md_dict = {} + for writer, path in zip(self.data_writers, self.data_paths): + fn = path.split(self.fs.sep)[-1] + md_dict[fn] = writer.close(metadata_file_path=fn) + for f in self.data_files: + f.close() + return md_dict"," def _close_writers(self): + md_dict = {} + for writer, path in zip(self.data_writers, self.data_paths): + fn = path.split(self.fs.sep)[-1] + md_dict[fn] = writer.close(metadata_file_path=fn) + return md_dict","[{'piece_type': 'error message', 'piece_content': '(rapids) root@dafff4b22f48:/nvtabular# python examples/dask-nvtabular-criteo-benchmark.py -d 0,1,2,3,4,5,6,7 --data-path gs://merlin-datasets/crit_int_pq --out-path gs://merlin-datasets/output --freq-limit 0 --part-mem-frac 0.12 --device-limit-f\\nrac 0.7 --device-pool-frac 0.8\\ndistributed.worker - WARNING - Compute Failed\\nFunction: subgraph_callable\\nargs: ( label I1 I2 I3 I4 I5 I6 I7 I8 I9 ... C17 C18 C19 C20 C21 C22 C23 C24 C25 C26\\n0 0 2.772589 5.808143 1.609438 2.397895 3.332205 0.000000 1.098612 4.442651 0.000000 ... -771205462 -1206449222 -864387787 359448199 -1761877609 357969245 -740331133 44548210 -842849922 -507617550\\n1 0 0.000000 5.147494 1.945910 4.584968 1.098612 0.000000 0.000000 4.394449 2.302585 ... -1206449222 -1793932789 -1441487878 809724924 -1775758394\\n2 0 2.639057 0.693147 0.693147 2.890372 0.000000 1.791759 0.000000 2.302585 2.833213 ... 1966974451 -1578429167 -1264946531 -2019528747 870435994 -322370806 -1701803791 2093085390 809724924 -317696227\\n3 0 4.110874 7.392032 0.693147 5.937536 3.610918 0.000\\nkwargs: {}\\nException: FileNotFoundError(2, \\'No such file or directory\\')\\n\\nTraceback (most recent call last):\\nFile ""examples/dask-nvtabular-criteo-benchmark.py"", line 373, in \\nmain(parse_args())\\nFile ""examples/dask-nvtabular-criteo-benchmark.py"", line 195, in main\\noutput_path=output_path,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 876, in apply\\ndtypes=dtypes,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 991, in build_and_process_graph\\nnum_threads=num_io_threads,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 1080, in ddf_to_dataset\\nnum_threads,\\nFile ""/nvtabular/nvtabular/io/dask.py"", line 110, in _ddf_to_dataset\\nout = client.compute(out).result()\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/distributed/client.py"", line 225, in result\\nraise exc.with_traceback(tb)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/optimization.py"", line 961, in __call__\\nreturn core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 151, in get\\nresult = _execute_task(task, cache)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 121, in _execute_task\\nreturn func(*(_execute_task(a, cache) for a in args))\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/utils.py"", line 29, in apply\\nreturn func(*args, **kwargs)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/core.py"", line 5298, in apply_and_enforce\\ndf = func(*args, **kwargs)\\nFile ""/nvtabular/nvtabular/workflow.py"", line 723, in _aggregated_op\\ngdf = logic(gdf, columns_ctx, cols_grp, target_cols, stats_context)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/contextlib.py"", line 74, in inner\\nreturn func(*args, **kwds)\\nFile ""/nvtabular/nvtabular/ops/categorify.py"", line 365, in apply_op\\ncat_names=cat_names,\\nFile ""/nvtabular/nvtabular/ops/categorify.py"", line 871, in _encode\\ncache, path, columns=selection_r, cache=cat_cache, cats_only=True\\nFile ""/nvtabular/nvtabular/worker.py"", line 84, in fetch_table_data\\nwith open(path, ""rb"") as f:\\nFileNotFoundError: [Errno 2] No such file or directory: \\'gs://merlin-datasets/output/stats/categories/unique.C1.parquet\\''}]","(rapids) root@dafff4b22f48:/nvtabular# python examples/dask-nvtabular-criteo-benchmark.py -d 0,1,2,3,4,5,6,7 --data-path gs://merlin-datasets/crit_int_pq --out-path gs://merlin-datasets/output --freq-limit 0 --part-mem-frac 0.12 --device-limit-f +rac 0.7 --device-pool-frac 0.8 +distributed.worker - WARNING - Compute Failed +Function: subgraph_callable +args: ( label I1 I2 I3 I4 I5 I6 I7 I8 I9 ... C17 C18 C19 C20 C21 C22 C23 C24 C25 C26 +0 0 2.772589 5.808143 1.609438 2.397895 3.332205 0.000000 1.098612 4.442651 0.000000 ... -771205462 -1206449222 -864387787 359448199 -1761877609 357969245 -740331133 44548210 -842849922 -507617550 +1 0 0.000000 5.147494 1.945910 4.584968 1.098612 0.000000 0.000000 4.394449 2.302585 ... -1206449222 -1793932789 -1441487878 809724924 -1775758394 +2 0 2.639057 0.693147 0.693147 2.890372 0.000000 1.791759 0.000000 2.302585 2.833213 ... 1966974451 -1578429167 -1264946531 -2019528747 870435994 -322370806 -1701803791 2093085390 809724924 -317696227 +3 0 4.110874 7.392032 0.693147 5.937536 3.610918 0.000 +kwargs: {} +Exception: FileNotFoundError(2, 'No such file or directory') + +Traceback (most recent call last): +File ""examples/dask-nvtabular-criteo-benchmark.py"", line 373, in +main(parse_args()) +File ""examples/dask-nvtabular-criteo-benchmark.py"", line 195, in main +output_path=output_path, +File ""/nvtabular/nvtabular/workflow.py"", line 876, in apply +dtypes=dtypes, +File ""/nvtabular/nvtabular/workflow.py"", line 991, in build_and_process_graph +num_threads=num_io_threads, +File ""/nvtabular/nvtabular/workflow.py"", line 1080, in ddf_to_dataset +num_threads, +File ""/nvtabular/nvtabular/io/dask.py"", line 110, in _ddf_to_dataset +out = client.compute(out).result() +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/distributed/client.py"", line 225, in result +raise exc.with_traceback(tb) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/optimization.py"", line 961, in __call__ +return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args))) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 151, in get +result = _execute_task(task, cache) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 121, in _execute_task +return func(*(_execute_task(a, cache) for a in args)) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/utils.py"", line 29, in apply +return func(*args, **kwargs) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/core.py"", line 5298, in apply_and_enforce +df = func(*args, **kwargs) +File ""/nvtabular/nvtabular/workflow.py"", line 723, in _aggregated_op +gdf = logic(gdf, columns_ctx, cols_grp, target_cols, stats_context) +File ""/opt/conda/envs/rapids/lib/python3.7/contextlib.py"", line 74, in inner +return func(*args, **kwds) +File ""/nvtabular/nvtabular/ops/categorify.py"", line 365, in apply_op +cat_names=cat_names, +File ""/nvtabular/nvtabular/ops/categorify.py"", line 871, in _encode +cache, path, columns=selection_r, cache=cat_cache, cats_only=True +File ""/nvtabular/nvtabular/worker.py"", line 84, in fetch_table_data +with open(path, ""rb"") as f: +FileNotFoundError: [Errno 2] No such file or directory: 'gs://merlin-datasets/output/stats/categories/unique.C1.parquet'",FileNotFoundError +"def fetch_table_data( + table_cache, path, cache=""disk"", cats_only=False, reader=None, columns=None, **kwargs +): + """"""Utility to retrieve a cudf DataFrame from a cache (and add the + DataFrame to a cache if the element is missing). Note that `cats_only=True` + results in optimized logic for the `Categorify` transformation. + """""" + table = table_cache.get(path, None) + if table and not isinstance(table, cudf.DataFrame): + if not cats_only: + return cudf.io.read_parquet(table, index=False) + df = cudf.io.read_parquet(table, index=False, columns=columns) + df.index.name = ""labels"" + df.reset_index(drop=False, inplace=True) + return df + + reader = reader or cudf.io.read_parquet + if table is None: + if cache in (""device"", ""disk""): + table = reader(path, index=False, columns=columns, **kwargs) + elif cache == ""host"": + if reader == cudf.io.read_parquet: + # If the file is already in parquet format, + # we can just move the same bytes to host memory + with fsspec.open(path, ""rb"") as f: + table_cache[path] = BytesIO(f.read()) + table = reader(table_cache[path], index=False, columns=columns, **kwargs) + else: + # Otherwise, we should convert the format to parquet + table = reader(path, index=False, columns=columns, **kwargs) + table_cache[path] = BytesIO() + table.to_parquet(table_cache[path]) + if cats_only: + table.index.name = ""labels"" + table.reset_index(drop=False, inplace=True) + if cache == ""device"": + table_cache[path] = table.copy(deep=False) + return table","def fetch_table_data( + table_cache, path, cache=""disk"", cats_only=False, reader=None, columns=None, **kwargs +): + """"""Utility to retrieve a cudf DataFrame from a cache (and add the + DataFrame to a cache if the element is missing). Note that `cats_only=True` + results in optimized logic for the `Categorify` transformation. + """""" + table = table_cache.get(path, None) + if table and not isinstance(table, cudf.DataFrame): + if not cats_only: + return cudf.io.read_parquet(table, index=False) + df = cudf.io.read_parquet(table, index=False, columns=columns) + df.index.name = ""labels"" + df.reset_index(drop=False, inplace=True) + return df + + reader = reader or cudf.io.read_parquet + if table is None: + if cache in (""device"", ""disk""): + table = reader(path, index=False, columns=columns, **kwargs) + elif cache == ""host"": + if reader == cudf.io.read_parquet: + # If the file is already in parquet format, + # we can just move the same bytes to host memory + with open(path, ""rb"") as f: + table_cache[path] = BytesIO(f.read()) + table = reader(table_cache[path], index=False, columns=columns, **kwargs) + else: + # Otherwise, we should convert the format to parquet + table = reader(path, index=False, columns=columns, **kwargs) + table_cache[path] = BytesIO() + table.to_parquet(table_cache[path]) + if cats_only: + table.index.name = ""labels"" + table.reset_index(drop=False, inplace=True) + if cache == ""device"": + table_cache[path] = table.copy(deep=False) + return table","[{'piece_type': 'error message', 'piece_content': '(rapids) root@dafff4b22f48:/nvtabular# python examples/dask-nvtabular-criteo-benchmark.py -d 0,1,2,3,4,5,6,7 --data-path gs://merlin-datasets/crit_int_pq --out-path gs://merlin-datasets/output --freq-limit 0 --part-mem-frac 0.12 --device-limit-f\\nrac 0.7 --device-pool-frac 0.8\\ndistributed.worker - WARNING - Compute Failed\\nFunction: subgraph_callable\\nargs: ( label I1 I2 I3 I4 I5 I6 I7 I8 I9 ... C17 C18 C19 C20 C21 C22 C23 C24 C25 C26\\n0 0 2.772589 5.808143 1.609438 2.397895 3.332205 0.000000 1.098612 4.442651 0.000000 ... -771205462 -1206449222 -864387787 359448199 -1761877609 357969245 -740331133 44548210 -842849922 -507617550\\n1 0 0.000000 5.147494 1.945910 4.584968 1.098612 0.000000 0.000000 4.394449 2.302585 ... -1206449222 -1793932789 -1441487878 809724924 -1775758394\\n2 0 2.639057 0.693147 0.693147 2.890372 0.000000 1.791759 0.000000 2.302585 2.833213 ... 1966974451 -1578429167 -1264946531 -2019528747 870435994 -322370806 -1701803791 2093085390 809724924 -317696227\\n3 0 4.110874 7.392032 0.693147 5.937536 3.610918 0.000\\nkwargs: {}\\nException: FileNotFoundError(2, \\'No such file or directory\\')\\n\\nTraceback (most recent call last):\\nFile ""examples/dask-nvtabular-criteo-benchmark.py"", line 373, in \\nmain(parse_args())\\nFile ""examples/dask-nvtabular-criteo-benchmark.py"", line 195, in main\\noutput_path=output_path,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 876, in apply\\ndtypes=dtypes,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 991, in build_and_process_graph\\nnum_threads=num_io_threads,\\nFile ""/nvtabular/nvtabular/workflow.py"", line 1080, in ddf_to_dataset\\nnum_threads,\\nFile ""/nvtabular/nvtabular/io/dask.py"", line 110, in _ddf_to_dataset\\nout = client.compute(out).result()\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/distributed/client.py"", line 225, in result\\nraise exc.with_traceback(tb)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/optimization.py"", line 961, in __call__\\nreturn core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 151, in get\\nresult = _execute_task(task, cache)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 121, in _execute_task\\nreturn func(*(_execute_task(a, cache) for a in args))\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/utils.py"", line 29, in apply\\nreturn func(*args, **kwargs)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/core.py"", line 5298, in apply_and_enforce\\ndf = func(*args, **kwargs)\\nFile ""/nvtabular/nvtabular/workflow.py"", line 723, in _aggregated_op\\ngdf = logic(gdf, columns_ctx, cols_grp, target_cols, stats_context)\\nFile ""/opt/conda/envs/rapids/lib/python3.7/contextlib.py"", line 74, in inner\\nreturn func(*args, **kwds)\\nFile ""/nvtabular/nvtabular/ops/categorify.py"", line 365, in apply_op\\ncat_names=cat_names,\\nFile ""/nvtabular/nvtabular/ops/categorify.py"", line 871, in _encode\\ncache, path, columns=selection_r, cache=cat_cache, cats_only=True\\nFile ""/nvtabular/nvtabular/worker.py"", line 84, in fetch_table_data\\nwith open(path, ""rb"") as f:\\nFileNotFoundError: [Errno 2] No such file or directory: \\'gs://merlin-datasets/output/stats/categories/unique.C1.parquet\\''}]","(rapids) root@dafff4b22f48:/nvtabular# python examples/dask-nvtabular-criteo-benchmark.py -d 0,1,2,3,4,5,6,7 --data-path gs://merlin-datasets/crit_int_pq --out-path gs://merlin-datasets/output --freq-limit 0 --part-mem-frac 0.12 --device-limit-f +rac 0.7 --device-pool-frac 0.8 +distributed.worker - WARNING - Compute Failed +Function: subgraph_callable +args: ( label I1 I2 I3 I4 I5 I6 I7 I8 I9 ... C17 C18 C19 C20 C21 C22 C23 C24 C25 C26 +0 0 2.772589 5.808143 1.609438 2.397895 3.332205 0.000000 1.098612 4.442651 0.000000 ... -771205462 -1206449222 -864387787 359448199 -1761877609 357969245 -740331133 44548210 -842849922 -507617550 +1 0 0.000000 5.147494 1.945910 4.584968 1.098612 0.000000 0.000000 4.394449 2.302585 ... -1206449222 -1793932789 -1441487878 809724924 -1775758394 +2 0 2.639057 0.693147 0.693147 2.890372 0.000000 1.791759 0.000000 2.302585 2.833213 ... 1966974451 -1578429167 -1264946531 -2019528747 870435994 -322370806 -1701803791 2093085390 809724924 -317696227 +3 0 4.110874 7.392032 0.693147 5.937536 3.610918 0.000 +kwargs: {} +Exception: FileNotFoundError(2, 'No such file or directory') + +Traceback (most recent call last): +File ""examples/dask-nvtabular-criteo-benchmark.py"", line 373, in +main(parse_args()) +File ""examples/dask-nvtabular-criteo-benchmark.py"", line 195, in main +output_path=output_path, +File ""/nvtabular/nvtabular/workflow.py"", line 876, in apply +dtypes=dtypes, +File ""/nvtabular/nvtabular/workflow.py"", line 991, in build_and_process_graph +num_threads=num_io_threads, +File ""/nvtabular/nvtabular/workflow.py"", line 1080, in ddf_to_dataset +num_threads, +File ""/nvtabular/nvtabular/io/dask.py"", line 110, in _ddf_to_dataset +out = client.compute(out).result() +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/distributed/client.py"", line 225, in result +raise exc.with_traceback(tb) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/optimization.py"", line 961, in __call__ +return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args))) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 151, in get +result = _execute_task(task, cache) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/core.py"", line 121, in _execute_task +return func(*(_execute_task(a, cache) for a in args)) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/utils.py"", line 29, in apply +return func(*args, **kwargs) +File ""/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/core.py"", line 5298, in apply_and_enforce +df = func(*args, **kwargs) +File ""/nvtabular/nvtabular/workflow.py"", line 723, in _aggregated_op +gdf = logic(gdf, columns_ctx, cols_grp, target_cols, stats_context) +File ""/opt/conda/envs/rapids/lib/python3.7/contextlib.py"", line 74, in inner +return func(*args, **kwds) +File ""/nvtabular/nvtabular/ops/categorify.py"", line 365, in apply_op +cat_names=cat_names, +File ""/nvtabular/nvtabular/ops/categorify.py"", line 871, in _encode +cache, path, columns=selection_r, cache=cat_cache, cats_only=True +File ""/nvtabular/nvtabular/worker.py"", line 84, in fetch_table_data +with open(path, ""rb"") as f: +FileNotFoundError: [Errno 2] No such file or directory: 'gs://merlin-datasets/output/stats/categories/unique.C1.parquet'",FileNotFoundError +"def _chunkwise_moments(df): + df2 = cudf.DataFrame() + for col in df.columns: + df2[col] = df[col].astype(""float64"").pow(2) + vals = { + ""df-count"": df.count().to_frame().transpose(), + ""df-sum"": df.sum().astype(""float64"").to_frame().transpose(), + ""df2-sum"": df2.sum().to_frame().transpose(), + } + # NOTE: Perhaps we should convert to pandas here + # (since we know the results should be small)? + del df2 + return vals","def _chunkwise_moments(df): + df2 = cudf.DataFrame() + for col in df.columns: + df2[col] = df[col].astype(""float64"").pow(2) + vals = { + ""df-count"": df.count().to_frame().transpose(), + ""df-sum"": df.sum().to_frame().transpose(), + ""df2-sum"": df2.sum().to_frame().transpose(), + } + # NOTE: Perhaps we should convert to pandas here + # (since we know the results should be small)? + del df2 + return vals","[{'piece_type': 'error message', 'piece_content': '/opt/conda/envs/rapids/lib/python3.7/site-packages/pandas/core/series.py:726: RuntimeWarning: invalid value encountered in sqrt\\nresult = getattr(ufunc, method)(*inputs, **kwargs)\\n---------------------------------------------------------------------------\\nValueError Traceback (most recent call last)\\n in \\n\\n/nvtabular0.3/NVTabular/nvtabular/workflow.py in apply(self, dataset, apply_offline, record_stats, shuffle, output_path, output_format, out_files_per_proc, num_io_threads, dtypes)\\n869 out_files_per_proc=out_files_per_proc,\\n870 num_io_threads=num_io_threads,\\n--> 871 dtypes=dtypes,\\n872 )\\n873 else:\\n\\n/nvtabular0.3/NVTabular/nvtabular/workflow.py in build_and_process_graph(self, dataset, end_phase, output_path, record_stats, shuffle, output_format, out_files_per_proc, apply_ops, num_io_threads, dtypes)\\n968 self._base_phase = 0 # Set _base_phase\\n969 for idx, _ in enumerate(self.phases[:end]):\\n--> 970 self.exec_phase(idx, record_stats=record_stats, update_ddf=(idx == (end - 1)))\\n971 self._base_phase = 0 # Re-Set _base_phase\\n972\\n\\n/nvtabular0.3/NVTabular/nvtabular/workflow.py in exec_phase(self, phase_index, record_stats, update_ddf)\\n755 _ddf = self.get_ddf()\\n756 if transforms:\\n--> 757 _ddf = self._aggregated_dask_transform(_ddf, transforms)\\n758\\n759 stats = []\\n\\n/nvtabular0.3/NVTabular/nvtabular/workflow.py in _aggregated_dask_transform(self, ddf, transforms)\\n724 for transform in transforms:\\n725 columns_ctx, cols_grp, target_cols, logic, stats_context = transform\\n--> 726 meta = logic(meta, columns_ctx, cols_grp, target_cols, stats_context)\\n727 return ddf.map_partitions(self.__class__._aggregated_op, transforms, meta=meta)\\n728\\n\\n/nvtabular0.3/NVTabular/nvtabular/ops/transform_operator.py in apply_op(self, gdf, columns_ctx, input_cols, target_cols, stats_context)\\n89 new_gdf = self.op_logic(gdf, target_columns, stats_context=stats_context)\\n90 self.update_columns_ctx(columns_ctx, input_cols, new_gdf.columns, target_columns)\\n---> 91 return self.assemble_new_df(gdf, new_gdf, target_columns)\\n92\\n93 def assemble_new_df(self, origin_gdf, new_gdf, target_columns):\\n\\n/nvtabular0.3/NVTabular/nvtabular/ops/transform_operator.py in assemble_new_df(self, origin_gdf, new_gdf, target_columns)\\n96 return new_gdf\\n97 else:\\n---> 98 origin_gdf[target_columns] = new_gdf\\n99 return origin_gdf\\n100 return cudf.concat([origin_gdf, new_gdf], axis=1)\\n\\n/opt/conda/envs/rapids/lib/python3.7/contextlib.py in inner(*args, **kwds)\\n72 def inner(*args, **kwds):\\n73 with self._recreate_cm():\\n---> 74 return func(*args, **kwds)\\n75 return inner\\n76\\n\\n/opt/conda/envs/rapids/lib/python3.7/site-packages/cudf/core/dataframe.py in __setitem__(self, arg, value)\\n777 replace_df=value,\\n778 input_cols=arg,\\n--> 779 mask=None,\\n780 )\\n781 else:\\n\\n/opt/conda/envs/rapids/lib/python3.7/site-packages/cudf/core/dataframe.py in _setitem_with_dataframe(input_df, replace_df, input_cols, mask)\\n7266 if len(input_cols) != len(replace_df.columns):\\n7267 raise ValueError(\\n-> 7268 ""Number of Input Columns must be same replacement Dataframe""\\n7269 )\\n7270\\n\\nValueError: Number of Input Columns must be same replacement Dataframe'}, {'piece_type': 'other', 'piece_content': 'ds = nvt.Dataset(INPUT_PATH, engine=""parquet"", part_size=""1000MB"")\\n\\ncat_names = []\\ncont_names = [\\'NetworkTestLatency\\']\\nlabel_name = []\\n\\n# Initalize our Workflow\\nworkflow = nvt.Workflow(cat_names=cat_names, cont_names=cont_names, label_name=label_name)\\n\\n\\n# Add Normalize to the workflow for continuous columns\\nworkflow.add_cont_feature(nvt.ops.Normalize())\\n\\n# Finalize the Workflow\\nworkflow.finalize()\\n\\n%%time\\n\\nworkflow.apply(\\nds,\\noutput_format=""parquet"",\\noutput_path=OUTPUT_PATH,\\nshuffle=None,\\nout_files_per_proc=1,\\n)'}]","/opt/conda/envs/rapids/lib/python3.7/site-packages/pandas/core/series.py:726: RuntimeWarning: invalid value encountered in sqrt +result = getattr(ufunc, method)(*inputs, **kwargs) +--------------------------------------------------------------------------- +ValueError Traceback (most recent call last) + in + +/nvtabular0.3/NVTabular/nvtabular/workflow.py in apply(self, dataset, apply_offline, record_stats, shuffle, output_path, output_format, out_files_per_proc, num_io_threads, dtypes) +869 out_files_per_proc=out_files_per_proc, +870 num_io_threads=num_io_threads, +--> 871 dtypes=dtypes, +872 ) +873 else: + +/nvtabular0.3/NVTabular/nvtabular/workflow.py in build_and_process_graph(self, dataset, end_phase, output_path, record_stats, shuffle, output_format, out_files_per_proc, apply_ops, num_io_threads, dtypes) +968 self._base_phase = 0 # Set _base_phase +969 for idx, _ in enumerate(self.phases[:end]): +--> 970 self.exec_phase(idx, record_stats=record_stats, update_ddf=(idx == (end - 1))) +971 self._base_phase = 0 # Re-Set _base_phase +972 + +/nvtabular0.3/NVTabular/nvtabular/workflow.py in exec_phase(self, phase_index, record_stats, update_ddf) +755 _ddf = self.get_ddf() +756 if transforms: +--> 757 _ddf = self._aggregated_dask_transform(_ddf, transforms) +758 +759 stats = [] + +/nvtabular0.3/NVTabular/nvtabular/workflow.py in _aggregated_dask_transform(self, ddf, transforms) +724 for transform in transforms: +725 columns_ctx, cols_grp, target_cols, logic, stats_context = transform +--> 726 meta = logic(meta, columns_ctx, cols_grp, target_cols, stats_context) +727 return ddf.map_partitions(self.__class__._aggregated_op, transforms, meta=meta) +728 + +/nvtabular0.3/NVTabular/nvtabular/ops/transform_operator.py in apply_op(self, gdf, columns_ctx, input_cols, target_cols, stats_context) +89 new_gdf = self.op_logic(gdf, target_columns, stats_context=stats_context) +90 self.update_columns_ctx(columns_ctx, input_cols, new_gdf.columns, target_columns) +---> 91 return self.assemble_new_df(gdf, new_gdf, target_columns) +92 +93 def assemble_new_df(self, origin_gdf, new_gdf, target_columns): + +/nvtabular0.3/NVTabular/nvtabular/ops/transform_operator.py in assemble_new_df(self, origin_gdf, new_gdf, target_columns) +96 return new_gdf +97 else: +---> 98 origin_gdf[target_columns] = new_gdf +99 return origin_gdf +100 return cudf.concat([origin_gdf, new_gdf], axis=1) + +/opt/conda/envs/rapids/lib/python3.7/contextlib.py in inner(*args, **kwds) +72 def inner(*args, **kwds): +73 with self._recreate_cm(): +---> 74 return func(*args, **kwds) +75 return inner +76 + +/opt/conda/envs/rapids/lib/python3.7/site-packages/cudf/core/dataframe.py in __setitem__(self, arg, value) +777 replace_df=value, +778 input_cols=arg, +--> 779 mask=None, +780 ) +781 else: + +/opt/conda/envs/rapids/lib/python3.7/site-packages/cudf/core/dataframe.py in _setitem_with_dataframe(input_df, replace_df, input_cols, mask) +7266 if len(input_cols) != len(replace_df.columns): +7267 raise ValueError( +-> 7268 ""Number of Input Columns must be same replacement Dataframe"" +7269 ) +7270 + +ValueError: Number of Input Columns must be same replacement Dataframe",ValueError +" def to_ddf(self, columns=None): + return dask_cudf.read_parquet( + self.paths, + columns=columns, + # can't omit reading the index in if we aren't being passed columns + index=None if columns is None else False, + gather_statistics=False, + split_row_groups=self.row_groups_per_part, + storage_options=self.storage_options, + )"," def to_ddf(self, columns=None): + return dask_cudf.read_parquet( + self.paths, + columns=columns, + index=False, + gather_statistics=False, + split_row_groups=self.row_groups_per_part, + storage_options=self.storage_options, + )","[{'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nValueError Traceback (most recent call last)\\n in \\n2 valid_dataset = nvt.Dataset(OUTPUT_BUCKET_FOLDER+\\'valid_gdf.parquet\\', part_mem_fraction=0.12)\\n3\\n----> 4 workflow.apply(train_dataset, record_stats=True, output_path=output_train_dir, shuffle=True, out_files_per_proc=5)\\n5 workflow.apply(valid_dataset, record_stats=False, output_path=output_valid_dir, shuffle=False, out_files_per_proc=5)\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in apply(self, dataset, apply_offline, record_stats, shuffle, output_path, output_format, out_files_per_proc, num_io_threads, dtypes)\\n782 out_files_per_proc=out_files_per_proc,\\n783 num_io_threads=num_io_threads,\\n--> 784 dtypes=dtypes,\\n785 )\\n786 else:\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in build_and_process_graph(self, dataset, end_phase, output_path, record_stats, shuffle, output_format, out_files_per_proc, apply_ops, num_io_threads, dtypes)\\n885 self._base_phase = 0 # Set _base_phase\\n886 for idx, _ in enumerate(self.phases[:end]):\\n--> 887 self.exec_phase(idx, record_stats=record_stats, update_ddf=(idx == (end - 1)))\\n888 self._base_phase = 0 # Re-Set _base_phase\\n889\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in exec_phase(self, phase_index, record_stats, update_ddf)\\n631\\n632 # Perform transforms as single dask task (per ddf partition)\\n--> 633 _ddf = self.get_ddf()\\n634 if transforms:\\n635 _ddf = self._aggregated_dask_transform(_ddf, transforms)\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in get_ddf(self)\\n587 elif isinstance(self.ddf, Dataset):\\n588 columns = self.columns_ctx[""all""][""base""]\\n--> 589 return self.ddf.to_ddf(columns=columns, shuffle=self._shuffle_parts)\\n590 return self.ddf\\n591\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/io/dataset.py in to_ddf(self, columns, shuffle, seed)\\n263 """"""\\n264 # Use DatasetEngine to create ddf\\n--> 265 ddf = self.engine.to_ddf(columns=columns)\\n266\\n267 # Shuffle the partitions of ddf (optional)\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/io/parquet.py in to_ddf(self, columns)\\n102 gather_statistics=False,\\n103 split_row_groups=self.row_groups_per_part,\\n--> 104 storage_options=self.storage_options,\\n105 )\\n106\\n\\n/opt/conda/envs/rapids/lib/python3.7/site-packages/dask_cudf/io/parquet.py in read_parquet(path, columns, split_row_groups, row_groups_per_part, **kwargs)\\n192 split_row_groups=split_row_groups,\\n193 engine=CudfEngine,\\n--> 194 **kwargs,\\n195 )\\n196\\n\\n/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/io/parquet/core.py in read_parquet(path, columns, filters, categories, index, storage_options, engine, gather_statistics, split_row_groups, chunksize, **kwargs)\\n248 # Modify `meta` dataframe accordingly\\n249 meta, index, columns = set_index_columns(\\n--> 250 meta, index, columns, index_in_columns, auto_index_allowed\\n251 )\\n252 if meta.index.name == NONE_LABEL:\\n\\n/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/io/parquet/core.py in set_index_columns(meta, index, columns, index_in_columns, auto_index_allowed)\\n771 ""The following columns were not found in the dataset %s\\\\n""\\n772 ""The following columns were found %s""\\n--> 773 % (set(columns) - set(meta.columns), meta.columns)\\n774 )\\n775\\n\\nValueError: The following columns were not found in the dataset {\\'document_id_promo_count\\', \\'publish_time_days_since_published\\', \\'campaign_id_clicked_sum_ctr\\', \\'ad_id_count\\', \\'ad_id_clicked_sum_ctr\\', \\'source_id_clicked_sum_ctr\\', \\'publish_time_promo_days_since_published\\', \\'advertiser_id_clicked_sum_ctr\\', \\'document_id_promo_clicked_sum_ctr\\', \\'publisher_id_clicked_sum_ctr\\', \\'geo_location_country\\', \\'geo_location_state\\'}\\nThe following columns were found Index([\\'display_id\\', \\'ad_id\\', \\'clicked\\', \\'uuid\\', \\'document_id\\', \\'timestamp\\',\\n\\'platform\\', \\'geo_location\\', \\'document_id_promo\\', \\'campaign_id\\',\\n\\'advertiser_id\\', \\'source_id\\', \\'publisher_id\\', \\'publish_time\\',\\n\\'source_id_promo\\', \\'publisher_id_promo\\', \\'publish_time_promo\\',\\n\\'day_event\\'],\\ndtype=\\'object\\')'}, {'piece_type': 'reproducing source code', 'piece_content': 'import cudf\\nimport nvtabular as nvt\\nfrom nvtabular.ops import LambdaOp, Categorify\\n\\n# Stripped down dataset with geo_locaiton codes like in outbrains\\ndf = cudf.DataFrame({""geo_location"": [""US>CA"", ""CA>BC"", ""US>TN>659""]})\\n\\n# defining a simple workflow that strips out the country code from the first two digits of the\\n# geo_location code and sticks in a new \\'geo_location_country\\' field\\nCATEGORICAL_COLUMNS = [""geo_location"", ""geo_location_country""]\\nworkflow = nvt.Workflow(cat_names=CATEGORICAL_COLUMNS, cont_names=[], label_name=[])\\nworkflow.add_feature(\\n[\\nLambdaOp(\\nop_name=""country"",\\nf=lambda col, gdf: col.str.slice(0, 2),\\ncolumns=[""geo_location""],\\nreplace=False,\\n),\\nCategorify(),\\n]\\n)\\nworkflow.finalize()\\n\\n# This fails because \\'geo_location_country\\' isn\\'t in the parquet file, but we\\'re listing\\n# as a column\\ndf.to_parquet(""geo.parquet"")\\nworkflow.apply(nvt.Dataset(""geo.parquet""), output_path=None)'}]","--------------------------------------------------------------------------- +ValueError Traceback (most recent call last) + in +2 valid_dataset = nvt.Dataset(OUTPUT_BUCKET_FOLDER+'valid_gdf.parquet', part_mem_fraction=0.12) +3 +----> 4 workflow.apply(train_dataset, record_stats=True, output_path=output_train_dir, shuffle=True, out_files_per_proc=5) +5 workflow.apply(valid_dataset, record_stats=False, output_path=output_valid_dir, shuffle=False, out_files_per_proc=5) + +/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in apply(self, dataset, apply_offline, record_stats, shuffle, output_path, output_format, out_files_per_proc, num_io_threads, dtypes) +782 out_files_per_proc=out_files_per_proc, +783 num_io_threads=num_io_threads, +--> 784 dtypes=dtypes, +785 ) +786 else: + +/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in build_and_process_graph(self, dataset, end_phase, output_path, record_stats, shuffle, output_format, out_files_per_proc, apply_ops, num_io_threads, dtypes) +885 self._base_phase = 0 # Set _base_phase +886 for idx, _ in enumerate(self.phases[:end]): +--> 887 self.exec_phase(idx, record_stats=record_stats, update_ddf=(idx == (end - 1))) +888 self._base_phase = 0 # Re-Set _base_phase +889 + +/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in exec_phase(self, phase_index, record_stats, update_ddf) +631 +632 # Perform transforms as single dask task (per ddf partition) +--> 633 _ddf = self.get_ddf() +634 if transforms: +635 _ddf = self._aggregated_dask_transform(_ddf, transforms) + +/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in get_ddf(self) +587 elif isinstance(self.ddf, Dataset): +588 columns = self.columns_ctx[""all""][""base""] +--> 589 return self.ddf.to_ddf(columns=columns, shuffle=self._shuffle_parts) +590 return self.ddf +591 + +/rapids/notebooks/benf/NVTabular/nvtabular/io/dataset.py in to_ddf(self, columns, shuffle, seed) +263 """""" +264 # Use DatasetEngine to create ddf +--> 265 ddf = self.engine.to_ddf(columns=columns) +266 +267 # Shuffle the partitions of ddf (optional) + +/rapids/notebooks/benf/NVTabular/nvtabular/io/parquet.py in to_ddf(self, columns) +102 gather_statistics=False, +103 split_row_groups=self.row_groups_per_part, +--> 104 storage_options=self.storage_options, +105 ) +106 + +/opt/conda/envs/rapids/lib/python3.7/site-packages/dask_cudf/io/parquet.py in read_parquet(path, columns, split_row_groups, row_groups_per_part, **kwargs) +192 split_row_groups=split_row_groups, +193 engine=CudfEngine, +--> 194 **kwargs, +195 ) +196 + +/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/io/parquet/core.py in read_parquet(path, columns, filters, categories, index, storage_options, engine, gather_statistics, split_row_groups, chunksize, **kwargs) +248 # Modify `meta` dataframe accordingly +249 meta, index, columns = set_index_columns( +--> 250 meta, index, columns, index_in_columns, auto_index_allowed +251 ) +252 if meta.index.name == NONE_LABEL: + +/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/io/parquet/core.py in set_index_columns(meta, index, columns, index_in_columns, auto_index_allowed) +771 ""The following columns were not found in the dataset %s\\n"" +772 ""The following columns were found %s"" +--> 773 % (set(columns) - set(meta.columns), meta.columns) +774 ) +775 + +ValueError: The following columns were not found in the dataset {'document_id_promo_count', 'publish_time_days_since_published', 'campaign_id_clicked_sum_ctr', 'ad_id_count', 'ad_id_clicked_sum_ctr', 'source_id_clicked_sum_ctr', 'publish_time_promo_days_since_published', 'advertiser_id_clicked_sum_ctr', 'document_id_promo_clicked_sum_ctr', 'publisher_id_clicked_sum_ctr', 'geo_location_country', 'geo_location_state'} +The following columns were found Index(['display_id', 'ad_id', 'clicked', 'uuid', 'document_id', 'timestamp', +'platform', 'geo_location', 'document_id_promo', 'campaign_id', +'advertiser_id', 'source_id', 'publisher_id', 'publish_time', +'source_id_promo', 'publisher_id_promo', 'publish_time_promo', +'day_event'], +dtype='object')",ValueError +" def get_ddf(self): + if self.ddf is None: + raise ValueError(""No dask_cudf frame available."") + elif isinstance(self.ddf, Dataset): + # Right now we can't distinguish between input columns and generated columns + # in the dataset, we don't limit the columm set right now in the to_ddf call + # (https://github.com/NVIDIA/NVTabular/issues/409 ) + return self.ddf.to_ddf(shuffle=self._shuffle_parts) + return self.ddf"," def get_ddf(self): + if self.ddf is None: + raise ValueError(""No dask_cudf frame available."") + elif isinstance(self.ddf, Dataset): + columns = self.columns_ctx[""all""][""base""] + return self.ddf.to_ddf(columns=columns, shuffle=self._shuffle_parts) + return self.ddf","[{'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nValueError Traceback (most recent call last)\\n in \\n2 valid_dataset = nvt.Dataset(OUTPUT_BUCKET_FOLDER+\\'valid_gdf.parquet\\', part_mem_fraction=0.12)\\n3\\n----> 4 workflow.apply(train_dataset, record_stats=True, output_path=output_train_dir, shuffle=True, out_files_per_proc=5)\\n5 workflow.apply(valid_dataset, record_stats=False, output_path=output_valid_dir, shuffle=False, out_files_per_proc=5)\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in apply(self, dataset, apply_offline, record_stats, shuffle, output_path, output_format, out_files_per_proc, num_io_threads, dtypes)\\n782 out_files_per_proc=out_files_per_proc,\\n783 num_io_threads=num_io_threads,\\n--> 784 dtypes=dtypes,\\n785 )\\n786 else:\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in build_and_process_graph(self, dataset, end_phase, output_path, record_stats, shuffle, output_format, out_files_per_proc, apply_ops, num_io_threads, dtypes)\\n885 self._base_phase = 0 # Set _base_phase\\n886 for idx, _ in enumerate(self.phases[:end]):\\n--> 887 self.exec_phase(idx, record_stats=record_stats, update_ddf=(idx == (end - 1)))\\n888 self._base_phase = 0 # Re-Set _base_phase\\n889\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in exec_phase(self, phase_index, record_stats, update_ddf)\\n631\\n632 # Perform transforms as single dask task (per ddf partition)\\n--> 633 _ddf = self.get_ddf()\\n634 if transforms:\\n635 _ddf = self._aggregated_dask_transform(_ddf, transforms)\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in get_ddf(self)\\n587 elif isinstance(self.ddf, Dataset):\\n588 columns = self.columns_ctx[""all""][""base""]\\n--> 589 return self.ddf.to_ddf(columns=columns, shuffle=self._shuffle_parts)\\n590 return self.ddf\\n591\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/io/dataset.py in to_ddf(self, columns, shuffle, seed)\\n263 """"""\\n264 # Use DatasetEngine to create ddf\\n--> 265 ddf = self.engine.to_ddf(columns=columns)\\n266\\n267 # Shuffle the partitions of ddf (optional)\\n\\n/rapids/notebooks/benf/NVTabular/nvtabular/io/parquet.py in to_ddf(self, columns)\\n102 gather_statistics=False,\\n103 split_row_groups=self.row_groups_per_part,\\n--> 104 storage_options=self.storage_options,\\n105 )\\n106\\n\\n/opt/conda/envs/rapids/lib/python3.7/site-packages/dask_cudf/io/parquet.py in read_parquet(path, columns, split_row_groups, row_groups_per_part, **kwargs)\\n192 split_row_groups=split_row_groups,\\n193 engine=CudfEngine,\\n--> 194 **kwargs,\\n195 )\\n196\\n\\n/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/io/parquet/core.py in read_parquet(path, columns, filters, categories, index, storage_options, engine, gather_statistics, split_row_groups, chunksize, **kwargs)\\n248 # Modify `meta` dataframe accordingly\\n249 meta, index, columns = set_index_columns(\\n--> 250 meta, index, columns, index_in_columns, auto_index_allowed\\n251 )\\n252 if meta.index.name == NONE_LABEL:\\n\\n/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/io/parquet/core.py in set_index_columns(meta, index, columns, index_in_columns, auto_index_allowed)\\n771 ""The following columns were not found in the dataset %s\\\\n""\\n772 ""The following columns were found %s""\\n--> 773 % (set(columns) - set(meta.columns), meta.columns)\\n774 )\\n775\\n\\nValueError: The following columns were not found in the dataset {\\'document_id_promo_count\\', \\'publish_time_days_since_published\\', \\'campaign_id_clicked_sum_ctr\\', \\'ad_id_count\\', \\'ad_id_clicked_sum_ctr\\', \\'source_id_clicked_sum_ctr\\', \\'publish_time_promo_days_since_published\\', \\'advertiser_id_clicked_sum_ctr\\', \\'document_id_promo_clicked_sum_ctr\\', \\'publisher_id_clicked_sum_ctr\\', \\'geo_location_country\\', \\'geo_location_state\\'}\\nThe following columns were found Index([\\'display_id\\', \\'ad_id\\', \\'clicked\\', \\'uuid\\', \\'document_id\\', \\'timestamp\\',\\n\\'platform\\', \\'geo_location\\', \\'document_id_promo\\', \\'campaign_id\\',\\n\\'advertiser_id\\', \\'source_id\\', \\'publisher_id\\', \\'publish_time\\',\\n\\'source_id_promo\\', \\'publisher_id_promo\\', \\'publish_time_promo\\',\\n\\'day_event\\'],\\ndtype=\\'object\\')'}, {'piece_type': 'reproducing source code', 'piece_content': 'import cudf\\nimport nvtabular as nvt\\nfrom nvtabular.ops import LambdaOp, Categorify\\n\\n# Stripped down dataset with geo_locaiton codes like in outbrains\\ndf = cudf.DataFrame({""geo_location"": [""US>CA"", ""CA>BC"", ""US>TN>659""]})\\n\\n# defining a simple workflow that strips out the country code from the first two digits of the\\n# geo_location code and sticks in a new \\'geo_location_country\\' field\\nCATEGORICAL_COLUMNS = [""geo_location"", ""geo_location_country""]\\nworkflow = nvt.Workflow(cat_names=CATEGORICAL_COLUMNS, cont_names=[], label_name=[])\\nworkflow.add_feature(\\n[\\nLambdaOp(\\nop_name=""country"",\\nf=lambda col, gdf: col.str.slice(0, 2),\\ncolumns=[""geo_location""],\\nreplace=False,\\n),\\nCategorify(),\\n]\\n)\\nworkflow.finalize()\\n\\n# This fails because \\'geo_location_country\\' isn\\'t in the parquet file, but we\\'re listing\\n# as a column\\ndf.to_parquet(""geo.parquet"")\\nworkflow.apply(nvt.Dataset(""geo.parquet""), output_path=None)'}]","--------------------------------------------------------------------------- +ValueError Traceback (most recent call last) + in +2 valid_dataset = nvt.Dataset(OUTPUT_BUCKET_FOLDER+'valid_gdf.parquet', part_mem_fraction=0.12) +3 +----> 4 workflow.apply(train_dataset, record_stats=True, output_path=output_train_dir, shuffle=True, out_files_per_proc=5) +5 workflow.apply(valid_dataset, record_stats=False, output_path=output_valid_dir, shuffle=False, out_files_per_proc=5) + +/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in apply(self, dataset, apply_offline, record_stats, shuffle, output_path, output_format, out_files_per_proc, num_io_threads, dtypes) +782 out_files_per_proc=out_files_per_proc, +783 num_io_threads=num_io_threads, +--> 784 dtypes=dtypes, +785 ) +786 else: + +/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in build_and_process_graph(self, dataset, end_phase, output_path, record_stats, shuffle, output_format, out_files_per_proc, apply_ops, num_io_threads, dtypes) +885 self._base_phase = 0 # Set _base_phase +886 for idx, _ in enumerate(self.phases[:end]): +--> 887 self.exec_phase(idx, record_stats=record_stats, update_ddf=(idx == (end - 1))) +888 self._base_phase = 0 # Re-Set _base_phase +889 + +/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in exec_phase(self, phase_index, record_stats, update_ddf) +631 +632 # Perform transforms as single dask task (per ddf partition) +--> 633 _ddf = self.get_ddf() +634 if transforms: +635 _ddf = self._aggregated_dask_transform(_ddf, transforms) + +/rapids/notebooks/benf/NVTabular/nvtabular/workflow.py in get_ddf(self) +587 elif isinstance(self.ddf, Dataset): +588 columns = self.columns_ctx[""all""][""base""] +--> 589 return self.ddf.to_ddf(columns=columns, shuffle=self._shuffle_parts) +590 return self.ddf +591 + +/rapids/notebooks/benf/NVTabular/nvtabular/io/dataset.py in to_ddf(self, columns, shuffle, seed) +263 """""" +264 # Use DatasetEngine to create ddf +--> 265 ddf = self.engine.to_ddf(columns=columns) +266 +267 # Shuffle the partitions of ddf (optional) + +/rapids/notebooks/benf/NVTabular/nvtabular/io/parquet.py in to_ddf(self, columns) +102 gather_statistics=False, +103 split_row_groups=self.row_groups_per_part, +--> 104 storage_options=self.storage_options, +105 ) +106 + +/opt/conda/envs/rapids/lib/python3.7/site-packages/dask_cudf/io/parquet.py in read_parquet(path, columns, split_row_groups, row_groups_per_part, **kwargs) +192 split_row_groups=split_row_groups, +193 engine=CudfEngine, +--> 194 **kwargs, +195 ) +196 + +/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/io/parquet/core.py in read_parquet(path, columns, filters, categories, index, storage_options, engine, gather_statistics, split_row_groups, chunksize, **kwargs) +248 # Modify `meta` dataframe accordingly +249 meta, index, columns = set_index_columns( +--> 250 meta, index, columns, index_in_columns, auto_index_allowed +251 ) +252 if meta.index.name == NONE_LABEL: + +/opt/conda/envs/rapids/lib/python3.7/site-packages/dask/dataframe/io/parquet/core.py in set_index_columns(meta, index, columns, index_in_columns, auto_index_allowed) +771 ""The following columns were not found in the dataset %s\\n"" +772 ""The following columns were found %s"" +--> 773 % (set(columns) - set(meta.columns), meta.columns) +774 ) +775 + +ValueError: The following columns were not found in the dataset {'document_id_promo_count', 'publish_time_days_since_published', 'campaign_id_clicked_sum_ctr', 'ad_id_count', 'ad_id_clicked_sum_ctr', 'source_id_clicked_sum_ctr', 'publish_time_promo_days_since_published', 'advertiser_id_clicked_sum_ctr', 'document_id_promo_clicked_sum_ctr', 'publisher_id_clicked_sum_ctr', 'geo_location_country', 'geo_location_state'} +The following columns were found Index(['display_id', 'ad_id', 'clicked', 'uuid', 'document_id', 'timestamp', +'platform', 'geo_location', 'document_id_promo', 'campaign_id', +'advertiser_id', 'source_id', 'publisher_id', 'publish_time', +'source_id_promo', 'publisher_id_promo', 'publish_time_promo', +'day_event'], +dtype='object')",ValueError +" def add_data(self, gdf): + # Populate columns idxs + if not self.col_idx: + for i, x in enumerate(gdf.columns.values): + self.col_idx[str(x)] = i + + # list columns in cudf don't currently support chunked writing in parquet. + # hack around this by just writing a single file with this partition + # this restriction can be removed once cudf supports chunked writing + # in parquet + if any(is_list_dtype(gdf[col].dtype) for col in gdf.columns): + self._write_table(0, gdf, True) + return + + # Generate `ind` array to map each row to an output file. + # This approach is certainly more optimized for shuffling + # than it is for non-shuffling, but using a single code + # path is probably worth the (possible) minor overhead. + nrows = gdf.shape[0] + typ = np.min_scalar_type(nrows * 2) + if self.shuffle: + ind = cp.random.choice(cp.arange(self.num_out_files, dtype=typ), nrows) + else: + ind = cp.arange(nrows, dtype=typ) + cp.floor_divide(ind, math.ceil(nrows / self.num_out_files), out=ind) + for x, group in enumerate( + gdf.scatter_by_map(ind, map_size=self.num_out_files, keep_index=False) + ): + self.num_samples[x] += len(group) + if self.num_threads > 1: + self.queue.put((x, group)) + else: + self._write_table(x, group) + + # wait for all writes to finish before exiting + # (so that we aren't using memory) + if self.num_threads > 1: + self.queue.join()"," def add_data(self, gdf): + # Populate columns idxs + if not self.col_idx: + for i, x in enumerate(gdf.columns.values): + self.col_idx[str(x)] = i + + # list columns in cudf don't currently support chunked writing in parquet. + # hack around this by just writing a single file with this partition + # this restriction can be removed once cudf supports chunked writing + # in parquet + if any(is_list_dtype(gdf[col].dtype) for col in gdf.columns): + self._write_table(gdf, 0, True) + return + + # Generate `ind` array to map each row to an output file. + # This approach is certainly more optimized for shuffling + # than it is for non-shuffling, but using a single code + # path is probably worth the (possible) minor overhead. + nrows = gdf.shape[0] + typ = np.min_scalar_type(nrows * 2) + if self.shuffle: + ind = cp.random.choice(cp.arange(self.num_out_files, dtype=typ), nrows) + else: + ind = cp.arange(nrows, dtype=typ) + cp.floor_divide(ind, math.ceil(nrows / self.num_out_files), out=ind) + for x, group in enumerate( + gdf.scatter_by_map(ind, map_size=self.num_out_files, keep_index=False) + ): + self.num_samples[x] += len(group) + if self.num_threads > 1: + self.queue.put((x, group)) + else: + self._write_table(x, group) + + # wait for all writes to finish before exiting + # (so that we aren't using memory) + if self.num_threads > 1: + self.queue.join()","[{'piece_type': 'other', 'piece_content': ""df = cudf.DataFrame({'doc_id': [1, 1, 2, 2, 3, 3, 4, 4], 'category_id': [1, 2, 3, 3, 5, 6, 6, 1], 'confidence_level': [0.92, 0.251, 0.352, 0.359, 0.978, 0.988, 0.978, 0.988]})\\n\\ndf_grouped = df.groupby('doc_id', as_index=False).agg({'category_id': ['collect'], 'confidence_level': ['collect']})\\n\\ndf_grouped.columns= df_grouped.columns.get_level_values(0)\\n\\ndf2 = cudf.DataFrame({'doc_id': [1, 2, 2, 3, 4, 3, 7, 8], 'category_id': [1, 2, 4, 3, 6, 6, 5, 2], 'ad_id': [1, 2, 3, 4, 4, 5, 10, 12],\\n'source_id': [1200, 1210, 1450, np.nan, 1330, 1200, 1500, 1350]})\\n\\ncolumns_ext = ['doc_id', 'category_id', 'confidence_level']\\nkind_ext='cudf'\\nproc = nvt.Workflow(\\ncat_names= ['doc_id', 'category_id', 'ad_id', 'source_id'],\\ncont_names=[],\\nlabel_name=[])\\n\\nproc.add_preprocess(JoinExternal(df_grouped, on= ['doc_id'], on_ext= ['doc_id'], kind_ext=kind_ext, columns_ext=columns_ext, cache='device', how='left'))\\ntrain_dataset = nvt.Dataset(df2)\\nproc.apply(train_dataset, apply_offline=True, record_stats=True, output_path='./output/', shuffle=True, out_files_per_proc=1)""}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in \\n11 proc.add_preprocess(JoinExternal(df_grouped, on= [\\'doc_id\\'], on_ext= [\\'doc_id\\'], kind_ext=kind_ext, columns_ext=columns_ext, cache=\\'device\\', how=\\'left\\'))\\n12 train_dataset = nvt.Dataset(df2)\\n---> 13 proc.apply(train_dataset, apply_offline=True, record_stats=True, output_path=\\'./output/\\', shuffle=True, out_files_per_proc=1)\\n\\n~/ronaya/NVTabular/nvtabular/workflow.py in apply(self, dataset, apply_offline, record_stats, shuffle, output_path, output_format, out_files_per_proc, num_io_threads)\\n738 output_format=output_format,\\n739 out_files_per_proc=out_files_per_proc,\\n--> 740 num_io_threads=num_io_threads,\\n741 )\\n742 else:\\n\\n~/ronaya/NVTabular/nvtabular/workflow.py in build_and_process_graph(self, dataset, end_phase, output_path, record_stats, shuffle, output_format, out_files_per_proc, apply_ops, num_io_threads)\\n845 shuffle=shuffle,\\n846 out_files_per_proc=out_files_per_proc,\\n--> 847 num_threads=num_io_threads,\\n848 )\\n849\\n\\n~/ronaya/NVTabular/nvtabular/workflow.py in ddf_to_dataset(self, output_path, shuffle, out_files_per_proc, output_format, num_threads)\\n931 output_format,\\n932 self.client,\\n--> 933 num_threads,\\n934 )\\n935 return\\n\\n~/ronaya/NVTabular/nvtabular/io/dask.py in _ddf_to_dataset(ddf, fs, output_path, shuffle, out_files_per_proc, cat_names, cont_names, label_names, output_format, client, num_threads)\\n110 out = client.compute(out).result()\\n111 else:\\n--> 112 out = dask.compute(out, scheduler=""synchronous"")[0]\\n113\\n114 # Follow-up Shuffling and _metadata creation\\n\\n~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/base.py in compute(*args, **kwargs)\\n450 postcomputes.append(x.__dask_postcompute__())\\n451\\n--> 452 results = schedule(dsk, keys, **kwargs)\\n453 return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])\\n454\\n\\n~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in get_sync(dsk, keys, **kwargs)\\n525 """"""\\n526 kwargs.pop(""num_workers"", None) # if num_workers present, remove it\\n--> 527 return get_async(apply_sync, 1, dsk, keys, **kwargs)\\n528\\n529\\n\\n~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in get_async(apply_async, num_workers, dsk, result, cache, get_id, rerun_exceptions_locally, pack_exception, raise_exception, callbacks, dumps, loads, **kwargs)\\n492\\n493 while state[""ready""] and len(state[""running""]) < num_workers:\\n--> 494 fire_task()\\n495\\n496 succeeded = True\\n\\n~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in fire_task()\\n464 pack_exception,\\n465 ),\\n--> 466 callback=queue.put,\\n467 )\\n468\\n\\n~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in apply_sync(func, args, kwds, callback)\\n514 def apply_sync(func, args=(), kwds={}, callback=None):\\n515 """""" A naive synchronous version of apply_async """"""\\n--> 516 res = func(*args, **kwds)\\n517 if callback is not None:\\n518 callback(res)\\n\\n~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception)\\n225 failed = False\\n226 except BaseException as e:\\n--> 227 result = pack_exception(e, dumps)\\n228 failed = True\\n229 return key, result, failed\\n\\n~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception)\\n220 try:\\n221 task, data = loads(task_info)\\n--> 222 result = _execute_task(task, data)\\n223 id = get_id()\\n224 result = dumps((result, id))\\n\\n~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/core.py in _execute_task(arg, cache, dsk)\\n119 # temporaries by their reference count and can execute certain\\n120 # operations in-place.\\n--> 121 return func(*(_execute_task(a, cache) for a in args))\\n122 elif not ishashable(arg):\\n123 return arg\\n\\n~/miniconda3/envs/1019/lib/python3.7/contextlib.py in inner(*args, **kwds)\\n72 def inner(*args, **kwds):\\n73 with self._recreate_cm():\\n---> 74 return func(*args, **kwds)\\n75 return inner\\n76\\n\\n~/ronaya/NVTabular/nvtabular/io/dask.py in _write_output_partition(gdf, processed_path, shuffle, out_files_per_proc, fs, cat_names, cont_names, label_names, output_format, num_threads)\\n61\\n62 # Add data\\n---> 63 writer.add_data(gdf)\\n64\\n65 return gdf_size\\n\\n~/miniconda3/envs/1019/lib/python3.7/contextlib.py in inner(*args, **kwds)\\n72 def inner(*args, **kwds):\\n73 with self._recreate_cm():\\n---> 74 return func(*args, **kwds)\\n75 return inner\\n76\\n\\n~/ronaya/NVTabular/nvtabular/io/writer.py in add_data(self, gdf)\\n125 # in parquet\\n126 if any(is_list_dtype(gdf[col].dtype) for col in gdf.columns):\\n--> 127 self._write_table(gdf, 0, True)\\n128 return\\n129\\n\\n~/ronaya/NVTabular/nvtabular/io/parquet.py in _write_table(self, idx, data, has_list_column)\\n210 # write out a new file, rather than stream multiple chunks to a single file\\n211 filename = self._get_filename(len(self.data_paths))\\n--> 212 data.to_parquet(filename)\\n213 self.data_paths.append(filename)\\n214 else:\\n\\nAttributeError: \\'int\\' object has no attribute \\'to_parquet\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in +11 proc.add_preprocess(JoinExternal(df_grouped, on= ['doc_id'], on_ext= ['doc_id'], kind_ext=kind_ext, columns_ext=columns_ext, cache='device', how='left')) +12 train_dataset = nvt.Dataset(df2) +---> 13 proc.apply(train_dataset, apply_offline=True, record_stats=True, output_path='./output/', shuffle=True, out_files_per_proc=1) + +~/ronaya/NVTabular/nvtabular/workflow.py in apply(self, dataset, apply_offline, record_stats, shuffle, output_path, output_format, out_files_per_proc, num_io_threads) +738 output_format=output_format, +739 out_files_per_proc=out_files_per_proc, +--> 740 num_io_threads=num_io_threads, +741 ) +742 else: + +~/ronaya/NVTabular/nvtabular/workflow.py in build_and_process_graph(self, dataset, end_phase, output_path, record_stats, shuffle, output_format, out_files_per_proc, apply_ops, num_io_threads) +845 shuffle=shuffle, +846 out_files_per_proc=out_files_per_proc, +--> 847 num_threads=num_io_threads, +848 ) +849 + +~/ronaya/NVTabular/nvtabular/workflow.py in ddf_to_dataset(self, output_path, shuffle, out_files_per_proc, output_format, num_threads) +931 output_format, +932 self.client, +--> 933 num_threads, +934 ) +935 return + +~/ronaya/NVTabular/nvtabular/io/dask.py in _ddf_to_dataset(ddf, fs, output_path, shuffle, out_files_per_proc, cat_names, cont_names, label_names, output_format, client, num_threads) +110 out = client.compute(out).result() +111 else: +--> 112 out = dask.compute(out, scheduler=""synchronous"")[0] +113 +114 # Follow-up Shuffling and _metadata creation + +~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/base.py in compute(*args, **kwargs) +450 postcomputes.append(x.__dask_postcompute__()) +451 +--> 452 results = schedule(dsk, keys, **kwargs) +453 return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)]) +454 + +~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in get_sync(dsk, keys, **kwargs) +525 """""" +526 kwargs.pop(""num_workers"", None) # if num_workers present, remove it +--> 527 return get_async(apply_sync, 1, dsk, keys, **kwargs) +528 +529 + +~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in get_async(apply_async, num_workers, dsk, result, cache, get_id, rerun_exceptions_locally, pack_exception, raise_exception, callbacks, dumps, loads, **kwargs) +492 +493 while state[""ready""] and len(state[""running""]) < num_workers: +--> 494 fire_task() +495 +496 succeeded = True + +~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in fire_task() +464 pack_exception, +465 ), +--> 466 callback=queue.put, +467 ) +468 + +~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in apply_sync(func, args, kwds, callback) +514 def apply_sync(func, args=(), kwds={}, callback=None): +515 """""" A naive synchronous version of apply_async """""" +--> 516 res = func(*args, **kwds) +517 if callback is not None: +518 callback(res) + +~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception) +225 failed = False +226 except BaseException as e: +--> 227 result = pack_exception(e, dumps) +228 failed = True +229 return key, result, failed + +~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception) +220 try: +221 task, data = loads(task_info) +--> 222 result = _execute_task(task, data) +223 id = get_id() +224 result = dumps((result, id)) + +~/miniconda3/envs/1019/lib/python3.7/site-packages/dask/core.py in _execute_task(arg, cache, dsk) +119 # temporaries by their reference count and can execute certain +120 # operations in-place. +--> 121 return func(*(_execute_task(a, cache) for a in args)) +122 elif not ishashable(arg): +123 return arg + +~/miniconda3/envs/1019/lib/python3.7/contextlib.py in inner(*args, **kwds) +72 def inner(*args, **kwds): +73 with self._recreate_cm(): +---> 74 return func(*args, **kwds) +75 return inner +76 + +~/ronaya/NVTabular/nvtabular/io/dask.py in _write_output_partition(gdf, processed_path, shuffle, out_files_per_proc, fs, cat_names, cont_names, label_names, output_format, num_threads) +61 +62 # Add data +---> 63 writer.add_data(gdf) +64 +65 return gdf_size + +~/miniconda3/envs/1019/lib/python3.7/contextlib.py in inner(*args, **kwds) +72 def inner(*args, **kwds): +73 with self._recreate_cm(): +---> 74 return func(*args, **kwds) +75 return inner +76 + +~/ronaya/NVTabular/nvtabular/io/writer.py in add_data(self, gdf) +125 # in parquet +126 if any(is_list_dtype(gdf[col].dtype) for col in gdf.columns): +--> 127 self._write_table(gdf, 0, True) +128 return +129 + +~/ronaya/NVTabular/nvtabular/io/parquet.py in _write_table(self, idx, data, has_list_column) +210 # write out a new file, rather than stream multiple chunks to a single file +211 filename = self._get_filename(len(self.data_paths)) +--> 212 data.to_parquet(filename) +213 self.data_paths.append(filename) +214 else: + +AttributeError: 'int' object has no attribute 'to_parquet'",AttributeError +" def __init__( + self, + paths, + part_size, + storage_options, + row_groups_per_part=None, + legacy=False, + batch_size=None, + ): + # TODO: Improve dask_cudf.read_parquet performance so that + # this class can be slimmed down. + super().__init__(paths, part_size, storage_options) + self.batch_size = batch_size + self._metadata, self._base = self.metadata + self._pieces = None + if row_groups_per_part is None: + file_path = self._metadata.row_group(0).column(0).file_path + path0 = ( + self.fs.sep.join([self._base, file_path]) + if file_path != """" + else self._base # This is a single file + ) + + if row_groups_per_part is None: + rg_byte_size_0 = _memory_usage(cudf.io.read_parquet(path0, row_groups=0, row_group=0)) + row_groups_per_part = self.part_size / rg_byte_size_0 + if row_groups_per_part < 1.0: + warnings.warn( + f""Row group size {rg_byte_size_0} is bigger than requested part_size "" + f""{self.part_size}"" + ) + row_groups_per_part = 1.0 + + self.row_groups_per_part = int(row_groups_per_part) + + assert self.row_groups_per_part > 0"," def __init__( + self, + paths, + part_size, + storage_options, + row_groups_per_part=None, + legacy=False, + batch_size=None, + ): + # TODO: Improve dask_cudf.read_parquet performance so that + # this class can be slimmed down. + super().__init__(paths, part_size, storage_options) + self.batch_size = batch_size + self._metadata, self._base = self.metadata + self._pieces = None + if row_groups_per_part is None: + file_path = self._metadata.row_group(0).column(0).file_path + path0 = ( + self.fs.sep.join([self._base, file_path]) + if file_path != """" + else self._base # This is a single file + ) + + if row_groups_per_part is None: + rg_byte_size_0 = ( + cudf.io.read_parquet(path0, row_groups=0, row_group=0) + .memory_usage(deep=True, index=True) + .sum() + ) + row_groups_per_part = self.part_size / rg_byte_size_0 + if row_groups_per_part < 1.0: + warnings.warn( + f""Row group size {rg_byte_size_0} is bigger than requested part_size "" + f""{self.part_size}"" + ) + row_groups_per_part = 1.0 + + self.row_groups_per_part = int(row_groups_per_part) + + assert self.row_groups_per_part > 0","[{'piece_type': 'other', 'piece_content': 'python dataloader_bench.py torch parquet 0.2'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 106, in \\nmain(args)\\nFile ""main.py"", line 61, in main\\ntrain_paths, engine=""parquet"", part_mem_fraction=float(args.gpu_mem_frac)\\nFile ""/root/miniconda/lib/python3.7/site-packages/nvtabular/io/dataset.py"", line 224, in __init__\\npaths, part_size, storage_options=storage_options, **kwargs\\nFile ""/root/miniconda/lib/python3.7/site-packages/nvtabular/io/parquet.py"", line 69, in __init__\\n.memory_usage(deep=True, index=True)\\nFile ""/root/miniconda/lib/python3.7/site-packages/cudf/core/dataframe.py"", line 842, in memory_usage\\nsizes = [col._memory_usage(deep=deep) for col in self._data.columns]\\nFile ""/root/miniconda/lib/python3.7/site-packages/cudf/core/dataframe.py"", line 842, in \\nsizes = [col._memory_usage(deep=deep) for col in self._data.columns]\\nFile ""/root/miniconda/lib/python3.7/site-packages/cudf/core/column/column.py"", line 299, in _memory_usage\\nreturn self.__sizeof__()\\nFile ""/root/miniconda/lib/python3.7/site-packages/cudf/core/column/column.py"", line 183, in __sizeof__\\nn = self.data.size\\nFile ""cudf/_lib/column.pyx"", line 99, in cudf._lib.column.Column.data.__get__\\nAttributeError: \\'ListDtype\\' object has no attribute \\'itemsize\\''}, {'piece_type': 'other', 'piece_content': '# packages in environment at /root/miniconda:\\n#\\n# Name Version Build Channel\\n_libgcc_mutex 0.1 main\\n_pytorch_select 0.1 cpu_0\\nabseil-cpp 20200225.2 he1b5a44_2 conda-forge\\narrow-cpp 0.17.1 py37h1234567_11_cuda conda-forge\\narrow-cpp-proc 1.0.1 cuda conda-forge\\naws-sdk-cpp 1.7.164 hba45d7a_2 conda-forge\\nblas 1.0 mkl\\nbokeh 2.2.2 py37_0\\nboost-cpp 1.72.0 h9359b55_3 conda-forge\\nbrotli 1.0.9 he6710b0_2\\nbrotlipy 0.7.0 py37h7b6447c_1000\\nbzip2 1.0.8 h7b6447c_0\\nc-ares 1.16.1 h7b6447c_0\\nca-certificates 2020.10.14 0\\ncertifi 2020.6.20 py37_0\\ncffi 1.14.3 py37he30daa8_0\\nchardet 3.0.4 py37_1003\\nclick 7.1.2 py_0\\ncloudpickle 1.6.0 py_0\\nconda 4.9.0 py37he5f6b98_0 conda-forge\\nconda-package-handling 1.7.2 py37h03888b9_0\\ncryptography 3.1.1 py37h1ba5d50_0\\ncudatoolkit 10.2.89 h6bb024c_0 nvidia\\ncudf 0.15.0 cuda_10.2_py37_g71cb8c0e0_0 rapidsai\\ncudnn 7.6.5 cuda10.2_0\\ncupy 7.8.0 py37h940342b_1 conda-forge\\ncurl 7.71.1 hbc83047_1\\ncython 0.29.21 pypi_0 pypi\\ncytoolz 0.11.0 py37h7b6447c_0\\ndask 2.30.0 py_0\\ndask-core 2.30.0 py_0\\ndask-cudf 0.15.0 py37_g71cb8c0e0_0 rapidsai\\ndistributed 2.30.0 py37_0\\ndlpack 0.3 he6710b0_1\\ndouble-conversion 3.1.5 he6710b0_1\\nfastavro 1.0.0.post1 py37h7b6447c_0\\nfastrlock 0.5 py37he6710b0_0\\nfreetype 2.10.3 h5ab3b9f_0\\nfsspec 0.8.3 py_0\\ngflags 2.2.2 he6710b0_0\\nglog 0.4.0 he6710b0_0\\ngrpc-cpp 1.30.2 heedbac9_0 conda-forge\\nheapdict 1.0.1 py_0\\nicu 67.1 he1b5a44_0 conda-forge\\nidna 2.10 py_0\\nintel-openmp 2019.4 243\\njinja2 2.11.2 py_0\\njpeg 9b h024ee3a_2\\nkrb5 1.18.2 h173b8e3_0\\nlcms2 2.11 h396b838_0\\nld_impl_linux-64 2.33.1 h53a641e_7\\nlibcudf 0.15.0 cuda10.2_g71cb8c0e0_0 rapidsai\\nlibcurl 7.71.1 h20c2e04_1\\nlibedit 3.1.20191231 h14c3975_1\\nlibevent 2.1.10 hcdb4288_3 conda-forge\\nlibffi 3.3 he6710b0_2\\nlibgcc-ng 9.1.0 hdf63c60_0\\nlibllvm10 10.0.1 hbcb73fb_5\\nlibpng 1.6.37 hbc83047_0\\nlibprotobuf 3.12.4 hd408876_0\\nlibrmm 0.15.0 cuda10.2_g8005ca5_0 rapidsai\\nlibssh2 1.9.0 h1ba5d50_1\\nlibstdcxx-ng 9.1.0 hdf63c60_0\\nlibthrift 0.13.0 hbe8ec66_6 conda-forge\\nlibtiff 4.1.0 h2733197_1\\nllvmlite 0.34.0 py37h269e1b5_4\\nlocket 0.2.0 py37_1\\nlz4-c 1.9.2 heb0550a_3\\nmarkupsafe 1.1.1 py37h14c3975_1\\nmkl 2019.4 243\\nmkl-service 2.3.0 py37he904b0f_0\\nmkl_fft 1.2.0 py37h23d657b_0\\nmkl_random 1.1.0 py37hd6b4f25_0\\nmsgpack-python 1.0.0 py37hfd86e86_1\\nnccl 2.7.8.1 hc6a2c23_1 conda-forge\\nncurses 6.2 he6710b0_1\\nninja 1.10.1 py37hfd86e86_0\\nnumba 0.51.2 py37h04863e7_1\\nnumpy 1.19.1 py37hbc911f0_0\\nnumpy-base 1.19.1 py37hfa32c7d_0\\nnvtabular 0.2.0 cudaunknown_py37_0 nvidia/label/nvidia\\nolefile 0.46 py37_0\\nopenssl 1.1.1h h7b6447c_0\\npackaging 20.4 py_0\\npandas 1.1.3 py37he6710b0_0\\nparquet-cpp 1.5.1 2 conda-forge\\npartd 1.1.0 py_0\\npillow 8.0.0 py37h9a89aac_0\\npip 20.2.3 py37_0\\npsutil 5.7.2 py37h7b6447c_0\\npyarrow 0.17.1 py37h1234567_11_cuda conda-forge\\npycosat 0.6.3 py37h7b6447c_0\\npycparser 2.19 pypi_0 pypi\\npynvml 8.0.4 py_1 conda-forge\\npyopenssl 19.1.0 py_1\\npyparsing 2.4.7 py_0\\npysocks 1.7.1 py37_1\\npython 3.7.9 h7579374_0\\npython-dateutil 2.8.1 py_0\\npython_abi 3.7 1_cp37m conda-forge\\npytorch 1.5.0 cpu_py37hd91cbb3_0\\npytz 2020.1 py_0\\npyyaml 5.3.1 py37h7b6447c_1\\nre2 2020.07.06 he1b5a44_1 conda-forge\\nreadline 8.0 h7b6447c_0\\nrequests 2.24.0 py_0\\nrmm 0.15.0 cuda_10.2_py37_g8005ca5_0 rapidsai\\nruamel_yaml 0.15.87 py37h7b6447c_1\\nsetuptools 50.3.0 py37hb0f4dca_1\\nsix 1.15.0 py_0\\nsnappy 1.1.8 he6710b0_0\\nsortedcontainers 2.2.2 py_0\\nspdlog 1.8.0 hfd86e86_1\\nsqlite 3.33.0 h62c20be_0\\ntbb 2020.3 hfd86e86_0\\ntblib 1.7.0 py_0\\nthrift-compiler 0.13.0 hbe8ec66_6 conda-forge\\nthrift-cpp 0.13.0 6 conda-forge\\ntk 8.6.10 hbc83047_0\\ntoolz 0.11.1 py_0\\ntornado 6.0.4 py37h7b6447c_1\\ntqdm 4.50.2 py_0\\ntyping_extensions 3.7.4.3 py_0\\nurllib3 1.25.10 py_0\\nwheel 0.35.1 py_0\\nxz 5.2.5 h7b6447c_0\\nyaml 0.2.5 h7b6447c_0\\nzict 2.0.0 py_0\\nzlib 1.2.11 h7b6447c_3\\nzstd 1.4.5 h9ceee32_0'}]","Traceback (most recent call last): +File ""main.py"", line 106, in +main(args) +File ""main.py"", line 61, in main +train_paths, engine=""parquet"", part_mem_fraction=float(args.gpu_mem_frac) +File ""/root/miniconda/lib/python3.7/site-packages/nvtabular/io/dataset.py"", line 224, in __init__ +paths, part_size, storage_options=storage_options, **kwargs +File ""/root/miniconda/lib/python3.7/site-packages/nvtabular/io/parquet.py"", line 69, in __init__ +.memory_usage(deep=True, index=True) +File ""/root/miniconda/lib/python3.7/site-packages/cudf/core/dataframe.py"", line 842, in memory_usage +sizes = [col._memory_usage(deep=deep) for col in self._data.columns] +File ""/root/miniconda/lib/python3.7/site-packages/cudf/core/dataframe.py"", line 842, in +sizes = [col._memory_usage(deep=deep) for col in self._data.columns] +File ""/root/miniconda/lib/python3.7/site-packages/cudf/core/column/column.py"", line 299, in _memory_usage +return self.__sizeof__() +File ""/root/miniconda/lib/python3.7/site-packages/cudf/core/column/column.py"", line 183, in __sizeof__ +n = self.data.size +File ""cudf/_lib/column.pyx"", line 99, in cudf._lib.column.Column.data.__get__ +AttributeError: 'ListDtype' object has no attribute 'itemsize'",AttributeError +" def __init__(self, *args, **kwargs): + super().__init__(*args) + self._meta = {} + self.csv_kwargs = kwargs + self.names = self.csv_kwargs.get(""names"", None) + # CSV reader needs a list of files + # (Assume flat directory structure if this is a dir) + if len(self.paths) == 1 and self.fs.isdir(self.paths[0]): + self.paths = self.fs.glob(self.fs.sep.join([self.paths[0], ""*""]))"," def __init__(self, *args, **kwargs): + super().__init__(*args) + self._meta = {} + self.names = kwargs.pop(""names"", None) + self.csv_kwargs = kwargs + # CSV reader needs a list of files + # (Assume flat directory structure if this is a dir) + if len(self.paths) == 1 and self.fs.isdir(self.paths[0]): + self.paths = self.fs.glob(self.fs.sep.join([self.paths[0], ""*""]))","[{'piece_type': 'error message', 'piece_content': ""AttributeErrorTraceback (most recent call last)\\n in \\n44 del gdf\\n45 path_out = '/raid/criteo/tests/jp_csv_orig/'\\n---> 46 file_to_pq(train_set, 'csv', output_folder=path_out, cols=cols, dtypes=dtypes)\\n\\n in file_to_pq(target_files, file_type, output_folder, cols, dtypes)\\n34 old_file_path = None\\n35 writer = None\\n---> 36 for gdf in tar:\\n37 # gdf.to_parquet(output_folder)\\n38 file_path = os.path.join(output_folder, os.path.split(tar.itr.file_path)[1].split('.')[0])\\n\\n/nvtabular/nvtabular/io.py in __iter__(self)\\n329 def __iter__(self):\\n330 for path in self.paths:\\n--> 331 yield from GPUFileIterator(path, **self.kwargs)\\n332\\n333\\n\\n/nvtabular/nvtabular/io.py in __iter__(self)\\n271 for chunk in self.engine:\\n272 if self.dtypes:\\n--> 273 self._set_dtypes(chunk)\\n274 yield chunk\\n275 chunk = None\\n\\nAttributeError: 'GPUFileIterator' object has no attribute '_set_dtypes'""}]","AttributeErrorTraceback (most recent call last) + in +44 del gdf +45 path_out = '/raid/criteo/tests/jp_csv_orig/' +---> 46 file_to_pq(train_set, 'csv', output_folder=path_out, cols=cols, dtypes=dtypes) + + in file_to_pq(target_files, file_type, output_folder, cols, dtypes) +34 old_file_path = None +35 writer = None +---> 36 for gdf in tar: +37 # gdf.to_parquet(output_folder) +38 file_path = os.path.join(output_folder, os.path.split(tar.itr.file_path)[1].split('.')[0]) + +/nvtabular/nvtabular/io.py in __iter__(self) +329 def __iter__(self): +330 for path in self.paths: +--> 331 yield from GPUFileIterator(path, **self.kwargs) +332 +333 + +/nvtabular/nvtabular/io.py in __iter__(self) +271 for chunk in self.engine: +272 if self.dtypes: +--> 273 self._set_dtypes(chunk) +274 yield chunk +275 chunk = None + +AttributeError: 'GPUFileIterator' object has no attribute '_set_dtypes'",AttributeError +" def to_ddf(self, columns=None): + return dask_cudf.read_csv(self.paths, chunksize=self.part_size, **self.csv_kwargs)[columns]"," def to_ddf(self, columns=None): + return dask_cudf.read_csv( + self.paths, names=self.names, chunksize=self.part_size, **self.csv_kwargs + )[columns]","[{'piece_type': 'error message', 'piece_content': ""AttributeErrorTraceback (most recent call last)\\n in \\n44 del gdf\\n45 path_out = '/raid/criteo/tests/jp_csv_orig/'\\n---> 46 file_to_pq(train_set, 'csv', output_folder=path_out, cols=cols, dtypes=dtypes)\\n\\n in file_to_pq(target_files, file_type, output_folder, cols, dtypes)\\n34 old_file_path = None\\n35 writer = None\\n---> 36 for gdf in tar:\\n37 # gdf.to_parquet(output_folder)\\n38 file_path = os.path.join(output_folder, os.path.split(tar.itr.file_path)[1].split('.')[0])\\n\\n/nvtabular/nvtabular/io.py in __iter__(self)\\n329 def __iter__(self):\\n330 for path in self.paths:\\n--> 331 yield from GPUFileIterator(path, **self.kwargs)\\n332\\n333\\n\\n/nvtabular/nvtabular/io.py in __iter__(self)\\n271 for chunk in self.engine:\\n272 if self.dtypes:\\n--> 273 self._set_dtypes(chunk)\\n274 yield chunk\\n275 chunk = None\\n\\nAttributeError: 'GPUFileIterator' object has no attribute '_set_dtypes'""}]","AttributeErrorTraceback (most recent call last) + in +44 del gdf +45 path_out = '/raid/criteo/tests/jp_csv_orig/' +---> 46 file_to_pq(train_set, 'csv', output_folder=path_out, cols=cols, dtypes=dtypes) + + in file_to_pq(target_files, file_type, output_folder, cols, dtypes) +34 old_file_path = None +35 writer = None +---> 36 for gdf in tar: +37 # gdf.to_parquet(output_folder) +38 file_path = os.path.join(output_folder, os.path.split(tar.itr.file_path)[1].split('.')[0]) + +/nvtabular/nvtabular/io.py in __iter__(self) +329 def __iter__(self): +330 for path in self.paths: +--> 331 yield from GPUFileIterator(path, **self.kwargs) +332 +333 + +/nvtabular/nvtabular/io.py in __iter__(self) +271 for chunk in self.engine: +272 if self.dtypes: +--> 273 self._set_dtypes(chunk) +274 yield chunk +275 chunk = None + +AttributeError: 'GPUFileIterator' object has no attribute '_set_dtypes'",AttributeError +" def _predict(self, X): + """"""Collect results from clf.predict calls."""""" + + if self.refit: + return np.asarray([clf.predict(X) for clf in self.clfs_]).T + else: + return np.asarray([self.le_.transform(clf.predict(X)) + for clf in self.clfs_]).T"," def _predict(self, X): + """"""Collect results from clf.predict calls."""""" + return np.asarray([clf.predict(X) for clf in self.clfs_]).T","[{'piece_type': 'reproducing source code', 'piece_content': ""import numpy as np\\nfrom sklearn.ensemble import RandomForestClassifier\\nfrom mlxtend.classifier import EnsembleVoteClassifier\\n\\ndata = np.array([0, 1, 2, 3, 0, 1, 2, 3])[:, np.newaxis]\\nlabels = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']\\n\\ntest = np.array([0, 1])[:, np.newaxis]\\n\\nrf = RandomForestClassifier()\\nrf.fit(data, labels)\\nprint(rf.predict(test)) # output: ['a', 'b']\\n\\nclf = EnsembleVoteClassifier(clfs=[rf, rf], refit=False)\\nclf.fit(data, labels)\\nprint(clf.predict(test)) # <-- error""}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/_mlxtend_bug/reproduce.py"", line 16, in \\nprint(clf.predict(test))\\nFile ""/venv/py3/lib/python3.4/site-packages/mlxtend/classifier/ensemble_vote.py"", line 197, in predict\\narr=predictions)\\nFile ""/venv/py3/lib/python3.4/site-packages/numpy/lib/shape_base.py"", line 132, in apply_along_axis\\nres = asanyarray(func1d(inarr_view[ind0], *args, **kwargs))\\nFile ""/venv/py3/lib/python3.4/site-packages/mlxtend/classifier/ensemble_vote.py"", line 195, in \\nweights=self.weights)),\\nTypeError: Cannot cast array data from dtype(\\' +print(clf.predict(test)) +File ""/venv/py3/lib/python3.4/site-packages/mlxtend/classifier/ensemble_vote.py"", line 197, in predict +arr=predictions) +File ""/venv/py3/lib/python3.4/site-packages/numpy/lib/shape_base.py"", line 132, in apply_along_axis +res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs)) +File ""/venv/py3/lib/python3.4/site-packages/mlxtend/classifier/ensemble_vote.py"", line 195, in +weights=self.weights)), +TypeError: Cannot cast array data from dtype(' Any: + """""" + Transform points between two coordinate systems. + + .. versionadded:: 2.1.1 errcheck + .. versionadded:: 2.2.0 direction + + Parameters + ---------- + xx: scalar or array (numpy or python) + Input x coordinate(s). + yy: scalar or array (numpy or python) + Input y coordinate(s). + zz: scalar or array (numpy or python), optional + Input z coordinate(s). + tt: scalar or array (numpy or python), optional + Input time coordinate(s). + radians: boolean, optional + If True, will expect input data to be in radians and will return radians + if the projection is geographic. Default is False (degrees). Ignored for + pipeline transformations. + errcheck: boolean, optional (default False) + If True an exception is raised if the transformation is invalid. + By default errcheck=False and an invalid transformation + returns ``inf`` and no exception is raised. + direction: pyproj.enums.TransformDirection, optional + The direction of the transform. + Default is :attr:`pyproj.enums.TransformDirection.FORWARD`. + + + Example: + + >>> from pyproj import Transformer + >>> transformer = Transformer.from_crs(""epsg:4326"", ""epsg:3857"") + >>> x3, y3 = transformer.transform(33, 98) + >>> ""%.3f %.3f"" % (x3, y3) + '10909310.098 3895303.963' + >>> pipeline_str = ( + ... ""+proj=pipeline +step +proj=longlat +ellps=WGS84 "" + ... ""+step +proj=unitconvert +xy_in=rad +xy_out=deg"" + ... ) + >>> pipe_trans = Transformer.from_pipeline(pipeline_str) + >>> xt, yt = pipe_trans.transform(2.1, 0.001) + >>> ""%.3f %.3f"" % (xt, yt) + '2.100 0.001' + >>> transproj = Transformer.from_crs( + ... {""proj"":'geocent', ""ellps"":'WGS84', ""datum"":'WGS84'}, + ... ""EPSG:4326"", + ... always_xy=True, + ... ) + >>> xpj, ypj, zpj = transproj.transform( + ... -2704026.010, + ... -4253051.810, + ... 3895878.820, + ... radians=True, + ... ) + >>> ""%.3f %.3f %.3f"" % (xpj, ypj, zpj) + '-2.137 0.661 -20.531' + >>> transprojr = Transformer.from_crs( + ... ""EPSG:4326"", + ... {""proj"":'geocent', ""ellps"":'WGS84', ""datum"":'WGS84'}, + ... always_xy=True, + ... ) + >>> xpjr, ypjr, zpjr = transprojr.transform(xpj, ypj, zpj, radians=True) + >>> ""%.3f %.3f %.3f"" % (xpjr, ypjr, zpjr) + '-2704026.010 -4253051.810 3895878.820' + >>> transformer = Transformer.from_proj(""epsg:4326"", 4326, skip_equivalent=True) + >>> xeq, yeq = transformer.transform(33, 98) + >>> ""%.0f %.0f"" % (xeq, yeq) + '33 98' + + """""" + # process inputs, making copies that support buffer API. + inx, xisfloat, xislist, xistuple = _copytobuffer(xx) + iny, yisfloat, yislist, yistuple = _copytobuffer(yy) + if zz is not None: + inz, zisfloat, zislist, zistuple = _copytobuffer(zz) + else: + inz = None + if tt is not None: + intime, tisfloat, tislist, tistuple = _copytobuffer(tt) + else: + intime = None + # call pj_transform. inx,iny,inz buffers modified in place. + self._transformer._transform( + inx, + iny, + inz=inz, + intime=intime, + direction=direction, + radians=radians, + errcheck=errcheck, + ) + # if inputs were lists, tuples or floats, convert back. + outx = _convertback(xisfloat, xislist, xistuple, inx) + outy = _convertback(yisfloat, yislist, xistuple, iny) + return_data = (outx, outy) + if inz is not None: + return_data += ( # type: ignore + _convertback(zisfloat, zislist, zistuple, inz), + ) + if intime is not None: + return_data += ( # type: ignore + _convertback(tisfloat, tislist, tistuple, intime), + ) + return return_data"," def transform( + self, + xx: Any, + yy: Any, + zz: Any = None, + tt: Any = None, + radians: bool = False, + errcheck: bool = False, + direction: Union[TransformDirection, str] = TransformDirection.FORWARD, + ) -> Any: + """""" + Transform points between two coordinate systems. + + .. versionadded:: 2.1.1 errcheck + .. versionadded:: 2.2.0 direction + + Parameters + ---------- + xx: scalar or array (numpy or python) + Input x coordinate(s). + yy: scalar or array (numpy or python) + Input y coordinate(s). + zz: scalar or array (numpy or python), optional + Input z coordinate(s). + tt: scalar or array (numpy or python), optional + Input time coordinate(s). + radians: boolean, optional + If True, will expect input data to be in radians and will return radians + if the projection is geographic. Default is False (degrees). Ignored for + pipeline transformations. + errcheck: boolean, optional (default False) + If True an exception is raised if the transformation is invalid. + By default errcheck=False and an invalid transformation + returns ``inf`` and no exception is raised. + direction: pyproj.enums.TransformDirection, optional + The direction of the transform. + Default is :attr:`pyproj.enums.TransformDirection.FORWARD`. + + + Example: + + >>> from pyproj import Transformer + >>> transformer = Transformer.from_crs(""epsg:4326"", ""epsg:3857"") + >>> x3, y3 = transformer.transform(33, 98) + >>> ""%.3f %.3f"" % (x3, y3) + '10909310.098 3895303.963' + >>> pipeline_str = ( + ... ""+proj=pipeline +step +proj=longlat +ellps=WGS84 "" + ... ""+step +proj=unitconvert +xy_in=rad +xy_out=deg"" + ... ) + >>> pipe_trans = Transformer.from_pipeline(pipeline_str) + >>> xt, yt = pipe_trans.transform(2.1, 0.001) + >>> ""%.3f %.3f"" % (xt, yt) + '120.321 0.057' + >>> transproj = Transformer.from_crs( + ... {""proj"":'geocent', ""ellps"":'WGS84', ""datum"":'WGS84'}, + ... ""EPSG:4326"", + ... always_xy=True, + ... ) + >>> xpj, ypj, zpj = transproj.transform( + ... -2704026.010, + ... -4253051.810, + ... 3895878.820, + ... radians=True, + ... ) + >>> ""%.3f %.3f %.3f"" % (xpj, ypj, zpj) + '-2.137 0.661 -20.531' + >>> transprojr = Transformer.from_crs( + ... ""EPSG:4326"", + ... {""proj"":'geocent', ""ellps"":'WGS84', ""datum"":'WGS84'}, + ... always_xy=True, + ... ) + >>> xpjr, ypjr, zpjr = transprojr.transform(xpj, ypj, zpj, radians=True) + >>> ""%.3f %.3f %.3f"" % (xpjr, ypjr, zpjr) + '-2704026.010 -4253051.810 3895878.820' + >>> transformer = Transformer.from_proj(""epsg:4326"", 4326, skip_equivalent=True) + >>> xeq, yeq = transformer.transform(33, 98) + >>> ""%.0f %.0f"" % (xeq, yeq) + '33 98' + + """""" + # process inputs, making copies that support buffer API. + inx, xisfloat, xislist, xistuple = _copytobuffer(xx) + iny, yisfloat, yislist, yistuple = _copytobuffer(yy) + if zz is not None: + inz, zisfloat, zislist, zistuple = _copytobuffer(zz) + else: + inz = None + if tt is not None: + intime, tisfloat, tislist, tistuple = _copytobuffer(tt) + else: + intime = None + # call pj_transform. inx,iny,inz buffers modified in place. + self._transformer._transform( + inx, + iny, + inz=inz, + intime=intime, + direction=direction, + radians=radians, + errcheck=errcheck, + ) + # if inputs were lists, tuples or floats, convert back. + outx = _convertback(xisfloat, xislist, xistuple, inx) + outy = _convertback(yisfloat, yislist, xistuple, iny) + return_data = (outx, outy) + if inz is not None: + return_data += ( # type: ignore + _convertback(zisfloat, zislist, zistuple, inz), + ) + if intime is not None: + return_data += ( # type: ignore + _convertback(tisfloat, tislist, tistuple, intime), + ) + return return_data","[{'piece_type': 'other', 'piece_content': 'echo 50 25 0 | cct +proj=pipeline +ellps=GRS80 +step +proj=cart'}, {'piece_type': 'other', 'piece_content': '3717892.6072 4430811.8715 2679074.4629 inf'}, {'piece_type': 'source code', 'piece_content': 'from pyproj import Transformer\\n\\nstring = ""+proj=pipeline +ellps=GRS80 +step +proj=cart""\\npipe = Transformer.from_pipeline(string)\\npipe.transform(50, 25, 0, errcheck=True)'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile """", line 1, in \\nFile ""/usr/local/lib/python3.7/site-packages/pyproj/transformer.py"", line 446, in transform\\nerrcheck=errcheck,\\nFile ""pyproj/_transformer.pyx"", line 463, in pyproj._transformer._Transformer._transform\\npyproj.exceptions.ProjError: transform error: latitude or longitude exceeded limits'}]","Traceback (most recent call last): +File """", line 1, in +File ""/usr/local/lib/python3.7/site-packages/pyproj/transformer.py"", line 446, in transform +errcheck=errcheck, +File ""pyproj/_transformer.pyx"", line 463, in pyproj._transformer._Transformer._transform +pyproj.exceptions.ProjError: transform error: latitude or longitude exceeded limits",pyproj.exceptions.ProjError +" def itransform( + self, + points: Any, + switch: bool = False, + time_3rd: bool = False, + radians: bool = False, + errcheck: bool = False, + direction: Union[TransformDirection, str] = TransformDirection.FORWARD, + ) -> Iterator[Iterable]: + """""" + Iterator/generator version of the function pyproj.Transformer.transform. + + .. versionadded:: 2.1.1 errcheck + .. versionadded:: 2.2.0 direction + + Parameters + ---------- + points: list + List of point tuples. + switch: boolean, optional + If True x, y or lon,lat coordinates of points are switched to y, x + or lat, lon. Default is False. + time_3rd: boolean, optional + If the input coordinates are 3 dimensional and the 3rd dimension is time. + radians: boolean, optional + If True, will expect input data to be in radians and will return radians + if the projection is geographic. Default is False (degrees). Ignored for + pipeline transformations. + errcheck: boolean, optional (default False) + If True an exception is raised if the transformation is invalid. + By default errcheck=False and an invalid transformation + returns ``inf`` and no exception is raised. + direction: pyproj.enums.TransformDirection, optional + The direction of the transform. + Default is :attr:`pyproj.enums.TransformDirection.FORWARD`. + + + Example: + + >>> from pyproj import Transformer + >>> transformer = Transformer.from_crs(4326, 2100) + >>> points = [(22.95, 40.63), (22.81, 40.53), (23.51, 40.86)] + >>> for pt in transformer.itransform(points): '{:.3f} {:.3f}'.format(*pt) + '2221638.801 2637034.372' + '2212924.125 2619851.898' + '2238294.779 2703763.736' + >>> pipeline_str = ( + ... ""+proj=pipeline +step +proj=longlat +ellps=WGS84 "" + ... ""+step +proj=unitconvert +xy_in=rad +xy_out=deg"" + ... ) + >>> pipe_trans = Transformer.from_pipeline(pipeline_str) + >>> for pt in pipe_trans.itransform([(2.1, 0.001)]): + ... '{:.3f} {:.3f}'.format(*pt) + '2.100 0.001' + >>> transproj = Transformer.from_crs( + ... {""proj"":'geocent', ""ellps"":'WGS84', ""datum"":'WGS84'}, + ... ""EPSG:4326"", + ... always_xy=True, + ... ) + >>> for pt in transproj.itransform( + ... [(-2704026.010, -4253051.810, 3895878.820)], + ... radians=True, + ... ): + ... '{:.3f} {:.3f} {:.3f}'.format(*pt) + '-2.137 0.661 -20.531' + >>> transprojr = Transformer.from_crs( + ... ""EPSG:4326"", + ... {""proj"":'geocent', ""ellps"":'WGS84', ""datum"":'WGS84'}, + ... always_xy=True, + ... ) + >>> for pt in transprojr.itransform( + ... [(-2.137, 0.661, -20.531)], + ... radians=True + ... ): + ... '{:.3f} {:.3f} {:.3f}'.format(*pt) + '-2704214.394 -4254414.478 3894270.731' + >>> transproj_eq = Transformer.from_proj( + ... 'EPSG:4326', + ... '+proj=longlat +datum=WGS84 +no_defs +type=crs', + ... always_xy=True, + ... skip_equivalent=True + ... ) + >>> for pt in transproj_eq.itransform([(-2.137, 0.661)]): + ... '{:.3f} {:.3f}'.format(*pt) + '-2.137 0.661' + + """""" + it = iter(points) # point iterator + # get first point to check stride + try: + fst_pt = next(it) + except StopIteration: + raise ValueError(""iterable must contain at least one point"") + + stride = len(fst_pt) + if stride not in (2, 3, 4): + raise ValueError(""points can contain up to 4 coordinates"") + + if time_3rd and stride != 3: + raise ValueError(""'time_3rd' is only valid for 3 coordinates."") + + # create a coordinate sequence generator etc. x1,y1,z1,x2,y2,z2,.... + # chain so the generator returns the first point that was already acquired + coord_gen = chain(fst_pt, (coords[c] for coords in it for c in range(stride))) + + while True: + # create a temporary buffer storage for + # the next 64 points (64*stride*8 bytes) + buff = array(""d"", islice(coord_gen, 0, 64 * stride)) + if len(buff) == 0: + break + + self._transformer._transform_sequence( + stride, + buff, + switch=switch, + direction=direction, + time_3rd=time_3rd, + radians=radians, + errcheck=errcheck, + ) + + for pt in zip(*([iter(buff)] * stride)): + yield pt"," def itransform( + self, + points: Any, + switch: bool = False, + time_3rd: bool = False, + radians: bool = False, + errcheck: bool = False, + direction: Union[TransformDirection, str] = TransformDirection.FORWARD, + ) -> Iterator[Iterable]: + """""" + Iterator/generator version of the function pyproj.Transformer.transform. + + .. versionadded:: 2.1.1 errcheck + .. versionadded:: 2.2.0 direction + + Parameters + ---------- + points: list + List of point tuples. + switch: boolean, optional + If True x, y or lon,lat coordinates of points are switched to y, x + or lat, lon. Default is False. + time_3rd: boolean, optional + If the input coordinates are 3 dimensional and the 3rd dimension is time. + radians: boolean, optional + If True, will expect input data to be in radians and will return radians + if the projection is geographic. Default is False (degrees). Ignored for + pipeline transformations. + errcheck: boolean, optional (default False) + If True an exception is raised if the transformation is invalid. + By default errcheck=False and an invalid transformation + returns ``inf`` and no exception is raised. + direction: pyproj.enums.TransformDirection, optional + The direction of the transform. + Default is :attr:`pyproj.enums.TransformDirection.FORWARD`. + + + Example: + + >>> from pyproj import Transformer + >>> transformer = Transformer.from_crs(4326, 2100) + >>> points = [(22.95, 40.63), (22.81, 40.53), (23.51, 40.86)] + >>> for pt in transformer.itransform(points): '{:.3f} {:.3f}'.format(*pt) + '2221638.801 2637034.372' + '2212924.125 2619851.898' + '2238294.779 2703763.736' + >>> pipeline_str = ( + ... ""+proj=pipeline +step +proj=longlat +ellps=WGS84 "" + ... ""+step +proj=unitconvert +xy_in=rad +xy_out=deg"" + ... ) + >>> pipe_trans = Transformer.from_pipeline(pipeline_str) + >>> for pt in pipe_trans.itransform([(2.1, 0.001)]): + ... '{:.3f} {:.3f}'.format(*pt) + '120.321 0.057' + >>> transproj = Transformer.from_crs( + ... {""proj"":'geocent', ""ellps"":'WGS84', ""datum"":'WGS84'}, + ... ""EPSG:4326"", + ... always_xy=True, + ... ) + >>> for pt in transproj.itransform( + ... [(-2704026.010, -4253051.810, 3895878.820)], + ... radians=True, + ... ): + ... '{:.3f} {:.3f} {:.3f}'.format(*pt) + '-2.137 0.661 -20.531' + >>> transprojr = Transformer.from_crs( + ... ""EPSG:4326"", + ... {""proj"":'geocent', ""ellps"":'WGS84', ""datum"":'WGS84'}, + ... always_xy=True, + ... ) + >>> for pt in transprojr.itransform( + ... [(-2.137, 0.661, -20.531)], + ... radians=True + ... ): + ... '{:.3f} {:.3f} {:.3f}'.format(*pt) + '-2704214.394 -4254414.478 3894270.731' + >>> transproj_eq = Transformer.from_proj( + ... 'EPSG:4326', + ... '+proj=longlat +datum=WGS84 +no_defs +type=crs', + ... always_xy=True, + ... skip_equivalent=True + ... ) + >>> for pt in transproj_eq.itransform([(-2.137, 0.661)]): + ... '{:.3f} {:.3f}'.format(*pt) + '-2.137 0.661' + + """""" + it = iter(points) # point iterator + # get first point to check stride + try: + fst_pt = next(it) + except StopIteration: + raise ValueError(""iterable must contain at least one point"") + + stride = len(fst_pt) + if stride not in (2, 3, 4): + raise ValueError(""points can contain up to 4 coordinates"") + + if time_3rd and stride != 3: + raise ValueError(""'time_3rd' is only valid for 3 coordinates."") + + # create a coordinate sequence generator etc. x1,y1,z1,x2,y2,z2,.... + # chain so the generator returns the first point that was already acquired + coord_gen = chain(fst_pt, (coords[c] for coords in it for c in range(stride))) + + while True: + # create a temporary buffer storage for + # the next 64 points (64*stride*8 bytes) + buff = array(""d"", islice(coord_gen, 0, 64 * stride)) + if len(buff) == 0: + break + + self._transformer._transform_sequence( + stride, + buff, + switch=switch, + direction=direction, + time_3rd=time_3rd, + radians=radians, + errcheck=errcheck, + ) + + for pt in zip(*([iter(buff)] * stride)): + yield pt","[{'piece_type': 'other', 'piece_content': 'echo 50 25 0 | cct +proj=pipeline +ellps=GRS80 +step +proj=cart'}, {'piece_type': 'other', 'piece_content': '3717892.6072 4430811.8715 2679074.4629 inf'}, {'piece_type': 'source code', 'piece_content': 'from pyproj import Transformer\\n\\nstring = ""+proj=pipeline +ellps=GRS80 +step +proj=cart""\\npipe = Transformer.from_pipeline(string)\\npipe.transform(50, 25, 0, errcheck=True)'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile """", line 1, in \\nFile ""/usr/local/lib/python3.7/site-packages/pyproj/transformer.py"", line 446, in transform\\nerrcheck=errcheck,\\nFile ""pyproj/_transformer.pyx"", line 463, in pyproj._transformer._Transformer._transform\\npyproj.exceptions.ProjError: transform error: latitude or longitude exceeded limits'}]","Traceback (most recent call last): +File """", line 1, in +File ""/usr/local/lib/python3.7/site-packages/pyproj/transformer.py"", line 446, in transform +errcheck=errcheck, +File ""pyproj/_transformer.pyx"", line 463, in pyproj._transformer._Transformer._transform +pyproj.exceptions.ProjError: transform error: latitude or longitude exceeded limits",pyproj.exceptions.ProjError +" def from_user_input(value: Any) -> ""CRS"": + """""" + Initialize a CRS class instance with: + - PROJ string + - Dictionary of PROJ parameters + - PROJ keyword arguments for parameters + - JSON string with PROJ parameters + - CRS WKT string + - An authority string [i.e. 'epsg:4326'] + - An EPSG integer code [i.e. 4326] + - A tuple of (""auth_name"": ""auth_code"") [i.e ('epsg', '4326')] + - An object with a `to_wkt` method. + - A :class:`pyproj.crs.CRS` class + + Parameters + ---------- + value : obj + A Python int, dict, or str. + + Returns + ------- + CRS + """""" + if isinstance(value, CRS): + return value + return CRS(value)"," def from_user_input(value: str) -> ""CRS"": + """""" + Initialize a CRS class instance with: + - PROJ string + - Dictionary of PROJ parameters + - PROJ keyword arguments for parameters + - JSON string with PROJ parameters + - CRS WKT string + - An authority string [i.e. 'epsg:4326'] + - An EPSG integer code [i.e. 4326] + - A tuple of (""auth_name"": ""auth_code"") [i.e ('epsg', '4326')] + - An object with a `to_wkt` method. + - A :class:`pyproj.crs.CRS` class + + Parameters + ---------- + value : obj + A Python int, dict, or str. + + Returns + ------- + CRS + """""" + if isinstance(value, CRS): + return value + return CRS(value)","[{'piece_type': 'error message', 'piece_content': 'import pyproj\\n\\n---------------------------------------------------------------------------\\nKeyError Traceback (most recent call last)\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name()\\n\\nKeyError: \\'URN:OGC:DEF:DATUM:EPSG::6326\\'\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nCRSError Traceback (most recent call last)\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name()\\n\\nCRSError: Invalid datum name: urn:ogc:def:datum:EPSG::6326\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nCRSError Traceback (most recent call last)\\n in \\n----> 1 import pyproj\\n\\n~/scipy/repos/pyproj/pyproj/__init__.py in \\n79 )\\n80 from pyproj._show_versions import show_versions # noqa: F401\\n---> 81 from pyproj.crs import CRS # noqa: F401\\n82 from pyproj.exceptions import DataDirError, ProjError # noqa: F401\\n83 from pyproj.geod import Geod, geodesic_version_str, pj_ellps # noqa: F401\\n\\n~/scipy/repos/pyproj/pyproj/crs/__init__.py in \\n17 is_wkt,\\n18 )\\n---> 19 from pyproj.crs.crs import ( # noqa: F401\\n20 CRS,\\n21 BoundCRS,\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in \\n1026\\n1027\\n-> 1028 class ProjectedCRS(CRS):\\n1029 """"""\\n1030 .. versionadded:: 2.5.0\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in ProjectedCRS()\\n1038 name=""undefined"",\\n1039 cartesian_cs=Cartesian2DCS(),\\n-> 1040 geodetic_crs=GeographicCRS(),\\n1041 ):\\n1042 """"""\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in __init__(self, name, datum, ellipsoidal_cs)\\n977 ""type"": ""GeographicCRS"",\\n978 ""name"": name,\\n--> 979 ""datum"": Datum.from_user_input(datum).to_json_dict(),\\n980 ""coordinate_system"": CoordinateSystem.from_user_input(\\n981 ellipsoidal_cs\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs._CRSParts.from_user_input()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum._from_string()\\n\\nCRSError: Invalid datum string: urn:ogc:def:datum:EPSG::6326: (Internal Proj Error: proj_create: SQLite error on SELECT name, ellipsoid_auth_name, ellipsoid_code, prime_meridian_auth_name, prime_meridian_code, area_of_use_auth_name, area_of_use_code, publication_date, deprecated FROM geodetic_datum WHERE auth_name = ? AND code = ?: no such column: publication_date)'}]","import pyproj + +--------------------------------------------------------------------------- +KeyError Traceback (most recent call last) +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name() + +KeyError: 'URN:OGC:DEF:DATUM:EPSG::6326' + +During handling of the above exception, another exception occurred: + +CRSError Traceback (most recent call last) +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name() + +CRSError: Invalid datum name: urn:ogc:def:datum:EPSG::6326 + +During handling of the above exception, another exception occurred: + +CRSError Traceback (most recent call last) + in +----> 1 import pyproj + +~/scipy/repos/pyproj/pyproj/__init__.py in +79 ) +80 from pyproj._show_versions import show_versions # noqa: F401 +---> 81 from pyproj.crs import CRS # noqa: F401 +82 from pyproj.exceptions import DataDirError, ProjError # noqa: F401 +83 from pyproj.geod import Geod, geodesic_version_str, pj_ellps # noqa: F401 + +~/scipy/repos/pyproj/pyproj/crs/__init__.py in +17 is_wkt, +18 ) +---> 19 from pyproj.crs.crs import ( # noqa: F401 +20 CRS, +21 BoundCRS, + +~/scipy/repos/pyproj/pyproj/crs/crs.py in +1026 +1027 +-> 1028 class ProjectedCRS(CRS): +1029 """""" +1030 .. versionadded:: 2.5.0 + +~/scipy/repos/pyproj/pyproj/crs/crs.py in ProjectedCRS() +1038 name=""undefined"", +1039 cartesian_cs=Cartesian2DCS(), +-> 1040 geodetic_crs=GeographicCRS(), +1041 ): +1042 """""" + +~/scipy/repos/pyproj/pyproj/crs/crs.py in __init__(self, name, datum, ellipsoidal_cs) +977 ""type"": ""GeographicCRS"", +978 ""name"": name, +--> 979 ""datum"": Datum.from_user_input(datum).to_json_dict(), +980 ""coordinate_system"": CoordinateSystem.from_user_input( +981 ellipsoidal_cs + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs._CRSParts.from_user_input() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum._from_string() + +CRSError: Invalid datum string: urn:ogc:def:datum:EPSG::6326: (Internal Proj Error: proj_create: SQLite error on SELECT name, ellipsoid_auth_name, ellipsoid_code, prime_meridian_auth_name, prime_meridian_code, area_of_use_auth_name, area_of_use_code, publication_date, deprecated FROM geodetic_datum WHERE auth_name = ? AND code = ?: no such column: publication_date)",KeyError +" def __init__( + self, + name: str = ""undefined"", + datum: Any = ""urn:ogc:def:datum:EPSG::6326"", + ellipsoidal_cs: Any = None, + ) -> None: + """""" + Parameters + ---------- + name: str, optional + Name of the CRS. Default is undefined. + datum: Any, optional + Anything accepted by :meth:`pyproj.crs.Datum.from_user_input` or + a :class:`pyproj.crs.datum.CustomDatum`. + ellipsoidal_cs: Any, optional + Input to create an Ellipsoidal Coordinate System. + Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or an Ellipsoidal Coordinate System created from :ref:`coordinate_system`. + """""" + geographic_crs_json = { + ""$schema"": ""https://proj.org/schemas/v0.2/projjson.schema.json"", + ""type"": ""GeographicCRS"", + ""name"": name, + ""datum"": Datum.from_user_input(datum).to_json_dict(), + ""coordinate_system"": CoordinateSystem.from_user_input( + ellipsoidal_cs or Ellipsoidal2DCS() + ).to_json_dict(), + } + super().__init__(geographic_crs_json)"," def __init__( + self, + name: str = ""undefined"", + datum: Any = ""urn:ogc:def:datum:EPSG::6326"", + ellipsoidal_cs: Any = Ellipsoidal2DCS(), + ) -> None: + """""" + Parameters + ---------- + name: str, optional + Name of the CRS. Default is undefined. + datum: Any, optional + Anything accepted by :meth:`pyproj.crs.Datum.from_user_input` or + a :class:`pyproj.crs.datum.CustomDatum`. + ellipsoidal_cs: Any, optional + Input to create an Ellipsoidal Coordinate System. + Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or an Ellipsoidal Coordinate System created from :ref:`coordinate_system`. + """""" + geographic_crs_json = { + ""$schema"": ""https://proj.org/schemas/v0.2/projjson.schema.json"", + ""type"": ""GeographicCRS"", + ""name"": name, + ""datum"": Datum.from_user_input(datum).to_json_dict(), + ""coordinate_system"": CoordinateSystem.from_user_input( + ellipsoidal_cs + ).to_json_dict(), + } + super().__init__(geographic_crs_json)","[{'piece_type': 'error message', 'piece_content': 'import pyproj\\n\\n---------------------------------------------------------------------------\\nKeyError Traceback (most recent call last)\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name()\\n\\nKeyError: \\'URN:OGC:DEF:DATUM:EPSG::6326\\'\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nCRSError Traceback (most recent call last)\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name()\\n\\nCRSError: Invalid datum name: urn:ogc:def:datum:EPSG::6326\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nCRSError Traceback (most recent call last)\\n in \\n----> 1 import pyproj\\n\\n~/scipy/repos/pyproj/pyproj/__init__.py in \\n79 )\\n80 from pyproj._show_versions import show_versions # noqa: F401\\n---> 81 from pyproj.crs import CRS # noqa: F401\\n82 from pyproj.exceptions import DataDirError, ProjError # noqa: F401\\n83 from pyproj.geod import Geod, geodesic_version_str, pj_ellps # noqa: F401\\n\\n~/scipy/repos/pyproj/pyproj/crs/__init__.py in \\n17 is_wkt,\\n18 )\\n---> 19 from pyproj.crs.crs import ( # noqa: F401\\n20 CRS,\\n21 BoundCRS,\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in \\n1026\\n1027\\n-> 1028 class ProjectedCRS(CRS):\\n1029 """"""\\n1030 .. versionadded:: 2.5.0\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in ProjectedCRS()\\n1038 name=""undefined"",\\n1039 cartesian_cs=Cartesian2DCS(),\\n-> 1040 geodetic_crs=GeographicCRS(),\\n1041 ):\\n1042 """"""\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in __init__(self, name, datum, ellipsoidal_cs)\\n977 ""type"": ""GeographicCRS"",\\n978 ""name"": name,\\n--> 979 ""datum"": Datum.from_user_input(datum).to_json_dict(),\\n980 ""coordinate_system"": CoordinateSystem.from_user_input(\\n981 ellipsoidal_cs\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs._CRSParts.from_user_input()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum._from_string()\\n\\nCRSError: Invalid datum string: urn:ogc:def:datum:EPSG::6326: (Internal Proj Error: proj_create: SQLite error on SELECT name, ellipsoid_auth_name, ellipsoid_code, prime_meridian_auth_name, prime_meridian_code, area_of_use_auth_name, area_of_use_code, publication_date, deprecated FROM geodetic_datum WHERE auth_name = ? AND code = ?: no such column: publication_date)'}]","import pyproj + +--------------------------------------------------------------------------- +KeyError Traceback (most recent call last) +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name() + +KeyError: 'URN:OGC:DEF:DATUM:EPSG::6326' + +During handling of the above exception, another exception occurred: + +CRSError Traceback (most recent call last) +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name() + +CRSError: Invalid datum name: urn:ogc:def:datum:EPSG::6326 + +During handling of the above exception, another exception occurred: + +CRSError Traceback (most recent call last) + in +----> 1 import pyproj + +~/scipy/repos/pyproj/pyproj/__init__.py in +79 ) +80 from pyproj._show_versions import show_versions # noqa: F401 +---> 81 from pyproj.crs import CRS # noqa: F401 +82 from pyproj.exceptions import DataDirError, ProjError # noqa: F401 +83 from pyproj.geod import Geod, geodesic_version_str, pj_ellps # noqa: F401 + +~/scipy/repos/pyproj/pyproj/crs/__init__.py in +17 is_wkt, +18 ) +---> 19 from pyproj.crs.crs import ( # noqa: F401 +20 CRS, +21 BoundCRS, + +~/scipy/repos/pyproj/pyproj/crs/crs.py in +1026 +1027 +-> 1028 class ProjectedCRS(CRS): +1029 """""" +1030 .. versionadded:: 2.5.0 + +~/scipy/repos/pyproj/pyproj/crs/crs.py in ProjectedCRS() +1038 name=""undefined"", +1039 cartesian_cs=Cartesian2DCS(), +-> 1040 geodetic_crs=GeographicCRS(), +1041 ): +1042 """""" + +~/scipy/repos/pyproj/pyproj/crs/crs.py in __init__(self, name, datum, ellipsoidal_cs) +977 ""type"": ""GeographicCRS"", +978 ""name"": name, +--> 979 ""datum"": Datum.from_user_input(datum).to_json_dict(), +980 ""coordinate_system"": CoordinateSystem.from_user_input( +981 ellipsoidal_cs + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs._CRSParts.from_user_input() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum._from_string() + +CRSError: Invalid datum string: urn:ogc:def:datum:EPSG::6326: (Internal Proj Error: proj_create: SQLite error on SELECT name, ellipsoid_auth_name, ellipsoid_code, prime_meridian_auth_name, prime_meridian_code, area_of_use_auth_name, area_of_use_code, publication_date, deprecated FROM geodetic_datum WHERE auth_name = ? AND code = ?: no such column: publication_date)",KeyError +" def __init__( + self, + base_crs: Any, + conversion: Any, + ellipsoidal_cs: Any = None, + name: str = ""undefined"", + ) -> None: + """""" + Parameters + ---------- + base_crs: Any + Input to create the Geodetic CRS, a :class:`GeographicCRS` or + anything accepted by :meth:`pyproj.crs.CRS.from_user_input`. + conversion: Any + Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or a conversion from :ref:`coordinate_operation`. + ellipsoidal_cs: Any, optional + Input to create an Ellipsoidal Coordinate System. + Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or an Ellipsoidal Coordinate System created from :ref:`coordinate_system`. + name: str, optional + Name of the CRS. Default is undefined. + """""" + derived_geographic_crs_json = { + ""$schema"": ""https://proj.org/schemas/v0.2/projjson.schema.json"", + ""type"": ""DerivedGeographicCRS"", + ""name"": name, + ""base_crs"": CRS.from_user_input(base_crs).to_json_dict(), + ""conversion"": CoordinateOperation.from_user_input( + conversion + ).to_json_dict(), + ""coordinate_system"": CoordinateSystem.from_user_input( + ellipsoidal_cs or Ellipsoidal2DCS() + ).to_json_dict(), + } + super().__init__(derived_geographic_crs_json)"," def __init__( + self, + base_crs: Any, + conversion: Any, + ellipsoidal_cs: Any = Ellipsoidal2DCS(), + name: str = ""undefined"", + ) -> None: + """""" + Parameters + ---------- + base_crs: Any + Input to create the Geodetic CRS, a :class:`GeographicCRS` or + anything accepted by :meth:`pyproj.crs.CRS.from_user_input`. + conversion: Any + Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or a conversion from :ref:`coordinate_operation`. + ellipsoidal_cs: Any, optional + Input to create an Ellipsoidal Coordinate System. + Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or an Ellipsoidal Coordinate System created from :ref:`coordinate_system`. + name: str, optional + Name of the CRS. Default is undefined. + """""" + derived_geographic_crs_json = { + ""$schema"": ""https://proj.org/schemas/v0.2/projjson.schema.json"", + ""type"": ""DerivedGeographicCRS"", + ""name"": name, + ""base_crs"": CRS.from_user_input(base_crs).to_json_dict(), + ""conversion"": CoordinateOperation.from_user_input( + conversion + ).to_json_dict(), + ""coordinate_system"": CoordinateSystem.from_user_input( + ellipsoidal_cs + ).to_json_dict(), + } + super().__init__(derived_geographic_crs_json)","[{'piece_type': 'error message', 'piece_content': 'import pyproj\\n\\n---------------------------------------------------------------------------\\nKeyError Traceback (most recent call last)\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name()\\n\\nKeyError: \\'URN:OGC:DEF:DATUM:EPSG::6326\\'\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nCRSError Traceback (most recent call last)\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name()\\n\\nCRSError: Invalid datum name: urn:ogc:def:datum:EPSG::6326\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nCRSError Traceback (most recent call last)\\n in \\n----> 1 import pyproj\\n\\n~/scipy/repos/pyproj/pyproj/__init__.py in \\n79 )\\n80 from pyproj._show_versions import show_versions # noqa: F401\\n---> 81 from pyproj.crs import CRS # noqa: F401\\n82 from pyproj.exceptions import DataDirError, ProjError # noqa: F401\\n83 from pyproj.geod import Geod, geodesic_version_str, pj_ellps # noqa: F401\\n\\n~/scipy/repos/pyproj/pyproj/crs/__init__.py in \\n17 is_wkt,\\n18 )\\n---> 19 from pyproj.crs.crs import ( # noqa: F401\\n20 CRS,\\n21 BoundCRS,\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in \\n1026\\n1027\\n-> 1028 class ProjectedCRS(CRS):\\n1029 """"""\\n1030 .. versionadded:: 2.5.0\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in ProjectedCRS()\\n1038 name=""undefined"",\\n1039 cartesian_cs=Cartesian2DCS(),\\n-> 1040 geodetic_crs=GeographicCRS(),\\n1041 ):\\n1042 """"""\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in __init__(self, name, datum, ellipsoidal_cs)\\n977 ""type"": ""GeographicCRS"",\\n978 ""name"": name,\\n--> 979 ""datum"": Datum.from_user_input(datum).to_json_dict(),\\n980 ""coordinate_system"": CoordinateSystem.from_user_input(\\n981 ellipsoidal_cs\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs._CRSParts.from_user_input()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum._from_string()\\n\\nCRSError: Invalid datum string: urn:ogc:def:datum:EPSG::6326: (Internal Proj Error: proj_create: SQLite error on SELECT name, ellipsoid_auth_name, ellipsoid_code, prime_meridian_auth_name, prime_meridian_code, area_of_use_auth_name, area_of_use_code, publication_date, deprecated FROM geodetic_datum WHERE auth_name = ? AND code = ?: no such column: publication_date)'}]","import pyproj + +--------------------------------------------------------------------------- +KeyError Traceback (most recent call last) +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name() + +KeyError: 'URN:OGC:DEF:DATUM:EPSG::6326' + +During handling of the above exception, another exception occurred: + +CRSError Traceback (most recent call last) +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name() + +CRSError: Invalid datum name: urn:ogc:def:datum:EPSG::6326 + +During handling of the above exception, another exception occurred: + +CRSError Traceback (most recent call last) + in +----> 1 import pyproj + +~/scipy/repos/pyproj/pyproj/__init__.py in +79 ) +80 from pyproj._show_versions import show_versions # noqa: F401 +---> 81 from pyproj.crs import CRS # noqa: F401 +82 from pyproj.exceptions import DataDirError, ProjError # noqa: F401 +83 from pyproj.geod import Geod, geodesic_version_str, pj_ellps # noqa: F401 + +~/scipy/repos/pyproj/pyproj/crs/__init__.py in +17 is_wkt, +18 ) +---> 19 from pyproj.crs.crs import ( # noqa: F401 +20 CRS, +21 BoundCRS, + +~/scipy/repos/pyproj/pyproj/crs/crs.py in +1026 +1027 +-> 1028 class ProjectedCRS(CRS): +1029 """""" +1030 .. versionadded:: 2.5.0 + +~/scipy/repos/pyproj/pyproj/crs/crs.py in ProjectedCRS() +1038 name=""undefined"", +1039 cartesian_cs=Cartesian2DCS(), +-> 1040 geodetic_crs=GeographicCRS(), +1041 ): +1042 """""" + +~/scipy/repos/pyproj/pyproj/crs/crs.py in __init__(self, name, datum, ellipsoidal_cs) +977 ""type"": ""GeographicCRS"", +978 ""name"": name, +--> 979 ""datum"": Datum.from_user_input(datum).to_json_dict(), +980 ""coordinate_system"": CoordinateSystem.from_user_input( +981 ellipsoidal_cs + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs._CRSParts.from_user_input() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum._from_string() + +CRSError: Invalid datum string: urn:ogc:def:datum:EPSG::6326: (Internal Proj Error: proj_create: SQLite error on SELECT name, ellipsoid_auth_name, ellipsoid_code, prime_meridian_auth_name, prime_meridian_code, area_of_use_auth_name, area_of_use_code, publication_date, deprecated FROM geodetic_datum WHERE auth_name = ? AND code = ?: no such column: publication_date)",KeyError +" def __init__( + self, + conversion: Any, + name: str = ""undefined"", + cartesian_cs: Any = None, + geodetic_crs: Any = None, + ) -> None: + """""" + Parameters + ---------- + conversion: Any + Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or a conversion from :ref:`coordinate_operation`. + name: str, optional + The name of the Projected CRS. Default is undefined. + cartesian_cs: Any, optional + Input to create a Cartesian Coordinate System. + Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or :class:`pyproj.crs.coordinate_system.Cartesian2DCS`. + geodetic_crs: Any, optional + Input to create the Geodetic CRS, a :class:`GeographicCRS` or + anything accepted by :meth:`pyproj.crs.CRS.from_user_input`. + """""" + proj_crs_json = { + ""$schema"": ""https://proj.org/schemas/v0.2/projjson.schema.json"", + ""type"": ""ProjectedCRS"", + ""name"": name, + ""base_crs"": CRS.from_user_input( + geodetic_crs or GeographicCRS() + ).to_json_dict(), + ""conversion"": CoordinateOperation.from_user_input( + conversion + ).to_json_dict(), + ""coordinate_system"": CoordinateSystem.from_user_input( + cartesian_cs or Cartesian2DCS() + ).to_json_dict(), + } + super().__init__(proj_crs_json)"," def __init__( + self, + conversion: Any, + name: str = ""undefined"", + cartesian_cs: Any = Cartesian2DCS(), + geodetic_crs: Any = GeographicCRS(), + ) -> None: + """""" + Parameters + ---------- + conversion: Any + Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or a conversion from :ref:`coordinate_operation`. + name: str, optional + The name of the Projected CRS. Default is undefined. + cartesian_cs: Any, optional + Input to create a Cartesian Coordinate System. + Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or :class:`pyproj.crs.coordinate_system.Cartesian2DCS`. + geodetic_crs: Any, optional + Input to create the Geodetic CRS, a :class:`GeographicCRS` or + anything accepted by :meth:`pyproj.crs.CRS.from_user_input`. + """""" + proj_crs_json = { + ""$schema"": ""https://proj.org/schemas/v0.2/projjson.schema.json"", + ""type"": ""ProjectedCRS"", + ""name"": name, + ""base_crs"": CRS.from_user_input(geodetic_crs).to_json_dict(), + ""conversion"": CoordinateOperation.from_user_input( + conversion + ).to_json_dict(), + ""coordinate_system"": CoordinateSystem.from_user_input( + cartesian_cs + ).to_json_dict(), + } + super().__init__(proj_crs_json)","[{'piece_type': 'error message', 'piece_content': 'import pyproj\\n\\n---------------------------------------------------------------------------\\nKeyError Traceback (most recent call last)\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name()\\n\\nKeyError: \\'URN:OGC:DEF:DATUM:EPSG::6326\\'\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nCRSError Traceback (most recent call last)\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name()\\n\\nCRSError: Invalid datum name: urn:ogc:def:datum:EPSG::6326\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nCRSError Traceback (most recent call last)\\n in \\n----> 1 import pyproj\\n\\n~/scipy/repos/pyproj/pyproj/__init__.py in \\n79 )\\n80 from pyproj._show_versions import show_versions # noqa: F401\\n---> 81 from pyproj.crs import CRS # noqa: F401\\n82 from pyproj.exceptions import DataDirError, ProjError # noqa: F401\\n83 from pyproj.geod import Geod, geodesic_version_str, pj_ellps # noqa: F401\\n\\n~/scipy/repos/pyproj/pyproj/crs/__init__.py in \\n17 is_wkt,\\n18 )\\n---> 19 from pyproj.crs.crs import ( # noqa: F401\\n20 CRS,\\n21 BoundCRS,\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in \\n1026\\n1027\\n-> 1028 class ProjectedCRS(CRS):\\n1029 """"""\\n1030 .. versionadded:: 2.5.0\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in ProjectedCRS()\\n1038 name=""undefined"",\\n1039 cartesian_cs=Cartesian2DCS(),\\n-> 1040 geodetic_crs=GeographicCRS(),\\n1041 ):\\n1042 """"""\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in __init__(self, name, datum, ellipsoidal_cs)\\n977 ""type"": ""GeographicCRS"",\\n978 ""name"": name,\\n--> 979 ""datum"": Datum.from_user_input(datum).to_json_dict(),\\n980 ""coordinate_system"": CoordinateSystem.from_user_input(\\n981 ellipsoidal_cs\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs._CRSParts.from_user_input()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum._from_string()\\n\\nCRSError: Invalid datum string: urn:ogc:def:datum:EPSG::6326: (Internal Proj Error: proj_create: SQLite error on SELECT name, ellipsoid_auth_name, ellipsoid_code, prime_meridian_auth_name, prime_meridian_code, area_of_use_auth_name, area_of_use_code, publication_date, deprecated FROM geodetic_datum WHERE auth_name = ? AND code = ?: no such column: publication_date)'}]","import pyproj + +--------------------------------------------------------------------------- +KeyError Traceback (most recent call last) +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name() + +KeyError: 'URN:OGC:DEF:DATUM:EPSG::6326' + +During handling of the above exception, another exception occurred: + +CRSError Traceback (most recent call last) +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name() + +CRSError: Invalid datum name: urn:ogc:def:datum:EPSG::6326 + +During handling of the above exception, another exception occurred: + +CRSError Traceback (most recent call last) + in +----> 1 import pyproj + +~/scipy/repos/pyproj/pyproj/__init__.py in +79 ) +80 from pyproj._show_versions import show_versions # noqa: F401 +---> 81 from pyproj.crs import CRS # noqa: F401 +82 from pyproj.exceptions import DataDirError, ProjError # noqa: F401 +83 from pyproj.geod import Geod, geodesic_version_str, pj_ellps # noqa: F401 + +~/scipy/repos/pyproj/pyproj/crs/__init__.py in +17 is_wkt, +18 ) +---> 19 from pyproj.crs.crs import ( # noqa: F401 +20 CRS, +21 BoundCRS, + +~/scipy/repos/pyproj/pyproj/crs/crs.py in +1026 +1027 +-> 1028 class ProjectedCRS(CRS): +1029 """""" +1030 .. versionadded:: 2.5.0 + +~/scipy/repos/pyproj/pyproj/crs/crs.py in ProjectedCRS() +1038 name=""undefined"", +1039 cartesian_cs=Cartesian2DCS(), +-> 1040 geodetic_crs=GeographicCRS(), +1041 ): +1042 """""" + +~/scipy/repos/pyproj/pyproj/crs/crs.py in __init__(self, name, datum, ellipsoidal_cs) +977 ""type"": ""GeographicCRS"", +978 ""name"": name, +--> 979 ""datum"": Datum.from_user_input(datum).to_json_dict(), +980 ""coordinate_system"": CoordinateSystem.from_user_input( +981 ellipsoidal_cs + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs._CRSParts.from_user_input() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum._from_string() + +CRSError: Invalid datum string: urn:ogc:def:datum:EPSG::6326: (Internal Proj Error: proj_create: SQLite error on SELECT name, ellipsoid_auth_name, ellipsoid_code, prime_meridian_auth_name, prime_meridian_code, area_of_use_auth_name, area_of_use_code, publication_date, deprecated FROM geodetic_datum WHERE auth_name = ? AND code = ?: no such column: publication_date)",KeyError +" def __init__( + self, + name: str, + datum: Any, + vertical_cs: Any = None, + geoid_model: Optional[str] = None, + ) -> None: + """""" + Parameters + ---------- + name: str + The name of the Vertical CRS (e.g. NAVD88 height). + datum: Any + Anything accepted by :meth:`pyproj.crs.Datum.from_user_input` + vertical_cs: Any, optional + Input to create a Vertical Coordinate System accepted by + :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or :class:`pyproj.crs.coordinate_system.VerticalCS` + geoid_model: str, optional + The name of the GEOID Model (e.g. GEOID12B). + """""" + vert_crs_json = { + ""$schema"": ""https://proj.org/schemas/v0.2/projjson.schema.json"", + ""type"": ""VerticalCRS"", + ""name"": name, + ""datum"": Datum.from_user_input(datum).to_json_dict(), + ""coordinate_system"": CoordinateSystem.from_user_input( + vertical_cs or VerticalCS() + ).to_json_dict(), + } + if geoid_model is not None: + vert_crs_json[""geoid_model""] = {""name"": geoid_model} + + super().__init__(vert_crs_json)"," def __init__( + self, + name: str, + datum: Any, + vertical_cs: Any = VerticalCS(), + geoid_model: str = None, + ) -> None: + """""" + Parameters + ---------- + name: str + The name of the Vertical CRS (e.g. NAVD88 height). + datum: Any + Anything accepted by :meth:`pyproj.crs.Datum.from_user_input` + vertical_cs: Any, optional + Input to create a Vertical Coordinate System accepted by + :meth:`pyproj.crs.CoordinateSystem.from_user_input` + or :class:`pyproj.crs.coordinate_system.VerticalCS` + geoid_model: str, optional + The name of the GEOID Model (e.g. GEOID12B). + """""" + vert_crs_json = { + ""$schema"": ""https://proj.org/schemas/v0.2/projjson.schema.json"", + ""type"": ""VerticalCRS"", + ""name"": name, + ""datum"": Datum.from_user_input(datum).to_json_dict(), + ""coordinate_system"": CoordinateSystem.from_user_input( + vertical_cs + ).to_json_dict(), + } + if geoid_model is not None: + vert_crs_json[""geoid_model""] = {""name"": geoid_model} + + super().__init__(vert_crs_json)","[{'piece_type': 'error message', 'piece_content': 'import pyproj\\n\\n---------------------------------------------------------------------------\\nKeyError Traceback (most recent call last)\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name()\\n\\nKeyError: \\'URN:OGC:DEF:DATUM:EPSG::6326\\'\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nCRSError Traceback (most recent call last)\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name()\\n\\nCRSError: Invalid datum name: urn:ogc:def:datum:EPSG::6326\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nCRSError Traceback (most recent call last)\\n in \\n----> 1 import pyproj\\n\\n~/scipy/repos/pyproj/pyproj/__init__.py in \\n79 )\\n80 from pyproj._show_versions import show_versions # noqa: F401\\n---> 81 from pyproj.crs import CRS # noqa: F401\\n82 from pyproj.exceptions import DataDirError, ProjError # noqa: F401\\n83 from pyproj.geod import Geod, geodesic_version_str, pj_ellps # noqa: F401\\n\\n~/scipy/repos/pyproj/pyproj/crs/__init__.py in \\n17 is_wkt,\\n18 )\\n---> 19 from pyproj.crs.crs import ( # noqa: F401\\n20 CRS,\\n21 BoundCRS,\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in \\n1026\\n1027\\n-> 1028 class ProjectedCRS(CRS):\\n1029 """"""\\n1030 .. versionadded:: 2.5.0\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in ProjectedCRS()\\n1038 name=""undefined"",\\n1039 cartesian_cs=Cartesian2DCS(),\\n-> 1040 geodetic_crs=GeographicCRS(),\\n1041 ):\\n1042 """"""\\n\\n~/scipy/repos/pyproj/pyproj/crs/crs.py in __init__(self, name, datum, ellipsoidal_cs)\\n977 ""type"": ""GeographicCRS"",\\n978 ""name"": name,\\n--> 979 ""datum"": Datum.from_user_input(datum).to_json_dict(),\\n980 ""coordinate_system"": CoordinateSystem.from_user_input(\\n981 ellipsoidal_cs\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs._CRSParts.from_user_input()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string()\\n\\n~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum._from_string()\\n\\nCRSError: Invalid datum string: urn:ogc:def:datum:EPSG::6326: (Internal Proj Error: proj_create: SQLite error on SELECT name, ellipsoid_auth_name, ellipsoid_code, prime_meridian_auth_name, prime_meridian_code, area_of_use_auth_name, area_of_use_code, publication_date, deprecated FROM geodetic_datum WHERE auth_name = ? AND code = ?: no such column: publication_date)'}]","import pyproj + +--------------------------------------------------------------------------- +KeyError Traceback (most recent call last) +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name() + +KeyError: 'URN:OGC:DEF:DATUM:EPSG::6326' + +During handling of the above exception, another exception occurred: + +CRSError Traceback (most recent call last) +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_name() + +CRSError: Invalid datum name: urn:ogc:def:datum:EPSG::6326 + +During handling of the above exception, another exception occurred: + +CRSError Traceback (most recent call last) + in +----> 1 import pyproj + +~/scipy/repos/pyproj/pyproj/__init__.py in +79 ) +80 from pyproj._show_versions import show_versions # noqa: F401 +---> 81 from pyproj.crs import CRS # noqa: F401 +82 from pyproj.exceptions import DataDirError, ProjError # noqa: F401 +83 from pyproj.geod import Geod, geodesic_version_str, pj_ellps # noqa: F401 + +~/scipy/repos/pyproj/pyproj/crs/__init__.py in +17 is_wkt, +18 ) +---> 19 from pyproj.crs.crs import ( # noqa: F401 +20 CRS, +21 BoundCRS, + +~/scipy/repos/pyproj/pyproj/crs/crs.py in +1026 +1027 +-> 1028 class ProjectedCRS(CRS): +1029 """""" +1030 .. versionadded:: 2.5.0 + +~/scipy/repos/pyproj/pyproj/crs/crs.py in ProjectedCRS() +1038 name=""undefined"", +1039 cartesian_cs=Cartesian2DCS(), +-> 1040 geodetic_crs=GeographicCRS(), +1041 ): +1042 """""" + +~/scipy/repos/pyproj/pyproj/crs/crs.py in __init__(self, name, datum, ellipsoidal_cs) +977 ""type"": ""GeographicCRS"", +978 ""name"": name, +--> 979 ""datum"": Datum.from_user_input(datum).to_json_dict(), +980 ""coordinate_system"": CoordinateSystem.from_user_input( +981 ellipsoidal_cs + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs._CRSParts.from_user_input() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum.from_string() + +~/scipy/repos/pyproj/pyproj/_crs.pyx in pyproj._crs.Datum._from_string() + +CRSError: Invalid datum string: urn:ogc:def:datum:EPSG::6326: (Internal Proj Error: proj_create: SQLite error on SELECT name, ellipsoid_auth_name, ellipsoid_code, prime_meridian_auth_name, prime_meridian_code, area_of_use_auth_name, area_of_use_code, publication_date, deprecated FROM geodetic_datum WHERE auth_name = ? AND code = ?: no such column: publication_date)",KeyError +"def set_data_dir(proj_data_dir): + """""" + Set the data directory for PROJ to use. + + Parameters + ---------- + proj_data_dir: str + The path to rhe PROJ data directory. + """""" + global _USER_PROJ_DATA + _USER_PROJ_DATA = proj_data_dir + # reset search paths + from pyproj._datadir import PYPROJ_CONTEXT + + PYPROJ_CONTEXT.set_search_paths(reset=True)","def set_data_dir(proj_data_dir): + """""" + Set the data directory for PROJ to use. + + Parameters + ---------- + proj_data_dir: str + The path to rhe PROJ data directory. + """""" + global _USER_PROJ_DATA + _USER_PROJ_DATA = proj_data_dir + # reset search paths + from pyproj._datadir import PYPROJ_CONTEXT + + PYPROJ_CONTEXT.set_search_paths()","[{'piece_type': 'other', 'piece_content': 'Fatal Python error: Segmentation fault\\n\\nCurrent thread 0x00007fa0f79c4700 (most recent call first):\\nFile ""/opt/conda/lib/python3.7/site-packages/pyproj/crs.py"", line 303 in __init__\\nFile ""/opt/conda/lib/python3.7/site-packages/pyproj/crs.py"", line 434 in from_user_input\\nFile ""/opt/conda/lib/python3.7/site-packages/pyproj/proj.py"", line 145 in __init__\\nFile ""/opt/conda/lib/python3.7/site-packages/geopandas/geoseries.py"", line 304 in to_crs\\nFile ""/opt/conda/lib/python3.7/site-packages/geopandas/geodataframe.py"", line 459 in to_crs\\n...\\nFile """", line 1 in \\nSegmentation fault (core dumped)'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile """", line 1, in \\n...\\nFile ""/opt/conda/lib/python3.7/site-packages/geopandas/geodataframe.py"", line 459, in to_crs\\ngeom = df.geometry.to_crs(crs=crs, epsg=epsg)\\nFile ""/opt/conda/lib/python3.7/site-packages/geopandas/geoseries.py"", line 304, in to_crs\\nproj_in = pyproj.Proj(self.crs, preserve_units=True)\\nFile ""/opt/conda/lib/python3.7/site-packages/pyproj/proj.py"", line 147, in __init__\\nself.crs = CRS.from_user_input(projparams if projparams is not None else kwargs)\\nFile ""/opt/conda/lib/python3.7/site-packages/pyproj/crs.py"", line 435, in from_user_input\\nreturn cls(value)\\nFile ""/opt/conda/lib/python3.7/site-packages/pyproj/crs.py"", line 304, in __init__\\nsuper(CRS, self).__init__(projstring)\\nFile ""pyproj/_crs.pyx"", line 1308, in pyproj._crs._CRS.__init__\\nFile ""pyproj/_datadir.pyx"", line 18, in pyproj._datadir.get_pyproj_context\\nFile ""/opt/conda/lib/python3.7/site-packages/pyproj/datadir.py"", line 99, in get_data_dir\\n""Valid PROJ data directory not found. ""\\npyproj.exceptions.DataDirError: Valid PROJ data directory not found. Either set the path using the environmental variable PROJ_LIB or with `pyproj.datadir.set_data_dir`.'}, {'piece_type': 'other', 'piece_content': 'System:\\npython: 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21) [GCC 7.3.0]\\nexecutable: /usr/bin/condapy\\nmachine: Linux-4.15.0-1037-gcp-x86_64-with-debian-stretch-sid\\n\\nPROJ:\\nPROJ: 6.1.1\\ndata dir: None\\n\\nPython deps:\\npyproj: 2.2.2\\npip: 19.2.3\\nsetuptools: 41.2.0\\nCython: None\\naenum: None'}, {'piece_type': 'other', 'piece_content': 'System:\\npython: 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21) [GCC 7.3.0]\\nexecutable: /usr/bin/condapy\\nmachine: Linux-4.15.0-1037-gcp-x86_64-with-debian-stretch-sid\\n\\nPROJ:\\nPROJ: 6.1.1\\ndata dir: /opt/conda/share/proj\\n\\nPython deps:\\npyproj: 2.3.0\\npip: 19.2.3\\nsetuptools: 41.2.0\\nCython: None'}, {'piece_type': 'other', 'piece_content': 'wget --quiet https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh && \\\\\\n/bin/bash ~/miniconda.sh -b -p /opt/conda && \\\\\\nconda update conda -y && \\\\\\nconda config --add channels conda-forge && \\\\\\nconda config --set channel_priority strict && \\\\\\nconda install \\\\\\ngeopandas numexpr bottleneck'}, {'piece_type': 'other', 'piece_content': 'proj4 6.1.1 hc80f0dc_1 conda-forge\\npyproj 2.3.0 py37h2fd02e8_0 conda-forge'}, {'piece_type': 'other', 'piece_content': 'active environment : None\\nuser config file : /root/.condarc\\npopulated config files : /root/.condarc\\nconda version : 4.7.11\\nconda-build version : not installed\\npython version : 3.7.3.final.0\\nvirtual packages :\\nbase environment : /opt/conda (writable)\\nchannel URLs : https://conda.anaconda.org/conda-forge/linux-64\\nhttps://conda.anaconda.org/conda-forge/noarch\\nhttps://repo.anaconda.com/pkgs/main/linux-64\\nhttps://repo.anaconda.com/pkgs/main/noarch\\nhttps://repo.anaconda.com/pkgs/r/linux-64\\nhttps://repo.anaconda.com/pkgs/r/noarch\\npackage cache : /opt/conda/pkgs\\n/root/.conda/pkgs\\nenvs directories : /opt/conda/envs\\n/root/.conda/envs\\nplatform : linux-64\\nuser-agent : conda/4.7.11 requests/2.22.0 CPython/3.7.3 Linux/4.15.0-1037-gcp ubuntu/16.04.6 glibc/2.23\\nUID:GID : 0:0\\nnetrc file : None\\noffline mode : False'}]","Traceback (most recent call last): +File """", line 1, in +... +File ""/opt/conda/lib/python3.7/site-packages/geopandas/geodataframe.py"", line 459, in to_crs +geom = df.geometry.to_crs(crs=crs, epsg=epsg) +File ""/opt/conda/lib/python3.7/site-packages/geopandas/geoseries.py"", line 304, in to_crs +proj_in = pyproj.Proj(self.crs, preserve_units=True) +File ""/opt/conda/lib/python3.7/site-packages/pyproj/proj.py"", line 147, in __init__ +self.crs = CRS.from_user_input(projparams if projparams is not None else kwargs) +File ""/opt/conda/lib/python3.7/site-packages/pyproj/crs.py"", line 435, in from_user_input +return cls(value) +File ""/opt/conda/lib/python3.7/site-packages/pyproj/crs.py"", line 304, in __init__ +super(CRS, self).__init__(projstring) +File ""pyproj/_crs.pyx"", line 1308, in pyproj._crs._CRS.__init__ +File ""pyproj/_datadir.pyx"", line 18, in pyproj._datadir.get_pyproj_context +File ""/opt/conda/lib/python3.7/site-packages/pyproj/datadir.py"", line 99, in get_data_dir +""Valid PROJ data directory not found. "" +pyproj.exceptions.DataDirError: Valid PROJ data directory not found. Either set the path using the environmental variable PROJ_LIB or with `pyproj.datadir.set_data_dir`.",pyproj.exceptions.DataDirError +"def set_data_dir(proj_data_dir): + """""" + Set the data directory for PROJ to use. + + Parameters + ---------- + proj_data_dir: str + The path to rhe PROJ data directory. + """""" + global _USER_PROJ_DATA + _USER_PROJ_DATA = proj_data_dir + # reset search paths + from pyproj._datadir import PYPROJ_CONTEXT + + PYPROJ_CONTEXT.set_search_paths()","def set_data_dir(proj_data_dir): + """""" + Set the data directory for PROJ to use. + + Parameters + ---------- + proj_data_dir: str + The path to rhe PROJ data directory. + """""" + global _USER_PROJ_DATA + global _VALIDATED_PROJ_DATA + _USER_PROJ_DATA = proj_data_dir + # set to none to re-validate + _VALIDATED_PROJ_DATA = None","[{'piece_type': 'error message', 'piece_content': '97%|█████████████████████████████████▊ | 88243/91210 [00:26<00:00, 6190.94it/s]\\nCRSs instantiated: 507\\nCRSs instantiated (cache hits included): 88603\\nTransformers instantiated: 502\\nTransformers instantiated (cache hits included): 88389\\n---------------------------------------------------------------------------\\nProjError Traceback (most recent call last)\\n... ...\\n~/.local/share/virtualenvs/bug-Ew6sNC7W/lib/python3.7/site-packages/pyproj/transformer.py in from_proj(proj_from, proj_to, skip_equivalent, always_xy)\\n\\npyproj/_transformer.pyx in pyproj._transformer._Transformer.from_crs()\\n\\nProjError: Error creating CRS to CRS.: (Internal Proj Error: proj_create: no dat\\nabase context specified)\\n\\nIn [2]:\\nDo you really want to exit ([y]/n)?\\n\\nError in atexit._run_exitfuncs:\\nTraceback (most recent call last):\\nFile ""/home/elias/.local/share/virtualenvs/bug-Ew6sNC7W/lib/python3.7/site-packages/IPython/core/history.py"", line 578, in end_session\\nsqlite3.OperationalError: unable to open database file'}, {'piece_type': 'source code', 'piece_content': 'import pyproj, tqdm\\nUSE_CACHE = True # without USE_CACHE, this is painfully slow.\\nwkt_cache = {}; transformer_cache = {}\\n# Keep track of the number of invocations:\\ntransforms = transforms_with_cache = 0\\ncrss_created = crss_created_with_cache = 0\\n\\ndef get_crs(code):\\nglobal crss_created\\nif code in wkt_cache: return wkt_cache[code]\\ntry: crs = pyproj.CRS.from_authority(\\'esri\\', code)\\nexcept: crs = pyproj.CRS.from_epsg(code)\\nif USE_CACHE: wkt_cache[code] = crs\\ncrss_created += 1\\nreturn crs\\n\\n# lines = [next(open(\\'wkts.txt\\', \\'rt\\'))] * 200_000 # This does not trigger the bug\\nlines = open(\\'wkts.txt\\', \\'rt\\').readlines()\\nproj_wgs84 = pyproj.Proj(""+init=epsg:4326"")\\n\\ndef main(lines):\\nglobal crss_created, crss_created_with_cache, transforms_with_cache, transforms\\nfor line in tqdm.tqdm(lines):\\ntry:\\nkey = wkid = int(line.strip())\\ncrs = get_crs(wkid)\\nexcept ValueError:\\nkey = wkt = line.strip()\\nif wkt in wkt_cache:\\ncrs = wkt_cache[wkt]\\nelse:\\ncrs = wkt_cache[wkt] = pyproj.CRS.from_wkt(wkt)\\ncrss_created += 1\\n\\ncrss_created_with_cache += 1\\ntry:\\nif USE_CACHE and key in transformer_cache:\\nt = transformer_cache[key]\\nelse:\\nt = transformer_cache[key] = pyproj.Transformer.from_proj(crs, proj_wgs84)\\ntransforms += 1\\ntransforms_with_cache += 1\\nexcept Exception as ex:\\nif \\'Input is not a transformation\\' not in str(ex): raise\\n\\ntry:\\nmain(lines)\\nfinally:\\nprint(\\'CRSs instantiated:\\', crss_created)\\nprint(\\'CRSs instantiated (cache hits included):\\', crss_created_with_cache)\\nprint(\\'Transformers instantiated:\\', transforms)\\nprint(\\'Transformers instantiated (cache hits included):\\', transforms_with_cache)'}, {'piece_type': 'other', 'piece_content': 'System:\\npython: 3.7.3 (default, Apr 3 2019, 19:16:38) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]\\nexecutable: /home/elias/.local/share/virtualenvs/bug-Ew6sNC7W/bin/python\\nmachine: Linux-4.15.0-54-generic-x86_64-with-Ubuntu-18.04-bionic\\n\\nPROJ:\\nPROJ: 6.1.0\\ndata dir: /home/elias/.local/share/virtualenvs/bug-Ew6sNC7W/lib/python3.7/site-packages/pyproj/proj_dir/share/proj\\n\\nPython deps:\\npyproj: 2.2.1\\npip: 19.1.1\\nsetuptools: 41.0.1\\nCython: None\\naenum: None```\\n\\nconda:'}, {'piece_type': 'other', 'piece_content': ""#### Installation method\\n- conda, pip wheel, from source, etc...\\n\\n#### Conda environment information (if you installed with conda):\\n\\n
\\nNB: conda environment was created with: conda install -c conda-forge 'pyproj>2.2' numpy\\nEnvironment (conda list):\\n
""}, {'piece_type': 'other', 'piece_content': '
\\n\\n
\\nDetails about conda and system ( conda info ):\\n
'}, {'piece_type': 'other', 'piece_content': '
'}]","97%|█████████████████████████████████▊ | 88243/91210 [00:26<00:00, 6190.94it/s] +CRSs instantiated: 507 +CRSs instantiated (cache hits included): 88603 +Transformers instantiated: 502 +Transformers instantiated (cache hits included): 88389 +--------------------------------------------------------------------------- +ProjError Traceback (most recent call last) +... ... +~/.local/share/virtualenvs/bug-Ew6sNC7W/lib/python3.7/site-packages/pyproj/transformer.py in from_proj(proj_from, proj_to, skip_equivalent, always_xy) + +pyproj/_transformer.pyx in pyproj._transformer._Transformer.from_crs() + +ProjError: Error creating CRS to CRS.: (Internal Proj Error: proj_create: no dat +abase context specified) + +In [2]: +Do you really want to exit ([y]/n)? + +Error in atexit._run_exitfuncs: +Traceback (most recent call last): +File ""/home/elias/.local/share/virtualenvs/bug-Ew6sNC7W/lib/python3.7/site-packages/IPython/core/history.py"", line 578, in end_session +sqlite3.OperationalError: unable to open database file",ProjError +"def get_data_dir(): + """""" + The order of preference for the data directory is: + + 1. The one set by pyproj.datadir.set_data_dir (if exists & valid) + 2. The internal proj directory (if exists & valid) + 3. The directory in PROJ_LIB (if exists & valid) + 4. The directory on the PATH (if exists & valid) + + Returns + ------- + str: The valid data directory. + + """""" + global _USER_PROJ_DATA + internal_datadir = os.path.join( + os.path.dirname(os.path.abspath(__file__)), ""proj_dir"", ""share"", ""proj"" + ) + proj_lib_dirs = os.environ.get(""PROJ_LIB"", """") + + def valid_data_dir(potential_data_dir): + if potential_data_dir is not None and os.path.exists( + os.path.join(potential_data_dir, ""proj.db"") + ): + return True + return False + + def valid_data_dirs(potential_data_dirs): + if potential_data_dirs is None: + return False + for proj_data_dir in potential_data_dirs.split(os.pathsep): + if valid_data_dir(proj_data_dir): + return True + break + return None + + validated_proj_data = None + if valid_data_dirs(_USER_PROJ_DATA): + validated_proj_data = _USER_PROJ_DATA + elif valid_data_dir(internal_datadir): + validated_proj_data = internal_datadir + elif valid_data_dirs(proj_lib_dirs): + validated_proj_data = proj_lib_dirs + else: + proj_exe = find_executable(""proj"") + if proj_exe is not None: + system_proj_dir = os.path.join( + os.path.dirname(os.path.dirname(proj_exe)), ""share"", ""proj"" + ) + if valid_data_dir(system_proj_dir): + validated_proj_data = system_proj_dir + + if validated_proj_data is None: + raise DataDirError( + ""Valid PROJ data directory not found. "" + ""Either set the path using the environmental variable PROJ_LIB or "" + ""with `pyproj.datadir.set_data_dir`."" + ) + return validated_proj_data","def get_data_dir(): + """""" + The order of preference for the data directory is: + + 1. The one set by pyproj.datadir.set_data_dir (if exists & valid) + 2. The internal proj directory (if exists & valid) + 3. The directory in PROJ_LIB (if exists & valid) + 4. The directory on the PATH (if exists & valid) + + Returns + ------- + str: The valid data directory. + + """""" + # to avoid re-validating + global _VALIDATED_PROJ_DATA + if _VALIDATED_PROJ_DATA is not None: + return _VALIDATED_PROJ_DATA + + global _USER_PROJ_DATA + internal_datadir = os.path.join( + os.path.dirname(os.path.abspath(__file__)), ""proj_dir"", ""share"", ""proj"" + ) + proj_lib_dirs = os.environ.get(""PROJ_LIB"", """") + + def valid_data_dir(potential_data_dir): + if potential_data_dir is not None and os.path.exists( + os.path.join(potential_data_dir, ""proj.db"") + ): + return True + return False + + def valid_data_dirs(potential_data_dirs): + if potential_data_dirs is None: + return False + for proj_data_dir in potential_data_dirs.split(os.pathsep): + if valid_data_dir(proj_data_dir): + return True + break + return None + + if valid_data_dirs(_USER_PROJ_DATA): + _VALIDATED_PROJ_DATA = _USER_PROJ_DATA + elif valid_data_dir(internal_datadir): + _VALIDATED_PROJ_DATA = internal_datadir + elif valid_data_dirs(proj_lib_dirs): + _VALIDATED_PROJ_DATA = proj_lib_dirs + else: + proj_exe = find_executable(""proj"") + if proj_exe is not None: + system_proj_dir = os.path.join( + os.path.dirname(os.path.dirname(proj_exe)), ""share"", ""proj"" + ) + if valid_data_dir(system_proj_dir): + _VALIDATED_PROJ_DATA = system_proj_dir + + if _VALIDATED_PROJ_DATA is None: + raise DataDirError( + ""Valid PROJ data directory not found. "" + ""Either set the path using the environmental variable PROJ_LIB or "" + ""with `pyproj.datadir.set_data_dir`."" + ) + return _VALIDATED_PROJ_DATA","[{'piece_type': 'error message', 'piece_content': '97%|█████████████████████████████████▊ | 88243/91210 [00:26<00:00, 6190.94it/s]\\nCRSs instantiated: 507\\nCRSs instantiated (cache hits included): 88603\\nTransformers instantiated: 502\\nTransformers instantiated (cache hits included): 88389\\n---------------------------------------------------------------------------\\nProjError Traceback (most recent call last)\\n... ...\\n~/.local/share/virtualenvs/bug-Ew6sNC7W/lib/python3.7/site-packages/pyproj/transformer.py in from_proj(proj_from, proj_to, skip_equivalent, always_xy)\\n\\npyproj/_transformer.pyx in pyproj._transformer._Transformer.from_crs()\\n\\nProjError: Error creating CRS to CRS.: (Internal Proj Error: proj_create: no dat\\nabase context specified)\\n\\nIn [2]:\\nDo you really want to exit ([y]/n)?\\n\\nError in atexit._run_exitfuncs:\\nTraceback (most recent call last):\\nFile ""/home/elias/.local/share/virtualenvs/bug-Ew6sNC7W/lib/python3.7/site-packages/IPython/core/history.py"", line 578, in end_session\\nsqlite3.OperationalError: unable to open database file'}, {'piece_type': 'source code', 'piece_content': 'import pyproj, tqdm\\nUSE_CACHE = True # without USE_CACHE, this is painfully slow.\\nwkt_cache = {}; transformer_cache = {}\\n# Keep track of the number of invocations:\\ntransforms = transforms_with_cache = 0\\ncrss_created = crss_created_with_cache = 0\\n\\ndef get_crs(code):\\nglobal crss_created\\nif code in wkt_cache: return wkt_cache[code]\\ntry: crs = pyproj.CRS.from_authority(\\'esri\\', code)\\nexcept: crs = pyproj.CRS.from_epsg(code)\\nif USE_CACHE: wkt_cache[code] = crs\\ncrss_created += 1\\nreturn crs\\n\\n# lines = [next(open(\\'wkts.txt\\', \\'rt\\'))] * 200_000 # This does not trigger the bug\\nlines = open(\\'wkts.txt\\', \\'rt\\').readlines()\\nproj_wgs84 = pyproj.Proj(""+init=epsg:4326"")\\n\\ndef main(lines):\\nglobal crss_created, crss_created_with_cache, transforms_with_cache, transforms\\nfor line in tqdm.tqdm(lines):\\ntry:\\nkey = wkid = int(line.strip())\\ncrs = get_crs(wkid)\\nexcept ValueError:\\nkey = wkt = line.strip()\\nif wkt in wkt_cache:\\ncrs = wkt_cache[wkt]\\nelse:\\ncrs = wkt_cache[wkt] = pyproj.CRS.from_wkt(wkt)\\ncrss_created += 1\\n\\ncrss_created_with_cache += 1\\ntry:\\nif USE_CACHE and key in transformer_cache:\\nt = transformer_cache[key]\\nelse:\\nt = transformer_cache[key] = pyproj.Transformer.from_proj(crs, proj_wgs84)\\ntransforms += 1\\ntransforms_with_cache += 1\\nexcept Exception as ex:\\nif \\'Input is not a transformation\\' not in str(ex): raise\\n\\ntry:\\nmain(lines)\\nfinally:\\nprint(\\'CRSs instantiated:\\', crss_created)\\nprint(\\'CRSs instantiated (cache hits included):\\', crss_created_with_cache)\\nprint(\\'Transformers instantiated:\\', transforms)\\nprint(\\'Transformers instantiated (cache hits included):\\', transforms_with_cache)'}, {'piece_type': 'other', 'piece_content': 'System:\\npython: 3.7.3 (default, Apr 3 2019, 19:16:38) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]\\nexecutable: /home/elias/.local/share/virtualenvs/bug-Ew6sNC7W/bin/python\\nmachine: Linux-4.15.0-54-generic-x86_64-with-Ubuntu-18.04-bionic\\n\\nPROJ:\\nPROJ: 6.1.0\\ndata dir: /home/elias/.local/share/virtualenvs/bug-Ew6sNC7W/lib/python3.7/site-packages/pyproj/proj_dir/share/proj\\n\\nPython deps:\\npyproj: 2.2.1\\npip: 19.1.1\\nsetuptools: 41.0.1\\nCython: None\\naenum: None```\\n\\nconda:'}, {'piece_type': 'other', 'piece_content': ""#### Installation method\\n- conda, pip wheel, from source, etc...\\n\\n#### Conda environment information (if you installed with conda):\\n\\n
\\nNB: conda environment was created with: conda install -c conda-forge 'pyproj>2.2' numpy\\nEnvironment (conda list):\\n
""}, {'piece_type': 'other', 'piece_content': '
\\n\\n
\\nDetails about conda and system ( conda info ):\\n
'}, {'piece_type': 'other', 'piece_content': '
'}]","97%|█████████████████████████████████▊ | 88243/91210 [00:26<00:00, 6190.94it/s] +CRSs instantiated: 507 +CRSs instantiated (cache hits included): 88603 +Transformers instantiated: 502 +Transformers instantiated (cache hits included): 88389 +--------------------------------------------------------------------------- +ProjError Traceback (most recent call last) +... ... +~/.local/share/virtualenvs/bug-Ew6sNC7W/lib/python3.7/site-packages/pyproj/transformer.py in from_proj(proj_from, proj_to, skip_equivalent, always_xy) + +pyproj/_transformer.pyx in pyproj._transformer._Transformer.from_crs() + +ProjError: Error creating CRS to CRS.: (Internal Proj Error: proj_create: no dat +abase context specified) + +In [2]: +Do you really want to exit ([y]/n)? + +Error in atexit._run_exitfuncs: +Traceback (most recent call last): +File ""/home/elias/.local/share/virtualenvs/bug-Ew6sNC7W/lib/python3.7/site-packages/IPython/core/history.py"", line 578, in end_session +sqlite3.OperationalError: unable to open database file",ProjError +" def from_proj(proj_from, proj_to, skip_equivalent=False, always_xy=False): + """"""Make a Transformer from a :obj:`~pyproj.proj.Proj` or input used to create one. + + Parameters + ---------- + proj_from: :obj:`~pyproj.proj.Proj` or input used to create one + Projection of input data. + proj_to: :obj:`~pyproj.proj.Proj` or input used to create one + Projection of output data. + skip_equivalent: bool, optional + If true, will skip the transformation operation if input and output + projections are equivalent. Default is false. + always_xy: bool, optional + If true, the transform method will accept as input and return as output + coordinates using the traditional GIS order, that is longitude, latitude + for geographic CRS and easting, northing for most projected CRS. + Default is false. + + Returns + ------- + :obj:`~Transformer` + + """""" + if not isinstance(proj_from, Proj): + proj_from = Proj(proj_from) + if not isinstance(proj_to, Proj): + proj_to = Proj(proj_to) + + return Transformer( + _Transformer.from_crs( + proj_from.crs, + proj_to.crs, + skip_equivalent=skip_equivalent, + always_xy=always_xy, + ) + )"," def from_proj(proj_from, proj_to, skip_equivalent=False, always_xy=False): + """"""Make a Transformer from a :obj:`~pyproj.proj.Proj` or input used to create one. + + Parameters + ---------- + proj_from: :obj:`~pyproj.proj.Proj` or input used to create one + Projection of input data. + proj_to: :obj:`~pyproj.proj.Proj` or input used to create one + Projection of output data. + skip_equivalent: bool, optional + If true, will skip the transformation operation if input and output + projections are equivalent. Default is false. + always_xy: bool, optional + If true, the transform method will accept as input and return as output + coordinates using the traditional GIS order, that is longitude, latitude + for geographic CRS and easting, northing for most projected CRS. + Default is false. + + Returns + ------- + :obj:`~Transformer` + + """""" + if not isinstance(proj_from, Proj): + proj_from = Proj(proj_from) + if not isinstance(proj_to, Proj): + proj_to = Proj(proj_to) + + transformer = Transformer() + transformer._transformer = _Transformer.from_crs( + proj_from.crs, + proj_to.crs, + skip_equivalent=skip_equivalent, + always_xy=always_xy, + ) + return transformer","[{'piece_type': 'error message', 'piece_content': ""In [4]: t = pyproj.Transformer()\\n\\nIn [5]: t\\nOut[5]: \\n\\nIn [6]: t.transform(0, 0)\\n---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in \\n----> 1 t.transform(0, 0)\\n\\n~/scipy/repos/pyproj/pyproj/transformer.py in transform(self, xx, yy, zz, tt, radians, errcheck, direction)\\n207 intime = None\\n208 # call pj_transform. inx,iny,inz buffers modified in place.\\n--> 209 self._transformer._transform(\\n210 inx,\\n211 iny,\\n\\nAttributeError: 'Transformer' object has no attribute '_transformer'""}]","In [4]: t = pyproj.Transformer() + +In [5]: t +Out[5]: + +In [6]: t.transform(0, 0) +--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in +----> 1 t.transform(0, 0) + +~/scipy/repos/pyproj/pyproj/transformer.py in transform(self, xx, yy, zz, tt, radians, errcheck, direction) +207 intime = None +208 # call pj_transform. inx,iny,inz buffers modified in place. +--> 209 self._transformer._transform( +210 inx, +211 iny, + +AttributeError: 'Transformer' object has no attribute '_transformer'",AttributeError +" def from_crs(crs_from, crs_to, skip_equivalent=False, always_xy=False): + """"""Make a Transformer from a :obj:`~pyproj.crs.CRS` or input used to create one. + + Parameters + ---------- + crs_from: ~pyproj.crs.CRS or input used to create one + Projection of input data. + crs_to: ~pyproj.crs.CRS or input used to create one + Projection of output data. + skip_equivalent: bool, optional + If true, will skip the transformation operation if input and output + projections are equivalent. Default is false. + always_xy: bool, optional + If true, the transform method will accept as input and return as output + coordinates using the traditional GIS order, that is longitude, latitude + for geographic CRS and easting, northing for most projected CRS. + Default is false. + + Returns + ------- + :obj:`~Transformer` + + """""" + transformer = Transformer( + _Transformer.from_crs( + CRS.from_user_input(crs_from), + CRS.from_user_input(crs_to), + skip_equivalent=skip_equivalent, + always_xy=always_xy, + ) + ) + return transformer"," def from_crs(crs_from, crs_to, skip_equivalent=False, always_xy=False): + """"""Make a Transformer from a :obj:`~pyproj.crs.CRS` or input used to create one. + + Parameters + ---------- + crs_from: ~pyproj.crs.CRS or input used to create one + Projection of input data. + crs_to: ~pyproj.crs.CRS or input used to create one + Projection of output data. + skip_equivalent: bool, optional + If true, will skip the transformation operation if input and output + projections are equivalent. Default is false. + always_xy: bool, optional + If true, the transform method will accept as input and return as output + coordinates using the traditional GIS order, that is longitude, latitude + for geographic CRS and easting, northing for most projected CRS. + Default is false. + + Returns + ------- + :obj:`~Transformer` + + """""" + transformer = Transformer() + transformer._transformer = _Transformer.from_crs( + CRS.from_user_input(crs_from), + CRS.from_user_input(crs_to), + skip_equivalent=skip_equivalent, + always_xy=always_xy, + ) + return transformer","[{'piece_type': 'error message', 'piece_content': ""In [4]: t = pyproj.Transformer()\\n\\nIn [5]: t\\nOut[5]: \\n\\nIn [6]: t.transform(0, 0)\\n---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in \\n----> 1 t.transform(0, 0)\\n\\n~/scipy/repos/pyproj/pyproj/transformer.py in transform(self, xx, yy, zz, tt, radians, errcheck, direction)\\n207 intime = None\\n208 # call pj_transform. inx,iny,inz buffers modified in place.\\n--> 209 self._transformer._transform(\\n210 inx,\\n211 iny,\\n\\nAttributeError: 'Transformer' object has no attribute '_transformer'""}]","In [4]: t = pyproj.Transformer() + +In [5]: t +Out[5]: + +In [6]: t.transform(0, 0) +--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in +----> 1 t.transform(0, 0) + +~/scipy/repos/pyproj/pyproj/transformer.py in transform(self, xx, yy, zz, tt, radians, errcheck, direction) +207 intime = None +208 # call pj_transform. inx,iny,inz buffers modified in place. +--> 209 self._transformer._transform( +210 inx, +211 iny, + +AttributeError: 'Transformer' object has no attribute '_transformer'",AttributeError +" def from_pipeline(proj_pipeline): + """"""Make a Transformer from a PROJ pipeline string. + + https://proj4.org/operations/pipeline.html + + Parameters + ---------- + proj_pipeline: str + Projection pipeline string. + + Returns + ------- + ~Transformer + + """""" + return Transformer(_Transformer.from_pipeline(cstrencode(proj_pipeline)))"," def from_pipeline(proj_pipeline): + """"""Make a Transformer from a PROJ pipeline string. + + https://proj4.org/operations/pipeline.html + + Parameters + ---------- + proj_pipeline: str + Projection pipeline string. + + Returns + ------- + ~Transformer + + """""" + transformer = Transformer() + transformer._transformer = _Transformer.from_pipeline(cstrencode(proj_pipeline)) + return transformer","[{'piece_type': 'error message', 'piece_content': ""In [4]: t = pyproj.Transformer()\\n\\nIn [5]: t\\nOut[5]: \\n\\nIn [6]: t.transform(0, 0)\\n---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in \\n----> 1 t.transform(0, 0)\\n\\n~/scipy/repos/pyproj/pyproj/transformer.py in transform(self, xx, yy, zz, tt, radians, errcheck, direction)\\n207 intime = None\\n208 # call pj_transform. inx,iny,inz buffers modified in place.\\n--> 209 self._transformer._transform(\\n210 inx,\\n211 iny,\\n\\nAttributeError: 'Transformer' object has no attribute '_transformer'""}]","In [4]: t = pyproj.Transformer() + +In [5]: t +Out[5]: + +In [6]: t.transform(0, 0) +--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in +----> 1 t.transform(0, 0) + +~/scipy/repos/pyproj/pyproj/transformer.py in transform(self, xx, yy, zz, tt, radians, errcheck, direction) +207 intime = None +208 # call pj_transform. inx,iny,inz buffers modified in place. +--> 209 self._transformer._transform( +210 inx, +211 iny, + +AttributeError: 'Transformer' object has no attribute '_transformer'",AttributeError +"def _dict2string(projparams): + # convert a dict to a proj4 string. + pjargs = [] + proj_inserted = False + for key, value in projparams.items(): + # the towgs84 as list + if isinstance(value, (list, tuple)): + value = "","".join([str(val) for val in value]) + # issue 183 (+ no_rot) + if value is None or value is True: + pjargs.append(""+{key}"".format(key=key)) + elif value is False: + pass + # make sure string starts with proj or init + elif not proj_inserted and key in (""init"", ""proj""): + pjargs.insert(0, ""+{key}={value}"".format(key=key, value=value)) + proj_inserted = True + else: + pjargs.append(""+{key}={value}"".format(key=key, value=value)) + return "" "".join(pjargs)","def _dict2string(projparams): + # convert a dict to a proj4 string. + pjargs = [] + for key, value in projparams.items(): + # the towgs84 as list + if isinstance(value, (list, tuple)): + value = "","".join([str(val) for val in value]) + # issue 183 (+ no_rot) + if value is None or value is True: + pjargs.append(""+"" + key + "" "") + elif value is False: + pass + else: + pjargs.append(""+"" + key + ""="" + str(value) + "" "") + return """".join(pjargs)","[{'piece_type': 'error message', 'piece_content': 'from pyproj import Proj\\nProj({\\'a\\': 6371229.0, \\'b\\': 6371229.0, \\'lon_0\\': -10.0, \\'o_lat_p\\': 30.0, \\'o_lon_p\\': 0.0, \\'o_proj\\': \\'longlat\\', \\'proj\\'\\n: \\'ob_tran\\'})\\nTraceback (most recent call last):\\nFile """", line 1, in \\nFile "".../lib/python3.7/site-packages/pyproj/proj.py"", line 303, in __init__\\ncstrencode(self.crs.to_proj4().replace(""+type=crs"", """").strip())\\nAttributeError: \\'NoneType\\' object has no attribute \\'replace\\''}]","from pyproj import Proj +Proj({'a': 6371229.0, 'b': 6371229.0, 'lon_0': -10.0, 'o_lat_p': 30.0, 'o_lon_p': 0.0, 'o_proj': 'longlat', 'proj' +: 'ob_tran'}) +Traceback (most recent call last): +File """", line 1, in +File "".../lib/python3.7/site-packages/pyproj/proj.py"", line 303, in __init__ +cstrencode(self.crs.to_proj4().replace(""+type=crs"", """").strip()) +AttributeError: 'NoneType' object has no attribute 'replace'",AttributeError +" def __init__(self, projparams=None, preserve_units=True, **kwargs): + """""" + initialize a Proj class instance. + + See the proj documentation (https://github.com/OSGeo/proj.4/wiki) + for more information about projection parameters. + + Parameters + ---------- + projparams: int, str, dict, pyproj.CRS + A proj.4 or WKT string, proj.4 dict, EPSG integer, or a pyproj.CRS instnace. + preserve_units: bool + If false, will ensure +units=m. + **kwargs: + proj.4 projection parameters. + + + Example usage: + + >>> from pyproj import Proj + >>> p = Proj(proj='utm',zone=10,ellps='WGS84', preserve_units=False) # use kwargs + >>> x,y = p(-120.108, 34.36116666) + >>> 'x=%9.3f y=%11.3f' % (x,y) + 'x=765975.641 y=3805993.134' + >>> 'lon=%8.3f lat=%5.3f' % p(x,y,inverse=True) + 'lon=-120.108 lat=34.361' + >>> # do 3 cities at a time in a tuple (Fresno, LA, SF) + >>> lons = (-119.72,-118.40,-122.38) + >>> lats = (36.77, 33.93, 37.62 ) + >>> x,y = p(lons, lats) + >>> 'x: %9.3f %9.3f %9.3f' % x + 'x: 792763.863 925321.537 554714.301' + >>> 'y: %9.3f %9.3f %9.3f' % y + 'y: 4074377.617 3763936.941 4163835.303' + >>> lons, lats = p(x, y, inverse=True) # inverse transform + >>> 'lons: %8.3f %8.3f %8.3f' % lons + 'lons: -119.720 -118.400 -122.380' + >>> 'lats: %8.3f %8.3f %8.3f' % lats + 'lats: 36.770 33.930 37.620' + >>> p2 = Proj('+proj=utm +zone=10 +ellps=WGS84', preserve_units=False) # use proj4 string + >>> x,y = p2(-120.108, 34.36116666) + >>> 'x=%9.3f y=%11.3f' % (x,y) + 'x=765975.641 y=3805993.134' + >>> p = Proj(init=""epsg:32667"", preserve_units=False) + >>> 'x=%12.3f y=%12.3f (meters)' % p(-114.057222, 51.045) + 'x=-1783506.250 y= 6193827.033 (meters)' + >>> p = Proj(""+init=epsg:32667"") + >>> 'x=%12.3f y=%12.3f (feet)' % p(-114.057222, 51.045) + 'x=-5851386.754 y=20320914.191 (feet)' + >>> # test data with radian inputs + >>> p1 = Proj(init=""epsg:4214"") + >>> x1, y1 = p1(116.366, 39.867) + >>> '{:.3f} {:.3f}'.format(x1, y1) + '2.031 0.696' + >>> x2, y2 = p1(x1, y1, inverse=True) + >>> '{:.3f} {:.3f}'.format(x2, y2) + '116.366 39.867' + """""" + self.crs = CRS.from_user_input(projparams if projparams is not None else kwargs) + # make sure units are meters if preserve_units is False. + if not preserve_units and ""foot"" in self.crs.axis_info[0].unit_name: + projstring = self.crs.to_proj4(4) + projstring = re.sub(r""\\s\\+units=[\\w-]+"", """", projstring) + projstring += "" +units=m"" + self.crs = CRS(projstring) + super(Proj, self).__init__( + cstrencode( + (self.crs.to_proj4() or self.crs.srs).replace(""+type=crs"", """").strip() + ) + )"," def __init__(self, projparams=None, preserve_units=True, **kwargs): + """""" + initialize a Proj class instance. + + See the proj documentation (https://github.com/OSGeo/proj.4/wiki) + for more information about projection parameters. + + Parameters + ---------- + projparams: int, str, dict, pyproj.CRS + A proj.4 or WKT string, proj.4 dict, EPSG integer, or a pyproj.CRS instnace. + preserve_units: bool + If false, will ensure +units=m. + **kwargs: + proj.4 projection parameters. + + + Example usage: + + >>> from pyproj import Proj + >>> p = Proj(proj='utm',zone=10,ellps='WGS84', preserve_units=False) # use kwargs + >>> x,y = p(-120.108, 34.36116666) + >>> 'x=%9.3f y=%11.3f' % (x,y) + 'x=765975.641 y=3805993.134' + >>> 'lon=%8.3f lat=%5.3f' % p(x,y,inverse=True) + 'lon=-120.108 lat=34.361' + >>> # do 3 cities at a time in a tuple (Fresno, LA, SF) + >>> lons = (-119.72,-118.40,-122.38) + >>> lats = (36.77, 33.93, 37.62 ) + >>> x,y = p(lons, lats) + >>> 'x: %9.3f %9.3f %9.3f' % x + 'x: 792763.863 925321.537 554714.301' + >>> 'y: %9.3f %9.3f %9.3f' % y + 'y: 4074377.617 3763936.941 4163835.303' + >>> lons, lats = p(x, y, inverse=True) # inverse transform + >>> 'lons: %8.3f %8.3f %8.3f' % lons + 'lons: -119.720 -118.400 -122.380' + >>> 'lats: %8.3f %8.3f %8.3f' % lats + 'lats: 36.770 33.930 37.620' + >>> p2 = Proj('+proj=utm +zone=10 +ellps=WGS84', preserve_units=False) # use proj4 string + >>> x,y = p2(-120.108, 34.36116666) + >>> 'x=%9.3f y=%11.3f' % (x,y) + 'x=765975.641 y=3805993.134' + >>> p = Proj(init=""epsg:32667"", preserve_units=False) + >>> 'x=%12.3f y=%12.3f (meters)' % p(-114.057222, 51.045) + 'x=-1783506.250 y= 6193827.033 (meters)' + >>> p = Proj(""+init=epsg:32667"") + >>> 'x=%12.3f y=%12.3f (feet)' % p(-114.057222, 51.045) + 'x=-5851386.754 y=20320914.191 (feet)' + >>> # test data with radian inputs + >>> p1 = Proj(init=""epsg:4214"") + >>> x1, y1 = p1(116.366, 39.867) + >>> '{:.3f} {:.3f}'.format(x1, y1) + '2.031 0.696' + >>> x2, y2 = p1(x1, y1, inverse=True) + >>> '{:.3f} {:.3f}'.format(x2, y2) + '116.366 39.867' + """""" + self.crs = CRS.from_user_input(projparams if projparams is not None else kwargs) + # make sure units are meters if preserve_units is False. + if not preserve_units and ""foot"" in self.crs.axis_info[0].unit_name: + projstring = self.crs.to_proj4(4) + projstring = re.sub(r""\\s\\+units=[\\w-]+"", """", projstring) + projstring += "" +units=m"" + self.crs = CRS(projstring) + super(Proj, self).__init__( + cstrencode(self.crs.to_proj4().replace(""+type=crs"", """").strip()) + )","[{'piece_type': 'error message', 'piece_content': 'from pyproj import Proj\\nProj({\\'a\\': 6371229.0, \\'b\\': 6371229.0, \\'lon_0\\': -10.0, \\'o_lat_p\\': 30.0, \\'o_lon_p\\': 0.0, \\'o_proj\\': \\'longlat\\', \\'proj\\'\\n: \\'ob_tran\\'})\\nTraceback (most recent call last):\\nFile """", line 1, in \\nFile "".../lib/python3.7/site-packages/pyproj/proj.py"", line 303, in __init__\\ncstrencode(self.crs.to_proj4().replace(""+type=crs"", """").strip())\\nAttributeError: \\'NoneType\\' object has no attribute \\'replace\\''}]","from pyproj import Proj +Proj({'a': 6371229.0, 'b': 6371229.0, 'lon_0': -10.0, 'o_lat_p': 30.0, 'o_lon_p': 0.0, 'o_proj': 'longlat', 'proj' +: 'ob_tran'}) +Traceback (most recent call last): +File """", line 1, in +File "".../lib/python3.7/site-packages/pyproj/proj.py"", line 303, in __init__ +cstrencode(self.crs.to_proj4().replace(""+type=crs"", """").strip()) +AttributeError: 'NoneType' object has no attribute 'replace'",AttributeError +"def Kuf_conv_patch(inducing_variable, kernel, Xnew): + Xp = kernel.get_patches(Xnew) # [N, num_patches, patch_len] + bigKzx = kernel.base_kernel.K( + inducing_variable.Z, Xp + ) # [M, N, P] -- thanks to broadcasting of kernels + Kzx = tf.reduce_sum(bigKzx * kernel.weights if hasattr(kernel, ""weights"") else bigKzx, [2]) + return Kzx / kernel.num_patches","def Kuf_conv_patch(feat, kern, Xnew): + Xp = kern.get_patches(Xnew) # [N, num_patches, patch_len] + bigKzx = kern.base_kernel.K(feat.Z, Xp) # [M, N, P] -- thanks to broadcasting of kernels + Kzx = tf.reduce_sum(bigKzx * kern.weights if hasattr(kern, ""weights"") else bigKzx, [2]) + return Kzx / kern.num_patches","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +"def Kuu_kernel_inducingpoints(inducing_variable: InducingPoints, kernel: Kernel, *, jitter=0.0): + Kzz = kernel(inducing_variable.Z) + Kzz += jitter * tf.eye(inducing_variable.num_inducing, dtype=Kzz.dtype) + return Kzz","def Kuu_kernel_inducingpoints(inducing_variable: InducingPoints, kernel: Kernel, *, jitter=0.0): + Kzz = kernel(inducing_variable.Z) + Kzz += jitter * tf.eye(len(inducing_variable), dtype=Kzz.dtype) + return Kzz","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +"def Kuu_sqexp_multiscale(inducing_variable: Multiscale, kernel: SquaredExponential, *, jitter=0.0): + Zmu, Zlen = kernel.slice(inducing_variable.Z, inducing_variable.scales) + idlengthscales2 = tf.square(kernel.lengthscales + Zlen) + sc = tf.sqrt( + idlengthscales2[None, ...] + idlengthscales2[:, None, ...] - kernel.lengthscales ** 2 + ) + d = inducing_variable._cust_square_dist(Zmu, Zmu, sc) + Kzz = kernel.variance * tf.exp(-d / 2) * tf.reduce_prod(kernel.lengthscales / sc, 2) + Kzz += jitter * tf.eye(inducing_variable.num_inducing, dtype=Kzz.dtype) + return Kzz","def Kuu_sqexp_multiscale(inducing_variable: Multiscale, kernel: SquaredExponential, *, jitter=0.0): + Zmu, Zlen = kernel.slice(inducing_variable.Z, inducing_variable.scales) + idlengthscales2 = tf.square(kernel.lengthscales + Zlen) + sc = tf.sqrt( + idlengthscales2[None, ...] + idlengthscales2[:, None, ...] - kernel.lengthscales ** 2 + ) + d = inducing_variable._cust_square_dist(Zmu, Zmu, sc) + Kzz = kernel.variance * tf.exp(-d / 2) * tf.reduce_prod(kernel.lengthscales / sc, 2) + Kzz += jitter * tf.eye(len(inducing_variable), dtype=Kzz.dtype) + return Kzz","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +"def Kuu_conv_patch(inducing_variable, kernel, jitter=0.0): + return kernel.base_kernel.K(inducing_variable.Z) + jitter * tf.eye( + inducing_variable.num_inducing, dtype=default_float() + )","def Kuu_conv_patch(feat, kern, jitter=0.0): + return kern.base_kernel.K(feat.Z) + jitter * tf.eye(len(feat), dtype=default_float())","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +"def _Kuu( + inducing_variable: FallbackSeparateIndependentInducingVariables, + kernel: Union[SeparateIndependent, LinearCoregionalization], + *, + jitter=0.0, +): + Kmms = [Kuu(f, k) for f, k in zip(inducing_variable.inducing_variable_list, kernel.kernels)] + Kmm = tf.stack(Kmms, axis=0) # [L, M, M] + jittermat = tf.eye(inducing_variable.num_inducing, dtype=Kmm.dtype)[None, :, :] * jitter + return Kmm + jittermat","def _Kuu( + inducing_variable: FallbackSeparateIndependentInducingVariables, + kernel: Union[SeparateIndependent, LinearCoregionalization], + *, + jitter=0.0, +): + Kmms = [Kuu(f, k) for f, k in zip(inducing_variable.inducing_variable_list, kernel.kernels)] + Kmm = tf.stack(Kmms, axis=0) # [L, M, M] + jittermat = tf.eye(len(inducing_variable), dtype=Kmm.dtype)[None, :, :] * jitter + return Kmm + jittermat","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def __init__(self, Z: TensorData, name: Optional[str] = None): + """""" + :param Z: the initial positions of the inducing points, size [M, D] + """""" + super().__init__(name=name) + if not isinstance(Z, (tf.Variable, tfp.util.TransformedVariable)): + Z = Parameter(Z) + self.Z = Z"," def __init__(self, Z: TensorData, name: Optional[str] = None): + """""" + :param Z: the initial positions of the inducing points, size [M, D] + """""" + super().__init__(name=name) + self.Z = Parameter(Z, dtype=default_float())","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def __len__(self) -> int: + return tf.shape(self.Z)[0]"," def __len__(self) -> int: + return self.Z.shape[0]","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def __len__(self) -> int: + return self.inducing_variable.num_inducing"," def __len__(self) -> int: + return len(self.inducing_variable)","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def __len__(self) -> int: + # TODO(st--) we should check that they all have the same length... + return self.inducing_variable_list[0].num_inducing"," def __len__(self) -> int: + return len(self.inducing_variable_list[0])","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def __init__( + self, + distribution_class: Type[tfp.distributions.Distribution] = tfp.distributions.Normal, + scale_transform: Optional[tfp.bijectors.Bijector] = None, + **kwargs, + ): + """""" + :param distribution_class: distribution class parameterized by `loc` and `scale` + as first and second argument, respectively. + :param scale_transform: callable/bijector applied to the latent + function modelling the scale to ensure its positivity. + Typically, `tf.exp` or `tf.softplus`, but can be any function f: R -> R^+. Defaults to exp if not explicitly specified. + """""" + if scale_transform is None: + scale_transform = positive(base=""exp"") + self.scale_transform = scale_transform + + def conditional_distribution(Fs) -> tfp.distributions.Distribution: + tf.debugging.assert_equal(tf.shape(Fs)[-1], 2) + loc = Fs[..., :1] + scale = self.scale_transform(Fs[..., 1:]) + return distribution_class(loc, scale) + + super().__init__( + latent_dim=2, conditional_distribution=conditional_distribution, **kwargs, + )"," def __init__( + self, + distribution_class: Type[tfp.distributions.Distribution] = tfp.distributions.Normal, + scale_transform: tfp.bijectors.Bijector = positive(base=""exp""), + **kwargs, + ): + """""" + :param distribution_class: distribution class parameterized by `loc` and `scale` + as first and second argument, respectively. + :param scale_transform: callable/bijector applied to the latent + function modelling the scale to ensure its positivity. + Typically, `tf.exp` or `tf.softplus`, but can be any function f: R -> R^+. + """""" + + def conditional_distribution(Fs) -> tfp.distributions.Distribution: + tf.debugging.assert_equal(tf.shape(Fs)[-1], 2) + loc = Fs[..., :1] + scale = scale_transform(Fs[..., 1:]) + return distribution_class(loc, scale) + + super().__init__( + latent_dim=2, conditional_distribution=conditional_distribution, **kwargs, + )","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def conditional_distribution(Fs) -> tfp.distributions.Distribution: + tf.debugging.assert_equal(tf.shape(Fs)[-1], 2) + loc = Fs[..., :1] + scale = self.scale_transform(Fs[..., 1:]) + return distribution_class(loc, scale)"," def conditional_distribution(Fs) -> tfp.distributions.Distribution: + tf.debugging.assert_equal(tf.shape(Fs)[-1], 2) + loc = Fs[..., :1] + scale = scale_transform(Fs[..., 1:]) + return distribution_class(loc, scale)","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def elbo(self) -> tf.Tensor: + """""" + Construct a tensorflow function to compute the bound on the marginal + likelihood. + """""" + Y_data = self.data + + pX = DiagonalGaussian(self.X_data_mean, self.X_data_var) + + num_inducing = self.inducing_variable.num_inducing + psi0 = tf.reduce_sum(expectation(pX, self.kernel)) + psi1 = expectation(pX, (self.kernel, self.inducing_variable)) + psi2 = tf.reduce_sum( + expectation( + pX, (self.kernel, self.inducing_variable), (self.kernel, self.inducing_variable) + ), + axis=0, + ) + cov_uu = covariances.Kuu(self.inducing_variable, self.kernel, jitter=default_jitter()) + L = tf.linalg.cholesky(cov_uu) + sigma2 = self.likelihood.variance + sigma = tf.sqrt(sigma2) + + # Compute intermediate matrices + A = tf.linalg.triangular_solve(L, tf.transpose(psi1), lower=True) / sigma + tmp = tf.linalg.triangular_solve(L, psi2, lower=True) + AAT = tf.linalg.triangular_solve(L, tf.transpose(tmp), lower=True) / sigma2 + B = AAT + tf.eye(num_inducing, dtype=default_float()) + LB = tf.linalg.cholesky(B) + log_det_B = 2.0 * tf.reduce_sum(tf.math.log(tf.linalg.diag_part(LB))) + c = tf.linalg.triangular_solve(LB, tf.linalg.matmul(A, Y_data), lower=True) / sigma + + # KL[q(x) || p(x)] + dX_data_var = ( + self.X_data_var + if self.X_data_var.shape.ndims == 2 + else tf.linalg.diag_part(self.X_data_var) + ) + NQ = to_default_float(tf.size(self.X_data_mean)) + D = to_default_float(tf.shape(Y_data)[1]) + KL = -0.5 * tf.reduce_sum(tf.math.log(dX_data_var)) + KL += 0.5 * tf.reduce_sum(tf.math.log(self.X_prior_var)) + KL -= 0.5 * NQ + KL += 0.5 * tf.reduce_sum( + (tf.square(self.X_data_mean - self.X_prior_mean) + dX_data_var) / self.X_prior_var + ) + + # compute log marginal bound + ND = to_default_float(tf.size(Y_data)) + bound = -0.5 * ND * tf.math.log(2 * np.pi * sigma2) + bound += -0.5 * D * log_det_B + bound += -0.5 * tf.reduce_sum(tf.square(Y_data)) / sigma2 + bound += 0.5 * tf.reduce_sum(tf.square(c)) + bound += -0.5 * D * (tf.reduce_sum(psi0) / sigma2 - tf.reduce_sum(tf.linalg.diag_part(AAT))) + bound -= KL + return bound"," def elbo(self) -> tf.Tensor: + """""" + Construct a tensorflow function to compute the bound on the marginal + likelihood. + """""" + Y_data = self.data + + pX = DiagonalGaussian(self.X_data_mean, self.X_data_var) + + num_inducing = len(self.inducing_variable) + psi0 = tf.reduce_sum(expectation(pX, self.kernel)) + psi1 = expectation(pX, (self.kernel, self.inducing_variable)) + psi2 = tf.reduce_sum( + expectation( + pX, (self.kernel, self.inducing_variable), (self.kernel, self.inducing_variable) + ), + axis=0, + ) + cov_uu = covariances.Kuu(self.inducing_variable, self.kernel, jitter=default_jitter()) + L = tf.linalg.cholesky(cov_uu) + sigma2 = self.likelihood.variance + sigma = tf.sqrt(sigma2) + + # Compute intermediate matrices + A = tf.linalg.triangular_solve(L, tf.transpose(psi1), lower=True) / sigma + tmp = tf.linalg.triangular_solve(L, psi2, lower=True) + AAT = tf.linalg.triangular_solve(L, tf.transpose(tmp), lower=True) / sigma2 + B = AAT + tf.eye(num_inducing, dtype=default_float()) + LB = tf.linalg.cholesky(B) + log_det_B = 2.0 * tf.reduce_sum(tf.math.log(tf.linalg.diag_part(LB))) + c = tf.linalg.triangular_solve(LB, tf.linalg.matmul(A, Y_data), lower=True) / sigma + + # KL[q(x) || p(x)] + dX_data_var = ( + self.X_data_var + if self.X_data_var.shape.ndims == 2 + else tf.linalg.diag_part(self.X_data_var) + ) + NQ = to_default_float(tf.size(self.X_data_mean)) + D = to_default_float(tf.shape(Y_data)[1]) + KL = -0.5 * tf.reduce_sum(tf.math.log(dX_data_var)) + KL += 0.5 * tf.reduce_sum(tf.math.log(self.X_prior_var)) + KL -= 0.5 * NQ + KL += 0.5 * tf.reduce_sum( + (tf.square(self.X_data_mean - self.X_prior_mean) + dX_data_var) / self.X_prior_var + ) + + # compute log marginal bound + ND = to_default_float(tf.size(Y_data)) + bound = -0.5 * ND * tf.math.log(2 * np.pi * sigma2) + bound += -0.5 * D * log_det_B + bound += -0.5 * tf.reduce_sum(tf.square(Y_data)) / sigma2 + bound += 0.5 * tf.reduce_sum(tf.square(c)) + bound += -0.5 * D * (tf.reduce_sum(psi0) / sigma2 - tf.reduce_sum(tf.linalg.diag_part(AAT))) + bound -= KL + return bound","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def predict_f( + self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False + ) -> MeanAndVariance: + """""" + Compute the mean and variance of the latent function at some new points. + Note that this is very similar to the SGPR prediction, for which + there are notes in the SGPR notebook. + + Note: This model does not allow full output covariances. + + :param Xnew: points at which to predict + """""" + if full_output_cov: + raise NotImplementedError + + pX = DiagonalGaussian(self.X_data_mean, self.X_data_var) + + Y_data = self.data + num_inducing = self.inducing_variable.num_inducing + psi1 = expectation(pX, (self.kernel, self.inducing_variable)) + psi2 = tf.reduce_sum( + expectation( + pX, (self.kernel, self.inducing_variable), (self.kernel, self.inducing_variable) + ), + axis=0, + ) + jitter = default_jitter() + Kus = covariances.Kuf(self.inducing_variable, self.kernel, Xnew) + sigma2 = self.likelihood.variance + sigma = tf.sqrt(sigma2) + L = tf.linalg.cholesky(covariances.Kuu(self.inducing_variable, self.kernel, jitter=jitter)) + + A = tf.linalg.triangular_solve(L, tf.transpose(psi1), lower=True) / sigma + tmp = tf.linalg.triangular_solve(L, psi2, lower=True) + AAT = tf.linalg.triangular_solve(L, tf.transpose(tmp), lower=True) / sigma2 + B = AAT + tf.eye(num_inducing, dtype=default_float()) + LB = tf.linalg.cholesky(B) + c = tf.linalg.triangular_solve(LB, tf.linalg.matmul(A, Y_data), lower=True) / sigma + tmp1 = tf.linalg.triangular_solve(L, Kus, lower=True) + tmp2 = tf.linalg.triangular_solve(LB, tmp1, lower=True) + mean = tf.linalg.matmul(tmp2, c, transpose_a=True) + if full_cov: + var = ( + self.kernel(Xnew) + + tf.linalg.matmul(tmp2, tmp2, transpose_a=True) + - tf.linalg.matmul(tmp1, tmp1, transpose_a=True) + ) + shape = tf.stack([1, 1, tf.shape(Y_data)[1]]) + var = tf.tile(tf.expand_dims(var, 2), shape) + else: + var = ( + self.kernel(Xnew, full_cov=False) + + tf.reduce_sum(tf.square(tmp2), axis=0) + - tf.reduce_sum(tf.square(tmp1), axis=0) + ) + shape = tf.stack([1, tf.shape(Y_data)[1]]) + var = tf.tile(tf.expand_dims(var, 1), shape) + return mean + self.mean_function(Xnew), var"," def predict_f( + self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False + ) -> MeanAndVariance: + """""" + Compute the mean and variance of the latent function at some new points. + Note that this is very similar to the SGPR prediction, for which + there are notes in the SGPR notebook. + + Note: This model does not allow full output covariances. + + :param Xnew: points at which to predict + """""" + if full_output_cov: + raise NotImplementedError + + pX = DiagonalGaussian(self.X_data_mean, self.X_data_var) + + Y_data = self.data + num_inducing = len(self.inducing_variable) + psi1 = expectation(pX, (self.kernel, self.inducing_variable)) + psi2 = tf.reduce_sum( + expectation( + pX, (self.kernel, self.inducing_variable), (self.kernel, self.inducing_variable) + ), + axis=0, + ) + jitter = default_jitter() + Kus = covariances.Kuf(self.inducing_variable, self.kernel, Xnew) + sigma2 = self.likelihood.variance + sigma = tf.sqrt(sigma2) + L = tf.linalg.cholesky(covariances.Kuu(self.inducing_variable, self.kernel, jitter=jitter)) + + A = tf.linalg.triangular_solve(L, tf.transpose(psi1), lower=True) / sigma + tmp = tf.linalg.triangular_solve(L, psi2, lower=True) + AAT = tf.linalg.triangular_solve(L, tf.transpose(tmp), lower=True) / sigma2 + B = AAT + tf.eye(num_inducing, dtype=default_float()) + LB = tf.linalg.cholesky(B) + c = tf.linalg.triangular_solve(LB, tf.linalg.matmul(A, Y_data), lower=True) / sigma + tmp1 = tf.linalg.triangular_solve(L, Kus, lower=True) + tmp2 = tf.linalg.triangular_solve(LB, tmp1, lower=True) + mean = tf.linalg.matmul(tmp2, c, transpose_a=True) + if full_cov: + var = ( + self.kernel(Xnew) + + tf.linalg.matmul(tmp2, tmp2, transpose_a=True) + - tf.linalg.matmul(tmp1, tmp1, transpose_a=True) + ) + shape = tf.stack([1, 1, tf.shape(Y_data)[1]]) + var = tf.tile(tf.expand_dims(var, 2), shape) + else: + var = ( + self.kernel(Xnew, full_cov=False) + + tf.reduce_sum(tf.square(tmp2), axis=0) + - tf.reduce_sum(tf.square(tmp1), axis=0) + ) + shape = tf.stack([1, tf.shape(Y_data)[1]]) + var = tf.tile(tf.expand_dims(var, 1), shape) + return mean + self.mean_function(Xnew), var","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def __init__( + self, + data: RegressionData, + kernel: Kernel, + likelihood: Likelihood, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + inducing_variable: Optional[InducingPoints] = None, + ): + """""" + data is a tuple of X, Y with X, a data matrix, size [N, D] and Y, a data matrix, size [N, R] + Z is a data matrix, of inducing inputs, size [M, D] + kernel, likelihood, mean_function are appropriate GPflow objects + """""" + if num_latent_gps is None: + num_latent_gps = self.calc_num_latent_gps_from_data(data, kernel, likelihood) + super().__init__(kernel, likelihood, mean_function, num_latent_gps=num_latent_gps) + self.data = data_input_to_tensor(data) + self.num_data = data[0].shape[0] + self.inducing_variable = inducingpoint_wrapper(inducing_variable) + self.V = Parameter(np.zeros((self.inducing_variable.num_inducing, self.num_latent_gps))) + self.V.prior = tfp.distributions.Normal( + loc=to_default_float(0.0), scale=to_default_float(1.0) + )"," def __init__( + self, + data: RegressionData, + kernel: Kernel, + likelihood: Likelihood, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + inducing_variable: Optional[InducingPoints] = None, + ): + """""" + data is a tuple of X, Y with X, a data matrix, size [N, D] and Y, a data matrix, size [N, R] + Z is a data matrix, of inducing inputs, size [M, D] + kernel, likelihood, mean_function are appropriate GPflow objects + """""" + if num_latent_gps is None: + num_latent_gps = self.calc_num_latent_gps_from_data(data, kernel, likelihood) + super().__init__(kernel, likelihood, mean_function, num_latent_gps=num_latent_gps) + self.data = data_input_to_tensor(data) + self.num_data = data[0].shape[0] + self.inducing_variable = inducingpoint_wrapper(inducing_variable) + self.V = Parameter(np.zeros((len(self.inducing_variable), self.num_latent_gps))) + self.V.prior = tfp.distributions.Normal( + loc=to_default_float(0.0), scale=to_default_float(1.0) + )","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def upper_bound(self) -> tf.Tensor: + """""" + Upper bound for the sparse GP regression marginal likelihood. Note that + the same inducing points are used for calculating the upper bound, as are + used for computing the likelihood approximation. This may not lead to the + best upper bound. The upper bound can be tightened by optimising Z, just + like the lower bound. This is especially important in FITC, as FITC is + known to produce poor inducing point locations. An optimisable upper bound + can be found in https://github.com/markvdw/gp_upper. + + The key reference is + + :: + + @misc{titsias_2014, + title={Variational Inference for Gaussian and Determinantal Point Processes}, + url={http://www2.aueb.gr/users/mtitsias/papers/titsiasNipsVar14.pdf}, + publisher={Workshop on Advances in Variational Inference (NIPS 2014)}, + author={Titsias, Michalis K.}, + year={2014}, + month={Dec} + } + + The key quantity, the trace term, can be computed via + + >>> _, v = conditionals.conditional(X, model.inducing_variable.Z, model.kernel, + ... np.zeros((model.inducing_variable.num_inducing, 1))) + + which computes each individual element of the trace term. + """""" + X_data, Y_data = self.data + num_data = to_default_float(tf.shape(Y_data)[0]) + + Kdiag = self.kernel(X_data, full_cov=False) + kuu = Kuu(self.inducing_variable, self.kernel, jitter=default_jitter()) + kuf = Kuf(self.inducing_variable, self.kernel, X_data) + + I = tf.eye(tf.shape(kuu)[0], dtype=default_float()) + + L = tf.linalg.cholesky(kuu) + A = tf.linalg.triangular_solve(L, kuf, lower=True) + AAT = tf.linalg.matmul(A, A, transpose_b=True) + B = I + AAT / self.likelihood.variance + LB = tf.linalg.cholesky(B) + + # Using the Trace bound, from Titsias' presentation + c = tf.reduce_sum(Kdiag) - tf.reduce_sum(tf.square(A)) + + # Alternative bound on max eigenval: + corrected_noise = self.likelihood.variance + c + + const = -0.5 * num_data * tf.math.log(2 * np.pi * self.likelihood.variance) + logdet = -tf.reduce_sum(tf.math.log(tf.linalg.diag_part(LB))) + + err = Y_data - self.mean_function(X_data) + LC = tf.linalg.cholesky(I + AAT / corrected_noise) + v = tf.linalg.triangular_solve(LC, tf.linalg.matmul(A, err) / corrected_noise, lower=True) + quad = -0.5 * tf.reduce_sum(tf.square(err)) / corrected_noise + 0.5 * tf.reduce_sum( + tf.square(v) + ) + + return const + logdet + quad"," def upper_bound(self) -> tf.Tensor: + """""" + Upper bound for the sparse GP regression marginal likelihood. Note that + the same inducing points are used for calculating the upper bound, as are + used for computing the likelihood approximation. This may not lead to the + best upper bound. The upper bound can be tightened by optimising Z, just + like the lower bound. This is especially important in FITC, as FITC is + known to produce poor inducing point locations. An optimisable upper bound + can be found in https://github.com/markvdw/gp_upper. + + The key reference is + + :: + + @misc{titsias_2014, + title={Variational Inference for Gaussian and Determinantal Point Processes}, + url={http://www2.aueb.gr/users/mtitsias/papers/titsiasNipsVar14.pdf}, + publisher={Workshop on Advances in Variational Inference (NIPS 2014)}, + author={Titsias, Michalis K.}, + year={2014}, + month={Dec} + } + + The key quantity, the trace term, can be computed via + + >>> _, v = conditionals.conditional(X, model.inducing_variable.Z, model.kernel, + ... np.zeros((len(model.inducing_variable), 1))) + + which computes each individual element of the trace term. + """""" + X_data, Y_data = self.data + num_data = to_default_float(tf.shape(Y_data)[0]) + + Kdiag = self.kernel(X_data, full_cov=False) + kuu = Kuu(self.inducing_variable, self.kernel, jitter=default_jitter()) + kuf = Kuf(self.inducing_variable, self.kernel, X_data) + + I = tf.eye(tf.shape(kuu)[0], dtype=default_float()) + + L = tf.linalg.cholesky(kuu) + A = tf.linalg.triangular_solve(L, kuf, lower=True) + AAT = tf.linalg.matmul(A, A, transpose_b=True) + B = I + AAT / self.likelihood.variance + LB = tf.linalg.cholesky(B) + + # Using the Trace bound, from Titsias' presentation + c = tf.reduce_sum(Kdiag) - tf.reduce_sum(tf.square(A)) + + # Alternative bound on max eigenval: + corrected_noise = self.likelihood.variance + c + + const = -0.5 * num_data * tf.math.log(2 * np.pi * self.likelihood.variance) + logdet = -tf.reduce_sum(tf.math.log(tf.linalg.diag_part(LB))) + + err = Y_data - self.mean_function(X_data) + LC = tf.linalg.cholesky(I + AAT / corrected_noise) + v = tf.linalg.triangular_solve(LC, tf.linalg.matmul(A, err) / corrected_noise, lower=True) + quad = -0.5 * tf.reduce_sum(tf.square(err)) / corrected_noise + 0.5 * tf.reduce_sum( + tf.square(v) + ) + + return const + logdet + quad","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def elbo(self) -> tf.Tensor: + """""" + Construct a tensorflow function to compute the bound on the marginal + likelihood. For a derivation of the terms in here, see the associated + SGPR notebook. + """""" + X_data, Y_data = self.data + + num_inducing = self.inducing_variable.num_inducing + num_data = to_default_float(tf.shape(Y_data)[0]) + output_dim = to_default_float(tf.shape(Y_data)[1]) + + err = Y_data - self.mean_function(X_data) + Kdiag = self.kernel(X_data, full_cov=False) + kuf = Kuf(self.inducing_variable, self.kernel, X_data) + kuu = Kuu(self.inducing_variable, self.kernel, jitter=default_jitter()) + L = tf.linalg.cholesky(kuu) + sigma = tf.sqrt(self.likelihood.variance) + + # Compute intermediate matrices + A = tf.linalg.triangular_solve(L, kuf, lower=True) / sigma + AAT = tf.linalg.matmul(A, A, transpose_b=True) + B = AAT + tf.eye(num_inducing, dtype=default_float()) + LB = tf.linalg.cholesky(B) + Aerr = tf.linalg.matmul(A, err) + c = tf.linalg.triangular_solve(LB, Aerr, lower=True) / sigma + + # compute log marginal bound + bound = -0.5 * num_data * output_dim * np.log(2 * np.pi) + bound += tf.negative(output_dim) * tf.reduce_sum(tf.math.log(tf.linalg.diag_part(LB))) + bound -= 0.5 * num_data * output_dim * tf.math.log(self.likelihood.variance) + bound += -0.5 * tf.reduce_sum(tf.square(err)) / self.likelihood.variance + bound += 0.5 * tf.reduce_sum(tf.square(c)) + bound += -0.5 * output_dim * tf.reduce_sum(Kdiag) / self.likelihood.variance + bound += 0.5 * output_dim * tf.reduce_sum(tf.linalg.diag_part(AAT)) + + return bound"," def elbo(self) -> tf.Tensor: + """""" + Construct a tensorflow function to compute the bound on the marginal + likelihood. For a derivation of the terms in here, see the associated + SGPR notebook. + """""" + X_data, Y_data = self.data + + num_inducing = len(self.inducing_variable) + num_data = to_default_float(tf.shape(Y_data)[0]) + output_dim = to_default_float(tf.shape(Y_data)[1]) + + err = Y_data - self.mean_function(X_data) + Kdiag = self.kernel(X_data, full_cov=False) + kuf = Kuf(self.inducing_variable, self.kernel, X_data) + kuu = Kuu(self.inducing_variable, self.kernel, jitter=default_jitter()) + L = tf.linalg.cholesky(kuu) + sigma = tf.sqrt(self.likelihood.variance) + + # Compute intermediate matrices + A = tf.linalg.triangular_solve(L, kuf, lower=True) / sigma + AAT = tf.linalg.matmul(A, A, transpose_b=True) + B = AAT + tf.eye(num_inducing, dtype=default_float()) + LB = tf.linalg.cholesky(B) + Aerr = tf.linalg.matmul(A, err) + c = tf.linalg.triangular_solve(LB, Aerr, lower=True) / sigma + + # compute log marginal bound + bound = -0.5 * num_data * output_dim * np.log(2 * np.pi) + bound += tf.negative(output_dim) * tf.reduce_sum(tf.math.log(tf.linalg.diag_part(LB))) + bound -= 0.5 * num_data * output_dim * tf.math.log(self.likelihood.variance) + bound += -0.5 * tf.reduce_sum(tf.square(err)) / self.likelihood.variance + bound += 0.5 * tf.reduce_sum(tf.square(c)) + bound += -0.5 * output_dim * tf.reduce_sum(Kdiag) / self.likelihood.variance + bound += 0.5 * output_dim * tf.reduce_sum(tf.linalg.diag_part(AAT)) + + return bound","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def predict_f(self, Xnew: InputData, full_cov=False, full_output_cov=False) -> MeanAndVariance: + """""" + Compute the mean and variance of the latent function at some new points + Xnew. For a derivation of the terms in here, see the associated SGPR + notebook. + """""" + X_data, Y_data = self.data + num_inducing = self.inducing_variable.num_inducing + err = Y_data - self.mean_function(X_data) + kuf = Kuf(self.inducing_variable, self.kernel, X_data) + kuu = Kuu(self.inducing_variable, self.kernel, jitter=default_jitter()) + Kus = Kuf(self.inducing_variable, self.kernel, Xnew) + sigma = tf.sqrt(self.likelihood.variance) + L = tf.linalg.cholesky(kuu) + A = tf.linalg.triangular_solve(L, kuf, lower=True) / sigma + B = tf.linalg.matmul(A, A, transpose_b=True) + tf.eye(num_inducing, dtype=default_float()) + LB = tf.linalg.cholesky(B) + Aerr = tf.linalg.matmul(A, err) + c = tf.linalg.triangular_solve(LB, Aerr, lower=True) / sigma + tmp1 = tf.linalg.triangular_solve(L, Kus, lower=True) + tmp2 = tf.linalg.triangular_solve(LB, tmp1, lower=True) + mean = tf.linalg.matmul(tmp2, c, transpose_a=True) + if full_cov: + var = ( + self.kernel(Xnew) + + tf.linalg.matmul(tmp2, tmp2, transpose_a=True) + - tf.linalg.matmul(tmp1, tmp1, transpose_a=True) + ) + var = tf.tile(var[None, ...], [self.num_latent_gps, 1, 1]) # [P, N, N] + else: + var = ( + self.kernel(Xnew, full_cov=False) + + tf.reduce_sum(tf.square(tmp2), 0) + - tf.reduce_sum(tf.square(tmp1), 0) + ) + var = tf.tile(var[:, None], [1, self.num_latent_gps]) + return mean + self.mean_function(Xnew), var"," def predict_f(self, Xnew: InputData, full_cov=False, full_output_cov=False) -> MeanAndVariance: + """""" + Compute the mean and variance of the latent function at some new points + Xnew. For a derivation of the terms in here, see the associated SGPR + notebook. + """""" + X_data, Y_data = self.data + num_inducing = len(self.inducing_variable) + err = Y_data - self.mean_function(X_data) + kuf = Kuf(self.inducing_variable, self.kernel, X_data) + kuu = Kuu(self.inducing_variable, self.kernel, jitter=default_jitter()) + Kus = Kuf(self.inducing_variable, self.kernel, Xnew) + sigma = tf.sqrt(self.likelihood.variance) + L = tf.linalg.cholesky(kuu) + A = tf.linalg.triangular_solve(L, kuf, lower=True) / sigma + B = tf.linalg.matmul(A, A, transpose_b=True) + tf.eye(num_inducing, dtype=default_float()) + LB = tf.linalg.cholesky(B) + Aerr = tf.linalg.matmul(A, err) + c = tf.linalg.triangular_solve(LB, Aerr, lower=True) / sigma + tmp1 = tf.linalg.triangular_solve(L, Kus, lower=True) + tmp2 = tf.linalg.triangular_solve(LB, tmp1, lower=True) + mean = tf.linalg.matmul(tmp2, c, transpose_a=True) + if full_cov: + var = ( + self.kernel(Xnew) + + tf.linalg.matmul(tmp2, tmp2, transpose_a=True) + - tf.linalg.matmul(tmp1, tmp1, transpose_a=True) + ) + var = tf.tile(var[None, ...], [self.num_latent_gps, 1, 1]) # [P, N, N] + else: + var = ( + self.kernel(Xnew, full_cov=False) + + tf.reduce_sum(tf.square(tmp2), 0) + - tf.reduce_sum(tf.square(tmp1), 0) + ) + var = tf.tile(var[:, None], [1, self.num_latent_gps]) + return mean + self.mean_function(Xnew), var","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def common_terms(self): + X_data, Y_data = self.data + num_inducing = self.inducing_variable.num_inducing + err = Y_data - self.mean_function(X_data) # size [N, R] + Kdiag = self.kernel(X_data, full_cov=False) + kuf = Kuf(self.inducing_variable, self.kernel, X_data) + kuu = Kuu(self.inducing_variable, self.kernel, jitter=default_jitter()) + + Luu = tf.linalg.cholesky(kuu) # => Luu Luu^T = kuu + V = tf.linalg.triangular_solve(Luu, kuf) # => V^T V = Qff = kuf^T kuu^-1 kuf + + diagQff = tf.reduce_sum(tf.square(V), 0) + nu = Kdiag - diagQff + self.likelihood.variance + + B = tf.eye(num_inducing, dtype=default_float()) + tf.linalg.matmul( + V / nu, V, transpose_b=True + ) + L = tf.linalg.cholesky(B) + beta = err / tf.expand_dims(nu, 1) # size [N, R] + alpha = tf.linalg.matmul(V, beta) # size [N, R] + + gamma = tf.linalg.triangular_solve(L, alpha, lower=True) # size [N, R] + + return err, nu, Luu, L, alpha, beta, gamma"," def common_terms(self): + X_data, Y_data = self.data + num_inducing = len(self.inducing_variable) + err = Y_data - self.mean_function(X_data) # size [N, R] + Kdiag = self.kernel(X_data, full_cov=False) + kuf = Kuf(self.inducing_variable, self.kernel, X_data) + kuu = Kuu(self.inducing_variable, self.kernel, jitter=default_jitter()) + + Luu = tf.linalg.cholesky(kuu) # => Luu Luu^T = kuu + V = tf.linalg.triangular_solve(Luu, kuf) # => V^T V = Qff = kuf^T kuu^-1 kuf + + diagQff = tf.reduce_sum(tf.square(V), 0) + nu = Kdiag - diagQff + self.likelihood.variance + + B = tf.eye(num_inducing, dtype=default_float()) + tf.linalg.matmul( + V / nu, V, transpose_b=True + ) + L = tf.linalg.cholesky(B) + beta = err / tf.expand_dims(nu, 1) # size [N, R] + alpha = tf.linalg.matmul(V, beta) # size [N, R] + + gamma = tf.linalg.triangular_solve(L, alpha, lower=True) # size [N, R] + + return err, nu, Luu, L, alpha, beta, gamma","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +" def __init__( + self, + kernel, + likelihood, + inducing_variable, + *, + mean_function=None, + num_latent_gps: int = 1, + q_diag: bool = False, + q_mu=None, + q_sqrt=None, + whiten: bool = True, + num_data=None, + ): + """""" + - kernel, likelihood, inducing_variables, mean_function are appropriate + GPflow objects + - num_latent_gps is the number of latent processes to use, defaults to 1 + - q_diag is a boolean. If True, the covariance is approximated by a + diagonal matrix. + - whiten is a boolean. If True, we use the whitened representation of + the inducing points. + - num_data is the total number of observations, defaults to X.shape[0] + (relevant when feeding in external minibatches) + """""" + # init the super class, accept args + super().__init__(kernel, likelihood, mean_function, num_latent_gps) + self.num_data = num_data + self.q_diag = q_diag + self.whiten = whiten + self.inducing_variable = inducingpoint_wrapper(inducing_variable) + + # init variational parameters + num_inducing = self.inducing_variable.num_inducing + self._init_variational_parameters(num_inducing, q_mu, q_sqrt, q_diag)"," def __init__( + self, + kernel, + likelihood, + inducing_variable, + *, + mean_function=None, + num_latent_gps: int = 1, + q_diag: bool = False, + q_mu=None, + q_sqrt=None, + whiten: bool = True, + num_data=None, + ): + """""" + - kernel, likelihood, inducing_variables, mean_function are appropriate + GPflow objects + - num_latent_gps is the number of latent processes to use, defaults to 1 + - q_diag is a boolean. If True, the covariance is approximated by a + diagonal matrix. + - whiten is a boolean. If True, we use the whitened representation of + the inducing points. + - num_data is the total number of observations, defaults to X.shape[0] + (relevant when feeding in external minibatches) + """""" + # init the super class, accept args + super().__init__(kernel, likelihood, mean_function, num_latent_gps) + self.num_data = num_data + self.q_diag = q_diag + self.whiten = whiten + self.inducing_variable = inducingpoint_wrapper(inducing_variable) + + # init variational parameters + num_inducing = len(self.inducing_variable) + self._init_variational_parameters(num_inducing, q_mu, q_sqrt, q_diag)","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nimport tensorflow as tf\\n\\nclass VariableInducingPoints(gpflow.inducing_variables.InducingPoints):\\ndef __init__(self, Z, name=None):\\nsuper().__init__(Z, name=name)\\n# overwrite with Variable with None as first element in shape so\\n# we can assign arrays with arbitrary length along this dimension:\\nself.Z = tf.Variable(Z, trainable=False, dtype=gpflow.default_float(),\\nshape=(None, Z.shape[1])\\n)\\n\\ndef __len__(self):\\nreturn tf.shape(self.Z)[0] # dynamic shape\\n# instead of the static shape returned by the InducingPoints parent class\\n\\nX, Y = np.random.randn(50, 2), np.random.randn(50, 1)\\nZ1 = np.random.randn(13, 2)\\n\\nk = gpflow.kernels.SquaredExponential()\\nm = gpflow.models.SGPR(data=(X, Y), kernel=k, inducing_variable=VariableInducingPoints(Z1))\\n\\nZ2 = np.random.randn(29, 2)\\nm.inducing_variable.Z.assign(Z2)\\n\\nopt = tf.optimizers.Adam()\\n\\n@tf.function\\ndef optimization_step():\\nopt.minimize(m.training_loss, m.trainable_variables)\\n\\nfor _ in range(iter):\\noptimization_step()'}, {'piece_type': 'error message', 'piece_content': 'TypeError Traceback (most recent call last)\\n in \\n38\\n39\\n---> 40 optimization_step()\\n41\\n42\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)\\n778 else:\\n779 compiler = ""nonXla""\\n--> 780 result = self._call(*args, **kwds)\\n781\\n782 new_tracing_count = self._get_tracing_count()\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)\\n821 # This is the first call of __call__, so we have to initialize.\\n822 initializers = []\\n--> 823 self._initialize(args, kwds, add_initializers_to=initializers)\\n824 finally:\\n825 # At this point we know that the initialization is complete (or less\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)\\n694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)\\n695 self._concrete_stateful_fn = (\\n--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access\\n697 *args, **kwds))\\n698\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)\\n2853 args, kwargs = None, None\\n2854 with self._lock:\\n-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs)\\n2856 return graph_function\\n2857\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)\\n3211\\n3212 self._function_cache.missed.add(call_context_key)\\n-> 3213 graph_function = self._create_graph_function(args, kwargs)\\n3214 self._function_cache.primary[cache_key] = graph_function\\n3215 return graph_function, args, kwargs\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)\\n3063 arg_names = base_arg_names + missing_arg_names\\n3064 graph_function = ConcreteFunction(\\n-> 3065 func_graph_module.func_graph_from_py_func(\\n3066 self._name,\\n3067 self._python_function,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)\\n984 _, original_func = tf_decorator.unwrap(python_func)\\n985\\n--> 986 func_outputs = python_func(*func_args, **func_kwargs)\\n987\\n988 # invariant: `func_outputs` contains only Tensors, CompositeTensors,\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)\\n598 # __wrapped__ allows AutoGraph to swap in a converted function. We give\\n599 # the function a weak reference to itself to avoid a reference cycle.\\n--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds)\\n601 weak_wrapped_fn = weakref.ref(wrapped_fn)\\n602\\n\\n~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)\\n971 except Exception as e: # pylint:disable=broad-except\\n972 if hasattr(e, ""ag_error_metadata""):\\n--> 973 raise e.ag_error_metadata.to_exception(e)\\n974 else:\\n975 raise\\n\\nTypeError: in user code:\\n\\n:32 optimization_step *\\noptimizer.minimize(m.training_loss, m.trainable_variables)\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize **\\ngrads_and_vars = self._compute_gradients(\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients\\nloss_value = loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss\\nreturn self._training_loss()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss\\nreturn -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density())\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective\\nreturn self.elbo()\\n/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo\\nnum_inducing = len(self.inducing_variable)\\n\\nTypeError: \\'Tensor\\' object cannot be interpreted as an integer'}]","TypeError Traceback (most recent call last) + in +38 +39 +---> 40 optimization_step() +41 +42 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) +778 else: +779 compiler = ""nonXla"" +--> 780 result = self._call(*args, **kwds) +781 +782 new_tracing_count = self._get_tracing_count() + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) +821 # This is the first call of __call__, so we have to initialize. +822 initializers = [] +--> 823 self._initialize(args, kwds, add_initializers_to=initializers) +824 finally: +825 # At this point we know that the initialization is complete (or less + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) +694 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph) +695 self._concrete_stateful_fn = ( +--> 696 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access +697 *args, **kwds)) +698 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) +2853 args, kwargs = None, None +2854 with self._lock: +-> 2855 graph_function, _, _ = self._maybe_define_function(args, kwargs) +2856 return graph_function +2857 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) +3211 +3212 self._function_cache.missed.add(call_context_key) +-> 3213 graph_function = self._create_graph_function(args, kwargs) +3214 self._function_cache.primary[cache_key] = graph_function +3215 return graph_function, args, kwargs + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) +3063 arg_names = base_arg_names + missing_arg_names +3064 graph_function = ConcreteFunction( +-> 3065 func_graph_module.func_graph_from_py_func( +3066 self._name, +3067 self._python_function, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes) +984 _, original_func = tf_decorator.unwrap(python_func) +985 +--> 986 func_outputs = python_func(*func_args, **func_kwargs) +987 +988 # invariant: `func_outputs` contains only Tensors, CompositeTensors, + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) +598 # __wrapped__ allows AutoGraph to swap in a converted function. We give +599 # the function a weak reference to itself to avoid a reference cycle. +--> 600 return weak_wrapped_fn().__wrapped__(*args, **kwds) +601 weak_wrapped_fn = weakref.ref(wrapped_fn) +602 + +~/anaconda3/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) +971 except Exception as e: # pylint:disable=broad-except +972 if hasattr(e, ""ag_error_metadata""): +--> 973 raise e.ag_error_metadata.to_exception(e) +974 else: +975 raise + +TypeError: in user code: + +:32 optimization_step * +optimizer.minimize(m.training_loss, m.trainable_variables) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:374 minimize ** +grads_and_vars = self._compute_gradients( +/home/maltamirano/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:429 _compute_gradients +loss_value = loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/training_mixins.py:64 training_loss +return self._training_loss() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/model.py:57 _training_loss +return -(self.maximum_log_likelihood_objective(*args, **kwargs) + self.log_prior_density()) +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:154 maximum_log_likelihood_objective +return self.elbo() +/home/maltamirano/anaconda3/lib/python3.8/site-packages/gpflow/models/sgpr.py:164 elbo +num_inducing = len(self.inducing_variable) + +TypeError: 'Tensor' object cannot be interpreted as an integer",TypeError +"def ndiagquad(funcs, H: int, Fmu, Fvar, logspace: bool = False, **Ys): + """""" + Computes N Gaussian expectation integrals of one or more functions + using Gauss-Hermite quadrature. The Gaussians must be independent. + + The means and variances of the Gaussians are specified by Fmu and Fvar. + The N-integrals are assumed to be taken wrt the last dimensions of Fmu, Fvar. + + :param funcs: the integrand(s): + Callable or Iterable of Callables that operates elementwise + :param H: number of Gauss-Hermite quadrature points + :param Fmu: array/tensor or `Din`-tuple/list thereof + :param Fvar: array/tensor or `Din`-tuple/list thereof + :param logspace: if True, funcs are the log-integrands and this calculates + the log-expectation of exp(funcs) + :param **Ys: arrays/tensors; deterministic arguments to be passed by name + + Fmu, Fvar, Ys should all have same shape, with overall size `N` + :return: shape is the same as that of the first Fmu + """""" + n_gh = H + if isinstance(Fmu, (tuple, list)): + dim = len(Fmu) + shape = tf.shape(Fmu[0]) + Fmu = tf.stack(Fmu, axis=-1) + Fvar = tf.stack(Fvar, axis=-1) + else: + dim = 1 + shape = tf.shape(Fmu) + + Fmu = tf.reshape(Fmu, (-1, dim)) + Fvar = tf.reshape(Fvar, (-1, dim)) + + Ys = {Yname: tf.reshape(Y, (-1, 1)) for Yname, Y in Ys.items()} + + def wrapper(old_fun): + def new_fun(X, **Ys): + Xs = tf.unstack(X, axis=-1) + fun_eval = old_fun(*Xs, **Ys) + return tf.cond( + pred=tf.less(tf.rank(fun_eval), tf.rank(X)), + true_fn=lambda: fun_eval[..., tf.newaxis], + false_fn=lambda: fun_eval, + ) + + return new_fun + + if isinstance(funcs, Iterable): + funcs = [wrapper(f) for f in funcs] + else: + funcs = wrapper(funcs) + + quadrature = NDiagGHQuadrature(dim, n_gh) + if logspace: + result = quadrature.logspace(funcs, Fmu, Fvar, **Ys) + else: + result = quadrature(funcs, Fmu, Fvar, **Ys) + + if isinstance(result, list): + result = [tf.reshape(r, shape) for r in result] + else: + result = tf.reshape(result, shape) + + return result","def ndiagquad(funcs, H: int, Fmu, Fvar, logspace: bool = False, **Ys): + """""" + Computes N Gaussian expectation integrals of one or more functions + using Gauss-Hermite quadrature. The Gaussians must be independent. + + The means and variances of the Gaussians are specified by Fmu and Fvar. + The N-integrals are assumed to be taken wrt the last dimensions of Fmu, Fvar. + + :param funcs: the integrand(s): + Callable or Iterable of Callables that operates elementwise + :param H: number of Gauss-Hermite quadrature points + :param Fmu: array/tensor or `Din`-tuple/list thereof + :param Fvar: array/tensor or `Din`-tuple/list thereof + :param logspace: if True, funcs are the log-integrands and this calculates + the log-expectation of exp(funcs) + :param **Ys: arrays/tensors; deterministic arguments to be passed by name + + Fmu, Fvar, Ys should all have same shape, with overall size `N` + :return: shape is the same as that of the first Fmu + """""" + n_gh = H + if isinstance(Fmu, (tuple, list)): + dim = len(Fmu) + shape = tf.shape(Fmu[0]) + Fmu = tf.stack(Fmu, axis=-1) + Fvar = tf.stack(Fvar, axis=-1) + else: + dim = 1 + shape = tf.shape(Fmu) + + Fmu = tf.reshape(Fmu, (-1, dim)) + Fvar = tf.reshape(Fvar, (-1, dim)) + + Ys = {Yname: tf.reshape(Y, (-1, 1)) for Yname, Y in Ys.items()} + + def wrapper(old_fun): + def new_fun(X, **Ys): + Xs = tf.unstack(X, axis=-1) + fun_eval = old_fun(*Xs, **Ys) + if tf.rank(fun_eval) < tf.rank(X): + fun_eval = tf.expand_dims(fun_eval, axis=-1) + return fun_eval + + return new_fun + + if isinstance(funcs, Iterable): + funcs = [wrapper(f) for f in funcs] + else: + funcs = wrapper(funcs) + + quadrature = NDiagGHQuadrature(dim, n_gh) + if logspace: + result = quadrature.logspace(funcs, Fmu, Fvar, **Ys) + else: + result = quadrature(funcs, Fmu, Fvar, **Ys) + + if isinstance(result, list): + result = [tf.reshape(r, shape) for r in result] + else: + result = tf.reshape(result, shape) + + return result","[{'piece_type': 'other', 'piece_content': 'tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.'}, {'piece_type': 'reproducing source code', 'piece_content': ""import tensorflow as tf\\nimport numpy as np\\nfrom gpflow import quadrature\\n\\n\\n@tf.function(autograph=False)\\ndef compute():\\nmu = np.array([1.0, 1.3])\\nvar = np.array([3.0, 3.5])\\nnum_gauss_hermite_points = 25\\nquad = quadrature.ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var])\\nreturn quad\\n\\n\\ndef go():\\nquad = compute()\\nprint(f'Result: {quad}')\\n\\n\\ngo()""}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""gpflow_error.py"", line 20, in \\ngo()\\nFile ""gpflow_error.py"", line 16, in go\\nquad = compute()\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 580, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 627, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 506, in _initialize\\n*args, **kwds))\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2446, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2777, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2667, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py"", line 981, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 441, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""gpflow_error.py"", line 11, in compute\\nquad = quadrature.ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var])\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 156, in ndiagquad\\nresult = quadrature(funcs, Fmu, Fvar, **Ys)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in __call__\\nreturn [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun]\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in \\nreturn [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun]\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 141, in new_fun\\nif tf.rank(fun_eval) < tf.rank(X):\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 778, in __bool__\\nself._disallow_bool_casting()\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 542, in _disallow_bool_casting\\n""using a `tf.Tensor` as a Python `bool`"")\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 527, in _disallow_when_autograph_disabled\\n"" Try decorating it directly with @tf.function."".format(task))\\ntensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.'}]","Traceback (most recent call last): +File ""gpflow_error.py"", line 20, in +go() +File ""gpflow_error.py"", line 16, in go +quad = compute() +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 580, in __call__ +result = self._call(*args, **kwds) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 627, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 506, in _initialize +*args, **kwds)) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2446, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2777, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2667, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py"", line 981, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 441, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""gpflow_error.py"", line 11, in compute +quad = quadrature.ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var]) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 156, in ndiagquad +result = quadrature(funcs, Fmu, Fvar, **Ys) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in __call__ +return [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun] +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in +return [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun] +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 141, in new_fun +if tf.rank(fun_eval) < tf.rank(X): +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 778, in __bool__ +self._disallow_bool_casting() +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 542, in _disallow_bool_casting +""using a `tf.Tensor` as a Python `bool`"") +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 527, in _disallow_when_autograph_disabled +"" Try decorating it directly with @tf.function."".format(task)) +tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.",tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError +" def wrapper(old_fun): + def new_fun(X, **Ys): + Xs = tf.unstack(X, axis=-1) + fun_eval = old_fun(*Xs, **Ys) + return tf.cond( + pred=tf.less(tf.rank(fun_eval), tf.rank(X)), + true_fn=lambda: fun_eval[..., tf.newaxis], + false_fn=lambda: fun_eval, + ) + + return new_fun"," def wrapper(old_fun): + def new_fun(X, **Ys): + Xs = tf.unstack(X, axis=-1) + fun_eval = old_fun(*Xs, **Ys) + if tf.rank(fun_eval) < tf.rank(X): + fun_eval = tf.expand_dims(fun_eval, axis=-1) + return fun_eval + + return new_fun","[{'piece_type': 'other', 'piece_content': 'tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.'}, {'piece_type': 'reproducing source code', 'piece_content': ""import tensorflow as tf\\nimport numpy as np\\nfrom gpflow import quadrature\\n\\n\\n@tf.function(autograph=False)\\ndef compute():\\nmu = np.array([1.0, 1.3])\\nvar = np.array([3.0, 3.5])\\nnum_gauss_hermite_points = 25\\nquad = quadrature.ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var])\\nreturn quad\\n\\n\\ndef go():\\nquad = compute()\\nprint(f'Result: {quad}')\\n\\n\\ngo()""}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""gpflow_error.py"", line 20, in \\ngo()\\nFile ""gpflow_error.py"", line 16, in go\\nquad = compute()\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 580, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 627, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 506, in _initialize\\n*args, **kwds))\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2446, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2777, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2667, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py"", line 981, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 441, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""gpflow_error.py"", line 11, in compute\\nquad = quadrature.ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var])\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 156, in ndiagquad\\nresult = quadrature(funcs, Fmu, Fvar, **Ys)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in __call__\\nreturn [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun]\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in \\nreturn [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun]\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 141, in new_fun\\nif tf.rank(fun_eval) < tf.rank(X):\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 778, in __bool__\\nself._disallow_bool_casting()\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 542, in _disallow_bool_casting\\n""using a `tf.Tensor` as a Python `bool`"")\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 527, in _disallow_when_autograph_disabled\\n"" Try decorating it directly with @tf.function."".format(task))\\ntensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.'}]","Traceback (most recent call last): +File ""gpflow_error.py"", line 20, in +go() +File ""gpflow_error.py"", line 16, in go +quad = compute() +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 580, in __call__ +result = self._call(*args, **kwds) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 627, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 506, in _initialize +*args, **kwds)) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2446, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2777, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2667, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py"", line 981, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 441, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""gpflow_error.py"", line 11, in compute +quad = quadrature.ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var]) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 156, in ndiagquad +result = quadrature(funcs, Fmu, Fvar, **Ys) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in __call__ +return [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun] +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in +return [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun] +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 141, in new_fun +if tf.rank(fun_eval) < tf.rank(X): +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 778, in __bool__ +self._disallow_bool_casting() +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 542, in _disallow_bool_casting +""using a `tf.Tensor` as a Python `bool`"") +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 527, in _disallow_when_autograph_disabled +"" Try decorating it directly with @tf.function."".format(task)) +tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.",tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError +" def new_fun(X, **Ys): + Xs = tf.unstack(X, axis=-1) + fun_eval = old_fun(*Xs, **Ys) + return tf.cond( + pred=tf.less(tf.rank(fun_eval), tf.rank(X)), + true_fn=lambda: fun_eval[..., tf.newaxis], + false_fn=lambda: fun_eval, + )"," def new_fun(X, **Ys): + Xs = tf.unstack(X, axis=-1) + fun_eval = old_fun(*Xs, **Ys) + if tf.rank(fun_eval) < tf.rank(X): + fun_eval = tf.expand_dims(fun_eval, axis=-1) + return fun_eval","[{'piece_type': 'other', 'piece_content': 'tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.'}, {'piece_type': 'reproducing source code', 'piece_content': ""import tensorflow as tf\\nimport numpy as np\\nfrom gpflow import quadrature\\n\\n\\n@tf.function(autograph=False)\\ndef compute():\\nmu = np.array([1.0, 1.3])\\nvar = np.array([3.0, 3.5])\\nnum_gauss_hermite_points = 25\\nquad = quadrature.ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var])\\nreturn quad\\n\\n\\ndef go():\\nquad = compute()\\nprint(f'Result: {quad}')\\n\\n\\ngo()""}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""gpflow_error.py"", line 20, in \\ngo()\\nFile ""gpflow_error.py"", line 16, in go\\nquad = compute()\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 580, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 627, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 506, in _initialize\\n*args, **kwds))\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2446, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2777, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2667, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py"", line 981, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 441, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""gpflow_error.py"", line 11, in compute\\nquad = quadrature.ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var])\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 156, in ndiagquad\\nresult = quadrature(funcs, Fmu, Fvar, **Ys)\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in __call__\\nreturn [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun]\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in \\nreturn [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun]\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 141, in new_fun\\nif tf.rank(fun_eval) < tf.rank(X):\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 778, in __bool__\\nself._disallow_bool_casting()\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 542, in _disallow_bool_casting\\n""using a `tf.Tensor` as a Python `bool`"")\\nFile ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 527, in _disallow_when_autograph_disabled\\n"" Try decorating it directly with @tf.function."".format(task))\\ntensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.'}]","Traceback (most recent call last): +File ""gpflow_error.py"", line 20, in +go() +File ""gpflow_error.py"", line 16, in go +quad = compute() +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 580, in __call__ +result = self._call(*args, **kwds) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 627, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 506, in _initialize +*args, **kwds)) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2446, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2777, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/function.py"", line 2667, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py"", line 981, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py"", line 441, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""gpflow_error.py"", line 11, in compute +quad = quadrature.ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var]) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 156, in ndiagquad +result = quadrature(funcs, Fmu, Fvar, **Ys) +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in __call__ +return [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun] +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/base.py"", line 52, in +return [tf.reduce_sum(f(X, *args, **kwargs) * W, axis=-2) for f in fun] +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/gpflow/quadrature/deprecated.py"", line 141, in new_fun +if tf.rank(fun_eval) < tf.rank(X): +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 778, in __bool__ +self._disallow_bool_casting() +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 542, in _disallow_bool_casting +""using a `tf.Tensor` as a Python `bool`"") +File ""/Users/nferguson/gpflow_error/lib/python3.7/site-packages/tensorflow/python/framework/ops.py"", line 527, in _disallow_when_autograph_disabled +"" Try decorating it directly with @tf.function."".format(task)) +tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.",tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError +" def __init__( + self, + data: OutputData, + latent_dim: int, + X_data_mean: Optional[tf.Tensor] = None, + kernel: Optional[Kernel] = None, + mean_function: Optional[MeanFunction] = None, + ): + """""" + Initialise GPLVM object. This method only works with a Gaussian likelihood. + + :param data: y data matrix, size N (number of points) x D (dimensions) + :param latent_dim: the number of latent dimensions (Q) + :param X_data_mean: latent positions ([N, Q]), for the initialisation of the latent space. + :param kernel: kernel specification, by default Squared Exponential + :param mean_function: mean function, by default None. + """""" + if X_data_mean is None: + X_data_mean = pca_reduce(data, latent_dim) + + num_latent_gps = X_data_mean.shape[1] + if num_latent_gps != latent_dim: + msg = ""Passed in number of latent {0} does not match initial X {1}."" + raise ValueError(msg.format(latent_dim, num_latent_gps)) + + if mean_function is None: + mean_function = Zero() + + if kernel is None: + kernel = kernels.SquaredExponential(lengthscales=tf.ones((latent_dim,))) + + if data.shape[1] < num_latent_gps: + raise ValueError(""More latent dimensions than observed."") + + gpr_data = (Parameter(X_data_mean), data_input_to_tensor(data)) + super().__init__(gpr_data, kernel, mean_function=mean_function)"," def __init__( + self, + data: OutputData, + latent_dim: int, + X_data_mean: Optional[tf.Tensor] = None, + kernel: Optional[Kernel] = None, + mean_function: Optional[MeanFunction] = None, + ): + """""" + Initialise GPLVM object. This method only works with a Gaussian likelihood. + + :param data: y data matrix, size N (number of points) x D (dimensions) + :param latent_dim: the number of latent dimensions (Q) + :param X_data_mean: latent positions ([N, Q]), for the initialisation of the latent space. + :param kernel: kernel specification, by default Squared Exponential + :param mean_function: mean function, by default None. + """""" + if X_data_mean is None: + X_data_mean = pca_reduce(data, latent_dim) + + num_latent_gps = X_data_mean.shape[1] + if num_latent_gps != latent_dim: + msg = ""Passed in number of latent {0} does not match initial X {1}."" + raise ValueError(msg.format(latent_dim, num_latent_gps)) + + if mean_function is None: + mean_function = Zero() + + if kernel is None: + kernel = kernels.SquaredExponential(lengthscales=tf.ones((latent_dim,))) + + if data.shape[1] < num_latent_gps: + raise ValueError(""More latent dimensions than observed."") + + gpr_data = (Parameter(X_data_mean), data) + super().__init__(gpr_data, kernel, mean_function=mean_function)","[{'piece_type': 'other', 'piece_content': 'ValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 177, in \\nmain(args)\\nFile ""main.py"", line 64, in main\\nbuild_allele(args)\\nFile ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele\\nopt_model_list(m)\\nFile ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list\\nm.trainable_variables)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize\\nfunc, initial_params, jac=True, method=method, **scipy_kwargs\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize\\ncallback=callback, **options)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb\\nf, g = func_and_grad(x)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad\\nf = fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper\\nreturn function(*(wrapper_args + args))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__\\nfg = self.fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval\\nloss, grad = _tf_eval(tf.convert_to_tensor(x))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize\\n*args, **kwds))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper\\nraise e.ag_error_metadata.to_exception(e)\\nValueError: in converted code:\\n\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval *\\nloss, grads = _compute_loss_and_gradients(closure, variables)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients *\\nloss = loss_closure()\\n/path/to/1_model_sim/model.py:354 None *\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood *\\nlog_prob = multivariate_normal(Y, m, L)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal *\\nd = x - mu\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper\\nx = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"")\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor\\nret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function\\nreturn constant_op.constant(value, dtype, name=name)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant\\nallow_broadcast=True)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl\\nallow_broadcast=allow_broadcast))\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto\\n""Cannot create a tensor proto whose content is larger than 2GB."")\\n\\nValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'other', 'piece_content': 'm = gpf.models.GPR(data=(X, Y),\\nkernel=gpf.kernels.Exponential(active_dims = [0,1]),\\nmean_function=None)\\n\\nopt = gpf.optimizers.Scipy()\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\nm.trainable_variables)'}]","Traceback (most recent call last): +File ""main.py"", line 177, in +main(args) +File ""main.py"", line 64, in main +build_allele(args) +File ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele +opt_model_list(m) +File ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list +m.trainable_variables) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize +func, initial_params, jac=True, method=method, **scipy_kwargs +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize +callback=callback, **options) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb +f, g = func_and_grad(x) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad +f = fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper +return function(*(wrapper_args + args)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__ +fg = self.fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval +loss, grad = _tf_eval(tf.convert_to_tensor(x)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__ +result = self._call(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize +*args, **kwds)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper +raise e.ag_error_metadata.to_exception(e) +ValueError: in converted code: + +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval * +loss, grads = _compute_loss_and_gradients(closure, variables) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients * +loss = loss_closure() +/path/to/1_model_sim/model.py:354 None * +opt.minimize(lambda: - m.log_marginal_likelihood(), +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood * +log_prob = multivariate_normal(Y, m, L) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal * +d = x - mu +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper +x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"") +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor +ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function +return constant_op.constant(value, dtype, name=name) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant +allow_broadcast=True) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl +allow_broadcast=allow_broadcast)) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto +""Cannot create a tensor proto whose content is larger than 2GB."") + +ValueError: Cannot create a tensor proto whose content is larger than 2GB.",ValueError +" def __init__( + self, + data: OutputData, + X_data_mean: tf.Tensor, + X_data_var: tf.Tensor, + kernel: Kernel, + num_inducing_variables: Optional[int] = None, + inducing_variable=None, + X_prior_mean=None, + X_prior_var=None, + ): + """""" + Initialise Bayesian GPLVM object. This method only works with a Gaussian likelihood. + + :param data: data matrix, size N (number of points) x D (dimensions) + :param X_data_mean: initial latent positions, size N (number of points) x Q (latent dimensions). + :param X_data_var: variance of latent positions ([N, Q]), for the initialisation of the latent space. + :param kernel: kernel specification, by default Squared Exponential + :param num_inducing_variables: number of inducing points, M + :param inducing_variable: matrix of inducing points, size M (inducing points) x Q (latent dimensions). By default + random permutation of X_data_mean. + :param X_prior_mean: prior mean used in KL term of bound. By default 0. Same size as X_data_mean. + :param X_prior_var: prior variance used in KL term of bound. By default 1. + """""" + num_data, num_latent_gps = X_data_mean.shape + super().__init__(kernel, likelihoods.Gaussian(), num_latent_gps=num_latent_gps) + self.data = data_input_to_tensor(data) + assert X_data_var.ndim == 2 + + self.X_data_mean = Parameter(X_data_mean) + self.X_data_var = Parameter(X_data_var, transform=positive()) + + self.num_data = num_data + self.output_dim = self.data.shape[-1] + + assert np.all(X_data_mean.shape == X_data_var.shape) + assert X_data_mean.shape[0] == self.data.shape[0], ""X mean and Y must be same size."" + assert X_data_var.shape[0] == self.data.shape[0], ""X var and Y must be same size."" + + if (inducing_variable is None) == (num_inducing_variables is None): + raise ValueError( + ""BayesianGPLVM needs exactly one of `inducing_variable` and `num_inducing_variables`"" + ) + + if inducing_variable is None: + # By default we initialize by subset of initial latent points + # Note that tf.random.shuffle returns a copy, it does not shuffle in-place + Z = tf.random.shuffle(X_data_mean)[:num_inducing_variables] + inducing_variable = InducingPoints(Z) + + self.inducing_variable = inducingpoint_wrapper(inducing_variable) + + assert X_data_mean.shape[1] == self.num_latent_gps + + # deal with parameters for the prior mean variance of X + if X_prior_mean is None: + X_prior_mean = tf.zeros((self.num_data, self.num_latent_gps), dtype=default_float()) + if X_prior_var is None: + X_prior_var = tf.ones((self.num_data, self.num_latent_gps)) + + self.X_prior_mean = tf.convert_to_tensor(np.atleast_1d(X_prior_mean), dtype=default_float()) + self.X_prior_var = tf.convert_to_tensor(np.atleast_1d(X_prior_var), dtype=default_float()) + + assert self.X_prior_mean.shape[0] == self.num_data + assert self.X_prior_mean.shape[1] == self.num_latent_gps + assert self.X_prior_var.shape[0] == self.num_data + assert self.X_prior_var.shape[1] == self.num_latent_gps"," def __init__( + self, + data: OutputData, + X_data_mean: tf.Tensor, + X_data_var: tf.Tensor, + kernel: Kernel, + num_inducing_variables: Optional[int] = None, + inducing_variable=None, + X_prior_mean=None, + X_prior_var=None, + ): + """""" + Initialise Bayesian GPLVM object. This method only works with a Gaussian likelihood. + + :param data: data matrix, size N (number of points) x D (dimensions) + :param X_data_mean: initial latent positions, size N (number of points) x Q (latent dimensions). + :param X_data_var: variance of latent positions ([N, Q]), for the initialisation of the latent space. + :param kernel: kernel specification, by default Squared Exponential + :param num_inducing_variables: number of inducing points, M + :param inducing_variable: matrix of inducing points, size M (inducing points) x Q (latent dimensions). By default + random permutation of X_data_mean. + :param X_prior_mean: prior mean used in KL term of bound. By default 0. Same size as X_data_mean. + :param X_prior_var: prior variance used in KL term of bound. By default 1. + """""" + num_data, num_latent_gps = X_data_mean.shape + super().__init__(kernel, likelihoods.Gaussian(), num_latent_gps=num_latent_gps) + self.data = data + assert X_data_var.ndim == 2 + + self.X_data_mean = Parameter(X_data_mean) + self.X_data_var = Parameter(X_data_var, transform=positive()) + + self.num_data = num_data + self.output_dim = data.shape[-1] + + assert np.all(X_data_mean.shape == X_data_var.shape) + assert X_data_mean.shape[0] == data.shape[0], ""X mean and Y must be same size."" + assert X_data_var.shape[0] == data.shape[0], ""X var and Y must be same size."" + + if (inducing_variable is None) == (num_inducing_variables is None): + raise ValueError( + ""BayesianGPLVM needs exactly one of `inducing_variable` and `num_inducing_variables`"" + ) + + if inducing_variable is None: + # By default we initialize by subset of initial latent points + # Note that tf.random.shuffle returns a copy, it does not shuffle in-place + Z = tf.random.shuffle(X_data_mean)[:num_inducing_variables] + inducing_variable = InducingPoints(Z) + + self.inducing_variable = inducingpoint_wrapper(inducing_variable) + + assert X_data_mean.shape[1] == self.num_latent_gps + + # deal with parameters for the prior mean variance of X + if X_prior_mean is None: + X_prior_mean = tf.zeros((self.num_data, self.num_latent_gps), dtype=default_float()) + if X_prior_var is None: + X_prior_var = tf.ones((self.num_data, self.num_latent_gps)) + + self.X_prior_mean = tf.convert_to_tensor(np.atleast_1d(X_prior_mean), dtype=default_float()) + self.X_prior_var = tf.convert_to_tensor(np.atleast_1d(X_prior_var), dtype=default_float()) + + assert self.X_prior_mean.shape[0] == self.num_data + assert self.X_prior_mean.shape[1] == self.num_latent_gps + assert self.X_prior_var.shape[0] == self.num_data + assert self.X_prior_var.shape[1] == self.num_latent_gps","[{'piece_type': 'other', 'piece_content': 'ValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 177, in \\nmain(args)\\nFile ""main.py"", line 64, in main\\nbuild_allele(args)\\nFile ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele\\nopt_model_list(m)\\nFile ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list\\nm.trainable_variables)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize\\nfunc, initial_params, jac=True, method=method, **scipy_kwargs\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize\\ncallback=callback, **options)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb\\nf, g = func_and_grad(x)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad\\nf = fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper\\nreturn function(*(wrapper_args + args))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__\\nfg = self.fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval\\nloss, grad = _tf_eval(tf.convert_to_tensor(x))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize\\n*args, **kwds))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper\\nraise e.ag_error_metadata.to_exception(e)\\nValueError: in converted code:\\n\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval *\\nloss, grads = _compute_loss_and_gradients(closure, variables)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients *\\nloss = loss_closure()\\n/path/to/1_model_sim/model.py:354 None *\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood *\\nlog_prob = multivariate_normal(Y, m, L)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal *\\nd = x - mu\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper\\nx = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"")\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor\\nret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function\\nreturn constant_op.constant(value, dtype, name=name)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant\\nallow_broadcast=True)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl\\nallow_broadcast=allow_broadcast))\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto\\n""Cannot create a tensor proto whose content is larger than 2GB."")\\n\\nValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'other', 'piece_content': 'm = gpf.models.GPR(data=(X, Y),\\nkernel=gpf.kernels.Exponential(active_dims = [0,1]),\\nmean_function=None)\\n\\nopt = gpf.optimizers.Scipy()\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\nm.trainable_variables)'}]","Traceback (most recent call last): +File ""main.py"", line 177, in +main(args) +File ""main.py"", line 64, in main +build_allele(args) +File ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele +opt_model_list(m) +File ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list +m.trainable_variables) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize +func, initial_params, jac=True, method=method, **scipy_kwargs +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize +callback=callback, **options) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb +f, g = func_and_grad(x) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad +f = fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper +return function(*(wrapper_args + args)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__ +fg = self.fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval +loss, grad = _tf_eval(tf.convert_to_tensor(x)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__ +result = self._call(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize +*args, **kwds)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper +raise e.ag_error_metadata.to_exception(e) +ValueError: in converted code: + +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval * +loss, grads = _compute_loss_and_gradients(closure, variables) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients * +loss = loss_closure() +/path/to/1_model_sim/model.py:354 None * +opt.minimize(lambda: - m.log_marginal_likelihood(), +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood * +log_prob = multivariate_normal(Y, m, L) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal * +d = x - mu +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper +x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"") +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor +ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function +return constant_op.constant(value, dtype, name=name) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant +allow_broadcast=True) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl +allow_broadcast=allow_broadcast)) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto +""Cannot create a tensor proto whose content is larger than 2GB."") + +ValueError: Cannot create a tensor proto whose content is larger than 2GB.",ValueError +" def __init__( + self, + data: RegressionData, + kernel: Kernel, + mean_function: Optional[MeanFunction] = None, + noise_variance: float = 1.0, + ): + likelihood = gpflow.likelihoods.Gaussian(noise_variance) + _, Y_data = data + super().__init__(kernel, likelihood, mean_function, num_latent_gps=Y_data.shape[-1]) + self.data = data_input_to_tensor(data)"," def __init__( + self, + data: RegressionData, + kernel: Kernel, + mean_function: Optional[MeanFunction] = None, + noise_variance: float = 1.0, + ): + likelihood = gpflow.likelihoods.Gaussian(noise_variance) + _, Y_data = data + super().__init__(kernel, likelihood, mean_function, num_latent_gps=Y_data.shape[-1]) + self.data = data","[{'piece_type': 'other', 'piece_content': 'ValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 177, in \\nmain(args)\\nFile ""main.py"", line 64, in main\\nbuild_allele(args)\\nFile ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele\\nopt_model_list(m)\\nFile ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list\\nm.trainable_variables)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize\\nfunc, initial_params, jac=True, method=method, **scipy_kwargs\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize\\ncallback=callback, **options)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb\\nf, g = func_and_grad(x)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad\\nf = fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper\\nreturn function(*(wrapper_args + args))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__\\nfg = self.fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval\\nloss, grad = _tf_eval(tf.convert_to_tensor(x))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize\\n*args, **kwds))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper\\nraise e.ag_error_metadata.to_exception(e)\\nValueError: in converted code:\\n\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval *\\nloss, grads = _compute_loss_and_gradients(closure, variables)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients *\\nloss = loss_closure()\\n/path/to/1_model_sim/model.py:354 None *\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood *\\nlog_prob = multivariate_normal(Y, m, L)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal *\\nd = x - mu\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper\\nx = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"")\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor\\nret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function\\nreturn constant_op.constant(value, dtype, name=name)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant\\nallow_broadcast=True)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl\\nallow_broadcast=allow_broadcast))\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto\\n""Cannot create a tensor proto whose content is larger than 2GB."")\\n\\nValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'other', 'piece_content': 'm = gpf.models.GPR(data=(X, Y),\\nkernel=gpf.kernels.Exponential(active_dims = [0,1]),\\nmean_function=None)\\n\\nopt = gpf.optimizers.Scipy()\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\nm.trainable_variables)'}]","Traceback (most recent call last): +File ""main.py"", line 177, in +main(args) +File ""main.py"", line 64, in main +build_allele(args) +File ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele +opt_model_list(m) +File ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list +m.trainable_variables) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize +func, initial_params, jac=True, method=method, **scipy_kwargs +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize +callback=callback, **options) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb +f, g = func_and_grad(x) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad +f = fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper +return function(*(wrapper_args + args)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__ +fg = self.fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval +loss, grad = _tf_eval(tf.convert_to_tensor(x)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__ +result = self._call(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize +*args, **kwds)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper +raise e.ag_error_metadata.to_exception(e) +ValueError: in converted code: + +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval * +loss, grads = _compute_loss_and_gradients(closure, variables) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients * +loss = loss_closure() +/path/to/1_model_sim/model.py:354 None * +opt.minimize(lambda: - m.log_marginal_likelihood(), +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood * +log_prob = multivariate_normal(Y, m, L) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal * +d = x - mu +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper +x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"") +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor +ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function +return constant_op.constant(value, dtype, name=name) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant +allow_broadcast=True) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl +allow_broadcast=allow_broadcast)) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto +""Cannot create a tensor proto whose content is larger than 2GB."") + +ValueError: Cannot create a tensor proto whose content is larger than 2GB.",ValueError +" def __init__( + self, + data: RegressionData, + kernel: Kernel, + likelihood: Likelihood, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + inducing_variable: Optional[InducingPoints] = None, + ): + """""" + data is a tuple of X, Y with X, a data matrix, size [N, D] and Y, a data matrix, size [N, R] + Z is a data matrix, of inducing inputs, size [M, D] + kernel, likelihood, mean_function are appropriate GPflow objects + """""" + if num_latent_gps is None: + num_latent_gps = self.calc_num_latent_gps_from_data(data, kernel, likelihood) + super().__init__(kernel, likelihood, mean_function, num_latent_gps=num_latent_gps) + self.data = data_input_to_tensor(data) + self.num_data = data[0].shape[0] + self.inducing_variable = inducingpoint_wrapper(inducing_variable) + self.V = Parameter(np.zeros((len(self.inducing_variable), self.num_latent_gps))) + self.V.prior = tfp.distributions.Normal( + loc=to_default_float(0.0), scale=to_default_float(1.0) + )"," def __init__( + self, + data: RegressionData, + kernel: Kernel, + likelihood: Likelihood, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + inducing_variable: Optional[InducingPoints] = None, + ): + """""" + data is a tuple of X, Y with X, a data matrix, size [N, D] and Y, a data matrix, size [N, R] + Z is a data matrix, of inducing inputs, size [M, D] + kernel, likelihood, mean_function are appropriate GPflow objects + """""" + if num_latent_gps is None: + num_latent_gps = self.calc_num_latent_gps_from_data(data, kernel, likelihood) + super().__init__(kernel, likelihood, mean_function, num_latent_gps=num_latent_gps) + self.data = data + self.num_data = data[0].shape[0] + self.inducing_variable = inducingpoint_wrapper(inducing_variable) + self.V = Parameter(np.zeros((len(self.inducing_variable), self.num_latent_gps))) + self.V.prior = tfp.distributions.Normal( + loc=to_default_float(0.0), scale=to_default_float(1.0) + )","[{'piece_type': 'other', 'piece_content': 'ValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 177, in \\nmain(args)\\nFile ""main.py"", line 64, in main\\nbuild_allele(args)\\nFile ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele\\nopt_model_list(m)\\nFile ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list\\nm.trainable_variables)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize\\nfunc, initial_params, jac=True, method=method, **scipy_kwargs\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize\\ncallback=callback, **options)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb\\nf, g = func_and_grad(x)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad\\nf = fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper\\nreturn function(*(wrapper_args + args))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__\\nfg = self.fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval\\nloss, grad = _tf_eval(tf.convert_to_tensor(x))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize\\n*args, **kwds))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper\\nraise e.ag_error_metadata.to_exception(e)\\nValueError: in converted code:\\n\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval *\\nloss, grads = _compute_loss_and_gradients(closure, variables)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients *\\nloss = loss_closure()\\n/path/to/1_model_sim/model.py:354 None *\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood *\\nlog_prob = multivariate_normal(Y, m, L)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal *\\nd = x - mu\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper\\nx = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"")\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor\\nret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function\\nreturn constant_op.constant(value, dtype, name=name)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant\\nallow_broadcast=True)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl\\nallow_broadcast=allow_broadcast))\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto\\n""Cannot create a tensor proto whose content is larger than 2GB."")\\n\\nValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'other', 'piece_content': 'm = gpf.models.GPR(data=(X, Y),\\nkernel=gpf.kernels.Exponential(active_dims = [0,1]),\\nmean_function=None)\\n\\nopt = gpf.optimizers.Scipy()\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\nm.trainable_variables)'}]","Traceback (most recent call last): +File ""main.py"", line 177, in +main(args) +File ""main.py"", line 64, in main +build_allele(args) +File ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele +opt_model_list(m) +File ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list +m.trainable_variables) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize +func, initial_params, jac=True, method=method, **scipy_kwargs +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize +callback=callback, **options) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb +f, g = func_and_grad(x) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad +f = fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper +return function(*(wrapper_args + args)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__ +fg = self.fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval +loss, grad = _tf_eval(tf.convert_to_tensor(x)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__ +result = self._call(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize +*args, **kwds)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper +raise e.ag_error_metadata.to_exception(e) +ValueError: in converted code: + +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval * +loss, grads = _compute_loss_and_gradients(closure, variables) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients * +loss = loss_closure() +/path/to/1_model_sim/model.py:354 None * +opt.minimize(lambda: - m.log_marginal_likelihood(), +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood * +log_prob = multivariate_normal(Y, m, L) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal * +d = x - mu +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper +x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"") +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor +ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function +return constant_op.constant(value, dtype, name=name) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant +allow_broadcast=True) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl +allow_broadcast=allow_broadcast)) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto +""Cannot create a tensor proto whose content is larger than 2GB."") + +ValueError: Cannot create a tensor proto whose content is larger than 2GB.",ValueError +" def __init__( + self, + data: RegressionData, + kernel: Kernel, + inducing_variable: InducingPoints, + *, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + noise_variance: float = 1.0, + ): + """""" + `data`: a tuple of (X, Y), where the inputs X has shape [N, D] + and the outputs Y has shape [N, R]. + `inducing_variable`: an InducingPoints instance or a matrix of + the pseudo inputs Z, of shape [M, D]. + `kernel`, `mean_function` are appropriate GPflow objects + + This method only works with a Gaussian likelihood, its variance is + initialized to `noise_variance`. + """""" + likelihood = likelihoods.Gaussian(noise_variance) + X_data, Y_data = data_input_to_tensor(data) + num_latent_gps = Y_data.shape[-1] if num_latent_gps is None else num_latent_gps + super().__init__(kernel, likelihood, mean_function, num_latent_gps=num_latent_gps) + + self.data = X_data, Y_data + self.num_data = X_data.shape[0] + + self.inducing_variable = inducingpoint_wrapper(inducing_variable)"," def __init__( + self, + data: RegressionData, + kernel: Kernel, + inducing_variable: InducingPoints, + *, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + noise_variance: float = 1.0, + ): + """""" + `data`: a tuple of (X, Y), where the inputs X has shape [N, D] + and the outputs Y has shape [N, R]. + `inducing_variable`: an InducingPoints instance or a matrix of + the pseudo inputs Z, of shape [M, D]. + `kernel`, `mean_function` are appropriate GPflow objects + + This method only works with a Gaussian likelihood, its variance is + initialized to `noise_variance`. + """""" + likelihood = likelihoods.Gaussian(noise_variance) + X_data, Y_data = data + num_latent_gps = Y_data.shape[-1] if num_latent_gps is None else num_latent_gps + super().__init__(kernel, likelihood, mean_function, num_latent_gps=num_latent_gps) + + self.data = data + self.num_data = X_data.shape[0] + + self.inducing_variable = inducingpoint_wrapper(inducing_variable)","[{'piece_type': 'other', 'piece_content': 'ValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 177, in \\nmain(args)\\nFile ""main.py"", line 64, in main\\nbuild_allele(args)\\nFile ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele\\nopt_model_list(m)\\nFile ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list\\nm.trainable_variables)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize\\nfunc, initial_params, jac=True, method=method, **scipy_kwargs\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize\\ncallback=callback, **options)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb\\nf, g = func_and_grad(x)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad\\nf = fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper\\nreturn function(*(wrapper_args + args))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__\\nfg = self.fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval\\nloss, grad = _tf_eval(tf.convert_to_tensor(x))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize\\n*args, **kwds))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper\\nraise e.ag_error_metadata.to_exception(e)\\nValueError: in converted code:\\n\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval *\\nloss, grads = _compute_loss_and_gradients(closure, variables)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients *\\nloss = loss_closure()\\n/path/to/1_model_sim/model.py:354 None *\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood *\\nlog_prob = multivariate_normal(Y, m, L)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal *\\nd = x - mu\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper\\nx = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"")\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor\\nret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function\\nreturn constant_op.constant(value, dtype, name=name)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant\\nallow_broadcast=True)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl\\nallow_broadcast=allow_broadcast))\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto\\n""Cannot create a tensor proto whose content is larger than 2GB."")\\n\\nValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'other', 'piece_content': 'm = gpf.models.GPR(data=(X, Y),\\nkernel=gpf.kernels.Exponential(active_dims = [0,1]),\\nmean_function=None)\\n\\nopt = gpf.optimizers.Scipy()\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\nm.trainable_variables)'}]","Traceback (most recent call last): +File ""main.py"", line 177, in +main(args) +File ""main.py"", line 64, in main +build_allele(args) +File ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele +opt_model_list(m) +File ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list +m.trainable_variables) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize +func, initial_params, jac=True, method=method, **scipy_kwargs +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize +callback=callback, **options) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb +f, g = func_and_grad(x) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad +f = fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper +return function(*(wrapper_args + args)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__ +fg = self.fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval +loss, grad = _tf_eval(tf.convert_to_tensor(x)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__ +result = self._call(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize +*args, **kwds)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper +raise e.ag_error_metadata.to_exception(e) +ValueError: in converted code: + +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval * +loss, grads = _compute_loss_and_gradients(closure, variables) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients * +loss = loss_closure() +/path/to/1_model_sim/model.py:354 None * +opt.minimize(lambda: - m.log_marginal_likelihood(), +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood * +log_prob = multivariate_normal(Y, m, L) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal * +d = x - mu +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper +x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"") +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor +ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function +return constant_op.constant(value, dtype, name=name) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant +allow_broadcast=True) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl +allow_broadcast=allow_broadcast)) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto +""Cannot create a tensor proto whose content is larger than 2GB."") + +ValueError: Cannot create a tensor proto whose content is larger than 2GB.",ValueError +" def __init__( + self, + data: RegressionData, + kernel: Kernel, + likelihood: Likelihood, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + ): + """""" + data = (X, Y) contains the input points [N, D] and the observations [N, P] + kernel, likelihood, mean_function are appropriate GPflow objects + """""" + if num_latent_gps is None: + num_latent_gps = self.calc_num_latent_gps_from_data(data, kernel, likelihood) + super().__init__(kernel, likelihood, mean_function, num_latent_gps) + + self.data = data_input_to_tensor(data) + X_data, Y_data = self.data + num_data = X_data.shape[0] + self.num_data = num_data + + self.q_mu = Parameter(np.zeros((num_data, self.num_latent_gps))) + q_sqrt = np.array([np.eye(num_data) for _ in range(self.num_latent_gps)]) + self.q_sqrt = Parameter(q_sqrt, transform=triangular())"," def __init__( + self, + data: RegressionData, + kernel: Kernel, + likelihood: Likelihood, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + ): + """""" + data = (X, Y) contains the input points [N, D] and the observations [N, P] + kernel, likelihood, mean_function are appropriate GPflow objects + """""" + if num_latent_gps is None: + num_latent_gps = self.calc_num_latent_gps_from_data(data, kernel, likelihood) + super().__init__(kernel, likelihood, mean_function, num_latent_gps) + + X_data, Y_data = data + num_data = X_data.shape[0] + self.num_data = num_data + self.data = data + + self.q_mu = Parameter(np.zeros((num_data, self.num_latent_gps))) + q_sqrt = np.array([np.eye(num_data) for _ in range(self.num_latent_gps)]) + self.q_sqrt = Parameter(q_sqrt, transform=triangular())","[{'piece_type': 'other', 'piece_content': 'ValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 177, in \\nmain(args)\\nFile ""main.py"", line 64, in main\\nbuild_allele(args)\\nFile ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele\\nopt_model_list(m)\\nFile ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list\\nm.trainable_variables)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize\\nfunc, initial_params, jac=True, method=method, **scipy_kwargs\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize\\ncallback=callback, **options)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb\\nf, g = func_and_grad(x)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad\\nf = fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper\\nreturn function(*(wrapper_args + args))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__\\nfg = self.fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval\\nloss, grad = _tf_eval(tf.convert_to_tensor(x))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize\\n*args, **kwds))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper\\nraise e.ag_error_metadata.to_exception(e)\\nValueError: in converted code:\\n\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval *\\nloss, grads = _compute_loss_and_gradients(closure, variables)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients *\\nloss = loss_closure()\\n/path/to/1_model_sim/model.py:354 None *\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood *\\nlog_prob = multivariate_normal(Y, m, L)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal *\\nd = x - mu\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper\\nx = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"")\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor\\nret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function\\nreturn constant_op.constant(value, dtype, name=name)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant\\nallow_broadcast=True)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl\\nallow_broadcast=allow_broadcast))\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto\\n""Cannot create a tensor proto whose content is larger than 2GB."")\\n\\nValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'other', 'piece_content': 'm = gpf.models.GPR(data=(X, Y),\\nkernel=gpf.kernels.Exponential(active_dims = [0,1]),\\nmean_function=None)\\n\\nopt = gpf.optimizers.Scipy()\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\nm.trainable_variables)'}]","Traceback (most recent call last): +File ""main.py"", line 177, in +main(args) +File ""main.py"", line 64, in main +build_allele(args) +File ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele +opt_model_list(m) +File ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list +m.trainable_variables) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize +func, initial_params, jac=True, method=method, **scipy_kwargs +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize +callback=callback, **options) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb +f, g = func_and_grad(x) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad +f = fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper +return function(*(wrapper_args + args)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__ +fg = self.fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval +loss, grad = _tf_eval(tf.convert_to_tensor(x)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__ +result = self._call(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize +*args, **kwds)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper +raise e.ag_error_metadata.to_exception(e) +ValueError: in converted code: + +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval * +loss, grads = _compute_loss_and_gradients(closure, variables) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients * +loss = loss_closure() +/path/to/1_model_sim/model.py:354 None * +opt.minimize(lambda: - m.log_marginal_likelihood(), +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood * +log_prob = multivariate_normal(Y, m, L) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal * +d = x - mu +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper +x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"") +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor +ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function +return constant_op.constant(value, dtype, name=name) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant +allow_broadcast=True) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl +allow_broadcast=allow_broadcast)) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto +""Cannot create a tensor proto whose content is larger than 2GB."") + +ValueError: Cannot create a tensor proto whose content is larger than 2GB.",ValueError +" def __init__( + self, + data: RegressionData, + kernel: Kernel, + likelihood: Likelihood, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + ): + """""" + data = (X, Y) contains the input points [N, D] and the observations [N, P] + kernel, likelihood, mean_function are appropriate GPflow objects + """""" + if num_latent_gps is None: + num_latent_gps = self.calc_num_latent_gps_from_data(data, kernel, likelihood) + super().__init__(kernel, likelihood, mean_function, num_latent_gps) + + self.data = data_input_to_tensor(data) + X_data, Y_data = self.data + self.num_data = X_data.shape[0] + self.q_alpha = Parameter(np.zeros((self.num_data, self.num_latent_gps))) + self.q_lambda = Parameter( + np.ones((self.num_data, self.num_latent_gps)), transform=gpflow.utilities.positive() + )"," def __init__( + self, + data: RegressionData, + kernel: Kernel, + likelihood: Likelihood, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + ): + """""" + data = (X, Y) contains the input points [N, D] and the observations [N, P] + kernel, likelihood, mean_function are appropriate GPflow objects + """""" + if num_latent_gps is None: + num_latent_gps = self.calc_num_latent_gps_from_data(data, kernel, likelihood) + super().__init__(kernel, likelihood, mean_function, num_latent_gps) + + X_data, Y_data = data + self.data = data + self.num_data = X_data.shape[0] + self.q_alpha = Parameter(np.zeros((self.num_data, self.num_latent_gps))) + self.q_lambda = Parameter( + np.ones((self.num_data, self.num_latent_gps)), transform=gpflow.utilities.positive() + )","[{'piece_type': 'other', 'piece_content': 'ValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 177, in \\nmain(args)\\nFile ""main.py"", line 64, in main\\nbuild_allele(args)\\nFile ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele\\nopt_model_list(m)\\nFile ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list\\nm.trainable_variables)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize\\nfunc, initial_params, jac=True, method=method, **scipy_kwargs\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize\\ncallback=callback, **options)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb\\nf, g = func_and_grad(x)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad\\nf = fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper\\nreturn function(*(wrapper_args + args))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__\\nfg = self.fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval\\nloss, grad = _tf_eval(tf.convert_to_tensor(x))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize\\n*args, **kwds))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper\\nraise e.ag_error_metadata.to_exception(e)\\nValueError: in converted code:\\n\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval *\\nloss, grads = _compute_loss_and_gradients(closure, variables)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients *\\nloss = loss_closure()\\n/path/to/1_model_sim/model.py:354 None *\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood *\\nlog_prob = multivariate_normal(Y, m, L)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal *\\nd = x - mu\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper\\nx = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"")\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor\\nret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function\\nreturn constant_op.constant(value, dtype, name=name)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant\\nallow_broadcast=True)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl\\nallow_broadcast=allow_broadcast))\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto\\n""Cannot create a tensor proto whose content is larger than 2GB."")\\n\\nValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'other', 'piece_content': 'm = gpf.models.GPR(data=(X, Y),\\nkernel=gpf.kernels.Exponential(active_dims = [0,1]),\\nmean_function=None)\\n\\nopt = gpf.optimizers.Scipy()\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\nm.trainable_variables)'}]","Traceback (most recent call last): +File ""main.py"", line 177, in +main(args) +File ""main.py"", line 64, in main +build_allele(args) +File ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele +opt_model_list(m) +File ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list +m.trainable_variables) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize +func, initial_params, jac=True, method=method, **scipy_kwargs +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize +callback=callback, **options) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb +f, g = func_and_grad(x) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad +f = fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper +return function(*(wrapper_args + args)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__ +fg = self.fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval +loss, grad = _tf_eval(tf.convert_to_tensor(x)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__ +result = self._call(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize +*args, **kwds)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper +raise e.ag_error_metadata.to_exception(e) +ValueError: in converted code: + +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval * +loss, grads = _compute_loss_and_gradients(closure, variables) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients * +loss = loss_closure() +/path/to/1_model_sim/model.py:354 None * +opt.minimize(lambda: - m.log_marginal_likelihood(), +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood * +log_prob = multivariate_normal(Y, m, L) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal * +d = x - mu +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper +x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"") +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor +ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function +return constant_op.constant(value, dtype, name=name) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant +allow_broadcast=True) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl +allow_broadcast=allow_broadcast)) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto +""Cannot create a tensor proto whose content is larger than 2GB."") + +ValueError: Cannot create a tensor proto whose content is larger than 2GB.",ValueError +" def __init__( + self, + data: RegressionData, + kernel: Kernel, + likelihood: Likelihood, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + ): + """""" + data is a tuple of X, Y with X, a data matrix, size [N, D] and Y, a data matrix, size [N, R] + kernel, likelihood, mean_function are appropriate GPflow objects + + This is a vanilla implementation of a GP with a non-Gaussian + likelihood. The latent function values are represented by centered + (whitened) variables, so + + v ~ N(0, I) + f = Lv + m(x) + + with + + L L^T = K + + """""" + if num_latent_gps is None: + num_latent_gps = self.calc_num_latent_gps_from_data(data, kernel, likelihood) + super().__init__(kernel, likelihood, mean_function, num_latent_gps) + self.data = data_input_to_tensor(data) + self.num_data = self.data[0].shape[0] + self.V = Parameter(np.zeros((self.num_data, self.num_latent_gps))) + self.V.prior = tfp.distributions.Normal( + loc=to_default_float(0.0), scale=to_default_float(1.0) + )"," def __init__( + self, + data: RegressionData, + kernel: Kernel, + likelihood: Likelihood, + mean_function: Optional[MeanFunction] = None, + num_latent_gps: Optional[int] = None, + ): + """""" + data is a tuple of X, Y with X, a data matrix, size [N, D] and Y, a data matrix, size [N, R] + kernel, likelihood, mean_function are appropriate GPflow objects + + This is a vanilla implementation of a GP with a non-Gaussian + likelihood. The latent function values are represented by centered + (whitened) variables, so + + v ~ N(0, I) + f = Lv + m(x) + + with + + L L^T = K + + """""" + if num_latent_gps is None: + num_latent_gps = self.calc_num_latent_gps_from_data(data, kernel, likelihood) + super().__init__(kernel, likelihood, mean_function, num_latent_gps) + self.data = data + self.num_data = data[0].shape[0] + self.V = Parameter(np.zeros((self.num_data, self.num_latent_gps))) + self.V.prior = tfp.distributions.Normal( + loc=to_default_float(0.0), scale=to_default_float(1.0) + )","[{'piece_type': 'other', 'piece_content': 'ValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 177, in \\nmain(args)\\nFile ""main.py"", line 64, in main\\nbuild_allele(args)\\nFile ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele\\nopt_model_list(m)\\nFile ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list\\nm.trainable_variables)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize\\nfunc, initial_params, jac=True, method=method, **scipy_kwargs\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize\\ncallback=callback, **options)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb\\nf, g = func_and_grad(x)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad\\nf = fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper\\nreturn function(*(wrapper_args + args))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__\\nfg = self.fun(x, *args)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval\\nloss, grad = _tf_eval(tf.convert_to_tensor(x))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__\\nresult = self._call(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call\\nself._initialize(args, kwds, add_initializers_to=initializers)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize\\n*args, **kwds))\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected\\ngraph_function, _, _ = self._maybe_define_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function\\ngraph_function = self._create_graph_function(args, kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function\\ncapture_by_value=self._capture_by_value),\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func\\nfunc_outputs = python_func(*func_args, **func_kwargs)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn\\nreturn weak_wrapped_fn().__wrapped__(*args, **kwds)\\nFile ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper\\nraise e.ag_error_metadata.to_exception(e)\\nValueError: in converted code:\\n\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval *\\nloss, grads = _compute_loss_and_gradients(closure, variables)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients *\\nloss = loss_closure()\\n/path/to/1_model_sim/model.py:354 None *\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood *\\nlog_prob = multivariate_normal(Y, m, L)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal *\\nd = x - mu\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper\\nx = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"")\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor\\nret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function\\nreturn constant_op.constant(value, dtype, name=name)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant\\nallow_broadcast=True)\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl\\nallow_broadcast=allow_broadcast))\\n/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto\\n""Cannot create a tensor proto whose content is larger than 2GB."")\\n\\nValueError: Cannot create a tensor proto whose content is larger than 2GB.'}, {'piece_type': 'other', 'piece_content': 'm = gpf.models.GPR(data=(X, Y),\\nkernel=gpf.kernels.Exponential(active_dims = [0,1]),\\nmean_function=None)\\n\\nopt = gpf.optimizers.Scipy()\\nopt.minimize(lambda: - m.log_marginal_likelihood(),\\nm.trainable_variables)'}]","Traceback (most recent call last): +File ""main.py"", line 177, in +main(args) +File ""main.py"", line 64, in main +build_allele(args) +File ""/path/to/1_model_sim/drivers.py"", line 226, in build_allele +opt_model_list(m) +File ""/path/to/1_model_sim/model.py"", line 355, in opt_model_list +m.trainable_variables) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 73, in minimize +func, initial_params, jac=True, method=method, **scipy_kwargs +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/_minimize.py"", line 610, in minimize +callback=callback, **options) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 345, in _minimize_lbfgsb +f, g = func_and_grad(x) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/lbfgsb.py"", line 295, in func_and_grad +f = fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 327, in function_wrapper +return function(*(wrapper_args + args)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/scipy/optimize/optimize.py"", line 65, in __call__ +fg = self.fun(x, *args) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py"", line 95, in _eval +loss, grad = _tf_eval(tf.convert_to_tensor(x)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 568, in __call__ +result = self._call(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 615, in _call +self._initialize(args, kwds, add_initializers_to=initializers) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 497, in _initialize +*args, **kwds)) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2389, in _get_concrete_function_internal_garbage_collected +graph_function, _, _ = self._maybe_define_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2703, in _maybe_define_function +graph_function = self._create_graph_function(args, kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py"", line 2593, in _create_graph_function +capture_by_value=self._capture_by_value), +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 978, in func_graph_from_py_func +func_outputs = python_func(*func_args, **func_kwargs) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py"", line 439, in wrapped_fn +return weak_wrapped_fn().__wrapped__(*args, **kwds) +File ""/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/func_graph.py"", line 968, in wrapper +raise e.ag_error_metadata.to_exception(e) +ValueError: in converted code: + +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:88 _tf_eval * +loss, grads = _compute_loss_and_gradients(closure, variables) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/optimizers/scipy.py:145 _compute_loss_and_gradients * +loss = loss_closure() +/path/to/1_model_sim/model.py:354 None * +opt.minimize(lambda: - m.log_marginal_likelihood(), +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/models/gpr.py:75 log_marginal_likelihood * +log_prob = multivariate_normal(Y, m, L) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/gpflow/logdensities.py:95 multivariate_normal * +d = x - mu +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/ops/math_ops.py:927 r_binary_op_wrapper +x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name=""x"") +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py:1314 convert_to_tensor +ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_conversion_registry.py:52 _default_conversion_function +return constant_op.constant(value, dtype, name=name) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:258 constant +allow_broadcast=True) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/constant_op.py:296 _constant_impl +allow_broadcast=allow_broadcast)) +/path/to/1_model_sim/venv/lib/python3.6/site-packages/tensorflow_core/python/framework/tensor_util.py:522 make_tensor_proto +""Cannot create a tensor proto whose content is larger than 2GB."") + +ValueError: Cannot create a tensor proto whose content is larger than 2GB.",ValueError +" def K(self, X: tf.Tensor, X2: Optional[tf.Tensor] = None) -> tf.Tensor: + sig_X = self._sigmoids(X) # N1 x 1 x Ncp + sig_X2 = self._sigmoids(X2) if X2 is not None else sig_X # N2 x 1 x Ncp + + # `starters` are the sigmoids going from 0 -> 1, whilst `stoppers` go + # from 1 -> 0, dimensions are N1 x N2 x Ncp + starters = sig_X * tf.transpose(sig_X2, perm=(1, 0, 2)) + stoppers = (1 - sig_X) * tf.transpose((1 - sig_X2), perm=(1, 0, 2)) + + # prepend `starters` with ones and append ones to `stoppers` since the + # first kernel has no start and the last kernel has no end + N1 = tf.shape(X)[0] + N2 = tf.shape(X2)[0] if X2 is not None else N1 + ones = tf.ones((N1, N2, 1), dtype=X.dtype) + starters = tf.concat([ones, starters], axis=2) + stoppers = tf.concat([stoppers, ones], axis=2) + + # now combine with the underlying kernels + kernel_stack = tf.stack([k(X, X2) for k in self.kernels], axis=2) + return tf.reduce_sum(kernel_stack * starters * stoppers, axis=2)"," def K(self, X: tf.Tensor, X2: Optional[tf.Tensor] = None) -> tf.Tensor: + sig_X = self._sigmoids(X) # N x 1 x Ncp + sig_X2 = self._sigmoids(X2) if X2 is not None else sig_X + + # `starters` are the sigmoids going from 0 -> 1, whilst `stoppers` go + # from 1 -> 0, dimensions are N x N x Ncp + starters = sig_X * tf.transpose(sig_X2, perm=(1, 0, 2)) + stoppers = (1 - sig_X) * tf.transpose((1 - sig_X2), perm=(1, 0, 2)) + + # prepend `starters` with ones and append ones to `stoppers` since the + # first kernel has no start and the last kernel has no end + N = tf.shape(X)[0] + ones = tf.ones((N, N, 1), dtype=X.dtype) + starters = tf.concat([ones, starters], axis=2) + stoppers = tf.concat([stoppers, ones], axis=2) + + # now combine with the underlying kernels + kernel_stack = tf.stack([k(X, X2) for k in self.kernels], axis=2) + return tf.reduce_sum(kernel_stack * starters * stoppers, axis=2)","[{'piece_type': 'reproducing source code', 'piece_content': 'import numpy as np\\nimport gpflow\\nX = np.linspace(0,100,100).reshape(100,1)\\nbase_k1 = gpflow.kernels.Matern32(lengthscales=0.2)\\nbase_k2 = gpflow.kernels.Matern32(lengthscales=2.0)\\nk = gpflow.kernels.ChangePoints([base_k1, base_k2], [0.0], steepness=5.0)\\nk(X) # works\\n\\nN = 25 # anything other than N=100 will reproduce the bug\\nxx = np.linspace(0,50,N).reshape(N,1)\\nk(X, xx) # breaks'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nInvalidArgumentError Traceback (most recent call last)\\n in \\n----> 1 k(X, xx)\\n\\n~/Code/GPflow/gpflow/kernels/base.py in __call__(self, X, X2, full_cov, presliced)\\n170\\n171 else:\\n--> 172 return self.K(X, X2)\\n173\\n174 def __add__(self, other):\\n\\n~/Code/GPflow/gpflow/kernels/changepoints.py in K(self, X, X2)\\n83 N = tf.shape(X)[0]\\n84 ones = tf.ones((N, N, 1), dtype=X.dtype)\\n---> 85 starters = tf.concat([ones, starters], axis=2)\\n86 stoppers = tf.concat([stoppers, ones], axis=2)\\n87\\n\\n~/anaconda3/envs/gpflux2/lib/python3.7/site-packages/tensorflow_core/python/util/dispatch.py in wrapper(*args, **kwargs)\\n178 """"""Call target, and fall back on dispatchers if there is a TypeError.""""""\\n179 try:\\n--> 180 return target(*args, **kwargs)\\n181 except (TypeError, ValueError):\\n182 # Note: convert_to_eager_tensor currently raises a ValueError, not a\\n\\n~/anaconda3/envs/gpflux2/lib/python3.7/site-packages/tensorflow_core/python/ops/array_ops.py in concat(values, axis, name)\\n1515 dtype=dtypes.int32).get_shape().assert_has_rank(0)\\n1516 return identity(values[0], name=name)\\n-> 1517 return gen_array_ops.concat_v2(values=values, axis=axis, name=name)\\n1518\\n1519\\n\\n~/anaconda3/envs/gpflux2/lib/python3.7/site-packages/tensorflow_core/python/ops/gen_array_ops.py in concat_v2(values, axis, name)\\n1116 pass # Add nodes to the TensorFlow graph.\\n1117 except _core._NotOkStatusException as e:\\n-> 1118 _ops.raise_from_not_ok_status(e, name)\\n1119 # Add nodes to the TensorFlow graph.\\n1120 if not isinstance(values, (list, tuple)):\\n\\n~/anaconda3/envs/gpflux2/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py in raise_from_not_ok_status(e, name)\\n6604 message = e.message + ("" name: "" + name if name is not None else """")\\n6605 # pylint: disable=protected-access\\n-> 6606 six.raise_from(core._status_to_exception(e.code, message), None)\\n6607 # pylint: enable=protected-access\\n6608\\n\\n~/anaconda3/envs/gpflux2/lib/python3.7/site-packages/six.py in raise_from(value, from_value)\\n\\nInvalidArgumentError: ConcatOp : Dimensions of inputs should match: shape[0] = [100,100,1] vs. shape[1] = [100,25,1] [Op:ConcatV2] name: concat'}, {'piece_type': 'source code', 'piece_content': 'def K(self, X: tf.Tensor, X2: Optional[tf.Tensor] = None) -> tf.Tensor:\\nsig_X = self._sigmoids(X) # N x 1 x Ncp\\nsig_X2 = self._sigmoids(X2) if X2 is not None else sig_X\\n\\n# `starters` are the sigmoids going from 0 -> 1, whilst `stoppers` go\\n# from 1 -> 0, dimensions are N x N x Ncp\\nstarters = sig_X * tf.transpose(sig_X2, perm=(1, 0, 2))\\nstoppers = (1 - sig_X) * tf.transpose((1 - sig_X2), perm=(1, 0, 2))\\n\\n# prepend `starters` with ones and append ones to `stoppers` since the\\n# first kernel has no start and the last kernel has no end\\nN = tf.shape(X)[0]\\nM = tf.shape(X2)[0] if X2 is not None else N # THIS IS THE FIX\\nones = tf.ones((N, M, 1), dtype=X.dtype) #PREVIOUSLY N WAS IN PLACE OF M HERE\\nstarters = tf.concat([ones, starters], axis=2)\\nstoppers = tf.concat([stoppers, ones], axis=2)'}]","--------------------------------------------------------------------------- +InvalidArgumentError Traceback (most recent call last) + in +----> 1 k(X, xx) + +~/Code/GPflow/gpflow/kernels/base.py in __call__(self, X, X2, full_cov, presliced) +170 +171 else: +--> 172 return self.K(X, X2) +173 +174 def __add__(self, other): + +~/Code/GPflow/gpflow/kernels/changepoints.py in K(self, X, X2) +83 N = tf.shape(X)[0] +84 ones = tf.ones((N, N, 1), dtype=X.dtype) +---> 85 starters = tf.concat([ones, starters], axis=2) +86 stoppers = tf.concat([stoppers, ones], axis=2) +87 + +~/anaconda3/envs/gpflux2/lib/python3.7/site-packages/tensorflow_core/python/util/dispatch.py in wrapper(*args, **kwargs) +178 """"""Call target, and fall back on dispatchers if there is a TypeError."""""" +179 try: +--> 180 return target(*args, **kwargs) +181 except (TypeError, ValueError): +182 # Note: convert_to_eager_tensor currently raises a ValueError, not a + +~/anaconda3/envs/gpflux2/lib/python3.7/site-packages/tensorflow_core/python/ops/array_ops.py in concat(values, axis, name) +1515 dtype=dtypes.int32).get_shape().assert_has_rank(0) +1516 return identity(values[0], name=name) +-> 1517 return gen_array_ops.concat_v2(values=values, axis=axis, name=name) +1518 +1519 + +~/anaconda3/envs/gpflux2/lib/python3.7/site-packages/tensorflow_core/python/ops/gen_array_ops.py in concat_v2(values, axis, name) +1116 pass # Add nodes to the TensorFlow graph. +1117 except _core._NotOkStatusException as e: +-> 1118 _ops.raise_from_not_ok_status(e, name) +1119 # Add nodes to the TensorFlow graph. +1120 if not isinstance(values, (list, tuple)): + +~/anaconda3/envs/gpflux2/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py in raise_from_not_ok_status(e, name) +6604 message = e.message + ("" name: "" + name if name is not None else """") +6605 # pylint: disable=protected-access +-> 6606 six.raise_from(core._status_to_exception(e.code, message), None) +6607 # pylint: enable=protected-access +6608 + +~/anaconda3/envs/gpflux2/lib/python3.7/site-packages/six.py in raise_from(value, from_value) + +InvalidArgumentError: ConcatOp : Dimensions of inputs should match: shape[0] = [100,100,1] vs. shape[1] = [100,25,1] [Op:ConcatV2] name: concat",InvalidArgumentError +"def autoflow(*af_args, **af_kwargs): + def autoflow_wrapper(method): + @functools.wraps(method) + def runnable(obj, *args, **kwargs): + if not isinstance(obj, Node): + raise GPflowError( + 'AutoFlow works only with node-like objects.') + if obj.is_built_coherence(obj.graph) is Build.NO: + raise GPflowError('Not built with ""{graph}"".'.format(graph=obj.graph)) + name = method.__name__ + store = AutoFlow.get_autoflow(obj, name) + session = kwargs.pop('session', None) + session = obj.enquire_session(session=session) + + scope_name = _name_scope_name(obj, name) + with session.graph.as_default(), tf.name_scope(scope_name): + if not store: + _setup_storage(store, *af_args, **af_kwargs) + _build_method(method, obj, store) + return _session_run(session, obj, store, *args, **kwargs) + return runnable + return autoflow_wrapper","def autoflow(*af_args, **af_kwargs): + def autoflow_wrapper(method): + @functools.wraps(method) + def runnable(obj, *args, **kwargs): + if not isinstance(obj, Node): + raise GPflowError( + 'AutoFlow works only with node-like objects.') + if obj.is_built_coherence(obj.graph) is Build.NO: + raise GPflowError('Not built with ""{graph}"".'.format(graph=obj.graph)) + name = method.__name__ + store = AutoFlow.get_autoflow(obj, name) + session = kwargs.pop('session', None) + session = obj.enquire_session(session=session) + if not store: + scope_name = _name_scope_name(obj, name) + with session.graph.as_default(), tf.name_scope(scope_name): + _setup_storage(store, *af_args, **af_kwargs) + _build_method(method, obj, store) + return _session_run(session, obj, store, *args, **kwargs) + return runnable + return autoflow_wrapper","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def autoflow_wrapper(method): + @functools.wraps(method) + def runnable(obj, *args, **kwargs): + if not isinstance(obj, Node): + raise GPflowError( + 'AutoFlow works only with node-like objects.') + if obj.is_built_coherence(obj.graph) is Build.NO: + raise GPflowError('Not built with ""{graph}"".'.format(graph=obj.graph)) + name = method.__name__ + store = AutoFlow.get_autoflow(obj, name) + session = kwargs.pop('session', None) + session = obj.enquire_session(session=session) + + scope_name = _name_scope_name(obj, name) + with session.graph.as_default(), tf.name_scope(scope_name): + if not store: + _setup_storage(store, *af_args, **af_kwargs) + _build_method(method, obj, store) + return _session_run(session, obj, store, *args, **kwargs) + return runnable"," def autoflow_wrapper(method): + @functools.wraps(method) + def runnable(obj, *args, **kwargs): + if not isinstance(obj, Node): + raise GPflowError( + 'AutoFlow works only with node-like objects.') + if obj.is_built_coherence(obj.graph) is Build.NO: + raise GPflowError('Not built with ""{graph}"".'.format(graph=obj.graph)) + name = method.__name__ + store = AutoFlow.get_autoflow(obj, name) + session = kwargs.pop('session', None) + session = obj.enquire_session(session=session) + if not store: + scope_name = _name_scope_name(obj, name) + with session.graph.as_default(), tf.name_scope(scope_name): + _setup_storage(store, *af_args, **af_kwargs) + _build_method(method, obj, store) + return _session_run(session, obj, store, *args, **kwargs) + return runnable","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def runnable(obj, *args, **kwargs): + if not isinstance(obj, Node): + raise GPflowError( + 'AutoFlow works only with node-like objects.') + if obj.is_built_coherence(obj.graph) is Build.NO: + raise GPflowError('Not built with ""{graph}"".'.format(graph=obj.graph)) + name = method.__name__ + store = AutoFlow.get_autoflow(obj, name) + session = kwargs.pop('session', None) + session = obj.enquire_session(session=session) + + scope_name = _name_scope_name(obj, name) + with session.graph.as_default(), tf.name_scope(scope_name): + if not store: + _setup_storage(store, *af_args, **af_kwargs) + _build_method(method, obj, store) + return _session_run(session, obj, store, *args, **kwargs)"," def runnable(obj, *args, **kwargs): + if not isinstance(obj, Node): + raise GPflowError( + 'AutoFlow works only with node-like objects.') + if obj.is_built_coherence(obj.graph) is Build.NO: + raise GPflowError('Not built with ""{graph}"".'.format(graph=obj.graph)) + name = method.__name__ + store = AutoFlow.get_autoflow(obj, name) + session = kwargs.pop('session', None) + session = obj.enquire_session(session=session) + if not store: + scope_name = _name_scope_name(obj, name) + with session.graph.as_default(), tf.name_scope(scope_name): + _setup_storage(store, *af_args, **af_kwargs) + _build_method(method, obj, store) + return _session_run(session, obj, store, *args, **kwargs)","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +"def initialize_variables(variables=None, session=None, force=False, **run_kwargs): + session = tf.get_default_session() if session is None else session + if variables is None: + initializer = tf.global_variables_initializer() + else: + if force: + vars_for_init = list(_initializable_tensors(variables)) + else: + vars_for_init = list(_find_initializable_tensors(variables, session)) + if not vars_for_init: + return + initializer = tf.variables_initializer(vars_for_init) + session.run(initializer, **run_kwargs)","def initialize_variables(variables=None, session=None, force=False, **run_kwargs): + session = tf.get_default_session() if session is None else session + if variables is None: + initializer = tf.global_variables_initializer() + else: + if force: + initializer = tf.variables_initializer(variables) + else: + uninitialized = tf.report_uninitialized_variables(var_list=variables) + def uninitialized_names(): + for uv in session.run(uninitialized): + yield uv.decode('utf-8') + # if isinstance(uv, bytes): + # yield uv.decode('utf-8') + # elif isinstance(uv, str): + # yield uv + # else: + # msg = 'Unknown output type ""{}"" from `tf.report_uninitialized_variables`' + # raise ValueError(msg.format(type(uv))) + names = set(uninitialized_names()) + vars_for_init = [v for v in variables if v.name.split(':')[0] in names] + initializer = tf.variables_initializer(vars_for_init) + session.run(initializer, **run_kwargs)","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def _clear(self): + self._reset_name() + self._initial_value_tensor = None + self._dataholder_tensor = None + self._is_initialized_tensor = None"," def _clear(self): + self._reset_name() + self._initial_value_tensor = None + self._dataholder_tensor = None","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def _build(self): + tensor = self._build_parameter() + self._dataholder_tensor = tensor + self._is_initialized_tensor = tf.is_variable_initialized(tensor)"," def _build(self): + self._dataholder_tensor = self._build_parameter() # pylint: disable=W0201","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def _init_parameter_defaults(self): + self._initial_value_tensor = None + self._dataholder_tensor = None + self._is_initialized_tensor = None"," def _init_parameter_defaults(self): + self._initial_value_tensor = None + self._dataholder_tensor = None","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def initializables(self): + if self._externally_defined: + return None + return [(self.parameter_tensor, self.is_initialized_tensor)]"," def initializables(self): + if self._externally_defined: + return None + return [self.parameter_tensor]","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def read_value(self, session=None): + if session is not None and not isinstance(session, tf.Session): + raise ValueError('TensorFlow session expected as an argument.') + if session is None and self._externally_defined: + raise GPflowError('Externally defined parameter requires session.') + elif session: + is_built = self.is_built_coherence(session.graph) + if is_built is Build.YES: + return self._read_parameter_tensor(session) + return self._value"," def read_value(self, session=None): + if session is not None: + if not isinstance(session, tf.Session): + raise ValueError('TensorFlow session expected as session argument.') + is_built = self.is_built_coherence(session.graph) + if is_built is Build.YES: + return self._read_parameter_tensor(session) + elif self._externally_defined: + raise GPflowError('Externally defined parameter requires session.') + return self._value","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def _clear(self): + self._reset_name() + self._externally_defined = False + self._is_initialized_tensor = None + self._initial_value_tensor = None + self._unconstrained_tensor = None + self._constrained_tensor = None + self._prior_tensor = None"," def _clear(self): + self._reset_name() + self._externally_defined = False # pylint: disable=W0201 + self._initial_value_tensor = None # pylint: disable=W0201 + self._unconstrained_tensor = None # pylint: disable=W0201 + self._constrained_tensor = None # pylint: disable=W0201 + self._prior_tensor = None # pylint: disable=W0201","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def _build(self): + unconstrained = self._build_parameter() + constrained = self._build_constrained(unconstrained) + prior = self._build_prior(unconstrained, constrained) + + self._is_initialized_tensor = tf.is_variable_initialized(unconstrained) + self._unconstrained_tensor = unconstrained + self._constrained_tensor = constrained + self._prior_tensor = prior"," def _build(self): + unconstrained = self._build_parameter() + constrained = self._build_constrained(unconstrained) + prior = self._build_prior(unconstrained, constrained) + self._unconstrained_tensor = unconstrained # pylint: disable=W0201 + self._constrained_tensor = constrained # pylint: disable=W0201 + self._prior_tensor = prior # pylint: disable=W0201","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def _build_parameter(self): + if self._externally_defined: + self._check_tensor_trainable(self.parameter_tensor) + return self.parameter_tensor + + name = self._parameter_name() + tensor = misc.get_variable_by_name(name) + if tensor is not None: + raise GPflowError('Tensor with name ""{name}"" already exists, {tensor}.' + .format(name=name, tensor=tensor)) + + value = self._apply_transform(self._value) + shape = value.shape if self.fixed_shape else None + init = tf.placeholder(self.dtype, shape=shape, name='initial_unconstrained_value') + self._initial_value_tensor = init + if self.fixed_shape: + args = dict(trainable=self.trainable) + else: + args = dict(validate_shape=False, trainable=self.trainable) + variable = tf.get_variable(name, initializer=init, **args) + return variable"," def _build_parameter(self): + if self._externally_defined: + self._check_tensor_trainable(self.parameter_tensor) + return self.parameter_tensor + + name = self._parameter_name() + tensor = misc.get_variable_by_name(name) + if tensor is not None: + raise GPflowError('Tensor with name ""{name}"" already exists, {tensor}.' + .format(name=name, tensor=tensor)) + + value = self._apply_transform(self._value) + shape = value.shape if self.fixed_shape else None + init = tf.placeholder(self.dtype, shape=shape, name='initial_unconstrained_value') + self._initial_value_tensor = init + if self.fixed_shape: + return tf.get_variable(name, initializer=init, trainable=self.trainable) + return tf.get_variable(name, initializer=init, + validate_shape=False, + trainable=self.trainable)","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def _init_parameter_defaults(self): + self._is_initialized_tensor = None + self._initial_value_tensor = None + self._unconstrained_tensor = None + self._prior_tensor = None + self._constrained_tensor = None"," def _init_parameter_defaults(self): + self._initial_value_tensor = None + self._unconstrained_tensor = None + self._prior_tensor = None + self._constrained_tensor = None","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def minimize(self, model, session=None, var_list=None, feed_dict=None, + maxiter=1000, initialize=False, anchor=True, **kwargs): + """""" + Minimizes objective function of the model. + + :param model: GPflow model with objective tensor. + :param session: Session where optimization will be run. + :param var_list: List of extra variables which should be trained during optimization. + :param feed_dict: Feed dictionary of tensors passed to session run method. + :param maxiter: Number of run interation. + :param initialize: If `True` model parameters will be re-initialized even if they were + initialized before for gotten session. + :param anchor: If `True` trained variable values computed during optimization at + particular session will be synchronized with internal parameter values. + :param kwargs: This is a dictionary of extra parameters for session run method. + """""" + + if model is None or not isinstance(model, Model): + raise ValueError('Unknown type passed for optimization.') + + session = model.enquire_session(session) + + self._model = model + objective = model.objective + + with session.graph.as_default(): + full_var_list = self._gen_var_list(model, var_list) + + # Create optimizer variables before initialization. + self._minimize_operation = self.optimizer.minimize( + objective, var_list=full_var_list, **kwargs) + + model.initialize(session=session, force=initialize) + self._initialize_optimizer(session, full_var_list) + + feed_dict = self._gen_feed_dict(model, feed_dict) + for _i in range(maxiter): + session.run(self.minimize_operation, feed_dict=feed_dict) + + if anchor: + model.anchor(session)"," def minimize(self, model, session=None, var_list=None, feed_dict=None, + maxiter=1000, initialize=True, anchor=True, **kwargs): + """""" + Minimizes objective function of the model. + + :param model: GPflow model with objective tensor. + :param session: Session where optimization will be run. + :param var_list: List of extra variables which should be trained during optimization. + :param feed_dict: Feed dictionary of tensors passed to session run method. + :param maxiter: Number of run interation. + :param initialize: If `True` model parameters will be re-initialized even if they were + initialized before for gotten session. + :param anchor: If `True` trained variable values computed during optimization at + particular session will be synchronized with internal parameter values. + :param kwargs: This is a dictionary of extra parameters for session run method. + """""" + + if model is None or not isinstance(model, Model): + raise ValueError('Unknown type passed for optimization.') + + session = model.enquire_session(session) + + self._model = model + objective = model.objective + + with session.graph.as_default(): + full_var_list = self._gen_var_list(model, var_list) + + # Create optimizer variables before initialization. + self._minimize_operation = self.optimizer.minimize( + objective, var_list=full_var_list, **kwargs) + + model.initialize(session=session, force=initialize) + self._initialize_optimizer(session, full_var_list) + + feed_dict = self._gen_feed_dict(model, feed_dict) + for _i in range(maxiter): + session.run(self.minimize_operation, feed_dict=feed_dict) + + if anchor: + model.anchor(session)","[{'piece_type': 'source code', 'piece_content': 'model = gpflow.models.svgp.SVGP(np.random.randn(1, 1),\\nnp.random.randn(1, 1),\\ngpflow.kernels.RBF(1),\\ngpflow.likelihoods.Gaussian(),\\nnp.random.randn(1, 1),\\nminibatch_size=1)\\nmodel.compute_log_likelihood()'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nAttributeError Traceback (most recent call last)\\n in ()\\n10 np.random.randn(M, D),\\n11 minibatch_size=2)\\n---> 12 model.compute_log_likelihood()\\n\\n/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs)\\n152 _setup_storage(store, *af_args, **af_kwargs)\\n153 _build_method(method, obj, store)\\n--> 154 return _session_run(session, obj, store, *args, **kwargs)\\n155 return runnable\\n156 return autoflow_wrapper\\n\\n/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs)\\n189 feed_dict.update(obj.feeds)\\n190 initialize = kwargs.pop(\\'initialize\\', False)\\n--> 191 obj.initialize(session=session, force=initialize)\\n192 return session.run(store[\\'result\\'], **kwargs)\\n193\\n\\n/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force)\\n82 session=session,\\n83 force=force,\\n---> 84 feed_dict=self.initializable_feeds)\\n85\\n86 def clear(self):\\n\\n/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs)\\n82 initializer = tf.variables_initializer(variables)\\n83 else:\\n---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables)\\n85 def uninitialized_names():\\n86 for uv in session.run(uninitialized):\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs)\\n105 """"""\\n106 def wrapped(*args, **kwargs):\\n--> 107 return _add_should_use_warning(fn(*args, **kwargs))\\n108 return tf_decorator.make_decorator(\\n109 fn, wrapped, \\'should_use_result\\',\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0)\\n1519 variables_mask = math_ops.logical_not(\\n1520 array_ops.stack(\\n-> 1521 [state_ops.is_variable_initialized(v) for v in var_list]))\\n1522 # Get a 1-D string tensor containing all the variable names.\\n1523 variable_names_tensor = array_ops.constant(\\n\\n/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name)\\n182 A `Tensor` of type `bool`.\\n183 """"""\\n--> 184 if ref.dtype._is_ref_dtype:\\n185 return gen_state_ops.is_variable_initialized(ref=ref, name=name)\\n186 # Handle resource variables.\\n\\nAttributeError: \\'Iterator\\' object has no attribute \\'dtype\\''}]","--------------------------------------------------------------------------- +AttributeError Traceback (most recent call last) + in () +10 np.random.randn(M, D), +11 minibatch_size=2) +---> 12 model.compute_log_likelihood() + +/[...]/GPflow/gpflow/decors.py in runnable(obj, *args, **kwargs) +152 _setup_storage(store, *af_args, **af_kwargs) +153 _build_method(method, obj, store) +--> 154 return _session_run(session, obj, store, *args, **kwargs) +155 return runnable +156 return autoflow_wrapper + +/[...]/GPflow/gpflow/decors.py in _session_run(session, obj, store, *args, **kwargs) +189 feed_dict.update(obj.feeds) +190 initialize = kwargs.pop('initialize', False) +--> 191 obj.initialize(session=session, force=initialize) +192 return session.run(store['result'], **kwargs) +193 + +/[...]/GPflow/gpflow/core/node.py in initialize(self, session, force) +82 session=session, +83 force=force, +---> 84 feed_dict=self.initializable_feeds) +85 +86 def clear(self): + +/[...]/GPflow/gpflow/misc.py in initialize_variables(variables, session, force, **run_kwargs) +82 initializer = tf.variables_initializer(variables) +83 else: +---> 84 uninitialized = tf.report_uninitialized_variables(var_list=variables) +85 def uninitialized_names(): +86 for uv in session.run(uninitialized): + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/util/tf_should_use.py in wrapped(*args, **kwargs) +105 """""" +106 def wrapped(*args, **kwargs): +--> 107 return _add_should_use_warning(fn(*args, **kwargs)) +108 return tf_decorator.make_decorator( +109 fn, wrapped, 'should_use_result', + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in report_uninitialized_variables(var_list, name) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/variables.py in (.0) +1519 variables_mask = math_ops.logical_not( +1520 array_ops.stack( +-> 1521 [state_ops.is_variable_initialized(v) for v in var_list])) +1522 # Get a 1-D string tensor containing all the variable names. +1523 variable_names_tensor = array_ops.constant( + +/[...]/anaconda3/envs/py35cpu/lib/python3.5/site-packages/tensorflow/python/ops/state_ops.py in is_variable_initialized(ref, name) +182 A `Tensor` of type `bool`. +183 """""" +--> 184 if ref.dtype._is_ref_dtype: +185 return gen_state_ops.is_variable_initialized(ref=ref, name=name) +186 # Handle resource variables. + +AttributeError: 'Iterator' object has no attribute 'dtype'",AttributeError +" def prob_is_largest(self, Y, mu, var, gh_x, gh_w): + # work out what the mean and variance is of the indicated latent function. + oh_on = tf.cast(tf.one_hot(tf.reshape(Y, (-1,)), self.num_classes, 1., 0.), tf.float64) + mu_selected = tf.reduce_sum(oh_on * mu, 1) + var_selected = tf.reduce_sum(oh_on * var, 1) + + # generate Gauss Hermite grid + X = tf.reshape(mu_selected, (-1, 1)) + gh_x * tf.reshape(tf.sqrt(tf.clip_by_value(2. * var_selected, 1e-10, np.inf)), (-1, 1)) + + # compute the CDF of the Gaussian between the latent functions and the grid (including the selected function) + dist = (tf.expand_dims(X, 1) - tf.expand_dims(mu, 2)) / tf.expand_dims(tf.sqrt(tf.clip_by_value(var, 1e-10, np.inf)), 2) + cdfs = 0.5 * (1.0 + tf.erf(dist/np.sqrt(2.0))) + + cdfs = cdfs * (1-2e-4) + 1e-4 + + # blank out all the distances on the selected latent function + oh_off = tf.cast(tf.one_hot(tf.reshape(Y, (-1,)), self.num_classes, 0., 1.), tf.float64) + cdfs = cdfs * tf.expand_dims(oh_off, 2) + tf.expand_dims(oh_on, 2) + + # take the product over the latent functions, and the sum over the GH grid. + return tf.matmul(tf.reduce_prod(cdfs, reduction_indices=[1]), tf.reshape(gh_w/np.sqrt(np.pi), (-1, 1)))"," def prob_is_largest(self, Y, mu, var, gh_x, gh_w): + # work out what the mean and variance is of the indicated latent function. + oh_on = tf.cast(tf.one_hot(tf.reshape(Y, (-1,)), self.num_classes, 1., 0.), tf.float64) + mu_selected = tf.reduce_sum(oh_on * mu, 1) + var_selected = tf.reduce_sum(oh_on * var, 1) + + # generate Gauss Hermite grid + X = tf.reshape(mu_selected, (-1, 1)) + gh_x * tf.reshape(tf.sqrt(tf.clip_by_value(2. * var_selected, 1e-10, np.inf)), (-1, 1)) + + # compute the CDF of the Gaussian between the latent functions and the grid (including the selected function) + dist = (tf.expand_dims(X, 1) - tf.expand_dims(mu, 2)) / tf.expand_dims(tf.sqrt(tf.clip_by_value(var, 1e-10, np.inf)), 2) + cdfs = 0.5 * (1.0 + tf.erf(dist/np.sqrt(2.0))) + + cdfs = cdfs * (1-2e-4) + 1e-4 + + # blank out all the distances on the selected latent function + oh_off = tf.cast(tf.one_hot(tf.reshape(Y, (-1,)), self.num_classes, 0., 1.), tf.float64) + cdfs = cdfs * tf.expand_dims(oh_off, 2) + tf.expand_dims(oh_on, 2) + + # take the product over the latent functions, and the sum over the GH grid. + return tf.matmul(tf.reduce_prod(cdfs, 1), tf.reshape(gh_w/np.sqrt(np.pi), (-1, 1)))","[{'piece_type': 'source code', 'piece_content': 'm.kern.white.variance.fixed = True\\nm.Z.fixed = True\\n_ = m.optimize()'}, {'piece_type': 'error message', 'piece_content': 'python\\n---------------------------------------------------------------------------\\nValueError Traceback (most recent call last)\\n in ()\\n1 m.kern.white.variance.fixed = True\\n2 m.Z.fixed = True\\n----> 3 _ = m.optimize()\\n\\n/Users/danmarthaler/GPflow/GPflow/model.pyc in optimize(self, method, tol, callback, maxiter, **kw)\\n207\\n208 if type(method) is str:\\n--> 209 return self._optimize_np(method, tol, callback, maxiter, **kw)\\n210 else:\\n211 return self._optimize_tf(method, callback, maxiter, **kw)\\n\\n/Users/danmarthaler/GPflow/GPflow/model.pyc in _optimize_np(self, method, tol, callback, maxiter, **kw)\\n265 """"""\\n266 if self._needs_recompile:\\n--> 267 self._compile()\\n268\\n269 options = dict(disp=True, maxiter=maxiter)\\n\\n/Users/danmarthaler/GPflow/GPflow/model.pyc in _compile(self, optimizer)\\n127 with self.tf_mode():\\n128 f = self.build_likelihood() + self.build_prior()\\n--> 129 g, = tf.gradients(f, self._free_vars)\\n130\\n131 self._minusF = tf.neg(f, name=\\'objective\\')\\n\\n/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/gradients.pyc in gradients(ys, xs, grad_ys, name, colocate_gradients_with_ops, gate_gradients, aggregation_method)\\n476 # If grad_fn was found, do not use SymbolicGradient even for\\n477 # functions.\\n--> 478 in_grads = _AsList(grad_fn(op, *out_grads))\\n479 else:\\n480 # For function call ops, we add a \\'SymbolicGradient\\'\\n\\n/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/math_grad.pyc in _ProdGrad(op, grad)\\n128 reduced = math_ops.cast(op.inputs[1], dtypes.int32)\\n129 idx = math_ops.range(0, array_ops.rank(op.inputs[0]))\\n--> 130 other, _ = array_ops.listdiff(idx, reduced)\\n131 perm = array_ops.concat(0, [reduced, other])\\n132 reduced_num = math_ops.reduce_prod(array_ops.gather(input_shape, reduced))\\n\\n/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.pyc in list_diff(x, y, name)\\n1199 idx: A `Tensor` of type `int32`. 1-D. Positions of `x` values preserved in `out`.\\n1200 """"""\\n-> 1201 result = _op_def_lib.apply_op(""ListDiff"", x=x, y=y, name=name)\\n1202 return _ListDiffOutput._make(result)\\n1203\\n\\n/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.pyc in apply_op(self, op_type_name, name, **keywords)\\n701 op = g.create_op(op_type_name, inputs, output_types, name=scope,\\n702 input_types=input_types, attrs=attr_protos,\\n--> 703 op_def=op_def)\\n704 outputs = op.outputs\\n705 return _Restructure(ops.convert_n_to_tensor(outputs),\\n\\n/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in create_op(self, op_type, inputs, dtypes, input_types, name, attrs, op_def, compute_shapes, compute_device)\\n2310 original_op=self._default_original_op, op_def=op_def)\\n2311 if compute_shapes:\\n-> 2312 set_shapes_for_outputs(ret)\\n2313 self._add_op(ret)\\n2314 self._record_op_seen_by_control_dependencies(ret)\\n\\n/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in set_shapes_for_outputs(op)\\n1702 raise RuntimeError(""No shape function registered for standard op: %s""\\n1703 % op.type)\\n-> 1704 shapes = shape_func(op)\\n1705 if shapes is None:\\n1706 raise RuntimeError(\\n\\n/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.pyc in _ListDiffShape(op)\\n1979 """"""Shape function for the ListDiff op.""""""\\n1980 op.inputs[0].get_shape().assert_has_rank(1)\\n-> 1981 op.inputs[1].get_shape().assert_has_rank(1)\\n1982 # TODO(mrry): Indicate that the length falls within an interval?\\n1983 return [tensor_shape.vector(None)] * 2\\n\\n/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/tensor_shape.pyc in assert_has_rank(self, rank)\\n619 """"""\\n620 if self.ndims not in (None, rank):\\n--> 621 raise ValueError(""Shape %s must have rank %d"" % (self, rank))\\n622\\n623 def with_rank(self, rank):\\n\\nValueError: Shape () must have rank 1'}]","python +--------------------------------------------------------------------------- +ValueError Traceback (most recent call last) + in () +1 m.kern.white.variance.fixed = True +2 m.Z.fixed = True +----> 3 _ = m.optimize() + +/Users/danmarthaler/GPflow/GPflow/model.pyc in optimize(self, method, tol, callback, maxiter, **kw) +207 +208 if type(method) is str: +--> 209 return self._optimize_np(method, tol, callback, maxiter, **kw) +210 else: +211 return self._optimize_tf(method, callback, maxiter, **kw) + +/Users/danmarthaler/GPflow/GPflow/model.pyc in _optimize_np(self, method, tol, callback, maxiter, **kw) +265 """""" +266 if self._needs_recompile: +--> 267 self._compile() +268 +269 options = dict(disp=True, maxiter=maxiter) + +/Users/danmarthaler/GPflow/GPflow/model.pyc in _compile(self, optimizer) +127 with self.tf_mode(): +128 f = self.build_likelihood() + self.build_prior() +--> 129 g, = tf.gradients(f, self._free_vars) +130 +131 self._minusF = tf.neg(f, name='objective') + +/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/gradients.pyc in gradients(ys, xs, grad_ys, name, colocate_gradients_with_ops, gate_gradients, aggregation_method) +476 # If grad_fn was found, do not use SymbolicGradient even for +477 # functions. +--> 478 in_grads = _AsList(grad_fn(op, *out_grads)) +479 else: +480 # For function call ops, we add a 'SymbolicGradient' + +/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/math_grad.pyc in _ProdGrad(op, grad) +128 reduced = math_ops.cast(op.inputs[1], dtypes.int32) +129 idx = math_ops.range(0, array_ops.rank(op.inputs[0])) +--> 130 other, _ = array_ops.listdiff(idx, reduced) +131 perm = array_ops.concat(0, [reduced, other]) +132 reduced_num = math_ops.reduce_prod(array_ops.gather(input_shape, reduced)) + +/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.pyc in list_diff(x, y, name) +1199 idx: A `Tensor` of type `int32`. 1-D. Positions of `x` values preserved in `out`. +1200 """""" +-> 1201 result = _op_def_lib.apply_op(""ListDiff"", x=x, y=y, name=name) +1202 return _ListDiffOutput._make(result) +1203 + +/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.pyc in apply_op(self, op_type_name, name, **keywords) +701 op = g.create_op(op_type_name, inputs, output_types, name=scope, +702 input_types=input_types, attrs=attr_protos, +--> 703 op_def=op_def) +704 outputs = op.outputs +705 return _Restructure(ops.convert_n_to_tensor(outputs), + +/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in create_op(self, op_type, inputs, dtypes, input_types, name, attrs, op_def, compute_shapes, compute_device) +2310 original_op=self._default_original_op, op_def=op_def) +2311 if compute_shapes: +-> 2312 set_shapes_for_outputs(ret) +2313 self._add_op(ret) +2314 self._record_op_seen_by_control_dependencies(ret) + +/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in set_shapes_for_outputs(op) +1702 raise RuntimeError(""No shape function registered for standard op: %s"" +1703 % op.type) +-> 1704 shapes = shape_func(op) +1705 if shapes is None: +1706 raise RuntimeError( + +/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/array_ops.pyc in _ListDiffShape(op) +1979 """"""Shape function for the ListDiff op."""""" +1980 op.inputs[0].get_shape().assert_has_rank(1) +-> 1981 op.inputs[1].get_shape().assert_has_rank(1) +1982 # TODO(mrry): Indicate that the length falls within an interval? +1983 return [tensor_shape.vector(None)] * 2 + +/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/tensor_shape.pyc in assert_has_rank(self, rank) +619 """""" +620 if self.ndims not in (None, rank): +--> 621 raise ValueError(""Shape %s must have rank %d"" % (self, rank)) +622 +623 def with_rank(self, rank): + +ValueError: Shape () must have rank 1",ValueError +" def __call__(self, tf_method): + @wraps(tf_method) + def runnable(instance, *np_args): + graph_name = '_' + tf_method.__name__ + '_graph' + if not hasattr(instance, graph_name): + if instance._needs_recompile: + instance._compile() # ensures free_vars is up-to-date. + self.tf_args = [tf.placeholder(*a) for a in self.tf_arg_tuples] + with instance.tf_mode(): + graph = tf_method(instance, *self.tf_args) + setattr(instance, graph_name, graph) + feed_dict = dict(zip(self.tf_args, np_args)) + feed_dict[instance._free_vars] = instance.get_free_state() + graph = getattr(instance, graph_name) + return instance._session.run(graph, feed_dict=feed_dict) + return runnable"," def __call__(self, tf_method): + @wraps(tf_method) + def runnable(instance, *np_args): + graph_name = '_' + tf_method.__name__ + '_graph' + if not hasattr(instance, graph_name): + instance._compile() + self.tf_args = [tf.placeholder(*a) for a in self.tf_arg_tuples] + with instance.tf_mode(): + graph = tf_method(instance, *self.tf_args) + setattr(instance, graph_name, graph) + feed_dict = dict(zip(self.tf_args, np_args)) + feed_dict[instance._free_vars] = instance.get_free_state() + graph = getattr(instance, graph_name) + return instance._session.run(graph, feed_dict=feed_dict) + return runnable","[{'piece_type': 'other', 'piece_content': 'import GPflow\\nimport tensorflow as tf\\nimport os\\nimport numpy as np\\ndef getData():\\nrng = np.random.RandomState( 1 )\\nN = 30\\nX = rng.rand(N,1)\\nY = np.sin(12*X) + 0.66*np.cos(25*X) + rng.randn(N,1)*0.1 + 3\\nreturn X,Y\\nif __name__ == \\'__main__\\':\\nX,Y = getData()\\nk = GPflow.kernels.Matern52(1)\\nmeanf = GPflow.mean_functions.Linear(1,0)\\nm = GPflow.gpr.GPR(X, Y, k, meanf)\\nm.likelihood.variance = 0.01\\nm._compile()\\nprint ""Here are the parameters before optimization""\\nprint m\\nm.kern.variance.fixed = True\\n#m._compile() # If we compile again the code below works\\n[mu,var] = m.predict_f(X)\\nprint mu\\nprint \\'done\\''}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/Users/mqbssaby/PrivateProjects/BranchedGP/runfile.py"", line 29, in \\n[mu,var] = m.predict_f(X)\\nFile ""/Users/mqbssaby/pythonlibs/GPflow/GPflow/model.py"", line 82, in runnable\\nreturn instance._session.run(graph, feed_dict=feed_dict)\\nFile ""/Users/mqbssaby/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py"", line 340, in run\\nrun_metadata_ptr)\\nFile ""/Users/mqbssaby/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py"", line 553, in _run\\n% (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))\\nValueError: Cannot feed value of shape (4,) for Tensor u\\'Variable:0\\', which has shape \\'(5,)\\''}]","Traceback (most recent call last): +File ""/Users/mqbssaby/PrivateProjects/BranchedGP/runfile.py"", line 29, in +[mu,var] = m.predict_f(X) +File ""/Users/mqbssaby/pythonlibs/GPflow/GPflow/model.py"", line 82, in runnable +return instance._session.run(graph, feed_dict=feed_dict) +File ""/Users/mqbssaby/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py"", line 340, in run +run_metadata_ptr) +File ""/Users/mqbssaby/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py"", line 553, in _run +% (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape()))) +ValueError: Cannot feed value of shape (4,) for Tensor u'Variable:0', which has shape '(5,)'",ValueError +" def runnable(instance, *np_args): + graph_name = '_' + tf_method.__name__ + '_graph' + if not hasattr(instance, graph_name): + if instance._needs_recompile: + instance._compile() # ensures free_vars is up-to-date. + self.tf_args = [tf.placeholder(*a) for a in self.tf_arg_tuples] + with instance.tf_mode(): + graph = tf_method(instance, *self.tf_args) + setattr(instance, graph_name, graph) + feed_dict = dict(zip(self.tf_args, np_args)) + feed_dict[instance._free_vars] = instance.get_free_state() + graph = getattr(instance, graph_name) + return instance._session.run(graph, feed_dict=feed_dict)"," def runnable(instance, *np_args): + graph_name = '_' + tf_method.__name__ + '_graph' + if not hasattr(instance, graph_name): + instance._compile() + self.tf_args = [tf.placeholder(*a) for a in self.tf_arg_tuples] + with instance.tf_mode(): + graph = tf_method(instance, *self.tf_args) + setattr(instance, graph_name, graph) + feed_dict = dict(zip(self.tf_args, np_args)) + feed_dict[instance._free_vars] = instance.get_free_state() + graph = getattr(instance, graph_name) + return instance._session.run(graph, feed_dict=feed_dict)","[{'piece_type': 'other', 'piece_content': 'import GPflow\\nimport tensorflow as tf\\nimport os\\nimport numpy as np\\ndef getData():\\nrng = np.random.RandomState( 1 )\\nN = 30\\nX = rng.rand(N,1)\\nY = np.sin(12*X) + 0.66*np.cos(25*X) + rng.randn(N,1)*0.1 + 3\\nreturn X,Y\\nif __name__ == \\'__main__\\':\\nX,Y = getData()\\nk = GPflow.kernels.Matern52(1)\\nmeanf = GPflow.mean_functions.Linear(1,0)\\nm = GPflow.gpr.GPR(X, Y, k, meanf)\\nm.likelihood.variance = 0.01\\nm._compile()\\nprint ""Here are the parameters before optimization""\\nprint m\\nm.kern.variance.fixed = True\\n#m._compile() # If we compile again the code below works\\n[mu,var] = m.predict_f(X)\\nprint mu\\nprint \\'done\\''}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/Users/mqbssaby/PrivateProjects/BranchedGP/runfile.py"", line 29, in \\n[mu,var] = m.predict_f(X)\\nFile ""/Users/mqbssaby/pythonlibs/GPflow/GPflow/model.py"", line 82, in runnable\\nreturn instance._session.run(graph, feed_dict=feed_dict)\\nFile ""/Users/mqbssaby/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py"", line 340, in run\\nrun_metadata_ptr)\\nFile ""/Users/mqbssaby/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py"", line 553, in _run\\n% (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))\\nValueError: Cannot feed value of shape (4,) for Tensor u\\'Variable:0\\', which has shape \\'(5,)\\''}]","Traceback (most recent call last): +File ""/Users/mqbssaby/PrivateProjects/BranchedGP/runfile.py"", line 29, in +[mu,var] = m.predict_f(X) +File ""/Users/mqbssaby/pythonlibs/GPflow/GPflow/model.py"", line 82, in runnable +return instance._session.run(graph, feed_dict=feed_dict) +File ""/Users/mqbssaby/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py"", line 340, in run +run_metadata_ptr) +File ""/Users/mqbssaby/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.py"", line 553, in _run +% (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape()))) +ValueError: Cannot feed value of shape (4,) for Tensor u'Variable:0', which has shape '(5,)'",ValueError +" def browse(self, uri): + logger.debug(""Browsing files at: %s"", uri) + result = [] + local_path = path.uri_to_path(uri) + + if str(local_path) == ""root"": + return list(self._get_media_dirs_refs()) + + if not self._is_in_basedir(local_path): + logger.warning( + ""Rejected attempt to browse path (%s) outside dirs defined "" + ""in file/media_dirs config."", + uri, + ) + return [] + if path.uri_to_path(uri).is_file(): + logger.error(""Rejected attempt to browse file (%s)"", uri) + return [] + + for dir_entry in local_path.iterdir(): + child_path = dir_entry.resolve() + uri = path.path_to_uri(child_path) + + if not self._show_dotfiles and dir_entry.name.startswith("".""): + continue + + if ( + self._excluded_file_extensions + and dir_entry.suffix in self._excluded_file_extensions + ): + continue + + if child_path.is_symlink() and not self._follow_symlinks: + logger.debug(""Ignoring symlink: %s"", uri) + continue + + if not self._is_in_basedir(child_path): + logger.debug(""Ignoring symlink to outside base dir: %s"", uri) + continue + + if child_path.is_dir(): + result.append( + models.Ref.directory(name=dir_entry.name, uri=uri) + ) + elif child_path.is_file(): + result.append(models.Ref.track(name=dir_entry.name, uri=uri)) + + def order(item): + return (item.type != models.Ref.DIRECTORY, item.name) + + result.sort(key=order) + + return result"," def browse(self, uri): + logger.debug(""Browsing files at: %s"", uri) + result = [] + local_path = path.uri_to_path(uri) + + if str(local_path) == ""root"": + return list(self._get_media_dirs_refs()) + + if not self._is_in_basedir(local_path): + logger.warning( + ""Rejected attempt to browse path (%s) outside dirs defined "" + ""in file/media_dirs config."", + uri, + ) + return [] + + for dir_entry in local_path.iterdir(): + child_path = dir_entry.resolve() + uri = path.path_to_uri(child_path) + + if not self._show_dotfiles and dir_entry.name.startswith("".""): + continue + + if ( + self._excluded_file_extensions + and dir_entry.suffix in self._excluded_file_extensions + ): + continue + + if child_path.is_symlink() and not self._follow_symlinks: + logger.debug(""Ignoring symlink: %s"", uri) + continue + + if not self._is_in_basedir(child_path): + logger.debug(""Ignoring symlink to outside base dir: %s"", uri) + continue + + if child_path.is_dir(): + result.append( + models.Ref.directory(name=dir_entry.name, uri=uri) + ) + elif child_path.is_file(): + result.append(models.Ref.track(name=dir_entry.name, uri=uri)) + + def order(item): + return (item.type != models.Ref.DIRECTORY, item.name) + + result.sort(key=order) + + return result","[{'piece_type': 'error message', 'piece_content': 'FileBackend-2 DEBUG 2020-05-07 14:06:45,889 Browsing files at: file:///home/nick/Music/Tall%20Ships%20-%20Chemistry.mp3\\nCore-7 ERROR 2020-05-07 14:06:45,889 FileBackend backend caused an exception.\\nTraceback (most recent call last):\\nFile ""/home/nick/Dev/mopidy-dev/mopidy/mopidy/core/library.py"", line 17, in _backend_error_handling\\nyield\\nFile ""/home/nick/Dev/mopidy-dev/mopidy/mopidy/core/library.py"", line 114, in _browse\\nresult = backend.library.browse(uri).get()\\nFile ""/usr/lib/python3/dist-packages/pykka/_threading.py"", line 45, in get\\n_compat.reraise(*self._data[\\'exc_info\\'])\\nFile ""/usr/lib/python3/dist-packages/pykka/_compat/__init__.py"", line 29, in reraise\\nraise value\\nFile ""/usr/lib/python3/dist-packages/pykka/_actor.py"", line 193, in _actor_loop\\nresponse = self._handle_receive(envelope.message)\\nFile ""/usr/lib/python3/dist-packages/pykka/_actor.py"", line 299, in _handle_receive\\nreturn callee(*message.args, **message.kwargs)\\nFile ""/home/nick/Dev/mopidy-dev/mopidy/mopidy/file/library.py"", line 55, in browse\\nfor dir_entry in local_path.iterdir():\\nFile ""/usr/lib/python3.8/pathlib.py"", line 1113, in iterdir\\nfor name in self._accessor.listdir(self):\\nNotADirectoryError: [Errno 20] Not a directory: \\'/home/nick/Music/Tall Ships - Chemistry.mp3\\''}]","FileBackend-2 DEBUG 2020-05-07 14:06:45,889 Browsing files at: file:///home/nick/Music/Tall%20Ships%20-%20Chemistry.mp3 +Core-7 ERROR 2020-05-07 14:06:45,889 FileBackend backend caused an exception. +Traceback (most recent call last): +File ""/home/nick/Dev/mopidy-dev/mopidy/mopidy/core/library.py"", line 17, in _backend_error_handling +yield +File ""/home/nick/Dev/mopidy-dev/mopidy/mopidy/core/library.py"", line 114, in _browse +result = backend.library.browse(uri).get() +File ""/usr/lib/python3/dist-packages/pykka/_threading.py"", line 45, in get +_compat.reraise(*self._data['exc_info']) +File ""/usr/lib/python3/dist-packages/pykka/_compat/__init__.py"", line 29, in reraise +raise value +File ""/usr/lib/python3/dist-packages/pykka/_actor.py"", line 193, in _actor_loop +response = self._handle_receive(envelope.message) +File ""/usr/lib/python3/dist-packages/pykka/_actor.py"", line 299, in _handle_receive +return callee(*message.args, **message.kwargs) +File ""/home/nick/Dev/mopidy-dev/mopidy/mopidy/file/library.py"", line 55, in browse +for dir_entry in local_path.iterdir(): +File ""/usr/lib/python3.8/pathlib.py"", line 1113, in iterdir +for name in self._accessor.listdir(self): +NotADirectoryError: [Errno 20] Not a directory: '/home/nick/Music/Tall Ships - Chemistry.mp3'",NotADirectoryError +" def on_error(self, error, debug): + gst_logger.error(f""GStreamer error: {error.message}"") + gst_logger.debug( + f""Got ERROR bus message: error={error!r} debug={debug!r}"" + ) + + # TODO: is this needed? + self._audio.stop_playback()"," def on_error(self, error, debug): + error_msg = str(error).decode() + debug_msg = debug.decode() + gst_logger.debug( + ""Got ERROR bus message: error=%r debug=%r"", error_msg, debug_msg + ) + gst_logger.error(""GStreamer error: %s"", error_msg) + # TODO: is this needed? + self._audio.stop_playback()","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 219, in on_message\\nself.on_error(error, debug)\\nFile ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 328, in on_error\\nerror_msg = str(error).decode()\\nAttributeError: \\'str\\' object has no attribute \\'decode\\''}]","Traceback (most recent call last): +File ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 219, in on_message +self.on_error(error, debug) +File ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 328, in on_error +error_msg = str(error).decode() +AttributeError: 'str' object has no attribute 'decode'",AttributeError +" def on_warning(self, error, debug): + gst_logger.warning(f""GStreamer warning: {error.message}"") + gst_logger.debug( + f""Got WARNING bus message: error={error!r} debug={debug!r}"" + )"," def on_warning(self, error, debug): + error_msg = str(error).decode() + debug_msg = debug.decode() + gst_logger.warning(""GStreamer warning: %s"", error_msg) + gst_logger.debug( + ""Got WARNING bus message: error=%r debug=%r"", error_msg, debug_msg + )","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 219, in on_message\\nself.on_error(error, debug)\\nFile ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 328, in on_error\\nerror_msg = str(error).decode()\\nAttributeError: \\'str\\' object has no attribute \\'decode\\''}]","Traceback (most recent call last): +File ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 219, in on_message +self.on_error(error, debug) +File ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 328, in on_error +error_msg = str(error).decode() +AttributeError: 'str' object has no attribute 'decode'",AttributeError +"def _unwrap_stream(uri, timeout, scanner, requests_session): + """""" + Get a stream URI from a playlist URI, ``uri``. + + Unwraps nested playlists until something that's not a playlist is found or + the ``timeout`` is reached. + """""" + + original_uri = uri + seen_uris = set() + deadline = time.time() + timeout + + while time.time() < deadline: + if uri in seen_uris: + logger.info( + 'Unwrapping stream from URI (%s) failed: ' + 'playlist referenced itself', uri) + return None, None + else: + seen_uris.add(uri) + + logger.debug('Unwrapping stream from URI: %s', uri) + + try: + scan_timeout = deadline - time.time() + if scan_timeout < 0: + logger.info( + 'Unwrapping stream from URI (%s) failed: ' + 'timed out in %sms', uri, timeout) + return None, None + scan_result = scanner.scan(uri, timeout=scan_timeout) + except exceptions.ScannerError as exc: + logger.debug('GStreamer failed scanning URI (%s): %s', uri, exc) + scan_result = None + + if scan_result is not None: + has_interesting_mime = ( + scan_result.mime is not None and + not scan_result.mime.startswith('text/') and + not scan_result.mime.startswith('application/') + ) + if scan_result.playable or has_interesting_mime: + logger.debug( + 'Unwrapped potential %s stream: %s', scan_result.mime, uri) + return uri, scan_result + + download_timeout = deadline - time.time() + if download_timeout < 0: + logger.info( + 'Unwrapping stream from URI (%s) failed: timed out in %sms', + uri, timeout) + return None, None + content = http.download( + requests_session, uri, timeout=download_timeout / 1000) + + if content is None: + logger.info( + 'Unwrapping stream from URI (%s) failed: ' + 'error downloading URI %s', original_uri, uri) + return None, None + + uris = playlists.parse(content) + if not uris: + logger.debug( + 'Failed parsing URI (%s) as playlist; found potential stream.', + uri) + return uri, None + + # TODO Test streams and return first that seems to be playable + logger.debug( + 'Parsed playlist (%s) and found new URI: %s', uri, uris[0]) + uri = urllib.parse.urljoin(uri, uris[0])","def _unwrap_stream(uri, timeout, scanner, requests_session): + """""" + Get a stream URI from a playlist URI, ``uri``. + + Unwraps nested playlists until something that's not a playlist is found or + the ``timeout`` is reached. + """""" + + original_uri = uri + seen_uris = set() + deadline = time.time() + timeout + + while time.time() < deadline: + if uri in seen_uris: + logger.info( + 'Unwrapping stream from URI (%s) failed: ' + 'playlist referenced itself', uri) + return None, None + else: + seen_uris.add(uri) + + logger.debug('Unwrapping stream from URI: %s', uri) + + try: + scan_timeout = deadline - time.time() + if scan_timeout < 0: + logger.info( + 'Unwrapping stream from URI (%s) failed: ' + 'timed out in %sms', uri, timeout) + return None, None + scan_result = scanner.scan(uri, timeout=scan_timeout) + except exceptions.ScannerError as exc: + logger.debug('GStreamer failed scanning URI (%s): %s', uri, exc) + scan_result = None + + if scan_result is not None: + if scan_result.playable or ( + not scan_result.mime.startswith('text/') and + not scan_result.mime.startswith('application/') + ): + logger.debug( + 'Unwrapped potential %s stream: %s', scan_result.mime, uri) + return uri, scan_result + + download_timeout = deadline - time.time() + if download_timeout < 0: + logger.info( + 'Unwrapping stream from URI (%s) failed: timed out in %sms', + uri, timeout) + return None, None + content = http.download( + requests_session, uri, timeout=download_timeout / 1000) + + if content is None: + logger.info( + 'Unwrapping stream from URI (%s) failed: ' + 'error downloading URI %s', original_uri, uri) + return None, None + + uris = playlists.parse(content) + if not uris: + logger.debug( + 'Failed parsing URI (%s) as playlist; found potential stream.', + uri) + return uri, None + + # TODO Test streams and return first that seems to be playable + logger.debug( + 'Parsed playlist (%s) and found new URI: %s', uri, uris[0]) + uri = urllib.parse.urljoin(uri, uris[0])","[{'piece_type': 'error message', 'piece_content': 'ERROR StreamBackend backend caused an exception.\\nTraceback (most recent call last):\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/core/library.py"", line 19, in _backend_error_handling\\nyield\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/core/library.py"", line 237, in lookup\\nresult = future.get()\\nFile ""/usr/lib64/python2.7/site-packages/pykka/threading.py"", line 52, in get\\ncompat.reraise(*self._data[\\'exc_info\\'])\\nFile ""/usr/lib64/python2.7/site-packages/pykka/compat.py"", line 12, in reraise\\nexec(\\'raise tp, value, tb\\')\\nFile ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 295, in _handle_receive\\nreturn callee(*message[\\'args\\'], **message[\\'kwargs\\'])\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/stream/actor.py"", line 65, in lookup\\nrequests_session=self.backend._session)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/stream/actor.py"", line 131, in _unwrap_stream\\nnot scan_result.mime.startswith(\\'text/\\') and\\nAttributeError: \\'NoneType\\' object has no attribute \\'startswith\\''}]","ERROR StreamBackend backend caused an exception. +Traceback (most recent call last): +File ""/usr/lib64/python2.7/site-packages/mopidy/core/library.py"", line 19, in _backend_error_handling +yield +File ""/usr/lib64/python2.7/site-packages/mopidy/core/library.py"", line 237, in lookup +result = future.get() +File ""/usr/lib64/python2.7/site-packages/pykka/threading.py"", line 52, in get +compat.reraise(*self._data['exc_info']) +File ""/usr/lib64/python2.7/site-packages/pykka/compat.py"", line 12, in reraise +exec('raise tp, value, tb') +File ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop +response = self._handle_receive(message) +File ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 295, in _handle_receive +return callee(*message['args'], **message['kwargs']) +File ""/usr/lib64/python2.7/site-packages/mopidy/stream/actor.py"", line 65, in lookup +requests_session=self.backend._session) +File ""/usr/lib64/python2.7/site-packages/mopidy/stream/actor.py"", line 131, in _unwrap_stream +not scan_result.mime.startswith('text/') and +AttributeError: 'NoneType' object has no attribute 'startswith'",AttributeError +"def listplaylist(context, name): + """""" + *musicpd.org, stored playlists section:* + + ``listplaylist {NAME}`` + + Lists the files in the playlist ``NAME.m3u``. + + Output format:: + + file: relative/path/to/file1.flac + file: relative/path/to/file2.ogg + file: relative/path/to/file3.mp3 + """""" + playlist = _get_playlist(context, name) + return [translator.uri_to_mpd_format(t.uri) for t in playlist.tracks]","def listplaylist(context, name): + """""" + *musicpd.org, stored playlists section:* + + ``listplaylist {NAME}`` + + Lists the files in the playlist ``NAME.m3u``. + + Output format:: + + file: relative/path/to/file1.flac + file: relative/path/to/file2.ogg + file: relative/path/to/file3.mp3 + """""" + playlist = _get_playlist(context, name) + return ['file: %s' % t.uri for t in playlist.tracks]","[{'piece_type': 'error message', 'piece_content': 'ERROR Unhandled exception in MpdSession (urn:uuid:76575e20-c10f-46e2-bc60-404ed1cffc27):\\nTraceback (most recent call last):\\nFile ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 304, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/internal/network.py"", line 423, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/session.py"", line 34, in on_line_received\\nresponse = self.dispatcher.handle_request(line)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 47, in handle_request\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 77, in _catch_mpd_ack_errors_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 87, in _authenticate_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 106, in _command_list_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 135, in _idle_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 148, in _add_ok_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 160, in _call_handler_filter\\nresponse = self._format_response(self._call_handler(request))\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 184, in _format_response\\nformatted_response.extend(self._format_lines(element))\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 210, in _format_lines\\nreturn [\\'%s: %s\\' % (key, value)]\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 38: ordinal not in range(128)'}]","ERROR Unhandled exception in MpdSession (urn:uuid:76575e20-c10f-46e2-bc60-404ed1cffc27): +Traceback (most recent call last): +File ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop +response = self._handle_receive(message) +File ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 304, in _handle_receive +return self.on_receive(message) +File ""/usr/lib64/python2.7/site-packages/mopidy/internal/network.py"", line 423, in on_receive +self.on_line_received(line) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/session.py"", line 34, in on_line_received +response = self.dispatcher.handle_request(line) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 47, in handle_request +return self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 77, in _catch_mpd_ack_errors_filter +return self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 87, in _authenticate_filter +return self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 106, in _command_list_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 135, in _idle_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 148, in _add_ok_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 160, in _call_handler_filter +response = self._format_response(self._call_handler(request)) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 184, in _format_response +formatted_response.extend(self._format_lines(element)) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 210, in _format_lines +return ['%s: %s' % (key, value)] +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 38: ordinal not in range(128)",UnicodeDecodeError +"def track_to_mpd_format(track, position=None, stream_title=None): + """""" + Format track for output to MPD client. + + :param track: the track + :type track: :class:`mopidy.models.Track` or :class:`mopidy.models.TlTrack` + :param position: track's position in playlist + :type position: integer + :param stream_title: the current streams title + :type position: string + :rtype: list of two-tuples + """""" + if isinstance(track, TlTrack): + (tlid, track) = track + else: + (tlid, track) = (None, track) + + if not track.uri: + logger.warning('Ignoring track without uri') + return [] + + result = [ + uri_to_mpd_format(track.uri), + ('Time', track.length and (track.length // 1000) or 0), + ('Artist', concat_multi_values(track.artists, 'name')), + ('Album', track.album and track.album.name or ''), + ] + + if stream_title is not None: + result.append(('Title', stream_title)) + if track.name: + result.append(('Name', track.name)) + else: + result.append(('Title', track.name or '')) + + if track.date: + result.append(('Date', track.date)) + + if track.album is not None and track.album.num_tracks is not None: + result.append(('Track', '%d/%d' % ( + track.track_no or 0, track.album.num_tracks))) + else: + result.append(('Track', track.track_no or 0)) + if position is not None and tlid is not None: + result.append(('Pos', position)) + result.append(('Id', tlid)) + if track.album is not None and track.album.musicbrainz_id is not None: + result.append(('MUSICBRAINZ_ALBUMID', track.album.musicbrainz_id)) + + if track.album is not None and track.album.artists: + result.append( + ('AlbumArtist', concat_multi_values(track.album.artists, 'name'))) + musicbrainz_ids = concat_multi_values( + track.album.artists, 'musicbrainz_id') + if musicbrainz_ids: + result.append(('MUSICBRAINZ_ALBUMARTISTID', musicbrainz_ids)) + + if track.artists: + musicbrainz_ids = concat_multi_values(track.artists, 'musicbrainz_id') + if musicbrainz_ids: + result.append(('MUSICBRAINZ_ARTISTID', musicbrainz_ids)) + + if track.composers: + result.append( + ('Composer', concat_multi_values(track.composers, 'name'))) + + if track.performers: + result.append( + ('Performer', concat_multi_values(track.performers, 'name'))) + + if track.genre: + result.append(('Genre', track.genre)) + + if track.disc_no: + result.append(('Disc', track.disc_no)) + + if track.last_modified: + datestring = datetime.datetime.utcfromtimestamp( + track.last_modified // 1000).isoformat() + result.append(('Last-Modified', datestring + 'Z')) + + if track.musicbrainz_id is not None: + result.append(('MUSICBRAINZ_TRACKID', track.musicbrainz_id)) + + if track.album and track.album.uri: + result.append(('X-AlbumUri', track.album.uri)) + if track.album and track.album.images: + images = ';'.join(i for i in track.album.images if i != '') + result.append(('X-AlbumImage', images)) + + result = [element for element in result if _has_value(*element)] + + return result","def track_to_mpd_format(track, position=None, stream_title=None): + """""" + Format track for output to MPD client. + + :param track: the track + :type track: :class:`mopidy.models.Track` or :class:`mopidy.models.TlTrack` + :param position: track's position in playlist + :type position: integer + :param stream_title: the current streams title + :type position: string + :rtype: list of two-tuples + """""" + if isinstance(track, TlTrack): + (tlid, track) = track + else: + (tlid, track) = (None, track) + + if not track.uri: + logger.warning('Ignoring track without uri') + return [] + + result = [ + ('file', track.uri), + ('Time', track.length and (track.length // 1000) or 0), + ('Artist', concat_multi_values(track.artists, 'name')), + ('Album', track.album and track.album.name or ''), + ] + + if stream_title is not None: + result.append(('Title', stream_title)) + if track.name: + result.append(('Name', track.name)) + else: + result.append(('Title', track.name or '')) + + if track.date: + result.append(('Date', track.date)) + + if track.album is not None and track.album.num_tracks is not None: + result.append(('Track', '%d/%d' % ( + track.track_no or 0, track.album.num_tracks))) + else: + result.append(('Track', track.track_no or 0)) + if position is not None and tlid is not None: + result.append(('Pos', position)) + result.append(('Id', tlid)) + if track.album is not None and track.album.musicbrainz_id is not None: + result.append(('MUSICBRAINZ_ALBUMID', track.album.musicbrainz_id)) + + if track.album is not None and track.album.artists: + result.append( + ('AlbumArtist', concat_multi_values(track.album.artists, 'name'))) + musicbrainz_ids = concat_multi_values( + track.album.artists, 'musicbrainz_id') + if musicbrainz_ids: + result.append(('MUSICBRAINZ_ALBUMARTISTID', musicbrainz_ids)) + + if track.artists: + musicbrainz_ids = concat_multi_values(track.artists, 'musicbrainz_id') + if musicbrainz_ids: + result.append(('MUSICBRAINZ_ARTISTID', musicbrainz_ids)) + + if track.composers: + result.append( + ('Composer', concat_multi_values(track.composers, 'name'))) + + if track.performers: + result.append( + ('Performer', concat_multi_values(track.performers, 'name'))) + + if track.genre: + result.append(('Genre', track.genre)) + + if track.disc_no: + result.append(('Disc', track.disc_no)) + + if track.last_modified: + datestring = datetime.datetime.utcfromtimestamp( + track.last_modified // 1000).isoformat() + result.append(('Last-Modified', datestring + 'Z')) + + if track.musicbrainz_id is not None: + result.append(('MUSICBRAINZ_TRACKID', track.musicbrainz_id)) + + if track.album and track.album.uri: + result.append(('X-AlbumUri', track.album.uri)) + if track.album and track.album.images: + images = ';'.join(i for i in track.album.images if i != '') + result.append(('X-AlbumImage', images)) + + result = [element for element in result if _has_value(*element)] + + return result","[{'piece_type': 'error message', 'piece_content': 'ERROR Unhandled exception in MpdSession (urn:uuid:76575e20-c10f-46e2-bc60-404ed1cffc27):\\nTraceback (most recent call last):\\nFile ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 304, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/internal/network.py"", line 423, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/session.py"", line 34, in on_line_received\\nresponse = self.dispatcher.handle_request(line)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 47, in handle_request\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 77, in _catch_mpd_ack_errors_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 87, in _authenticate_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 106, in _command_list_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 135, in _idle_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 148, in _add_ok_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 160, in _call_handler_filter\\nresponse = self._format_response(self._call_handler(request))\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 184, in _format_response\\nformatted_response.extend(self._format_lines(element))\\nFile ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 210, in _format_lines\\nreturn [\\'%s: %s\\' % (key, value)]\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 38: ordinal not in range(128)'}]","ERROR Unhandled exception in MpdSession (urn:uuid:76575e20-c10f-46e2-bc60-404ed1cffc27): +Traceback (most recent call last): +File ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop +response = self._handle_receive(message) +File ""/usr/lib64/python2.7/site-packages/pykka/actor.py"", line 304, in _handle_receive +return self.on_receive(message) +File ""/usr/lib64/python2.7/site-packages/mopidy/internal/network.py"", line 423, in on_receive +self.on_line_received(line) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/session.py"", line 34, in on_line_received +response = self.dispatcher.handle_request(line) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 47, in handle_request +return self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 77, in _catch_mpd_ack_errors_filter +return self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 87, in _authenticate_filter +return self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 106, in _command_list_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 135, in _idle_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 148, in _add_ok_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 69, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 160, in _call_handler_filter +response = self._format_response(self._call_handler(request)) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 184, in _format_response +formatted_response.extend(self._format_lines(element)) +File ""/usr/lib64/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 210, in _format_lines +return ['%s: %s' % (key, value)] +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 38: ordinal not in range(128)",UnicodeDecodeError +"def _get_user_dirs(xdg_config_dir): + """"""Returns a dict of XDG dirs read from + ``$XDG_CONFIG_HOME/user-dirs.dirs``. + + This is used at import time for most users of :mod:`mopidy`. By rolling our + own implementation instead of using :meth:`glib.get_user_special_dir` we + make it possible for many extensions to run their test suites, which are + importing parts of :mod:`mopidy`, in a virtualenv with global site-packages + disabled, and thus no :mod:`glib` available. + """""" + + dirs_file = os.path.join(xdg_config_dir, b'user-dirs.dirs') + + if not os.path.exists(dirs_file): + return {} + + with open(dirs_file, 'rb') as fh: + data = fh.read() + + data = b'[XDG_USER_DIRS]\\n' + data + data = data.replace(b'$HOME', os.path.expanduser(b'~')) + data = data.replace(b'""', b'') + + config = configparser.RawConfigParser() + config.readfp(io.BytesIO(data)) + + return { + k.upper().decode('utf-8'): os.path.abspath(v) + for k, v in config.items('XDG_USER_DIRS') if v is not None + }","def _get_user_dirs(xdg_config_dir): + """"""Returns a dict of XDG dirs read from + ``$XDG_CONFIG_HOME/user-dirs.dirs``. + + This is used at import time for most users of :mod:`mopidy`. By rolling our + own implementation instead of using :meth:`glib.get_user_special_dir` we + make it possible for many extensions to run their test suites, which are + importing parts of :mod:`mopidy`, in a virtualenv with global site-packages + disabled, and thus no :mod:`glib` available. + """""" + + dirs_file = os.path.join(xdg_config_dir, b'user-dirs.dirs') + + if not os.path.exists(dirs_file): + return {} + + with open(dirs_file, 'rb') as fh: + data = fh.read().decode('utf-8') + + data = '[XDG_USER_DIRS]\\n' + data + data = data.replace('$HOME', os.path.expanduser('~')) + data = data.replace('""', '') + + config = configparser.RawConfigParser() + config.readfp(io.StringIO(data)) + + return { + k.upper(): os.path.abspath(v) + for k, v in config.items('XDG_USER_DIRS') if v is not None}","[{'piece_type': 'error message', 'piece_content': 'ERROR FileBackend backend caused an exception.\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/core/library.py"", line 19, in _backend_error_handling\\nyield\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/core/library.py"", line 112, in _browse\\nresult = backend.library.browse(uri).get()\\nFile ""/usr/lib/python2.7/dist-packages/pykka/threading.py"", line 52, in get\\ncompat.reraise(*self._data[\\'exc_info\\'])\\nFile ""/usr/lib/python2.7/dist-packages/pykka/compat.py"", line 12, in reraise\\nexec(\\'raise tp, value, tb\\')\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 201, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 295, in _handle_receive\\nreturn callee(*message[\\'args\\'], **message[\\'kwargs\\'])\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/file/library.py"", line 53, in browse\\nif not self._is_in_basedir(os.path.realpath(local_path)):\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/file/library.py"", line 146, in _is_in_basedir\\nfor media_dir in self._media_dirs)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/file/library.py"", line 146, in \\nfor media_dir in self._media_dirs)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/internal/path.py"", line\\n210, in is_path_inside_base_dir\\nraise ValueError(\\'base_path is not a bytestring\\')\\nValueError: base_path is not a bytestring'}]","ERROR FileBackend backend caused an exception. +Traceback (most recent call last): +File ""/usr/lib/python2.7/dist-packages/mopidy/core/library.py"", line 19, in _backend_error_handling +yield +File ""/usr/lib/python2.7/dist-packages/mopidy/core/library.py"", line 112, in _browse +result = backend.library.browse(uri).get() +File ""/usr/lib/python2.7/dist-packages/pykka/threading.py"", line 52, in get +compat.reraise(*self._data['exc_info']) +File ""/usr/lib/python2.7/dist-packages/pykka/compat.py"", line 12, in reraise +exec('raise tp, value, tb') +File ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 201, in _actor_loop +response = self._handle_receive(message) +File ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 295, in _handle_receive +return callee(*message['args'], **message['kwargs']) +File ""/usr/lib/python2.7/dist-packages/mopidy/file/library.py"", line 53, in browse +if not self._is_in_basedir(os.path.realpath(local_path)): +File ""/usr/lib/python2.7/dist-packages/mopidy/file/library.py"", line 146, in _is_in_basedir +for media_dir in self._media_dirs) +File ""/usr/lib/python2.7/dist-packages/mopidy/file/library.py"", line 146, in +for media_dir in self._media_dirs) +File ""/usr/lib/python2.7/dist-packages/mopidy/internal/path.py"", line +210, in is_path_inside_base_dir +raise ValueError('base_path is not a bytestring') +ValueError: base_path is not a bytestring",ValueError +" def validate(self, value): + value = super(Identifier, self).validate(value) + if isinstance(value, compat.text_type): + value = value.encode('utf-8') + return compat.intern(value)"," def validate(self, value): + return compat.intern(str(super(Identifier, self).validate(value)))","[{'piece_type': 'error message', 'piece_content': 'INFO Scanned 3500 of 5494 files in 25s, ~14s left.\\nERROR \\'ascii\\' codec can\\'t encode character u\\'\\\\ufeff\\' in position 0: ordinal not in range(128)\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/__main__.py"", line 134, in main\\nreturn args.command.run(args, proxied_config)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/local/commands.py"", line 150, in run\\ntrack = tags.convert_tags_to_track(result.tags).replace(\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/audio/tags.py"", line 81, in convert_tags_to_track\\n\\'musicbrainz-sortname\\')\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/audio/tags.py"", line 137, in _artists\\nreturn [Artist(**attrs)]\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 158, in __call__\\n*args, **kwargs)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 34, in __init__\\nself._set_field(key, value)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 186, in _set_field\\nobject.__setattr__(self, name, value)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/models/fields.py"", line 50, in __set__\\nvalue = self.validate(value)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/models/fields.py"", line 98, in validate\\nreturn compat.intern(str(super(Identifier, self).validate(value)))\\nUnicodeEncodeError: \\'ascii\\' codec can\\'t encode character u\\'\\\\ufeff\\' in position 0: ordinal not in range(128)\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 9, in \\nload_entry_point(\\'Mopidy==2.0.0\\', \\'console_scripts\\', \\'mopidy\\')()\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/__main__.py"", line 134, in main\\nreturn args.command.run(args, proxied_config)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/local/commands.py"", line 150, in run\\ntrack = tags.convert_tags_to_track(result.tags).replace(\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/audio/tags.py"", line 81, in convert_tags_to_track\\n\\'musicbrainz-sortname\\')\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/audio/tags.py"", line 137, in _artists\\nreturn [Artist(**attrs)]\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 158, in __call__\\n*args, **kwargs)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 34, in __init__\\nself._set_field(key, value)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 186, in _set_field\\nobject.__setattr__(self, name, value)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/models/fields.py"", line 50, in __set__\\nvalue = self.validate(value)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/models/fields.py"", line 98, in validate\\nreturn compat.intern(str(super(Identifier, self).validate(value)))\\nUnicodeEncodeError: \\'ascii\\' codec can\\'t encode character u\\'\\\\ufeff\\' in position 0: ordinal not in range(128)'}]","INFO Scanned 3500 of 5494 files in 25s, ~14s left. +ERROR 'ascii' codec can't encode character u'\\ufeff' in position 0: ordinal not in range(128) +Traceback (most recent call last): +File ""/usr/local/lib/python2.7/site-packages/mopidy/__main__.py"", line 134, in main +return args.command.run(args, proxied_config) +File ""/usr/local/lib/python2.7/site-packages/mopidy/local/commands.py"", line 150, in run +track = tags.convert_tags_to_track(result.tags).replace( +File ""/usr/local/lib/python2.7/site-packages/mopidy/audio/tags.py"", line 81, in convert_tags_to_track +'musicbrainz-sortname') +File ""/usr/local/lib/python2.7/site-packages/mopidy/audio/tags.py"", line 137, in _artists +return [Artist(**attrs)] +File ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 158, in __call__ +*args, **kwargs) +File ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 34, in __init__ +self._set_field(key, value) +File ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 186, in _set_field +object.__setattr__(self, name, value) +File ""/usr/local/lib/python2.7/site-packages/mopidy/models/fields.py"", line 50, in __set__ +value = self.validate(value) +File ""/usr/local/lib/python2.7/site-packages/mopidy/models/fields.py"", line 98, in validate +return compat.intern(str(super(Identifier, self).validate(value))) +UnicodeEncodeError: 'ascii' codec can't encode character u'\\ufeff' in position 0: ordinal not in range(128) +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 9, in +load_entry_point('Mopidy==2.0.0', 'console_scripts', 'mopidy')() +File ""/usr/local/lib/python2.7/site-packages/mopidy/__main__.py"", line 134, in main +return args.command.run(args, proxied_config) +File ""/usr/local/lib/python2.7/site-packages/mopidy/local/commands.py"", line 150, in run +track = tags.convert_tags_to_track(result.tags).replace( +File ""/usr/local/lib/python2.7/site-packages/mopidy/audio/tags.py"", line 81, in convert_tags_to_track +'musicbrainz-sortname') +File ""/usr/local/lib/python2.7/site-packages/mopidy/audio/tags.py"", line 137, in _artists +return [Artist(**attrs)] +File ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 158, in __call__ +*args, **kwargs) +File ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 34, in __init__ +self._set_field(key, value) +File ""/usr/local/lib/python2.7/site-packages/mopidy/models/immutable.py"", line 186, in _set_field +object.__setattr__(self, name, value) +File ""/usr/local/lib/python2.7/site-packages/mopidy/models/fields.py"", line 50, in __set__ +value = self.validate(value) +File ""/usr/local/lib/python2.7/site-packages/mopidy/models/fields.py"", line 98, in validate +return compat.intern(str(super(Identifier, self).validate(value))) +UnicodeEncodeError: 'ascii' codec can't encode character u'\\ufeff' in position 0: ordinal not in range(128)",UnicodeEncodeError +" def on_stream_start(self): + gst_logger.debug('Got STREAM_START bus message') + uri = self._audio._pending_uri + logger.debug('Audio event: stream_changed(uri=%r)', uri) + AudioListener.send('stream_changed', uri=uri) + + # Emit any postponed tags that we got after about-to-finish. + tags, self._audio._pending_tags = self._audio._pending_tags, None + self._audio._tags = tags or {} + + if tags: + logger.debug('Audio event: tags_changed(tags=%r)', tags.keys()) + AudioListener.send('tags_changed', tags=tags.keys())"," def on_stream_start(self): + gst_logger.debug('Got STREAM_START bus message') + uri = self._audio._pending_uri + logger.debug('Audio event: stream_changed(uri=%r)', uri) + AudioListener.send('stream_changed', uri=uri) + + # Emit any postponed tags that we got after about-to-finish. + tags, self._audio._pending_tags = self._audio._pending_tags, None + self._audio._tags = tags + + if tags: + logger.debug('Audio event: tags_changed(tags=%r)', tags.keys()) + AudioListener.send('tags_changed', tags=tags.keys())","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 225, in on_message\\nself.on_tag(taglist)\\nFile ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 340, in on_tag\\nif self._audio._tags.get(key, unique) != value:\\nAttributeError: \\'NoneType\\' object has no attribute \\'get\\'\\nTraceback (most recent call last):\\nFile ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 225, in on_message\\nself.on_tag(taglist)\\nFile ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 340, in on_tag\\nif self._audio._tags.get(key, unique) != value:\\nAttributeError: \\'NoneType\\' object has no attribute \\'get\\''}]","Traceback (most recent call last): +File ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 225, in on_message +self.on_tag(taglist) +File ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 340, in on_tag +if self._audio._tags.get(key, unique) != value: +AttributeError: 'NoneType' object has no attribute 'get' +Traceback (most recent call last): +File ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 225, in on_message +self.on_tag(taglist) +File ""/home/jodal/mopidy-dev/mopidy/mopidy/audio/actor.py"", line 340, in on_tag +if self._audio._tags.get(key, unique) != value: +AttributeError: 'NoneType' object has no attribute 'get'",AttributeError +" def on_playbin_state_changed(self, old_state, new_state, pending_state): + gst_logger.debug( + 'Got STATE_CHANGED bus message: old=%s new=%s pending=%s', + old_state.value_name, new_state.value_name, + pending_state.value_name) + + if new_state == Gst.State.READY and pending_state == Gst.State.NULL: + # XXX: We're not called on the last state change when going down to + # NULL, so we rewrite the second to last call to get the expected + # behavior. + new_state = Gst.State.NULL + pending_state = Gst.State.VOID_PENDING + + if pending_state != Gst.State.VOID_PENDING: + return # Ignore intermediate state changes + + if new_state == Gst.State.READY: + return # Ignore READY state as it's GStreamer specific + + new_state = _GST_STATE_MAPPING[new_state] + old_state, self._audio.state = self._audio.state, new_state + + target_state = _GST_STATE_MAPPING.get(self._audio._target_state) + if target_state is None: + # XXX: Workaround for #1430, to be fixed properly by #1222. + logger.debug('Race condition happened. See #1222 and #1430.') + return + if target_state == new_state: + target_state = None + + logger.debug('Audio event: state_changed(old_state=%s, new_state=%s, ' + 'target_state=%s)', old_state, new_state, target_state) + AudioListener.send('state_changed', old_state=old_state, + new_state=new_state, target_state=target_state) + if new_state == PlaybackState.STOPPED: + logger.debug('Audio event: stream_changed(uri=None)') + AudioListener.send('stream_changed', uri=None) + + if 'GST_DEBUG_DUMP_DOT_DIR' in os.environ: + Gst.debug_bin_to_dot_file( + self._audio._playbin, Gst.DebugGraphDetails.ALL, 'mopidy')"," def on_playbin_state_changed(self, old_state, new_state, pending_state): + gst_logger.debug( + 'Got STATE_CHANGED bus message: old=%s new=%s pending=%s', + old_state.value_name, new_state.value_name, + pending_state.value_name) + + if new_state == Gst.State.READY and pending_state == Gst.State.NULL: + # XXX: We're not called on the last state change when going down to + # NULL, so we rewrite the second to last call to get the expected + # behavior. + new_state = Gst.State.NULL + pending_state = Gst.State.VOID_PENDING + + if pending_state != Gst.State.VOID_PENDING: + return # Ignore intermediate state changes + + if new_state == Gst.State.READY: + return # Ignore READY state as it's GStreamer specific + + new_state = _GST_STATE_MAPPING[new_state] + old_state, self._audio.state = self._audio.state, new_state + + target_state = _GST_STATE_MAPPING[self._audio._target_state] + if target_state == new_state: + target_state = None + + logger.debug('Audio event: state_changed(old_state=%s, new_state=%s, ' + 'target_state=%s)', old_state, new_state, target_state) + AudioListener.send('state_changed', old_state=old_state, + new_state=new_state, target_state=target_state) + if new_state == PlaybackState.STOPPED: + logger.debug('Audio event: stream_changed(uri=None)') + AudioListener.send('stream_changed', uri=None) + + if 'GST_DEBUG_DUMP_DOT_DIR' in os.environ: + Gst.debug_bin_to_dot_file( + self._audio._playbin, Gst.DebugGraphDetails.ALL, 'mopidy')","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/trygve/dev/mopidy/mopidy/mopidy/audio/actor.py"", line 210, in on_message\\nself.on_playbin_state_changed(old_state, new_state, pending_state)\\nFile ""/home/trygve/dev/mopidy/mopidy/mopidy/audio/actor.py"", line 260, in on_playbin_state_changed\\ntarget_state = _GST_STATE_MAPPING[self._audio._target_state]\\nKeyError: '}]","Traceback (most recent call last): +File ""/home/trygve/dev/mopidy/mopidy/mopidy/audio/actor.py"", line 210, in on_message +self.on_playbin_state_changed(old_state, new_state, pending_state) +File ""/home/trygve/dev/mopidy/mopidy/mopidy/audio/actor.py"", line 260, in on_playbin_state_changed +target_state = _GST_STATE_MAPPING[self._audio._target_state] +KeyError: ",KeyError +" def playlist_uri_from_name(self, name): + """""" + Helper function to retrieve a playlist URI from its unique MPD name. + """""" + if name not in self._uri_from_name: + self.refresh_playlists_mapping() + return self._uri_from_name.get(name)"," def playlist_uri_from_name(self, name): + """""" + Helper function to retrieve a playlist URI from its unique MPD name. + """""" + if not self._uri_from_name: + self.refresh_playlists_mapping() + return self._uri_from_name.get(name)","[{'piece_type': 'error message', 'piece_content': '2015-12-04 23:41:33,959 ERROR [MpdSession-13] /home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/actor.py:269\\npykka Unhandled exception in MpdSession (urn:uuid:093fbff0-33df-4e39-ba0b-c7259431372c):\\nTraceback (most recent call last):\\nFile ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/actor.py"", line 304, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/home/adamcik/dev/mopidy/mopidy/internal/network.py"", line 370, in on_receive\\nself.on_line_received(line)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/session.py"", line 34, in on_line_received\\nresponse = self.dispatcher.handle_request(line)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 47, in handle_request\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 76, in _catch_mpd_ack_errors_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 89, in _authenticate_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 105, in _command_list_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 134, in _idle_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 147, in _add_ok_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 159, in _call_handler_filter\\nresponse = self._format_response(self._call_handler(request))\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 174, in _call_handler\\nreturn protocol.commands.call(tokens, context=self.context)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/protocol/__init__.py"", line 180, in call\\nreturn self.handlers[tokens[0]](context, *tokens[1:])\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/protocol/__init__.py"", line 158, in validate\\nreturn func(**callargs)\\nFile ""/home/adamcik/dev/mopidy/mopidy/mpd/protocol/stored_playlists.py"", line 331, in rm\\ncontext.core.playlists.delete(uri).get()\\nFile ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/threading.py"", line 52, in get\\ncompat.reraise(*self._data[\\'exc_info\\'])\\nFile ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/compat.py"", line 12, in reraise\\nexec(\\'raise tp, value, tb\\')\\nFile ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/actor.py"", line 295, in _handle_receive\\nreturn callee(*message[\\'args\\'], **message[\\'kwargs\\'])\\nFile ""/home/adamcik/dev/mopidy/mopidy/core/playlists.py"", line 176, in delete\\nvalidation.check_uri(uri)\\nFile ""/home/adamcik/dev/mopidy/mopidy/internal/validation.py"", line 98, in check_uri\\nraise exceptions.ValidationError(msg.format(arg=arg))\\nValidationError: Expected a valid URI, not None'}]","2015-12-04 23:41:33,959 ERROR [MpdSession-13] /home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/actor.py:269 +pykka Unhandled exception in MpdSession (urn:uuid:093fbff0-33df-4e39-ba0b-c7259431372c): +Traceback (most recent call last): +File ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop +response = self._handle_receive(message) +File ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/actor.py"", line 304, in _handle_receive +return self.on_receive(message) +File ""/home/adamcik/dev/mopidy/mopidy/internal/network.py"", line 370, in on_receive +self.on_line_received(line) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/session.py"", line 34, in on_line_received +response = self.dispatcher.handle_request(line) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 47, in handle_request +return self._call_next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 76, in _catch_mpd_ack_errors_filter +return self._call_next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 89, in _authenticate_filter +return self._call_next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 105, in _command_list_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 134, in _idle_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 147, in _add_ok_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 159, in _call_handler_filter +response = self._format_response(self._call_handler(request)) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/dispatcher.py"", line 174, in _call_handler +return protocol.commands.call(tokens, context=self.context) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/protocol/__init__.py"", line 180, in call +return self.handlers[tokens[0]](context, *tokens[1:]) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/protocol/__init__.py"", line 158, in validate +return func(**callargs) +File ""/home/adamcik/dev/mopidy/mopidy/mpd/protocol/stored_playlists.py"", line 331, in rm +context.core.playlists.delete(uri).get() +File ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/threading.py"", line 52, in get +compat.reraise(*self._data['exc_info']) +File ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/compat.py"", line 12, in reraise +exec('raise tp, value, tb') +File ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop +response = self._handle_receive(message) +File ""/home/adamcik/dev/mopidy-virtualenv/local/lib/python2.7/site-packages/pykka/actor.py"", line 295, in _handle_receive +return callee(*message['args'], **message['kwargs']) +File ""/home/adamcik/dev/mopidy/mopidy/core/playlists.py"", line 176, in delete +validation.check_uri(uri) +File ""/home/adamcik/dev/mopidy/mopidy/internal/validation.py"", line 98, in check_uri +raise exceptions.ValidationError(msg.format(arg=arg)) +ValidationError: Expected a valid URI, not None",ValidationError +"def _get_library(args, config): + libraries = dict((l.name, l) for l in args.registry['local:library']) + library_name = config['local']['library'] + + if library_name not in libraries: + logger.error('Local library %s not found', library_name) + return None + + logger.debug('Using %s as the local library', library_name) + return libraries[library_name](config)","def _get_library(args, config): + libraries = dict((l.name, l) for l in args.registry['local:library']) + library_name = config['local']['library'] + + if library_name not in libraries: + logger.warning('Local library %s not found', library_name) + return 1 + + logger.debug('Using %s as the local library', library_name) + return libraries[library_name](config)","[{'piece_type': 'error message', 'piece_content': 'INFO Starting Mopidy 1.1.1\\nINFO Loading config from builtin defaults\\nINFO Loading config from /etc/mopidy/mopidy.conf\\nINFO Loading config from command line options\\nINFO Enabled extensions: mpd, http, stream, podcast-gpodder, m3u, podcast-itunes, softwaremixer, file, musicbox_webclient, podcast, local, tunein, soundcloud\\nINFO Disabled extensions: none\\nWARNING Local library images not found\\nINFO Found 8597 files in media_dir.\\nERROR \\'int\\' object has no attribute \\'load\\'\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main\\nreturn args.command.run(args, proxied_config)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run\\nnum_tracks = library.load()\\nAttributeError: \\'int\\' object has no attribute \\'load\\'\\nTraceback (most recent call last):\\nFile ""/usr/bin/mopidy"", line 9, in \\nload_entry_point(\\'Mopidy==1.1.1\\', \\'console_scripts\\', \\'mopidy\\')()\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main\\nreturn args.command.run(args, proxied_config)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run\\nnum_tracks = library.load()\\nAttributeError: \\'int\\' object has no attribute \\'load\\''}]","INFO Starting Mopidy 1.1.1 +INFO Loading config from builtin defaults +INFO Loading config from /etc/mopidy/mopidy.conf +INFO Loading config from command line options +INFO Enabled extensions: mpd, http, stream, podcast-gpodder, m3u, podcast-itunes, softwaremixer, file, musicbox_webclient, podcast, local, tunein, soundcloud +INFO Disabled extensions: none +WARNING Local library images not found +INFO Found 8597 files in media_dir. +ERROR 'int' object has no attribute 'load' +Traceback (most recent call last): +File ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main +return args.command.run(args, proxied_config) +File ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run +num_tracks = library.load() +AttributeError: 'int' object has no attribute 'load' +Traceback (most recent call last): +File ""/usr/bin/mopidy"", line 9, in +load_entry_point('Mopidy==1.1.1', 'console_scripts', 'mopidy')() +File ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main +return args.command.run(args, proxied_config) +File ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run +num_tracks = library.load() +AttributeError: 'int' object has no attribute 'load'",AttributeError +" def run(self, args, config): + library = _get_library(args, config) + if library is None: + return 1 + + prompt = '\\nAre you sure you want to clear the library? [y/N] ' + + if compat.input(prompt).lower() != 'y': + print('Clearing library aborted.') + return 0 + + if library.clear(): + print('Library successfully cleared.') + return 0 + + print('Unable to clear library.') + return 1"," def run(self, args, config): + library = _get_library(args, config) + prompt = '\\nAre you sure you want to clear the library? [y/N] ' + + if compat.input(prompt).lower() != 'y': + print('Clearing library aborted.') + return 0 + + if library.clear(): + print('Library successfully cleared.') + return 0 + + print('Unable to clear library.') + return 1","[{'piece_type': 'error message', 'piece_content': 'INFO Starting Mopidy 1.1.1\\nINFO Loading config from builtin defaults\\nINFO Loading config from /etc/mopidy/mopidy.conf\\nINFO Loading config from command line options\\nINFO Enabled extensions: mpd, http, stream, podcast-gpodder, m3u, podcast-itunes, softwaremixer, file, musicbox_webclient, podcast, local, tunein, soundcloud\\nINFO Disabled extensions: none\\nWARNING Local library images not found\\nINFO Found 8597 files in media_dir.\\nERROR \\'int\\' object has no attribute \\'load\\'\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main\\nreturn args.command.run(args, proxied_config)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run\\nnum_tracks = library.load()\\nAttributeError: \\'int\\' object has no attribute \\'load\\'\\nTraceback (most recent call last):\\nFile ""/usr/bin/mopidy"", line 9, in \\nload_entry_point(\\'Mopidy==1.1.1\\', \\'console_scripts\\', \\'mopidy\\')()\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main\\nreturn args.command.run(args, proxied_config)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run\\nnum_tracks = library.load()\\nAttributeError: \\'int\\' object has no attribute \\'load\\''}]","INFO Starting Mopidy 1.1.1 +INFO Loading config from builtin defaults +INFO Loading config from /etc/mopidy/mopidy.conf +INFO Loading config from command line options +INFO Enabled extensions: mpd, http, stream, podcast-gpodder, m3u, podcast-itunes, softwaremixer, file, musicbox_webclient, podcast, local, tunein, soundcloud +INFO Disabled extensions: none +WARNING Local library images not found +INFO Found 8597 files in media_dir. +ERROR 'int' object has no attribute 'load' +Traceback (most recent call last): +File ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main +return args.command.run(args, proxied_config) +File ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run +num_tracks = library.load() +AttributeError: 'int' object has no attribute 'load' +Traceback (most recent call last): +File ""/usr/bin/mopidy"", line 9, in +load_entry_point('Mopidy==1.1.1', 'console_scripts', 'mopidy')() +File ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main +return args.command.run(args, proxied_config) +File ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run +num_tracks = library.load() +AttributeError: 'int' object has no attribute 'load'",AttributeError +" def run(self, args, config): + media_dir = config['local']['media_dir'] + scan_timeout = config['local']['scan_timeout'] + flush_threshold = config['local']['scan_flush_threshold'] + excluded_file_extensions = config['local']['excluded_file_extensions'] + excluded_file_extensions = tuple( + bytes(file_ext.lower()) for file_ext in excluded_file_extensions) + + library = _get_library(args, config) + if library is None: + return 1 + + file_mtimes, file_errors = path.find_mtimes( + media_dir, follow=config['local']['scan_follow_symlinks']) + + logger.info('Found %d files in media_dir.', len(file_mtimes)) + + if file_errors: + logger.warning('Encountered %d errors while scanning media_dir.', + len(file_errors)) + for name in file_errors: + logger.debug('Scan error %r for %r', file_errors[name], name) + + num_tracks = library.load() + logger.info('Checking %d tracks from library.', num_tracks) + + uris_to_update = set() + uris_to_remove = set() + uris_in_library = set() + + for track in library.begin(): + abspath = translator.local_track_uri_to_path(track.uri, media_dir) + mtime = file_mtimes.get(abspath) + if mtime is None: + logger.debug('Missing file %s', track.uri) + uris_to_remove.add(track.uri) + elif mtime > track.last_modified or args.force: + uris_to_update.add(track.uri) + uris_in_library.add(track.uri) + + logger.info('Removing %d missing tracks.', len(uris_to_remove)) + for uri in uris_to_remove: + library.remove(uri) + + for abspath in file_mtimes: + relpath = os.path.relpath(abspath, media_dir) + uri = translator.path_to_local_track_uri(relpath) + + if b'/.' in relpath: + logger.debug('Skipped %s: Hidden directory/file.', uri) + elif relpath.lower().endswith(excluded_file_extensions): + logger.debug('Skipped %s: File extension excluded.', uri) + elif uri not in uris_in_library: + uris_to_update.add(uri) + + logger.info( + 'Found %d tracks which need to be updated.', len(uris_to_update)) + logger.info('Scanning...') + + uris_to_update = sorted(uris_to_update, key=lambda v: v.lower()) + uris_to_update = uris_to_update[:args.limit] + + scanner = scan.Scanner(scan_timeout) + progress = _Progress(flush_threshold, len(uris_to_update)) + + for uri in uris_to_update: + try: + relpath = translator.local_track_uri_to_path(uri, media_dir) + file_uri = path.path_to_uri(os.path.join(media_dir, relpath)) + result = scanner.scan(file_uri) + tags, duration = result.tags, result.duration + if not result.playable: + logger.warning('Failed %s: No audio found in file.', uri) + elif duration < MIN_DURATION_MS: + logger.warning('Failed %s: Track shorter than %dms', + uri, MIN_DURATION_MS) + else: + mtime = file_mtimes.get(os.path.join(media_dir, relpath)) + track = utils.convert_tags_to_track(tags).replace( + uri=uri, length=duration, last_modified=mtime) + if library.add_supports_tags_and_duration: + library.add(track, tags=tags, duration=duration) + else: + library.add(track) + logger.debug('Added %s', track.uri) + except exceptions.ScannerError as error: + logger.warning('Failed %s: %s', uri, error) + + if progress.increment(): + progress.log() + if library.flush(): + logger.debug('Progress flushed.') + + progress.log() + library.close() + logger.info('Done scanning.') + return 0"," def run(self, args, config): + media_dir = config['local']['media_dir'] + scan_timeout = config['local']['scan_timeout'] + flush_threshold = config['local']['scan_flush_threshold'] + excluded_file_extensions = config['local']['excluded_file_extensions'] + excluded_file_extensions = tuple( + bytes(file_ext.lower()) for file_ext in excluded_file_extensions) + + library = _get_library(args, config) + + file_mtimes, file_errors = path.find_mtimes( + media_dir, follow=config['local']['scan_follow_symlinks']) + + logger.info('Found %d files in media_dir.', len(file_mtimes)) + + if file_errors: + logger.warning('Encountered %d errors while scanning media_dir.', + len(file_errors)) + for name in file_errors: + logger.debug('Scan error %r for %r', file_errors[name], name) + + num_tracks = library.load() + logger.info('Checking %d tracks from library.', num_tracks) + + uris_to_update = set() + uris_to_remove = set() + uris_in_library = set() + + for track in library.begin(): + abspath = translator.local_track_uri_to_path(track.uri, media_dir) + mtime = file_mtimes.get(abspath) + if mtime is None: + logger.debug('Missing file %s', track.uri) + uris_to_remove.add(track.uri) + elif mtime > track.last_modified or args.force: + uris_to_update.add(track.uri) + uris_in_library.add(track.uri) + + logger.info('Removing %d missing tracks.', len(uris_to_remove)) + for uri in uris_to_remove: + library.remove(uri) + + for abspath in file_mtimes: + relpath = os.path.relpath(abspath, media_dir) + uri = translator.path_to_local_track_uri(relpath) + + if b'/.' in relpath: + logger.debug('Skipped %s: Hidden directory/file.', uri) + elif relpath.lower().endswith(excluded_file_extensions): + logger.debug('Skipped %s: File extension excluded.', uri) + elif uri not in uris_in_library: + uris_to_update.add(uri) + + logger.info( + 'Found %d tracks which need to be updated.', len(uris_to_update)) + logger.info('Scanning...') + + uris_to_update = sorted(uris_to_update, key=lambda v: v.lower()) + uris_to_update = uris_to_update[:args.limit] + + scanner = scan.Scanner(scan_timeout) + progress = _Progress(flush_threshold, len(uris_to_update)) + + for uri in uris_to_update: + try: + relpath = translator.local_track_uri_to_path(uri, media_dir) + file_uri = path.path_to_uri(os.path.join(media_dir, relpath)) + result = scanner.scan(file_uri) + tags, duration = result.tags, result.duration + if not result.playable: + logger.warning('Failed %s: No audio found in file.', uri) + elif duration < MIN_DURATION_MS: + logger.warning('Failed %s: Track shorter than %dms', + uri, MIN_DURATION_MS) + else: + mtime = file_mtimes.get(os.path.join(media_dir, relpath)) + track = utils.convert_tags_to_track(tags).replace( + uri=uri, length=duration, last_modified=mtime) + if library.add_supports_tags_and_duration: + library.add(track, tags=tags, duration=duration) + else: + library.add(track) + logger.debug('Added %s', track.uri) + except exceptions.ScannerError as error: + logger.warning('Failed %s: %s', uri, error) + + if progress.increment(): + progress.log() + if library.flush(): + logger.debug('Progress flushed.') + + progress.log() + library.close() + logger.info('Done scanning.') + return 0","[{'piece_type': 'error message', 'piece_content': 'INFO Starting Mopidy 1.1.1\\nINFO Loading config from builtin defaults\\nINFO Loading config from /etc/mopidy/mopidy.conf\\nINFO Loading config from command line options\\nINFO Enabled extensions: mpd, http, stream, podcast-gpodder, m3u, podcast-itunes, softwaremixer, file, musicbox_webclient, podcast, local, tunein, soundcloud\\nINFO Disabled extensions: none\\nWARNING Local library images not found\\nINFO Found 8597 files in media_dir.\\nERROR \\'int\\' object has no attribute \\'load\\'\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main\\nreturn args.command.run(args, proxied_config)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run\\nnum_tracks = library.load()\\nAttributeError: \\'int\\' object has no attribute \\'load\\'\\nTraceback (most recent call last):\\nFile ""/usr/bin/mopidy"", line 9, in \\nload_entry_point(\\'Mopidy==1.1.1\\', \\'console_scripts\\', \\'mopidy\\')()\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main\\nreturn args.command.run(args, proxied_config)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run\\nnum_tracks = library.load()\\nAttributeError: \\'int\\' object has no attribute \\'load\\''}]","INFO Starting Mopidy 1.1.1 +INFO Loading config from builtin defaults +INFO Loading config from /etc/mopidy/mopidy.conf +INFO Loading config from command line options +INFO Enabled extensions: mpd, http, stream, podcast-gpodder, m3u, podcast-itunes, softwaremixer, file, musicbox_webclient, podcast, local, tunein, soundcloud +INFO Disabled extensions: none +WARNING Local library images not found +INFO Found 8597 files in media_dir. +ERROR 'int' object has no attribute 'load' +Traceback (most recent call last): +File ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main +return args.command.run(args, proxied_config) +File ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run +num_tracks = library.load() +AttributeError: 'int' object has no attribute 'load' +Traceback (most recent call last): +File ""/usr/bin/mopidy"", line 9, in +load_entry_point('Mopidy==1.1.1', 'console_scripts', 'mopidy')() +File ""/usr/lib/python2.7/dist-packages/mopidy/__main__.py"", line 158, in main +return args.command.run(args, proxied_config) +File ""/usr/lib/python2.7/dist-packages/mopidy/local/commands.py"", line 91, in run +num_tracks = library.load() +AttributeError: 'int' object has no attribute 'load'",AttributeError +"def parse_urilist(data): + result = [] + for line in data.splitlines(): + if not line.strip() or line.startswith(b'#'): + continue + try: + validation.check_uri(line) + except ValueError: + return [] + result.append(line) + return result","def parse_urilist(data): + result = [] + for line in data.splitlines(): + if not line.strip() or line.startswith('#'): + continue + try: + validation.check_uri(line) + except ValueError: + return [] + result.append(line) + return result","[{'piece_type': 'error message', 'piece_content': 'INFO 2015-08-22 22:19:26,991 [855:MpdSession-31] mopidy.mpd.session\\nNew MPD connection from [::ffff:127.0.0.1]:50701\\nDEBUG 2015-08-22 22:19:26,993 [855:MpdSession-31] mopidy.mpd.session\\nRequest from [::ffff:127.0.0.1]:50701: command_list_begin\\nDEBUG 2015-08-22 22:19:26,993 [855:MpdSession-31] mopidy.mpd.session\\nRequest from [::ffff:127.0.0.1]:50701: add ""http://feedproxy.google.com/~r/WelcomeToNightVale/~5/tXeJa4IGs-8/23-EternalScouts.mp3""\\nDEBUG 2015-08-22 22:19:26,994 [855:MpdSession-31] mopidy.mpd.session\\nRequest from [::ffff:127.0.0.1]:50701: play ""0""\\nDEBUG 2015-08-22 22:19:26,994 [855:MpdSession-31] mopidy.mpd.session\\nRequest from [::ffff:127.0.0.1]:50701: command_list_end\\nDEBUG 2015-08-22 22:19:28,176 [855:Core-27] mopidy.core.tracklist\\nTriggering event: tracklist_changed()\\nDEBUG 2015-08-22 22:19:28,177 [855:MainThread] mopidy.listener\\nSending tracklist_changed to CoreListener: {}\\nDEBUG 2015-08-22 22:19:28,177 [855:Core-27] mopidy.core.playback\\nChanging state: stopped -> playing\\nDEBUG 2015-08-22 22:19:28,177 [855:Core-27] mopidy.core.playback\\nTriggering playback state change event\\nDEBUG 2015-08-22 22:19:28,179 [855:MainThread] mopidy.listener\\nSending playback_state_changed to CoreListener: {\\'old_state\\': u\\'stopped\\', \\'new_state\\': u\\'playing\\'}\\nDEBUG 2015-08-22 22:19:28,179 [855:Audio-2] mopidy.audio.gst\\nState change to GST_STATE_READY: result=GST_STATE_CHANGE_SUCCESS\\nDEBUG 2015-08-22 22:19:28,179 [855:MainThread] mopidy.audio.gst\\nGot state-changed message: old=GST_STATE_NULL new=GST_STATE_READY pending=GST_STATE_VOID_PENDING\\nINFO 2015-08-22 22:19:34,545 [855:MpdSession-32] mopidy.mpd.session\\nNew MPD connection from [::ffff:127.0.0.1]:50713\\nDEBUG 2015-08-22 22:19:34,547 [855:MpdSession-32] mopidy.mpd.session\\nRequest from [::ffff:127.0.0.1]:50713: status\\nERROR 2015-08-22 22:19:38,324 [855:MpdSession-31] pykka\\nUnhandled exception in MpdSession (urn:uuid:8a894042-6120-4236-a944-cd336bd7c8b3):\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 304, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/internal/network.py"", line 370, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/session.py"", line 34, in on_line_received\\nresponse = self.dispatcher.handle_request(line)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 47, in handle_request\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 76, in _catch_mpd_ack_errors_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 86, in _authenticate_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 105, in _command_list_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 134, in _idle_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 147, in _add_ok_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 159, in _call_handler_filter\\nresponse = self._format_response(self._call_handler(request))\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 174, in _call_handler\\nreturn protocol.commands.call(tokens, context=self.context)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 180, in call\\nreturn self.handlers[tokens[0]](context, *tokens[1:])\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 158, in validate\\nreturn func(**callargs)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/command_list.py"", line 42, in command_list_end\\ncommand, current_command_list_index=index)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 47, in handle_request\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 76, in _catch_mpd_ack_errors_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 86, in _authenticate_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 105, in _command_list_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 134, in _idle_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 147, in _add_ok_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 159, in _call_handler_filter\\nresponse = self._format_response(self._call_handler(request))\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 174, in _call_handler\\nreturn protocol.commands.call(tokens, context=self.context)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 180, in call\\nreturn self.handlers[tokens[0]](context, *tokens[1:])\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 158, in validate\\nreturn func(**callargs)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/playback.py"", line 181, in play\\nreturn context.core.playback.play(tl_track).get()\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/threading.py"", line 52, in get\\ncompat.reraise(*self._data[\\'exc_info\\'])\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/compat.py"", line 12, in reraise\\nexec(\\'raise tp, value, tb\\')\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 295, in _handle_receive\\nreturn callee(*message[\\'args\\'], **message[\\'kwargs\\'])\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/core/playback.py"", line 305, in play\\nself._play(tl_track=tl_track, tlid=tlid, on_error_step=1)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/core/playback.py"", line 348, in _play\\nbackend.playback.change_track(tl_track.track).get() and\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/threading.py"", line 52, in get\\ncompat.reraise(*self._data[\\'exc_info\\'])\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/compat.py"", line 12, in reraise\\nexec(\\'raise tp, value, tb\\')\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 295, in _handle_receive\\nreturn callee(*message[\\'args\\'], **message[\\'kwargs\\'])\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/backend.py"", line 245, in change_track\\nuri = self.translate_uri(track.uri)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/stream/actor.py"", line 90, in translate_uri\\ntracks = list(playlists.parse(content))\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/internal/playlists.py"", line 28, in parse\\nreturn parse_urilist(data) # Fallback\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/internal/playlists.py"", line 125, in parse_urilist\\nif not line.strip() or line.startswith(\\'#\\'):\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xdf in position 154: ordinal not in range(128)\\nDEBUG 2015-08-22 22:19:38,326 [855:Audio-2] mopidy.audio.actor\\nPosition query failed'}]","INFO 2015-08-22 22:19:26,991 [855:MpdSession-31] mopidy.mpd.session +New MPD connection from [::ffff:127.0.0.1]:50701 +DEBUG 2015-08-22 22:19:26,993 [855:MpdSession-31] mopidy.mpd.session +Request from [::ffff:127.0.0.1]:50701: command_list_begin +DEBUG 2015-08-22 22:19:26,993 [855:MpdSession-31] mopidy.mpd.session +Request from [::ffff:127.0.0.1]:50701: add ""http://feedproxy.google.com/~r/WelcomeToNightVale/~5/tXeJa4IGs-8/23-EternalScouts.mp3"" +DEBUG 2015-08-22 22:19:26,994 [855:MpdSession-31] mopidy.mpd.session +Request from [::ffff:127.0.0.1]:50701: play ""0"" +DEBUG 2015-08-22 22:19:26,994 [855:MpdSession-31] mopidy.mpd.session +Request from [::ffff:127.0.0.1]:50701: command_list_end +DEBUG 2015-08-22 22:19:28,176 [855:Core-27] mopidy.core.tracklist +Triggering event: tracklist_changed() +DEBUG 2015-08-22 22:19:28,177 [855:MainThread] mopidy.listener +Sending tracklist_changed to CoreListener: {} +DEBUG 2015-08-22 22:19:28,177 [855:Core-27] mopidy.core.playback +Changing state: stopped -> playing +DEBUG 2015-08-22 22:19:28,177 [855:Core-27] mopidy.core.playback +Triggering playback state change event +DEBUG 2015-08-22 22:19:28,179 [855:MainThread] mopidy.listener +Sending playback_state_changed to CoreListener: {'old_state': u'stopped', 'new_state': u'playing'} +DEBUG 2015-08-22 22:19:28,179 [855:Audio-2] mopidy.audio.gst +State change to GST_STATE_READY: result=GST_STATE_CHANGE_SUCCESS +DEBUG 2015-08-22 22:19:28,179 [855:MainThread] mopidy.audio.gst +Got state-changed message: old=GST_STATE_NULL new=GST_STATE_READY pending=GST_STATE_VOID_PENDING +INFO 2015-08-22 22:19:34,545 [855:MpdSession-32] mopidy.mpd.session +New MPD connection from [::ffff:127.0.0.1]:50713 +DEBUG 2015-08-22 22:19:34,547 [855:MpdSession-32] mopidy.mpd.session +Request from [::ffff:127.0.0.1]:50713: status +ERROR 2015-08-22 22:19:38,324 [855:MpdSession-31] pykka +Unhandled exception in MpdSession (urn:uuid:8a894042-6120-4236-a944-cd336bd7c8b3): +Traceback (most recent call last): +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop +response = self._handle_receive(message) +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 304, in _handle_receive +return self.on_receive(message) +File ""/usr/local/lib/python2.7/site-packages/mopidy/internal/network.py"", line 370, in on_receive +self.on_line_received(line) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/session.py"", line 34, in on_line_received +response = self.dispatcher.handle_request(line) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 47, in handle_request +return self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 76, in _catch_mpd_ack_errors_filter +return self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 86, in _authenticate_filter +return self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 105, in _command_list_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 134, in _idle_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 147, in _add_ok_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 159, in _call_handler_filter +response = self._format_response(self._call_handler(request)) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 174, in _call_handler +return protocol.commands.call(tokens, context=self.context) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 180, in call +return self.handlers[tokens[0]](context, *tokens[1:]) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 158, in validate +return func(**callargs) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/command_list.py"", line 42, in command_list_end +command, current_command_list_index=index) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 47, in handle_request +return self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 76, in _catch_mpd_ack_errors_filter +return self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 86, in _authenticate_filter +return self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 105, in _command_list_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 134, in _idle_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 147, in _add_ok_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 68, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 159, in _call_handler_filter +response = self._format_response(self._call_handler(request)) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 174, in _call_handler +return protocol.commands.call(tokens, context=self.context) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 180, in call +return self.handlers[tokens[0]](context, *tokens[1:]) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 158, in validate +return func(**callargs) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/playback.py"", line 181, in play +return context.core.playback.play(tl_track).get() +File ""/usr/local/lib/python2.7/site-packages/pykka/threading.py"", line 52, in get +compat.reraise(*self._data['exc_info']) +File ""/usr/local/lib/python2.7/site-packages/pykka/compat.py"", line 12, in reraise +exec('raise tp, value, tb') +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop +response = self._handle_receive(message) +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 295, in _handle_receive +return callee(*message['args'], **message['kwargs']) +File ""/usr/local/lib/python2.7/site-packages/mopidy/core/playback.py"", line 305, in play +self._play(tl_track=tl_track, tlid=tlid, on_error_step=1) +File ""/usr/local/lib/python2.7/site-packages/mopidy/core/playback.py"", line 348, in _play +backend.playback.change_track(tl_track.track).get() and +File ""/usr/local/lib/python2.7/site-packages/pykka/threading.py"", line 52, in get +compat.reraise(*self._data['exc_info']) +File ""/usr/local/lib/python2.7/site-packages/pykka/compat.py"", line 12, in reraise +exec('raise tp, value, tb') +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 201, in _actor_loop +response = self._handle_receive(message) +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 295, in _handle_receive +return callee(*message['args'], **message['kwargs']) +File ""/usr/local/lib/python2.7/site-packages/mopidy/backend.py"", line 245, in change_track +uri = self.translate_uri(track.uri) +File ""/usr/local/lib/python2.7/site-packages/mopidy/stream/actor.py"", line 90, in translate_uri +tracks = list(playlists.parse(content)) +File ""/usr/local/lib/python2.7/site-packages/mopidy/internal/playlists.py"", line 28, in parse +return parse_urilist(data) # Fallback +File ""/usr/local/lib/python2.7/site-packages/mopidy/internal/playlists.py"", line 125, in parse_urilist +if not line.strip() or line.startswith('#'): +UnicodeDecodeError: 'ascii' codec can't decode byte 0xdf in position 154: ordinal not in range(128) +DEBUG 2015-08-22 22:19:38,326 [855:Audio-2] mopidy.audio.actor +Position query failed",UnicodeDecodeError +" def send(self, data): + """"""Send data to client, return any unsent data."""""" + try: + sent = self.sock.send(data) + return data[sent:] + except socket.error as e: + if e.errno in (errno.EWOULDBLOCK, errno.EINTR): + return data + self.stop( + 'Unexpected client error: %s' % encoding.locale_decode(e)) + return b''"," def send(self, data): + """"""Send data to client, return any unsent data."""""" + try: + sent = self.sock.send(data) + return data[sent:] + except socket.error as e: + if e.errno in (errno.EWOULDBLOCK, errno.EINTR): + return data + self.stop('Unexpected client error: %s' % e) + return b''","[{'piece_type': 'error message', 'piece_content': '2015-02-04 06:30:11,901 ERROR [3714:MpdSession-27] pykka: Unhandled exception in MpdSession (urn:uuid:9595028c-486c-4c89-813a-785c3cafc057):\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 303, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 366, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/mpd/session.py"", line 41, in on_line_received\\nself.send_lines(response)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 428, in send_lines\\nself.connection.queue_send(self.encode(data))\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 189, in queue_send\\nself.send_buffer = self.send(self.send_buffer + data)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 202, in send\\nself.stop(\\'Unexpected client error: %s\\' % e)\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 16: ordinal not in range(128)'}, {'piece_type': 'error message', 'piece_content': 'file: local:track:Datarock/Kein%20Titel/11%20AudioTrack%2011.mp3\\nTime: 236\\nArtist: Datarock\\nTitle: AudioTrack 11\\nAlbum: Kein Titel\\nTrack: 11\\nGenre: Unbekannt\\nOK\\nERROR 2015-02-04 06:30:11,901 [3714:MpdSession-27] pykka\\nUnhandled exception in MpdSession (urn:uuid:9595028c-486c-4c89-813a-785c3cafc057):\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 303, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 366, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/mpd/session.py"", line 41, in on_line_received\\nself.send_lines(response)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 428, in send_lines\\nself.connection.queue_send(self.encode(data))\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 189, in queue_send\\nself.send_buffer = self.send(self.send_buffer + data)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 202, in send\\nself.stop(\\'Unexpected client error: %s\\' % e)\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 16: ordinal not in range(128)\\nDEBUG 2015-02-04 06:30:12,098 [3714:MpdSession-27] pykka\\nUnregistered MpdSession (urn:uuid:9595028c-486c-4c89-813a-785c3cafc057)'}, {'piece_type': 'other', 'piece_content': ""file: local:track:Datarock/Kein%20Titel/11%20AudioTrack%2011.mp3\\nTime: 236\\nArtist: Datarock\\nTitle: AudioTrack 11\\nAlbum: Kein Titel\\nTrack: 11\\nGenre: Unbekannt\\nOK\\nDEBUG 2015-02-10 16:49:56,626 [4213:MpdSession-11] mopidy.utils.network\\nUnexpected client error: error(32, 'Daten\\\\xc3\\\\xbcbergabe unterbrochen (broken pipe)')\\nDEBUG 2015-02-10 16:49:57,131 [4213:MainThread] pykka\\nRegistered MpdSession (urn:uuid:18e5db5c-fda7-4ee7-a183-7d84fdcff1ac)\\nDEBUG 2015-02-10 16:49:57,074 [4213:MpdSession-11] mopidy.mpd.session\\nRequest from [192.168.1.8]:56642: close\\nDEBUG 2015-02-10 16:49:57,177 [4213:MainThread] pykka\\nStarting MpdSession (urn:uuid:18e5db5c-fda7-4ee7-a183-7d84fdcff1ac)\\nDEBUG 2015-02-10 16:49:57,296 [4213:MpdSession-11] mopidy.mpd.session\\nResponse to [192.168.1.8]:56642: OK\\nDEBUG 2015-02-10 16:49:57,408 [4213:MpdSession-11] mopidy.utils.network\\nAlready stopping: Unexpected client error: error(9, 'Bad file descriptor')\\nINFO 2015-02-10 16:49:57,312 [4213:MpdSession-28] mopidy.mpd.session\\nNew MPD connection from [192.168.1.8]:56663\\nDEBUG 2015-02-10 16:49:57,499 [4213:MpdSession-11] mopidy.utils.network\\nAlready stopping: Client most likely disconnected.""}, {'piece_type': 'error message', 'piece_content': 'ERROR 2015-02-10 16:57:56,253 [4213:MpdSession-20] pykka\\nUnhandled exception in MpdSession (urn:uuid:68c56fc8-6342-41e4-b36d-ddc812875bc7):\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 303, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 366, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/mpd/session.py"", line 39, in on_line_received\\nformatting.indent(self.terminator.join(response)))\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/formatting.py"", line 13, in indent\\nresult = linebreak.join(lines)\\nMemoryError\\nDEBUG 2015-02-10 16:57:58,386 [4213:MpdSession-21] mopidy.utils.network\\nAlready stopping: Client most likely disconnected.\\nDEBUG 2015-02-10 16:57:58,434 [4213:MpdSession-20] pykka\\nUnregistered MpdSession (urn:uuid:68c56fc8-6342-41e4-b36d-ddc812875bc7)\\nDEBUG 2015-02-10 16:57:58,507 [4213:MpdSession-21] pykka\\nUnregistered MpdSession (urn:uuid:7af306aa-f2fe-4219-983f-dea5006c99b3)\\nDEBUG 2015-02-10 16:57:58,572 [4213:MpdSession-21] pykka\\nStopped MpdSession (urn:uuid:7af306aa-f2fe-4219-983f-dea5006c99b3)\\nDEBUG 2015-02-10 16:58:00,096 [4213:MpdSession-21] mopidy.utils.network\\nAlready stopping: Actor is shutting down.\\nDEBUG 2015-02-10 16:58:12,092 [4213:MainThread] mopidy.utils.network\\nAlready stopping: Client inactive for 60s; closing connection\\nDEBUG 2015-02-10 16:58:58,021 [4213:MpdSession-22] mopidy.utils.network\\nUnexpected client error: error(32, \\'Daten\\\\xc3\\\\xbcbergabe unterbrochen (broken pipe)\\')\\nDEBUG 2015-02-10 16:58:59,892 [4213:MpdSession-22] mopidy.mpd.session\\nRequest from [192.168.1.8]:56654: close\\nDEBUG 2015-02-10 16:58:59,938 [4213:MainThread] mopidy.utils.network\\nAlready stopping: Client inactive for 60s; closing connection\\nDEBUG 2015-02-10 16:59:00,001 [4213:MpdSession-22] mopidy.mpd.session\\nResponse to [192.168.1.8]:56654: OK\\nDEBUG 2015-02-10 16:59:00,004 [4213:MpdSession-22] mopidy.utils.network\\nAlready stopping: Unexpected client error: error(9, \\'Bad file descriptor\\')\\nDEBUG 2015-02-10 16:59:00,093 [4213:MpdSession-22] mopidy.utils.network\\nAlready stopping: Client most likely disconnected.\\nDEBUG 2015-02-10 16:59:00,193 [4213:MpdSession-22] pykka\\nUnregistered MpdSession (urn:uuid:710e58dd-1bf7-44d4-aaee-67cadedd419e)\\nDEBUG 2015-02-10 16:59:00,254 [4213:MpdSession-22] pykka\\nStopped MpdSession (urn:uuid:710e58dd-1bf7-44d4-aaee-67cadedd419e)\\nDEBUG 2015-02-10 16:59:00,291 [4213:MpdSession-22] mopidy.utils.network\\nAlready stopping: Actor is shutting down.\\nDEBUG 2015-02-10 17:00:04,191 [4213:MainThread] mopidy.utils.network\\nAlready stopping: Client inactive for 60s; closing connection\\nERROR 2015-02-10 17:00:44,073 [4213:MpdSession-24] pykka\\nUnhandled exception in MpdSession (urn:uuid:64d515a1-f2f1-454d-bc9e-c4eebb06c4ed):\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 303, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 366, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/mpd/session.py"", line 39, in on_line_received\\nformatting.indent(self.terminator.join(response)))\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/formatting.py"", line 13, in indent\\nresult = linebreak.join(lines)\\nMemoryError'}]","2015-02-04 06:30:11,901 ERROR [3714:MpdSession-27] pykka: Unhandled exception in MpdSession (urn:uuid:9595028c-486c-4c89-813a-785c3cafc057): +Traceback (most recent call last): +File ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 200, in _actor_loop +response = self._handle_receive(message) +File ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 303, in _handle_receive +return self.on_receive(message) +File ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 366, in on_receive +self.on_line_received(line) +File ""/usr/lib/python2.7/dist-packages/mopidy/mpd/session.py"", line 41, in on_line_received +self.send_lines(response) +File ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 428, in send_lines +self.connection.queue_send(self.encode(data)) +File ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 189, in queue_send +self.send_buffer = self.send(self.send_buffer + data) +File ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 202, in send +self.stop('Unexpected client error: %s' % e) +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128)",UnicodeDecodeError +"def _find_worker(relative, follow, done, work, results, errors): + """"""Worker thread for collecting stat() results. + + :param str relative: directory to make results relative to + :param bool follow: if symlinks should be followed + :param threading.Event done: event indicating that all work has been done + :param queue.Queue work: queue of paths to process + :param dict results: shared dictionary for storing all the stat() results + :param dict errors: shared dictionary for storing any per path errors + """""" + while not done.is_set(): + try: + entry, parents = work.get(block=False) + except queue.Empty: + continue + + if relative: + path = os.path.relpath(entry, relative) + else: + path = entry + + try: + if follow: + st = os.stat(entry) + else: + st = os.lstat(entry) + + if (st.st_dev, st.st_ino) in parents: + errors[path] = exceptions.FindError('Sym/hardlink loop found.') + continue + + parents = parents + [(st.st_dev, st.st_ino)] + if stat.S_ISDIR(st.st_mode): + for e in os.listdir(entry): + work.put((os.path.join(entry, e), parents)) + elif stat.S_ISREG(st.st_mode): + results[path] = st + elif stat.S_ISLNK(st.st_mode): + errors[path] = exceptions.FindError('Not following symlinks.') + else: + errors[path] = exceptions.FindError('Not a file or directory.') + + except OSError as e: + errors[path] = exceptions.FindError( + encoding.locale_decode(e.strerror), e.errno) + finally: + work.task_done()","def _find_worker(relative, follow, done, work, results, errors): + """"""Worker thread for collecting stat() results. + + :param str relative: directory to make results relative to + :param bool follow: if symlinks should be followed + :param threading.Event done: event indicating that all work has been done + :param queue.Queue work: queue of paths to process + :param dict results: shared dictionary for storing all the stat() results + :param dict errors: shared dictionary for storing any per path errors + """""" + while not done.is_set(): + try: + entry, parents = work.get(block=False) + except queue.Empty: + continue + + if relative: + path = os.path.relpath(entry, relative) + else: + path = entry + + try: + if follow: + st = os.stat(entry) + else: + st = os.lstat(entry) + + if (st.st_dev, st.st_ino) in parents: + errors[path] = exceptions.FindError('Sym/hardlink loop found.') + continue + + parents = parents + [(st.st_dev, st.st_ino)] + if stat.S_ISDIR(st.st_mode): + for e in os.listdir(entry): + work.put((os.path.join(entry, e), parents)) + elif stat.S_ISREG(st.st_mode): + results[path] = st + elif stat.S_ISLNK(st.st_mode): + errors[path] = exceptions.FindError('Not following symlinks.') + else: + errors[path] = exceptions.FindError('Not a file or directory.') + + except OSError as e: + errors[path] = exceptions.FindError(e.strerror, e.errno) + finally: + work.task_done()","[{'piece_type': 'error message', 'piece_content': '2015-02-04 06:30:11,901 ERROR [3714:MpdSession-27] pykka: Unhandled exception in MpdSession (urn:uuid:9595028c-486c-4c89-813a-785c3cafc057):\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 303, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 366, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/mpd/session.py"", line 41, in on_line_received\\nself.send_lines(response)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 428, in send_lines\\nself.connection.queue_send(self.encode(data))\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 189, in queue_send\\nself.send_buffer = self.send(self.send_buffer + data)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 202, in send\\nself.stop(\\'Unexpected client error: %s\\' % e)\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 16: ordinal not in range(128)'}, {'piece_type': 'error message', 'piece_content': 'file: local:track:Datarock/Kein%20Titel/11%20AudioTrack%2011.mp3\\nTime: 236\\nArtist: Datarock\\nTitle: AudioTrack 11\\nAlbum: Kein Titel\\nTrack: 11\\nGenre: Unbekannt\\nOK\\nERROR 2015-02-04 06:30:11,901 [3714:MpdSession-27] pykka\\nUnhandled exception in MpdSession (urn:uuid:9595028c-486c-4c89-813a-785c3cafc057):\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 303, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 366, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/mpd/session.py"", line 41, in on_line_received\\nself.send_lines(response)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 428, in send_lines\\nself.connection.queue_send(self.encode(data))\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 189, in queue_send\\nself.send_buffer = self.send(self.send_buffer + data)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 202, in send\\nself.stop(\\'Unexpected client error: %s\\' % e)\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 16: ordinal not in range(128)\\nDEBUG 2015-02-04 06:30:12,098 [3714:MpdSession-27] pykka\\nUnregistered MpdSession (urn:uuid:9595028c-486c-4c89-813a-785c3cafc057)'}, {'piece_type': 'other', 'piece_content': ""file: local:track:Datarock/Kein%20Titel/11%20AudioTrack%2011.mp3\\nTime: 236\\nArtist: Datarock\\nTitle: AudioTrack 11\\nAlbum: Kein Titel\\nTrack: 11\\nGenre: Unbekannt\\nOK\\nDEBUG 2015-02-10 16:49:56,626 [4213:MpdSession-11] mopidy.utils.network\\nUnexpected client error: error(32, 'Daten\\\\xc3\\\\xbcbergabe unterbrochen (broken pipe)')\\nDEBUG 2015-02-10 16:49:57,131 [4213:MainThread] pykka\\nRegistered MpdSession (urn:uuid:18e5db5c-fda7-4ee7-a183-7d84fdcff1ac)\\nDEBUG 2015-02-10 16:49:57,074 [4213:MpdSession-11] mopidy.mpd.session\\nRequest from [192.168.1.8]:56642: close\\nDEBUG 2015-02-10 16:49:57,177 [4213:MainThread] pykka\\nStarting MpdSession (urn:uuid:18e5db5c-fda7-4ee7-a183-7d84fdcff1ac)\\nDEBUG 2015-02-10 16:49:57,296 [4213:MpdSession-11] mopidy.mpd.session\\nResponse to [192.168.1.8]:56642: OK\\nDEBUG 2015-02-10 16:49:57,408 [4213:MpdSession-11] mopidy.utils.network\\nAlready stopping: Unexpected client error: error(9, 'Bad file descriptor')\\nINFO 2015-02-10 16:49:57,312 [4213:MpdSession-28] mopidy.mpd.session\\nNew MPD connection from [192.168.1.8]:56663\\nDEBUG 2015-02-10 16:49:57,499 [4213:MpdSession-11] mopidy.utils.network\\nAlready stopping: Client most likely disconnected.""}, {'piece_type': 'error message', 'piece_content': 'ERROR 2015-02-10 16:57:56,253 [4213:MpdSession-20] pykka\\nUnhandled exception in MpdSession (urn:uuid:68c56fc8-6342-41e4-b36d-ddc812875bc7):\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 303, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 366, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/mpd/session.py"", line 39, in on_line_received\\nformatting.indent(self.terminator.join(response)))\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/formatting.py"", line 13, in indent\\nresult = linebreak.join(lines)\\nMemoryError\\nDEBUG 2015-02-10 16:57:58,386 [4213:MpdSession-21] mopidy.utils.network\\nAlready stopping: Client most likely disconnected.\\nDEBUG 2015-02-10 16:57:58,434 [4213:MpdSession-20] pykka\\nUnregistered MpdSession (urn:uuid:68c56fc8-6342-41e4-b36d-ddc812875bc7)\\nDEBUG 2015-02-10 16:57:58,507 [4213:MpdSession-21] pykka\\nUnregistered MpdSession (urn:uuid:7af306aa-f2fe-4219-983f-dea5006c99b3)\\nDEBUG 2015-02-10 16:57:58,572 [4213:MpdSession-21] pykka\\nStopped MpdSession (urn:uuid:7af306aa-f2fe-4219-983f-dea5006c99b3)\\nDEBUG 2015-02-10 16:58:00,096 [4213:MpdSession-21] mopidy.utils.network\\nAlready stopping: Actor is shutting down.\\nDEBUG 2015-02-10 16:58:12,092 [4213:MainThread] mopidy.utils.network\\nAlready stopping: Client inactive for 60s; closing connection\\nDEBUG 2015-02-10 16:58:58,021 [4213:MpdSession-22] mopidy.utils.network\\nUnexpected client error: error(32, \\'Daten\\\\xc3\\\\xbcbergabe unterbrochen (broken pipe)\\')\\nDEBUG 2015-02-10 16:58:59,892 [4213:MpdSession-22] mopidy.mpd.session\\nRequest from [192.168.1.8]:56654: close\\nDEBUG 2015-02-10 16:58:59,938 [4213:MainThread] mopidy.utils.network\\nAlready stopping: Client inactive for 60s; closing connection\\nDEBUG 2015-02-10 16:59:00,001 [4213:MpdSession-22] mopidy.mpd.session\\nResponse to [192.168.1.8]:56654: OK\\nDEBUG 2015-02-10 16:59:00,004 [4213:MpdSession-22] mopidy.utils.network\\nAlready stopping: Unexpected client error: error(9, \\'Bad file descriptor\\')\\nDEBUG 2015-02-10 16:59:00,093 [4213:MpdSession-22] mopidy.utils.network\\nAlready stopping: Client most likely disconnected.\\nDEBUG 2015-02-10 16:59:00,193 [4213:MpdSession-22] pykka\\nUnregistered MpdSession (urn:uuid:710e58dd-1bf7-44d4-aaee-67cadedd419e)\\nDEBUG 2015-02-10 16:59:00,254 [4213:MpdSession-22] pykka\\nStopped MpdSession (urn:uuid:710e58dd-1bf7-44d4-aaee-67cadedd419e)\\nDEBUG 2015-02-10 16:59:00,291 [4213:MpdSession-22] mopidy.utils.network\\nAlready stopping: Actor is shutting down.\\nDEBUG 2015-02-10 17:00:04,191 [4213:MainThread] mopidy.utils.network\\nAlready stopping: Client inactive for 60s; closing connection\\nERROR 2015-02-10 17:00:44,073 [4213:MpdSession-24] pykka\\nUnhandled exception in MpdSession (urn:uuid:64d515a1-f2f1-454d-bc9e-c4eebb06c4ed):\\nTraceback (most recent call last):\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 303, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 366, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/mpd/session.py"", line 39, in on_line_received\\nformatting.indent(self.terminator.join(response)))\\nFile ""/usr/lib/python2.7/dist-packages/mopidy/utils/formatting.py"", line 13, in indent\\nresult = linebreak.join(lines)\\nMemoryError'}]","2015-02-04 06:30:11,901 ERROR [3714:MpdSession-27] pykka: Unhandled exception in MpdSession (urn:uuid:9595028c-486c-4c89-813a-785c3cafc057): +Traceback (most recent call last): +File ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 200, in _actor_loop +response = self._handle_receive(message) +File ""/usr/lib/python2.7/dist-packages/pykka/actor.py"", line 303, in _handle_receive +return self.on_receive(message) +File ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 366, in on_receive +self.on_line_received(line) +File ""/usr/lib/python2.7/dist-packages/mopidy/mpd/session.py"", line 41, in on_line_received +self.send_lines(response) +File ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 428, in send_lines +self.connection.queue_send(self.encode(data)) +File ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 189, in queue_send +self.send_buffer = self.send(self.send_buffer + data) +File ""/usr/lib/python2.7/dist-packages/mopidy/utils/network.py"", line 202, in send +self.stop('Unexpected client error: %s' % e) +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128)",UnicodeDecodeError +" def push(self, buffer_): + if self._source is None: + return False + + if buffer_ is None: + gst_logger.debug('Sending appsrc end-of-stream event.') + return self._source.emit('end-of-stream') == gst.FLOW_OK + else: + return self._source.emit('push-buffer', buffer_) == gst.FLOW_OK"," def push(self, buffer_): + if buffer_ is None: + gst_logger.debug('Sending appsrc end-of-stream event.') + return self._source.emit('end-of-stream') == gst.FLOW_OK + else: + return self._source.emit('push-buffer', buffer_) == gst.FLOW_OK","[{'piece_type': 'error message', 'piece_content': '^CINFO Interrupted. Exiting...\\nINFO Stopping Mopidy frontends\\nINFO Stopping Mopidy core\\nINFO Stopping Mopidy backends\\nFrom callback :\\nTraceback (most recent call last):\\nFile ""/home/jodal/dev/pyspotify2/spotify/session.py"", line 989, in music_delivery\\nspotify._session_instance, audio_format, frames_bytes, num_frames)\\nFile ""/home/jodal/dev/pyspotify2/spotify/utils.py"", line 108, in call\\nreturn listener.callback(*args)\\nFile ""/home/jodal/dev/mopidy-spotify/mopidy_spotify/playback.py"", line 159, in music_delivery_callback\\nif audio_actor.emit_data(buffer_).get():\\nFile ""build/bdist.linux-x86_64/egg/pykka/future.py"", line 299, in get\\nFile ""build/bdist.linux-x86_64/egg/pykka/actor.py"", line 200, in _actor_loop\\nFile ""build/bdist.linux-x86_64/egg/pykka/actor.py"", line 294, in _handle_receive\\nFile ""/home/jodal/dev/mopidy/mopidy/audio/actor.py"", line 587, in emit_data\\nreturn self._appsrc.push(buffer_)\\nFile ""/home/jodal/dev/mopidy/mopidy/audio/actor.py"", line 135, in push\\nreturn self._source.emit(\\'push-buffer\\', buffer_) == gst.FLOW_OK\\nAttributeError: \\'NoneType\\' object has no attribute \\'emit\\'\\nINFO Stopping Mopidy audio\\nINFO Stopping Mopidy mixer'}]","^CINFO Interrupted. Exiting... +INFO Stopping Mopidy frontends +INFO Stopping Mopidy core +INFO Stopping Mopidy backends +From callback : +Traceback (most recent call last): +File ""/home/jodal/dev/pyspotify2/spotify/session.py"", line 989, in music_delivery +spotify._session_instance, audio_format, frames_bytes, num_frames) +File ""/home/jodal/dev/pyspotify2/spotify/utils.py"", line 108, in call +return listener.callback(*args) +File ""/home/jodal/dev/mopidy-spotify/mopidy_spotify/playback.py"", line 159, in music_delivery_callback +if audio_actor.emit_data(buffer_).get(): +File ""build/bdist.linux-x86_64/egg/pykka/future.py"", line 299, in get +File ""build/bdist.linux-x86_64/egg/pykka/actor.py"", line 200, in _actor_loop +File ""build/bdist.linux-x86_64/egg/pykka/actor.py"", line 294, in _handle_receive +File ""/home/jodal/dev/mopidy/mopidy/audio/actor.py"", line 587, in emit_data +return self._appsrc.push(buffer_) +File ""/home/jodal/dev/mopidy/mopidy/audio/actor.py"", line 135, in push +return self._source.emit('push-buffer', buffer_) == gst.FLOW_OK +AttributeError: 'NoneType' object has no attribute 'emit' +INFO Stopping Mopidy audio +INFO Stopping Mopidy mixer",AttributeError +"def find_exact(tracks, query=None, uris=None): + # TODO Only return results within URI roots given by ``uris`` + + if query is None: + query = {} + + _validate_query(query) + + for (field, values) in query.items(): + if not hasattr(values, '__iter__'): + values = [values] + # FIXME this is bound to be slow for large libraries + for value in values: + if field == 'track_no': + q = _convert_to_int(value) + else: + q = value.strip() + + uri_filter = lambda t: q == t.uri + track_name_filter = lambda t: q == t.name + album_filter = lambda t: q == getattr( + getattr(t, 'album', None), 'name', None) + artist_filter = lambda t: filter( + lambda a: q == a.name, t.artists) + albumartist_filter = lambda t: any([ + q == a.name + for a in getattr(t.album, 'artists', [])]) + composer_filter = lambda t: any([ + q == a.name + for a in getattr(t, 'composers', [])]) + performer_filter = lambda t: any([ + q == a.name + for a in getattr(t, 'performers', [])]) + track_no_filter = lambda t: q == t.track_no + genre_filter = lambda t: t.genre and q == t.genre + date_filter = lambda t: q == t.date + comment_filter = lambda t: q == t.comment + any_filter = lambda t: ( + uri_filter(t) or + track_name_filter(t) or + album_filter(t) or + artist_filter(t) or + albumartist_filter(t) or + composer_filter(t) or + performer_filter(t) or + track_no_filter(t) or + genre_filter(t) or + date_filter(t) or + comment_filter(t)) + + if field == 'uri': + tracks = filter(uri_filter, tracks) + elif field == 'track_name': + tracks = filter(track_name_filter, tracks) + elif field == 'album': + tracks = filter(album_filter, tracks) + elif field == 'artist': + tracks = filter(artist_filter, tracks) + elif field == 'albumartist': + tracks = filter(albumartist_filter, tracks) + elif field == 'composer': + tracks = filter(composer_filter, tracks) + elif field == 'performer': + tracks = filter(performer_filter, tracks) + elif field == 'track_no': + tracks = filter(track_no_filter, tracks) + elif field == 'genre': + tracks = filter(genre_filter, tracks) + elif field == 'date': + tracks = filter(date_filter, tracks) + elif field == 'comment': + tracks = filter(comment_filter, tracks) + elif field == 'any': + tracks = filter(any_filter, tracks) + else: + raise LookupError('Invalid lookup field: %s' % field) + + # TODO: add local:search: + return SearchResult(uri='local:search', tracks=tracks)","def find_exact(tracks, query=None, uris=None): + # TODO Only return results within URI roots given by ``uris`` + + if query is None: + query = {} + + _validate_query(query) + + for (field, values) in query.items(): + if not hasattr(values, '__iter__'): + values = [values] + # FIXME this is bound to be slow for large libraries + for value in values: + if field == 'track_no': + q = _convert_to_int(value) + else: + q = value.strip() + + uri_filter = lambda t: q == t.uri + track_name_filter = lambda t: q == t.name + album_filter = lambda t: q == getattr(t, 'album', Album()).name + artist_filter = lambda t: filter( + lambda a: q == a.name, t.artists) + albumartist_filter = lambda t: any([ + q == a.name + for a in getattr(t.album, 'artists', [])]) + composer_filter = lambda t: any([ + q == a.name + for a in getattr(t, 'composers', [])]) + performer_filter = lambda t: any([ + q == a.name + for a in getattr(t, 'performers', [])]) + track_no_filter = lambda t: q == t.track_no + genre_filter = lambda t: t.genre and q == t.genre + date_filter = lambda t: q == t.date + comment_filter = lambda t: q == t.comment + any_filter = lambda t: ( + uri_filter(t) or + track_name_filter(t) or + album_filter(t) or + artist_filter(t) or + albumartist_filter(t) or + composer_filter(t) or + performer_filter(t) or + track_no_filter(t) or + genre_filter(t) or + date_filter(t) or + comment_filter(t)) + + if field == 'uri': + tracks = filter(uri_filter, tracks) + elif field == 'track_name': + tracks = filter(track_name_filter, tracks) + elif field == 'album': + tracks = filter(album_filter, tracks) + elif field == 'artist': + tracks = filter(artist_filter, tracks) + elif field == 'albumartist': + tracks = filter(albumartist_filter, tracks) + elif field == 'composer': + tracks = filter(composer_filter, tracks) + elif field == 'performer': + tracks = filter(performer_filter, tracks) + elif field == 'track_no': + tracks = filter(track_no_filter, tracks) + elif field == 'genre': + tracks = filter(genre_filter, tracks) + elif field == 'date': + tracks = filter(date_filter, tracks) + elif field == 'comment': + tracks = filter(comment_filter, tracks) + elif field == 'any': + tracks = filter(any_filter, tracks) + else: + raise LookupError('Invalid lookup field: %s' % field) + + # TODO: add local:search: + return SearchResult(uri='local:search', tracks=tracks)","[{'piece_type': 'other', 'piece_content': ""Track(artists=[Artist(name=u'Daktyl')], bitrate=320000, comment=u'Visit http://diehighrecords.bandcamp.com', date=u'2014-01-01', last_modified=1397622512, length=208065, name=u'244', uri=u'local:track:sauza/244%201.mp3')""}, {'piece_type': 'error message', 'piece_content': 'INFO New MPD connection from [::1]:55924\\nERROR Unhandled exception in MpdSession (urn:uuid:127f99a4-9753-4960-9b72-368255948637):\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 303, in _handle_receive\\nreturn self.on_receive(message)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/utils/network.py"", line 366, in on_receive\\nself.on_line_received(line)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/session.py"", line 33, in on_line_received\\nresponse = self.dispatcher.handle_request(line)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 46, in handle_request\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 75, in _catch_mpd_ack_errors_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 85, in _authenticate_filter\\nreturn self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 104, in _command_list_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 133, in _idle_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 146, in _add_ok_filter\\nresponse = self._call_next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter\\nreturn next_filter(request, response, filter_chain)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 158, in _call_handler_filter\\nresponse = self._format_response(self._call_handler(request))\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 167, in _call_handler\\nreturn protocol.commands.call(tokens, context=self.context)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 178, in call\\nreturn self.handlers[tokens[0]](context, *tokens[1:])\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 140, in validate\\nreturn func(*args, **kwargs)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/music_db.py"", line 135, in find\\nresults = context.core.library.find_exact(**query).get()\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/future.py"", line 299, in get\\nexec(\\'raise exc_info[0], exc_info[1], exc_info[2]\\')\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 294, in _handle_receive\\nreturn callee(*message[\\'args\\'], **message[\\'kwargs\\'])\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/core/library.py"", line 118, in find_exact\\nreturn [result for result in pykka.get_all(futures) if result]\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/future.py"", line 330, in get_all\\nreturn [future.get(timeout=timeout) for future in futures]\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/future.py"", line 299, in get\\nexec(\\'raise exc_info[0], exc_info[1], exc_info[2]\\')\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 200, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 294, in _handle_receive\\nreturn callee(*message[\\'args\\'], **message[\\'kwargs\\'])\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/local/library.py"", line 47, in find_exact\\nreturn self._library.search(query=query, uris=uris, exact=True)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/local/json.py"", line 162, in search\\nreturn search.find_exact(tracks, query=query, uris=uris)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/local/search.py"", line 60, in find_exact\\ntracks = filter(album_filter, tracks)\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/local/search.py"", line 26, in \\nalbum_filter = lambda t: q == getattr(t, \\'album\\', Album()).name\\nAttributeError: \\'NoneType\\' object has no attribute \\'name\\'\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python2.7/site-packages/mopidy/utils/network.py"", line 272, in recv_callback\\nself.actor_ref.tell({\\'close\\': True})\\nFile ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 437, in tell\\nraise _ActorDeadError(\\'%s not found\\' % self)\\npykka.exceptions.ActorDeadError: MpdSession (urn:uuid:127f99a4-9753-4960-9b72-368255948637) not found'}]","INFO New MPD connection from [::1]:55924 +ERROR Unhandled exception in MpdSession (urn:uuid:127f99a4-9753-4960-9b72-368255948637): +Traceback (most recent call last): +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 200, in _actor_loop +response = self._handle_receive(message) +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 303, in _handle_receive +return self.on_receive(message) +File ""/usr/local/lib/python2.7/site-packages/mopidy/utils/network.py"", line 366, in on_receive +self.on_line_received(line) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/session.py"", line 33, in on_line_received +response = self.dispatcher.handle_request(line) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 46, in handle_request +return self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 75, in _catch_mpd_ack_errors_filter +return self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 85, in _authenticate_filter +return self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 104, in _command_list_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 133, in _idle_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 146, in _add_ok_filter +response = self._call_next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 67, in _call_next_filter +return next_filter(request, response, filter_chain) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 158, in _call_handler_filter +response = self._format_response(self._call_handler(request)) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/dispatcher.py"", line 167, in _call_handler +return protocol.commands.call(tokens, context=self.context) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 178, in call +return self.handlers[tokens[0]](context, *tokens[1:]) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/__init__.py"", line 140, in validate +return func(*args, **kwargs) +File ""/usr/local/lib/python2.7/site-packages/mopidy/mpd/protocol/music_db.py"", line 135, in find +results = context.core.library.find_exact(**query).get() +File ""/usr/local/lib/python2.7/site-packages/pykka/future.py"", line 299, in get +exec('raise exc_info[0], exc_info[1], exc_info[2]') +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 200, in _actor_loop +response = self._handle_receive(message) +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 294, in _handle_receive +return callee(*message['args'], **message['kwargs']) +File ""/usr/local/lib/python2.7/site-packages/mopidy/core/library.py"", line 118, in find_exact +return [result for result in pykka.get_all(futures) if result] +File ""/usr/local/lib/python2.7/site-packages/pykka/future.py"", line 330, in get_all +return [future.get(timeout=timeout) for future in futures] +File ""/usr/local/lib/python2.7/site-packages/pykka/future.py"", line 299, in get +exec('raise exc_info[0], exc_info[1], exc_info[2]') +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 200, in _actor_loop +response = self._handle_receive(message) +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 294, in _handle_receive +return callee(*message['args'], **message['kwargs']) +File ""/usr/local/lib/python2.7/site-packages/mopidy/local/library.py"", line 47, in find_exact +return self._library.search(query=query, uris=uris, exact=True) +File ""/usr/local/lib/python2.7/site-packages/mopidy/local/json.py"", line 162, in search +return search.find_exact(tracks, query=query, uris=uris) +File ""/usr/local/lib/python2.7/site-packages/mopidy/local/search.py"", line 60, in find_exact +tracks = filter(album_filter, tracks) +File ""/usr/local/lib/python2.7/site-packages/mopidy/local/search.py"", line 26, in +album_filter = lambda t: q == getattr(t, 'album', Album()).name +AttributeError: 'NoneType' object has no attribute 'name' +Traceback (most recent call last): +File ""/usr/local/lib/python2.7/site-packages/mopidy/utils/network.py"", line 272, in recv_callback +self.actor_ref.tell({'close': True}) +File ""/usr/local/lib/python2.7/site-packages/pykka/actor.py"", line 437, in tell +raise _ActorDeadError('%s not found' % self) +pykka.exceptions.ActorDeadError: MpdSession (urn:uuid:127f99a4-9753-4960-9b72-368255948637) not found",AttributeError +"def validate_extension(extension): + """"""Verify extension's dependencies and environment. + + :param extensions: an extension to check + :returns: if extension should be run + """""" + + logger.debug('Validating extension: %s', extension.ext_name) + + if extension.ext_name != extension.entry_point.name: + logger.warning( + 'Disabled extension %(ep)s: entry point name (%(ep)s) ' + 'does not match extension name (%(ext)s)', + {'ep': extension.entry_point.name, 'ext': extension.ext_name}) + return False + + try: + extension.entry_point.require() + except pkg_resources.DistributionNotFound as ex: + logger.info( + 'Disabled extension %s: Dependency %s not found', + extension.ext_name, ex) + return False + except pkg_resources.VersionConflict as ex: + if len(ex.args) == 2: + found, required = ex.args + logger.info( + 'Disabled extension %s: %s required, but found %s at %s', + extension.ext_name, required, found, found.location) + else: + logger.info('Disabled extension %s: %s', extension.ext_name, ex) + return False + + try: + extension.validate_environment() + except exceptions.ExtensionError as ex: + logger.info( + 'Disabled extension %s: %s', extension.ext_name, ex.message) + return False + + return True","def validate_extension(extension): + """"""Verify extension's dependencies and environment. + + :param extensions: an extension to check + :returns: if extension should be run + """""" + + logger.debug('Validating extension: %s', extension.ext_name) + + if extension.ext_name != extension.entry_point.name: + logger.warning( + 'Disabled extension %(ep)s: entry point name (%(ep)s) ' + 'does not match extension name (%(ext)s)', + {'ep': extension.entry_point.name, 'ext': extension.ext_name}) + return False + + try: + extension.entry_point.require() + except pkg_resources.DistributionNotFound as ex: + logger.info( + 'Disabled extension %s: Dependency %s not found', + extension.ext_name, ex) + return False + except pkg_resources.VersionConflict as ex: + found, required = ex.args + logger.info( + 'Disabled extension %s: %s required, but found %s at %s', + extension.ext_name, required, found, found.location) + return False + + try: + extension.validate_environment() + except exceptions.ExtensionError as ex: + logger.info( + 'Disabled extension %s: %s', extension.ext_name, ex.message) + return False + + return True","[{'piece_type': 'error message', 'piece_content': '2014-12-15 19:54:53,052 INFO [7923:MainThread] mopidy.__main__: Starting Mopidy 0.19.4\\n2014-12-15 19:54:53,433 INFO [7923:MainThread] mopidy.config: Loading config from: builtin defaults, /usr/share/mopidy/conf.d, /etc/mopidy/mopidy.conf, command line options\\n2014-12-15 19:54:54,860 ERROR [7923:MainThread] mopidy.__main__: need more than 1 value to unpack\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python2.7/dist-packages/mopidy/__main__.py"", line 79, in main\\nif not ext.validate_extension(extension):\\nFile ""/usr/local/lib/python2.7/dist-packages/mopidy/ext.py"", line 190, in validate_extension\\nfound, required = ex.args\\nValueError: need more than 1 value to unpack'}]","2014-12-15 19:54:53,052 INFO [7923:MainThread] mopidy.__main__: Starting Mopidy 0.19.4 +2014-12-15 19:54:53,433 INFO [7923:MainThread] mopidy.config: Loading config from: builtin defaults, /usr/share/mopidy/conf.d, /etc/mopidy/mopidy.conf, command line options +2014-12-15 19:54:54,860 ERROR [7923:MainThread] mopidy.__main__: need more than 1 value to unpack +Traceback (most recent call last): +File ""/usr/local/lib/python2.7/dist-packages/mopidy/__main__.py"", line 79, in main +if not ext.validate_extension(extension): +File ""/usr/local/lib/python2.7/dist-packages/mopidy/ext.py"", line 190, in validate_extension +found, required = ex.args +ValueError: need more than 1 value to unpack",ValueError +" def recv_callback(self, fd, flags): + if flags & (gobject.IO_ERR | gobject.IO_HUP): + self.stop('Bad client flags: %s' % flags) + return True + + try: + data = self.sock.recv(4096) + except socket.error as e: + if e.errno not in (errno.EWOULDBLOCK, errno.EINTR): + self.stop('Unexpected client error: %s' % e) + return True + + if not data: + self.disable_recv() + self.actor_ref.tell({'close': True}) + return True + + try: + self.actor_ref.tell({'received': data}) + except pykka.ActorDeadError: + self.stop('Actor is dead.') + + return True"," def recv_callback(self, fd, flags): + if flags & (gobject.IO_ERR | gobject.IO_HUP): + self.stop('Bad client flags: %s' % flags) + return True + + try: + data = self.sock.recv(4096) + except socket.error as e: + if e.errno not in (errno.EWOULDBLOCK, errno.EINTR): + self.stop('Unexpected client error: %s' % e) + return True + + if not data: + self.actor_ref.tell({'close': True}) + self.disable_recv() + return True + + try: + self.actor_ref.tell({'received': data}) + except pykka.ActorDeadError: + self.stop('Actor is dead.') + + return True","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/adamcik/dev/mopidy/mopidy/utils/network.py"", line 272, in recv_callback\\nself.disable_recv()\\nFile ""/home/adamcik/dev/mopidy/mopidy/utils/network.py"", line 236, in disable_recv\\ngobject.source_remove(self.recv_id)\\nTypeError: an integer is required'}]","Traceback (most recent call last): +File ""/home/adamcik/dev/mopidy/mopidy/utils/network.py"", line 272, in recv_callback +self.disable_recv() +File ""/home/adamcik/dev/mopidy/mopidy/utils/network.py"", line 236, in disable_recv +gobject.source_remove(self.recv_id) +TypeError: an integer is required",TypeError +" def publish(self): + if not dbus: + logger.debug('Zeroconf publish failed: dbus not installed.') + return False + + try: + bus = dbus.SystemBus() + except dbus.exceptions.DBusException as e: + logger.debug('Zeroconf publish failed: %s', e) + return False + + if not bus.name_has_owner('org.freedesktop.Avahi'): + logger.debug('Zeroconf publish failed: Avahi service not running.') + return False + + server = dbus.Interface(bus.get_object('org.freedesktop.Avahi', '/'), + 'org.freedesktop.Avahi.Server') + + self.group = dbus.Interface( + bus.get_object('org.freedesktop.Avahi', server.EntryGroupNew()), + 'org.freedesktop.Avahi.EntryGroup') + + try: + text = [_convert_text_to_dbus_bytes(t) for t in self.text] + self.group.AddService( + _AVAHI_IF_UNSPEC, _AVAHI_PROTO_UNSPEC, + dbus.UInt32(_AVAHI_PUBLISHFLAGS_NONE), self.name, self.stype, + self.domain, self.host, dbus.UInt16(self.port), text) + except dbus.exceptions.DBusException as e: + logger.debug('Zeroconf publish failed: %s', e) + return False + + self.group.Commit() + return True"," def publish(self): + if not dbus: + logger.debug('Zeroconf publish failed: dbus not installed.') + return False + + try: + bus = dbus.SystemBus() + except dbus.exceptions.DBusException as e: + logger.debug('Zeroconf publish failed: %s', e) + return False + + if not bus.name_has_owner('org.freedesktop.Avahi'): + logger.debug('Zeroconf publish failed: Avahi service not running.') + return False + + server = dbus.Interface(bus.get_object('org.freedesktop.Avahi', '/'), + 'org.freedesktop.Avahi.Server') + + self.group = dbus.Interface( + bus.get_object('org.freedesktop.Avahi', server.EntryGroupNew()), + 'org.freedesktop.Avahi.EntryGroup') + + text = [_convert_text_to_dbus_bytes(t) for t in self.text] + self.group.AddService(_AVAHI_IF_UNSPEC, _AVAHI_PROTO_UNSPEC, + dbus.UInt32(_AVAHI_PUBLISHFLAGS_NONE), + self.name, self.stype, self.domain, self.host, + dbus.UInt16(self.port), text) + + self.group.Commit() + return True","[{'piece_type': 'error message', 'piece_content': 'INFO 2013-11-13 23:26:28,001 [4304:MainThread] mopidy.frontends.mpd\\nMPD server running at [::]:6600\\nERROR 2013-11-13 23:26:28,013 [4304:MpdFrontend-5] pykka\\nUnhandled exception in MpdFrontend (urn:uuid:93b3b156-44ca-42de-a0cf-602474d1c582):\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python2.7/dist-packages/Pykka-1.2.0-py2.7.egg/pykka/actor.py"", line 191, in _actor_loop\\nself.on_start()\\nFile ""/home/zenith/dev/mopidy/mopidy/frontends/mpd/actor.py"", line 49, in on_start\\nif self.zeroconf_service.publish():\\nFile ""/home/zenith/dev/mopidy/mopidy/utils/zeroconf.py"", line 73, in publish\\ndbus.UInt16(self.port), text)\\nFile ""/usr/lib/python2.7/dist-packages/dbus/proxies.py"", line 70, in __call__\\nreturn self._proxy_method(*args, **keywords)\\nFile ""/usr/lib/python2.7/dist-packages/dbus/proxies.py"", line 145, in __call__\\n**keywords)\\nFile ""/usr/lib/python2.7/dist-packages/dbus/connection.py"", line 651, in call_blocking\\nmessage, timeout)\\nDBusException: org.freedesktop.Avahi.InvalidHostNameError: Invalid host name'}]","INFO 2013-11-13 23:26:28,001 [4304:MainThread] mopidy.frontends.mpd +MPD server running at [::]:6600 +ERROR 2013-11-13 23:26:28,013 [4304:MpdFrontend-5] pykka +Unhandled exception in MpdFrontend (urn:uuid:93b3b156-44ca-42de-a0cf-602474d1c582): +Traceback (most recent call last): +File ""/usr/local/lib/python2.7/dist-packages/Pykka-1.2.0-py2.7.egg/pykka/actor.py"", line 191, in _actor_loop +self.on_start() +File ""/home/zenith/dev/mopidy/mopidy/frontends/mpd/actor.py"", line 49, in on_start +if self.zeroconf_service.publish(): +File ""/home/zenith/dev/mopidy/mopidy/utils/zeroconf.py"", line 73, in publish +dbus.UInt16(self.port), text) +File ""/usr/lib/python2.7/dist-packages/dbus/proxies.py"", line 70, in __call__ +return self._proxy_method(*args, **keywords) +File ""/usr/lib/python2.7/dist-packages/dbus/proxies.py"", line 145, in __call__ +**keywords) +File ""/usr/lib/python2.7/dist-packages/dbus/connection.py"", line 651, in call_blocking +message, timeout) +DBusException: org.freedesktop.Avahi.InvalidHostNameError: Invalid host name",DBusException +"def parse_options(): + parser = optparse.OptionParser( + version='Mopidy %s' % versioning.get_version()) + # NOTE Python 2.6: To support Python versions < 2.6.2rc1 we must use + # bytestrings for the first argument to ``add_option`` + # See https://github.com/mopidy/mopidy/issues/302 for details + parser.add_option( + b'--help-gst', + action='store_true', dest='help_gst', + help='show GStreamer help options') + parser.add_option( + b'-i', '--interactive', + action='store_true', dest='interactive', + help='ask interactively for required settings which are missing') + parser.add_option( + b'-q', '--quiet', + action='store_const', const=0, dest='verbosity_level', + help='less output (warning level)') + parser.add_option( + b'-v', '--verbose', + action='count', default=1, dest='verbosity_level', + help='more output (debug level)') + parser.add_option( + b'--save-debug-log', + action='store_true', dest='save_debug_log', + help='save debug log to ""./mopidy.log""') + parser.add_option( + b'--list-settings', + action='callback', + callback=settings_utils.list_settings_optparse_callback, + help='list current settings') + parser.add_option( + b'--list-deps', + action='callback', callback=deps.list_deps_optparse_callback, + help='list dependencies and their versions') + parser.add_option( + b'--debug-thread', + action='store_true', dest='debug_thread', + help='run background thread that dumps tracebacks on SIGUSR1') + return parser.parse_args(args=mopidy_args)[0]","def parse_options(): + parser = optparse.OptionParser( + version='Mopidy %s' % versioning.get_version()) + parser.add_option( + '--help-gst', + action='store_true', dest='help_gst', + help='show GStreamer help options') + parser.add_option( + '-i', '--interactive', + action='store_true', dest='interactive', + help='ask interactively for required settings which are missing') + parser.add_option( + '-q', '--quiet', + action='store_const', const=0, dest='verbosity_level', + help='less output (warning level)') + parser.add_option( + '-v', '--verbose', + action='count', default=1, dest='verbosity_level', + help='more output (debug level)') + parser.add_option( + '--save-debug-log', + action='store_true', dest='save_debug_log', + help='save debug log to ""./mopidy.log""') + parser.add_option( + '--list-settings', + action='callback', + callback=settings_utils.list_settings_optparse_callback, + help='list current settings') + parser.add_option( + '--list-deps', + action='callback', callback=deps.list_deps_optparse_callback, + help='list dependencies and their versions') + parser.add_option( + '--debug-thread', + action='store_true', dest='debug_thread', + help='run background thread that dumps tracebacks on SIGUSR1') + return parser.parse_args(args=mopidy_args)[0]","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def _convert_mpd_data(data, tracks, music_dir): + if not data: + return + + # NOTE: kwargs are explicitly made bytestrings to work on Python + # 2.6.0/2.6.1. See https://github.com/mopidy/mopidy/issues/302 for details. + + track_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + albumartist_kwargs = {} + + if 'track' in data: + if '/' in data['track']: + album_kwargs[b'num_tracks'] = int(data['track'].split('/')[1]) + track_kwargs[b'track_no'] = int(data['track'].split('/')[0]) + else: + track_kwargs[b'track_no'] = int(data['track']) + + if 'artist' in data: + artist_kwargs[b'name'] = data['artist'] + albumartist_kwargs[b'name'] = data['artist'] + + if 'albumartist' in data: + albumartist_kwargs[b'name'] = data['albumartist'] + + if 'album' in data: + album_kwargs[b'name'] = data['album'] + + if 'title' in data: + track_kwargs[b'name'] = data['title'] + + if 'date' in data: + track_kwargs[b'date'] = data['date'] + + if 'musicbrainz_trackid' in data: + track_kwargs[b'musicbrainz_id'] = data['musicbrainz_trackid'] + + if 'musicbrainz_albumid' in data: + album_kwargs[b'musicbrainz_id'] = data['musicbrainz_albumid'] + + if 'musicbrainz_artistid' in data: + artist_kwargs[b'musicbrainz_id'] = data['musicbrainz_artistid'] + + if 'musicbrainz_albumartistid' in data: + albumartist_kwargs[b'musicbrainz_id'] = ( + data['musicbrainz_albumartistid']) + + if data['file'][0] == '/': + path = data['file'][1:] + else: + path = data['file'] + path = urllib.unquote(path) + + if artist_kwargs: + artist = Artist(**artist_kwargs) + track_kwargs[b'artists'] = [artist] + + if albumartist_kwargs: + albumartist = Artist(**albumartist_kwargs) + album_kwargs[b'artists'] = [albumartist] + + if album_kwargs: + album = Album(**album_kwargs) + track_kwargs[b'album'] = album + + track_kwargs[b'uri'] = path_to_uri(music_dir, path) + track_kwargs[b'length'] = int(data.get('time', 0)) * 1000 + + track = Track(**track_kwargs) + tracks.add(track)","def _convert_mpd_data(data, tracks, music_dir): + if not data: + return + + track_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + albumartist_kwargs = {} + + if 'track' in data: + if '/' in data['track']: + album_kwargs['num_tracks'] = int(data['track'].split('/')[1]) + track_kwargs['track_no'] = int(data['track'].split('/')[0]) + else: + track_kwargs['track_no'] = int(data['track']) + + if 'artist' in data: + artist_kwargs['name'] = data['artist'] + albumartist_kwargs['name'] = data['artist'] + + if 'albumartist' in data: + albumartist_kwargs['name'] = data['albumartist'] + + if 'album' in data: + album_kwargs['name'] = data['album'] + + if 'title' in data: + track_kwargs['name'] = data['title'] + + if 'date' in data: + track_kwargs['date'] = data['date'] + + if 'musicbrainz_trackid' in data: + track_kwargs['musicbrainz_id'] = data['musicbrainz_trackid'] + + if 'musicbrainz_albumid' in data: + album_kwargs['musicbrainz_id'] = data['musicbrainz_albumid'] + + if 'musicbrainz_artistid' in data: + artist_kwargs['musicbrainz_id'] = data['musicbrainz_artistid'] + + if 'musicbrainz_albumartistid' in data: + albumartist_kwargs['musicbrainz_id'] = ( + data['musicbrainz_albumartistid']) + + if data['file'][0] == '/': + path = data['file'][1:] + else: + path = data['file'] + path = urllib.unquote(path) + + if artist_kwargs: + artist = Artist(**artist_kwargs) + track_kwargs['artists'] = [artist] + + if albumartist_kwargs: + albumartist = Artist(**albumartist_kwargs) + album_kwargs['artists'] = [albumartist] + + if album_kwargs: + album = Album(**album_kwargs) + track_kwargs['album'] = album + + track_kwargs['uri'] = path_to_uri(music_dir, path) + track_kwargs['length'] = int(data.get('time', 0)) * 1000 + + track = Track(**track_kwargs) + tracks.add(track)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def translator(data): + albumartist_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + track_kwargs = {} + + # NOTE: kwargs are explicitly made bytestrings to work on Python + # 2.6.0/2.6.1. See https://github.com/mopidy/mopidy/issues/302 for + # details. + + def _retrieve(source_key, target_key, target): + if source_key in data: + target[str(target_key)] = data[source_key] + + _retrieve(gst.TAG_ALBUM, 'name', album_kwargs) + _retrieve(gst.TAG_TRACK_COUNT, 'num_tracks', album_kwargs) + _retrieve(gst.TAG_ARTIST, 'name', artist_kwargs) + + if gst.TAG_DATE in data and data[gst.TAG_DATE]: + date = data[gst.TAG_DATE] + try: + date = datetime.date(date.year, date.month, date.day) + except ValueError: + pass # Ignore invalid dates + else: + track_kwargs[b'date'] = date.isoformat() + + _retrieve(gst.TAG_TITLE, 'name', track_kwargs) + _retrieve(gst.TAG_TRACK_NUMBER, 'track_no', track_kwargs) + + # Following keys don't seem to have TAG_* constant. + _retrieve('album-artist', 'name', albumartist_kwargs) + _retrieve('musicbrainz-trackid', 'musicbrainz_id', track_kwargs) + _retrieve('musicbrainz-artistid', 'musicbrainz_id', artist_kwargs) + _retrieve('musicbrainz-albumid', 'musicbrainz_id', album_kwargs) + _retrieve( + 'musicbrainz-albumartistid', 'musicbrainz_id', albumartist_kwargs) + + if albumartist_kwargs: + album_kwargs[b'artists'] = [Artist(**albumartist_kwargs)] + + track_kwargs['uri'] = data['uri'] + track_kwargs['length'] = data[gst.TAG_DURATION] + track_kwargs['album'] = Album(**album_kwargs) + track_kwargs['artists'] = [Artist(**artist_kwargs)] + + return Track(**track_kwargs)","def translator(data): + albumartist_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + track_kwargs = {} + + def _retrieve(source_key, target_key, target): + if source_key in data: + target[target_key] = data[source_key] + + _retrieve(gst.TAG_ALBUM, 'name', album_kwargs) + _retrieve(gst.TAG_TRACK_COUNT, 'num_tracks', album_kwargs) + _retrieve(gst.TAG_ARTIST, 'name', artist_kwargs) + + if gst.TAG_DATE in data and data[gst.TAG_DATE]: + date = data[gst.TAG_DATE] + try: + date = datetime.date(date.year, date.month, date.day) + except ValueError: + pass # Ignore invalid dates + else: + track_kwargs['date'] = date.isoformat() + + _retrieve(gst.TAG_TITLE, 'name', track_kwargs) + _retrieve(gst.TAG_TRACK_NUMBER, 'track_no', track_kwargs) + + # Following keys don't seem to have TAG_* constant. + _retrieve('album-artist', 'name', albumartist_kwargs) + _retrieve('musicbrainz-trackid', 'musicbrainz_id', track_kwargs) + _retrieve('musicbrainz-artistid', 'musicbrainz_id', artist_kwargs) + _retrieve('musicbrainz-albumid', 'musicbrainz_id', album_kwargs) + _retrieve( + 'musicbrainz-albumartistid', 'musicbrainz_id', albumartist_kwargs) + + if albumartist_kwargs: + album_kwargs['artists'] = [Artist(**albumartist_kwargs)] + + track_kwargs['uri'] = data['uri'] + track_kwargs['length'] = data[gst.TAG_DURATION] + track_kwargs['album'] = Album(**album_kwargs) + track_kwargs['artists'] = [Artist(**artist_kwargs)] + + return Track(**track_kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def _retrieve(source_key, target_key, target): + if source_key in data: + target[str(target_key)] = data[source_key]"," def _retrieve(source_key, target_key, target): + if source_key in data: + target[target_key] = data[source_key]","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def translator(data): + albumartist_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + track_kwargs = {} + + # NOTE: kwargs are explicitly made bytestrings to work on Python + # 2.6.0/2.6.1. See https://github.com/mopidy/mopidy/issues/302 for + # details. + + def _retrieve(source_key, target_key, target): + if source_key in data: + target[str(target_key)] = data[source_key] + + _retrieve(gst.TAG_ALBUM, 'name', album_kwargs) + _retrieve(gst.TAG_TRACK_COUNT, 'num_tracks', album_kwargs) + _retrieve(gst.TAG_ARTIST, 'name', artist_kwargs) + + if gst.TAG_DATE in data and data[gst.TAG_DATE]: + date = data[gst.TAG_DATE] + try: + date = datetime.date(date.year, date.month, date.day) + except ValueError: + pass # Ignore invalid dates + else: + track_kwargs[b'date'] = date.isoformat() + + _retrieve(gst.TAG_TITLE, 'name', track_kwargs) + _retrieve(gst.TAG_TRACK_NUMBER, 'track_no', track_kwargs) + + # Following keys don't seem to have TAG_* constant. + _retrieve('album-artist', 'name', albumartist_kwargs) + _retrieve('musicbrainz-trackid', 'musicbrainz_id', track_kwargs) + _retrieve('musicbrainz-artistid', 'musicbrainz_id', artist_kwargs) + _retrieve('musicbrainz-albumid', 'musicbrainz_id', album_kwargs) + _retrieve( + 'musicbrainz-albumartistid', 'musicbrainz_id', albumartist_kwargs) + + if albumartist_kwargs: + album_kwargs[b'artists'] = [Artist(**albumartist_kwargs)] + + track_kwargs[b'uri'] = data['uri'] + track_kwargs[b'length'] = data[gst.TAG_DURATION] + track_kwargs[b'album'] = Album(**album_kwargs) + track_kwargs[b'artists'] = [Artist(**artist_kwargs)] + + return Track(**track_kwargs)","def translator(data): + albumartist_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + track_kwargs = {} + + # NOTE: kwargs are explicitly made bytestrings to work on Python + # 2.6.0/2.6.1. See https://github.com/mopidy/mopidy/issues/302 for + # details. + + def _retrieve(source_key, target_key, target): + if source_key in data: + target[str(target_key)] = data[source_key] + + _retrieve(gst.TAG_ALBUM, 'name', album_kwargs) + _retrieve(gst.TAG_TRACK_COUNT, 'num_tracks', album_kwargs) + _retrieve(gst.TAG_ARTIST, 'name', artist_kwargs) + + if gst.TAG_DATE in data and data[gst.TAG_DATE]: + date = data[gst.TAG_DATE] + try: + date = datetime.date(date.year, date.month, date.day) + except ValueError: + pass # Ignore invalid dates + else: + track_kwargs[b'date'] = date.isoformat() + + _retrieve(gst.TAG_TITLE, 'name', track_kwargs) + _retrieve(gst.TAG_TRACK_NUMBER, 'track_no', track_kwargs) + + # Following keys don't seem to have TAG_* constant. + _retrieve('album-artist', 'name', albumartist_kwargs) + _retrieve('musicbrainz-trackid', 'musicbrainz_id', track_kwargs) + _retrieve('musicbrainz-artistid', 'musicbrainz_id', artist_kwargs) + _retrieve('musicbrainz-albumid', 'musicbrainz_id', album_kwargs) + _retrieve( + 'musicbrainz-albumartistid', 'musicbrainz_id', albumartist_kwargs) + + if albumartist_kwargs: + album_kwargs[b'artists'] = [Artist(**albumartist_kwargs)] + + track_kwargs['uri'] = data['uri'] + track_kwargs['length'] = data[gst.TAG_DURATION] + track_kwargs['album'] = Album(**album_kwargs) + track_kwargs['artists'] = [Artist(**artist_kwargs)] + + return Track(**track_kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def parse_options(): + parser = optparse.OptionParser( + version='Mopidy %s' % versioning.get_version()) + # NOTE Python 2.6: To support Python versions < 2.6.2rc1 we must use + # bytestrings for the first argument to ``add_option`` + # See https://github.com/mopidy/mopidy/issues/302 for details + parser.add_option( + b'-q', '--quiet', + action='store_const', const=0, dest='verbosity_level', + help='less output (warning level)') + parser.add_option( + b'-v', '--verbose', + action='count', default=1, dest='verbosity_level', + help='more output (debug level)') + return parser.parse_args(args=mopidy_args)[0]","def parse_options(): + parser = optparse.OptionParser( + version='Mopidy %s' % versioning.get_version()) + parser.add_option( + '-q', '--quiet', + action='store_const', const=0, dest='verbosity_level', + help='less output (warning level)') + parser.add_option( + '-v', '--verbose', + action='count', default=1, dest='verbosity_level', + help='more output (debug level)') + return parser.parse_args(args=mopidy_args)[0]","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, core): + super(MpdFrontend, self).__init__() + hostname = network.format_hostname(settings.MPD_SERVER_HOSTNAME) + port = settings.MPD_SERVER_PORT + + # NOTE: dict key must be bytestring to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + try: + network.Server( + hostname, port, + protocol=session.MpdSession, protocol_kwargs={b'core': core}, + max_connections=settings.MPD_SERVER_MAX_CONNECTIONS, + timeout=settings.MPD_SERVER_CONNECTION_TIMEOUT) + except IOError as error: + logger.error( + 'MPD server startup failed: %s', + encoding.locale_decode(error)) + sys.exit(1) + + logger.info('MPD server running at [%s]:%s', hostname, port)"," def __init__(self, core): + super(MpdFrontend, self).__init__() + hostname = network.format_hostname(settings.MPD_SERVER_HOSTNAME) + port = settings.MPD_SERVER_PORT + + try: + network.Server( + hostname, port, + protocol=session.MpdSession, protocol_kwargs={'core': core}, + max_connections=settings.MPD_SERVER_MAX_CONNECTIONS, + timeout=settings.MPD_SERVER_CONNECTION_TIMEOUT) + except IOError as error: + logger.error( + 'MPD server startup failed: %s', + encoding.locale_decode(error)) + sys.exit(1) + + logger.info('MPD server running at [%s]:%s', hostname, port)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def handle_request(pattern, auth_required=True): + """""" + Decorator for connecting command handlers to command requests. + + If you use named groups in the pattern, the decorated method will get the + groups as keyword arguments. If the group is optional, remember to give the + argument a default value. + + For example, if the command is ``do that thing`` the ``what`` argument will + be ``this thing``:: + + @handle_request('^do (?P.+)$') + def do(what): + ... + + :param pattern: regexp pattern for matching commands + :type pattern: string + """""" + def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + # NOTE: Make pattern a bytestring to get bytestring keys in the dict + # returned from matches.groupdict(), which is again used as a **kwargs + # dict. This is needed to work on Python < 2.6.5. See + # https://github.com/mopidy/mopidy/issues/302 for details. + bytestring_pattern = pattern.encode('utf-8') + compiled_pattern = re.compile(bytestring_pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func + return decorator","def handle_request(pattern, auth_required=True): + """""" + Decorator for connecting command handlers to command requests. + + If you use named groups in the pattern, the decorated method will get the + groups as keyword arguments. If the group is optional, remember to give the + argument a default value. + + For example, if the command is ``do that thing`` the ``what`` argument will + be ``this thing``:: + + @handle_request('^do (?P.+)$') + def do(what): + ... + + :param pattern: regexp pattern for matching commands + :type pattern: string + """""" + def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + compiled_pattern = re.compile(pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func + return decorator","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + # NOTE: Make pattern a bytestring to get bytestring keys in the dict + # returned from matches.groupdict(), which is again used as a **kwargs + # dict. This is needed to work on Python < 2.6.5. See + # https://github.com/mopidy/mopidy/issues/302 for details. + bytestring_pattern = pattern.encode('utf-8') + compiled_pattern = re.compile(bytestring_pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func"," def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + compiled_pattern = re.compile(pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def parse_options(): + parser = optparse.OptionParser( + version='Mopidy %s' % versioning.get_version()) + # NOTE First argument to add_option must be bytestrings on Python < 2.6.2 + # See https://github.com/mopidy/mopidy/issues/302 for details + parser.add_option( + b'--help-gst', + action='store_true', dest='help_gst', + help='show GStreamer help options') + parser.add_option( + b'-i', '--interactive', + action='store_true', dest='interactive', + help='ask interactively for required settings which are missing') + parser.add_option( + b'-q', '--quiet', + action='store_const', const=0, dest='verbosity_level', + help='less output (warning level)') + parser.add_option( + b'-v', '--verbose', + action='count', default=1, dest='verbosity_level', + help='more output (debug level)') + parser.add_option( + b'--save-debug-log', + action='store_true', dest='save_debug_log', + help='save debug log to ""./mopidy.log""') + parser.add_option( + b'--list-settings', + action='callback', + callback=settings_utils.list_settings_optparse_callback, + help='list current settings') + parser.add_option( + b'--list-deps', + action='callback', callback=deps.list_deps_optparse_callback, + help='list dependencies and their versions') + parser.add_option( + b'--debug-thread', + action='store_true', dest='debug_thread', + help='run background thread that dumps tracebacks on SIGUSR1') + return parser.parse_args(args=mopidy_args)[0]","def parse_options(): + parser = optparse.OptionParser( + version='Mopidy %s' % versioning.get_version()) + # NOTE Python 2.6: To support Python versions < 2.6.2rc1 we must use + # bytestrings for the first argument to ``add_option`` + # See https://github.com/mopidy/mopidy/issues/302 for details + parser.add_option( + b'--help-gst', + action='store_true', dest='help_gst', + help='show GStreamer help options') + parser.add_option( + b'-i', '--interactive', + action='store_true', dest='interactive', + help='ask interactively for required settings which are missing') + parser.add_option( + b'-q', '--quiet', + action='store_const', const=0, dest='verbosity_level', + help='less output (warning level)') + parser.add_option( + b'-v', '--verbose', + action='count', default=1, dest='verbosity_level', + help='more output (debug level)') + parser.add_option( + b'--save-debug-log', + action='store_true', dest='save_debug_log', + help='save debug log to ""./mopidy.log""') + parser.add_option( + b'--list-settings', + action='callback', + callback=settings_utils.list_settings_optparse_callback, + help='list current settings') + parser.add_option( + b'--list-deps', + action='callback', callback=deps.list_deps_optparse_callback, + help='list dependencies and their versions') + parser.add_option( + b'--debug-thread', + action='store_true', dest='debug_thread', + help='run background thread that dumps tracebacks on SIGUSR1') + return parser.parse_args(args=mopidy_args)[0]","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def _convert_mpd_data(data, tracks, music_dir): + if not data: + return + + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details. + + track_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + albumartist_kwargs = {} + + if 'track' in data: + if '/' in data['track']: + album_kwargs[b'num_tracks'] = int(data['track'].split('/')[1]) + track_kwargs[b'track_no'] = int(data['track'].split('/')[0]) + else: + track_kwargs[b'track_no'] = int(data['track']) + + if 'artist' in data: + artist_kwargs[b'name'] = data['artist'] + albumartist_kwargs[b'name'] = data['artist'] + + if 'albumartist' in data: + albumartist_kwargs[b'name'] = data['albumartist'] + + if 'album' in data: + album_kwargs[b'name'] = data['album'] + + if 'title' in data: + track_kwargs[b'name'] = data['title'] + + if 'date' in data: + track_kwargs[b'date'] = data['date'] + + if 'musicbrainz_trackid' in data: + track_kwargs[b'musicbrainz_id'] = data['musicbrainz_trackid'] + + if 'musicbrainz_albumid' in data: + album_kwargs[b'musicbrainz_id'] = data['musicbrainz_albumid'] + + if 'musicbrainz_artistid' in data: + artist_kwargs[b'musicbrainz_id'] = data['musicbrainz_artistid'] + + if 'musicbrainz_albumartistid' in data: + albumartist_kwargs[b'musicbrainz_id'] = ( + data['musicbrainz_albumartistid']) + + if data['file'][0] == '/': + path = data['file'][1:] + else: + path = data['file'] + path = urllib.unquote(path) + + if artist_kwargs: + artist = Artist(**artist_kwargs) + track_kwargs[b'artists'] = [artist] + + if albumartist_kwargs: + albumartist = Artist(**albumartist_kwargs) + album_kwargs[b'artists'] = [albumartist] + + if album_kwargs: + album = Album(**album_kwargs) + track_kwargs[b'album'] = album + + track_kwargs[b'uri'] = path_to_uri(music_dir, path) + track_kwargs[b'length'] = int(data.get('time', 0)) * 1000 + + track = Track(**track_kwargs) + tracks.add(track)","def _convert_mpd_data(data, tracks, music_dir): + if not data: + return + + # NOTE: kwargs are explicitly made bytestrings to work on Python + # 2.6.0/2.6.1. See https://github.com/mopidy/mopidy/issues/302 for details. + + track_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + albumartist_kwargs = {} + + if 'track' in data: + if '/' in data['track']: + album_kwargs[b'num_tracks'] = int(data['track'].split('/')[1]) + track_kwargs[b'track_no'] = int(data['track'].split('/')[0]) + else: + track_kwargs[b'track_no'] = int(data['track']) + + if 'artist' in data: + artist_kwargs[b'name'] = data['artist'] + albumartist_kwargs[b'name'] = data['artist'] + + if 'albumartist' in data: + albumartist_kwargs[b'name'] = data['albumartist'] + + if 'album' in data: + album_kwargs[b'name'] = data['album'] + + if 'title' in data: + track_kwargs[b'name'] = data['title'] + + if 'date' in data: + track_kwargs[b'date'] = data['date'] + + if 'musicbrainz_trackid' in data: + track_kwargs[b'musicbrainz_id'] = data['musicbrainz_trackid'] + + if 'musicbrainz_albumid' in data: + album_kwargs[b'musicbrainz_id'] = data['musicbrainz_albumid'] + + if 'musicbrainz_artistid' in data: + artist_kwargs[b'musicbrainz_id'] = data['musicbrainz_artistid'] + + if 'musicbrainz_albumartistid' in data: + albumartist_kwargs[b'musicbrainz_id'] = ( + data['musicbrainz_albumartistid']) + + if data['file'][0] == '/': + path = data['file'][1:] + else: + path = data['file'] + path = urllib.unquote(path) + + if artist_kwargs: + artist = Artist(**artist_kwargs) + track_kwargs[b'artists'] = [artist] + + if albumartist_kwargs: + albumartist = Artist(**albumartist_kwargs) + album_kwargs[b'artists'] = [albumartist] + + if album_kwargs: + album = Album(**album_kwargs) + track_kwargs[b'album'] = album + + track_kwargs[b'uri'] = path_to_uri(music_dir, path) + track_kwargs[b'length'] = int(data.get('time', 0)) * 1000 + + track = Track(**track_kwargs) + tracks.add(track)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, core): + super(MpdFrontend, self).__init__() + hostname = network.format_hostname(settings.MPD_SERVER_HOSTNAME) + port = settings.MPD_SERVER_PORT + + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details. + try: + network.Server( + hostname, port, + protocol=session.MpdSession, protocol_kwargs={b'core': core}, + max_connections=settings.MPD_SERVER_MAX_CONNECTIONS, + timeout=settings.MPD_SERVER_CONNECTION_TIMEOUT) + except IOError as error: + logger.error( + 'MPD server startup failed: %s', + encoding.locale_decode(error)) + sys.exit(1) + + logger.info('MPD server running at [%s]:%s', hostname, port)"," def __init__(self, core): + super(MpdFrontend, self).__init__() + hostname = network.format_hostname(settings.MPD_SERVER_HOSTNAME) + port = settings.MPD_SERVER_PORT + + # NOTE: dict key must be bytestring to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + try: + network.Server( + hostname, port, + protocol=session.MpdSession, protocol_kwargs={b'core': core}, + max_connections=settings.MPD_SERVER_MAX_CONNECTIONS, + timeout=settings.MPD_SERVER_CONNECTION_TIMEOUT) + except IOError as error: + logger.error( + 'MPD server startup failed: %s', + encoding.locale_decode(error)) + sys.exit(1) + + logger.info('MPD server running at [%s]:%s', hostname, port)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def handle_request(pattern, auth_required=True): + """""" + Decorator for connecting command handlers to command requests. + + If you use named groups in the pattern, the decorated method will get the + groups as keyword arguments. If the group is optional, remember to give the + argument a default value. + + For example, if the command is ``do that thing`` the ``what`` argument will + be ``this thing``:: + + @handle_request('^do (?P.+)$') + def do(what): + ... + + :param pattern: regexp pattern for matching commands + :type pattern: string + """""" + def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + # NOTE Make pattern a bytestring to get bytestring keys in the dict + # returned from matches.groupdict(), which is again used as a **kwargs + # dict. This is needed to work on Python < 2.6.5. + # See https://github.com/mopidy/mopidy/issues/302 for details. + bytestring_pattern = pattern.encode('utf-8') + compiled_pattern = re.compile(bytestring_pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func + return decorator","def handle_request(pattern, auth_required=True): + """""" + Decorator for connecting command handlers to command requests. + + If you use named groups in the pattern, the decorated method will get the + groups as keyword arguments. If the group is optional, remember to give the + argument a default value. + + For example, if the command is ``do that thing`` the ``what`` argument will + be ``this thing``:: + + @handle_request('^do (?P.+)$') + def do(what): + ... + + :param pattern: regexp pattern for matching commands + :type pattern: string + """""" + def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + # NOTE: Make pattern a bytestring to get bytestring keys in the dict + # returned from matches.groupdict(), which is again used as a **kwargs + # dict. This is needed to work on Python < 2.6.5. See + # https://github.com/mopidy/mopidy/issues/302 for details. + bytestring_pattern = pattern.encode('utf-8') + compiled_pattern = re.compile(bytestring_pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func + return decorator","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + # NOTE Make pattern a bytestring to get bytestring keys in the dict + # returned from matches.groupdict(), which is again used as a **kwargs + # dict. This is needed to work on Python < 2.6.5. + # See https://github.com/mopidy/mopidy/issues/302 for details. + bytestring_pattern = pattern.encode('utf-8') + compiled_pattern = re.compile(bytestring_pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func"," def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + # NOTE: Make pattern a bytestring to get bytestring keys in the dict + # returned from matches.groupdict(), which is again used as a **kwargs + # dict. This is needed to work on Python < 2.6.5. See + # https://github.com/mopidy/mopidy/issues/302 for details. + bytestring_pattern = pattern.encode('utf-8') + compiled_pattern = re.compile(bytestring_pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def query_from_mpd_list_format(field, mpd_query): + """""" + Converts an MPD ``list`` query to a Mopidy query. + """""" + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + if mpd_query is None: + return {} + try: + # shlex does not seem to be friends with unicode objects + tokens = shlex.split(mpd_query.encode('utf-8')) + except ValueError as error: + if str(error) == 'No closing quotation': + raise MpdArgError('Invalid unquoted character', command='list') + else: + raise + tokens = [t.decode('utf-8') for t in tokens] + if len(tokens) == 1: + if field == 'album': + if not tokens[0]: + raise ValueError + return {b'artist': [tokens[0]]} # See above NOTE + else: + raise MpdArgError( + 'should be ""Album"" for 3 arguments', command='list') + elif len(tokens) % 2 == 0: + query = {} + while tokens: + key = str(tokens[0].lower()) # See above NOTE + value = tokens[1] + tokens = tokens[2:] + if key not in ('artist', 'album', 'date', 'genre'): + raise MpdArgError('not able to parse args', command='list') + if not value: + raise ValueError + if key in query: + query[key].append(value) + else: + query[key] = [value] + return query + else: + raise MpdArgError('not able to parse args', command='list')","def query_from_mpd_list_format(field, mpd_query): + """""" + Converts an MPD ``list`` query to a Mopidy query. + """""" + if mpd_query is None: + return {} + try: + # shlex does not seem to be friends with unicode objects + tokens = shlex.split(mpd_query.encode('utf-8')) + except ValueError as error: + if str(error) == 'No closing quotation': + raise MpdArgError('Invalid unquoted character', command='list') + else: + raise + tokens = [t.decode('utf-8') for t in tokens] + if len(tokens) == 1: + if field == 'album': + if not tokens[0]: + raise ValueError + return {'artist': [tokens[0]]} + else: + raise MpdArgError( + 'should be ""Album"" for 3 arguments', command='list') + elif len(tokens) % 2 == 0: + query = {} + while tokens: + key = tokens[0].lower() + key = str(key) # Needed for kwargs keys on OS X and Windows + value = tokens[1] + tokens = tokens[2:] + if key not in ('artist', 'album', 'date', 'genre'): + raise MpdArgError('not able to parse args', command='list') + if not value: + raise ValueError + if key in query: + query[key].append(value) + else: + query[key] = [value] + return query + else: + raise MpdArgError('not able to parse args', command='list')","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def copy(self, **values): + """""" + Copy the model with ``field`` updated to new value. + + Examples:: + + # Returns a track with a new name + Track(name='foo').copy(name='bar') + # Return an album with a new number of tracks + Album(num_tracks=2).copy(num_tracks=5) + + :param values: the model fields to modify + :type values: dict + :rtype: new instance of the model being copied + """""" + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + data = {} + for key in self.__dict__.keys(): + public_key = key.lstrip('_') + data[str(public_key)] = values.pop(public_key, self.__dict__[key]) + for key in values.keys(): + if hasattr(self, key): + data[str(key)] = values.pop(key) + if values: + raise TypeError( + 'copy() got an unexpected keyword argument ""%s""' % key) + return self.__class__(**data)"," def copy(self, **values): + """""" + Copy the model with ``field`` updated to new value. + + Examples:: + + # Returns a track with a new name + Track(name='foo').copy(name='bar') + # Return an album with a new number of tracks + Album(num_tracks=2).copy(num_tracks=5) + + :param values: the model fields to modify + :type values: dict + :rtype: new instance of the model being copied + """""" + data = {} + for key in self.__dict__.keys(): + public_key = key.lstrip('_') + data[public_key] = values.pop(public_key, self.__dict__[key]) + for key in values.keys(): + if hasattr(self, key): + data[key] = values.pop(key) + if values: + raise TypeError( + 'copy() got an unexpected keyword argument ""%s""' % key) + return self.__class__(**data)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, *args, **kwargs): + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + self.__dict__[b'artists'] = frozenset(kwargs.pop('artists', [])) + super(Album, self).__init__(*args, **kwargs)"," def __init__(self, *args, **kwargs): + self.__dict__['artists'] = frozenset(kwargs.pop('artists', [])) + super(Album, self).__init__(*args, **kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, *args, **kwargs): + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + self.__dict__[b'artists'] = frozenset(kwargs.pop('artists', [])) + super(Track, self).__init__(*args, **kwargs)"," def __init__(self, *args, **kwargs): + self.__dict__['artists'] = frozenset(kwargs.pop('artists', [])) + super(Track, self).__init__(*args, **kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, *args, **kwargs): + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + if len(args) == 2 and len(kwargs) == 0: + kwargs[b'tlid'] = args[0] + kwargs[b'track'] = args[1] + args = [] + super(TlTrack, self).__init__(*args, **kwargs)"," def __init__(self, *args, **kwargs): + if len(args) == 2 and len(kwargs) == 0: + kwargs['tlid'] = args[0] + kwargs['track'] = args[1] + args = [] + super(TlTrack, self).__init__(*args, **kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, *args, **kwargs): + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + self.__dict__[b'tracks'] = tuple(kwargs.pop('tracks', [])) + super(Playlist, self).__init__(*args, **kwargs)"," def __init__(self, *args, **kwargs): + self.__dict__['tracks'] = tuple(kwargs.pop('tracks', [])) + super(Playlist, self).__init__(*args, **kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, *args, **kwargs): + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + self.__dict__[b'tracks'] = tuple(kwargs.pop('tracks', [])) + self.__dict__[b'artists'] = tuple(kwargs.pop('artists', [])) + self.__dict__[b'albums'] = tuple(kwargs.pop('albums', [])) + super(SearchResult, self).__init__(*args, **kwargs)"," def __init__(self, *args, **kwargs): + self.__dict__['tracks'] = tuple(kwargs.pop('tracks', [])) + self.__dict__['artists'] = tuple(kwargs.pop('artists', [])) + self.__dict__['albums'] = tuple(kwargs.pop('albums', [])) + super(SearchResult, self).__init__(*args, **kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def parse_options(): + parser = optparse.OptionParser( + version='Mopidy %s' % versioning.get_version()) + # NOTE First argument to add_option must be bytestrings on Python < 2.6.2 + # See https://github.com/mopidy/mopidy/issues/302 for details + parser.add_option( + b'-q', '--quiet', + action='store_const', const=0, dest='verbosity_level', + help='less output (warning level)') + parser.add_option( + b'-v', '--verbose', + action='count', default=1, dest='verbosity_level', + help='more output (debug level)') + return parser.parse_args(args=mopidy_args)[0]","def parse_options(): + parser = optparse.OptionParser( + version='Mopidy %s' % versioning.get_version()) + # NOTE Python 2.6: To support Python versions < 2.6.2rc1 we must use + # bytestrings for the first argument to ``add_option`` + # See https://github.com/mopidy/mopidy/issues/302 for details + parser.add_option( + b'-q', '--quiet', + action='store_const', const=0, dest='verbosity_level', + help='less output (warning level)') + parser.add_option( + b'-v', '--verbose', + action='count', default=1, dest='verbosity_level', + help='more output (debug level)') + return parser.parse_args(args=mopidy_args)[0]","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def translator(data): + albumartist_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + track_kwargs = {} + + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details. + + def _retrieve(source_key, target_key, target): + if source_key in data: + target[str(target_key)] = data[source_key] + + _retrieve(gst.TAG_ALBUM, 'name', album_kwargs) + _retrieve(gst.TAG_TRACK_COUNT, 'num_tracks', album_kwargs) + _retrieve(gst.TAG_ARTIST, 'name', artist_kwargs) + + if gst.TAG_DATE in data and data[gst.TAG_DATE]: + date = data[gst.TAG_DATE] + try: + date = datetime.date(date.year, date.month, date.day) + except ValueError: + pass # Ignore invalid dates + else: + track_kwargs[b'date'] = date.isoformat() + + _retrieve(gst.TAG_TITLE, 'name', track_kwargs) + _retrieve(gst.TAG_TRACK_NUMBER, 'track_no', track_kwargs) + + # Following keys don't seem to have TAG_* constant. + _retrieve('album-artist', 'name', albumartist_kwargs) + _retrieve('musicbrainz-trackid', 'musicbrainz_id', track_kwargs) + _retrieve('musicbrainz-artistid', 'musicbrainz_id', artist_kwargs) + _retrieve('musicbrainz-albumid', 'musicbrainz_id', album_kwargs) + _retrieve( + 'musicbrainz-albumartistid', 'musicbrainz_id', albumartist_kwargs) + + if albumartist_kwargs: + album_kwargs[b'artists'] = [Artist(**albumartist_kwargs)] + + track_kwargs[b'uri'] = data['uri'] + track_kwargs[b'length'] = data[gst.TAG_DURATION] + track_kwargs[b'album'] = Album(**album_kwargs) + track_kwargs[b'artists'] = [Artist(**artist_kwargs)] + + return Track(**track_kwargs)","def translator(data): + albumartist_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + track_kwargs = {} + + # NOTE: kwargs are explicitly made bytestrings to work on Python + # 2.6.0/2.6.1. See https://github.com/mopidy/mopidy/issues/302 for + # details. + + def _retrieve(source_key, target_key, target): + if source_key in data: + target[str(target_key)] = data[source_key] + + _retrieve(gst.TAG_ALBUM, 'name', album_kwargs) + _retrieve(gst.TAG_TRACK_COUNT, 'num_tracks', album_kwargs) + _retrieve(gst.TAG_ARTIST, 'name', artist_kwargs) + + if gst.TAG_DATE in data and data[gst.TAG_DATE]: + date = data[gst.TAG_DATE] + try: + date = datetime.date(date.year, date.month, date.day) + except ValueError: + pass # Ignore invalid dates + else: + track_kwargs[b'date'] = date.isoformat() + + _retrieve(gst.TAG_TITLE, 'name', track_kwargs) + _retrieve(gst.TAG_TRACK_NUMBER, 'track_no', track_kwargs) + + # Following keys don't seem to have TAG_* constant. + _retrieve('album-artist', 'name', albumartist_kwargs) + _retrieve('musicbrainz-trackid', 'musicbrainz_id', track_kwargs) + _retrieve('musicbrainz-artistid', 'musicbrainz_id', artist_kwargs) + _retrieve('musicbrainz-albumid', 'musicbrainz_id', album_kwargs) + _retrieve( + 'musicbrainz-albumartistid', 'musicbrainz_id', albumartist_kwargs) + + if albumartist_kwargs: + album_kwargs[b'artists'] = [Artist(**albumartist_kwargs)] + + track_kwargs[b'uri'] = data['uri'] + track_kwargs[b'length'] = data[gst.TAG_DURATION] + track_kwargs[b'album'] = Album(**album_kwargs) + track_kwargs[b'artists'] = [Artist(**artist_kwargs)] + + return Track(**track_kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def model_json_decoder(dct): + """""" + Automatically deserialize Mopidy models from JSON. + + Usage:: + + >>> import json + >>> json.loads( + ... '{""a_track"": {""__model__"": ""Track"", ""name"": ""name""}}', + ... object_hook=model_json_decoder) + {u'a_track': Track(artists=[], name=u'name')} + + """""" + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details. + if '__model__' in dct: + model_name = dct.pop('__model__') + cls = globals().get(model_name, None) + if issubclass(cls, ImmutableObject): + kwargs = {} + for key, value in dct.items(): + kwargs[str(key)] = value + return cls(**kwargs) + return dct","def model_json_decoder(dct): + """""" + Automatically deserialize Mopidy models from JSON. + + Usage:: + + >>> import json + >>> json.loads( + ... '{""a_track"": {""__model__"": ""Track"", ""name"": ""name""}}', + ... object_hook=model_json_decoder) + {u'a_track': Track(artists=[], name=u'name')} + + """""" + if '__model__' in dct: + model_name = dct.pop('__model__') + cls = globals().get(model_name, None) + if issubclass(cls, ImmutableObject): + return cls(**dct) + return dct","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def _convert_mpd_data(data, tracks, music_dir): + if not data: + return + + track_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + albumartist_kwargs = {} + + if 'track' in data: + if '/' in data['track']: + album_kwargs['num_tracks'] = int(data['track'].split('/')[1]) + track_kwargs['track_no'] = int(data['track'].split('/')[0]) + else: + track_kwargs['track_no'] = int(data['track']) + + if 'artist' in data: + artist_kwargs['name'] = data['artist'] + albumartist_kwargs['name'] = data['artist'] + + if 'albumartist' in data: + albumartist_kwargs['name'] = data['albumartist'] + + if 'album' in data: + album_kwargs['name'] = data['album'] + + if 'title' in data: + track_kwargs['name'] = data['title'] + + if 'date' in data: + track_kwargs['date'] = data['date'] + + if 'musicbrainz_trackid' in data: + track_kwargs['musicbrainz_id'] = data['musicbrainz_trackid'] + + if 'musicbrainz_albumid' in data: + album_kwargs['musicbrainz_id'] = data['musicbrainz_albumid'] + + if 'musicbrainz_artistid' in data: + artist_kwargs['musicbrainz_id'] = data['musicbrainz_artistid'] + + if 'musicbrainz_albumartistid' in data: + albumartist_kwargs['musicbrainz_id'] = ( + data['musicbrainz_albumartistid']) + + if artist_kwargs: + artist = Artist(**artist_kwargs) + track_kwargs['artists'] = [artist] + + if albumartist_kwargs: + albumartist = Artist(**albumartist_kwargs) + album_kwargs['artists'] = [albumartist] + + if album_kwargs: + album = Album(**album_kwargs) + track_kwargs['album'] = album + + if data['file'][0] == '/': + path = data['file'][1:] + else: + path = data['file'] + path = urllib.unquote(path.encode('utf-8')) + + if isinstance(music_dir, unicode): + music_dir = music_dir.encode('utf-8') + + # Make sure we only pass bytestrings to path_to_uri to avoid implicit + # decoding of bytestrings to unicode strings + track_kwargs['uri'] = path_to_uri(music_dir, path) + + track_kwargs['length'] = int(data.get('time', 0)) * 1000 + + track = Track(**track_kwargs) + tracks.add(track)","def _convert_mpd_data(data, tracks, music_dir): + if not data: + return + + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details. + + track_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + albumartist_kwargs = {} + + if 'track' in data: + if '/' in data['track']: + album_kwargs[b'num_tracks'] = int(data['track'].split('/')[1]) + track_kwargs[b'track_no'] = int(data['track'].split('/')[0]) + else: + track_kwargs[b'track_no'] = int(data['track']) + + if 'artist' in data: + artist_kwargs[b'name'] = data['artist'] + albumartist_kwargs[b'name'] = data['artist'] + + if 'albumartist' in data: + albumartist_kwargs[b'name'] = data['albumartist'] + + if 'album' in data: + album_kwargs[b'name'] = data['album'] + + if 'title' in data: + track_kwargs[b'name'] = data['title'] + + if 'date' in data: + track_kwargs[b'date'] = data['date'] + + if 'musicbrainz_trackid' in data: + track_kwargs[b'musicbrainz_id'] = data['musicbrainz_trackid'] + + if 'musicbrainz_albumid' in data: + album_kwargs[b'musicbrainz_id'] = data['musicbrainz_albumid'] + + if 'musicbrainz_artistid' in data: + artist_kwargs[b'musicbrainz_id'] = data['musicbrainz_artistid'] + + if 'musicbrainz_albumartistid' in data: + albumartist_kwargs[b'musicbrainz_id'] = ( + data['musicbrainz_albumartistid']) + + if artist_kwargs: + artist = Artist(**artist_kwargs) + track_kwargs[b'artists'] = [artist] + + if albumartist_kwargs: + albumartist = Artist(**albumartist_kwargs) + album_kwargs[b'artists'] = [albumartist] + + if album_kwargs: + album = Album(**album_kwargs) + track_kwargs[b'album'] = album + + if data['file'][0] == '/': + path = data['file'][1:] + else: + path = data['file'] + path = urllib.unquote(path.encode('utf-8')) + + if isinstance(music_dir, unicode): + music_dir = music_dir.encode('utf-8') + + # Make sure we only pass bytestrings to path_to_uri to avoid implicit + # decoding of bytestrings to unicode strings + track_kwargs[b'uri'] = path_to_uri(music_dir, path) + + track_kwargs[b'length'] = int(data.get('time', 0)) * 1000 + + track = Track(**track_kwargs) + tracks.add(track)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, config, core): + super(MpdFrontend, self).__init__() + hostname = network.format_hostname(config['mpd']['hostname']) + port = config['mpd']['port'] + + try: + network.Server( + hostname, port, + protocol=session.MpdSession, + protocol_kwargs={ + 'config': config, + 'core': core, + }, + max_connections=config['mpd']['max_connections'], + timeout=config['mpd']['connection_timeout']) + except IOError as error: + logger.error( + 'MPD server startup failed: %s', + encoding.locale_decode(error)) + sys.exit(1) + + logger.info('MPD server running at [%s]:%s', hostname, port)"," def __init__(self, config, core): + super(MpdFrontend, self).__init__() + hostname = network.format_hostname(config['mpd']['hostname']) + port = config['mpd']['port'] + + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details. + try: + network.Server( + hostname, port, + protocol=session.MpdSession, + protocol_kwargs={ + b'config': config, + b'core': core, + }, + max_connections=config['mpd']['max_connections'], + timeout=config['mpd']['connection_timeout']) + except IOError as error: + logger.error( + 'MPD server startup failed: %s', + encoding.locale_decode(error)) + sys.exit(1) + + logger.info('MPD server running at [%s]:%s', hostname, port)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def handle_request(pattern, auth_required=True): + """""" + Decorator for connecting command handlers to command requests. + + If you use named groups in the pattern, the decorated method will get the + groups as keyword arguments. If the group is optional, remember to give the + argument a default value. + + For example, if the command is ``do that thing`` the ``what`` argument will + be ``this thing``:: + + @handle_request('^do (?P.+)$') + def do(what): + ... + + :param pattern: regexp pattern for matching commands + :type pattern: string + """""" + def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + compiled_pattern = re.compile(pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func + return decorator","def handle_request(pattern, auth_required=True): + """""" + Decorator for connecting command handlers to command requests. + + If you use named groups in the pattern, the decorated method will get the + groups as keyword arguments. If the group is optional, remember to give the + argument a default value. + + For example, if the command is ``do that thing`` the ``what`` argument will + be ``this thing``:: + + @handle_request('^do (?P.+)$') + def do(what): + ... + + :param pattern: regexp pattern for matching commands + :type pattern: string + """""" + def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + # NOTE Make pattern a bytestring to get bytestring keys in the dict + # returned from matches.groupdict(), which is again used as a **kwargs + # dict. This is needed to work on Python < 2.6.5. + # See https://github.com/mopidy/mopidy/issues/302 for details. + bytestring_pattern = pattern.encode('utf-8') + compiled_pattern = re.compile(bytestring_pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func + return decorator","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + compiled_pattern = re.compile(pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func"," def decorator(func): + match = re.search('([a-z_]+)', pattern) + if match is not None: + mpd_commands.add( + MpdCommand(name=match.group(), auth_required=auth_required)) + # NOTE Make pattern a bytestring to get bytestring keys in the dict + # returned from matches.groupdict(), which is again used as a **kwargs + # dict. This is needed to work on Python < 2.6.5. + # See https://github.com/mopidy/mopidy/issues/302 for details. + bytestring_pattern = pattern.encode('utf-8') + compiled_pattern = re.compile(bytestring_pattern, flags=re.UNICODE) + if compiled_pattern in request_handlers: + raise ValueError('Tried to redefine handler for %s with %s' % ( + pattern, func)) + request_handlers[compiled_pattern] = func + func.__doc__ = ' - *Pattern:* ``%s``\\n\\n%s' % ( + pattern, func.__doc__ or '') + return func","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def query_from_mpd_list_format(field, mpd_query): + """""" + Converts an MPD ``list`` query to a Mopidy query. + """""" + if mpd_query is None: + return {} + try: + # shlex does not seem to be friends with unicode objects + tokens = shlex.split(mpd_query.encode('utf-8')) + except ValueError as error: + if str(error) == 'No closing quotation': + raise MpdArgError('Invalid unquoted character', command='list') + else: + raise + tokens = [t.decode('utf-8') for t in tokens] + if len(tokens) == 1: + if field == 'album': + if not tokens[0]: + raise ValueError + return {'artist': [tokens[0]]} # See above NOTE + else: + raise MpdArgError( + 'should be ""Album"" for 3 arguments', command='list') + elif len(tokens) % 2 == 0: + query = {} + while tokens: + key = str(tokens[0].lower()) # See above NOTE + value = tokens[1] + tokens = tokens[2:] + if key not in ('artist', 'album', 'date', 'genre'): + raise MpdArgError('not able to parse args', command='list') + if not value: + raise ValueError + if key in query: + query[key].append(value) + else: + query[key] = [value] + return query + else: + raise MpdArgError('not able to parse args', command='list')","def query_from_mpd_list_format(field, mpd_query): + """""" + Converts an MPD ``list`` query to a Mopidy query. + """""" + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + if mpd_query is None: + return {} + try: + # shlex does not seem to be friends with unicode objects + tokens = shlex.split(mpd_query.encode('utf-8')) + except ValueError as error: + if str(error) == 'No closing quotation': + raise MpdArgError('Invalid unquoted character', command='list') + else: + raise + tokens = [t.decode('utf-8') for t in tokens] + if len(tokens) == 1: + if field == 'album': + if not tokens[0]: + raise ValueError + return {b'artist': [tokens[0]]} # See above NOTE + else: + raise MpdArgError( + 'should be ""Album"" for 3 arguments', command='list') + elif len(tokens) % 2 == 0: + query = {} + while tokens: + key = str(tokens[0].lower()) # See above NOTE + value = tokens[1] + tokens = tokens[2:] + if key not in ('artist', 'album', 'date', 'genre'): + raise MpdArgError('not able to parse args', command='list') + if not value: + raise ValueError + if key in query: + query[key].append(value) + else: + query[key] = [value] + return query + else: + raise MpdArgError('not able to parse args', command='list')","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def copy(self, **values): + """""" + Copy the model with ``field`` updated to new value. + + Examples:: + + # Returns a track with a new name + Track(name='foo').copy(name='bar') + # Return an album with a new number of tracks + Album(num_tracks=2).copy(num_tracks=5) + + :param values: the model fields to modify + :type values: dict + :rtype: new instance of the model being copied + """""" + data = {} + for key in self.__dict__.keys(): + public_key = key.lstrip('_') + data[public_key] = values.pop(public_key, self.__dict__[key]) + for key in values.keys(): + if hasattr(self, key): + data[key] = values.pop(key) + if values: + raise TypeError( + 'copy() got an unexpected keyword argument ""%s""' % key) + return self.__class__(**data)"," def copy(self, **values): + """""" + Copy the model with ``field`` updated to new value. + + Examples:: + + # Returns a track with a new name + Track(name='foo').copy(name='bar') + # Return an album with a new number of tracks + Album(num_tracks=2).copy(num_tracks=5) + + :param values: the model fields to modify + :type values: dict + :rtype: new instance of the model being copied + """""" + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + data = {} + for key in self.__dict__.keys(): + public_key = key.lstrip('_') + data[str(public_key)] = values.pop(public_key, self.__dict__[key]) + for key in values.keys(): + if hasattr(self, key): + data[str(key)] = values.pop(key) + if values: + raise TypeError( + 'copy() got an unexpected keyword argument ""%s""' % key) + return self.__class__(**data)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def model_json_decoder(dct): + """""" + Automatically deserialize Mopidy models from JSON. + + Usage:: + + >>> import json + >>> json.loads( + ... '{""a_track"": {""__model__"": ""Track"", ""name"": ""name""}}', + ... object_hook=model_json_decoder) + {u'a_track': Track(artists=[], name=u'name')} + + """""" + if '__model__' in dct: + model_name = dct.pop('__model__') + cls = globals().get(model_name, None) + if issubclass(cls, ImmutableObject): + kwargs = {} + for key, value in dct.items(): + kwargs[key] = value + return cls(**kwargs) + return dct","def model_json_decoder(dct): + """""" + Automatically deserialize Mopidy models from JSON. + + Usage:: + + >>> import json + >>> json.loads( + ... '{""a_track"": {""__model__"": ""Track"", ""name"": ""name""}}', + ... object_hook=model_json_decoder) + {u'a_track': Track(artists=[], name=u'name')} + + """""" + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details. + if '__model__' in dct: + model_name = dct.pop('__model__') + cls = globals().get(model_name, None) + if issubclass(cls, ImmutableObject): + kwargs = {} + for key, value in dct.items(): + kwargs[str(key)] = value + return cls(**kwargs) + return dct","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, *args, **kwargs): + self.__dict__['artists'] = frozenset(kwargs.pop('artists', [])) + self.__dict__['images'] = frozenset(kwargs.pop('images', [])) + super(Album, self).__init__(*args, **kwargs)"," def __init__(self, *args, **kwargs): + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + self.__dict__[b'artists'] = frozenset(kwargs.pop('artists', [])) + self.__dict__[b'images'] = frozenset(kwargs.pop('images', [])) + super(Album, self).__init__(*args, **kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, *args, **kwargs): + self.__dict__['artists'] = frozenset(kwargs.pop('artists', [])) + super(Track, self).__init__(*args, **kwargs)"," def __init__(self, *args, **kwargs): + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + self.__dict__[b'artists'] = frozenset(kwargs.pop('artists', [])) + super(Track, self).__init__(*args, **kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, *args, **kwargs): + if len(args) == 2 and len(kwargs) == 0: + kwargs['tlid'] = args[0] + kwargs['track'] = args[1] + args = [] + super(TlTrack, self).__init__(*args, **kwargs)"," def __init__(self, *args, **kwargs): + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + if len(args) == 2 and len(kwargs) == 0: + kwargs[b'tlid'] = args[0] + kwargs[b'track'] = args[1] + args = [] + super(TlTrack, self).__init__(*args, **kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, *args, **kwargs): + self.__dict__['tracks'] = tuple(kwargs.pop('tracks', [])) + super(Playlist, self).__init__(*args, **kwargs)"," def __init__(self, *args, **kwargs): + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + self.__dict__[b'tracks'] = tuple(kwargs.pop('tracks', [])) + super(Playlist, self).__init__(*args, **kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def __init__(self, *args, **kwargs): + self.__dict__['tracks'] = tuple(kwargs.pop('tracks', [])) + self.__dict__['artists'] = tuple(kwargs.pop('artists', [])) + self.__dict__['albums'] = tuple(kwargs.pop('albums', [])) + super(SearchResult, self).__init__(*args, **kwargs)"," def __init__(self, *args, **kwargs): + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details + self.__dict__[b'tracks'] = tuple(kwargs.pop('tracks', [])) + self.__dict__[b'artists'] = tuple(kwargs.pop('artists', [])) + self.__dict__[b'albums'] = tuple(kwargs.pop('albums', [])) + super(SearchResult, self).__init__(*args, **kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def parse_options(): + parser = optparse.OptionParser( + version='Mopidy %s' % versioning.get_version()) + parser.add_option( + '-q', '--quiet', + action='store_const', const=0, dest='verbosity_level', + help='less output (warning level)') + parser.add_option( + '-v', '--verbose', + action='count', default=1, dest='verbosity_level', + help='more output (debug level)') + return parser.parse_args(args=mopidy_args)[0]","def parse_options(): + parser = optparse.OptionParser( + version='Mopidy %s' % versioning.get_version()) + # NOTE First argument to add_option must be bytestrings on Python < 2.6.2 + # See https://github.com/mopidy/mopidy/issues/302 for details + parser.add_option( + b'-q', '--quiet', + action='store_const', const=0, dest='verbosity_level', + help='less output (warning level)') + parser.add_option( + b'-v', '--verbose', + action='count', default=1, dest='verbosity_level', + help='more output (debug level)') + return parser.parse_args(args=mopidy_args)[0]","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +"def translator(data): + albumartist_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + track_kwargs = {} + + def _retrieve(source_key, target_key, target): + if source_key in data: + target[target_key] = data[source_key] + + _retrieve(gst.TAG_ALBUM, 'name', album_kwargs) + _retrieve(gst.TAG_TRACK_COUNT, 'num_tracks', album_kwargs) + _retrieve(gst.TAG_ARTIST, 'name', artist_kwargs) + + if gst.TAG_DATE in data and data[gst.TAG_DATE]: + date = data[gst.TAG_DATE] + try: + date = datetime.date(date.year, date.month, date.day) + except ValueError: + pass # Ignore invalid dates + else: + track_kwargs['date'] = date.isoformat() + + _retrieve(gst.TAG_TITLE, 'name', track_kwargs) + _retrieve(gst.TAG_TRACK_NUMBER, 'track_no', track_kwargs) + + # Following keys don't seem to have TAG_* constant. + _retrieve('album-artist', 'name', albumartist_kwargs) + _retrieve('musicbrainz-trackid', 'musicbrainz_id', track_kwargs) + _retrieve('musicbrainz-artistid', 'musicbrainz_id', artist_kwargs) + _retrieve('musicbrainz-albumid', 'musicbrainz_id', album_kwargs) + _retrieve( + 'musicbrainz-albumartistid', 'musicbrainz_id', albumartist_kwargs) + + if albumartist_kwargs: + album_kwargs['artists'] = [Artist(**albumartist_kwargs)] + + track_kwargs['uri'] = data['uri'] + track_kwargs['length'] = data[gst.TAG_DURATION] + track_kwargs['album'] = Album(**album_kwargs) + track_kwargs['artists'] = [Artist(**artist_kwargs)] + + return Track(**track_kwargs)","def translator(data): + albumartist_kwargs = {} + album_kwargs = {} + artist_kwargs = {} + track_kwargs = {} + + # NOTE kwargs dict keys must be bytestrings to work on Python < 2.6.5 + # See https://github.com/mopidy/mopidy/issues/302 for details. + + def _retrieve(source_key, target_key, target): + if source_key in data: + target[str(target_key)] = data[source_key] + + _retrieve(gst.TAG_ALBUM, 'name', album_kwargs) + _retrieve(gst.TAG_TRACK_COUNT, 'num_tracks', album_kwargs) + _retrieve(gst.TAG_ARTIST, 'name', artist_kwargs) + + if gst.TAG_DATE in data and data[gst.TAG_DATE]: + date = data[gst.TAG_DATE] + try: + date = datetime.date(date.year, date.month, date.day) + except ValueError: + pass # Ignore invalid dates + else: + track_kwargs[b'date'] = date.isoformat() + + _retrieve(gst.TAG_TITLE, 'name', track_kwargs) + _retrieve(gst.TAG_TRACK_NUMBER, 'track_no', track_kwargs) + + # Following keys don't seem to have TAG_* constant. + _retrieve('album-artist', 'name', albumartist_kwargs) + _retrieve('musicbrainz-trackid', 'musicbrainz_id', track_kwargs) + _retrieve('musicbrainz-artistid', 'musicbrainz_id', artist_kwargs) + _retrieve('musicbrainz-albumid', 'musicbrainz_id', album_kwargs) + _retrieve( + 'musicbrainz-albumartistid', 'musicbrainz_id', albumartist_kwargs) + + if albumartist_kwargs: + album_kwargs[b'artists'] = [Artist(**albumartist_kwargs)] + + track_kwargs[b'uri'] = data['uri'] + track_kwargs[b'length'] = data[gst.TAG_DURATION] + track_kwargs[b'album'] = Album(**album_kwargs) + track_kwargs[b'artists'] = [Artist(**artist_kwargs)] + + return Track(**track_kwargs)","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def _retrieve(source_key, target_key, target): + if source_key in data: + target[target_key] = data[source_key]"," def _retrieve(source_key, target_key, target): + if source_key in data: + target[str(target_key)] = data[source_key]","[{'piece_type': 'error message', 'piece_content': 'erik@faust:~$ mopidy\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/mopidy"", line 5, in \\nmain()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main\\noptions = parse_options()\\nFile ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options\\nhelp=\\'show GStreamer help options\\')\\nFile ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option\\nraise TypeError, ""invalid arguments""\\nTypeError: invalid arguments\\nerik@faust:~$ python --version\\nPython 2.6\\nerik@faust:~$ uname -a\\nLinux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux\\nerik@faust:~$ cat /etc/SuSE-release\\nSUSE Linux Enterprise Server 11 (x86_64)\\nVERSION = 11\\nPATCHLEVEL = 2\\nerik@faust:~$'}]","erik@faust:~$ mopidy +Traceback (most recent call last): +File ""/usr/local/bin/mopidy"", line 5, in +main() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 48, in main +options = parse_options() +File ""/usr/local/lib64/python2.6/site-packages/mopidy/__main__.py"", line 85, in parse_options +help='show GStreamer help options') +File ""/usr/lib64/python2.6/optparse.py"", line 1012, in add_option +raise TypeError, ""invalid arguments"" +TypeError: invalid arguments +erik@faust:~$ python --version +Python 2.6 +erik@faust:~$ uname -a +Linux faust 3.0.13-0.27-default #1 SMP Wed Feb 15 13:33:49 UTC 2012 (d73692b) x86_64 x86_64 x86_64 GNU/Linux +erik@faust:~$ cat /etc/SuSE-release +SUSE Linux Enterprise Server 11 (x86_64) +VERSION = 11 +PATCHLEVEL = 2 +erik@faust:~$",TypeError +" def _select_mixer_track(self, mixer, track_label): + # Ignore tracks without volumes, then look for track with + # label == settings.MIXER_TRACK, otherwise fallback to first usable + # track hoping the mixer gave them to us in a sensible order. + + usable_tracks = [] + for track in mixer.list_tracks(): + if not mixer.get_volume(track): + continue + + if track_label and track.label == track_label: + return track + elif track.flags & (gst.interfaces.MIXER_TRACK_MASTER | + gst.interfaces.MIXER_TRACK_OUTPUT): + usable_tracks.append(track) + + if usable_tracks: + return usable_tracks[0]"," def _select_mixer_track(self, mixer, track_label): + # Look for track with label == MIXER_TRACK, otherwise fallback to + # master track which is also an output. + for track in mixer.list_tracks(): + if track_label: + if track.label == track_label: + return track + elif track.flags & (gst.interfaces.MIXER_TRACK_MASTER | + gst.interfaces.MIXER_TRACK_OUTPUT): + return track","[{'piece_type': 'other', 'piece_content': ""OUTPUT = u'alsasink'\\nMIXER_TRACK = u'Master'""}, {'piece_type': 'error message', 'piece_content': 'INFO 2013-01-03 15:47:01,091 [7328:MainThread] mopidy.utils.log\\nStarting Mopidy 0.11.1\\nINFO 2013-01-03 15:47:01,095 [7328:MainThread] mopidy.utils.log\\nPlatform: Linux-3.2.0-4-amd64-x86_64-with-debian-7.0\\nINFO 2013-01-03 15:47:01,095 [7328:MainThread] mopidy.utils.log\\nPython: CPython 2.7.3rc2\\nDEBUG 2013-01-03 15:47:01,097 [7328:MainThread] mopidy.utils\\nLoading: mopidy.backends.local.LocalBackend\\nWARNING 2013-01-03 15:47:01,101 [7328:MainThread] mopidy.backends.local\\nCould not open tag cache: [Errno 2] No such file or directory: u\\'/home/levesqu6/.local/share/mopidy/tag_cache\\'\\nINFO 2013-01-03 15:47:01,101 [7328:MainThread] mopidy.backends.local\\nLoading tracks from /home/levesqu6/None using /home/levesqu6/.local/share/mopidy/tag_cache\\nINFO 2013-01-03 15:47:01,102 [7328:MainThread] mopidy.backends.local\\nLoading playlists from /home/levesqu6/.local/share/mopidy/playlists\\nDEBUG 2013-01-03 15:47:01,104 [7328:MainThread] mopidy.utils\\nLoading: mopidy.backends.spotify.SpotifyBackend\\nINFO 2013-01-03 15:47:01,104 [7328:Audio-1] mopidy.audio\\nAudio output set to ""alsasink""\\nDEBUG 2013-01-03 15:47:01,123 [7328:Audio-1] mopidy.audio.mixers.auto\\nAutoAudioMixer chose: alsamixerelement1\\nINFO 2013-01-03 15:47:01,124 [7328:Audio-1] mopidy.audio\\nAudio mixer set to ""alsamixer"" using track ""Bass Boost""\\nINFO 2013-01-03 15:47:01,127 [7328:SpotifyBackend-4] mopidy.backends.spotify\\nMopidy uses SPOTIFY(R) CORE\\nDEBUG 2013-01-03 15:47:01,129 [7328:SpotifyBackend-4] mopidy.backends.spotify\\nConnecting to Spotify\\nDEBUG 2013-01-03 15:47:01,132 [7328:SpotifyThread] mopidy.utils.process\\nSpotifyThread: Starting thread\\nDEBUG 2013-01-03 15:47:01,134 [7328:SpotifyThread] mopidy.backends.spotify\\nSystem message: 20:47:01.134 I [offline_authorizer.cpp:297] Unable to login offline: no such user\\nDEBUG 2013-01-03 15:47:01,134 [7328:SpotifyThread] pyspotify.manager.session\\nNo message received before timeout. Processing events\\nDEBUG 2013-01-03 15:47:01,134 [7328:Dummy-5] mopidy.backends.spotify\\nSystem message: 20:47:01.134 I [ap:1752] Connecting to AP ap.spotify.com:4070\\nDEBUG 2013-01-03 15:47:01,135 [7328:SpotifyThread] pyspotify.manager.session\\nWill wait 300.041s for next message\\nERROR 2013-01-03 15:47:01,139 [7328:MainThread] mopidy.main\\nfloat division by zero\\nTraceback (most recent call last):\\nFile ""/usr/lib/pymodules/python2.7/mopidy/__main__.py"", line 61, in main\\ncore = setup_core(audio, backends)\\nFile ""/usr/lib/pymodules/python2.7/mopidy/__main__.py"", line 164, in setup_core\\nreturn Core.start(audio=audio, backends=backends).proxy()\\nFile ""/usr/lib/pymodules/python2.7/pykka/actor.py"", line 461, in proxy\\nreturn _ActorProxy(self)\\nFile ""/usr/lib/pymodules/python2.7/pykka/proxy.py"", line 99, in __init__\\nself._known_attrs = self._get_attributes()\\nFile ""/usr/lib/pymodules/python2.7/pykka/proxy.py"", line 111, in _get_attributes\\nattr = self._actor._get_attribute_from_path(attr_path)\\nFile ""/usr/lib/pymodules/python2.7/pykka/actor.py"", line 296, in _get_attribute_from_path\\nattr = getattr(attr, attr_name)\\nFile ""/usr/lib/pymodules/python2.7/mopidy/core/playback.py"", line 280, in get_volume\\nreturn self.audio.get_volume().get()\\nFile ""/usr/lib/pymodules/python2.7/pykka/future.py"", line 116, in get\\n\\'raise exc_info[0], exc_info[1], exc_info[2]\\')\\nFile ""/usr/lib/pymodules/python2.7/pykka/actor.py"", line 194, in _actor_loop\\nresponse = self._handle_receive(message)\\nFile ""/usr/lib/pymodules/python2.7/pykka/actor.py"", line 265, in _handle_receive\\nreturn callee(*message[\\'args\\'], **message[\\'kwargs\\'])\\nFile ""/usr/lib/pymodules/python2.7/mopidy/audio/actor.py"", line 393, in get_volume\\navg_volume = float(sum(volumes)) / len(volumes)\\nZeroDivisionError: float division by zero\\nDEBUG 2013-01-03 15:47:01,141 [7328:MainThread] mopidy.utils\\nLoading: mopidy.frontends.mpd.MpdFrontend\\nDEBUG 2013-01-03 15:47:01,183 [7328:MainThread] mopidy.utils.process\\nStopping 0 instance(s) of MpdFrontend\\nDEBUG 2013-01-03 15:47:01,183 [7328:MainThread] mopidy.utils\\nLoading: mopidy.frontends.lastfm.LastfmFrontend\\nDEBUG 2013-01-03 15:47:01,199 [7328:MainThread] mopidy.utils.process\\nStopping 0 instance(s) of LastfmFrontend\\nDEBUG 2013-01-03 15:47:01,200 [7328:Dummy-5] mopidy.backends.spotify\\nSystem message: 20:47:01.184 I [ap:1226] Connected to AP: 193.182.8.35:4070\\nDEBUG 2013-01-03 15:47:01,200 [7328:MainThread] mopidy.utils\\nLoading: mopidy.frontends.mpris.MprisFrontend\\nDEBUG 2013-01-03 15:47:01,247 [7328:MainThread] mopidy.utils.process\\nStopping 0 instance(s) of MprisFrontend\\nDEBUG 2013-01-03 15:47:01,248 [7328:MainThread] mopidy.utils.process\\nStopping 1 instance(s) of Core\\nDEBUG 2013-01-03 15:47:01,248 [7328:MainThread] mopidy.utils\\nLoading: mopidy.backends.local.LocalBackend\\nDEBUG 2013-01-03 15:47:01,248 [7328:MainThread] mopidy.utils.process\\nStopping 1 instance(s) of LocalBackend\\nDEBUG 2013-01-03 15:47:01,248 [7328:MainThread] mopidy.utils\\nLoading: mopidy.backends.spotify.SpotifyBackend\\nDEBUG 2013-01-03 15:47:01,249 [7328:MainThread] mopidy.utils.process\\nStopping 1 instance(s) of SpotifyBackend\\nDEBUG 2013-01-03 15:47:01,249 [7328:SpotifyBackend-4] mopidy.backends.spotify\\nLogging out from Spotify\\nDEBUG 2013-01-03 15:47:01,249 [7328:MainThread] mopidy.utils.process\\nStopping 1 instance(s) of Audio\\nDEBUG 2013-01-03 15:47:01,250 [7328:MainThread] mopidy.utils.process\\nAll actors stopped.'}, {'piece_type': 'other', 'piece_content': ""~$ amixer\\nSimple mixer control 'Bass Boost',0\\nCapabilities: pswitch pswitch-joined penum\\nPlayback channels: Mono\\nMono: Playback [off]\\nSimple mixer control 'PCM',0\\nCapabilities: pvolume pswitch pswitch-joined penum\\nPlayback channels: Front Left - Front Right\\nLimits: Playback 0 - 704\\nMono:\\nFront Left: Playback 90 [13%] [-35.38dB] [on]\\nFront Right: Playback 90 [13%] [-35.38dB] [on]\\nSimple mixer control 'Auto Gain Control',0\\nCapabilities: pswitch pswitch-joined penum\\nPlayback channels: Mono\\nMono: Playback [off]\\n\\n~$ aplay -l\\n**** List of PLAYBACK Hardware Devices ****\\ncard 0: Speaker [Z-10 USB Speaker], device 0: USB Audio [USB Audio]\\nSubdevices: 0/1\\nSubdevice #0: subdevice #0\\n\\n\\n:~$ aplay -L\\nnull\\nDiscard all samples (playback) or generate zero samples (capture)\\ndefault:CARD=Speaker\\nZ-10 USB Speaker, USB Audio\\nDefault Audio Device\\nsysdefault:CARD=Speaker\\nZ-10 USB Speaker, USB Audio\\nDefault Audio Device\\nfront:CARD=Speaker,DEV=0\\nZ-10 USB Speaker, USB Audio\\nFront speakers\\nsurround40:CARD=Speaker,DEV=0\\nZ-10 USB Speaker, USB Audio\\n4.0 Surround output to Front and Rear speakers\\nsurround41:CARD=Speaker,DEV=0\\nZ-10 USB Speaker, USB Audio\\n4.1 Surround output to Front, Rear and Subwoofer speakers\\nsurround50:CARD=Speaker,DEV=0\\nZ-10 USB Speaker, USB Audio\\n5.0 Surround output to Front, Center and Rear speakers\\nsurround51:CARD=Speaker,DEV=0\\nZ-10 USB Speaker, USB Audio\\n5.1 Surround output to Front, Center, Rear and Subwoofer speakers\\nsurround71:CARD=Speaker,DEV=0\\nZ-10 USB Speaker, USB Audio\\n7.1 Surround output to Front, Center, Side, Rear and Woofer speakers\\niec958:CARD=Speaker,DEV=0\\nZ-10 USB Speaker, USB Audio\\nIEC958 (S/PDIF) Digital Audio Output""}]","INFO 2013-01-03 15:47:01,091 [7328:MainThread] mopidy.utils.log +Starting Mopidy 0.11.1 +INFO 2013-01-03 15:47:01,095 [7328:MainThread] mopidy.utils.log +Platform: Linux-3.2.0-4-amd64-x86_64-with-debian-7.0 +INFO 2013-01-03 15:47:01,095 [7328:MainThread] mopidy.utils.log +Python: CPython 2.7.3rc2 +DEBUG 2013-01-03 15:47:01,097 [7328:MainThread] mopidy.utils +Loading: mopidy.backends.local.LocalBackend +WARNING 2013-01-03 15:47:01,101 [7328:MainThread] mopidy.backends.local +Could not open tag cache: [Errno 2] No such file or directory: u'/home/levesqu6/.local/share/mopidy/tag_cache' +INFO 2013-01-03 15:47:01,101 [7328:MainThread] mopidy.backends.local +Loading tracks from /home/levesqu6/None using /home/levesqu6/.local/share/mopidy/tag_cache +INFO 2013-01-03 15:47:01,102 [7328:MainThread] mopidy.backends.local +Loading playlists from /home/levesqu6/.local/share/mopidy/playlists +DEBUG 2013-01-03 15:47:01,104 [7328:MainThread] mopidy.utils +Loading: mopidy.backends.spotify.SpotifyBackend +INFO 2013-01-03 15:47:01,104 [7328:Audio-1] mopidy.audio +Audio output set to ""alsasink"" +DEBUG 2013-01-03 15:47:01,123 [7328:Audio-1] mopidy.audio.mixers.auto +AutoAudioMixer chose: alsamixerelement1 +INFO 2013-01-03 15:47:01,124 [7328:Audio-1] mopidy.audio +Audio mixer set to ""alsamixer"" using track ""Bass Boost"" +INFO 2013-01-03 15:47:01,127 [7328:SpotifyBackend-4] mopidy.backends.spotify +Mopidy uses SPOTIFY(R) CORE +DEBUG 2013-01-03 15:47:01,129 [7328:SpotifyBackend-4] mopidy.backends.spotify +Connecting to Spotify +DEBUG 2013-01-03 15:47:01,132 [7328:SpotifyThread] mopidy.utils.process +SpotifyThread: Starting thread +DEBUG 2013-01-03 15:47:01,134 [7328:SpotifyThread] mopidy.backends.spotify +System message: 20:47:01.134 I [offline_authorizer.cpp:297] Unable to login offline: no such user +DEBUG 2013-01-03 15:47:01,134 [7328:SpotifyThread] pyspotify.manager.session +No message received before timeout. Processing events +DEBUG 2013-01-03 15:47:01,134 [7328:Dummy-5] mopidy.backends.spotify +System message: 20:47:01.134 I [ap:1752] Connecting to AP ap.spotify.com:4070 +DEBUG 2013-01-03 15:47:01,135 [7328:SpotifyThread] pyspotify.manager.session +Will wait 300.041s for next message +ERROR 2013-01-03 15:47:01,139 [7328:MainThread] mopidy.main +float division by zero +Traceback (most recent call last): +File ""/usr/lib/pymodules/python2.7/mopidy/__main__.py"", line 61, in main +core = setup_core(audio, backends) +File ""/usr/lib/pymodules/python2.7/mopidy/__main__.py"", line 164, in setup_core +return Core.start(audio=audio, backends=backends).proxy() +File ""/usr/lib/pymodules/python2.7/pykka/actor.py"", line 461, in proxy +return _ActorProxy(self) +File ""/usr/lib/pymodules/python2.7/pykka/proxy.py"", line 99, in __init__ +self._known_attrs = self._get_attributes() +File ""/usr/lib/pymodules/python2.7/pykka/proxy.py"", line 111, in _get_attributes +attr = self._actor._get_attribute_from_path(attr_path) +File ""/usr/lib/pymodules/python2.7/pykka/actor.py"", line 296, in _get_attribute_from_path +attr = getattr(attr, attr_name) +File ""/usr/lib/pymodules/python2.7/mopidy/core/playback.py"", line 280, in get_volume +return self.audio.get_volume().get() +File ""/usr/lib/pymodules/python2.7/pykka/future.py"", line 116, in get +'raise exc_info[0], exc_info[1], exc_info[2]') +File ""/usr/lib/pymodules/python2.7/pykka/actor.py"", line 194, in _actor_loop +response = self._handle_receive(message) +File ""/usr/lib/pymodules/python2.7/pykka/actor.py"", line 265, in _handle_receive +return callee(*message['args'], **message['kwargs']) +File ""/usr/lib/pymodules/python2.7/mopidy/audio/actor.py"", line 393, in get_volume +avg_volume = float(sum(volumes)) / len(volumes) +ZeroDivisionError: float division by zero +DEBUG 2013-01-03 15:47:01,141 [7328:MainThread] mopidy.utils +Loading: mopidy.frontends.mpd.MpdFrontend +DEBUG 2013-01-03 15:47:01,183 [7328:MainThread] mopidy.utils.process +Stopping 0 instance(s) of MpdFrontend +DEBUG 2013-01-03 15:47:01,183 [7328:MainThread] mopidy.utils +Loading: mopidy.frontends.lastfm.LastfmFrontend +DEBUG 2013-01-03 15:47:01,199 [7328:MainThread] mopidy.utils.process +Stopping 0 instance(s) of LastfmFrontend +DEBUG 2013-01-03 15:47:01,200 [7328:Dummy-5] mopidy.backends.spotify +System message: 20:47:01.184 I [ap:1226] Connected to AP: 193.182.8.35:4070 +DEBUG 2013-01-03 15:47:01,200 [7328:MainThread] mopidy.utils +Loading: mopidy.frontends.mpris.MprisFrontend +DEBUG 2013-01-03 15:47:01,247 [7328:MainThread] mopidy.utils.process +Stopping 0 instance(s) of MprisFrontend +DEBUG 2013-01-03 15:47:01,248 [7328:MainThread] mopidy.utils.process +Stopping 1 instance(s) of Core +DEBUG 2013-01-03 15:47:01,248 [7328:MainThread] mopidy.utils +Loading: mopidy.backends.local.LocalBackend +DEBUG 2013-01-03 15:47:01,248 [7328:MainThread] mopidy.utils.process +Stopping 1 instance(s) of LocalBackend +DEBUG 2013-01-03 15:47:01,248 [7328:MainThread] mopidy.utils +Loading: mopidy.backends.spotify.SpotifyBackend +DEBUG 2013-01-03 15:47:01,249 [7328:MainThread] mopidy.utils.process +Stopping 1 instance(s) of SpotifyBackend +DEBUG 2013-01-03 15:47:01,249 [7328:SpotifyBackend-4] mopidy.backends.spotify +Logging out from Spotify +DEBUG 2013-01-03 15:47:01,249 [7328:MainThread] mopidy.utils.process +Stopping 1 instance(s) of Audio +DEBUG 2013-01-03 15:47:01,250 [7328:MainThread] mopidy.utils.process +All actors stopped.",ZeroDivisionError +"def parse_m3u(file_path, music_folder): + """""" + Convert M3U file list of uris + + Example M3U data:: + + # This is a comment + Alternative\\Band - Song.mp3 + Classical\\Other Band - New Song.mp3 + Stuff.mp3 + D:\\More Music\\Foo.mp3 + http://www.example.com:8000/Listen.pls + http://www.example.com/~user/Mine.mp3 + + - Relative paths of songs should be with respect to location of M3U. + - Paths are normaly platform specific. + - Lines starting with # should be ignored. + - m3u files are latin-1. + - This function does not bother with Extended M3U directives. + """""" + + uris = [] + try: + with open(file_path) as m3u: + contents = m3u.readlines() + except IOError as error: + logger.error('Couldn\\'t open m3u: %s', locale_decode(error)) + return uris + + for line in contents: + line = line.strip().decode('latin1') + + if line.startswith('#'): + continue + + # FIXME what about other URI types? + if line.startswith('file://'): + uris.append(line) + else: + path = path_to_uri(music_folder, line) + uris.append(path) + + return uris","def parse_m3u(file_path): + """""" + Convert M3U file list of uris + + Example M3U data:: + + # This is a comment + Alternative\\Band - Song.mp3 + Classical\\Other Band - New Song.mp3 + Stuff.mp3 + D:\\More Music\\Foo.mp3 + http://www.example.com:8000/Listen.pls + http://www.example.com/~user/Mine.mp3 + + - Relative paths of songs should be with respect to location of M3U. + - Paths are normaly platform specific. + - Lines starting with # should be ignored. + - m3u files are latin-1. + - This function does not bother with Extended M3U directives. + """""" + + uris = [] + folder = os.path.dirname(file_path) + + try: + with open(file_path) as m3u: + contents = m3u.readlines() + except IOError as error: + logger.error('Couldn\\'t open m3u: %s', locale_decode(error)) + return uris + + for line in contents: + line = line.strip().decode('latin1') + + if line.startswith('#'): + continue + + # FIXME what about other URI types? + if line.startswith('file://'): + uris.append(line) + else: + path = path_to_uri(folder, line) + uris.append(path) + + return uris","[{'piece_type': 'error message', 'piece_content': '$ PYTHONPATH=. ./bin/mopidy-scan\\nINFO 2012-09-11 15:56:32,431 [15354:MainThread] root\\nScanning None\\nTraceback (most recent call last):\\nFile ""./bin/mopidy-scan"", line 26, in \\nscanner = Scanner(settings.LOCAL_MUSIC_PATH, store, debug)\\nFile ""/home/jodal/dev/mopidy/mopidy/scanner.py"", line 55, in __init__\\nself.uris = [path_to_uri(f) for f in find_files(folder)]\\nFile ""/home/jodal/dev/mopidy/mopidy/utils/path.py"", line 53, in find_files\\nif os.path.isfile(path):\\nFile ""/home/jodal/dev/virtualenvs/mopidy/lib/python2.7/genericpath.py"", line 29, in isfile\\nst = os.stat(path)\\nTypeError: coercing to Unicode: need string or buffer, NoneType found'}]","$ PYTHONPATH=. ./bin/mopidy-scan +INFO 2012-09-11 15:56:32,431 [15354:MainThread] root +Scanning None +Traceback (most recent call last): +File ""./bin/mopidy-scan"", line 26, in +scanner = Scanner(settings.LOCAL_MUSIC_PATH, store, debug) +File ""/home/jodal/dev/mopidy/mopidy/scanner.py"", line 55, in __init__ +self.uris = [path_to_uri(f) for f in find_files(folder)] +File ""/home/jodal/dev/mopidy/mopidy/utils/path.py"", line 53, in find_files +if os.path.isfile(path): +File ""/home/jodal/dev/virtualenvs/mopidy/lib/python2.7/genericpath.py"", line 29, in isfile +st = os.stat(path) +TypeError: coercing to Unicode: need string or buffer, NoneType found",TypeError +" def __init__(self, folder, data_callback, error_callback=None): + self.files = find_files(folder) + self.data_callback = data_callback + self.error_callback = error_callback + self.loop = gobject.MainLoop() + + fakesink = gst.element_factory_make('fakesink') + + self.uribin = gst.element_factory_make('uridecodebin') + self.uribin.set_property('caps', gst.Caps('audio/x-raw-int')) + self.uribin.connect('pad-added', self.process_new_pad, + fakesink.get_pad('sink')) + + self.pipe = gst.element_factory_make('pipeline') + self.pipe.add(self.uribin) + self.pipe.add(fakesink) + + bus = self.pipe.get_bus() + bus.add_signal_watch() + bus.connect('message::tag', self.process_tags) + bus.connect('message::error', self.process_error)"," def __init__(self, folder, data_callback, error_callback=None): + self.uris = [path_to_uri(f) for f in find_files(folder)] + self.data_callback = data_callback + self.error_callback = error_callback + self.loop = gobject.MainLoop() + + fakesink = gst.element_factory_make('fakesink') + + self.uribin = gst.element_factory_make('uridecodebin') + self.uribin.set_property('caps', gst.Caps('audio/x-raw-int')) + self.uribin.connect('pad-added', self.process_new_pad, + fakesink.get_pad('sink')) + + self.pipe = gst.element_factory_make('pipeline') + self.pipe.add(self.uribin) + self.pipe.add(fakesink) + + bus = self.pipe.get_bus() + bus.add_signal_watch() + bus.connect('message::tag', self.process_tags) + bus.connect('message::error', self.process_error)","[{'piece_type': 'error message', 'piece_content': '$ PYTHONPATH=. ./bin/mopidy-scan\\nINFO 2012-09-11 15:56:32,431 [15354:MainThread] root\\nScanning None\\nTraceback (most recent call last):\\nFile ""./bin/mopidy-scan"", line 26, in \\nscanner = Scanner(settings.LOCAL_MUSIC_PATH, store, debug)\\nFile ""/home/jodal/dev/mopidy/mopidy/scanner.py"", line 55, in __init__\\nself.uris = [path_to_uri(f) for f in find_files(folder)]\\nFile ""/home/jodal/dev/mopidy/mopidy/utils/path.py"", line 53, in find_files\\nif os.path.isfile(path):\\nFile ""/home/jodal/dev/virtualenvs/mopidy/lib/python2.7/genericpath.py"", line 29, in isfile\\nst = os.stat(path)\\nTypeError: coercing to Unicode: need string or buffer, NoneType found'}]","$ PYTHONPATH=. ./bin/mopidy-scan +INFO 2012-09-11 15:56:32,431 [15354:MainThread] root +Scanning None +Traceback (most recent call last): +File ""./bin/mopidy-scan"", line 26, in +scanner = Scanner(settings.LOCAL_MUSIC_PATH, store, debug) +File ""/home/jodal/dev/mopidy/mopidy/scanner.py"", line 55, in __init__ +self.uris = [path_to_uri(f) for f in find_files(folder)] +File ""/home/jodal/dev/mopidy/mopidy/utils/path.py"", line 53, in find_files +if os.path.isfile(path): +File ""/home/jodal/dev/virtualenvs/mopidy/lib/python2.7/genericpath.py"", line 29, in isfile +st = os.stat(path) +TypeError: coercing to Unicode: need string or buffer, NoneType found",TypeError +" def next_uri(self): + try: + uri = path_to_uri(self.files.next()) + except StopIteration: + self.stop() + return False + self.pipe.set_state(gst.STATE_NULL) + self.uribin.set_property('uri', uri) + self.pipe.set_state(gst.STATE_PAUSED) + return True"," def next_uri(self): + if not self.uris: + return self.stop() + + self.pipe.set_state(gst.STATE_NULL) + self.uribin.set_property('uri', self.uris.pop()) + self.pipe.set_state(gst.STATE_PAUSED)","[{'piece_type': 'error message', 'piece_content': '$ PYTHONPATH=. ./bin/mopidy-scan\\nINFO 2012-09-11 15:56:32,431 [15354:MainThread] root\\nScanning None\\nTraceback (most recent call last):\\nFile ""./bin/mopidy-scan"", line 26, in \\nscanner = Scanner(settings.LOCAL_MUSIC_PATH, store, debug)\\nFile ""/home/jodal/dev/mopidy/mopidy/scanner.py"", line 55, in __init__\\nself.uris = [path_to_uri(f) for f in find_files(folder)]\\nFile ""/home/jodal/dev/mopidy/mopidy/utils/path.py"", line 53, in find_files\\nif os.path.isfile(path):\\nFile ""/home/jodal/dev/virtualenvs/mopidy/lib/python2.7/genericpath.py"", line 29, in isfile\\nst = os.stat(path)\\nTypeError: coercing to Unicode: need string or buffer, NoneType found'}]","$ PYTHONPATH=. ./bin/mopidy-scan +INFO 2012-09-11 15:56:32,431 [15354:MainThread] root +Scanning None +Traceback (most recent call last): +File ""./bin/mopidy-scan"", line 26, in +scanner = Scanner(settings.LOCAL_MUSIC_PATH, store, debug) +File ""/home/jodal/dev/mopidy/mopidy/scanner.py"", line 55, in __init__ +self.uris = [path_to_uri(f) for f in find_files(folder)] +File ""/home/jodal/dev/mopidy/mopidy/utils/path.py"", line 53, in find_files +if os.path.isfile(path): +File ""/home/jodal/dev/virtualenvs/mopidy/lib/python2.7/genericpath.py"", line 29, in isfile +st = os.stat(path) +TypeError: coercing to Unicode: need string or buffer, NoneType found",TypeError +" def start(self): + if self.next_uri(): + self.loop.run()"," def start(self): + if not self.uris: + return + self.next_uri() + self.loop.run()","[{'piece_type': 'error message', 'piece_content': '$ PYTHONPATH=. ./bin/mopidy-scan\\nINFO 2012-09-11 15:56:32,431 [15354:MainThread] root\\nScanning None\\nTraceback (most recent call last):\\nFile ""./bin/mopidy-scan"", line 26, in \\nscanner = Scanner(settings.LOCAL_MUSIC_PATH, store, debug)\\nFile ""/home/jodal/dev/mopidy/mopidy/scanner.py"", line 55, in __init__\\nself.uris = [path_to_uri(f) for f in find_files(folder)]\\nFile ""/home/jodal/dev/mopidy/mopidy/utils/path.py"", line 53, in find_files\\nif os.path.isfile(path):\\nFile ""/home/jodal/dev/virtualenvs/mopidy/lib/python2.7/genericpath.py"", line 29, in isfile\\nst = os.stat(path)\\nTypeError: coercing to Unicode: need string or buffer, NoneType found'}]","$ PYTHONPATH=. ./bin/mopidy-scan +INFO 2012-09-11 15:56:32,431 [15354:MainThread] root +Scanning None +Traceback (most recent call last): +File ""./bin/mopidy-scan"", line 26, in +scanner = Scanner(settings.LOCAL_MUSIC_PATH, store, debug) +File ""/home/jodal/dev/mopidy/mopidy/scanner.py"", line 55, in __init__ +self.uris = [path_to_uri(f) for f in find_files(folder)] +File ""/home/jodal/dev/mopidy/mopidy/utils/path.py"", line 53, in find_files +if os.path.isfile(path): +File ""/home/jodal/dev/virtualenvs/mopidy/lib/python2.7/genericpath.py"", line 29, in isfile +st = os.stat(path) +TypeError: coercing to Unicode: need string or buffer, NoneType found",TypeError +"def import_targets(request): + context = {} + context['import_target_li'] = 'active' + context['target_data_active'] = 'true' + if request.method == 'POST': + if 'txtFile' in request.FILES: + txt_file = request.FILES['txtFile'] + if txt_file.content_type == 'text/plain': + target_count = 0 + txt_content = txt_file.read().decode('UTF-8') + io_string = io.StringIO(txt_content) + for target in io_string: + if validators.domain(target): + Domain.objects.create( + domain_name=target.rstrip(""\\n""), insert_date=timezone.now()) + target_count += 1 + if target_count: + messages.add_message(request, messages.SUCCESS, str( + target_count) + ' targets added successfully!') + return http.HttpResponseRedirect(reverse('list_target')) + else: + messages.add_message( + request, + messages.ERROR, + 'Oops! File format was invalid, could not import any targets.') + else: + messages.add_message( + request, messages.ERROR, 'Invalid File type!') + elif 'csvFile' in request.FILES: + csv_file = request.FILES['csvFile'] + if csv_file.content_type == 'text/csv': + target_count = 0 + csv_content = csv_file.read().decode('UTF-8') + io_string = io.StringIO(csv_content) + for column in csv.reader(io_string, delimiter=','): + if validators.domain(column[0]): + Domain.objects.create( + domain_name=column[0], + domain_description=column[1], + insert_date=timezone.now()) + target_count += 1 + if target_count: + messages.add_message(request, messages.SUCCESS, str( + target_count) + ' targets added successfully!') + return http.HttpResponseRedirect(reverse('list_target')) + else: + messages.add_message( + request, + messages.ERROR, + 'Oops! File format was invalid, could not import any targets.') + else: + messages.add_message( + request, messages.ERROR, 'Invalid File type!') + return render(request, 'target/import.html', context)","def import_targets(request): + context = {} + context['import_target_li'] = 'active' + context['target_data_active'] = 'true' + if request.method == 'POST': + if 'txtFile' in request.FILES: + txt_file = request.FILES['txtFile'] + if txt_file.content_type == 'text/plain': + target_count = 0 + txt_content = txt_file.read().decode('UTF-8') + io_string = io.StringIO(txt_content) + for target in io_string: + if validators.domain(target): + Domain.objects.create( + domain_name=target, insert_date=timezone.now()) + target_count += 1 + if target_count: + messages.add_message(request, messages.SUCCESS, str( + target_count) + ' targets added successfully!') + return http.HttpResponseRedirect(reverse('list_target')) + else: + messages.add_message( + request, + messages.ERROR, + 'Oops! File format was invalid, could not import any targets.') + else: + messages.add_message( + request, messages.ERROR, 'Invalid File type!') + elif 'csvFile' in request.FILES: + csv_file = request.FILES['csvFile'] + if csv_file.content_type == 'text/csv': + target_count = 0 + csv_content = csv_file.read().decode('UTF-8') + io_string = io.StringIO(csv_content) + for column in csv.reader(io_string, delimiter=','): + if validators.domain(column[0]): + Domain.objects.create( + domain_name=column[0], + domain_description=column[1], + insert_date=timezone.now()) + target_count += 1 + if target_count: + messages.add_message(request, messages.SUCCESS, str( + target_count) + ' targets added successfully!') + return http.HttpResponseRedirect(reverse('list_target')) + else: + messages.add_message( + request, + messages.ERROR, + 'Oops! File format was invalid, could not import any targets.') + else: + messages.add_message( + request, messages.ERROR, 'Invalid File type!') + return render(request, 'target/import.html', context)","[{'piece_type': 'error message', 'piece_content': 'Running migrations:\\nNo migrations to apply.\\nInstalled 3 object(s) from 1 fixture(s)\\n[2020-09-07 09:47:08 +0000] [1] [INFO] Starting gunicorn 20.0.4\\n[2020-09-07 09:47:08 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)\\n[2020-09-07 09:47:08 +0000] [1] [INFO] Using worker: sync\\n[2020-09-07 09:47:08 +0000] [12] [INFO] Booting worker with pid: 12\\ncat: can\\'t open \\'/*.txt\\': No such file or directory\\nsh: twitter.com: not found\\nsh: _2020_09_07_09_47_35: not found\\nTraceback (most recent call last):\\nFile ""/app/startScan/views.py"", line 184, in doScan\\nwith open(subdomain_scan_results_file) as subdomain_list:\\nFileNotFoundError: [Errno 2] No such file or directory: \\'/app/tools/scan_results/twitter.com\\\\n_2020_09_07_09_47_35/sorted_subdomain_collection.txt\\''}]","Running migrations: +No migrations to apply. +Installed 3 object(s) from 1 fixture(s) +[2020-09-07 09:47:08 +0000] [1] [INFO] Starting gunicorn 20.0.4 +[2020-09-07 09:47:08 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) +[2020-09-07 09:47:08 +0000] [1] [INFO] Using worker: sync +[2020-09-07 09:47:08 +0000] [12] [INFO] Booting worker with pid: 12 +cat: can't open '/*.txt': No such file or directory +sh: twitter.com: not found +sh: _2020_09_07_09_47_35: not found +Traceback (most recent call last): +File ""/app/startScan/views.py"", line 184, in doScan +with open(subdomain_scan_results_file) as subdomain_list: +FileNotFoundError: [Errno 2] No such file or directory: '/app/tools/scan_results/twitter.com\\n_2020_09_07_09_47_35/sorted_subdomain_collection.txt'",FileNotFoundError +" def __init__(self, key_prefixes, runtime_dirs=get_runtime_dirs()): + key_prefixes = map(self._sanitize, key_prefixes) + # compute read and write dirs from base runtime dirs: the first base + # dir is selected for writes and prefered for reads + self._read_dirs = [os.path.join(x, *key_prefixes) for x in runtime_dirs] + self._write_dir = self._read_dirs[0] + os.makedirs(self._write_dir, exist_ok=True) + if sys.platform == 'linux': + # set the sticky bit to prevent removal during cleanup + os.chmod(self._write_dir, 0o1700) + _LOGGER.debug('data in %s', self._write_dir)"," def __init__(self, key_prefixes): + key_prefixes = map(self._sanitize, key_prefixes) + # compute read and write dirs from base runtime dirs: the first base + # dir is selected for writes and prefered for reads + self._read_dirs = [os.path.join(x, *key_prefixes) for x in get_runtime_dirs()] + self._write_dir = self._read_dirs[0] + os.makedirs(self._write_dir, exist_ok=True) + if sys.platform == 'linux': + # set the sticky bit to prevent removal during cleanup + os.chmod(self._write_dir, 0o1700) + _LOGGER.debug('data in %s', self._write_dir)","[{'piece_type': 'error message', 'piece_content': 'C:\\\\>liquidctl list --verbose\\nDevice ID 0: Corsair H100i PRO XT (experimental)\\n├── Vendor ID: 0x1b1c\\n├── Product ID: 0x0c20\\n├── Release number: 0x0100\\n├── Bus: hid\\n├── Address: \\\\\\\\?\\\\hid#vid_1b1c&pid_0c20#7&1e4e78f5&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}\\n└── Driver: HydroPlatinum using module hid\\n\\n\\nC:\\\\>liquidctl initialize all\\nERROR: Unexpected error with Corsair H100i PRO XT (experimental)\\nTraceback (most recent call last):\\nValueError: source code string cannot contain null bytes'}]","C:\\>liquidctl list --verbose +Device ID 0: Corsair H100i PRO XT (experimental) +├── Vendor ID: 0x1b1c +├── Product ID: 0x0c20 +├── Release number: 0x0100 +├── Bus: hid +├── Address: \\\\?\\hid#vid_1b1c&pid_0c20#7&1e4e78f5&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030} +└── Driver: HydroPlatinum using module hid + + +C:\\>liquidctl initialize all +ERROR: Unexpected error with Corsair H100i PRO XT (experimental) +Traceback (most recent call last): +ValueError: source code string cannot contain null bytes",ValueError +" def load(self, key): + for base in self._read_dirs: + path = os.path.join(base, key) + if not os.path.isfile(path): + continue + try: + with open(path, mode='r') as f: + data = f.read().strip() + if len(data) == 0: + value = None + else: + value = literal_eval(data) + _LOGGER.debug('loaded %s=%r (from %s)', key, value, path) + except OSError as err: + _LOGGER.warning('%s exists but could not be read: %s', path, err) + except ValueError as err: + _LOGGER.warning('%s exists but was corrupted: %s', key, err) + else: + return value + + _LOGGER.debug('no data (file) found for %s', key) + return None"," def load(self, key): + for base in self._read_dirs: + path = os.path.join(base, key) + if not os.path.isfile(path): + continue + try: + with open(path, mode='r') as f: + data = f.read().strip() + if len(data) == 0: + value = None + else: + value = literal_eval(data) + _LOGGER.debug('loaded %s=%r (from %s)', key, value, path) + except OSError as err: + _LOGGER.warning('%s exists but cannot be read: %s', path, err) + continue + return value + _LOGGER.debug('no data (file) found for %s', key) + return None","[{'piece_type': 'error message', 'piece_content': 'C:\\\\>liquidctl list --verbose\\nDevice ID 0: Corsair H100i PRO XT (experimental)\\n├── Vendor ID: 0x1b1c\\n├── Product ID: 0x0c20\\n├── Release number: 0x0100\\n├── Bus: hid\\n├── Address: \\\\\\\\?\\\\hid#vid_1b1c&pid_0c20#7&1e4e78f5&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}\\n└── Driver: HydroPlatinum using module hid\\n\\n\\nC:\\\\>liquidctl initialize all\\nERROR: Unexpected error with Corsair H100i PRO XT (experimental)\\nTraceback (most recent call last):\\nValueError: source code string cannot contain null bytes'}]","C:\\>liquidctl list --verbose +Device ID 0: Corsair H100i PRO XT (experimental) +├── Vendor ID: 0x1b1c +├── Product ID: 0x0c20 +├── Release number: 0x0100 +├── Bus: hid +├── Address: \\\\?\\hid#vid_1b1c&pid_0c20#7&1e4e78f5&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030} +└── Driver: HydroPlatinum using module hid + + +C:\\>liquidctl initialize all +ERROR: Unexpected error with Corsair H100i PRO XT (experimental) +Traceback (most recent call last): +ValueError: source code string cannot contain null bytes",ValueError +" def _write(self, data): + assert len(data) <= _REPORT_LENGTH + packet = bytearray(1 + _REPORT_LENGTH) + packet[1 : 1 + len(data)] = data # device doesn't use numbered reports + self.device.write(packet)"," def _write(self, data): + padding = [0x0]*(_WRITE_LENGTH - len(data)) + self.device.write(data + padding)","[{'piece_type': 'error message', 'piece_content': 'PS E:\\\\liquidctl> .\\\\liquidctl status\\nNZXT Kraken X (X42, X52, X62 or X72)\\n├── Liquid temperature 30.4 °C\\n├── Fan speed 1100 rpm\\n├── Pump speed 2703 rpm\\n└── Firmware version 6.0.2\\n\\nERROR: Unexpected error with NZXT E850 (experimental)\\nTraceback (most recent call last):\\nAssertionError: invalid response (attempts=3)\\n\\nAnd here is the debug output:\\n\\n[DEBUG] __main__: device: NZXT E850 (experimental)\\n[DEBUG] liquidctl.driver.usb: discarded 0 previously enqueued reports\\n[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[ERROR] __main__: Unexpected error with NZXT E850 (experimental)\\nTraceback (most recent call last):\\nFile ""liquidctl\\\\cli.py"", line 302, in main\\nFile ""liquidctl\\\\driver\\\\nzxt_epsu.py"", line 59, in get_status\\nFile ""liquidctl\\\\driver\\\\nzxt_epsu.py"", line 145, in _get_fw_versions\\nFile ""liquidctl\\\\driver\\\\nzxt_epsu.py"", line 113, in _exec_read\\nAssertionError: invalid response (attempts=3)'}]","PS E:\\liquidctl> .\\liquidctl status +NZXT Kraken X (X42, X52, X62 or X72) +├── Liquid temperature 30.4 °C +├── Fan speed 1100 rpm +├── Pump speed 2703 rpm +└── Firmware version 6.0.2 + +ERROR: Unexpected error with NZXT E850 (experimental) +Traceback (most recent call last): +AssertionError: invalid response (attempts=3) + +And here is the debug output: + +[DEBUG] __main__: device: NZXT E850 (experimental) +[DEBUG] liquidctl.driver.usb: discarded 0 previously enqueued reports +[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[ERROR] __main__: Unexpected error with NZXT E850 (experimental) +Traceback (most recent call last): +File ""liquidctl\\cli.py"", line 302, in main +File ""liquidctl\\driver\\nzxt_epsu.py"", line 59, in get_status +File ""liquidctl\\driver\\nzxt_epsu.py"", line 145, in _get_fw_versions +File ""liquidctl\\driver\\nzxt_epsu.py"", line 113, in _exec_read +AssertionError: invalid response (attempts=3)",AssertionError +" def _read(self): + return self.device.read(_REPORT_LENGTH)"," def _read(self): + return self.device.read(_READ_LENGTH)","[{'piece_type': 'error message', 'piece_content': 'PS E:\\\\liquidctl> .\\\\liquidctl status\\nNZXT Kraken X (X42, X52, X62 or X72)\\n├── Liquid temperature 30.4 °C\\n├── Fan speed 1100 rpm\\n├── Pump speed 2703 rpm\\n└── Firmware version 6.0.2\\n\\nERROR: Unexpected error with NZXT E850 (experimental)\\nTraceback (most recent call last):\\nAssertionError: invalid response (attempts=3)\\n\\nAnd here is the debug output:\\n\\n[DEBUG] __main__: device: NZXT E850 (experimental)\\n[DEBUG] liquidctl.driver.usb: discarded 0 previously enqueued reports\\n[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\\n[ERROR] __main__: Unexpected error with NZXT E850 (experimental)\\nTraceback (most recent call last):\\nFile ""liquidctl\\\\cli.py"", line 302, in main\\nFile ""liquidctl\\\\driver\\\\nzxt_epsu.py"", line 59, in get_status\\nFile ""liquidctl\\\\driver\\\\nzxt_epsu.py"", line 145, in _get_fw_versions\\nFile ""liquidctl\\\\driver\\\\nzxt_epsu.py"", line 113, in _exec_read\\nAssertionError: invalid response (attempts=3)'}]","PS E:\\liquidctl> .\\liquidctl status +NZXT Kraken X (X42, X52, X62 or X72) +├── Liquid temperature 30.4 °C +├── Fan speed 1100 rpm +├── Pump speed 2703 rpm +└── Firmware version 6.0.2 + +ERROR: Unexpected error with NZXT E850 (experimental) +Traceback (most recent call last): +AssertionError: invalid response (attempts=3) + +And here is the debug output: + +[DEBUG] __main__: device: NZXT E850 (experimental) +[DEBUG] liquidctl.driver.usb: discarded 0 previously enqueued reports +[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[DEBUG] liquidctl.driver.usb: writting report 0xad with 63 bytes: 00:03:01:60:fc:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[DEBUG] liquidctl.driver.usb: read 64 bytes: aa:04:02:08:d2:45:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 +[ERROR] __main__: Unexpected error with NZXT E850 (experimental) +Traceback (most recent call last): +File ""liquidctl\\cli.py"", line 302, in main +File ""liquidctl\\driver\\nzxt_epsu.py"", line 59, in get_status +File ""liquidctl\\driver\\nzxt_epsu.py"", line 145, in _get_fw_versions +File ""liquidctl\\driver\\nzxt_epsu.py"", line 113, in _exec_read +AssertionError: invalid response (attempts=3)",AssertionError +" def connect(self, **kwargs): + """"""Connect to the device."""""" + super().connect(**kwargs) + ids = f'vid{self.vendor_id:04x}_pid{self.product_id:04x}' + # must use the HID path because there is no serial number; however, + # these can be quite long on Windows and macOS, so only take the + # numbers, since they are likely the only parts that vary between two + # devices of the same model + loc = 'loc' + '_'.join(re.findall(r'\\d+', self.address)) + self._data = RuntimeStorage(key_prefixes=[ids, loc]) + self._sequence = _sequence(self._data)"," def connect(self, **kwargs): + """"""Connect to the device."""""" + super().connect(**kwargs) + ids = f'vid{self.vendor_id:04x}_pid{self.product_id:04x}' + # must use the HID path because there is no serial number; however, + # these can be quite long on Windows and macOS, so only take the + # numbers, since they are likely the only parts that vary between two + # devices of the same model + loc = 'loc' + '_'.join((num.decode() for num in re.findall(b'\\\\d+', self.address))) + self._data = RuntimeStorage(key_prefixes=[ids, loc]) + self._sequence = _sequence(self._data)","[{'piece_type': 'error message', 'piece_content': '[DEBUG] __main__: device: Corsair H115i PRO XT (experimental)\\nself.address: ""/dev/hidraw1""\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/runpy.py"", line 194, in _run_module_as_main\\nreturn _run_code(code, main_globals, None,\\nFile ""/usr/lib/python3.8/runpy.py"", line 87, in _run_code\\nexec(code, run_globals)\\nFile ""/home/meta/src/liquidctl/liquidctl/cli.py"", line 327, in \\nmain()\\nFile ""/home/meta/src/liquidctl/liquidctl/cli.py"", line 297, in main\\ndev.connect(**opts)\\nFile ""/home/meta/src/liquidctl/liquidctl/driver/hydro_platinum.py"", line 158, in connect\\nloc = \\'loc\\' + \\'_\\'.join((num.decode() for num in re.findall(b\\'\\\\\\\\d+\\', self.address)))\\nFile ""/usr/lib/python3.8/re.py"", line 241, in findall\\nreturn _compile(pattern, flags).findall(string)\\nTypeError: cannot use a bytes pattern on a string-like object'}]","[DEBUG] __main__: device: Corsair H115i PRO XT (experimental) +self.address: ""/dev/hidraw1"" +Traceback (most recent call last): +File ""/usr/lib/python3.8/runpy.py"", line 194, in _run_module_as_main +return _run_code(code, main_globals, None, +File ""/usr/lib/python3.8/runpy.py"", line 87, in _run_code +exec(code, run_globals) +File ""/home/meta/src/liquidctl/liquidctl/cli.py"", line 327, in +main() +File ""/home/meta/src/liquidctl/liquidctl/cli.py"", line 297, in main +dev.connect(**opts) +File ""/home/meta/src/liquidctl/liquidctl/driver/hydro_platinum.py"", line 158, in connect +loc = 'loc' + '_'.join((num.decode() for num in re.findall(b'\\\\d+', self.address))) +File ""/usr/lib/python3.8/re.py"", line 241, in findall +return _compile(pattern, flags).findall(string) +TypeError: cannot use a bytes pattern on a string-like object",TypeError +" def connect(self, **kwargs): + """"""Connect to the device. + + Enables the device to send data to the host."""""" + super().connect(**kwargs) + self._configure_flow_control(clear_to_send=True)"," def connect(self, **kwargs): + """"""Connect to the device."""""" + super().connect() + try: + self._open() + except usb.core.USBError as err: + LOGGER.warning('report: failed to open right away, will close first') + LOGGER.debug(err, exc_info=True) + self._close() + self._open() + finally: + self.device.release()","[{'piece_type': 'other', 'piece_content': '# extra/liquiddump --product 0xb200 --interval 3\\n# extra/tests/asetek_modern'}, {'piece_type': 'error message', 'piece_content': '# extra/liquiddump --product 0xb200 --interval 3\\n{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\\\u00b0C""], [""Fan speed"", 420, ""rpm""], [""Pump speed"", 2670, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]}\\n{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\\\u00b0C""], [""Fan speed"", 480, ""rpm""], [""Pump speed"", 2610, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]}\\n{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\\\u00b0C""], [""Fan speed"", 420, ""rpm""], [""Pump speed"", 2640, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]}\\nUnexpected error\\nTraceback (most recent call last):\\nFile ""extra/liquiddump"", line 92, in \\nstatus[d.description] = d.get_status()\\nFile ""/usr/lib/python3.7/site-packages/liquidctl/driver/asetek.py"", line 221, in get_status\\nmsg = self._end_transaction_and_read()\\nFile ""/usr/lib/python3.7/site-packages/liquidctl/driver/asetek.py"", line 140, in _end_transaction_and_read\\nmsg = self.device.read(_READ_ENDPOINT, _READ_LENGTH, _READ_TIMEOUT)\\nFile ""/usr/lib/python3.7/site-packages/liquidctl/driver/usb.py"", line 260, in read\\nreturn self.usbdev.read(endpoint, length, timeout=timeout)\\nFile ""/usr/lib/python3.7/site-packages/usb/core.py"", line 988, in read\\nself.__get_timeout(timeout))\\nFile ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 833, in bulk_read\\ntimeout)\\nFile ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 936, in __read\\n_check(retval)\\nFile ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 595, in _check\\nraise USBError(_strerror(ret), ret, _libusb_errno[ret])\\nusb.core.USBError: [Errno 110] Operation timed out\\n\\n$ echo $?\\n0'}, {'piece_type': 'other', 'piece_content': ""# extra/tests/asetek_modern\\n+ DEVICE='--vendor 0x2433 --product 0xb200'\\n+ liquidctl --vendor 0x2433 --product 0xb200 list --verbose\\nDevice 0, Asetek 690LC (assuming EVGA CLC)\\nVendor ID: 0x2433\\nProduct ID: 0xb200\\nRelease number: 0x0100\\nSerial number: CCVI_1.0\\nBus: usb1\\nAddress: 10\\nPort: 12\\nHierarchy: AsetekDriver, CommonAsetekDriver, UsbDeviceDriver, BaseDriver; PyUsbDevice=usb\\n\\n+ liquidctl --vendor 0x2433 --product 0xb200 initialize\\n+ sleep 2\\n+ liquidctl --vendor 0x2433 --product 0xb200 status\\nDevice 0, Asetek 690LC (assuming EVGA CLC)\\nusb.core.USBError: [Errno 16] Resource busy\\n\\n$ echo $?\\n1""}]","# extra/liquiddump --product 0xb200 --interval 3 +{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\u00b0C""], [""Fan speed"", 420, ""rpm""], [""Pump speed"", 2670, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]} +{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\u00b0C""], [""Fan speed"", 480, ""rpm""], [""Pump speed"", 2610, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]} +{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\u00b0C""], [""Fan speed"", 420, ""rpm""], [""Pump speed"", 2640, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]} +Unexpected error +Traceback (most recent call last): +File ""extra/liquiddump"", line 92, in +status[d.description] = d.get_status() +File ""/usr/lib/python3.7/site-packages/liquidctl/driver/asetek.py"", line 221, in get_status +msg = self._end_transaction_and_read() +File ""/usr/lib/python3.7/site-packages/liquidctl/driver/asetek.py"", line 140, in _end_transaction_and_read +msg = self.device.read(_READ_ENDPOINT, _READ_LENGTH, _READ_TIMEOUT) +File ""/usr/lib/python3.7/site-packages/liquidctl/driver/usb.py"", line 260, in read +return self.usbdev.read(endpoint, length, timeout=timeout) +File ""/usr/lib/python3.7/site-packages/usb/core.py"", line 988, in read +self.__get_timeout(timeout)) +File ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 833, in bulk_read +timeout) +File ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 936, in __read +_check(retval) +File ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 595, in _check +raise USBError(_strerror(ret), ret, _libusb_errno[ret]) +usb.core.USBError: [Errno 110] Operation timed out + +$ echo $? +0",usb.core.USBError +" def disconnect(self, **kwargs): + """"""Disconnect from the device. + + Implementation note: unlike SI_Close is supposed to do,¹ do not send + _USBXPRESS_NOT_CLEAR_TO_SEND to the device. This allows one program to + disconnect without sotping reads from another. + + Surrounding device.read() with _USBXPRESS_[NOT_]CLEAR_TO_SEND would + make more sense, but there seems to be a yet unknown minimum delay + necessary for that to work well. + + ¹ https://github.com/craigshelley/SiUSBXp/blob/master/SiUSBXp.c + """""" + super().disconnect(**kwargs)"," def disconnect(self, **kwargs): + """"""Disconnect from the device."""""" + self._close() + super().disconnect() + self.device.release()","[{'piece_type': 'other', 'piece_content': '# extra/liquiddump --product 0xb200 --interval 3\\n# extra/tests/asetek_modern'}, {'piece_type': 'error message', 'piece_content': '# extra/liquiddump --product 0xb200 --interval 3\\n{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\\\u00b0C""], [""Fan speed"", 420, ""rpm""], [""Pump speed"", 2670, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]}\\n{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\\\u00b0C""], [""Fan speed"", 480, ""rpm""], [""Pump speed"", 2610, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]}\\n{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\\\u00b0C""], [""Fan speed"", 420, ""rpm""], [""Pump speed"", 2640, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]}\\nUnexpected error\\nTraceback (most recent call last):\\nFile ""extra/liquiddump"", line 92, in \\nstatus[d.description] = d.get_status()\\nFile ""/usr/lib/python3.7/site-packages/liquidctl/driver/asetek.py"", line 221, in get_status\\nmsg = self._end_transaction_and_read()\\nFile ""/usr/lib/python3.7/site-packages/liquidctl/driver/asetek.py"", line 140, in _end_transaction_and_read\\nmsg = self.device.read(_READ_ENDPOINT, _READ_LENGTH, _READ_TIMEOUT)\\nFile ""/usr/lib/python3.7/site-packages/liquidctl/driver/usb.py"", line 260, in read\\nreturn self.usbdev.read(endpoint, length, timeout=timeout)\\nFile ""/usr/lib/python3.7/site-packages/usb/core.py"", line 988, in read\\nself.__get_timeout(timeout))\\nFile ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 833, in bulk_read\\ntimeout)\\nFile ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 936, in __read\\n_check(retval)\\nFile ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 595, in _check\\nraise USBError(_strerror(ret), ret, _libusb_errno[ret])\\nusb.core.USBError: [Errno 110] Operation timed out\\n\\n$ echo $?\\n0'}, {'piece_type': 'other', 'piece_content': ""# extra/tests/asetek_modern\\n+ DEVICE='--vendor 0x2433 --product 0xb200'\\n+ liquidctl --vendor 0x2433 --product 0xb200 list --verbose\\nDevice 0, Asetek 690LC (assuming EVGA CLC)\\nVendor ID: 0x2433\\nProduct ID: 0xb200\\nRelease number: 0x0100\\nSerial number: CCVI_1.0\\nBus: usb1\\nAddress: 10\\nPort: 12\\nHierarchy: AsetekDriver, CommonAsetekDriver, UsbDeviceDriver, BaseDriver; PyUsbDevice=usb\\n\\n+ liquidctl --vendor 0x2433 --product 0xb200 initialize\\n+ sleep 2\\n+ liquidctl --vendor 0x2433 --product 0xb200 status\\nDevice 0, Asetek 690LC (assuming EVGA CLC)\\nusb.core.USBError: [Errno 16] Resource busy\\n\\n$ echo $?\\n1""}]","# extra/liquiddump --product 0xb200 --interval 3 +{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\u00b0C""], [""Fan speed"", 420, ""rpm""], [""Pump speed"", 2670, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]} +{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\u00b0C""], [""Fan speed"", 480, ""rpm""], [""Pump speed"", 2610, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]} +{""Asetek 690LC (assuming EVGA CLC)"": [[""Liquid temperature"", 28.8, ""\\u00b0C""], [""Fan speed"", 420, ""rpm""], [""Pump speed"", 2640, ""rpm""], [""Firmware version"", ""2.10.0.0"", """"]]} +Unexpected error +Traceback (most recent call last): +File ""extra/liquiddump"", line 92, in +status[d.description] = d.get_status() +File ""/usr/lib/python3.7/site-packages/liquidctl/driver/asetek.py"", line 221, in get_status +msg = self._end_transaction_and_read() +File ""/usr/lib/python3.7/site-packages/liquidctl/driver/asetek.py"", line 140, in _end_transaction_and_read +msg = self.device.read(_READ_ENDPOINT, _READ_LENGTH, _READ_TIMEOUT) +File ""/usr/lib/python3.7/site-packages/liquidctl/driver/usb.py"", line 260, in read +return self.usbdev.read(endpoint, length, timeout=timeout) +File ""/usr/lib/python3.7/site-packages/usb/core.py"", line 988, in read +self.__get_timeout(timeout)) +File ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 833, in bulk_read +timeout) +File ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 936, in __read +_check(retval) +File ""/usr/lib/python3.7/site-packages/usb/backend/libusb1.py"", line 595, in _check +raise USBError(_strerror(ret), ret, _libusb_errno[ret]) +usb.core.USBError: [Errno 110] Operation timed out + +$ echo $? +0",usb.core.USBError +" def dump(self): + """""" + Returns the string that represents the nyan file. + """""" + fileinfo_str = f""# NYAN FILE\\nversion {FILE_VERSION}\\n\\n"" + import_str = """" + objects_str = """" + + for nyan_object in self.nyan_objects: + objects_str += nyan_object.dump(import_tree=self.import_tree) + + # Removes one empty newline at the end of the objects definition + objects_str = objects_str[:-1] + + import_aliases = self.import_tree.get_import_dict() + self.import_tree.clear_marks() + + for alias, fqon in import_aliases.items(): + import_str += ""import "" + + import_str += ""."".join(fqon) + + import_str += f"" as {alias}\\n"" + + import_str += ""\\n"" + + output_str = fileinfo_str + import_str + objects_str + + return output_str"," def dump(self): + """""" + Returns the string that represents the nyan file. + """""" + output_str = f""# NYAN FILE\\nversion {FILE_VERSION}\\n\\n"" + + import_aliases = self.import_tree.establish_import_dict(self, + ignore_names=[""type"", ""types""]) + + for alias, fqon in import_aliases.items(): + output_str += ""import "" + + output_str += ""."".join(fqon) + + output_str += f"" as {alias}\\n"" + + output_str += ""\\n"" + + for nyan_object in self.nyan_objects: + output_str += nyan_object.dump(import_tree=self.import_tree) + + self.import_tree.clear_marks() + + # Removes one empty line at the end of the file + output_str = output_str[:-1] + + return output_str","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +"def convert_assets(assets, args, srcdir=None, prev_source_dir_path=None): + """""" + Perform asset conversion. + + Requires original assets and stores them in usable and free formats. + + assets must be a filesystem-like object pointing at the game's asset dir. + srcdir must be None, or point at some source directory. + + If gen_extra_files is True, some more files, mostly for debugging purposes, + are created. + + This method prepares srcdir and targetdir to allow a pleasant, unified + conversion experience, then passes them to .driver.convert(). + """""" + # acquire conversion source directory + if srcdir is None: + srcdir = acquire_conversion_source_dir(prev_source_dir_path) + + converted_path = assets / ""converted"" + converted_path.mkdirs() + targetdir = DirectoryCreator(converted_path).root + + # Set compression level for media output if it was not set + if ""compression_level"" not in vars(args): + args.compression_level = 1 + + # Set verbosity for debug output + if ""debug_info"" not in vars(args) or not args.debug_info: + if args.devmode: + args.debug_info = 3 + + else: + args.debug_info = 0 + + # add a dir for debug info + debug_log_path = converted_path / ""debug"" / datetime.now().strftime(""%Y-%m-%d-%H-%M-%S"") + debugdir = DirectoryCreator(debug_log_path).root + args.debugdir = AccessSynchronizer(debugdir).root + + # Create CLI args info + debug_cli_args(args.debugdir, args.debug_info, args) + + # Initialize game versions data + auxiliary_files_dir = args.cfg_dir / ""converter"" / ""games"" + args.avail_game_eds, args.avail_game_exps = create_version_objects(auxiliary_files_dir) + + # Acquire game version info + args.game_version = get_game_version(srcdir, args.avail_game_eds, args.avail_game_exps) + debug_game_version(args.debugdir, args.debug_info, args) + + # Mount assets into conversion folder + data_dir = mount_asset_dirs(srcdir, args.game_version) + if not data_dir: + return None + + # make srcdir and targetdir safe for threaded conversion + args.srcdir = AccessSynchronizer(data_dir).root + args.targetdir = AccessSynchronizer(targetdir).root + + # Create mountpoint info + debug_mounts(args.debugdir, args.debug_info, args) + + def flag(name): + """""" + Convenience function for accessing boolean flags in args. + Flags default to False if they don't exist. + """""" + return getattr(args, name, False) + + args.flag = flag + + # import here so codegen.py doesn't depend on it. + from .tool.driver import convert + + converted_count = 0 + total_count = None + for current_item in convert(args): + if isinstance(current_item, int): + # convert is informing us about the estimated number of remaining + # items. + total_count = current_item + converted_count + continue + + # TODO a GUI would be nice here. + + if total_count is None: + info(""[%s] %s"", converted_count, current_item) + else: + info(""[%s] %s"", format_progress(converted_count, total_count), current_item) + + converted_count += 1 + + # clean args + del args.srcdir + del args.targetdir + + return data_dir.resolve_native_path()","def convert_assets(assets, args, srcdir=None, prev_source_dir_path=None): + """""" + Perform asset conversion. + + Requires original assets and stores them in usable and free formats. + + assets must be a filesystem-like object pointing at the game's asset dir. + srcdir must be None, or point at some source directory. + + If gen_extra_files is True, some more files, mostly for debugging purposes, + are created. + + This method prepares srcdir and targetdir to allow a pleasant, unified + conversion experience, then passes them to .driver.convert(). + """""" + # acquire conversion source directory + if srcdir is None: + srcdir = acquire_conversion_source_dir(prev_source_dir_path) + + converted_path = assets / ""converted"" + converted_path.mkdirs() + targetdir = DirectoryCreator(converted_path).root + + # Set compression level for media output if it was not set + if ""compression_level"" not in vars(args): + args.compression_level = 1 + + # Set verbosity for debug output + if ""debug_info"" not in vars(args): + if args.devmode: + args.debug_info = 3 + + else: + args.debug_info = 0 + + # add a dir for debug info + debug_log_path = converted_path / ""debug"" / datetime.now().strftime(""%Y-%m-%d-%H-%M-%S"") + debugdir = DirectoryCreator(debug_log_path).root + args.debugdir = AccessSynchronizer(debugdir).root + + # Create CLI args info + debug_cli_args(args.debugdir, args.debug_info, args) + + # Initialize game versions data + auxiliary_files_dir = args.cfg_dir / ""converter"" / ""games"" + args.avail_game_eds, args.avail_game_exps = create_version_objects(auxiliary_files_dir) + + # Acquire game version info + args.game_version = get_game_version(srcdir, args.avail_game_eds, args.avail_game_exps) + debug_game_version(args.debugdir, args.debug_info, args) + + # Mount assets into conversion folder + data_dir = mount_asset_dirs(srcdir, args.game_version) + if not data_dir: + return None + + # make srcdir and targetdir safe for threaded conversion + args.srcdir = AccessSynchronizer(data_dir).root + args.targetdir = AccessSynchronizer(targetdir).root + + # Create mountpoint info + debug_mounts(args.debugdir, args.debug_info, args) + + def flag(name): + """""" + Convenience function for accessing boolean flags in args. + Flags default to False if they don't exist. + """""" + return getattr(args, name, False) + + args.flag = flag + + # import here so codegen.py doesn't depend on it. + from .tool.driver import convert + + converted_count = 0 + total_count = None + for current_item in convert(args): + if isinstance(current_item, int): + # convert is informing us about the estimated number of remaining + # items. + total_count = current_item + converted_count + continue + + # TODO a GUI would be nice here. + + if total_count is None: + info(""[%s] %s"", converted_count, current_item) + else: + info(""[%s] %s"", format_progress(converted_count, total_count), current_item) + + converted_count += 1 + + # clean args + del args.srcdir + del args.targetdir + + return data_dir.resolve_native_path()","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def _get_aoe2_base(cls, gamedata): + """""" + Create the aoe2-base modpack. + """""" + modpack = Modpack(""aoe2_base"") + + mod_def = modpack.get_info() + + mod_def.set_version(""1.0c"") + mod_def.set_uid(2000) + + mod_def.add_assets_to_load(""data/*"") + + cls.organize_nyan_objects(modpack, gamedata) + cls.organize_media_objects(modpack, gamedata) + + return modpack"," def _get_aoe2_base(cls, gamedata): + """""" + Create the aoe2-base modpack. + """""" + modpack = Modpack(""aoe2-base"") + + mod_def = modpack.get_info() + + mod_def.set_version(""1.0c"") + mod_def.set_uid(2000) + + mod_def.add_assets_to_load(""data/*"") + + cls.organize_nyan_objects(modpack, gamedata) + cls.organize_media_objects(modpack, gamedata) + + return modpack","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def organize_nyan_objects(modpack, full_data_set): + """""" + Put available nyan objects into a given modpack. + """""" + created_nyan_files = {} + + # Access all raw API objects + raw_api_objects = [] + raw_api_objects.extend(full_data_set.pregen_nyan_objects.values()) + + for unit_line in full_data_set.unit_lines.values(): + raw_api_objects.extend(unit_line.get_raw_api_objects().values()) + + for building_line in full_data_set.building_lines.values(): + raw_api_objects.extend(building_line.get_raw_api_objects().values()) + + for ambient_group in full_data_set.ambient_groups.values(): + raw_api_objects.extend(ambient_group.get_raw_api_objects().values()) + + for variant_group in full_data_set.variant_groups.values(): + raw_api_objects.extend(variant_group.get_raw_api_objects().values()) + + for tech_group in full_data_set.tech_groups.values(): + raw_api_objects.extend(tech_group.get_raw_api_objects().values()) + + for terrain_group in full_data_set.terrain_groups.values(): + raw_api_objects.extend(terrain_group.get_raw_api_objects().values()) + + for civ_group in full_data_set.civ_groups.values(): + raw_api_objects.extend(civ_group.get_raw_api_objects().values()) + + # Create the files + for raw_api_object in raw_api_objects: + obj_location = raw_api_object.get_location() + + if isinstance(obj_location, ForwardRef): + # Resolve location and add nested object + nyan_object = obj_location.resolve() + nyan_object.add_nested_object(raw_api_object.get_nyan_object()) + continue + + obj_filename = raw_api_object.get_filename() + nyan_file_path = f""{modpack.info.name}/{obj_location}{obj_filename}"" + + if nyan_file_path in created_nyan_files.keys(): + nyan_file = created_nyan_files[nyan_file_path] + + else: + nyan_file = NyanFile(obj_location, obj_filename, + modpack.info.name) + created_nyan_files.update({nyan_file.get_relative_file_path(): nyan_file}) + modpack.add_data_export(nyan_file) + + nyan_file.add_nyan_object(raw_api_object.get_nyan_object()) + + # Create an import tree from the files + import_tree = ImportTree() + + for nyan_file in created_nyan_files.values(): + import_tree.expand_from_file(nyan_file) + + for nyan_object in full_data_set.nyan_api_objects.values(): + import_tree.expand_from_object(nyan_object) + + for nyan_file in created_nyan_files.values(): + nyan_file.set_import_tree(import_tree) + + AoCModpackSubprocessor._set_static_aliases(modpack, import_tree)"," def organize_nyan_objects(modpack, full_data_set): + """""" + Put available nyan objects into a given modpack. + """""" + created_nyan_files = {} + + # Access all raw API objects + raw_api_objects = [] + raw_api_objects.extend(full_data_set.pregen_nyan_objects.values()) + + for unit_line in full_data_set.unit_lines.values(): + raw_api_objects.extend(unit_line.get_raw_api_objects().values()) + + for building_line in full_data_set.building_lines.values(): + raw_api_objects.extend(building_line.get_raw_api_objects().values()) + + for ambient_group in full_data_set.ambient_groups.values(): + raw_api_objects.extend(ambient_group.get_raw_api_objects().values()) + + for variant_group in full_data_set.variant_groups.values(): + raw_api_objects.extend(variant_group.get_raw_api_objects().values()) + + for tech_group in full_data_set.tech_groups.values(): + raw_api_objects.extend(tech_group.get_raw_api_objects().values()) + + for terrain_group in full_data_set.terrain_groups.values(): + raw_api_objects.extend(terrain_group.get_raw_api_objects().values()) + + for civ_group in full_data_set.civ_groups.values(): + raw_api_objects.extend(civ_group.get_raw_api_objects().values()) + + # Create the files + for raw_api_object in raw_api_objects: + obj_location = raw_api_object.get_location() + + if isinstance(obj_location, ForwardRef): + # Resolve location and add nested object + nyan_object = obj_location.resolve() + nyan_object.add_nested_object(raw_api_object.get_nyan_object()) + continue + + obj_filename = raw_api_object.get_filename() + nyan_file_path = f""{modpack.info.name}/{obj_location}{obj_filename}"" + + if nyan_file_path in created_nyan_files.keys(): + nyan_file = created_nyan_files[nyan_file_path] + + else: + nyan_file = NyanFile(obj_location, obj_filename, + modpack.info.name) + created_nyan_files.update({nyan_file.get_relative_file_path(): nyan_file}) + modpack.add_data_export(nyan_file) + + nyan_file.add_nyan_object(raw_api_object.get_nyan_object()) + + # Create an import tree from the files + import_tree = ImportTree() + + for nyan_file in created_nyan_files.values(): + import_tree.expand_from_file(nyan_file) + + for nyan_object in full_data_set.nyan_api_objects.values(): + import_tree.expand_from_object(nyan_object) + + for nyan_file in created_nyan_files.values(): + nyan_file.set_import_tree(import_tree)","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def generate_modifiers(full_data_set, pregen_converter_group): + """""" + Generate standard modifiers. + + :param full_data_set: GenieObjectContainer instance that + contains all relevant data for the conversion + process. + :type full_data_set: ...dataformat.aoc.genie_object_container.GenieObjectContainer + :param pregen_converter_group: GenieObjectGroup instance that stores + pregenerated API objects for referencing with + ForwardRef + :type pregen_converter_group: ...dataformat.aoc.genie_object_container.GenieObjectGroup + """""" + pregen_nyan_objects = full_data_set.pregen_nyan_objects + api_objects = full_data_set.nyan_api_objects + + modifier_parent = ""engine.modifier.multiplier.MultiplierModifier"" + type_parent = ""engine.modifier.multiplier.effect.flat_attribute_change.type.Flyover"" + types_location = ""data/aux/modifier/flyover_cliff/"" + + # ======================================================================= + # Flyover effect multiplier + # ======================================================================= + modifier_ref_in_modpack = ""aux.modifier.flyover_cliff.AttackMultiplierFlyover"" + modifier_raw_api_object = RawAPIObject(modifier_ref_in_modpack, + ""AttackMultiplierFlyover"", api_objects, + types_location) + modifier_raw_api_object.set_filename(""flyover_cliff"") + modifier_raw_api_object.add_raw_parent(type_parent) + + pregen_converter_group.add_raw_api_object(modifier_raw_api_object) + pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) + + # Increases effect value by 25% + modifier_raw_api_object.add_raw_member(""multiplier"", + 1.25, + modifier_parent) + + # Relative angle to cliff must not be larger than 90° + modifier_raw_api_object.add_raw_member(""relative_angle"", + 90, + type_parent) + + # Affects all cliffs + types = [ForwardRef(pregen_converter_group, ""aux.game_entity_type.types.Cliff"")] + modifier_raw_api_object.add_raw_member(""flyover_types"", + types, + type_parent) + modifier_raw_api_object.add_raw_member(""blacklisted_entities"", + [], + type_parent) + + # ======================================================================= + # Elevation difference effect multiplier (higher unit) + # ======================================================================= + modifier_parent = ""engine.modifier.multiplier.MultiplierModifier"" + type_parent = ""engine.modifier.multiplier.effect.flat_attribute_change.type.ElevationDifferenceHigh"" + types_location = ""data/aux/modifier/elevation_difference/"" + + modifier_ref_in_modpack = ""aux.modifier.elevation_difference.AttackMultiplierHigh"" + modifier_raw_api_object = RawAPIObject(modifier_ref_in_modpack, + ""AttackMultiplierHigh"", api_objects, + types_location) + modifier_raw_api_object.set_filename(""elevation_difference"") + modifier_raw_api_object.add_raw_parent(type_parent) + + pregen_converter_group.add_raw_api_object(modifier_raw_api_object) + pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) + + # Increases effect value to 125% + modifier_raw_api_object.add_raw_member(""multiplier"", + 1.25, + modifier_parent) + + # Min elevation difference is not set + + # ======================================================================= + # Elevation difference effect multiplier (lower unit) + # ======================================================================= + modifier_parent = ""engine.modifier.multiplier.MultiplierModifier"" + type_parent = ""engine.modifier.multiplier.effect.flat_attribute_change.type.ElevationDifferenceLow"" + types_location = ""data/aux/modifier/elevation_difference/"" + + modifier_ref_in_modpack = ""aux.modifier.elevation_difference.AttackMultiplierLow"" + modifier_raw_api_object = RawAPIObject(modifier_ref_in_modpack, + ""AttackMultiplierLow"", api_objects, + types_location) + modifier_raw_api_object.set_filename(""elevation_difference"") + modifier_raw_api_object.add_raw_parent(type_parent) + + pregen_converter_group.add_raw_api_object(modifier_raw_api_object) + pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) + + # Decreases effect value to 75% + modifier_raw_api_object.add_raw_member(""multiplier"", + 0.75, + modifier_parent)"," def generate_modifiers(full_data_set, pregen_converter_group): + """""" + Generate standard modifiers. + + :param full_data_set: GenieObjectContainer instance that + contains all relevant data for the conversion + process. + :type full_data_set: ...dataformat.aoc.genie_object_container.GenieObjectContainer + :param pregen_converter_group: GenieObjectGroup instance that stores + pregenerated API objects for referencing with + ForwardRef + :type pregen_converter_group: ...dataformat.aoc.genie_object_container.GenieObjectGroup + """""" + pregen_nyan_objects = full_data_set.pregen_nyan_objects + api_objects = full_data_set.nyan_api_objects + + modifier_parent = ""engine.modifier.multiplier.MultiplierModifier"" + type_parent = ""engine.modifier.multiplier.effect.flat_attribute_change.type.Flyover"" + types_location = ""data/aux/modifier/flyover_cliff"" + + # ======================================================================= + # Flyover effect multiplier + # ======================================================================= + modifier_ref_in_modpack = ""aux.modifier.flyover_cliff.AttackMultiplierFlyover"" + modifier_raw_api_object = RawAPIObject(modifier_ref_in_modpack, + ""AttackMultiplierFlyover"", api_objects, + types_location) + modifier_raw_api_object.set_filename(""flyover_cliff"") + modifier_raw_api_object.add_raw_parent(type_parent) + + pregen_converter_group.add_raw_api_object(modifier_raw_api_object) + pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) + + # Increases effect value by 25% + modifier_raw_api_object.add_raw_member(""multiplier"", + 1.25, + modifier_parent) + + # Relative angle to cliff must not be larger than 90° + modifier_raw_api_object.add_raw_member(""relative_angle"", + 90, + type_parent) + + # Affects all cliffs + types = [ForwardRef(pregen_converter_group, ""aux.game_entity_type.types.Cliff"")] + modifier_raw_api_object.add_raw_member(""flyover_types"", + types, + type_parent) + modifier_raw_api_object.add_raw_member(""blacklisted_entities"", + [], + type_parent) + + # ======================================================================= + # Elevation difference effect multiplier (higher unit) + # ======================================================================= + modifier_parent = ""engine.modifier.multiplier.MultiplierModifier"" + type_parent = ""engine.modifier.multiplier.effect.flat_attribute_change.type.ElevationDifferenceHigh"" + types_location = ""data/aux/modifier/elevation_difference"" + + modifier_ref_in_modpack = ""aux.modifier.elevation_difference.AttackMultiplierHigh"" + modifier_raw_api_object = RawAPIObject(modifier_ref_in_modpack, + ""AttackMultiplierHigh"", api_objects, + types_location) + modifier_raw_api_object.set_filename(""elevation_difference"") + modifier_raw_api_object.add_raw_parent(type_parent) + + pregen_converter_group.add_raw_api_object(modifier_raw_api_object) + pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) + + # Increases effect value to 125% + modifier_raw_api_object.add_raw_member(""multiplier"", + 1.25, + modifier_parent) + + # Min elevation difference is not set + + # ======================================================================= + # Elevation difference effect multiplier (lower unit) + # ======================================================================= + modifier_parent = ""engine.modifier.multiplier.MultiplierModifier"" + type_parent = ""engine.modifier.multiplier.effect.flat_attribute_change.type.ElevationDifferenceLow"" + types_location = ""data/aux/modifier/elevation_difference"" + + modifier_ref_in_modpack = ""aux.modifier.elevation_difference.AttackMultiplierLow"" + modifier_raw_api_object = RawAPIObject(modifier_ref_in_modpack, + ""AttackMultiplierLow"", api_objects, + types_location) + modifier_raw_api_object.set_filename(""elevation_difference"") + modifier_raw_api_object.add_raw_parent(type_parent) + + pregen_converter_group.add_raw_api_object(modifier_raw_api_object) + pregen_nyan_objects.update({modifier_ref_in_modpack: modifier_raw_api_object}) + + # Decreases effect value to 75% + modifier_raw_api_object.add_raw_member(""multiplier"", + 0.75, + modifier_parent)","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def live_ability(converter_group, line, container_obj_ref, diff=None): + """""" + Creates a patch for the Live ability of a line. + + :param converter_group: Group that gets the patch. + :type converter_group: ...dataformat.converter_object.ConverterObjectGroup + :param line: Unit/Building line that has the ability. + :type line: ...dataformat.converter_object.ConverterObjectGroup + :param container_obj_ref: Reference of the raw API object the patch is nested in. + :type container_obj_ref: str + :param diff: A diff between two ConvertObject instances. + :type diff: ...dataformat.converter_object.ConverterObject + :returns: The forward references for the generated patches. + :rtype: list + """""" + head_unit_id = line.get_head_unit_id() + tech_id = converter_group.get_id() + dataset = line.data + + patches = [] + + name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) + tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version) + + game_entity_name = name_lookup_dict[head_unit_id][0] + + if diff: + diff_hp = diff[""hit_points""] + if isinstance(diff_hp, NoDiffMember): + return patches + + diff_hp_value = diff_hp.get_value() + + else: + return patches + + patch_target_ref = f""{game_entity_name}.Live.Health"" + patch_target_forward_ref = ForwardRef(line, patch_target_ref) + + # Wrapper + wrapper_name = f""Change{game_entity_name}HealthWrapper"" + wrapper_ref = f""{container_obj_ref}.{wrapper_name}"" + wrapper_raw_api_object = RawAPIObject(wrapper_ref, + wrapper_name, + dataset.nyan_api_objects) + wrapper_raw_api_object.add_raw_parent(""engine.aux.patch.Patch"") + + if isinstance(line, GenieBuildingLineGroup): + # Store building upgrades next to their game entity definition, + # not in the Age up techs. + wrapper_raw_api_object.set_location(""data/game_entity/generic/%s/"" + % (name_lookup_dict[head_unit_id][1])) + wrapper_raw_api_object.set_filename(f""{tech_lookup_dict[tech_id][1]}_upgrade"") + + else: + wrapper_raw_api_object.set_location(ForwardRef(converter_group, container_obj_ref)) + + # Nyan patch + nyan_patch_name = f""Change{game_entity_name}Health"" + nyan_patch_ref = f""{container_obj_ref}.{wrapper_name}.{nyan_patch_name}"" + nyan_patch_location = ForwardRef(converter_group, wrapper_ref) + nyan_patch_raw_api_object = RawAPIObject(nyan_patch_ref, + nyan_patch_name, + dataset.nyan_api_objects, + nyan_patch_location) + nyan_patch_raw_api_object.add_raw_parent(""engine.aux.patch.NyanPatch"") + nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref) + + # HP max value + nyan_patch_raw_api_object.add_raw_patch_member(""max_value"", + diff_hp_value, + ""engine.aux.attribute.AttributeSetting"", + MemberOperator.ADD) + + # HP starting value + nyan_patch_raw_api_object.add_raw_patch_member(""starting_value"", + diff_hp_value, + ""engine.aux.attribute.AttributeSetting"", + MemberOperator.ADD) + + patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref) + wrapper_raw_api_object.add_raw_member(""patch"", + patch_forward_ref, + ""engine.aux.patch.Patch"") + + converter_group.add_raw_api_object(wrapper_raw_api_object) + converter_group.add_raw_api_object(nyan_patch_raw_api_object) + + wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref) + patches.append(wrapper_forward_ref) + + return patches"," def live_ability(converter_group, line, container_obj_ref, diff=None): + """""" + Creates a patch for the Live ability of a line. + + :param converter_group: Group that gets the patch. + :type converter_group: ...dataformat.converter_object.ConverterObjectGroup + :param line: Unit/Building line that has the ability. + :type line: ...dataformat.converter_object.ConverterObjectGroup + :param container_obj_ref: Reference of the raw API object the patch is nested in. + :type container_obj_ref: str + :param diff: A diff between two ConvertObject instances. + :type diff: ...dataformat.converter_object.ConverterObject + :returns: The forward references for the generated patches. + :rtype: list + """""" + head_unit_id = line.get_head_unit_id() + tech_id = converter_group.get_id() + dataset = line.data + + patches = [] + + name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) + tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version) + + game_entity_name = name_lookup_dict[head_unit_id][0] + + if diff: + diff_hp = diff[""hit_points""] + if isinstance(diff_hp, NoDiffMember): + return patches + + diff_hp_value = diff_hp.get_value() + + else: + return patches + + patch_target_ref = f""{game_entity_name}.Live.Health"" + patch_target_forward_ref = ForwardRef(line, patch_target_ref) + + # Wrapper + wrapper_name = f""Change{game_entity_name}HealthWrapper"" + wrapper_ref = f""{container_obj_ref}.{wrapper_name}"" + wrapper_raw_api_object = RawAPIObject(wrapper_ref, + wrapper_name, + dataset.nyan_api_objects) + wrapper_raw_api_object.add_raw_parent(""engine.aux.patch.Patch"") + + if isinstance(line, GenieBuildingLineGroup): + # Store building upgrades next to their game entity definition, + # not in the Age up techs. + wrapper_raw_api_object.set_location(""data/game_entity/generic/%s/"" + % (name_lookup_dict[head_unit_id][1])) + wrapper_raw_api_object.set_filename(f""{tech_lookup_dict[tech_id][1]}_upgrade"") + + else: + wrapper_raw_api_object.set_location(ForwardRef(converter_group, container_obj_ref)) + + # Nyan patch + nyan_patch_name = f""Change{game_entity_name}Health"" + nyan_patch_ref = f""{container_obj_ref}.{wrapper_name}.{nyan_patch_name}"" + nyan_patch_location = ForwardRef(converter_group, wrapper_ref) + nyan_patch_raw_api_object = RawAPIObject(nyan_patch_ref, + nyan_patch_name, + dataset.nyan_api_objects, + nyan_patch_location) + nyan_patch_raw_api_object.add_raw_parent(""engine.aux.patch.NyanPatch"") + nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref) + + # HP max value + nyan_patch_raw_api_object.add_raw_patch_member(""max_value"", + diff_hp_value, + ""engine.aux.attribute.AttributeSetting"", + MemberOperator.ADD) + + patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref) + wrapper_raw_api_object.add_raw_member(""patch"", + patch_forward_ref, + ""engine.aux.patch.Patch"") + + converter_group.add_raw_api_object(wrapper_raw_api_object) + converter_group.add_raw_api_object(nyan_patch_raw_api_object) + + wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref) + patches.append(wrapper_forward_ref) + + return patches","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def hp_upgrade(converter_group, line, value, operator, team=False): + """""" + Creates a patch for the HP modify effect (ID: 0). + + :param converter_group: Tech/Civ that gets the patch. + :type converter_group: ...dataformat.converter_object.ConverterObjectGroup + :param line: Unit/Building line that has the ability. + :type line: ...dataformat.converter_object.ConverterObjectGroup + :param value: Value used for patching the member. + :type value: MemberOperator + :param operator: Operator used for patching the member. + :type operator: MemberOperator + :returns: The forward references for the generated patches. + :rtype: list + """""" + head_unit_id = line.get_head_unit_id() + dataset = line.data + + patches = [] + + obj_id = converter_group.get_id() + if isinstance(converter_group, GenieTechEffectBundleGroup): + tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version) + obj_name = tech_lookup_dict[obj_id][0] + + else: + civ_lookup_dict = internal_name_lookups.get_civ_lookups(dataset.game_version) + obj_name = civ_lookup_dict[obj_id][0] + + name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) + + game_entity_name = name_lookup_dict[head_unit_id][0] + + patch_target_ref = f""{game_entity_name}.Live.Health"" + patch_target_forward_ref = ForwardRef(line, patch_target_ref) + + # Wrapper + wrapper_name = f""Change{game_entity_name}MaxHealthWrapper"" + wrapper_ref = f""{obj_name}.{wrapper_name}"" + wrapper_location = ForwardRef(converter_group, obj_name) + wrapper_raw_api_object = RawAPIObject(wrapper_ref, + wrapper_name, + dataset.nyan_api_objects, + wrapper_location) + wrapper_raw_api_object.add_raw_parent(""engine.aux.patch.Patch"") + + # Nyan patch + nyan_patch_name = f""Change{game_entity_name}MaxHealth"" + nyan_patch_ref = f""{obj_name}.{wrapper_name}.{nyan_patch_name}"" + nyan_patch_location = ForwardRef(converter_group, wrapper_ref) + nyan_patch_raw_api_object = RawAPIObject(nyan_patch_ref, + nyan_patch_name, + dataset.nyan_api_objects, + nyan_patch_location) + nyan_patch_raw_api_object.add_raw_parent(""engine.aux.patch.NyanPatch"") + nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref) + + nyan_patch_raw_api_object.add_raw_patch_member(""max_value"", + value, + ""engine.aux.attribute.AttributeSetting"", + operator) + + nyan_patch_raw_api_object.add_raw_patch_member(""starting_value"", + value, + ""engine.aux.attribute.AttributeSetting"", + operator) + + patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref) + wrapper_raw_api_object.add_raw_member(""patch"", + patch_forward_ref, + ""engine.aux.patch.Patch"") + + if team: + wrapper_raw_api_object.add_raw_parent(""engine.aux.patch.type.DiplomaticPatch"") + stances = [ + dataset.nyan_api_objects[""engine.aux.diplomatic_stance.type.Self""], + dataset.pregen_nyan_objects[""aux.diplomatic_stance.types.Friendly""].get_nyan_object() + ] + wrapper_raw_api_object.add_raw_member(""stances"", + stances, + ""engine.aux.patch.type.DiplomaticPatch"") + + converter_group.add_raw_api_object(wrapper_raw_api_object) + converter_group.add_raw_api_object(nyan_patch_raw_api_object) + + wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref) + patches.append(wrapper_forward_ref) + + return patches"," def hp_upgrade(converter_group, line, value, operator, team=False): + """""" + Creates a patch for the HP modify effect (ID: 0). + + :param converter_group: Tech/Civ that gets the patch. + :type converter_group: ...dataformat.converter_object.ConverterObjectGroup + :param line: Unit/Building line that has the ability. + :type line: ...dataformat.converter_object.ConverterObjectGroup + :param value: Value used for patching the member. + :type value: MemberOperator + :param operator: Operator used for patching the member. + :type operator: MemberOperator + :returns: The forward references for the generated patches. + :rtype: list + """""" + head_unit_id = line.get_head_unit_id() + dataset = line.data + + patches = [] + + obj_id = converter_group.get_id() + if isinstance(converter_group, GenieTechEffectBundleGroup): + tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version) + obj_name = tech_lookup_dict[obj_id][0] + + else: + civ_lookup_dict = internal_name_lookups.get_civ_lookups(dataset.game_version) + obj_name = civ_lookup_dict[obj_id][0] + + name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version) + + game_entity_name = name_lookup_dict[head_unit_id][0] + + patch_target_ref = f""{game_entity_name}.Live.Health"" + patch_target_forward_ref = ForwardRef(line, patch_target_ref) + + # Wrapper + wrapper_name = f""Change{game_entity_name}MaxHealthWrapper"" + wrapper_ref = f""{obj_name}.{wrapper_name}"" + wrapper_location = ForwardRef(converter_group, obj_name) + wrapper_raw_api_object = RawAPIObject(wrapper_ref, + wrapper_name, + dataset.nyan_api_objects, + wrapper_location) + wrapper_raw_api_object.add_raw_parent(""engine.aux.patch.Patch"") + + # Nyan patch + nyan_patch_name = f""Change{game_entity_name}MaxHealth"" + nyan_patch_ref = f""{obj_name}.{wrapper_name}.{nyan_patch_name}"" + nyan_patch_location = ForwardRef(converter_group, wrapper_ref) + nyan_patch_raw_api_object = RawAPIObject(nyan_patch_ref, + nyan_patch_name, + dataset.nyan_api_objects, + nyan_patch_location) + nyan_patch_raw_api_object.add_raw_parent(""engine.aux.patch.NyanPatch"") + nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref) + + nyan_patch_raw_api_object.add_raw_patch_member(""max_value"", + value, + ""engine.aux.attribute.AttributeSetting"", + operator) + + patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref) + wrapper_raw_api_object.add_raw_member(""patch"", + patch_forward_ref, + ""engine.aux.patch.Patch"") + + if team: + wrapper_raw_api_object.add_raw_parent(""engine.aux.patch.type.DiplomaticPatch"") + stances = [ + dataset.nyan_api_objects[""engine.aux.diplomatic_stance.type.Self""], + dataset.pregen_nyan_objects[""aux.diplomatic_stance.types.Friendly""].get_nyan_object() + ] + wrapper_raw_api_object.add_raw_member(""stances"", + stances, + ""engine.aux.patch.type.DiplomaticPatch"") + + converter_group.add_raw_api_object(wrapper_raw_api_object) + converter_group.add_raw_api_object(nyan_patch_raw_api_object) + + wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref) + patches.append(wrapper_forward_ref) + + return patches","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def _get_aoe2_base(cls, gamedata): + """""" + Create the aoe2-base modpack. + """""" + modpack = Modpack(""de2_base"") + + mod_def = modpack.get_info() + + mod_def.set_version(""TODO"") + mod_def.set_uid(2000) + + mod_def.add_assets_to_load(""data/*"") + + AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) + AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) + + return modpack"," def _get_aoe2_base(cls, gamedata): + """""" + Create the aoe2-base modpack. + """""" + modpack = Modpack(""de2-base"") + + mod_def = modpack.get_info() + + mod_def.set_version(""TODO"") + mod_def.set_uid(2000) + + mod_def.add_assets_to_load(""data/*"") + + AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) + AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) + + return modpack","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def _get_aoe1_base(cls, gamedata): + """""" + Create the aoe1-base modpack. + """""" + modpack = Modpack(""aoe1_base"") + + mod_def = modpack.get_info() + + mod_def.set_version(""1.0B"") + mod_def.set_uid(1000) + + mod_def.add_assets_to_load(""data/*"") + + AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) + AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) + + return modpack"," def _get_aoe1_base(cls, gamedata): + """""" + Create the aoe1-base modpack. + """""" + modpack = Modpack(""aoe1-base"") + + mod_def = modpack.get_info() + + mod_def.set_version(""1.0B"") + mod_def.set_uid(1000) + + mod_def.add_assets_to_load(""data/*"") + + AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) + AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) + + return modpack","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def _get_swgb_base(cls, gamedata): + """""" + Create the swgb-base modpack. + """""" + modpack = Modpack(""swgb_base"") + + mod_def = modpack.get_info() + + mod_def.set_version(""GOG"") + mod_def.set_uid(5000) + + mod_def.add_assets_to_load(""data/*"") + + AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) + AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) + + return modpack"," def _get_swgb_base(cls, gamedata): + """""" + Create the swgb-base modpack. + """""" + modpack = Modpack(""swgb-base"") + + mod_def = modpack.get_info() + + mod_def.set_version(""GOG"") + mod_def.set_uid(5000) + + mod_def.add_assets_to_load(""data/*"") + + AoCModpackSubprocessor.organize_nyan_objects(modpack, gamedata) + AoCModpackSubprocessor.organize_media_objects(modpack, gamedata) + + return modpack","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def expand_from_file(self, nyan_file): + """""" + Expands the tree from a nyan file. + + :param nyan_file: File with nyan objects. + :type nyan_file: .convert.export.formats.nyan_file.NyanFile + """""" + current_node = self.root + fqon = nyan_file.get_fqon() + node_type = NodeType.FILESYS + + for node_str in fqon: + if current_node.has_child(node_str): + # Choose the already created node + current_node = current_node.get_child(node_str) + + else: + # Add a new node + new_node = Node(node_str, node_type, current_node) + current_node.add_child(new_node) + current_node = new_node + + # Process fqons of the contained objects + for nyan_object in nyan_file.nyan_objects: + self.expand_from_object(nyan_object)"," def expand_from_file(self, nyan_file): + """""" + Expands the tree from a nyan file. + + :param nyan_file: File with nyan objects. + :type nyan_file: .convert.export.formats.nyan_file.NyanFile + """""" + # Process fqon of the file + current_node = self.root + fqon = nyan_file.get_fqon() + node_type = NodeType.FILESYS + + for node_str in fqon: + if current_node.has_child(node_str): + # Choose the already created node + current_node = current_node.get_child(node_str) + + else: + # Add a new node + new_node = Node(node_str, node_type, current_node) + current_node.add_child(new_node) + current_node = new_node + + # Process fqons of the contained objects + for nyan_object in nyan_file.nyan_objects: + self.expand_from_object(nyan_object)","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def get_alias_fqon(self, fqon, namespace=None): + """""" + Find the (shortened) fqon by traversing the tree to the fqon node and + then going upwards until an alias is found. + + :param fqon: Object reference for which an alias should be found. + :type fqon: tuple + :param namespace: Identifier of a namespace. If this is a (nested) object, + we check if the fqon is in the namespace before + searching for an alias. + :type namespace: tuple + """""" + if namespace: + current_node = self.root + + if len(namespace) <= len(fqon): + # Check if the fqon is in the namespace by comparing their identifiers + for index in range(len(namespace)): + current_node = current_node.get_child(namespace[index]) + + if namespace[index] != fqon[index]: + break + + else: + # Check if the namespace node is an object + if current_node.node_type in (NodeType.OBJECT, NodeType.NESTED): + # The object with the fqon is nested and we don't have to look + # up an alias + return (fqon[-1],) + + # Traverse the tree downwards + current_node = self.root + for part in fqon: + current_node = current_node.get_child(part) + + # Traverse the tree upwards + sfqon = [] + while current_node.depth > 0: + if current_node.alias: + sfqon.insert(0, current_node.alias) + current_node.mark() + break + + sfqon.insert(0, current_node.name) + + current_node = current_node.parent + + if not current_node.alias: + print(fqon) + + return tuple(sfqon)"," def get_alias_fqon(self, fqon): + """""" + Find the (shortened) fqon by traversing the tree to the fqon node and + then going upwards until a marked node is found. + """""" + # Traverse the tree downwards + current_node = self.root + for part in fqon: + current_node = current_node.get_child(part) + + # Traverse the tree upwards + sfqon = [] + while current_node.depth > 0: + sfqon.insert(0, current_node.name) + + if current_node.alias: + break + + current_node = current_node.parent + + return tuple(sfqon)","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def __init__(self, name, node_type, parent): + """""" + Create a node for an import tree. + + :param name: Name of the node. + :type name: str + :param node_type: Type of the node. + :type node_type: NodeType + :param parent: Parent node of this node. + :type parent: Node + """""" + + self.name = name + self.node_type = node_type + self.parent = parent + + if not self.parent and self.node_type is not NodeType.ROOT: + raise Exception(""Only node with type ROOT are allowed to have no parent"") + + self.depth = 0 + if self.node_type is NodeType.ROOT: + self.depth = 0 + + else: + self.depth = self.parent.depth + 1 + + self.children = {} + + self.marked = False + self.alias = """""," def __init__(self, name, node_type, parent): + """""" + Create a node for an import tree. + + :param name: Name of the node. + :type name: str + :param node_type: Type of the node. + :type node_type: NodeType + :param parent: Parent node of this node. + :type parent: Node + """""" + + self.name = name + self.node_type = node_type + self.parent = parent + + if not self.parent and self.node_type is not NodeType.ROOT: + raise Exception(""Only node with type ROOT are allowed to have no parent"") + + self.depth = 0 + if self.node_type is NodeType.ROOT: + self.depth = 0 + + else: + self.depth = self.parent.depth + 1 + + self.children = {} + + self.alias = False","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def mark(self): + """""" + Mark this node as an alias node. + """""" + self.marked = True"," def mark(self): + """""" + Mark this node as an alias node. + """""" + self.alias = True","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def unmark(self): + """""" + Unmark this node as an alias node. + """""" + self.marked = False"," def unmark(self): + """""" + Unmark this node as an alias node. + """""" + self.alias = False","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def _prepare_object_content(self, indent_depth, import_tree=None): + """""" + Returns a string containing the nyan object's content + (members, nested objects). + + Subroutine of dump(). + """""" + output_str = """" + empty = True + + if len(self._inherited_members) > 0: + for inherited_member in self._inherited_members: + if inherited_member.has_value(): + empty = False + output_str += ""%s%s\\n"" % ( + (indent_depth + 1) * INDENT, + inherited_member.dump( + indent_depth + 1, + import_tree=import_tree, + namespace=self.get_fqon() + ) + ) + if not empty: + output_str += ""\\n"" + + if len(self._members) > 0: + empty = False + for member in self._members: + if self.is_patch(): + # Patches do not need the type definition + output_str += ""%s%s\\n"" % ( + (indent_depth + 1) * INDENT, + member.dump_short( + indent_depth + 1, + import_tree=import_tree, + namespace=self.get_fqon() + ) + ) + else: + output_str += ""%s%s\\n"" % ( + (indent_depth + 1) * INDENT, + member.dump( + indent_depth + 1, + import_tree=import_tree, + namespace=self.get_fqon() + ) + ) + + output_str += ""\\n"" + + # Nested objects + if len(self._nested_objects) > 0: + empty = False + for nested_object in self._nested_objects: + output_str += ""%s%s"" % ( + (indent_depth + 1) * INDENT, + nested_object.dump( + indent_depth + 1, + import_tree=import_tree + ) + ) + + output_str += """" + + # Empty objects need a 'pass' line + if empty: + output_str += f""{(indent_depth + 1) * INDENT}pass\\n\\n"" + + return output_str"," def _prepare_object_content(self, indent_depth, import_tree=None): + """""" + Returns a string containing the nyan object's content + (members, nested objects). + + Subroutine of dump(). + """""" + output_str = """" + empty = True + + if len(self._inherited_members) > 0: + for inherited_member in self._inherited_members: + if inherited_member.has_value(): + empty = False + output_str += ""%s%s\\n"" % ( + (indent_depth + 1) * INDENT, + inherited_member.dump(import_tree=import_tree) + ) + if not empty: + output_str += ""\\n"" + + if len(self._members) > 0: + empty = False + for member in self._members: + if self.is_patch(): + # Patches do not need the type definition + output_str += ""%s%s\\n"" % ( + (indent_depth + 1) * INDENT, + member.dump_short(import_tree=import_tree) + ) + else: + output_str += ""%s%s\\n"" % ( + (indent_depth + 1) * INDENT, + member.dump(import_tree=import_tree) + ) + + output_str += ""\\n"" + + # Nested objects + if len(self._nested_objects) > 0: + empty = False + for nested_object in self._nested_objects: + output_str += ""%s%s"" % ( + (indent_depth + 1) * INDENT, + nested_object.dump( + indent_depth + 1, + import_tree + ) + ) + + output_str += """" + + # Empty objects need a 'pass' line + if empty: + output_str += f""{(indent_depth + 1) * INDENT}pass\\n\\n"" + + return output_str","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def _prepare_inheritance_content(self, import_tree=None): + """""" + Returns a string containing the nyan object's inheritance set + in the header. + + Subroutine of dump(). + """""" + output_str = ""("" + + if len(self._parents) > 0: + for parent in self._parents: + if import_tree: + sfqon = ""."".join(import_tree.get_alias_fqon( + parent.get_fqon(), + namespace=self.get_fqon() + )) + + else: + sfqon = ""."".join(parent.get_fqon()) + + output_str += f""{sfqon}, "" + + output_str = output_str[:-2] + + output_str += ""):\\n"" + + return output_str"," def _prepare_inheritance_content(self, import_tree=None): + """""" + Returns a string containing the nyan object's inheritance set + in the header. + + Subroutine of dump(). + """""" + output_str = ""("" + + if len(self._parents) > 0: + for parent in self._parents: + if import_tree: + sfqon = ""."".join(import_tree.get_alias_fqon(parent.get_fqon())) + + else: + sfqon = ""."".join(parent.get_fqon()) + + output_str += f""{sfqon}, "" + + output_str = output_str[:-2] + + output_str += ""):\\n"" + + return output_str","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def dump(self, indent_depth, import_tree=None, namespace=None): + """""" + Returns the nyan string representation of the member. + """""" + output_str = f""{self.name}"" + + type_str = """" + + if isinstance(self._member_type, NyanObject): + if import_tree: + sfqon = ""."".join(import_tree.get_alias_fqon( + self._member_type.get_fqon(), + namespace + )) + + else: + sfqon = ""."".join(self._member_type.get_fqon()) + + type_str = sfqon + + else: + type_str = self._member_type.value + + if self._optional: + output_str += f"" : optional({type_str})"" + + else: + output_str += f"" : {type_str}"" + + if self.is_complex(): + if isinstance(self._set_type, NyanObject): + if import_tree: + sfqon = ""."".join(import_tree.get_alias_fqon( + self._set_type.get_fqon(), + namespace + )) + + else: + sfqon = ""."".join(self._set_type.get_fqon()) + + output_str += f""({sfqon})"" + + else: + output_str += f""({self._set_type.value})"" + + if self.is_initialized(): + output_str += "" %s%s %s"" % (""@"" * self._override_depth, + self._operator.value, + self._get_str_representation( + indent_depth, + import_tree=import_tree, + namespace=namespace + )) + + return output_str"," def dump(self, import_tree=None): + """""" + Returns the nyan string representation of the member. + """""" + output_str = f""{self.name}"" + + type_str = """" + + if isinstance(self._member_type, NyanObject): + if import_tree: + sfqon = ""."".join(import_tree.get_alias_fqon(self._member_type.get_fqon())) + + else: + sfqon = ""."".join(self._member_type.get_fqon()) + + type_str = sfqon + + else: + type_str = self._member_type.value + + if self._optional: + output_str += f"" : optional({type_str})"" + + else: + output_str += f"" : {type_str}"" + + if self.is_complex(): + if isinstance(self._set_type, NyanObject): + if import_tree: + sfqon = ""."".join(import_tree.get_alias_fqon(self._set_type.get_fqon())) + + else: + sfqon = ""."".join(self._set_type.get_fqon()) + + output_str += f""({sfqon})"" + + else: + output_str += f""({self._set_type.value})"" + + if self.is_initialized(): + output_str += "" %s%s %s"" % (""@"" * self._override_depth, + self._operator.value, + self._get_str_representation(import_tree=import_tree)) + + return output_str","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def dump_short(self, indent_depth, import_tree=None, namespace=None): + """""" + Returns the nyan string representation of the member, but + without the type definition. + """""" + return ""%s %s%s %s"" % ( + self.get_name(), + ""@"" * self._override_depth, + self._operator.value, + self._get_str_representation( + indent_depth, + import_tree=import_tree, + namespace=namespace + ) + )"," def dump_short(self, import_tree=None): + """""" + Returns the nyan string representation of the member, but + without the type definition. + """""" + return ""%s %s%s %s"" % (self.get_name(), + ""@"" * self._override_depth, + self._operator.value, + self._get_str_representation(import_tree=import_tree))","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def _get_primitive_value_str(self, member_type, value, import_tree=None, namespace=None): + """""" + Returns the nyan string representation of primitive values. + + Subroutine of _get_str_representation() + """""" + if member_type in (MemberType.TEXT, MemberType.FILE): + return f""\\""{value}\\"""" + + elif isinstance(member_type, NyanObject): + if import_tree: + sfqon = ""."".join(import_tree.get_alias_fqon( + value.get_fqon(), + namespace=namespace + )) + + else: + sfqon = ""."".join(value.get_fqon()) + + return sfqon + + return f""{value}"""," def _get_primitive_value_str(self, member_type, value, import_tree=None): + """""" + Returns the nyan string representation of primitive values. + + Subroutine of _get_str_representation() + """""" + if member_type is MemberType.FLOAT: + return f""{value}f"" + + elif member_type in (MemberType.TEXT, MemberType.FILE): + return f""\\""{value}\\"""" + + elif isinstance(member_type, NyanObject): + if import_tree: + sfqon = ""."".join(import_tree.get_alias_fqon(value.get_fqon())) + + else: + sfqon = ""."".join(value.get_fqon()) + + return sfqon + + return f""{value}""","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def _get_str_representation(self, indent_depth, import_tree=None, namespace=None): + """""" + Returns the nyan string representation of the value. + """""" + if not self.is_initialized(): + return f""UNINITIALIZED VALUE {self.__repr__()}"" + + if self._optional and self.value is MemberSpecialValue.NYAN_NONE: + return MemberSpecialValue.NYAN_NONE.value + + if self.value is MemberSpecialValue.NYAN_INF: + return MemberSpecialValue.NYAN_INF.value + + if self._member_type in (MemberType.INT, MemberType.FLOAT, + MemberType.TEXT, MemberType.FILE, + MemberType.BOOLEAN): + return self._get_primitive_value_str( + self._member_type, + self.value, + import_tree=import_tree, + namespace=namespace + ) + + elif self._member_type in (MemberType.SET, MemberType.ORDEREDSET): + return self._get_complex_value_str( + indent_depth, + self._member_type, + self.value, + import_tree=import_tree, + namespace=namespace + ) + + elif isinstance(self._member_type, NyanObject): + if import_tree: + sfqon = ""."".join(import_tree.get_alias_fqon( + self.value.get_fqon(), + namespace + )) + + else: + sfqon = ""."".join(self.value.get_fqon()) + + return sfqon + + else: + raise Exception(f""{self.__repr__()} has no valid type"")"," def _get_str_representation(self, import_tree=None): + """""" + Returns the nyan string representation of the value. + """""" + if not self.is_initialized(): + return f""UNINITIALIZED VALUE {self.__repr__()}"" + + if self._optional and self.value is MemberSpecialValue.NYAN_NONE: + return MemberSpecialValue.NYAN_NONE.value + + if self.value is MemberSpecialValue.NYAN_INF: + return MemberSpecialValue.NYAN_INF.value + + if self._member_type in (MemberType.INT, MemberType.FLOAT, + MemberType.TEXT, MemberType.FILE, + MemberType.BOOLEAN): + return self._get_primitive_value_str(self._member_type, + self.value, + import_tree=import_tree) + + elif self._member_type in (MemberType.SET, MemberType.ORDEREDSET): + output_str = """" + + if self._member_type is MemberType.ORDEREDSET: + output_str += ""o"" + + output_str += ""{"" + + if len(self.value) > 0: + for val in self.value: + output_str += ""%s, "" % self._get_primitive_value_str( + self._set_type, + val, + import_tree=import_tree + ) + + return output_str[:-2] + ""}"" + + return output_str + ""}"" + + elif isinstance(self._member_type, NyanObject): + if import_tree: + sfqon = ""."".join(import_tree.get_alias_fqon(self.value.get_fqon())) + + else: + sfqon = ""."".join(self.value.get_fqon()) + + return sfqon + + else: + raise Exception(f""{self.__repr__()} has no valid type"")","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def dump(self, indent_depth, import_tree=None, namespace=None): + """""" + Returns the string representation of the member. + """""" + return self.dump_short(indent_depth, import_tree=import_tree, namespace=namespace)"," def dump(self, import_tree=None): + """""" + Returns the string representation of the member. + """""" + return self.dump_short(import_tree=import_tree)","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +" def dump_short(self, indent_depth, import_tree=None, namespace=None): + """""" + Returns the nyan string representation of the member, but + without the type definition. + """""" + return ""%s %s%s %s"" % ( + self.get_name_with_origin(), + ""@"" * self._override_depth, + self._operator.value, + self._get_str_representation( + indent_depth, + import_tree=import_tree, + namespace=namespace + ) + )"," def dump_short(self, import_tree=None): + """""" + Returns the nyan string representation of the member, but + without the type definition. + """""" + return ""%s %s%s %s"" % (self.get_name_with_origin(), + ""@"" * self._override_depth, + self._operator.value, + self._get_str_representation(import_tree=import_tree))","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-377-g2be30ba76\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\nY\\nShould we call wine to determine an AOE installation? [Y/n]\\nn\\nCould not find any installation directory automatically.\\nPlease enter an AOE2 install path manually.\\n/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/\\nconverting from \\'/home/schatzi/nvme/Steam/steamapps/common/AoE2DE\\'\\nINFO [py] Game edition detected:\\nINFO [py] * Age of Empires 2: Definitive Edition\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] Starting conversion...\\nINFO [py] Extracting Genie data...\\nINFO [py] Creating API-like objects...\\nINFO [py] Linking API-like objects...\\nINFO [py] Generating auxiliary objects...\\nINFO [py] Creating nyan objects...\\nTraceback (most recent call last):\\nFile ""/usr/bin/openage"", line 15, in \\nmain()\\nFile ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main\\nused_asset_path = convert_assets(\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets\\nfor current_item in convert(args):\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert\\nyield from convert_metadata(args)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata\\nmodpacks = args.converter.convert(gamespec,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert\\nmodpacks = cls._post_processor(dataset)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor\\nDE2NyanSubprocessor.convert(full_data_set)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert\\ncls._process_game_entities(gamedata)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities\\ncls.tech_group_to_tech(tech_group)\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech\\npatches.extend(DE2TechSubprocessor.get_patches(tech_group))\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches\\npatches.extend(cls.resource_modify_effect(converter_group,\\nFile ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect\\nupgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]\\nKeyError: 208'}]","INFO [py] launching openage v0.4.1-377-g2be30ba76 +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +Y +Should we call wine to determine an AOE installation? [Y/n] +n +Could not find any installation directory automatically. +Please enter an AOE2 install path manually. +/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/ +converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE' +INFO [py] Game edition detected: +INFO [py] * Age of Empires 2: Definitive Edition +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] Starting conversion... +INFO [py] Extracting Genie data... +INFO [py] Creating API-like objects... +INFO [py] Linking API-like objects... +INFO [py] Generating auxiliary objects... +INFO [py] Creating nyan objects... +Traceback (most recent call last): +File ""/usr/bin/openage"", line 15, in +main() +File ""/usr/lib/python3.9/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/usr/lib/python3.9/site-packages/openage/game/main.py"", line 71, in main +used_asset_path = convert_assets( +File ""/usr/lib/python3.9/site-packages/openage/convert/main.py"", line 100, in convert_assets +for current_item in convert(args): +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 48, in convert +yield from convert_metadata(args) +File ""/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py"", line 96, in convert_metadata +modpacks = args.converter.convert(gamespec, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 63, in convert +modpacks = cls._post_processor(dataset) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py"", line 153, in _post_processor +DE2NyanSubprocessor.convert(full_data_set) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 38, in convert +cls._process_game_entities(gamedata) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 120, in _process_game_entities +cls.tech_group_to_tech(tech_group) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py"", line 596, in tech_group_to_tech +patches.extend(DE2TechSubprocessor.get_patches(tech_group)) +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 147, in get_patches +patches.extend(cls.resource_modify_effect(converter_group, +File ""/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py"", line 276, in resource_modify_effect +upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id] +KeyError: 208",KeyError +"def convert_assets(assets, args, srcdir=None, prev_source_dir_path=None): + """""" + Perform asset conversion. + + Requires original assets and stores them in usable and free formats. + + assets must be a filesystem-like object pointing at the game's asset dir. + srcdir must be None, or point at some source directory. + + If gen_extra_files is True, some more files, mostly for debugging purposes, + are created. + + This method prepares srcdir and targetdir to allow a pleasant, unified + conversion experience, then passes them to .driver.convert(). + """""" + # acquire conversion source directory + if srcdir is None: + srcdir = acquire_conversion_source_dir(prev_source_dir_path) + + converted_path = assets / ""converted"" + converted_path.mkdirs() + targetdir = DirectoryCreator(converted_path).root + + # Set compression level for media output if it was not set + if ""compression_level"" not in vars(args): + args.compression_level = 1 + + # Set verbosity for debug output + if ""debug_info"" not in vars(args): + if args.devmode: + args.debug_info = 3 + + else: + args.debug_info = 0 + + # add a dir for debug info + debug_log_path = converted_path / ""debug"" / datetime.now().strftime(""%Y-%m-%d-%H-%M-%S"") + debugdir = DirectoryCreator(debug_log_path).root + args.debugdir = AccessSynchronizer(debugdir).root + + # Create CLI args info + debug_cli_args(args.debugdir, args.debug_info, args) + + # Initialize game versions data + auxiliary_files_dir = args.cfg_dir / ""converter"" / ""games"" + args.avail_game_eds, args.avail_game_exps = create_version_objects(auxiliary_files_dir) + + # Acquire game version info + args.game_version = get_game_version(srcdir, args.avail_game_eds, args.avail_game_exps) + debug_game_version(args.debugdir, args.debug_info, args) + + # Mount assets into conversion folder + data_dir = mount_asset_dirs(srcdir, args.game_version) + if not data_dir: + return None + + # make srcdir and targetdir safe for threaded conversion + args.srcdir = AccessSynchronizer(data_dir).root + args.targetdir = AccessSynchronizer(targetdir).root + + # Create mountpoint info + debug_mounts(args.debugdir, args.debug_info, args) + + def flag(name): + """""" + Convenience function for accessing boolean flags in args. + Flags default to False if they don't exist. + """""" + return getattr(args, name, False) + + args.flag = flag + + # import here so codegen.py doesn't depend on it. + from .tool.driver import convert + + converted_count = 0 + total_count = None + for current_item in convert(args): + if isinstance(current_item, int): + # convert is informing us about the estimated number of remaining + # items. + total_count = current_item + converted_count + continue + + # TODO a GUI would be nice here. + + if total_count is None: + info(""[%s] %s"", converted_count, current_item) + else: + info(""[%s] %s"", format_progress(converted_count, total_count), current_item) + + converted_count += 1 + + # clean args + del args.srcdir + del args.targetdir + + return data_dir.resolve_native_path()","def convert_assets(assets, args, srcdir=None, prev_source_dir_path=None): + """""" + Perform asset conversion. + + Requires original assets and stores them in usable and free formats. + + assets must be a filesystem-like object pointing at the game's asset dir. + srcdir must be None, or point at some source directory. + + If gen_extra_files is True, some more files, mostly for debugging purposes, + are created. + + This method prepares srcdir and targetdir to allow a pleasant, unified + conversion experience, then passes them to .driver.convert(). + """""" + # acquire conversion source directory + if srcdir is None: + srcdir = acquire_conversion_source_dir(prev_source_dir_path) + + converted_path = assets / ""converted"" + converted_path.mkdirs() + targetdir = DirectoryCreator(converted_path).root + + # add a dir for debug info + debug_log_path = converted_path / ""debug"" / datetime.now().strftime(""%Y-%m-%d-%H-%M-%S"") + debugdir = DirectoryCreator(debug_log_path).root + args.debugdir = AccessSynchronizer(debugdir).root + + # Create CLI args info + debug_cli_args(args.debugdir, args.debug_info, args) + + # Initialize game versions data + auxiliary_files_dir = args.cfg_dir / ""converter"" / ""games"" + args.avail_game_eds, args.avail_game_exps = create_version_objects(auxiliary_files_dir) + + # Acquire game version info + args.game_version = get_game_version(srcdir, args.avail_game_eds, args.avail_game_exps) + debug_game_version(args.debugdir, args.debug_info, args) + + # Mount assets into conversion folder + data_dir = mount_asset_dirs(srcdir, args.game_version) + if not data_dir: + return None + + # make srcdir and targetdir safe for threaded conversion + args.srcdir = AccessSynchronizer(data_dir).root + args.targetdir = AccessSynchronizer(targetdir).root + + # Create mountpoint info + debug_mounts(args.debugdir, args.debug_info, args) + + def flag(name): + """""" + Convenience function for accessing boolean flags in args. + Flags default to False if they don't exist. + """""" + return getattr(args, name, False) + + args.flag = flag + + # import here so codegen.py doesn't depend on it. + from .tool.driver import convert + + converted_count = 0 + total_count = None + for current_item in convert(args): + if isinstance(current_item, int): + # convert is informing us about the estimated number of remaining + # items. + total_count = current_item + converted_count + continue + + # TODO a GUI would be nice here. + + if total_count is None: + info(""[%s] %s"", converted_count, current_item) + else: + info(""[%s] %s"", format_progress(converted_count, total_count), current_item) + + converted_count += 1 + + # clean args + del args.srcdir + del args.targetdir + + return data_dir.resolve_native_path()","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-371-g0c6e704b\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\ny\\nTraceback (most recent call last):\\nFile ""/app/bin/openage"", line 15, in \\nmain()\\nFile ""/app/lib/python3.8/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/app/lib/python3.8/site-packages/openage/game/main.py"", line 68, in main\\nused_asset_path = convert_assets(root[""assets""], root[""cfg""], args,\\nFile ""/app/lib/python3.8/site-packages/openage/convert/main.py"", line 52, in convert_assets\\ndebug_cli_args(args.debugdir, args.debug_info, args)\\nAttributeError: \\'UnionPath\\' object has no attribute \\'debug_info\\''}]","INFO [py] launching openage v0.4.1-371-g0c6e704b +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +y +Traceback (most recent call last): +File ""/app/bin/openage"", line 15, in +main() +File ""/app/lib/python3.8/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/app/lib/python3.8/site-packages/openage/game/main.py"", line 68, in main +used_asset_path = convert_assets(root[""assets""], root[""cfg""], args, +File ""/app/lib/python3.8/site-packages/openage/convert/main.py"", line 52, in convert_assets +debug_cli_args(args.debugdir, args.debug_info, args) +AttributeError: 'UnionPath' object has no attribute 'debug_info'",AttributeError +"def main(args, error): + """""" CLI entry point """""" + del error # unused + + # initialize libopenage + from ..cppinterface.setup import setup + setup(args) + + # conversion source + if args.source_dir is not None: + srcdir = CaseIgnoringDirectory(args.source_dir).root + else: + srcdir = None + + # mount the config folder at ""cfg/"" + from ..cvar.location import get_config_path + from ..util.fslike.union import Union + root = Union().root + root[""cfg""].mount(get_config_path()) + args.cfg_dir = root[""cfg""] + + if args.interactive: + interactive_browser(root[""cfg""], srcdir) + return 0 + + # conversion target + from ..assets import get_asset_path + outdir = get_asset_path(args.output_dir) + + if args.force or wanna_convert() or conversion_required(outdir, args): + if not convert_assets(outdir, args, srcdir): + return 1 + else: + print(""assets are up to date; no conversion is required."") + print(""override with --force."") + + return 0","def main(args, error): + """""" CLI entry point """""" + del error # unused + + # initialize libopenage + from ..cppinterface.setup import setup + setup(args) + + # conversion source + if args.source_dir is not None: + srcdir = CaseIgnoringDirectory(args.source_dir).root + else: + srcdir = None + + # Set verbosity for debug output + if not args.debug_info: + if args.devmode: + args.debug_info = 3 + + else: + args.debug_info = 0 + + # mount the config folder at ""cfg/"" + from ..cvar.location import get_config_path + from ..util.fslike.union import Union + root = Union().root + root[""cfg""].mount(get_config_path()) + args.cfg_dir = root[""cfg""] + + if args.interactive: + interactive_browser(root[""cfg""], srcdir) + return 0 + + # conversion target + from ..assets import get_asset_path + outdir = get_asset_path(args.output_dir) + + if args.force or wanna_convert() or conversion_required(outdir, args): + if not convert_assets(outdir, args, srcdir): + return 1 + else: + print(""assets are up to date; no conversion is required."") + print(""override with --force."") + + return 0","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-371-g0c6e704b\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\ny\\nTraceback (most recent call last):\\nFile ""/app/bin/openage"", line 15, in \\nmain()\\nFile ""/app/lib/python3.8/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/app/lib/python3.8/site-packages/openage/game/main.py"", line 68, in main\\nused_asset_path = convert_assets(root[""assets""], root[""cfg""], args,\\nFile ""/app/lib/python3.8/site-packages/openage/convert/main.py"", line 52, in convert_assets\\ndebug_cli_args(args.debugdir, args.debug_info, args)\\nAttributeError: \\'UnionPath\\' object has no attribute \\'debug_info\\''}]","INFO [py] launching openage v0.4.1-371-g0c6e704b +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +y +Traceback (most recent call last): +File ""/app/bin/openage"", line 15, in +main() +File ""/app/lib/python3.8/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/app/lib/python3.8/site-packages/openage/game/main.py"", line 68, in main +used_asset_path = convert_assets(root[""assets""], root[""cfg""], args, +File ""/app/lib/python3.8/site-packages/openage/convert/main.py"", line 52, in convert_assets +debug_cli_args(args.debugdir, args.debug_info, args) +AttributeError: 'UnionPath' object has no attribute 'debug_info'",AttributeError +"def main(args, error): + """""" + Makes sure that the assets have been converted, + and jumps into the C++ main method. + """""" + del error # unused + + # we have to import stuff inside the function + # as it depends on generated/compiled code + from .main_cpp import run_game + from .. import config + from ..assets import get_asset_path + from ..convert.main import conversion_required, convert_assets + from ..cppinterface.setup import setup as cpp_interface_setup + from ..cvar.location import get_config_path + from ..util.fslike.union import Union + + # initialize libopenage + cpp_interface_setup(args) + + info(""launching openage %s"", config.VERSION) + info(""compiled by %s"", config.COMPILER) + + if config.DEVMODE: + info(""running in DEVMODE"") + + # create virtual file system for data paths + root = Union().root + + # mount the assets folder union at ""assets/"" + root[""assets""].mount(get_asset_path(args.asset_dir)) + + # mount the config folder at ""cfg/"" + root[""cfg""].mount(get_config_path(args.cfg_dir)) + args.cfg_dir = root[""cfg""] + + # ensure that the assets have been converted + if wanna_convert() or conversion_required(root[""assets""], args): + # try to get previously used source dir + asset_location_path = root[""cfg""] / ""asset_location"" + try: + with asset_location_path.open(""r"") as file_obj: + prev_source_dir_path = file_obj.read().strip() + except FileNotFoundError: + prev_source_dir_path = None + used_asset_path = convert_assets( + root[""assets""], + args, + prev_source_dir_path=prev_source_dir_path + ) + + if used_asset_path: + # Remember the asset location + with asset_location_path.open(""wb"") as file_obj: + file_obj.write(used_asset_path) + else: + err(""game asset conversion failed"") + return 1 + + # Exit here with an explanation because the converted assets are incompatible! + # Remove this when the gamestate works again + info(""Generated nyan assets are not yet compatible to the engine."") + info(""Please revert to release v0.4.1 if you want to test the previous working gamestate."") + info(""Exiting..."") + import sys + sys.exit() + + # start the game, continue in main_cpp.pyx! + return run_game(args, root)","def main(args, error): + """""" + Makes sure that the assets have been converted, + and jumps into the C++ main method. + """""" + del error # unused + + # we have to import stuff inside the function + # as it depends on generated/compiled code + from .main_cpp import run_game + from .. import config + from ..assets import get_asset_path + from ..convert.main import conversion_required, convert_assets + from ..cppinterface.setup import setup as cpp_interface_setup + from ..cvar.location import get_config_path + from ..util.fslike.union import Union + + # initialize libopenage + cpp_interface_setup(args) + + info(""launching openage %s"", config.VERSION) + info(""compiled by %s"", config.COMPILER) + + if config.DEVMODE: + info(""running in DEVMODE"") + + # create virtual file system for data paths + root = Union().root + + # mount the assets folder union at ""assets/"" + root[""assets""].mount(get_asset_path(args.asset_dir)) + + # mount the config folder at ""cfg/"" + root[""cfg""].mount(get_config_path(args.cfg_dir)) + + # ensure that the assets have been converted + if wanna_convert() or conversion_required(root[""assets""], args): + # try to get previously used source dir + asset_location_path = root[""cfg""] / ""asset_location"" + try: + with asset_location_path.open(""r"") as file_obj: + prev_source_dir_path = file_obj.read().strip() + except FileNotFoundError: + prev_source_dir_path = None + used_asset_path = convert_assets(root[""assets""], root[""cfg""], args, + prev_source_dir_path=prev_source_dir_path) + if used_asset_path: + # Remember the asset location + with asset_location_path.open(""wb"") as file_obj: + file_obj.write(used_asset_path) + else: + err(""game asset conversion failed"") + return 1 + + # start the game, continue in main_cpp.pyx! + return run_game(args, root)","[{'piece_type': 'error message', 'piece_content': 'INFO [py] launching openage v0.4.1-371-g0c6e704b\\nINFO [py] compiled by GNU 10.2.0\\nDo you want to convert assets? [Y/n]\\ny\\nTraceback (most recent call last):\\nFile ""/app/bin/openage"", line 15, in \\nmain()\\nFile ""/app/lib/python3.8/site-packages/openage/__main__.py"", line 132, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/app/lib/python3.8/site-packages/openage/game/main.py"", line 68, in main\\nused_asset_path = convert_assets(root[""assets""], root[""cfg""], args,\\nFile ""/app/lib/python3.8/site-packages/openage/convert/main.py"", line 52, in convert_assets\\ndebug_cli_args(args.debugdir, args.debug_info, args)\\nAttributeError: \\'UnionPath\\' object has no attribute \\'debug_info\\''}]","INFO [py] launching openage v0.4.1-371-g0c6e704b +INFO [py] compiled by GNU 10.2.0 +Do you want to convert assets? [Y/n] +y +Traceback (most recent call last): +File ""/app/bin/openage"", line 15, in +main() +File ""/app/lib/python3.8/site-packages/openage/__main__.py"", line 132, in main +return args.entrypoint(args, cli.error) +File ""/app/lib/python3.8/site-packages/openage/game/main.py"", line 68, in main +used_asset_path = convert_assets(root[""assets""], root[""cfg""], args, +File ""/app/lib/python3.8/site-packages/openage/convert/main.py"", line 52, in convert_assets +debug_cli_args(args.debugdir, args.debug_info, args) +AttributeError: 'UnionPath' object has no attribute 'debug_info'",AttributeError +"def main(): + """""" CLI entry point """""" + args = parse_args() + cppname = ""libopenage"" + cppdir = Path(cppname).absolute() + out_cppdir = Path(args.output_dir) / cppname + + if args.verbose: + hdr_count = len(args.all_files) + plural = ""s"" if hdr_count > 1 else """" + + print(""extracting pxd information "" + ""from {} header{}..."".format(hdr_count, plural)) + + for filename in args.all_files: + filename = Path(filename).resolve() + if cppdir not in filename.parents: + print(""pxdgen source file is not in "" + cppdir + "": "" + filename) + sys.exit(1) + + # join out_cppdir with relative path from cppdir + pxdfile_relpath = filename.with_suffix('.pxd').relative_to(cppdir) + pxdfile = out_cppdir / pxdfile_relpath + + if args.verbose: + print(""creating '{}' for '{}':"".format(pxdfile, filename)) + + generator = PXDGenerator(filename) + + result = generator.generate( + pxdfile, + ignore_timestamps=args.ignore_timestamps, + print_warnings=True + ) + + if args.verbose and not result: + print(""nothing done."") + + # create empty __init__.py in all parent directories. + # Cython requires this; else it won't find the .pxd files. + for dirname in pxdfile_relpath.parents: + template = out_cppdir / dirname / ""__init__"" + for extension in (""py"", ""pxd""): + initfile = template.with_suffix(""."" + extension) + if not initfile.exists(): + print(""\\x1b[36mpxdgen: create package index %s\\x1b[0m"" % ( + initfile.relative_to(args.output_dir))) + + initfile.touch()","def main(): + """""" CLI entry point """""" + args = parse_args() + cppname = ""libopenage"" + cppdir = Path(cppname).absolute() + out_cppdir = Path(args.output_dir) / cppname + + if args.verbose: + hdr_count = len(args.all_files) + plural = ""s"" if hdr_count > 1 else """" + + print(""extracting pxd information "" + ""from {} header{}..."".format(hdr_count, plural)) + + for filename in args.all_files: + filename = Path(filename).resolve() + if cppdir not in filename.parents: + print(""pxdgen source file is not in "" + cppdir + "": "" + filename) + sys.exit(1) + + # join out_cppdir with relative path from cppdir + pxdfile_relpath = filename.with_suffix('.pxd').relative_to(cppdir) + pxdfile = out_cppdir / pxdfile_relpath + + if args.verbose: + print(""creating '{}' for '{}':"".format(pxdfile, filename)) + + generator = PXDGenerator(filename) + + result = generator.generate( + pxdfile, + ignore_timestamps=args.ignore_timestamps, + print_warnings=True + ) + + if args.verbose and not result: + print(""nothing done."") + + # create empty __init__.py in all parent directories. + # Cython requires this; else it won't find the .pxd files. + for dirname in pxdfile_relpath.parents: + template = out_cppdir / dirname / ""__init__"" + for extension in (""py"", ""pxd""): + initfile = template.with_suffix(""."" + extension) + if not initfile.exists(): + print(""\\x1b[36mpxdgen: create package index %s\\x1b[0m"" % ( + initfile.relative_to(CWD))) + + initfile.touch()","[{'piece_type': 'error message', 'piece_content': '% make pxdgen VERBOSE=1\\n/usr/bin/cmake -S/tmp/portage/games-strategy/openage-9999/work/openage-9999 -B/tmp/portage/games-strategy/openage-9999/work/openage-9999_build --check-build-system CMakeFiles/Makefile.cmake 0\\nmake -f CMakeFiles/Makefile2 pxdgen\\nmake[1]: Entering directory \\'/tmp/portage/games-strategy/openage-9999/work/openage-9999_build\\'\\n/usr/bin/cmake -S/tmp/portage/games-strategy/openage-9999/work/openage-9999 -B/tmp/portage/games-strategy/openage-9999/work/openage-9999_build --check-build-system CMakeFiles/Makefile.cmake 0\\n/usr/bin/cmake -E cmake_progress_start /tmp/portage/games-strategy/openage-9999/work/openage-9999_build/CMakeFiles 1\\nmake -f CMakeFiles/Makefile2 CMakeFiles/pxdgen.dir/all\\nmake[2]: Entering directory \\'/tmp/portage/games-strategy/openage-9999/work/openage-9999_build\\'\\nmake -f CMakeFiles/pxdgen.dir/build.make CMakeFiles/pxdgen.dir/depend\\nmake[3]: Entering directory \\'/tmp/portage/games-strategy/openage-9999/work/openage-9999_build\\'\\ncd /tmp/portage/games-strategy/openage-9999/work/openage-9999_build && /usr/bin/cmake -E cmake_depends ""Unix Makefiles"" /tmp/portage/games-strategy/openage-9999/work/openage-9999 /tmp/portage/games-strategy/openage-9999/work/openage-9999 /tmp/portage/games-strategy/openage-9999/work/openage-9999_build /tmp/portage/games-strategy/openage-9999/work/openage-9999_build /tmp/portage/games-strategy/openage-9999/work/openage-9999_build/CMakeFiles/pxdgen.dir/DependInfo.cmake --color=\\nmake[3]: Leaving directory \\'/tmp/portage/games-strategy/openage-9999/work/openage-9999_build\\'\\nmake -f CMakeFiles/pxdgen.dir/build.make CMakeFiles/pxdgen.dir/build\\nmake[3]: Entering directory \\'/tmp/portage/games-strategy/openage-9999/work/openage-9999_build\\'\\n[100%] pxdgen: generating .pxd files from headers\\ncd /tmp/portage/games-strategy/openage-9999/work/openage-9999 && /usr/bin/python3.6 -m buildsystem.pxdgen --file-list /tmp/portage/games-strategy/openage-9999/work/openage-9999_build/py/pxdgen_sources --output-dir /tmp/portage/games-strategy/openage-9999/work/openage-9999_build\\nTraceback (most recent call last):\\nFile ""/usr/lib64/python3.6/runpy.py"", line 193, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib64/python3.6/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/tmp/portage/games-strategy/openage-9999/work/openage-9999/buildsystem/pxdgen.py"", line 479, in \\nmain()\\nFile ""/tmp/portage/games-strategy/openage-9999/work/openage-9999/buildsystem/pxdgen.py"", line 473, in main\\ninitfile.relative_to(CWD)))\\nFile ""/usr/lib64/python3.6/pathlib.py"", line 874, in relative_to\\n.format(str(self), str(formatted)))\\nValueError: \\'/tmp/portage/games-strategy/openage-9999/work/openage-9999_build/libopenage/__init__.py\\' does not start with \\'/tmp/portage/games-strategy/openage-9999/work/openage-9999\\'\\nmake[3]: *** [CMakeFiles/pxdgen.dir/build.make:94: py/pxdgen_timefile] Error 1\\nmake[3]: Leaving directory \\'/tmp/portage/games-strategy/openage-9999/work/openage-9999_build\\'\\nmake[2]: *** [CMakeFiles/Makefile2:1198: CMakeFiles/pxdgen.dir/all] Error 2\\nmake[2]: Leaving directory \\'/tmp/portage/games-strategy/openage-9999/work/openage-9999_build\\'\\nmake[1]: *** [CMakeFiles/Makefile2:1209: CMakeFiles/pxdgen.dir/rule] Error 2\\nmake[1]: Leaving directory \\'/tmp/portage/games-strategy/openage-9999/work/openage-9999_build\\'\\nmake: *** [Makefile:652: pxdgen] Error 2'}]","% make pxdgen VERBOSE=1 +/usr/bin/cmake -S/tmp/portage/games-strategy/openage-9999/work/openage-9999 -B/tmp/portage/games-strategy/openage-9999/work/openage-9999_build --check-build-system CMakeFiles/Makefile.cmake 0 +make -f CMakeFiles/Makefile2 pxdgen +make[1]: Entering directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' +/usr/bin/cmake -S/tmp/portage/games-strategy/openage-9999/work/openage-9999 -B/tmp/portage/games-strategy/openage-9999/work/openage-9999_build --check-build-system CMakeFiles/Makefile.cmake 0 +/usr/bin/cmake -E cmake_progress_start /tmp/portage/games-strategy/openage-9999/work/openage-9999_build/CMakeFiles 1 +make -f CMakeFiles/Makefile2 CMakeFiles/pxdgen.dir/all +make[2]: Entering directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' +make -f CMakeFiles/pxdgen.dir/build.make CMakeFiles/pxdgen.dir/depend +make[3]: Entering directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' +cd /tmp/portage/games-strategy/openage-9999/work/openage-9999_build && /usr/bin/cmake -E cmake_depends ""Unix Makefiles"" /tmp/portage/games-strategy/openage-9999/work/openage-9999 /tmp/portage/games-strategy/openage-9999/work/openage-9999 /tmp/portage/games-strategy/openage-9999/work/openage-9999_build /tmp/portage/games-strategy/openage-9999/work/openage-9999_build /tmp/portage/games-strategy/openage-9999/work/openage-9999_build/CMakeFiles/pxdgen.dir/DependInfo.cmake --color= +make[3]: Leaving directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' +make -f CMakeFiles/pxdgen.dir/build.make CMakeFiles/pxdgen.dir/build +make[3]: Entering directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' +[100%] pxdgen: generating .pxd files from headers +cd /tmp/portage/games-strategy/openage-9999/work/openage-9999 && /usr/bin/python3.6 -m buildsystem.pxdgen --file-list /tmp/portage/games-strategy/openage-9999/work/openage-9999_build/py/pxdgen_sources --output-dir /tmp/portage/games-strategy/openage-9999/work/openage-9999_build +Traceback (most recent call last): +File ""/usr/lib64/python3.6/runpy.py"", line 193, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib64/python3.6/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/tmp/portage/games-strategy/openage-9999/work/openage-9999/buildsystem/pxdgen.py"", line 479, in +main() +File ""/tmp/portage/games-strategy/openage-9999/work/openage-9999/buildsystem/pxdgen.py"", line 473, in main +initfile.relative_to(CWD))) +File ""/usr/lib64/python3.6/pathlib.py"", line 874, in relative_to +.format(str(self), str(formatted))) +ValueError: '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build/libopenage/__init__.py' does not start with '/tmp/portage/games-strategy/openage-9999/work/openage-9999' +make[3]: *** [CMakeFiles/pxdgen.dir/build.make:94: py/pxdgen_timefile] Error 1 +make[3]: Leaving directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' +make[2]: *** [CMakeFiles/Makefile2:1198: CMakeFiles/pxdgen.dir/all] Error 2 +make[2]: Leaving directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' +make[1]: *** [CMakeFiles/Makefile2:1209: CMakeFiles/pxdgen.dir/rule] Error 2 +make[1]: Leaving directory '/tmp/portage/games-strategy/openage-9999/work/openage-9999_build' +make: *** [Makefile:652: pxdgen] Error 2",ValueError +"def main(argv=None): + """""" Top-level argparsing; invokes subparser for all submodules. """""" + cli = argparse.ArgumentParser( + ""openage"", + description=(""free age of empires II engine clone"") + ) + + cli.add_argument(""--version"", ""-V"", nargs=0, action=PrintVersion, + help=""print version info and exit"") + + # shared arguments for all subcommands + global_cli = argparse.ArgumentParser(add_help=False) + global_cli.add_argument(""--verbose"", ""-v"", action='count', + default=ENV_VERBOSITY, + help=""increase verbosity"") + global_cli.add_argument(""--quiet"", ""-q"", action='count', default=0, + help=""decrease verbosity"") + global_cli.add_argument(""--devmode"", action=""store_true"", + help=""force-enable development mode"") + global_cli.add_argument(""--no-devmode"", action=""store_true"", + help=""force-disable devlopment mode"") + global_cli.add_argument(""--trap-exceptions"", action=""store_true"", + help=(""upon throwing an exception a debug break is "" + ""triggered. this will crash openage if no "" + ""debugger is present"")) + + # shared directory arguments for most subcommands + cfg_cli = argparse.ArgumentParser(add_help=False) + + cfg_cli.add_argument(""--asset-dir"", + help=""Use this as an additional asset directory."") + cfg_cli.add_argument(""--cfg-dir"", + help=""Use this as an additional config directory."") + + subparsers = cli.add_subparsers(dest=""subcommand"") + + # enable reimports for ""init_subparser"" + # pylint: disable=reimported + + from .game.main import init_subparser + game_cli = subparsers.add_parser( + ""game"", + parents=[global_cli, cfg_cli]) + init_subparser(game_cli) + + from .testing.main import init_subparser + init_subparser(subparsers.add_parser( + ""test"", + parents=[global_cli, cfg_cli])) + + from .convert.main import init_subparser + init_subparser(subparsers.add_parser( + ""convert"", + parents=[global_cli])) + + from .convert.singlefile import init_subparser + init_subparser(subparsers.add_parser( + ""convert-file"", + parents=[global_cli])) + + from .codegen.main import init_subparser + init_subparser(subparsers.add_parser( + ""codegen"", + parents=[global_cli])) + + args = cli.parse_args(argv) + + if not args.subcommand: + # the user didn't specify a subcommand. default to 'game'. + args = game_cli.parse_args(argv) + + # process the shared args + set_loglevel(verbosity_to_level(args.verbose - args.quiet)) + + if args.no_devmode and args.devmode: + cli.error(""can't force enable and disable devmode at the same time"") + + try: + from . import config + + if args.no_devmode: + config.DEVMODE = False + if args.devmode: + config.DEVMODE = True + except ImportError: + if args.no_devmode or args.devmode: + print(""code was not yet generated, ignoring devmode activation request"") + + if ""asset_dir"" in args and args.asset_dir: + if not os.path.exists(args.asset_dir): + cli.error(""asset directory does not exist: "" + args.asset_dir) + + # call the entry point for the subcommand. + return args.entrypoint(args, cli.error)","def main(argv=None): + """""" Top-level argparsing; invokes subparser for all submodules. """""" + cli = argparse.ArgumentParser( + ""openage"", + description=(""free age of empires II engine clone"") + ) + + cli.add_argument(""--version"", ""-V"", nargs=0, action=PrintVersion, + help=""print version info and exit"") + + # shared arguments for all subcommands + global_cli = argparse.ArgumentParser(add_help=False) + global_cli.add_argument(""--verbose"", ""-v"", action='count', + default=ENV_VERBOSITY, + help=""increase verbosity"") + global_cli.add_argument(""--quiet"", ""-q"", action='count', default=0, + help=""decrease verbosity"") + global_cli.add_argument(""--devmode"", action=""store_true"", + help=""force-enable development mode"") + global_cli.add_argument(""--no-devmode"", action=""store_true"", + help=""force-disable devlopment mode"") + global_cli.add_argument(""--trap-exceptions"", action=""store_true"", + help=(""upon throwing an exception a debug break is "" + ""triggered. this will crash openage if no "" + ""debugger is present"")) + + # shared directory arguments for most subcommands + cfg_cli = argparse.ArgumentParser(add_help=False) + + cfg_cli.add_argument(""--asset-dir"", + help=""Use this as an additional asset directory."") + cfg_cli.add_argument(""--cfg-dir"", + help=""Use this as an additional config directory."") + + subparsers = cli.add_subparsers(dest=""subcommand"") + + # enable reimports for ""init_subparser"" + # pylint: disable=reimported + + from .game.main import init_subparser + game_cli = subparsers.add_parser( + ""game"", + parents=[global_cli, cfg_cli]) + init_subparser(game_cli) + + from .testing.main import init_subparser + init_subparser(subparsers.add_parser( + ""test"", + parents=[global_cli, cfg_cli])) + + from .convert.main import init_subparser + init_subparser(subparsers.add_parser( + ""convert"", + parents=[global_cli, cfg_cli])) + + from .convert.singlefile import init_subparser + init_subparser(subparsers.add_parser( + ""convert-file"", + parents=[global_cli, cfg_cli])) + + from .codegen.main import init_subparser + init_subparser(subparsers.add_parser( + ""codegen"", + parents=[global_cli])) + + args = cli.parse_args(argv) + + if not args.subcommand: + # the user didn't specify a subcommand. default to 'game'. + args = game_cli.parse_args(argv) + + # process the shared args + set_loglevel(verbosity_to_level(args.verbose - args.quiet)) + + if args.no_devmode and args.devmode: + cli.error(""can't force enable and disable devmode at the same time"") + + try: + from . import config + + if args.no_devmode: + config.DEVMODE = False + if args.devmode: + config.DEVMODE = True + except ImportError: + if args.no_devmode or args.devmode: + print(""code was not yet generated, ignoring devmode activation request"") + + if ""asset_dir"" in args and args.asset_dir: + if not os.path.exists(args.asset_dir): + cli.error(""directory does not exist: "" + args.asset_dir) + + # call the entry point for the subcommand. + return args.entrypoint(args, cli.error)","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +"def get_asset_path(custom_asset_dir=None): + """""" + Returns a Path object for the game assets. + + `custom_asset_dir` can a custom asset directory, which is mounted at the + top of the union filesystem (i.e. has highest priority). + + This function is used by the both the conversion process + and the game startup. The conversion uses it for its output, + the game as its data source(s). + """""" + + # if we're in devmode, use only the in-repo asset folder + if not custom_asset_dir and config.DEVMODE: + return Directory(os.path.join(config.BUILD_SRC_DIR, ""assets"")).root + + # else, mount the possible locations in an union: + # overlay the global dir and the user dir. + result = Union().root + + # the cmake-determined folder for storing assets + global_data = Path(config.GLOBAL_ASSET_DIR) + if global_data.is_dir(): + result.mount(WriteBlocker(Directory(global_data).root).root) + + # user-data directory as provided by environment variables + # and platform standards + # we always create this! + home_data = default_dirs.get_dir(""data_home"") / ""openage"" + result.mount( + Directory( + home_data, + create_if_missing=True + ).root / ""assets"" + ) + + # the program argument overrides it all + if custom_asset_dir: + result.mount(Directory(custom_asset_dir).root) + + return result","def get_asset_path(args): + """""" + Returns a Path object for the game assets. + + args are the arguments, as provided by the CLI's ArgumentParser. + """""" + + # if we're in devmode, use only the build source asset folder + if not args.asset_dir and config.DEVMODE: + return Directory(os.path.join(config.BUILD_SRC_DIR, ""assets"")).root + + # else, mount the possible locations in an union: + # overlay the global dir and the user dir. + result = Union().root + + # the cmake-determined folder for storing assets + global_data = Path(config.GLOBAL_ASSET_DIR) + if global_data.is_dir(): + result.mount(WriteBlocker(Directory(global_data).root).root) + + # user-data directory as provided by environment variables + # and platform standards + # we always create this! + home_data = default_dirs.get_dir(""data_home"") / ""openage"" + result.mount( + Directory( + home_data, + create_if_missing=True + ).root / ""assets"" + ) + + # the program argument overrides it all + if args.asset_dir: + result.mount(Directory(args.asset_dir).root) + + return result","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +"def interactive_browser(srcdir=None): + """""" + launch an interactive view for browsing the original + archives. + """""" + + info(""launching interactive data browser..."") + + # the variables are actually used, in the interactive prompt. + # pylint: disable=unused-variable + data, game_versions = mount_input(srcdir) + + if not data: + warn(""cannot launch browser as no valid input assets were found."") + return + + def save(path, target): + """""" + save a path to a custom target + """""" + with path.open(""rb"") as infile: + with open(target, ""rb"") as outfile: + outfile.write(infile.read()) + + def save_slp(path, target, palette=None): + """""" + save a slp as png. + """""" + from .texture import Texture + from .slp import SLP + from .driver import get_palette + + if not palette: + palette = get_palette(data) + + with path.open(""rb"") as slpfile: + tex = Texture(SLP(slpfile.read()), palette) + + out_path, filename = os.path.split(target) + tex.save(Directory(out_path).root, filename) + + import code + from pprint import pprint + + import rlcompleter + + completer = rlcompleter.Completer(locals()) + readline.parse_and_bind(""tab: complete"") + readline.parse_and_bind(""set show-all-if-ambiguous on"") + readline.set_completer(completer.complete) + + code.interact( + banner=(""\\nuse `pprint` for beautiful output!\\n"" + ""you can access stuff by the `data` variable!\\n"" + ""`data` is an openage.util.fslike.path.Path!\\n\\n"" + ""* version detection: pprint(game_versions)\\n"" + ""* list contents: pprint(list(data['graphics'].list()))\\n"" + ""* dump data: save(data['file/path'], '/tmp/outputfile')\\n"" + ""* save a slp as png: save_slp(data['dir/123.slp'], '/tmp/pic.png')\\n""), + local=locals() + )","def interactive_browser(srcdir=None): + """""" + launch an interactive view for browsing the original + archives. + """""" + + info(""launching interactive data browser..."") + + # the variable is actually used, in the interactive prompt. + # pylint: disable=unused-variable + data, game_versions = mount_input(srcdir) + + if not data: + warn(""cannot launch browser as no valid input assets were found."") + return + + def save(path, target): + """""" + save a path to a custom target + """""" + with path.open(""rb"") as infile: + with open(target, ""rb"") as outfile: + outfile.write(infile.read()) + + def save_slp(path, target, palette=None): + """""" + save a slp as png. + """""" + from .texture import Texture + from .slp import SLP + from .driver import get_palette + + if not palette: + palette = get_palette(data, game_versions) + + with path.open(""rb"") as slpfile: + tex = Texture(SLP(slpfile.read()), palette) + + out_path, filename = os.path.split(target) + tex.save(Directory(out_path).root, filename) + + import code + from pprint import pprint + + import rlcompleter + + completer = rlcompleter.Completer(locals()) + readline.parse_and_bind(""tab: complete"") + readline.parse_and_bind(""set show-all-if-ambiguous on"") + readline.set_completer(completer.complete) + + code.interact( + banner=(""\\nuse `pprint` for beautiful output!\\n"" + ""you can access stuff by the `data` variable!\\n"" + ""`data` is an openage.util.fslike.path.Path!\\n"" + ""* list contents: `pprint(list(data['graphics'].list()))`\\n"" + ""* dump data: `save(data['file/path'], '/tmp/outputfile')`.\\n"" + ""* save a slp as png: `save_slp(data['dir/123.slp'], '/tmp/pic.png')`.\\n""), + local=locals() + )","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +" def save_slp(path, target, palette=None): + """""" + save a slp as png. + """""" + from .texture import Texture + from .slp import SLP + from .driver import get_palette + + if not palette: + palette = get_palette(data) + + with path.open(""rb"") as slpfile: + tex = Texture(SLP(slpfile.read()), palette) + + out_path, filename = os.path.split(target) + tex.save(Directory(out_path).root, filename)"," def save_slp(path, target, palette=None): + """""" + save a slp as png. + """""" + from .texture import Texture + from .slp import SLP + from .driver import get_palette + + if not palette: + palette = get_palette(data, game_versions) + + with path.open(""rb"") as slpfile: + tex = Texture(SLP(slpfile.read()), palette) + + out_path, filename = os.path.split(target) + tex.save(Directory(out_path).root, filename)","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +"def init_subparser(cli): + """""" Initializes the parser for convert-specific args. """""" + cli.set_defaults(entrypoint=main) + + cli.add_argument( + ""--source-dir"", default=None, + help=""source data directory"") + + cli.add_argument( + ""--output-dir"", default=None, + help=""destination data output directory"") + + cli.add_argument( + ""--force"", action='store_true', + help=""force conversion, even if up-to-date assets already exist."") + + cli.add_argument( + ""--gen-extra-files"", action='store_true', + help=""generate some extra files, useful for debugging the converter."") + + cli.add_argument( + ""--no-media"", action='store_true', + help=""do not convert any media files (slp, wav, ...)"") + + cli.add_argument( + ""--no-metadata"", action='store_true', + help=(""do not store any metadata "" + ""(except for those associated with media files)"")) + + cli.add_argument( + ""--no-sounds"", action='store_true', + help=""do not convert any sound files"") + + cli.add_argument( + ""--no-graphics"", action='store_true', + help=""do not convert game graphics"") + + cli.add_argument( + ""--no-interface"", action='store_true', + help=""do not convert interface graphics"") + + cli.add_argument( + ""--no-scripts"", action='store_true', + help=""do not convert scripts (AI and Random Maps)"") + + cli.add_argument( + ""--no-pickle-cache"", action='store_true', + help=""don't use a pickle file to skip the dat file reading."") + + cli.add_argument( + ""--jobs"", ""-j"", type=int, default=None) + + cli.add_argument( + ""--interactive"", ""-i"", action='store_true', + help=""browse the files interactively"") + + cli.add_argument( + ""--id"", type=int, default=None, + help=""only convert files with this id (used for debugging..)"")","def init_subparser(cli): + """""" Initializes the parser for convert-specific args. """""" + cli.set_defaults(entrypoint=main) + + cli.add_argument( + ""--source-dir"", default=None, + help=""source data directory"") + + cli.add_argument( + ""--force"", action='store_true', + help=""force conversion, even if up-to-date assets already exist."") + + cli.add_argument( + ""--gen-extra-files"", action='store_true', + help=""generate some extra files, useful for debugging the converter."") + + cli.add_argument( + ""--no-media"", action='store_true', + help=""do not convert any media files (slp, wav, ...)"") + + cli.add_argument( + ""--no-metadata"", action='store_true', + help=(""do not store any metadata "" + ""(except for those associated with media files)"")) + + cli.add_argument( + ""--no-sounds"", action='store_true', + help=""do not convert any sound files"") + + cli.add_argument( + ""--no-graphics"", action='store_true', + help=""do not convert game graphics"") + + cli.add_argument( + ""--no-interface"", action='store_true', + help=""do not convert interface graphics"") + + cli.add_argument( + ""--no-scripts"", action='store_true', + help=""do not convert scripts (AI and Random Maps)"") + + cli.add_argument( + ""--no-pickle-cache"", action='store_true', + help=""don't use a pickle file to skip the dat file reading."") + + cli.add_argument( + ""--jobs"", ""-j"", type=int, default=None) + + cli.add_argument( + ""--interactive"", ""-i"", action='store_true', + help=""browse the files interactively"") + + cli.add_argument( + ""--id"", type=int, default=None, + help=""only convert files with this id (used for debugging..)"")","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +"def main(args, error): + """""" CLI entry point """""" + del error # unused + + # initialize libopenage + from ..cppinterface.setup import setup + setup(args) + + # conversion source + if args.source_dir is not None: + srcdir = CaseIgnoringDirectory(args.source_dir).root + else: + srcdir = None + + if args.interactive: + interactive_browser(srcdir) + return 0 + + # conversion target + from ..assets import get_asset_path + outdir = get_asset_path(args.output_dir) + + if args.force or conversion_required(outdir, args): + if not convert_assets(outdir, args, srcdir): + return 1 + else: + print(""assets are up to date; no conversion is required."") + print(""override with --force."")","def main(args, error): + """""" CLI entry point """""" + del error # unused + + # initialize libopenage + from ..cppinterface.setup import setup + setup(args) + + # conversion source + if args.source_dir is not None: + srcdir = CaseIgnoringDirectory(args.source_dir).root + else: + srcdir = None + + if args.interactive: + interactive_browser(srcdir) + return 0 + + # conversion target + from ..assets import get_asset_path + assets = get_asset_path(args) + + if args.force or conversion_required(assets, args): + if not convert_assets(assets, args, srcdir): + return 1 + else: + print(""assets are up to date; no conversion is required."") + print(""override with --force."")","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +"def init_subparser(cli): + """""" Initializes the parser for convert-specific args. """""" + import argparse + + cli.set_defaults(entrypoint=main) + + cli.add_argument(""--palette"", default=""50500"", help=""palette number"") + cli.add_argument(""--interfac"", type=argparse.FileType('rb'), + help=(""drs archive where palette "" + ""is contained (interfac.drs). "" + ""If not set, assumed to be in same "" + ""directory as the source drs archive"")) + cli.add_argument(""drs"", type=argparse.FileType('rb'), + help=(""drs archive filename that contains the slp "" + ""e.g. path ~/games/aoe/graphics.drs"")) + cli.add_argument(""slp"", help=(""slp filename inside the drs archive "" + ""e.g. 326.slp"")) + cli.add_argument(""output"", help=""image output path name"")","def init_subparser(cli): + """""" Initializes the parser for convert-specific args. """""" + cli.set_defaults(entrypoint=main) + + cli.add_argument(""--palette"", default=""50500"", help=""palette number"") + cli.add_argument(""--interfac"", help=(""drs archive where palette "" + ""is contained (interfac.drs)"")) + cli.add_argument(""drs"", help=(""drs archive filename that contains the slp "" + ""e.g. path ~/games/aoe/graphics.drs"")) + cli.add_argument(""slp"", help=(""slp filename inside the drs archive "" + ""e.g. 326.slp"")) + cli.add_argument(""output"", help=""image output path name"")","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +"def main(args, error): + """""" CLI entry point for single file conversions """""" + del error # unused + + drspath = Path(args.drs.name) + outputpath = Path(args.output) + + if args.interfac: + interfacfile = args.interfac + else: + # if no interfac was given, assume + # the same path of the drs archive. + + interfacfile = drspath.with_name(""interfac.drs"").open(""rb"") # pylint: disable=no-member + + # here, try opening slps from interfac or whereever + info(""opening slp in drs '%s:%s'..."" % (drspath, args.slp)) + slpfile = DRS(args.drs).root[args.slp].open(""rb"") + + # import here to prevent that the __main__ depends on SLP + # just by importing this singlefile.py. + from .slp import SLP + + # parse the slp image + info(""parsing slp image..."") + slpimage = SLP(slpfile.read()) + + # open color palette + info(""opening palette in drs '%s:%s.bina'..."" % (interfacfile.name, args.palette)) + palettefile = DRS(interfacfile).root[""%s.bina"" % args.palette].open(""rb"") + + info(""parsing palette data..."") + palette = ColorTable(palettefile.read()) + + # create texture + info(""packing texture..."") + tex = Texture(slpimage, palette) + + # to save as png: + tex.save(Directory(outputpath.parent).root, outputpath.name)","def main(args, error): + """""" CLI entry point for single file conversions """""" + del error # unused + + if args.interfac: + interfacfile = args.interfac + else: + # if no interfac was given, assume + # the same path of the drs archive. + drspath = os.path.split(args.drs)[0] + interfacfile = os.path.join(drspath, ""interfac.drs"") + + # if .png was passed, strip it away. + if args.output.endswith("".png""): + args.output = args.output[:-4] + + # here, try opening slps from interfac or whereever + info(""opening slp in drs '%s:%s'..."" % (args.drs, args.slp)) + slpfile = DRS(open(args.drs, ""rb"")).root[args.slp].open(""rb"") + + # import here to prevent that the __main__ depends on SLP + # just by importing this singlefile.py. + from .slp import SLP + + # parse the slp image + info(""parsing slp image..."") + slpimage = SLP(slpfile.read()) + + # open color palette + info(""opening palette in drs '%s:%s.bina'..."" % (interfacfile, + args.palette)) + palettefile = DRS(open(interfacfile, ""rb"")).\\ + root[""%s.bina"" % args.palette].open(""rb"") + info(""parsing palette data..."") + palette = ColorTable(palettefile.read()) + + # create texture + info(""packing texture..."") + tex = Texture(slpimage, palette) + + # to save as png: + path, filename = os.path.split(args.output) + tex.save(Directory(path).root, filename)","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +" def save(self, targetdir, filename, meta_formats=None): + """""" + Store the image data into the target directory path, + with given filename=""dir/out.png"" + If metaformats are requested, export e.g. as ""dir/out.docx"". + """""" + if not isinstance(targetdir, Path): + raise ValueError(""util.fslike Path expected as targetdir"") + if not isinstance(filename, str): + raise ValueError(""str expected as filename, not %s"" % type(filename)) + + basename, ext = os.path.splitext(filename) + + # only allow png, although PIL could of course + # do other formats. + if ext != "".png"": + raise ValueError(""Filename invalid, a texture must be saved"" + ""as 'filename.png', not '%s'"" % (filename)) + + # without the dot + ext = ext[1:] + + # generate PNG file + with targetdir[filename].open(""wb"") as imagefile: + self.image_data.get_pil_image().save(imagefile, ext) + + if meta_formats: + # generate formatted texture metadata + formatter = data_formatter.DataFormatter() + formatter.add_data(self.dump(basename)) + formatter.export(targetdir, meta_formats)"," def save(self, targetdir, filename, meta_formats=None): + """""" + Store the image data into the target directory path, + with given filename=""dir/out.png"" + If metaformats are requested, export e.g. as ""dir/out.docx"". + """""" + if not isinstance(targetdir, Path): + raise ValueError(""util.fslike Path expected as targetdir"") + if not isinstance(filename, str): + raise ValueError(""str expected as filename, not %s"" % type(filename)) + + basename, ext = os.path.splitext(filename) + + if ext != "".png"": + raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) + + # without the dot + ext = ext[1:] + + # generate PNG file + with targetdir[filename].open(""wb"") as imagefile: + self.image_data.get_pil_image().save(imagefile, ext) + + if meta_formats: + # generate formatted texture metadata + formatter = data_formatter.DataFormatter() + formatter.add_data(self.dump(basename)) + formatter.export(targetdir, meta_formats)","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +"def get_config_path(custom_cfg_dir=None): + """""" + Locates the main configuration file by name in some searchpaths. + Optionally, mount a custom directory with highest priority. + """""" + + # if we're in devmode, use only the build source config folder + if config.DEVMODE: + return Directory(os.path.join(config.BUILD_SRC_DIR, ""cfg"")).root + + # else, mount the possible locations in an union + # to overlay the global dir and the user dir. + result = Union().root + + # mount the global config dir + # we don't use xdg config_dirs because that would be /etc/xdg/openage + # and nobody would ever look in there. + global_configs = pathlib.Path(config.GLOBAL_CONFIG_DIR) + if global_configs.is_dir(): + result.mount(WriteBlocker(Directory(global_configs).root).root) + + # then the per-user config dir (probably ~/.config/openage) + home_cfg = default_dirs.get_dir(""config_home"") / ""openage"" + result.mount( + Directory( + home_cfg, + create_if_missing=True + ).root + ) + + # the optional command line argument overrides it all + if custom_cfg_dir: + result.mount(Directory(custom_cfg_dir).root) + + return result","def get_config_path(args): + """""" + Locates the main configuration file by name in some searchpaths. + """""" + + # if we're in devmode, use only the build source config folder + if config.DEVMODE: + return Directory(os.path.join(config.BUILD_SRC_DIR, ""cfg"")).root + + # else, mount the possible locations in an union + # to overlay the global dir and the user dir. + result = Union().root + + # mount the global config dir + # we don't use xdg config_dirs because that would be /etc/xdg/openage + # and nobody would ever look in there. + global_configs = pathlib.Path(config.GLOBAL_CONFIG_DIR) + if global_configs.is_dir(): + result.mount(WriteBlocker(Directory(global_configs).root).root) + + # then the per-user config dir (probably ~/.config/openage) + home_cfg = default_dirs.get_dir(""config_home"") / ""openage"" + result.mount( + Directory( + home_cfg, + create_if_missing=True + ).root + ) + + # the optional command line argument overrides it all + if args.cfg_dir: + result.mount(Directory(args.cfg_dir).root) + + return result","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +"def main(args, error): + """""" + Makes sure that the assets have been converted, + and jumps into the C++ main method. + """""" + del error # unused + + # we have to import stuff inside the function + # as it depends on generated/compiled code + from .main_cpp import run_game + from .. import config + from ..assets import get_asset_path + from ..convert.main import conversion_required, convert_assets + from ..cppinterface.setup import setup as cpp_interface_setup + from ..cvar.location import get_config_path + from ..util.fslike.union import Union + + # initialize libopenage + cpp_interface_setup(args) + + info(""launching openage {}"".format(config.VERSION)) + info(""compiled by {}"".format(config.COMPILER)) + + if config.DEVMODE: + info(""running in DEVMODE"") + + # create virtual file system for data paths + root = Union().root + + # mount the assets folder union at ""assets/"" + root[""assets""].mount(get_asset_path(args.asset_dir)) + + # mount the config folder at ""cfg/"" + root[""cfg""].mount(get_config_path(args.cfg_dir)) + + # ensure that the assets have been converted + if conversion_required(root[""assets""], args): + if not convert_assets(root[""assets""], args): + err(""game asset conversion failed"") + return 1 + + # start the game, continue in main_cpp.pyx! + return run_game(args, root)","def main(args, error): + """""" + Makes sure that the assets have been converted, + and jumps into the C++ main method. + """""" + del error # unused + + # we have to import stuff inside the function + # as it depends on generated/compiled code + from .main_cpp import run_game + from .. import config + from ..assets import get_asset_path + from ..convert.main import conversion_required, convert_assets + from ..cppinterface.setup import setup as cpp_interface_setup + from ..cvar.location import get_config_path + from ..util.fslike.union import Union + + # initialize libopenage + cpp_interface_setup(args) + + info(""launching openage {}"".format(config.VERSION)) + info(""compiled by {}"".format(config.COMPILER)) + + if config.DEVMODE: + info(""running in DEVMODE"") + + # create virtual file system for data paths + root = Union().root + + # mount the assets folder union at ""assets/"" + root[""assets""].mount(get_asset_path(args)) + + # mount the config folder at ""cfg/"" + root[""cfg""].mount(get_config_path(args)) + + # ensure that the assets have been converted + if conversion_required(root[""assets""], args): + if not convert_assets(root[""assets""], args): + err(""game asset conversion failed"") + return 1 + + # start the game, continue in main_cpp.pyx! + return run_game(args, root)","[{'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/convert/texture.py"", line 170, in save\\nraise ValueError(""Texture must be saved as name.png. got: %s"" % filename)\\nValueError: Texture must be saved as name.png. got: test'}, {'piece_type': 'error message', 'piece_content': 'dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp test.png\\nINFO opening slp in drs \\'/home/dev/aoe1/data/Border.drs:20000.slp\\'...\\nINFO parsing slp image...\\nINFO opening palette in drs \\'/home/dev/aoe1/data/interfac.drs:50500.bin\\'...\\nINFO parsing palette data...\\nINFO packing texture...\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""/home/dev/openage/openage/__main__.py"", line 128, in \\nexit(main())\\nFile ""/home/dev/openage/openage/__main__.py"", line 121, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main\\ntex.save(Directory(path).root, filename)\\nFile ""/home/dev/openage/openage/util/fslike/directory.py"", line 37, in __init__\\nraise FileNotFoundError(path)\\nFileNotFoundError: b\\'\\''}]","dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png +INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'... +INFO parsing slp image... +INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'... +INFO parsing palette data... +INFO packing texture... +Traceback (most recent call last): +File ""/usr/lib/python3.5/runpy.py"", line 184, in _run_module_as_main +""__main__"", mod_spec) +File ""/usr/lib/python3.5/runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""/home/dev/openage/openage/__main__.py"", line 128, in +exit(main()) +File ""/home/dev/openage/openage/__main__.py"", line 121, in main +return args.entrypoint(args, cli.error) +File ""/home/dev/openage/openage/convert/singlefile.py"", line 72, in main +tex.save(Directory(path).root, filename) +File ""/home/dev/openage/openage/convert/texture.py"", line 170, in save +raise ValueError(""Texture must be saved as name.png. got: %s"" % filename) +ValueError: Texture must be saved as name.png. got: test",ValueError +"def get_string_resources(args): + """""" reads the (language) string resources """""" + from .stringresource import StringResource + stringres = StringResource() + + srcdir = args.srcdir + count = 0 + + # AoK:TC uses .DLL PE files for its string resources, + # HD uses plaintext files + if GameVersion.age2_fe in args.game_versions: + from .hdlanguagefile import read_hd_language_file + + for lang in srcdir[""resources""].list(): + try: + if lang == b'_common': + continue + langfilename = [""resources"", lang.decode(), ""strings"", ""key-value"", + ""key-value-strings-utf8.txt""] + + with srcdir[langfilename].open('rb') as langfile: + stringres.fill_from(read_hd_language_file(langfile, lang)) + + count += 1 + except FileNotFoundError: + # that's fine, there are no language files for every language. + pass + elif GameVersion.age2_hd_3x in args.game_versions: + from .hdlanguagefile import read_hd_language_file + + # HD Edition 3.x and below store language .txt files in the Bin/ folder. + # Specific language strings are in Bin/$LANG/*.txt. + for lang in srcdir[""bin""].list(): + dirname = [""bin"", lang.decode()] + + # There are some .txt files immediately in bin/, but they don't seem + # to contain anything useful. (Everything is overridden by files in + # Bin/$LANG/.) + if not srcdir[dirname].is_dir(): + continue + + for basename in srcdir[dirname].list(): + langfilename = [""bin"", lang.decode(), basename] + with srcdir[langfilename].open('rb') as langfile: + # No utf-8 :( + stringres.fill_from(read_hd_language_file(langfile, lang, enc='iso-8859-1')) + count += 1 + elif srcdir[""language.dll""].is_file(): + from .pefile import PEFile + for name in [""language.dll"", ""language_x1.dll"", ""language_x1_p1.dll""]: + pefile = PEFile(srcdir[name].open('rb')) + stringres.fill_from(pefile.resources().strings) + count += 1 + + if not count: + raise FileNotFoundError(""could not find any language files"") + + # TODO transform and cleanup the read strings: + # convert formatting indicators from HTML to something sensible, etc + + return stringres","def get_string_resources(args): + """""" reads the (language) string resources """""" + from .stringresource import StringResource + stringres = StringResource() + + srcdir = args.srcdir + count = 0 + + # AoK:TC uses .DLL PE files for its string resources, + # HD uses plaintext files + if srcdir[""language.dll""].is_file(): + from .pefile import PEFile + for name in [""language.dll"", ""language_x1.dll"", ""language_x1_p1.dll""]: + pefile = PEFile(srcdir[name].open('rb')) + stringres.fill_from(pefile.resources().strings) + count += 1 + elif GameVersion.age2_fe in args.game_versions: + from .hdlanguagefile import read_hd_language_file + + for lang in srcdir[""resources""].list(): + try: + if lang == b'_common': + continue + langfilename = [""resources"", lang.decode(), ""strings"", ""key-value"", + ""key-value-strings-utf8.txt""] + + with srcdir[langfilename].open('rb') as langfile: + stringres.fill_from(read_hd_language_file(langfile, lang)) + + count += 1 + except FileNotFoundError: + # that's fine, there are no language files for every language. + pass + elif GameVersion.age2_hd_3x in args.game_versions: + from .hdlanguagefile import read_hd_language_file + + # HD Edition 3.x and below store language .txt files in the Bin/ folder. + # Specific language strings are in Bin/$LANG/*.txt. + for lang in srcdir[""bin""].list(): + dirname = [""bin"", lang.decode()] + + # There are some .txt files immediately in bin/, but they don't seem + # to contain anything useful. (Everything is overridden by files in + # Bin/$LANG/.) + if not srcdir[dirname].is_dir(): + continue + + for basename in srcdir[dirname].list(): + langfilename = [""bin"", lang.decode(), basename] + with srcdir[langfilename].open('rb') as langfile: + # No utf-8 :( + stringres.fill_from(read_hd_language_file(langfile, lang, enc='iso-8859-1')) + count += 1 + + if not count: + raise FileNotFoundError(""could not find any language files"") + + # TODO transform and cleanup the read strings: + # convert formatting indicators from HTML to something sensible, etc + + return stringres","[{'piece_type': 'error message', 'piece_content': '$ make run\\n./run game\\nINFO [py] No converted assets have been found\\nmedia conversion is required.\\nplease provide your AoE II installation dir:\\n/media/niklas/E4DE307EDE304AD6/Program Files (x86)/Steam/SteamApps/common/Age2HD\\nINFO [py] Game version(s) detected: Age of Empires 2: HD Edition (Version 3.x); Forgotten Empires; Age of Empires 2: The Conquerors, Patch 1.0c\\nINFO [py] converting metadata\\nINFO [py] [0] palette\\nINFO [py] [1] empires.dat\\nINFO [py] [2] blendomatic.dat\\nINFO [py] blending masks successfully exported\\nINFO [py] [3] player color palette\\nINFO [py] [4] terminal color palette\\nINFO [py] [5] string resources\\nTraceback (most recent call last):\\nFile ""run.py"", line 15, in init run (/home/niklas/Projekte/openage/run.cpp:832)\\nmain()\\nFile ""/home/niklas/Projekte/openage/openage/__main__.py"", line 94, in main\\nreturn args.entrypoint(args, cli.error)\\nFile ""/home/niklas/Projekte/openage/openage/game/main.py"", line 33, in main\\nif not convert_assets(assets, args):\\nFile ""/home/niklas/Projekte/openage/openage/convert/main.py"", line 125, in convert_assets\\nfor current_item in convert(args):\\nFile ""/home/niklas/Projekte/openage/openage/convert/driver.py"", line 126, in convert\\nyield from convert_metadata(args)\\nFile ""/home/niklas/Projekte/openage/openage/convert/driver.py"", line 179, in convert_metadata\\nstringres = get_string_resources(args)\\nFile ""/home/niklas/Projekte/openage/openage/convert/driver.py"", line 37, in get_string_resources\\npefile = PEFile(srcdir[name].open(\\'rb\\'))\\nFile ""/home/niklas/Projekte/openage/openage/convert/pefile.py"", line 191, in __init__\\nraise Exception(""Invalid section name: "" + section.name)\\nException: Invalid section name: CODE\\nMakefile:22: recipe for target \\'run\\' failed\\nmake: *** [run] Error 1'}]","$ make run +./run game +INFO [py] No converted assets have been found +media conversion is required. +please provide your AoE II installation dir: +/media/niklas/E4DE307EDE304AD6/Program Files (x86)/Steam/SteamApps/common/Age2HD +INFO [py] Game version(s) detected: Age of Empires 2: HD Edition (Version 3.x); Forgotten Empires; Age of Empires 2: The Conquerors, Patch 1.0c +INFO [py] converting metadata +INFO [py] [0] palette +INFO [py] [1] empires.dat +INFO [py] [2] blendomatic.dat +INFO [py] blending masks successfully exported +INFO [py] [3] player color palette +INFO [py] [4] terminal color palette +INFO [py] [5] string resources +Traceback (most recent call last): +File ""run.py"", line 15, in init run (/home/niklas/Projekte/openage/run.cpp:832) +main() +File ""/home/niklas/Projekte/openage/openage/__main__.py"", line 94, in main +return args.entrypoint(args, cli.error) +File ""/home/niklas/Projekte/openage/openage/game/main.py"", line 33, in main +if not convert_assets(assets, args): +File ""/home/niklas/Projekte/openage/openage/convert/main.py"", line 125, in convert_assets +for current_item in convert(args): +File ""/home/niklas/Projekte/openage/openage/convert/driver.py"", line 126, in convert +yield from convert_metadata(args) +File ""/home/niklas/Projekte/openage/openage/convert/driver.py"", line 179, in convert_metadata +stringres = get_string_resources(args) +File ""/home/niklas/Projekte/openage/openage/convert/driver.py"", line 37, in get_string_resources +pefile = PEFile(srcdir[name].open('rb')) +File ""/home/niklas/Projekte/openage/openage/convert/pefile.py"", line 191, in __init__ +raise Exception(""Invalid section name: "" + section.name) +Exception: Invalid section name: CODE +Makefile:22: recipe for target 'run' failed +make: *** [run] Error 1",Exception +"def get_domain_mx_list(domain): + """"""Return a list of MX IP address for domain."""""" + result = [] + logger = logging.getLogger(""modoboa.admin"") + dns_server = param_tools.get_global_parameter(""custom_dns_server"") + if dns_server: + resolver = dns.resolver.Resolver() + resolver.nameservers = [dns_server] + else: + resolver = dns.resolver + + try: + dns_answers = resolver.query(domain, ""MX"") + except dns.resolver.NXDOMAIN as e: + logger.error(_(""No DNS records found for %s"") % domain, exc_info=e) + except dns.resolver.NoAnswer as e: + logger.error(_(""No MX record for %s"") % domain, exc_info=e) + except dns.resolver.NoNameservers as e: + logger.error(_(""No working name servers found""), exc_info=e) + except dns.resolver.Timeout as e: + logger.warning( + _(""DNS resolution timeout, unable to query %s at the moment"") % + domain, exc_info=e) + else: + for dns_answer in dns_answers: + for rtype in [""A"", ""AAAA""]: + try: + mx_domain = dns_answer.exchange.to_unicode( + omit_final_dot=True, idna_codec=IDNA_2008_UTS_46) + ip_answers = resolver.query(mx_domain, rtype) + except dns.resolver.NXDOMAIN as e: + logger.error( + _(""No {type} record found for MX {mx}"").format( + type=rtype, mx=domain), exc_info=e) + except dns.resolver.NoAnswer: + pass + else: + for ip_answer in ip_answers: + try: + address_smart = smart_text(ip_answer.address) + mx_ip = ipaddress.ip_address(address_smart) + except ValueError as e: + logger.warning( + _(""Invalid IP address format for "" + ""{domain}; {addr}"").format( + domain=mx_domain, + addr=smart_text(ip_answer.address) + ), exc_info=e) + else: + result.append((mx_domain, mx_ip)) + return result","def get_domain_mx_list(domain): + """"""Return a list of MX IP address for domain."""""" + result = [] + logger = logging.getLogger(""modoboa.admin"") + dns_server = param_tools.get_global_parameter(""custom_dns_server"") + if dns_server: + resolver = dns.resolver.Resolver() + resolver.nameservers = [dns_server] + else: + resolver = dns.resolver + + try: + dns_answers = resolver.query(domain, ""MX"") + except dns.resolver.NXDOMAIN as e: + logger.error(_(""No DNS records found for %s"") % domain, exc_info=e) + except dns.resolver.NoAnswer as e: + logger.error(_(""No MX record for %s"") % domain, exc_info=e) + except dns.resolver.NoNameservers as e: + logger.error(_(""No working name servers found""), exc_info=e) + except dns.resolver.Timeout as e: + logger.warning( + _(""DNS resolution timeout, unable to query %s at the moment"") % + domain, exc_info=e) + else: + for dns_answer in dns_answers: + for rtype in [""A"", ""AAAA""]: + try: + mx_domain = dns_answer.exchange.to_unicode( + omit_final_dot=True, idna_codec=IDNA_2008_UTS_46) + ip_answers = resolver.query(mx_domain, rtype) + except dns.resolver.NXDOMAIN as e: + logger.error( + _(""No {type} record found for MX {mx}"").format( + type=rtype, mx=domain), exc_info=e) + else: + for ip_answer in ip_answers: + try: + address_smart = smart_text(ip_answer.address) + mx_ip = ipaddress.ip_address(address_smart) + except ValueError as e: + logger.warning( + _(""Invalid IP address format for "" + ""{domain}; {addr}"").format( + domain=mx_domain, + addr=smart_text(ip_answer.address) + ), exc_info=e) + else: + result.append((mx_domain, mx_ip)) + return result","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py"", line 215, in __init__\\nrdclass, rdtype)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/message.py"", line 352, in find_rrset\\nraise KeyError\\nKeyError\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py"", line 225, in __init__\\ndns.rdatatype.CNAME)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/message.py"", line 352, in find_rrset\\nraise KeyError\\nKeyError\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/instance/manage.py"", line 10, in \\nexecute_from_command_line(sys.argv)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/__init__.py"", line 364, in execute_from_command_line\\nutility.execute()\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/__init__.py"", line 356, in execute\\nself.fetch_command(subcommand).run_from_argv(self.argv)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/subcommand/base.py"", line 53, in run_from_argv\\nreturn super(SubcommandCommand, self).run_from_argv(argv)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py"", line 283, in run_from_argv\\nself.execute(*args, **cmd_options)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py"", line 330, in execute\\noutput = self.handle(*args, **options)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/subcommand/base.py"", line 84, in handle\\nreturn command.run_from_argv(argv)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py"", line 283, in run_from_argv\\nself.execute(*args, **cmd_options)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py"", line 330, in execute\\noutput = self.handle(*args, **options)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 244, in handle\\nself.check_domain(domain, **options)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 191, in check_domain\\nmodels.MXRecord.objects.get_or_create_for_domain(domain, ttl))\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/models/mxrecord.py"", line 47, in get_or_create_for_domain\\ndomain_mxs = lib.get_domain_mx_list(domain.name)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/lib.py"", line 202, in get_domain_mx_list\\nip_answers = resolver.query(mx_domain, rtype)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py"", line 1132, in query\\nraise_on_no_answer, source_port)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py"", line 1053, in query\\nraise_on_no_answer)\\nFile ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py"", line 234, in __init__\\nraise NoAnswer(response=response)\\ndns.resolver.NoAnswer: The DNS response does not contain an answer to the question: mail.toto.com. IN AAAA'}]","Traceback (most recent call last): +File ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py"", line 215, in __init__ +rdclass, rdtype) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/message.py"", line 352, in find_rrset +raise KeyError +KeyError + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py"", line 225, in __init__ +dns.rdatatype.CNAME) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/message.py"", line 352, in find_rrset +raise KeyError +KeyError + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/srv/modoboa/instance/manage.py"", line 10, in +execute_from_command_line(sys.argv) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/__init__.py"", line 364, in execute_from_command_line +utility.execute() +File ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/__init__.py"", line 356, in execute +self.fetch_command(subcommand).run_from_argv(self.argv) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/subcommand/base.py"", line 53, in run_from_argv +return super(SubcommandCommand, self).run_from_argv(argv) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py"", line 283, in run_from_argv +self.execute(*args, **cmd_options) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py"", line 330, in execute +output = self.handle(*args, **options) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/subcommand/base.py"", line 84, in handle +return command.run_from_argv(argv) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py"", line 283, in run_from_argv +self.execute(*args, **cmd_options) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/django/core/management/base.py"", line 330, in execute +output = self.handle(*args, **options) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 244, in handle +self.check_domain(domain, **options) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 191, in check_domain +models.MXRecord.objects.get_or_create_for_domain(domain, ttl)) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/models/mxrecord.py"", line 47, in get_or_create_for_domain +domain_mxs = lib.get_domain_mx_list(domain.name) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/modoboa/admin/lib.py"", line 202, in get_domain_mx_list +ip_answers = resolver.query(mx_domain, rtype) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py"", line 1132, in query +raise_on_no_answer, source_port) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py"", line 1053, in query +raise_on_no_answer) +File ""/srv/modoboa/env3/lib/python3.5/site-packages/dns/resolver.py"", line 234, in __init__ +raise NoAnswer(response=response) +dns.resolver.NoAnswer: The DNS response does not contain an answer to the question: mail.toto.com. IN AAAA",KeyError +" def authenticate(self, request, username=None, password=None): + """"""Check the username/password and return a User."""""" + host = getattr(settings, ""AUTH_SMTP_SERVER_ADDRESS"", ""localhost"") + port = getattr(settings, ""AUTH_SMTP_SERVER_PORT"", 25) + secured_mode = getattr(settings, ""AUTH_SMTP_SECURED_MODE"", None) + if secured_mode == ""ssl"": + smtp = smtplib.SMTP_SSL(host, port) + else: + smtp = smtplib.SMTP(host, port) + if secured_mode == ""starttls"": + smtp.starttls() + try: + smtp.login(username, password) + except smtplib.SMTPException: + return None + return self.get_or_build_user(username)"," def authenticate(self, username=None, password=None): + """"""Check the username/password and return a User."""""" + host = getattr(settings, ""AUTH_SMTP_SERVER_ADDRESS"", ""localhost"") + port = getattr(settings, ""AUTH_SMTP_SERVER_PORT"", 25) + secured_mode = getattr(settings, ""AUTH_SMTP_SECURED_MODE"", None) + if secured_mode == ""ssl"": + smtp = smtplib.SMTP_SSL(host, port) + else: + smtp = smtplib.SMTP(host, port) + if secured_mode == ""starttls"": + smtp.starttls() + try: + smtp.login(username, password) + except smtplib.SMTPException: + return None + return self.get_or_build_user(username)","[{'piece_type': 'error message', 'piece_content': 'Internal Server Error: /accounts/login/\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/exception.py"", line 41, in inner\\nresponse = get_response(request)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py"", line 187, in _get_response\\nresponse = self.process_exception_by_middleware(e, request)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py"", line 185, in _get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py"", line 185, in inner\\nreturn func(*args, **kwargs)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py"", line 185, in inner\\nreturn func(*args, **kwargs)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/views/decorators/cache.py"", line 57, in _wrapped_view_func\\nresponse = view_func(request, *args, **kwargs)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/core/views/auth.py"", line 34, in dologin\\npassword=form.cleaned_data[""password""])\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py"", line 70, in authenticate\\nuser = _authenticate_with_backend(backend, backend_path, request, credentials)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py"", line 116, in _authenticate_with_backend\\nreturn backend.authenticate(*args, **credentials)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/lib/authbackends.py"", line 119, in authenticate\\nusername=username, password=password)\\nTypeError: authenticate() takes at least 2 arguments (3 given)'}]","Internal Server Error: /accounts/login/ +Traceback (most recent call last): +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/exception.py"", line 41, in inner +response = get_response(request) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py"", line 187, in _get_response +response = self.process_exception_by_middleware(e, request) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py"", line 185, in _get_response +response = wrapped_callback(request, *callback_args, **callback_kwargs) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py"", line 185, in inner +return func(*args, **kwargs) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py"", line 185, in inner +return func(*args, **kwargs) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/views/decorators/cache.py"", line 57, in _wrapped_view_func +response = view_func(request, *args, **kwargs) +File ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/core/views/auth.py"", line 34, in dologin +password=form.cleaned_data[""password""]) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py"", line 70, in authenticate +user = _authenticate_with_backend(backend, backend_path, request, credentials) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py"", line 116, in _authenticate_with_backend +return backend.authenticate(*args, **credentials) +File ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/lib/authbackends.py"", line 119, in authenticate +username=username, password=password) +TypeError: authenticate() takes at least 2 arguments (3 given)",TypeError +" def authenticate(self, *args, **kwargs): + if self.global_params[""authentication_type""] == ""ldap"": + return super(LDAPBackend, self).authenticate(*args, **kwargs) + return None"," def authenticate(self, username, password): + if self.global_params[""authentication_type""] == ""ldap"": + return super(LDAPBackend, self).authenticate( + username=username, password=password) + return None","[{'piece_type': 'error message', 'piece_content': 'Internal Server Error: /accounts/login/\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/exception.py"", line 41, in inner\\nresponse = get_response(request)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py"", line 187, in _get_response\\nresponse = self.process_exception_by_middleware(e, request)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py"", line 185, in _get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py"", line 185, in inner\\nreturn func(*args, **kwargs)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py"", line 185, in inner\\nreturn func(*args, **kwargs)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/views/decorators/cache.py"", line 57, in _wrapped_view_func\\nresponse = view_func(request, *args, **kwargs)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/core/views/auth.py"", line 34, in dologin\\npassword=form.cleaned_data[""password""])\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py"", line 70, in authenticate\\nuser = _authenticate_with_backend(backend, backend_path, request, credentials)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py"", line 116, in _authenticate_with_backend\\nreturn backend.authenticate(*args, **credentials)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/lib/authbackends.py"", line 119, in authenticate\\nusername=username, password=password)\\nTypeError: authenticate() takes at least 2 arguments (3 given)'}]","Internal Server Error: /accounts/login/ +Traceback (most recent call last): +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/exception.py"", line 41, in inner +response = get_response(request) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py"", line 187, in _get_response +response = self.process_exception_by_middleware(e, request) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py"", line 185, in _get_response +response = wrapped_callback(request, *callback_args, **callback_kwargs) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py"", line 185, in inner +return func(*args, **kwargs) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py"", line 185, in inner +return func(*args, **kwargs) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/views/decorators/cache.py"", line 57, in _wrapped_view_func +response = view_func(request, *args, **kwargs) +File ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/core/views/auth.py"", line 34, in dologin +password=form.cleaned_data[""password""]) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py"", line 70, in authenticate +user = _authenticate_with_backend(backend, backend_path, request, credentials) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py"", line 116, in _authenticate_with_backend +return backend.authenticate(*args, **credentials) +File ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/lib/authbackends.py"", line 119, in authenticate +username=username, password=password) +TypeError: authenticate() takes at least 2 arguments (3 given)",TypeError +" def handle(self, *args, **options): + exts_pool.load_all() + self.csvwriter = csv.writer( + self.stdout, delimiter=smart_text(options[""sepchar""])) + getattr(self, ""export_{}"".format(options[""objtype""]))()"," def handle(self, *args, **options): + exts_pool.load_all() + self.csvwriter = csv.writer(sys.stdout, delimiter=options[""sepchar""]) + getattr(self, ""export_{}"".format(options[""objtype""]))()","[{'piece_type': 'other', 'piece_content': 'sudo -u -i\\nsource /bin/activate\\npython /instance/manage.py modo export --sepchar , domains\\n# or the equivalent (gives same result)\\npython /instance/manage.py modo export domains'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""manage.py"", line 22, in \\nexecute_from_command_line(sys.argv)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/__init__.py"", line 364, in execute_from_command_line\\nutility.execute()\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/__init__.py"", line 356, in execute\\nself.fetch_command(subcommand).run_from_argv(self.argv)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/subcommand/base.py"", line 53, in run_from_argv\\nreturn super(SubcommandCommand, self).run_from_argv(argv)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py"", line 283, in run_from_argv\\nself.execute(*args, **cmd_options)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py"", line 330, in execute\\noutput = self.handle(*args, **options)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/subcommand/base.py"", line 84, in handle\\nreturn command.run_from_argv(argv)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py"", line 283, in run_from_argv\\nself.execute(*args, **cmd_options)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py"", line 330, in execute\\noutput = self.handle(*args, **options)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_export.py"", line 64, in handle\\nself.csvwriter = csv.writer(sys.stdout, delimiter=options[""sepchar""])\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/backports/csv.py"", line 185, in __init__\\nraise TypeError(*e.args)\\nTypeError: ""delimiter"" must be string, not bytes'}, {'piece_type': 'other', 'piece_content': '$ source /bin/activate\\n(env) $ pip freeze\\nasn1crypto==0.24.0\\nbackports.csv==1.0.5\\nbcrypt==3.1.4\\ncaldav==0.5.0\\ncertifi==2018.4.16\\ncffi==1.11.5\\nchardet==3.0.4\\nclick==6.7\\ncoreapi==2.3.3\\ncoreapi-cli==1.0.6\\ncoreschema==0.0.4\\ncoverage==4.5.1\\ncryptography==2.2.2\\ndj-database-url==0.5.0\\nDjango==1.11.12\\ndjango-braces==1.11.0\\ndjango-ckeditor==5.2.2\\ndjango-filter==1.0.4\\ndjango-reversion==2.0.12\\ndjango-subcommand2==0.1.1\\ndjango-webpack-loader==0.6.0\\ndjango-xforwardedfor-middleware==2.0\\ndjangorestframework==3.7.3\\ndnspython==1.15.0\\ndrf-nested-routers==0.90.2\\nenum34==1.1.6\\nfeedparser==5.2.1\\nfuture==0.16.0\\ngevent==1.2.2\\ngreenlet==0.4.13\\nhtml2text==2018.1.9\\nicalendar==4.0.1\\nidna==2.6\\nipaddress==1.0.22\\nitypes==1.1.0\\nJinja2==2.10\\njsonfield==2.0.2\\nLEPL==5.1.3\\nlxml==4.2.1\\nMarkupSafe==1.0\\nmodoboa==1.10.5.dev8+gf604aacb\\nmodoboa-admin==1.1.2\\nmodoboa-admin-limits==1.0.2\\nmodoboa-admin-relaydomains==1.1.0\\nmodoboa-amavis==1.2.2\\nmodoboa-contacts==0.5.0\\nmodoboa-imap-migration==1.2.0\\nmodoboa-pdfcredentials==1.3.1\\nmodoboa-postfix-autoreply==1.4.1\\nmodoboa-radicale==1.3.2\\nmodoboa-sievefilters==1.4.1\\nmodoboa-stats==1.4.0\\nmodoboa-webmail==1.4.2\\nnose==1.3.7\\npasslib==1.7.1\\nPillow==5.1.0\\npkg-resources==0.0.0\\nprogressbar33==2.4\\npsycopg2-binary==2.7.4\\npy-dateutil==2.2\\npycparser==2.18\\npython-dateutil==2.7.2\\npytz==2018.4\\nreportlab==3.4.0\\nrequests==2.18.4\\nrfc6266==0.0.4\\nrrdtool==0.1.14\\nsievelib==1.1.1\\nsix==1.11.0\\nuritemplate==3.0.0\\nurllib3==1.22'}]","Traceback (most recent call last): +File ""manage.py"", line 22, in +execute_from_command_line(sys.argv) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/__init__.py"", line 364, in execute_from_command_line +utility.execute() +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/__init__.py"", line 356, in execute +self.fetch_command(subcommand).run_from_argv(self.argv) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/subcommand/base.py"", line 53, in run_from_argv +return super(SubcommandCommand, self).run_from_argv(argv) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py"", line 283, in run_from_argv +self.execute(*args, **cmd_options) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py"", line 330, in execute +output = self.handle(*args, **options) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/subcommand/base.py"", line 84, in handle +return command.run_from_argv(argv) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py"", line 283, in run_from_argv +self.execute(*args, **cmd_options) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py"", line 330, in execute +output = self.handle(*args, **options) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_export.py"", line 64, in handle +self.csvwriter = csv.writer(sys.stdout, delimiter=options[""sepchar""]) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/backports/csv.py"", line 185, in __init__ +raise TypeError(*e.args) +TypeError: ""delimiter"" must be string, not bytes",TypeError +" def ready(self): + load_core_settings() + + # Import these to force registration of checks and signals + from . import checks # noqa:F401 + from . import handlers + + signals.post_migrate.connect(handlers.create_local_config, sender=self)"," def ready(self): + load_core_settings() + + from . import handlers + + signals.post_migrate.connect(handlers.create_local_config, sender=self)","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/srv/modoboa/instance/manage.py"", line 10, in \\nexecute_from_command_line(sys.argv)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/__init__.py"", line 353, in execute_from_command_line\\nutility.execute()\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/__init__.py"", line 345, in execute\\nself.fetch_command(subcommand).run_from_argv(self.argv)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/django_subcommand2-0.1.1-py2.7.egg/subcommand/base.py"", line 53, in run_from_argv\\nreturn super(SubcommandCommand, self).run_from_argv(argv)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py"", line 348, in run_from_argv\\nself.execute(*args, **cmd_options)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py"", line 399, in execute\\noutput = self.handle(*args, **options)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/django_subcommand2-0.1.1-py2.7.egg/subcommand/base.py"", line 84, in handle\\nreturn command.run_from_argv(argv)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py"", line 348, in run_from_argv\\nself.execute(*args, **cmd_options)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py"", line 399, in execute\\noutput = self.handle(*args, **options)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 262, in handle\\nself.check_domain(domain, **options)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 218, in check_domain\\nmx_list = list(self.get_mx_records_for_domain(domain, ttl=ttl))\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 109, in get_mx_records_for_domain\\nupdated=now + delta)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/manager.py"", line 122, in manager_method\\nreturn getattr(self.get_queryset(), name)(*args, **kwargs)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/query.py"", line 401, in create\\nobj.save(force_insert=True, using=self.db)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py"", line 708, in save\\nforce_update=force_update, update_fields=update_fields)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py"", line 736, in save_base\\nupdated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py"", line 820, in _save_table\\nresult = self._do_insert(cls._base_manager, using, fields, update_pk, raw)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py"", line 859, in _do_insert\\nusing=using, raw=raw)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/manager.py"", line 122, in manager_method\\nreturn getattr(self.get_queryset(), name)(*args, **kwargs)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/query.py"", line 1039, in _insert\\nreturn query.get_compiler(using=using).execute_sql(return_id)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/sql/compiler.py"", line 1059, in execute_sql\\nfor sql, params in self.as_sql():\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/sql/compiler.py"", line 1019, in as_sql\\nfor obj in self.query.objs\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/sql/compiler.py"", line 958, in prepare_value\\nvalue = field.get_db_prep_save(value, connection=self.connection)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/fields/__init__.py"", line 728, in get_db_prep_save\\nprepared=False)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/fields/__init__.py"", line 1461, in get_db_prep_value\\nvalue = self.get_prep_value(value)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/fields/__init__.py"", line 1455, in get_prep_value\\nvalue = timezone.make_aware(value, default_timezone)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/utils/timezone.py"", line 364, in make_aware\\nreturn timezone.localize(value, is_dst=is_dst)\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/pytz/tzinfo.py"", line 327, in localize\\nraise NonExistentTimeError(dt)\\npytz.exceptions.NonExistentTimeError: 2017-03-26 02:30:01.875287'}]","Traceback (most recent call last): +File ""/srv/modoboa/instance/manage.py"", line 10, in +execute_from_command_line(sys.argv) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/__init__.py"", line 353, in execute_from_command_line +utility.execute() +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/__init__.py"", line 345, in execute +self.fetch_command(subcommand).run_from_argv(self.argv) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/django_subcommand2-0.1.1-py2.7.egg/subcommand/base.py"", line 53, in run_from_argv +return super(SubcommandCommand, self).run_from_argv(argv) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py"", line 348, in run_from_argv +self.execute(*args, **cmd_options) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py"", line 399, in execute +output = self.handle(*args, **options) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/django_subcommand2-0.1.1-py2.7.egg/subcommand/base.py"", line 84, in handle +return command.run_from_argv(argv) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py"", line 348, in run_from_argv +self.execute(*args, **cmd_options) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/core/management/base.py"", line 399, in execute +output = self.handle(*args, **options) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 262, in handle +self.check_domain(domain, **options) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 218, in check_domain +mx_list = list(self.get_mx_records_for_domain(domain, ttl=ttl)) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 109, in get_mx_records_for_domain +updated=now + delta) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/manager.py"", line 122, in manager_method +return getattr(self.get_queryset(), name)(*args, **kwargs) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/query.py"", line 401, in create +obj.save(force_insert=True, using=self.db) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py"", line 708, in save +force_update=force_update, update_fields=update_fields) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py"", line 736, in save_base +updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py"", line 820, in _save_table +result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/base.py"", line 859, in _do_insert +using=using, raw=raw) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/manager.py"", line 122, in manager_method +return getattr(self.get_queryset(), name)(*args, **kwargs) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/query.py"", line 1039, in _insert +return query.get_compiler(using=using).execute_sql(return_id) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/sql/compiler.py"", line 1059, in execute_sql +for sql, params in self.as_sql(): +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/sql/compiler.py"", line 1019, in as_sql +for obj in self.query.objs +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/sql/compiler.py"", line 958, in prepare_value +value = field.get_db_prep_save(value, connection=self.connection) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/fields/__init__.py"", line 728, in get_db_prep_save +prepared=False) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/fields/__init__.py"", line 1461, in get_db_prep_value +value = self.get_prep_value(value) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/db/models/fields/__init__.py"", line 1455, in get_prep_value +value = timezone.make_aware(value, default_timezone) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.9.12-py2.7.egg/django/utils/timezone.py"", line 364, in make_aware +return timezone.localize(value, is_dst=is_dst) +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/pytz/tzinfo.py"", line 327, in localize +raise NonExistentTimeError(dt) +pytz.exceptions.NonExistentTimeError: 2017-03-26 02:30:01.875287",pytz.exceptions.NonExistentTimeError +" def store_dnsbl_result(self, domain, provider, results, **options): + """"""Store DNSBL provider results for domain."""""" + alerts = {} + to_create = [] + for mx, result in list(results.items()): + if not result: + result = """" + dnsbl_result = models.DNSBLResult.objects.filter( + domain=domain, provider=provider, mx=mx).first() + trigger = False + if dnsbl_result is None: + to_create.append( + models.DNSBLResult( + domain=domain, provider=provider, mx=mx, + status=result) + ) + if result: + trigger = True + else: + dnsbl_result.status = result + dnsbl_result.save() + if not dnsbl_result.status and result: + trigger = True + if trigger: + if domain not in alerts: + alerts[domain] = [] + alerts[domain].append((provider, mx)) + models.DNSBLResult.objects.bulk_create(to_create) + if not alerts: + return + emails = list(options[""email""]) + if not options[""skip_admin_emails""]: + emails.extend( + domain.admins.exclude(mailbox__isnull=True) + .values_list(""email"", flat=True) + ) + if not len(emails): + return + with mail.get_connection() as connection: + for domain, providers in list(alerts.items()): + content = render_to_string( + ""admin/notifications/domain_in_dnsbl.html"", { + ""domain"": domain, ""alerts"": providers + }) + subject = _(""[modoboa] DNSBL issue(s) for domain {}"").format( + domain.name) + msg = EmailMessage( + subject, content.strip(), self.sender, emails, + connection=connection + ) + msg.send()"," def store_dnsbl_result(self, domain, provider, results, **options): + """"""Store DNSBL provider results for domain."""""" + alerts = {} + to_create = [] + for mx in results.keys(): + result = """" if not results[mx] else results[mx] + dnsbl_result = models.DNSBLResult.objects.filter( + domain=domain, provider=provider, mx=mx).first() + trigger = False + if dnsbl_result is None: + to_create.append( + models.DNSBLResult( + domain=domain, provider=provider, mx=mx, + status=result) + ) + if result: + trigger = True + else: + dnsbl_result.status = result + dnsbl_result.save() + if not dnsbl_result.status and result: + trigger = True + if trigger: + if domain not in alerts: + alerts[domain] = [] + alerts[domain].append((provider, mx)) + models.DNSBLResult.objects.bulk_create(to_create) + if not alerts: + return + emails = list(options[""email""]) + if not options[""skip_admin_emails""]: + emails.extend( + domain.admins.exclude(mailbox__isnull=True) + .values_list(""email"", flat=True) + ) + if not len(emails): + return + with mail.get_connection() as connection: + for domain, providers in list(alerts.items()): + content = render_to_string( + ""admin/notifications/domain_in_dnsbl.html"", { + ""domain"": domain, ""alerts"": providers + }) + subject = _(""[modoboa] DNSBL issue(s) for domain {}"").format( + domain.name) + msg = EmailMessage( + subject, content.strip(), self.sender, emails, + connection=connection + ) + msg.send()","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/srv/modoboa/instance/manage.py"", line 22, in \\nexecute_from_command_line(sys.argv)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 367, in execute_from_command_line\\nutility.execute()\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 359, in execute\\nself.fetch_command(subcommand).run_from_argv(self.argv)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/subcommand/base.py"", line 53, in run_from_argv\\nreturn super(SubcommandCommand, self).run_from_argv(argv)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py"", line 294, in run_from_argv\\nself.execute(*args, **cmd_options)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py"", line 345, in execute\\noutput = self.handle(*args, **options)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/subcommand/base.py"", line 84, in handle\\nreturn command.run_from_argv(argv)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py"", line 294, in run_from_argv\\nself.execute(*args, **cmd_options)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py"", line 345, in execute\\noutput = self.handle(*args, **options)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 225, in handle\\nself.check_domain(domain, **options)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 198, in check_domain\\nself.store_dnsbl_result(domain, provider, results, **options)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 107, in store_dnsbl_result\\nmodels.DNSBLResult.objects.bulk_create(to_create)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/manager.py"", line 85, in manager_method\\nreturn getattr(self.get_queryset(), name)(*args, **kwargs)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py"", line 452, in bulk_create\\nids = self._batched_insert(objs_without_pk, fields, batch_size)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py"", line 1062, in _batched_insert\\ninserted_id = self._insert(item, fields=fields, using=self.db, return_id=True)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py"", line 1045, in _insert\\nreturn query.get_compiler(using=using).execute_sql(return_id)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1054, in execute_sql\\ncursor.execute(sql, params)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/backends/utils.py"", line 64, in execute\\nreturn self.cursor.execute(sql, params)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/utils.py"", line 94, in __exit__\\nsix.reraise(dj_exc_type, dj_exc_value, traceback)\\nFile ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/backends/utils.py"", line 64, in execute\\nreturn self.cursor.execute(sql, params)\\ndjango.db.utils.IntegrityError: duplicate key value violates unique constraint ""admin_dnsblresult_domain_id_9710ce0d_uniq""\\nDETAIL: Key (domain_id, provider, mx_id)=(1, aspews.ext.sorbs.net, 55) already exists.```'}]","Traceback (most recent call last): +File ""/srv/modoboa/instance/manage.py"", line 22, in +execute_from_command_line(sys.argv) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 367, in execute_from_command_line +utility.execute() +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/__init__.py"", line 359, in execute +self.fetch_command(subcommand).run_from_argv(self.argv) +File ""/srv/modoboa/env/lib/python2.7/site-packages/subcommand/base.py"", line 53, in run_from_argv +return super(SubcommandCommand, self).run_from_argv(argv) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py"", line 294, in run_from_argv +self.execute(*args, **cmd_options) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py"", line 345, in execute +output = self.handle(*args, **options) +File ""/srv/modoboa/env/lib/python2.7/site-packages/subcommand/base.py"", line 84, in handle +return command.run_from_argv(argv) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py"", line 294, in run_from_argv +self.execute(*args, **cmd_options) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py"", line 345, in execute +output = self.handle(*args, **options) +File ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 225, in handle +self.check_domain(domain, **options) +File ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 198, in check_domain +self.store_dnsbl_result(domain, provider, results, **options) +File ""/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py"", line 107, in store_dnsbl_result +models.DNSBLResult.objects.bulk_create(to_create) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/manager.py"", line 85, in manager_method +return getattr(self.get_queryset(), name)(*args, **kwargs) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py"", line 452, in bulk_create +ids = self._batched_insert(objs_without_pk, fields, batch_size) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py"", line 1062, in _batched_insert +inserted_id = self._insert(item, fields=fields, using=self.db, return_id=True) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py"", line 1045, in _insert +return query.get_compiler(using=using).execute_sql(return_id) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1054, in execute_sql +cursor.execute(sql, params) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/backends/utils.py"", line 64, in execute +return self.cursor.execute(sql, params) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/utils.py"", line 94, in __exit__ +six.reraise(dj_exc_type, dj_exc_value, traceback) +File ""/srv/modoboa/env/lib/python2.7/site-packages/django/db/backends/utils.py"", line 64, in execute +return self.cursor.execute(sql, params) +django.db.utils.IntegrityError: duplicate key value violates unique constraint ""admin_dnsblresult_domain_id_9710ce0d_uniq"" +DETAIL: Key (domain_id, provider, mx_id)=(1, aspews.ext.sorbs.net, 55) already exists.```",django.db.utils.IntegrityError +"def on_mailbox_modified(mailbox): + """"""Update amavis records if address has changed."""""" + if parameters.get_admin(""MANUAL_LEARNING"") == ""no"" or \\ + not hasattr(mailbox, ""old_full_address"") or \\ + mailbox.full_address == mailbox.old_full_address: + return + user = Users.objects.select_related().get(email=mailbox.old_full_address) + full_address = mailbox.full_address + user.email = full_address + user.policy.policy_name = full_address[:32] + user.policy.sa_username = full_address + user.policy.save() + user.save()","def on_mailbox_modified(mailbox): + """"""Update amavis records if address has changed."""""" + if parameters.get_admin(""MANUAL_LEARNING"") == ""no"" or \\ + not hasattr(mailbox, ""old_full_address"") or \\ + mailbox.full_address == mailbox.old_full_address: + return + user = Users.objects.select_related.get(email=mailbox.old_full_address) + full_address = mailbox.full_address + user.email = full_address + user.policy.policy_name = full_address[:32] + user.policy.sa_username = full_address + user.policy.save() + user.save()","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/django/core/handlers/base.py"", line 112, in get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 22, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 22, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/reversion/revisions.py"", line 297, in do_revision_context\\nreturn func(*args, **kwargs)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/views/identity.py"", line 177, in editaccount\\nreturn AccountForm(request, instances=instances).process()\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/lib/formutils.py"", line 315, in process\\nself.save()\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/forms/account.py"", line 427, in save\\nself.forms[1][""instance""].save(self.user, self.account)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/forms/account.py"", line 305, in save\\nself.update_mailbox(user, account)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/forms/account.py"", line 257, in update_mailbox\\nevents.raiseEvent(\\'MailboxModified\\', self.mb)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/lib/events.py"", line 145, in raiseEvent\\ncallback(*args, **kwargs)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/lib/events.py"", line 98, in wrapped_f\\nreturn f(*args, **kwargs)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/amavis/general_callbacks.py"", line 67, in on_mailbox_modified\\nuser = Users.objects.select_related.get(email=mailbox.old_full_address)\\n\\nAttributeError: \\'function\\' object has no attribute \\'get\\''}]","Traceback (most recent call last): + +File ""/srv/python-envs/service/lib/python2.7/site-packages/django/core/handlers/base.py"", line 112, in get_response +response = wrapped_callback(request, *callback_args, **callback_kwargs) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 22, in _wrapped_view +return view_func(request, *args, **kwargs) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 22, in _wrapped_view +return view_func(request, *args, **kwargs) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/reversion/revisions.py"", line 297, in do_revision_context +return func(*args, **kwargs) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/views/identity.py"", line 177, in editaccount +return AccountForm(request, instances=instances).process() + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/lib/formutils.py"", line 315, in process +self.save() + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/forms/account.py"", line 427, in save +self.forms[1][""instance""].save(self.user, self.account) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/forms/account.py"", line 305, in save +self.update_mailbox(user, account) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/admin/forms/account.py"", line 257, in update_mailbox +events.raiseEvent('MailboxModified', self.mb) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/lib/events.py"", line 145, in raiseEvent +callback(*args, **kwargs) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/lib/events.py"", line 98, in wrapped_f +return f(*args, **kwargs) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa/extensions/amavis/general_callbacks.py"", line 67, in on_mailbox_modified +user = Users.objects.select_related.get(email=mailbox.old_full_address) + +AttributeError: 'function' object has no attribute 'get'",AttributeError +" def get_mail_content(self, mailid): + """"""Retrieve the content of a message."""""" + content = """".join([ + str(qmail.mail_text) + for qmail in Quarantine.objects.filter(mail=mailid) + ]) + if isinstance(content, unicode): + content = content.encode(""utf-8"") + return content"," def get_mail_content(self, mailid): + """"""Retrieve the content of a message. + """""" + return Quarantine.objects.filter(mail=mailid)","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 36, in wrapped_f\\nreturn f(request, *args, **kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 135, in getmailcontent\\nmail = SQLemail(mail_id, mformat=""plain"", links=""0"")\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 23, in __init__\\n{""name"": label, ""value"": self.get_header(self.msg, f)}\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 44, in msg\\nmail_text = """".join([qm.mail_text for qm in qmails])\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 96, in __iter__\\nself._fetch_all()\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all\\nself._result_cache = list(self.iterator())\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator\\nfor row in compiler.results_iter():\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter\\nfor rows in self.execute_sql(MULTI):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 786, in execute_sql\\ncursor.execute(sql, params)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute\\nreturn self.cursor.execute(sql, params)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py"", line 99, in __exit__\\nsix.reraise(dj_exc_type, dj_exc_value, traceback)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute\\nreturn self.cursor.execute(sql, params)\\n\\nDataError: invalid byte sequence for encoding ""UTF8"": 0xb3'}]","Traceback (most recent call last): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response +response = wrapped_callback(request, *callback_args, **callback_kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 36, in wrapped_f +return f(request, *args, **kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 135, in getmailcontent +mail = SQLemail(mail_id, mformat=""plain"", links=""0"") + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 23, in __init__ +{""name"": label, ""value"": self.get_header(self.msg, f)} + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 44, in msg +mail_text = """".join([qm.mail_text for qm in qmails]) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 96, in __iter__ +self._fetch_all() + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all +self._result_cache = list(self.iterator()) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator +for row in compiler.results_iter(): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter +for rows in self.execute_sql(MULTI): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 786, in execute_sql +cursor.execute(sql, params) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute +return self.cursor.execute(sql, params) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py"", line 99, in __exit__ +six.reraise(dj_exc_type, dj_exc_value, traceback) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute +return self.cursor.execute(sql, params) + +DataError: invalid byte sequence for encoding ""UTF8"": 0xb3",DataError +" def get_mail_content(self, mailid): + """"""Retrieve the content of a message."""""" + content = """".join([ + str(qmail.mail_text) + for qmail in Quarantine.objects.filter(mail=mailid) + ]) + if isinstance(content, unicode): + content = content.encode(""utf-8"") + return content"," def get_mail_content(self, mailid): + """"""Retrieve the content of a message."""""" + return Quarantine.objects.filter(mail=mailid).extra( + select={'mail_text': ""convert_from(mail_text, 'UTF8')""} + )","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 36, in wrapped_f\\nreturn f(request, *args, **kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 135, in getmailcontent\\nmail = SQLemail(mail_id, mformat=""plain"", links=""0"")\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 23, in __init__\\n{""name"": label, ""value"": self.get_header(self.msg, f)}\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 44, in msg\\nmail_text = """".join([qm.mail_text for qm in qmails])\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 96, in __iter__\\nself._fetch_all()\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all\\nself._result_cache = list(self.iterator())\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator\\nfor row in compiler.results_iter():\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter\\nfor rows in self.execute_sql(MULTI):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 786, in execute_sql\\ncursor.execute(sql, params)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute\\nreturn self.cursor.execute(sql, params)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py"", line 99, in __exit__\\nsix.reraise(dj_exc_type, dj_exc_value, traceback)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute\\nreturn self.cursor.execute(sql, params)\\n\\nDataError: invalid byte sequence for encoding ""UTF8"": 0xb3'}]","Traceback (most recent call last): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response +response = wrapped_callback(request, *callback_args, **callback_kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 36, in wrapped_f +return f(request, *args, **kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 135, in getmailcontent +mail = SQLemail(mail_id, mformat=""plain"", links=""0"") + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 23, in __init__ +{""name"": label, ""value"": self.get_header(self.msg, f)} + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 44, in msg +mail_text = """".join([qm.mail_text for qm in qmails]) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 96, in __iter__ +self._fetch_all() + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all +self._result_cache = list(self.iterator()) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator +for row in compiler.results_iter(): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter +for rows in self.execute_sql(MULTI): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 786, in execute_sql +cursor.execute(sql, params) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute +return self.cursor.execute(sql, params) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py"", line 99, in __exit__ +six.reraise(dj_exc_type, dj_exc_value, traceback) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute +return self.cursor.execute(sql, params) + +DataError: invalid byte sequence for encoding ""UTF8"": 0xb3",DataError +" def msg(self): + """"""Get message's content."""""" + import email + + if self._msg is None: + mail_text = get_connector().get_mail_content(self.mailid) + self._msg = email.message_from_string(mail_text) + self._parse(self._msg) + return self._msg"," def msg(self): + """"""Get message's content."""""" + import email + + if self._msg is None: + qmails = get_connector().get_mail_content(self.mailid) + mail_text = """".join([qm.mail_text for qm in qmails]) + if type(mail_text) is unicode: + mail_text = mail_text.encode(""utf-8"") + self._msg = email.message_from_string(mail_text) + self._parse(self._msg) + return self._msg","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 36, in wrapped_f\\nreturn f(request, *args, **kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 135, in getmailcontent\\nmail = SQLemail(mail_id, mformat=""plain"", links=""0"")\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 23, in __init__\\n{""name"": label, ""value"": self.get_header(self.msg, f)}\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 44, in msg\\nmail_text = """".join([qm.mail_text for qm in qmails])\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 96, in __iter__\\nself._fetch_all()\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all\\nself._result_cache = list(self.iterator())\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator\\nfor row in compiler.results_iter():\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter\\nfor rows in self.execute_sql(MULTI):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 786, in execute_sql\\ncursor.execute(sql, params)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute\\nreturn self.cursor.execute(sql, params)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py"", line 99, in __exit__\\nsix.reraise(dj_exc_type, dj_exc_value, traceback)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute\\nreturn self.cursor.execute(sql, params)\\n\\nDataError: invalid byte sequence for encoding ""UTF8"": 0xb3'}]","Traceback (most recent call last): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response +response = wrapped_callback(request, *callback_args, **callback_kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 36, in wrapped_f +return f(request, *args, **kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 135, in getmailcontent +mail = SQLemail(mail_id, mformat=""plain"", links=""0"") + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 23, in __init__ +{""name"": label, ""value"": self.get_header(self.msg, f)} + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 44, in msg +mail_text = """".join([qm.mail_text for qm in qmails]) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 96, in __iter__ +self._fetch_all() + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all +self._result_cache = list(self.iterator()) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator +for row in compiler.results_iter(): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter +for rows in self.execute_sql(MULTI): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 786, in execute_sql +cursor.execute(sql, params) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute +return self.cursor.execute(sql, params) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py"", line 99, in __exit__ +six.reraise(dj_exc_type, dj_exc_value, traceback) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute +return self.cursor.execute(sql, params) + +DataError: invalid byte sequence for encoding ""UTF8"": 0xb3",DataError +"def viewheaders(request, mail_id): + """"""Display message headers."""""" + content = get_connector().get_mail_content(mail_id) + msg = email.message_from_string(content) + headers = [] + for name, value in msg.items(): + if value: + result = chardet.detect(value) + if result[""encoding""] is not None: + value = value.decode(result[""encoding""]) + headers += [(name, value)] + return render(request, 'amavis/viewheader.html', { + ""headers"": headers + })","def viewheaders(request, mail_id): + """"""Display message headers."""""" + content = """" + for qm in get_connector().get_mail_content(mail_id): + content += qm.mail_text + if type(content) is unicode: + content = content.encode(""utf-8"") + msg = email.message_from_string(content) + headers = [] + for name, value in msg.items(): + if value: + result = chardet.detect(value) + if result[""encoding""] is not None: + value = value.decode(result[""encoding""]) + headers += [(name, value)] + return render(request, 'amavis/viewheader.html', { + ""headers"": headers + })","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 36, in wrapped_f\\nreturn f(request, *args, **kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 135, in getmailcontent\\nmail = SQLemail(mail_id, mformat=""plain"", links=""0"")\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 23, in __init__\\n{""name"": label, ""value"": self.get_header(self.msg, f)}\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 44, in msg\\nmail_text = """".join([qm.mail_text for qm in qmails])\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 96, in __iter__\\nself._fetch_all()\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all\\nself._result_cache = list(self.iterator())\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator\\nfor row in compiler.results_iter():\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter\\nfor rows in self.execute_sql(MULTI):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 786, in execute_sql\\ncursor.execute(sql, params)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute\\nreturn self.cursor.execute(sql, params)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py"", line 99, in __exit__\\nsix.reraise(dj_exc_type, dj_exc_value, traceback)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute\\nreturn self.cursor.execute(sql, params)\\n\\nDataError: invalid byte sequence for encoding ""UTF8"": 0xb3'}]","Traceback (most recent call last): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response +response = wrapped_callback(request, *callback_args, **callback_kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 36, in wrapped_f +return f(request, *args, **kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 135, in getmailcontent +mail = SQLemail(mail_id, mformat=""plain"", links=""0"") + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 23, in __init__ +{""name"": label, ""value"": self.get_header(self.msg, f)} + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 44, in msg +mail_text = """".join([qm.mail_text for qm in qmails]) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 96, in __iter__ +self._fetch_all() + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all +self._result_cache = list(self.iterator()) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator +for row in compiler.results_iter(): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter +for rows in self.execute_sql(MULTI): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 786, in execute_sql +cursor.execute(sql, params) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute +return self.cursor.execute(sql, params) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py"", line 99, in __exit__ +six.reraise(dj_exc_type, dj_exc_value, traceback) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute +return self.cursor.execute(sql, params) + +DataError: invalid byte sequence for encoding ""UTF8"": 0xb3",DataError +"def mark_messages(request, selection, mtype, recipient_db=None): + """"""Mark a selection of messages as spam. + + :param str selection: message unique identifier + :param str mtype: type of marking (spam or ham) + """""" + if not manual_learning_enabled(request.user): + return render_to_json_response({""status"": ""ok""}) + if recipient_db is None: + recipient_db = ( + ""user"" if request.user.group == ""SimpleUsers"" else ""global"" + ) + selection = check_mail_id(request, selection) + connector = get_connector() + saclient = SpamassassinClient(request.user, recipient_db) + for item in selection: + rcpt, mail_id = item.split() + content = connector.get_mail_content(mail_id) + result = saclient.learn_spam(rcpt, content) if mtype == ""spam"" \\ + else saclient.learn_ham(rcpt, content) + if not result: + break + connector.set_msgrcpt_status(rcpt, mail_id, mtype[0].upper()) + if saclient.error is None: + saclient.done() + message = ungettext(""%(count)d message processed successfully"", + ""%(count)d messages processed successfully"", + len(selection)) % {""count"": len(selection)} + else: + message = saclient.error + status = 400 if saclient.error else 200 + return render_to_json_response({ + ""message"": message, ""reload"": True + }, status=status)","def mark_messages(request, selection, mtype, recipient_db=None): + """"""Mark a selection of messages as spam. + + :param str selection: message unique identifier + :param str mtype: type of marking (spam or ham) + """""" + if not manual_learning_enabled(request.user): + return render_to_json_response({""status"": ""ok""}) + if recipient_db is None: + recipient_db = ( + ""user"" if request.user.group == ""SimpleUsers"" else ""global"" + ) + selection = check_mail_id(request, selection) + connector = get_connector() + saclient = SpamassassinClient(request.user, recipient_db) + for item in selection: + rcpt, mail_id = item.split() + content = """".join( + [msg.mail_text for msg in connector.get_mail_content(mail_id)] + ) + result = saclient.learn_spam(rcpt, content) if mtype == ""spam"" \\ + else saclient.learn_ham(rcpt, content) + if not result: + break + connector.set_msgrcpt_status(rcpt, mail_id, mtype[0].upper()) + if saclient.error is None: + saclient.done() + message = ungettext(""%(count)d message processed successfully"", + ""%(count)d messages processed successfully"", + len(selection)) % {""count"": len(selection)} + else: + message = saclient.error + status = 400 if saclient.error else 200 + return render_to_json_response({ + ""message"": message, ""reload"": True + }, status=status)","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 36, in wrapped_f\\nreturn f(request, *args, **kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 135, in getmailcontent\\nmail = SQLemail(mail_id, mformat=""plain"", links=""0"")\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 23, in __init__\\n{""name"": label, ""value"": self.get_header(self.msg, f)}\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 44, in msg\\nmail_text = """".join([qm.mail_text for qm in qmails])\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 96, in __iter__\\nself._fetch_all()\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all\\nself._result_cache = list(self.iterator())\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator\\nfor row in compiler.results_iter():\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter\\nfor rows in self.execute_sql(MULTI):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 786, in execute_sql\\ncursor.execute(sql, params)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute\\nreturn self.cursor.execute(sql, params)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py"", line 99, in __exit__\\nsix.reraise(dj_exc_type, dj_exc_value, traceback)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute\\nreturn self.cursor.execute(sql, params)\\n\\nDataError: invalid byte sequence for encoding ""UTF8"": 0xb3'}]","Traceback (most recent call last): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response +response = wrapped_callback(request, *callback_args, **callback_kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 36, in wrapped_f +return f(request, *args, **kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 135, in getmailcontent +mail = SQLemail(mail_id, mformat=""plain"", links=""0"") + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 23, in __init__ +{""name"": label, ""value"": self.get_header(self.msg, f)} + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py"", line 44, in msg +mail_text = """".join([qm.mail_text for qm in qmails]) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 96, in __iter__ +self._fetch_all() + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all +self._result_cache = list(self.iterator()) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator +for row in compiler.results_iter(): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter +for rows in self.execute_sql(MULTI): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 786, in execute_sql +cursor.execute(sql, params) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute +return self.cursor.execute(sql, params) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py"", line 99, in __exit__ +six.reraise(dj_exc_type, dj_exc_value, traceback) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py"", line 53, in execute +return self.cursor.execute(sql, params) + +DataError: invalid byte sequence for encoding ""UTF8"": 0xb3",DataError +"def list_quotas(request): + from modoboa.lib.dbutils import db_type + + sort_order, sort_dir = get_sort_order(request.GET, ""address"") + mboxes = Mailbox.objects.get_for_admin( + request.user, request.GET.get(""searchquery"", None) + ) + mboxes = mboxes.exclude(quota=0) + if sort_order in [""address"", ""quota""]: + mboxes = mboxes.order_by(""%s%s"" % (sort_dir, sort_order)) + elif sort_order == ""quota_value__bytes"": + where = ""admin_mailbox.address||'@'||admin_domain.name"" + mboxes = mboxes.extra( + select={""quota_value__bytes"": ""admin_quota.bytes""}, + where=[""admin_quota.username=%s"" % where], + tables=[""admin_quota"", ""admin_domain""], + order_by=[""%s%s"" % (sort_dir, sort_order)] + ) + elif sort_order == ""quota_usage"": + where = ""admin_mailbox.address||'@'||admin_domain.name"" + db_type = db_type() + if db_type == ""postgres"": + select = '(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100' + else: + select = 'admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100' + if db_type == ""mysql"": + where = ""CONCAT(admin_mailbox.address,'@',admin_domain.name)"" + mboxes = mboxes.extra( + select={'quota_usage': select}, + where=[""admin_quota.username=%s"" % where], + tables=[""admin_quota"", ""admin_domain""], + order_by=[""%s%s"" % (sort_dir, sort_order)] + ) + else: + raise BadRequest(_(""Invalid request"")) + page = get_listing_page(mboxes, request.GET.get(""page"", 1)) + context = { + ""headers"": _render_to_string( + request, ""admin/quota_headers.html"", {} + ) + } + if page is None: + context[""length""] = 0 + else: + context[""rows""] = _render_to_string( + request, ""admin/quotas.html"", { + ""mboxes"": page + } + ) + context[""pages""] = [page.number] + return render_to_json_response(context)","def list_quotas(request): + from modoboa.lib.dbutils import db_type + + sort_order, sort_dir = get_sort_order(request.GET, ""address"") + mboxes = Mailbox.objects.get_for_admin( + request.user, request.GET.get(""searchquery"", None) + ) + mboxes = mboxes.exclude(quota=0) + if sort_order in [""address"", ""quota"", ""quota_value__bytes""]: + mboxes = mboxes.order_by(""%s%s"" % (sort_dir, sort_order)) + elif sort_order == ""quota_usage"": + where = ""admin_mailbox.address||'@'||admin_domain.name"" + db_type = db_type() + if db_type == ""postgres"": + select = '(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100' + else: + select = 'admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100' + if db_type == ""mysql"": + where = ""CONCAT(admin_mailbox.address,'@',admin_domain.name)"" + mboxes = mboxes.extra( + select={'quota_usage': select}, + where=[""admin_quota.username=%s"" % where], + tables=[""admin_quota"", ""admin_domain""], + order_by=[""%s%s"" % (sort_dir, sort_order)] + ) + else: + raise BadRequest(_(""Invalid request"")) + page = get_listing_page(mboxes, request.GET.get(""page"", 1)) + context = { + ""headers"": _render_to_string( + request, ""admin/quota_headers.html"", {} + ) + } + if page is None: + context[""length""] = 0 + else: + context[""rows""] = _render_to_string( + request, ""admin/quotas.html"", { + ""mboxes"": page + } + ) + context[""pages""] = [page.number] + return render_to_json_response(context)","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/contrib/auth/decorators.py"", line 22, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/contrib/auth/decorators.py"", line 22, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/admin/views/identity.py"", line 107, in list_quotas\\n""mboxes"": page\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/lib/webutils.py"", line 25, in _render_to_string\\ncontext_instance=template.RequestContext(request))\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/loader.py"", line 169, in render_to_string\\nreturn t.render(context_instance)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py"", line 140, in render\\nreturn self._render(context)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py"", line 134, in _render\\nreturn self.nodelist.render(context)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py"", line 840, in render\\nbit = self.render_node(node, context)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py"", line 854, in render_node\\nreturn node.render(context)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/defaulttags.py"", line 156, in render\\nlen_values = len(values)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/paginator.py"", line 117, in __len__\\nreturn len(self.object_list)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 77, in __len__\\nself._fetch_all()\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all\\nself._result_cache = list(self.iterator())\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator\\nfor row in compiler.results_iter():\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter\\nfor rows in self.execute_sql(MULTI):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 776, in execute_sql\\nsql, params = self.as_sql()\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 84, in as_sql\\nordering, o_params, ordering_group_by = self.get_ordering()\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 403, in get_ordering\\nself.query.get_meta(), default_order=asc):\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 437, in find_ordering_name\\nfield, cols, alias, joins, opts = self._setup_joins(pieces, opts, alias)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 470, in _setup_joins\\npieces, opts, alias)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/query.py"", line 1363, in setup_joins\\nnames, opts, allow_many, allow_explicit_fk)\\n\\nFile ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/query.py"", line 1283, in names_to_path\\n""Choices are: %s"" % (name, "", "".join(available)))\\n\\nFieldError: Cannot resolve keyword u\\'quota_value\\' into field. Choices are: accessrule, address, alias, armessage, dates, domain, id, mailboxoperation, migration, quota, use_domain_quota, user, usercalendar'}]","Traceback (most recent call last): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py"", line 112, in get_response +response = wrapped_callback(request, *callback_args, **callback_kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/contrib/auth/decorators.py"", line 22, in _wrapped_view +return view_func(request, *args, **kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/contrib/auth/decorators.py"", line 22, in _wrapped_view +return view_func(request, *args, **kwargs) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/admin/views/identity.py"", line 107, in list_quotas +""mboxes"": page + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/lib/webutils.py"", line 25, in _render_to_string +context_instance=template.RequestContext(request)) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/loader.py"", line 169, in render_to_string +return t.render(context_instance) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py"", line 140, in render +return self._render(context) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py"", line 134, in _render +return self.nodelist.render(context) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py"", line 840, in render +bit = self.render_node(node, context) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/base.py"", line 854, in render_node +return node.render(context) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/template/defaulttags.py"", line 156, in render +len_values = len(values) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/paginator.py"", line 117, in __len__ +return len(self.object_list) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 77, in __len__ +self._fetch_all() + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 857, in _fetch_all +self._result_cache = list(self.iterator()) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py"", line 220, in iterator +for row in compiler.results_iter(): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 713, in results_iter +for rows in self.execute_sql(MULTI): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 776, in execute_sql +sql, params = self.as_sql() + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 84, in as_sql +ordering, o_params, ordering_group_by = self.get_ordering() + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 403, in get_ordering +self.query.get_meta(), default_order=asc): + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 437, in find_ordering_name +field, cols, alias, joins, opts = self._setup_joins(pieces, opts, alias) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py"", line 470, in _setup_joins +pieces, opts, alias) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/query.py"", line 1363, in setup_joins +names, opts, allow_many, allow_explicit_fk) + +File ""/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/query.py"", line 1283, in names_to_path +""Choices are: %s"" % (name, "", "".join(available))) + +FieldError: Cannot resolve keyword u'quota_value' into field. Choices are: accessrule, address, alias, armessage, dates, domain, id, mailboxoperation, migration, quota, use_domain_quota, user, usercalendar",FieldError +" def messages_count(self, **kwargs): + if self.count is None: + filter = Q(chunk_ind=1) + if self.mail_ids is not None: + filter &= Q(mail__in=self.mail_ids) + if self.filter: + filter &= self.filter + self.messages = Quarantine.objects.filter(filter).values( + ""mail__from_addr"", + ""mail__msgrcpt__rid__email"", + ""mail__subject"", + ""mail__mail_id"", + ""mail__time_num"", + ""mail__msgrcpt__content"", + ""mail__msgrcpt__bspam_level"", + ""mail__msgrcpt__rs"" + ) + if ""order"" in kwargs: + order = kwargs[""order""] + sign = """" + if order[0] == ""-"": + sign = ""-"" + order = order[1:] + order = self.order_translation_table[order] + self.messages = self.messages.order_by(sign + order) + + self.count = self.messages.count() + return self.count"," def messages_count(self, **kwargs): + if self.count is None: + filter = Q(chunk_ind=1) + if self.mail_ids is not None: + filter &= Q(mail__in=self.mail_ids) + if self.filter: + filter &= self.filter + self.messages = Quarantine.objects.filter(filter).values( + ""mail__from_addr"", + ""mail__msgrcpt__rid__email"", + ""mail__subject"", + ""mail__mail_id"", + ""mail__time_num"", + ""mail__msgrcpt__content"", + ""mail__msgrcpt__bspam_level"", + ""mail__msgrcpt__rs"" + ) + if ""order"" in kwargs: + order = kwargs[""order""] + sign = """" + if order[0] == ""-"": + sign = ""-"" + order = order[1:] + order = self.order_translation_table[order] + self.messages = self.messages.order_by(sign + order) + + self.count = len(self.messages) + return self.count","[{'piece_type': 'error message', 'piece_content': 'Internal Server Error: /quarantine/process/\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response\\nresponse = callback(request, *callback_args, **callback_kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process\\nreturn release(request, ids)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f\\nreturn f(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release\\nrcpt.save()\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save\\nforce_update=force_update, update_fields=update_fields)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base\\nrows = manager.using(using).filter(pk=pk_val)._update(values)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update\\nreturn query.get_compiler(self.db).execute_sql(None)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql\\ncursor = super(SQLUpdateCompiler, self).execute_sql(result_type)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql\\ncursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute\\nreturn self.cursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute\\nsix.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute\\nreturn self.cursor.execute(query, args)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute\\nself.errorhandler(self, exc, value)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler\\nraise errorclass, errorvalue\\nIntegrityError: (1062, ""Duplicate entry \\'0-NTFOxSLhytYl-1\\' for key \\'PRIMARY\\'"")'}]","Internal Server Error: /quarantine/process/ +Traceback (most recent call last): +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response +response = callback(request, *callback_args, **callback_kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view +return view_func(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process +return release(request, ids) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f +return f(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release +rcpt.save() +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save +force_update=force_update, update_fields=update_fields) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base +rows = manager.using(using).filter(pk=pk_val)._update(values) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update +return query.get_compiler(self.db).execute_sql(None) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql +cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql +cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute +return self.cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute +six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute +return self.cursor.execute(query, args) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute +self.errorhandler(self, exc, value) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler +raise errorclass, errorvalue +IntegrityError: (1062, ""Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'"")",IntegrityError +" def fetch(self, start=None, stop=None, **kwargs): + emails = [] + for qm in self.messages[start - 1:stop]: + m = {""from"": qm[""mail__from_addr""], + ""to"": qm[""mail__msgrcpt__rid__email""], + ""subject"": qm[""mail__subject""], + ""mailid"": qm[""mail__mail_id""], + ""date"": qm[""mail__time_num""], + ""type"": qm[""mail__msgrcpt__content""], + ""score"": qm[""mail__msgrcpt__bspam_level""]} + rs = qm[""mail__msgrcpt__rs""] + if rs == 'D': + continue + elif rs == '': + m[""class""] = ""unseen"" + elif rs == 'R': + m[""img_rstatus""] = static_url(""pics/release.png"") + elif rs == 'p': + m[""class""] = ""pending"" + emails.append(m) + return emails"," def fetch(self, start=None, stop=None, **kwargs): + emails = [] + for qm in self.messages[start - 1:stop]: + m = {""from"": qm[""mail__from_addr""], + ""to"": qm[""mail__msgrcpt__rid__email""], + ""subject"": qm[""mail__subject""], + ""mailid"": qm[""mail__mail_id""], + ""date"": qm[""mail__time_num""], + ""type"": qm[""mail__msgrcpt__content""], + ""score"": qm[""mail__msgrcpt__bspam_level""]} + rs = qm[""mail__msgrcpt__rs""] + if rs == '': + m[""class""] = ""unseen"" + elif rs == 'R': + m[""img_rstatus""] = static_url(""pics/release.png"") + elif rs == 'p': + m[""class""] = ""pending"" + emails.append(m) + return emails","[{'piece_type': 'error message', 'piece_content': 'Internal Server Error: /quarantine/process/\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response\\nresponse = callback(request, *callback_args, **callback_kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process\\nreturn release(request, ids)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f\\nreturn f(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release\\nrcpt.save()\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save\\nforce_update=force_update, update_fields=update_fields)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base\\nrows = manager.using(using).filter(pk=pk_val)._update(values)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update\\nreturn query.get_compiler(self.db).execute_sql(None)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql\\ncursor = super(SQLUpdateCompiler, self).execute_sql(result_type)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql\\ncursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute\\nreturn self.cursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute\\nsix.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute\\nreturn self.cursor.execute(query, args)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute\\nself.errorhandler(self, exc, value)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler\\nraise errorclass, errorvalue\\nIntegrityError: (1062, ""Duplicate entry \\'0-NTFOxSLhytYl-1\\' for key \\'PRIMARY\\'"")'}]","Internal Server Error: /quarantine/process/ +Traceback (most recent call last): +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response +response = callback(request, *callback_args, **callback_kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view +return view_func(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process +return release(request, ids) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f +return f(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release +rcpt.save() +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save +force_update=force_update, update_fields=update_fields) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base +rows = manager.using(using).filter(pk=pk_val)._update(values) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update +return query.get_compiler(self.db).execute_sql(None) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql +cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql +cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute +return self.cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute +six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute +return self.cursor.execute(query, args) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute +self.errorhandler(self, exc, value) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler +raise errorclass, errorvalue +IntegrityError: (1062, ""Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'"")",IntegrityError +"def viewmail(request, mail_id): + rcpt = request.GET[""rcpt""] + if request.user.mailbox_set.count(): + mb = Mailbox.objects.get(user=request.user) + if rcpt in mb.alias_addresses: + get_wrapper().set_msgrcpt_status(rcpt, mail_id, 'V') + + content = Template("""""" + +"""""").render(Context({""url"": reverse(getmailcontent, args=[mail_id])})) + menu = viewm_menu(mail_id, rcpt) + ctx = getctx(""ok"", menu=menu, listing=content) + request.session['location'] = 'viewmail' + return render_to_json_response(ctx)","def viewmail(request, mail_id): + rcpt = request.GET[""rcpt""] + if request.user.mailbox_set.count(): + mb = Mailbox.objects.get(user=request.user) + if rcpt in mb.alias_addresses: + msgrcpt = get_wrapper().get_recipient_message(rcpt, mail_id) + msgrcpt.rs = 'V' + msgrcpt.save() + + content = Template("""""" + +"""""").render(Context({""url"": reverse(getmailcontent, args=[mail_id])})) + menu = viewm_menu(mail_id, rcpt) + ctx = getctx(""ok"", menu=menu, listing=content) + request.session['location'] = 'viewmail' + return render_to_json_response(ctx)","[{'piece_type': 'error message', 'piece_content': 'Internal Server Error: /quarantine/process/\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response\\nresponse = callback(request, *callback_args, **callback_kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process\\nreturn release(request, ids)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f\\nreturn f(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release\\nrcpt.save()\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save\\nforce_update=force_update, update_fields=update_fields)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base\\nrows = manager.using(using).filter(pk=pk_val)._update(values)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update\\nreturn query.get_compiler(self.db).execute_sql(None)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql\\ncursor = super(SQLUpdateCompiler, self).execute_sql(result_type)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql\\ncursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute\\nreturn self.cursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute\\nsix.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute\\nreturn self.cursor.execute(query, args)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute\\nself.errorhandler(self, exc, value)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler\\nraise errorclass, errorvalue\\nIntegrityError: (1062, ""Duplicate entry \\'0-NTFOxSLhytYl-1\\' for key \\'PRIMARY\\'"")'}]","Internal Server Error: /quarantine/process/ +Traceback (most recent call last): +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response +response = callback(request, *callback_args, **callback_kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view +return view_func(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process +return release(request, ids) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f +return f(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release +rcpt.save() +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save +force_update=force_update, update_fields=update_fields) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base +rows = manager.using(using).filter(pk=pk_val)._update(values) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update +return query.get_compiler(self.db).execute_sql(None) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql +cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql +cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute +return self.cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute +six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute +return self.cursor.execute(query, args) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute +self.errorhandler(self, exc, value) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler +raise errorclass, errorvalue +IntegrityError: (1062, ""Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'"")",IntegrityError +"def delete_selfservice(request, mail_id): + rcpt = request.GET.get(""rcpt"", None) + if rcpt is None: + raise BadRequest(_(""Invalid request"")) + try: + get_wrapper().set_msgrcpt_status(rcpt, mail_id, 'D') + except Msgrcpt.DoesNotExist: + raise BadRequest(_(""Invalid request"")) + return render_to_json_response(_(""Message deleted""))","def delete_selfservice(request, mail_id): + rcpt = request.GET.get(""rcpt"", None) + if rcpt is None: + raise BadRequest(_(""Invalid request"")) + try: + msgrcpt = get_wrapper().get_recipient_message(rcpt, mail_id) + msgrcpt.rs = 'D' + msgrcpt.save() + except Msgrcpt.DoesNotExist: + raise BadRequest(_(""Invalid request"")) + return render_to_json_response(_(""Message deleted""))","[{'piece_type': 'error message', 'piece_content': 'Internal Server Error: /quarantine/process/\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response\\nresponse = callback(request, *callback_args, **callback_kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process\\nreturn release(request, ids)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f\\nreturn f(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release\\nrcpt.save()\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save\\nforce_update=force_update, update_fields=update_fields)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base\\nrows = manager.using(using).filter(pk=pk_val)._update(values)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update\\nreturn query.get_compiler(self.db).execute_sql(None)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql\\ncursor = super(SQLUpdateCompiler, self).execute_sql(result_type)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql\\ncursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute\\nreturn self.cursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute\\nsix.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute\\nreturn self.cursor.execute(query, args)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute\\nself.errorhandler(self, exc, value)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler\\nraise errorclass, errorvalue\\nIntegrityError: (1062, ""Duplicate entry \\'0-NTFOxSLhytYl-1\\' for key \\'PRIMARY\\'"")'}]","Internal Server Error: /quarantine/process/ +Traceback (most recent call last): +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response +response = callback(request, *callback_args, **callback_kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view +return view_func(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process +return release(request, ids) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f +return f(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release +rcpt.save() +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save +force_update=force_update, update_fields=update_fields) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base +rows = manager.using(using).filter(pk=pk_val)._update(values) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update +return query.get_compiler(self.db).execute_sql(None) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql +cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql +cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute +return self.cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute +six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute +return self.cursor.execute(query, args) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute +self.errorhandler(self, exc, value) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler +raise errorclass, errorvalue +IntegrityError: (1062, ""Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'"")",IntegrityError +"def delete(request, mail_id): + """"""Delete message selection. + + :param str mail_id: message unique identifier + """""" + mail_id = check_mail_id(request, mail_id) + wrapper = get_wrapper() + mb = Mailbox.objects.get(user=request.user) \\ + if request.user.group == 'SimpleUsers' else None + for mid in mail_id: + r, i = mid.split() + if mb is not None and r != mb.full_address \\ + and not r in mb.alias_addresses: + continue + wrapper.set_msgrcpt_status(r, i, 'D') + message = ungettext(""%(count)d message deleted successfully"", + ""%(count)d messages deleted successfully"", + len(mail_id)) % {""count"": len(mail_id)} + return ajax_response( + request, respmsg=message, + url=QuarantineNavigationParameters(request).back_to_listing() + )","def delete(request, mail_id): + """"""Delete message selection. + + :param str mail_id: message unique identifier + """""" + mail_id = check_mail_id(request, mail_id) + wrapper = get_wrapper() + mb = Mailbox.objects.get(user=request.user) \\ + if request.user.group == 'SimpleUsers' else None + for mid in mail_id: + r, i = mid.split() + if mb is not None and r != mb.full_address \\ + and not r in mb.alias_addresses: + continue + msgrcpt = wrapper.get_recipient_message(r, i) + msgrcpt.rs = 'D' + msgrcpt.save() + message = ungettext(""%(count)d message deleted successfully"", + ""%(count)d messages deleted successfully"", + len(mail_id)) % {""count"": len(mail_id)} + return ajax_response( + request, respmsg=message, + url=QuarantineNavigationParameters(request).back_to_listing() + )","[{'piece_type': 'error message', 'piece_content': 'Internal Server Error: /quarantine/process/\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response\\nresponse = callback(request, *callback_args, **callback_kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process\\nreturn release(request, ids)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f\\nreturn f(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release\\nrcpt.save()\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save\\nforce_update=force_update, update_fields=update_fields)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base\\nrows = manager.using(using).filter(pk=pk_val)._update(values)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update\\nreturn query.get_compiler(self.db).execute_sql(None)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql\\ncursor = super(SQLUpdateCompiler, self).execute_sql(result_type)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql\\ncursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute\\nreturn self.cursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute\\nsix.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute\\nreturn self.cursor.execute(query, args)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute\\nself.errorhandler(self, exc, value)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler\\nraise errorclass, errorvalue\\nIntegrityError: (1062, ""Duplicate entry \\'0-NTFOxSLhytYl-1\\' for key \\'PRIMARY\\'"")'}]","Internal Server Error: /quarantine/process/ +Traceback (most recent call last): +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response +response = callback(request, *callback_args, **callback_kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view +return view_func(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process +return release(request, ids) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f +return f(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release +rcpt.save() +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save +force_update=force_update, update_fields=update_fields) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base +rows = manager.using(using).filter(pk=pk_val)._update(values) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update +return query.get_compiler(self.db).execute_sql(None) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql +cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql +cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute +return self.cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute +six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute +return self.cursor.execute(query, args) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute +self.errorhandler(self, exc, value) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler +raise errorclass, errorvalue +IntegrityError: (1062, ""Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'"")",IntegrityError +"def release_selfservice(request, mail_id): + rcpt = request.GET.get(""rcpt"", None) + secret_id = request.GET.get(""secret_id"", None) + if rcpt is None or secret_id is None: + raise BadRequest(_(""Invalid request"")) + wrapper = get_wrapper() + try: + msgrcpt = wrapper.get_recipient_message(rcpt, mail_id) + except Msgrcpt.DoesNotExist: + raise BadRequest(_(""Invalid request"")) + if secret_id != msgrcpt.mail.secret_id: + raise BadRequest(_(""Invalid request"")) + if parameters.get_admin(""USER_CAN_RELEASE"") == ""no"": + wrapper.set_msgrcpt_status(rcpt, mail_id, 'p') + msg = _(""Request sent"") + else: + amr = AMrelease() + result = amr.sendreq(mail_id, secret_id, rcpt) + if result: + wrapper.set_msgrcpt_status(rcpt, mail_id, 'R') + msg = _(""Message released"") + else: + raise BadRequest(result) + return render_to_json_response(msg)","def release_selfservice(request, mail_id): + rcpt = request.GET.get(""rcpt"", None) + secret_id = request.GET.get(""secret_id"", None) + if rcpt is None or secret_id is None: + raise BadRequest(_(""Invalid request"")) + try: + msgrcpt = get_wrapper().get_recipient_message(rcpt, mail_id) + except Msgrcpt.DoesNotExist: + raise BadRequest(_(""Invalid request"")) + if secret_id != msgrcpt.mail.secret_id: + raise BadRequest(_(""Invalid request"")) + if parameters.get_admin(""USER_CAN_RELEASE"") == ""no"": + msgrcpt.rs = 'p' + msg = _(""Request sent"") + else: + amr = AMrelease() + result = amr.sendreq(mail_id, secret_id, rcpt) + if result: + rcpt.rs = 'R' + msg = _(""Message released"") + else: + raise BadRequest(result) + msgrcpt.save() + return render_to_json_response(msg)","[{'piece_type': 'error message', 'piece_content': 'Internal Server Error: /quarantine/process/\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response\\nresponse = callback(request, *callback_args, **callback_kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process\\nreturn release(request, ids)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f\\nreturn f(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release\\nrcpt.save()\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save\\nforce_update=force_update, update_fields=update_fields)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base\\nrows = manager.using(using).filter(pk=pk_val)._update(values)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update\\nreturn query.get_compiler(self.db).execute_sql(None)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql\\ncursor = super(SQLUpdateCompiler, self).execute_sql(result_type)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql\\ncursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute\\nreturn self.cursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute\\nsix.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute\\nreturn self.cursor.execute(query, args)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute\\nself.errorhandler(self, exc, value)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler\\nraise errorclass, errorvalue\\nIntegrityError: (1062, ""Duplicate entry \\'0-NTFOxSLhytYl-1\\' for key \\'PRIMARY\\'"")'}]","Internal Server Error: /quarantine/process/ +Traceback (most recent call last): +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response +response = callback(request, *callback_args, **callback_kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view +return view_func(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process +return release(request, ids) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f +return f(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release +rcpt.save() +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save +force_update=force_update, update_fields=update_fields) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base +rows = manager.using(using).filter(pk=pk_val)._update(values) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update +return query.get_compiler(self.db).execute_sql(None) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql +cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql +cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute +return self.cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute +six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute +return self.cursor.execute(query, args) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute +self.errorhandler(self, exc, value) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler +raise errorclass, errorvalue +IntegrityError: (1062, ""Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'"")",IntegrityError +"def release(request, mail_id): + """"""Release message selection. + + :param str mail_id: message unique identifier + """""" + mail_id = check_mail_id(request, mail_id) + msgrcpts = [] + wrapper = get_wrapper() + mb = Mailbox.objects.get(user=request.user) \\ + if request.user.group == 'SimpleUsers' else None + for mid in mail_id: + r, i = mid.split() + if mb is not None and r != mb.full_address \\ + and not r in mb.alias_addresses: + continue + msgrcpts += [wrapper.get_recipient_message(r, i)] + if mb is not None and parameters.get_admin(""USER_CAN_RELEASE"") == ""no"": + for msgrcpt in msgrcpts: + wrapper.set_msgrcpt_status( + msgrcpt.rid.email, msgrcpt.mail.mail_id, 'p' + ) + message = ungettext(""%(count)d request sent"", + ""%(count)d requests sent"", + len(mail_id)) % {""count"": len(mail_id)} + return ajax_response( + request, ""ok"", respmsg=message, + url=QuarantineNavigationParameters(request).back_to_listing() + ) + + amr = AMrelease() + error = None + for rcpt in msgrcpts: + result = amr.sendreq( + rcpt.mail.mail_id, rcpt.mail.secret_id, rcpt.rid.email + ) + if result: + wrapper.set_msgrcpt_status(rcpt.rid.email, rcpt.mail.mail_id, 'R') + else: + error = result + break + + if not error: + message = ungettext(""%(count)d message released successfully"", + ""%(count)d messages released successfully"", + len(mail_id)) % {""count"": len(mail_id)} + else: + message = error + return ajax_response( + request, ""ko"" if error else ""ok"", respmsg=message, + url=QuarantineNavigationParameters(request).back_to_listing() + )","def release(request, mail_id): + """"""Release message selection. + + :param str mail_id: message unique identifier + """""" + mail_id = check_mail_id(request, mail_id) + msgrcpts = [] + wrapper = get_wrapper() + mb = Mailbox.objects.get(user=request.user) \\ + if request.user.group == 'SimpleUsers' else None + for mid in mail_id: + r, i = mid.split() + if mb is not None and r != mb.full_address \\ + and not r in mb.alias_addresses: + continue + msgrcpts += [wrapper.get_recipient_message(r, i)] + if mb is not None and parameters.get_admin(""USER_CAN_RELEASE"") == ""no"": + # FIXME : can't use this syntax because extra SQL (using + # .extra() for postgres) is not propagated (the 'tables' + # parameter is lost somewhere...) + # + # msgrcpts.update(rs='p') + for msgrcpt in msgrcpts: + msgrcpt.rs = 'p' + msgrcpt.save() + message = ungettext(""%(count)d request sent"", + ""%(count)d requests sent"", + len(mail_id)) % {""count"": len(mail_id)} + return ajax_response( + request, ""ok"", respmsg=message, + url=QuarantineNavigationParameters(request).back_to_listing() + ) + + amr = AMrelease() + error = None + for rcpt in msgrcpts: + result = amr.sendreq(rcpt.mail.mail_id, rcpt.mail.secret_id, rcpt.rid.email) + if result: + rcpt.rs = 'R' + rcpt.save() + else: + error = result + break + + if not error: + message = ungettext(""%(count)d message released successfully"", + ""%(count)d messages released successfully"", + len(mail_id)) % {""count"": len(mail_id)} + else: + message = error + return ajax_response( + request, ""ko"" if error else ""ok"", respmsg=message, + url=QuarantineNavigationParameters(request).back_to_listing() + )","[{'piece_type': 'error message', 'piece_content': 'Internal Server Error: /quarantine/process/\\nTraceback (most recent call last):\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response\\nresponse = callback(request, *callback_args, **callback_kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view\\nreturn view_func(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process\\nreturn release(request, ids)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f\\nreturn f(request, *args, **kwargs)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release\\nrcpt.save()\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save\\nforce_update=force_update, update_fields=update_fields)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base\\nrows = manager.using(using).filter(pk=pk_val)._update(values)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update\\nreturn query.get_compiler(self.db).execute_sql(None)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql\\ncursor = super(SQLUpdateCompiler, self).execute_sql(result_type)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql\\ncursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute\\nreturn self.cursor.execute(sql, params)\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute\\nsix.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])\\nFile ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute\\nreturn self.cursor.execute(query, args)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute\\nself.errorhandler(self, exc, value)\\nFile ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler\\nraise errorclass, errorvalue\\nIntegrityError: (1062, ""Duplicate entry \\'0-NTFOxSLhytYl-1\\' for key \\'PRIMARY\\'"")'}]","Internal Server Error: /quarantine/process/ +Traceback (most recent call last): +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response +response = callback(request, *callback_args, **callback_kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"", line 25, in _wrapped_view +return view_func(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 307, in process +return release(request, ids) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py"", line 30, in wrapped_f +return f(request, *args, **kwargs) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py"", line 282, in release +rcpt.save() +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 546, in save +force_update=force_update, update_fields=update_fields) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/base.py"", line 626, in save_base +rows = manager.using(using).filter(pk=pk_val)._update(values) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/query.py"", line 605, in _update +return query.get_compiler(self.db).execute_sql(None) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 1020, in execute_sql +cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py"", line 846, in execute_sql +cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/util.py"", line 41, in execute +return self.cursor.execute(sql, params) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 122, in execute +six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) +File ""/srv/modoboa/python-virtualenv-modoboa-1.1.1/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py"", line 120, in execute +return self.cursor.execute(query, args) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py"", line 174, in execute +self.errorhandler(self, exc, value) +File ""/usr/lib/python2.7/dist-packages/MySQLdb/connections.py"", line 36, in defaulterrorhandler +raise errorclass, errorvalue +IntegrityError: (1062, ""Duplicate entry '0-NTFOxSLhytYl-1' for key 'PRIMARY'"")",IntegrityError +"def get_password_hasher(scheme): + """"""Retrieve the hasher corresponding to :keyword:`scheme`. + + If no class is found, `PLAINHasher` is returned. + + :param str scheme: a valid scheme name + :rtype: PasswordHasher sub class + :return: The hasher class + """""" + try: + scheme = scheme.replace('-', '') + hasher = globals()['%sHasher' % scheme.upper()] + except KeyError: + hasher = PLAINHasher + return hasher","def get_password_hasher(scheme): + """"""Retrieve the hasher corresponding to :keyword:`scheme`. + + If no class is found, `PLAINHasher` is returned. + + :param str scheme: a valid scheme name + :rtype: PasswordHasher sub class + :return: The hasher class + """""" + try: + scheme = scheme.replace('-', '') + hasher = globals()['%sHasher' % scheme] + except AttributeError: + hasher = PLAINHasher + return hasher","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response\\nresponse = callback(request, *callback_args, **callback_kwargs)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/django/views/decorators/cache.py"", line 89, in _wrapped_view_func\\nresponse = view_func(request, *args, **kwargs)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/views/auth.py"", line 20, in dologin\\npassword=form.cleaned_data[""password""])\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/django/contrib/auth/__init__.py"", line 60, in authenticate\\nuser = backend.authenticate(**credentials)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/lib/authbackends.py"", line 14, in authenticate\\nif not user.check_password(password):\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/models.py"", line 134, in check_password\\nhasher = get_password_hasher(scheme)\\n\\nFile ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/password_hashers/__init__.py"", line 23, in get_password_hasher\\nhasher = globals()[\\'%sHasher\\' % scheme]\\n\\nKeyError: u\\'plainHasher\\''}]","Traceback (most recent call last): + +File ""/srv/python-envs/service/lib/python2.7/site-packages/django/core/handlers/base.py"", line 115, in get_response +response = callback(request, *callback_args, **callback_kwargs) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/django/views/decorators/cache.py"", line 89, in _wrapped_view_func +response = view_func(request, *args, **kwargs) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/views/auth.py"", line 20, in dologin +password=form.cleaned_data[""password""]) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/django/contrib/auth/__init__.py"", line 60, in authenticate +user = backend.authenticate(**credentials) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/lib/authbackends.py"", line 14, in authenticate +if not user.check_password(password): + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/models.py"", line 134, in check_password +hasher = get_password_hasher(scheme) + +File ""/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/password_hashers/__init__.py"", line 23, in get_password_hasher +hasher = globals()['%sHasher' % scheme] + +KeyError: u'plainHasher'",KeyError +"def print_summary(samples, prob=0.9, group_by_chain=True): + """""" + Prints a summary table displaying diagnostics of ``samples`` from the + posterior. The diagnostics displayed are mean, standard deviation, median, + the 90% Credibility Interval, :func:`~pyro.ops.stats.effective_sample_size`, + :func:`~pyro.ops.stats.split_gelman_rubin`. + + :param dict samples: dictionary of samples keyed by site name. + :param float prob: the probability mass of samples within the credibility interval. + :param bool group_by_chain: If True, each variable in `samples` + will be treated as having shape `num_chains x num_samples x sample_shape`. + Otherwise, the corresponding shape will be `num_samples x sample_shape` + (i.e. without chain dimension). + """""" + if len(samples) == 0: + return + summary_dict = summary(samples, prob, group_by_chain) + + row_names = {k: k + '[' + ','.join(map(lambda x: str(x - 1), v.shape[2:])) + ']' + for k, v in samples.items()} + max_len = max(max(map(lambda x: len(x), row_names.values())), 10) + name_format = '{:>' + str(max_len) + '}' + header_format = name_format + ' {:>9}' * 7 + columns = [''] + list(list(summary_dict.values())[0].keys()) + + print() + print(header_format.format(*columns)) + + row_format = name_format + ' {:>9.2f}' * 7 + for name, stats_dict in summary_dict.items(): + shape = stats_dict[""mean""].shape + if len(shape) == 0: + print(row_format.format(name, *stats_dict.values())) + else: + for idx in product(*map(range, shape)): + idx_str = '[{}]'.format(','.join(map(str, idx))) + print(row_format.format(name + idx_str, *[v[idx] for v in stats_dict.values()])) + print()","def print_summary(samples, prob=0.9, group_by_chain=True): + """""" + Prints a summary table displaying diagnostics of ``samples`` from the + posterior. The diagnostics displayed are mean, standard deviation, median, + the 90% Credibility Interval, :func:`~pyro.ops.stats.effective_sample_size`, + :func:`~pyro.ops.stats.split_gelman_rubin`. + + :param dict samples: dictionary of samples keyed by site name. + :param float prob: the probability mass of samples within the credibility interval. + :param bool group_by_chain: If True, each variable in `samples` + will be treated as having shape `num_chains x num_samples x sample_shape`. + Otherwise, the corresponding shape will be `num_samples x sample_shape` + (i.e. without chain dimension). + """""" + summary_dict = summary(samples, prob, group_by_chain) + + row_names = {k: k + '[' + ','.join(map(lambda x: str(x - 1), v.shape[2:])) + ']' + for k, v in samples.items()} + max_len = max(max(map(lambda x: len(x), row_names.values())), 10) + name_format = '{:>' + str(max_len) + '}' + header_format = name_format + ' {:>9}' * 7 + columns = [''] + list(list(summary_dict.values())[0].keys()) + + print() + print(header_format.format(*columns)) + + row_format = name_format + ' {:>9.2f}' * 7 + for name, stats_dict in summary_dict.items(): + shape = stats_dict[""mean""].shape + if len(shape) == 0: + print(row_format.format(name, *stats_dict.values())) + else: + for idx in product(*map(range, shape)): + idx_str = '[{}]'.format(','.join(map(str, idx))) + print(row_format.format(name + idx_str, *[v[idx] for v in stats_dict.values()])) + print()","[{'piece_type': 'other', 'piece_content': 'import torch\\nimport pyro\\nimport pyro.distributions as dist\\nimport pyro.poutine as poutine\\nfrom pyro.infer import MCMC, NUTS\\n#pyro.set_rng_seed(101)\\n\\n# This works if I set it to True\\nuse_gaussian = False\\n\\ndef model(prior_elves):\\nprint(\\'prior:\\', prior_elves)\\nif use_gaussian:\\nnum_elves = pyro.sample(""num_elves"",\\ndist.Normal(prior_elves, torch.tensor(2.0)))\\nelse:\\nnum_elves = pyro.sample(""num_elves"",\\npyro.distributions.Categorical(probs=prior_elves))\\nprint(""Num elves: "", num_elves)\\n\\nnum_rocks = num_elves * 4\\nnum_logs = num_elves * 6\\n\\nprint(f""Rocks: {num_rocks}, Logs: {num_logs}"")\\n\\n# begin https://pyro.ai/examples/intro_part_ii.html\\n\\nrocks_observed = pyro.sample(""rocks_observed"",\\ndist.Normal(num_rocks, torch.tensor(3.0)))\\n\\nlogs_observed = pyro.sample(""logs_observed"",\\ndist.Normal(num_logs, torch.tensor(3.0)))\\n\\nprint(f""Rocks obs: {rocks_observed}, Logs obs: {logs_observed}"")\\n\\nreturn num_elves\\n\\ndef conditioned_model(model, data, prior_elves):\\nreturn poutine.condition(model, data=data)(prior_elves)\\n\\ndata = {""rocks_observed"": torch.tensor(4),\\n""logs_observed"": torch.tensor(6),\\n}\\n\\nif use_gaussian:\\nprior_elves = torch.tensor(2.0)\\nelse:\\nprior_elves = torch.tensor([.2,.2,.2,.2,.2])\\n\\nnuts_kernel = NUTS(conditioned_model, jit_compile=False)\\nmcmc = MCMC(nuts_kernel,\\nnum_samples=10,\\nwarmup_steps=5,\\nnum_chains=1)\\nmcmc.run(model, data, prior_elves)\\n\\nmcmc.summary(prob=.5)'}, {'piece_type': 'error message', 'piece_content': 'Sample: 100%|██████████| 15/15 [00:00, 1853.70it/s, step size=1.00e+00, acc. prob=1.000]\\nprior: tensor([0.2000, 0.2000, 0.2000, 0.2000, 0.2000])\\nNum elves: tensor(4)\\nRocks: 16, Logs: 24\\nRocks obs: 4, Logs obs: 6\\nprior: tensor([0.2000, 0.2000, 0.2000, 0.2000, 0.2000])\\nNum elves: tensor([0, 1, 2, 3, 4])\\nRocks: tensor([ 0, 4, 8, 12, 16]), Logs: tensor([ 0, 6, 12, 18, 24])\\nRocks obs: 4, Logs obs: 6\\nprior: tensor([0.2000, 0.2000, 0.2000, 0.2000, 0.2000])\\nNum elves: tensor([0, 1, 2, 3, 4])\\nRocks: tensor([ 0, 4, 8, 12, 16]), Logs: tensor([ 0, 6, 12, 18, 24])\\nRocks obs: 4, Logs obs: 6\\n\\nTraceback (most recent call last):\\nFile ""/Users/jmugan/Dropbox/code/python_examples/jwm_pyro/elves.py"", line 75, in \\nmcmc.summary(prob=.5)\\nFile ""/Users/jmugan/anaconda3/lib/python3.7/site-packages/pyro/infer/mcmc/api.py"", line 485, in summary\\nprint_summary(self._samples, prob=prob)\\nFile ""/Users/jmugan/anaconda3/lib/python3.7/site-packages/pyro/infer/mcmc/util.py"", line 522, in print_summary\\nmax_len = max(max(map(lambda x: len(x), row_names.values())), 10)\\nValueError: max() arg is an empty sequence\\n\\nProcess finished with exit code 1'}]","Sample: 100%|██████████| 15/15 [00:00, 1853.70it/s, step size=1.00e+00, acc. prob=1.000] +prior: tensor([0.2000, 0.2000, 0.2000, 0.2000, 0.2000]) +Num elves: tensor(4) +Rocks: 16, Logs: 24 +Rocks obs: 4, Logs obs: 6 +prior: tensor([0.2000, 0.2000, 0.2000, 0.2000, 0.2000]) +Num elves: tensor([0, 1, 2, 3, 4]) +Rocks: tensor([ 0, 4, 8, 12, 16]), Logs: tensor([ 0, 6, 12, 18, 24]) +Rocks obs: 4, Logs obs: 6 +prior: tensor([0.2000, 0.2000, 0.2000, 0.2000, 0.2000]) +Num elves: tensor([0, 1, 2, 3, 4]) +Rocks: tensor([ 0, 4, 8, 12, 16]), Logs: tensor([ 0, 6, 12, 18, 24]) +Rocks obs: 4, Logs obs: 6 + +Traceback (most recent call last): +File ""/Users/jmugan/Dropbox/code/python_examples/jwm_pyro/elves.py"", line 75, in +mcmc.summary(prob=.5) +File ""/Users/jmugan/anaconda3/lib/python3.7/site-packages/pyro/infer/mcmc/api.py"", line 485, in summary +print_summary(self._samples, prob=prob) +File ""/Users/jmugan/anaconda3/lib/python3.7/site-packages/pyro/infer/mcmc/util.py"", line 522, in print_summary +max_len = max(max(map(lambda x: len(x), row_names.values())), 10) +ValueError: max() arg is an empty sequence + +Process finished with exit code 1",ValueError +"def get_dependent_plate_dims(sites): + """""" + Return a list of dims for plates that are not common to all sites. + """""" + plate_sets = [site[""cond_indep_stack""] + for site in sites if site[""type""] == ""sample""] + all_plates = set().union(*plate_sets) + common_plates = all_plates.intersection(*plate_sets) + sum_plates = all_plates - common_plates + sum_dims = list(sorted(f.dim for f in sum_plates if f.dim is not None)) + return sum_dims","def get_dependent_plate_dims(sites): + """""" + Return a list of dims for plates that are not common to all sites. + """""" + plate_sets = [site[""cond_indep_stack""] + for site in sites if site[""type""] == ""sample""] + all_plates = set().union(*plate_sets) + common_plates = all_plates.intersection(*plate_sets) + sum_plates = all_plates - common_plates + sum_dims = list(sorted(f.dim for f in sum_plates)) + return sum_dims","[{'piece_type': 'source code', 'piece_content': ""import sys, torch, pyro\\nprint(sys.version, torch.__version__, pyro.__version__)\\n\\ndef model(data):\\nx = pyro.sample('x', pyro.distributions.Bernoulli(torch.tensor(0.5)))\\nfor i in pyro.plate('data_plate', len(data)):\\npyro.sample('data_{:d}'.format(i), pyro.distributions.Normal(x, scale=torch.tensor(0.1)), obs=data[i])\\n\\n# Works as expected\\n# def model(data):\\n# x = pyro.sample('x', pyro.distributions.Bernoulli(torch.tensor(0.5)))\\n# with pyro.plate('data_plate', len(data)):\\n# pyro.sample('data', pyro.distributions.Normal(x, scale=torch.tensor(0.1)), obs=data)\\n\\ndef guide(data):\\np = pyro.param('p', torch.tensor(0.5))\\nx = pyro.sample('x', pyro.distributions.Bernoulli(p))\\n\\nelbo = pyro.infer.TraceGraph_ELBO()\\nprint(elbo.loss(model, guide, torch.randn([3])))\\n\\nelbo = pyro.infer.RenyiELBO()\\nprint(elbo.loss(model, guide, torch.randn([3])))""}, {'piece_type': 'error message', 'piece_content': ""3.8.1 (default, Jan 8 2020, 16:15:59)\\n[Clang 4.0.1 (tags/RELEASE_401/final)] 1.4.0 1.3.0\\n2.4235687255859375\\n---------------------------------------------------------------------------\\nTypeError Traceback (most recent call last)\\n in \\n15\\n16 elbo = pyro.infer.RenyiELBO()\\n---> 17 print(elbo.loss(model, guide, torch.randn([3])))\\n\\n~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/torch/autograd/grad_mode.py in decorate_no_grad(*args, **kwargs)\\n47 def decorate_no_grad(*args, **kwargs):\\n48 with self:\\n---> 49 return func(*args, **kwargs)\\n50 return decorate_no_grad\\n51\\n\\n~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/pyro/infer/renyi_elbo.py in loss(self, model, guide, *args, **kwargs)\\n96 for model_trace, guide_trace in self._get_traces(model, guide, args, kwargs):\\n97 elbo_particle = 0.\\n---> 98 sum_dims = get_dependent_plate_dims(model_trace.nodes.values())\\n99\\n100 # compute elbo\\n\\n~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/pyro/infer/util.py in get_dependent_plate_dims(sites)\\n114 common_plates = all_plates.intersection(*plate_sets)\\n115 sum_plates = all_plates - common_plates\\n--> 116 sum_dims = list(sorted(f.dim for f in sum_plates))\\n117 return sum_dims\\n118\\n\\nTypeError: '<' not supported between instances of 'NoneType' and 'NoneType'""}]","3.8.1 (default, Jan 8 2020, 16:15:59) +[Clang 4.0.1 (tags/RELEASE_401/final)] 1.4.0 1.3.0 +2.4235687255859375 +--------------------------------------------------------------------------- +TypeError Traceback (most recent call last) + in +15 +16 elbo = pyro.infer.RenyiELBO() +---> 17 print(elbo.loss(model, guide, torch.randn([3]))) + +~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/torch/autograd/grad_mode.py in decorate_no_grad(*args, **kwargs) +47 def decorate_no_grad(*args, **kwargs): +48 with self: +---> 49 return func(*args, **kwargs) +50 return decorate_no_grad +51 + +~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/pyro/infer/renyi_elbo.py in loss(self, model, guide, *args, **kwargs) +96 for model_trace, guide_trace in self._get_traces(model, guide, args, kwargs): +97 elbo_particle = 0. +---> 98 sum_dims = get_dependent_plate_dims(model_trace.nodes.values()) +99 +100 # compute elbo + +~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/pyro/infer/util.py in get_dependent_plate_dims(sites) +114 common_plates = all_plates.intersection(*plate_sets) +115 sum_plates = all_plates - common_plates +--> 116 sum_dims = list(sorted(f.dim for f in sum_plates)) +117 return sum_dims +118 + +TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'",TypeError +" def run(self, *args, **kwargs): + self._args, self._kwargs = args, kwargs + num_samples = [0] * self.num_chains + z_flat_acc = [[] for _ in range(self.num_chains)] + with pyro.validation_enabled(not self.disable_validation): + for x, chain_id in self.sampler.run(*args, **kwargs): + if num_samples[chain_id] == 0: + num_samples[chain_id] += 1 + z_structure = x + elif num_samples[chain_id] == self.num_samples + 1: + self._diagnostics[chain_id] = x + else: + num_samples[chain_id] += 1 + if self.num_chains > 1: + x_cloned = x.clone() + del x + else: + x_cloned = x + z_flat_acc[chain_id].append(x_cloned) + + z_flat_acc = torch.stack([torch.stack(l) for l in z_flat_acc]) + + # unpack latent + pos = 0 + z_acc = z_structure.copy() + for k in sorted(z_structure): + shape = z_structure[k] + next_pos = pos + shape.numel() + z_acc[k] = z_flat_acc[:, :, pos:next_pos].reshape( + (self.num_chains, self.num_samples) + shape) + pos = next_pos + assert pos == z_flat_acc.shape[-1] + + # If transforms is not explicitly provided, infer automatically using + # model args, kwargs. + if self.transforms is None: + # Use `kernel.transforms` when available + if hasattr(self.kernel, 'transforms') and self.kernel.transforms is not None: + self.transforms = self.kernel.transforms + # Else, get transforms from model (e.g. in multiprocessing). + elif self.kernel.model: + _, _, self.transforms, _ = initialize_model(self.kernel.model, + model_args=args, + model_kwargs=kwargs) + # Assign default value + else: + self.transforms = {} + + # transform samples back to constrained space + for name, transform in self.transforms.items(): + z_acc[name] = transform.inv(z_acc[name]) + self._samples = z_acc + + # terminate the sampler (shut down worker processes) + self.sampler.terminate(True)"," def run(self, *args, **kwargs): + self._args, self._kwargs = args, kwargs + num_samples = [0] * self.num_chains + z_flat_acc = [[] for _ in range(self.num_chains)] + with pyro.validation_enabled(not self.disable_validation): + for x, chain_id in self.sampler.run(*args, **kwargs): + if num_samples[chain_id] == 0: + num_samples[chain_id] += 1 + z_structure = x + elif num_samples[chain_id] == self.num_samples + 1: + self._diagnostics[chain_id] = x + else: + num_samples[chain_id] += 1 + if self.num_chains > 1: + x_cloned = x.clone() + del x + else: + x_cloned = x + z_flat_acc[chain_id].append(x_cloned) + + z_flat_acc = torch.stack([torch.stack(l) for l in z_flat_acc]) + + # unpack latent + pos = 0 + z_acc = z_structure.copy() + for k in sorted(z_structure): + shape = z_structure[k] + next_pos = pos + shape.numel() + z_acc[k] = z_flat_acc[:, :, pos:next_pos].reshape( + (self.num_chains, self.num_samples) + shape) + pos = next_pos + assert pos == z_flat_acc.shape[-1] + + # If transforms is not explicitly provided, infer automatically using + # model args, kwargs. + if self.transforms is None: + if hasattr(self.kernel, 'transforms'): + if self.kernel.transforms is not None: + self.transforms = self.kernel.transforms + elif self.kernel.model: + _, _, self.transforms, _ = initialize_model(self.kernel.model, + model_args=args, + model_kwargs=kwargs) + else: + self.transforms = {} + + # transform samples back to constrained space + for name, transform in self.transforms.items(): + z_acc[name] = transform.inv(z_acc[name]) + self._samples = z_acc + + # terminate the sampler (shut down worker processes) + self.sampler.terminate(True)","[{'piece_type': 'error message', 'piece_content': ""AttributeError Traceback (most recent call last)\\n in ()\\n8 mcmc = MCMC(nuts_kernel, num_samples=25, warmup_steps=100, num_chains=cpu_count)\\n9\\n---> 10 mcmc.run(y)\\n\\n~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/pyro/poutine/messenger.py in _context_wrap(context, fn, *args, **kwargs)\\n9 def _context_wrap(context, fn, *args, **kwargs):\\n10 with context:\\n---> 11 return fn(*args, **kwargs)\\n12\\n13\\n\\n~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/pyro/infer/mcmc/api.py in run(self, *args, **kwargs)\\n397\\n398 # transform samples back to constrained space\\n--> 399 for name, transform in self.transforms.items():\\n400 z_acc[name] = transform.inv(z_acc[name])\\n401 self._samples = z_acc\\n\\nAttributeError: 'NoneType' object has no attribute 'items'""}, {'piece_type': 'source code', 'piece_content': ""import numpy as np\\n\\nimport torch\\nprint(torch.__version__)\\nassert torch.__version__.startswith('1.4.0')\\n\\nimport pyro\\nimport pyro.distributions as dist\\nfrom pyro.infer import MCMC, NUTS\\nprint(pyro.__version__)\\nassert pyro.__version__.startswith('1.2.0') or pyro.__version__.startswith('1.1.0')\\n\\n# set\\nseed = 2020\\npyro.set_rng_seed(seed)\\n\\ndef nrv(n=1000, loc=5, scale=2, seed=2020):\\nnp.random.seed(2020)\\nz = np.random.normal(loc, scale, size=n)\\ny = torch.from_numpy(z).type(torch.float)\\nreturn y\\n\\ndef model(y):\\nscale_guess = torch.tensor(20, dtype=torch.float)\\nscale_prior = pyro.sample('scale', dist.HalfNormal(scale_guess))\\nmean_guess = torch.tensor(0, dtype=torch.float)\\nmean_prior = pyro.sample('loc', dist.Normal(mean_guess, scale_prior), obs=y)\\n\\ndef main(num_chains):\\nnuts_kernel = NUTS(model, adapt_step_size=True)\\nmcmc = MCMC(nuts_kernel, num_samples=25, warmup_steps=100, num_chains=chains)\\nmcmc.run(y)\\n\\nif __name__ == '__main__':\\nmain(1)\\nmain(2)""}]","AttributeError Traceback (most recent call last) + in () +8 mcmc = MCMC(nuts_kernel, num_samples=25, warmup_steps=100, num_chains=cpu_count) +9 +---> 10 mcmc.run(y) + +~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/pyro/poutine/messenger.py in _context_wrap(context, fn, *args, **kwargs) +9 def _context_wrap(context, fn, *args, **kwargs): +10 with context: +---> 11 return fn(*args, **kwargs) +12 +13 + +~/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/pyro/infer/mcmc/api.py in run(self, *args, **kwargs) +397 +398 # transform samples back to constrained space +--> 399 for name, transform in self.transforms.items(): +400 z_acc[name] = transform.inv(z_acc[name]) +401 self._samples = z_acc + +AttributeError: 'NoneType' object has no attribute 'items'",AttributeError +" def get_posterior(self, *args, **kwargs): + """""" + Returns a MultivariateNormal posterior distribution. + """""" + loc = pyro.param(""{}_loc"".format(self.prefix), self._init_loc) + scale_tril = pyro.param(""{}_scale_tril"".format(self.prefix), + lambda: eye_like(loc, self.latent_dim), + constraint=constraints.lower_cholesky) + return dist.MultivariateNormal(loc, scale_tril=scale_tril)"," def get_posterior(self, *args, **kwargs): + """""" + Returns a MultivariateNormal posterior distribution. + """""" + loc = pyro.param(""{}_loc"".format(self.prefix), + lambda: torch.zeros(self.latent_dim)) + scale_tril = pyro.param(""{}_scale_tril"".format(self.prefix), + lambda: torch.eye(self.latent_dim), + constraint=constraints.lower_cholesky) + return dist.MultivariateNormal(loc, scale_tril=scale_tril)","[{'piece_type': 'source code', 'piece_content': 'import pyro\\nimport pyro.distributions as dist\\nimport torch\\nfrom pyro.contrib.autoguide import AutoDiagonalNormal\\nfrom pyro.infer import SVI, Trace_ELBO\\nfrom pyro.optim import Adam\\n\\n\\ndef model(xs, prior_loc, prior_scale):\\nmu = pyro.sample(\\'mu\\', dist.Normal(prior_loc, prior_scale))\\nreturn pyro.sample(\\'obs\\', dist.Normal(mu, prior_scale), obs=xs)\\n\\n\\ndef train():\\nxs = torch.tensor([5, 5.5, 5.6, 5.8, 6.3], device=\\'cuda\\')\\nprior_loc = torch.tensor(0.0, device=\\'cuda\\')\\nprior_scale = torch.tensor(1.0, device=\\'cuda\\')\\nguide = AutoDiagonalNormal(model)\\noptim = Adam({\\'lr\\': 1e-3})\\nloss = Trace_ELBO()\\nsvi = SVI(model, guide, optim, loss)\\nsvi.step(xs, prior_loc, prior_scale)\\n\\nif __name__ == ""__main__"":\\ntrain()'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\IPython\\\\core\\\\interactiveshell.py"", line 3265, in run_code\\nexec(code_obj, self.user_global_ns, self.user_ns)\\nFile """", line 26, in \\ntrain()\\nFile """", line 23, in train\\nsvi.step(xs, prior_loc, prior_scale)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\svi.py"", line 99, in step\\nloss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\trace_elbo.py"", line 136, in loss_and_grads\\nsurrogate_loss_particle.backward(retain_graph=self.retain_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\tensor.py"", line 107, in backward\\ntorch.autograd.backward(self, gradient, retain_graph, create_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\autograd\\\\__init__.py"", line 93, in backward\\nallow_unreachable=True) # allow_unreachable flag\\nRuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor'}]","Traceback (most recent call last): +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\IPython\\core\\interactiveshell.py"", line 3265, in run_code +exec(code_obj, self.user_global_ns, self.user_ns) +File """", line 26, in +train() +File """", line 23, in train +svi.step(xs, prior_loc, prior_scale) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\svi.py"", line 99, in step +loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\trace_elbo.py"", line 136, in loss_and_grads +surrogate_loss_particle.backward(retain_graph=self.retain_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\tensor.py"", line 107, in backward +torch.autograd.backward(self, gradient, retain_graph, create_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\autograd\\__init__.py"", line 93, in backward +allow_unreachable=True) # allow_unreachable flag +RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor",RuntimeError +" def get_posterior(self, *args, **kwargs): + """""" + Returns a diagonal Normal posterior distribution. + """""" + loc = pyro.param(""{}_loc"".format(self.prefix), self._init_loc) + scale = pyro.param(""{}_scale"".format(self.prefix), + lambda: loc.new_ones(self.latent_dim), + constraint=constraints.positive) + return dist.Normal(loc, scale).to_event(1)"," def get_posterior(self, *args, **kwargs): + """""" + Returns a diagonal Normal posterior distribution. + """""" + loc = pyro.param(""{}_loc"".format(self.prefix), + lambda: torch.zeros(self.latent_dim)) + scale = pyro.param(""{}_scale"".format(self.prefix), + lambda: torch.ones(self.latent_dim), + constraint=constraints.positive) + return dist.Normal(loc, scale).to_event(1)","[{'piece_type': 'source code', 'piece_content': 'import pyro\\nimport pyro.distributions as dist\\nimport torch\\nfrom pyro.contrib.autoguide import AutoDiagonalNormal\\nfrom pyro.infer import SVI, Trace_ELBO\\nfrom pyro.optim import Adam\\n\\n\\ndef model(xs, prior_loc, prior_scale):\\nmu = pyro.sample(\\'mu\\', dist.Normal(prior_loc, prior_scale))\\nreturn pyro.sample(\\'obs\\', dist.Normal(mu, prior_scale), obs=xs)\\n\\n\\ndef train():\\nxs = torch.tensor([5, 5.5, 5.6, 5.8, 6.3], device=\\'cuda\\')\\nprior_loc = torch.tensor(0.0, device=\\'cuda\\')\\nprior_scale = torch.tensor(1.0, device=\\'cuda\\')\\nguide = AutoDiagonalNormal(model)\\noptim = Adam({\\'lr\\': 1e-3})\\nloss = Trace_ELBO()\\nsvi = SVI(model, guide, optim, loss)\\nsvi.step(xs, prior_loc, prior_scale)\\n\\nif __name__ == ""__main__"":\\ntrain()'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\IPython\\\\core\\\\interactiveshell.py"", line 3265, in run_code\\nexec(code_obj, self.user_global_ns, self.user_ns)\\nFile """", line 26, in \\ntrain()\\nFile """", line 23, in train\\nsvi.step(xs, prior_loc, prior_scale)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\svi.py"", line 99, in step\\nloss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\trace_elbo.py"", line 136, in loss_and_grads\\nsurrogate_loss_particle.backward(retain_graph=self.retain_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\tensor.py"", line 107, in backward\\ntorch.autograd.backward(self, gradient, retain_graph, create_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\autograd\\\\__init__.py"", line 93, in backward\\nallow_unreachable=True) # allow_unreachable flag\\nRuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor'}]","Traceback (most recent call last): +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\IPython\\core\\interactiveshell.py"", line 3265, in run_code +exec(code_obj, self.user_global_ns, self.user_ns) +File """", line 26, in +train() +File """", line 23, in train +svi.step(xs, prior_loc, prior_scale) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\svi.py"", line 99, in step +loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\trace_elbo.py"", line 136, in loss_and_grads +surrogate_loss_particle.backward(retain_graph=self.retain_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\tensor.py"", line 107, in backward +torch.autograd.backward(self, gradient, retain_graph, create_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\autograd\\__init__.py"", line 93, in backward +allow_unreachable=True) # allow_unreachable flag +RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor",RuntimeError +" def __init__(self, model, prefix=""auto"", init_loc_fn=init_to_median, rank=1): + if not isinstance(rank, numbers.Number) or not rank > 0: + raise ValueError(""Expected rank > 0 but got {}"".format(rank)) + self.rank = rank + super(AutoLowRankMultivariateNormal, self).__init__( + model, prefix=prefix, init_loc_fn=init_loc_fn)"," def __init__(self, model, prefix=""auto"", rank=1): + if not isinstance(rank, numbers.Number) or not rank > 0: + raise ValueError(""Expected rank > 0 but got {}"".format(rank)) + self.rank = rank + super(AutoLowRankMultivariateNormal, self).__init__(model, prefix)","[{'piece_type': 'source code', 'piece_content': 'import pyro\\nimport pyro.distributions as dist\\nimport torch\\nfrom pyro.contrib.autoguide import AutoDiagonalNormal\\nfrom pyro.infer import SVI, Trace_ELBO\\nfrom pyro.optim import Adam\\n\\n\\ndef model(xs, prior_loc, prior_scale):\\nmu = pyro.sample(\\'mu\\', dist.Normal(prior_loc, prior_scale))\\nreturn pyro.sample(\\'obs\\', dist.Normal(mu, prior_scale), obs=xs)\\n\\n\\ndef train():\\nxs = torch.tensor([5, 5.5, 5.6, 5.8, 6.3], device=\\'cuda\\')\\nprior_loc = torch.tensor(0.0, device=\\'cuda\\')\\nprior_scale = torch.tensor(1.0, device=\\'cuda\\')\\nguide = AutoDiagonalNormal(model)\\noptim = Adam({\\'lr\\': 1e-3})\\nloss = Trace_ELBO()\\nsvi = SVI(model, guide, optim, loss)\\nsvi.step(xs, prior_loc, prior_scale)\\n\\nif __name__ == ""__main__"":\\ntrain()'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\IPython\\\\core\\\\interactiveshell.py"", line 3265, in run_code\\nexec(code_obj, self.user_global_ns, self.user_ns)\\nFile """", line 26, in \\ntrain()\\nFile """", line 23, in train\\nsvi.step(xs, prior_loc, prior_scale)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\svi.py"", line 99, in step\\nloss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\trace_elbo.py"", line 136, in loss_and_grads\\nsurrogate_loss_particle.backward(retain_graph=self.retain_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\tensor.py"", line 107, in backward\\ntorch.autograd.backward(self, gradient, retain_graph, create_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\autograd\\\\__init__.py"", line 93, in backward\\nallow_unreachable=True) # allow_unreachable flag\\nRuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor'}]","Traceback (most recent call last): +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\IPython\\core\\interactiveshell.py"", line 3265, in run_code +exec(code_obj, self.user_global_ns, self.user_ns) +File """", line 26, in +train() +File """", line 23, in train +svi.step(xs, prior_loc, prior_scale) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\svi.py"", line 99, in step +loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\trace_elbo.py"", line 136, in loss_and_grads +surrogate_loss_particle.backward(retain_graph=self.retain_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\tensor.py"", line 107, in backward +torch.autograd.backward(self, gradient, retain_graph, create_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\autograd\\__init__.py"", line 93, in backward +allow_unreachable=True) # allow_unreachable flag +RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor",RuntimeError +" def get_posterior(self, *args, **kwargs): + """""" + Returns a LowRankMultivariateNormal posterior distribution. + """""" + loc = pyro.param(""{}_loc"".format(self.prefix), self._init_loc) + factor = pyro.param(""{}_cov_factor"".format(self.prefix), + lambda: loc.new_empty(self.latent_dim, self.rank).normal_(0, (0.5 / self.rank) ** 0.5)) + diagonal = pyro.param(""{}_cov_diag"".format(self.prefix), + lambda: loc.new_full((self.latent_dim,), 0.5), + constraint=constraints.positive) + return dist.LowRankMultivariateNormal(loc, factor, diagonal)"," def get_posterior(self, *args, **kwargs): + """""" + Returns a LowRankMultivariateNormal posterior distribution. + """""" + loc = pyro.param(""{}_loc"".format(self.prefix), + lambda: torch.zeros(self.latent_dim)) + factor = pyro.param(""{}_cov_factor"".format(self.prefix), + lambda: torch.randn(self.latent_dim, self.rank) * (0.5 / self.rank) ** 0.5) + diagonal = pyro.param(""{}_cov_diag"".format(self.prefix), + lambda: torch.ones(self.latent_dim) * 0.5, + constraint=constraints.positive) + return dist.LowRankMultivariateNormal(loc, factor, diagonal)","[{'piece_type': 'source code', 'piece_content': 'import pyro\\nimport pyro.distributions as dist\\nimport torch\\nfrom pyro.contrib.autoguide import AutoDiagonalNormal\\nfrom pyro.infer import SVI, Trace_ELBO\\nfrom pyro.optim import Adam\\n\\n\\ndef model(xs, prior_loc, prior_scale):\\nmu = pyro.sample(\\'mu\\', dist.Normal(prior_loc, prior_scale))\\nreturn pyro.sample(\\'obs\\', dist.Normal(mu, prior_scale), obs=xs)\\n\\n\\ndef train():\\nxs = torch.tensor([5, 5.5, 5.6, 5.8, 6.3], device=\\'cuda\\')\\nprior_loc = torch.tensor(0.0, device=\\'cuda\\')\\nprior_scale = torch.tensor(1.0, device=\\'cuda\\')\\nguide = AutoDiagonalNormal(model)\\noptim = Adam({\\'lr\\': 1e-3})\\nloss = Trace_ELBO()\\nsvi = SVI(model, guide, optim, loss)\\nsvi.step(xs, prior_loc, prior_scale)\\n\\nif __name__ == ""__main__"":\\ntrain()'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\IPython\\\\core\\\\interactiveshell.py"", line 3265, in run_code\\nexec(code_obj, self.user_global_ns, self.user_ns)\\nFile """", line 26, in \\ntrain()\\nFile """", line 23, in train\\nsvi.step(xs, prior_loc, prior_scale)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\svi.py"", line 99, in step\\nloss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\trace_elbo.py"", line 136, in loss_and_grads\\nsurrogate_loss_particle.backward(retain_graph=self.retain_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\tensor.py"", line 107, in backward\\ntorch.autograd.backward(self, gradient, retain_graph, create_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\autograd\\\\__init__.py"", line 93, in backward\\nallow_unreachable=True) # allow_unreachable flag\\nRuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor'}]","Traceback (most recent call last): +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\IPython\\core\\interactiveshell.py"", line 3265, in run_code +exec(code_obj, self.user_global_ns, self.user_ns) +File """", line 26, in +train() +File """", line 23, in train +svi.step(xs, prior_loc, prior_scale) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\svi.py"", line 99, in step +loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\trace_elbo.py"", line 136, in loss_and_grads +surrogate_loss_particle.backward(retain_graph=self.retain_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\tensor.py"", line 107, in backward +torch.autograd.backward(self, gradient, retain_graph, create_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\autograd\\__init__.py"", line 93, in backward +allow_unreachable=True) # allow_unreachable flag +RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor",RuntimeError +" def __init__(self, model, hidden_dim=None, prefix=""auto"", init_loc_fn=init_to_median): + self.hidden_dim = hidden_dim + self.arn = None + super(AutoIAFNormal, self).__init__(model, prefix=prefix, init_loc_fn=init_loc_fn)"," def __init__(self, model, hidden_dim=None, prefix=""auto""): + self.hidden_dim = hidden_dim + self.arn = None + super(AutoIAFNormal, self).__init__(model, prefix)","[{'piece_type': 'source code', 'piece_content': 'import pyro\\nimport pyro.distributions as dist\\nimport torch\\nfrom pyro.contrib.autoguide import AutoDiagonalNormal\\nfrom pyro.infer import SVI, Trace_ELBO\\nfrom pyro.optim import Adam\\n\\n\\ndef model(xs, prior_loc, prior_scale):\\nmu = pyro.sample(\\'mu\\', dist.Normal(prior_loc, prior_scale))\\nreturn pyro.sample(\\'obs\\', dist.Normal(mu, prior_scale), obs=xs)\\n\\n\\ndef train():\\nxs = torch.tensor([5, 5.5, 5.6, 5.8, 6.3], device=\\'cuda\\')\\nprior_loc = torch.tensor(0.0, device=\\'cuda\\')\\nprior_scale = torch.tensor(1.0, device=\\'cuda\\')\\nguide = AutoDiagonalNormal(model)\\noptim = Adam({\\'lr\\': 1e-3})\\nloss = Trace_ELBO()\\nsvi = SVI(model, guide, optim, loss)\\nsvi.step(xs, prior_loc, prior_scale)\\n\\nif __name__ == ""__main__"":\\ntrain()'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\IPython\\\\core\\\\interactiveshell.py"", line 3265, in run_code\\nexec(code_obj, self.user_global_ns, self.user_ns)\\nFile """", line 26, in \\ntrain()\\nFile """", line 23, in train\\nsvi.step(xs, prior_loc, prior_scale)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\svi.py"", line 99, in step\\nloss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\trace_elbo.py"", line 136, in loss_and_grads\\nsurrogate_loss_particle.backward(retain_graph=self.retain_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\tensor.py"", line 107, in backward\\ntorch.autograd.backward(self, gradient, retain_graph, create_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\autograd\\\\__init__.py"", line 93, in backward\\nallow_unreachable=True) # allow_unreachable flag\\nRuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor'}]","Traceback (most recent call last): +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\IPython\\core\\interactiveshell.py"", line 3265, in run_code +exec(code_obj, self.user_global_ns, self.user_ns) +File """", line 26, in +train() +File """", line 23, in train +svi.step(xs, prior_loc, prior_scale) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\svi.py"", line 99, in step +loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\trace_elbo.py"", line 136, in loss_and_grads +surrogate_loss_particle.backward(retain_graph=self.retain_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\tensor.py"", line 107, in backward +torch.autograd.backward(self, gradient, retain_graph, create_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\autograd\\__init__.py"", line 93, in backward +allow_unreachable=True) # allow_unreachable flag +RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor",RuntimeError +" def get_posterior(self, *args, **kwargs): + """""" + Returns a Delta posterior distribution for MAP inference. + """""" + loc = pyro.param(""{}_loc"".format(self.prefix), self._init_loc) + return dist.Delta(loc).to_event(1)"," def get_posterior(self, *args, **kwargs): + """""" + Returns a Delta posterior distribution for MAP inference. + """""" + loc = pyro.param(""{}_loc"".format(self.prefix), + lambda: torch.zeros(self.latent_dim)) + return dist.Delta(loc).to_event(1)","[{'piece_type': 'source code', 'piece_content': 'import pyro\\nimport pyro.distributions as dist\\nimport torch\\nfrom pyro.contrib.autoguide import AutoDiagonalNormal\\nfrom pyro.infer import SVI, Trace_ELBO\\nfrom pyro.optim import Adam\\n\\n\\ndef model(xs, prior_loc, prior_scale):\\nmu = pyro.sample(\\'mu\\', dist.Normal(prior_loc, prior_scale))\\nreturn pyro.sample(\\'obs\\', dist.Normal(mu, prior_scale), obs=xs)\\n\\n\\ndef train():\\nxs = torch.tensor([5, 5.5, 5.6, 5.8, 6.3], device=\\'cuda\\')\\nprior_loc = torch.tensor(0.0, device=\\'cuda\\')\\nprior_scale = torch.tensor(1.0, device=\\'cuda\\')\\nguide = AutoDiagonalNormal(model)\\noptim = Adam({\\'lr\\': 1e-3})\\nloss = Trace_ELBO()\\nsvi = SVI(model, guide, optim, loss)\\nsvi.step(xs, prior_loc, prior_scale)\\n\\nif __name__ == ""__main__"":\\ntrain()'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\IPython\\\\core\\\\interactiveshell.py"", line 3265, in run_code\\nexec(code_obj, self.user_global_ns, self.user_ns)\\nFile """", line 26, in \\ntrain()\\nFile """", line 23, in train\\nsvi.step(xs, prior_loc, prior_scale)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\svi.py"", line 99, in step\\nloss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\pyro\\\\infer\\\\trace_elbo.py"", line 136, in loss_and_grads\\nsurrogate_loss_particle.backward(retain_graph=self.retain_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\tensor.py"", line 107, in backward\\ntorch.autograd.backward(self, gradient, retain_graph, create_graph)\\nFile ""C:\\\\tools\\\\miniconda3\\\\envs\\\\scanner-pyro\\\\lib\\\\site-packages\\\\torch\\\\autograd\\\\__init__.py"", line 93, in backward\\nallow_unreachable=True) # allow_unreachable flag\\nRuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor'}]","Traceback (most recent call last): +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\IPython\\core\\interactiveshell.py"", line 3265, in run_code +exec(code_obj, self.user_global_ns, self.user_ns) +File """", line 26, in +train() +File """", line 23, in train +svi.step(xs, prior_loc, prior_scale) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\svi.py"", line 99, in step +loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\pyro\\infer\\trace_elbo.py"", line 136, in loss_and_grads +surrogate_loss_particle.backward(retain_graph=self.retain_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\tensor.py"", line 107, in backward +torch.autograd.backward(self, gradient, retain_graph, create_graph) +File ""C:\\tools\\miniconda3\\envs\\scanner-pyro\\lib\\site-packages\\torch\\autograd\\__init__.py"", line 93, in backward +allow_unreachable=True) # allow_unreachable flag +RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor",RuntimeError +"def main(args): + baseball_dataset = pd.read_csv(DATA_URL, ""\\t"") + train, _, player_names = train_test_split(baseball_dataset) + at_bats, hits = train[:, 0], train[:, 1] + nuts_kernel = NUTS(conditioned_model) + logging.info(""Original Dataset:"") + logging.info(baseball_dataset) + + # (1) Full Pooling Model + posterior_fully_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(fully_pooled, at_bats, hits) + logging.info(""\\nModel: Fully Pooled"") + logging.info(""==================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_fully_pooled, sites=[""phi""], player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(fully_pooled, + posterior_fully_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(fully_pooled, posterior_fully_pooled, baseball_dataset) + + # (2) No Pooling Model + posterior_not_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(not_pooled, at_bats, hits) + logging.info(""\\nModel: Not Pooled"") + logging.info(""================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_not_pooled, sites=[""phi""], player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(not_pooled, + posterior_not_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(not_pooled, posterior_not_pooled, baseball_dataset) + + # (3) Partially Pooled Model + # TODO: remove once htps://github.com/uber/pyro/issues/1458 is resolved + if ""CI"" not in os.environ: + posterior_partially_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(partially_pooled, at_bats, hits) + logging.info(""\\nModel: Partially Pooled"") + logging.info(""======================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_partially_pooled, sites=[""phi""], + player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(partially_pooled, + posterior_partially_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(partially_pooled, posterior_partially_pooled, baseball_dataset) + + # (4) Partially Pooled with Logit Model + posterior_partially_pooled_with_logit = MCMC(nuts_kernel, num_samples=args.num_samples, + warmup_steps=args.warmup_steps) \\ + .run(partially_pooled_with_logit, at_bats, hits) + logging.info(""\\nModel: Partially Pooled with Logit"") + logging.info(""=================================="") + logging.info(""\\nSigmoid(alpha):"") + logging.info(summary(posterior_partially_pooled_with_logit, + sites=[""alpha""], + player_names=player_names, + transforms={""alpha"": lambda x: 1. / (1 + np.exp(-x))})[""alpha""]) + posterior_predictive = TracePredictive(partially_pooled_with_logit, + posterior_partially_pooled_with_logit, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(partially_pooled_with_logit, + posterior_partially_pooled_with_logit, baseball_dataset)","def main(args): + baseball_dataset = pd.read_csv(DATA_URL, ""\\t"") + train, _, player_names = train_test_split(baseball_dataset) + at_bats, hits = train[:, 0], train[:, 1] + nuts_kernel = NUTS(conditioned_model) + logging.info(""Original Dataset:"") + logging.info(baseball_dataset) + + # (1) Full Pooling Model + posterior_fully_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(fully_pooled, at_bats, hits) + logging.info(""\\nModel: Fully Pooled"") + logging.info(""==================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_fully_pooled, sites=[""phi""], player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(fully_pooled, + posterior_fully_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(fully_pooled, posterior_fully_pooled, baseball_dataset) + + # (2) No Pooling Model + posterior_not_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(not_pooled, at_bats, hits) + logging.info(""\\nModel: Not Pooled"") + logging.info(""================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_not_pooled, sites=[""phi""], player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(not_pooled, + posterior_not_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(not_pooled, posterior_not_pooled, baseball_dataset) + + # (3) Partially Pooled Model + posterior_partially_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(partially_pooled, at_bats, hits) + logging.info(""\\nModel: Partially Pooled"") + logging.info(""======================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_partially_pooled, sites=[""phi""], + player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(partially_pooled, + posterior_partially_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(partially_pooled, posterior_partially_pooled, baseball_dataset) + + # (4) Partially Pooled with Logit Model + posterior_partially_pooled_with_logit = MCMC(nuts_kernel, num_samples=args.num_samples, + warmup_steps=args.warmup_steps) \\ + .run(partially_pooled_with_logit, at_bats, hits) + logging.info(""\\nModel: Partially Pooled with Logit"") + logging.info(""=================================="") + logging.info(""\\nSigmoid(alpha):"") + logging.info(summary(posterior_partially_pooled_with_logit, + sites=[""alpha""], + player_names=player_names, + transforms={""alpha"": lambda x: 1. / (1 + np.exp(-x))})[""alpha""]) + posterior_predictive = TracePredictive(partially_pooled_with_logit, + posterior_partially_pooled_with_logit, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(partially_pooled_with_logit, + posterior_partially_pooled_with_logit, baseball_dataset)","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 128, in log_prob_sum\\nlog_p = site[""log_prob_sum""]\\nKeyError: \\'log_prob_sum\\'\\nDuring handling of the above exception, another exception occurred:\\nTraceback (most recent call last):\\nFile ""/home/travis/build/uber/pyro/examples/baseball.py"", line 309, in \\nmain(args)\\nFile ""/home/travis/build/uber/pyro/examples/baseball.py"", line 272, in main\\n.run(partially_pooled, at_bats, hits)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/abstract_infer.py"", line 84, in run\\nfor tr, logit in self._traces(*args, **kwargs):\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 51, in _traces\\nfor trace in self._gen_samples(self.num_samples, trace):\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 35, in _gen_samples\\ntrace = self.kernel.sample(trace)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 276, in sample\\ndirection, tree_depth, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 159, in _build_tree\\ndirection, tree_depth-1, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree\\ndirection, tree_depth-1, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree\\ndirection, tree_depth-1, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 155, in _build_tree\\nreturn self._build_basetree(z, r, z_grads, log_slice, direction, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 130, in _build_basetree\\nz, r, self._potential_energy, self._inverse_mass_matrix, step_size, z_grads=z_grads)\\nFile ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 68, in single_step_velocity_verlet\\nz_grads, potential_energy = _potential_grad(potential_fn, z_next)\\nFile ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 79, in _potential_grad\\npotential_energy = potential_fn(z)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 170, in _potential_energy\\npotential_energy = -self._compute_trace_log_prob(trace)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 154, in _compute_trace_log_prob\\nreturn self._trace_prob_evaluator.log_prob(model_trace)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/util.py"", line 132, in log_prob\\nreturn model_trace.log_prob_sum()\\nFile ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 130, in log_prob_sum\\nlog_p = site[""fn""].log_prob(site[""value""], *site[""args""], **site[""kwargs""])\\nFile ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/transformed_distribution.py"", line 86, in log_prob\\nlog_prob += _sum_rightmost(self.base_dist.log_prob(y),\\nFile ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/exponential.py"", line 51, in log_prob\\nself._validate_sample(value)\\nFile ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/distribution.py"", line 221, in _validate_sample\\nraise ValueError(\\'The value argument must be within the support\\')'}]","Traceback (most recent call last): +File ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 128, in log_prob_sum +log_p = site[""log_prob_sum""] +KeyError: 'log_prob_sum' +During handling of the above exception, another exception occurred: +Traceback (most recent call last): +File ""/home/travis/build/uber/pyro/examples/baseball.py"", line 309, in +main(args) +File ""/home/travis/build/uber/pyro/examples/baseball.py"", line 272, in main +.run(partially_pooled, at_bats, hits) +File ""/home/travis/build/uber/pyro/pyro/infer/abstract_infer.py"", line 84, in run +for tr, logit in self._traces(*args, **kwargs): +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 51, in _traces +for trace in self._gen_samples(self.num_samples, trace): +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 35, in _gen_samples +trace = self.kernel.sample(trace) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 276, in sample +direction, tree_depth, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 159, in _build_tree +direction, tree_depth-1, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree +direction, tree_depth-1, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree +direction, tree_depth-1, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 155, in _build_tree +return self._build_basetree(z, r, z_grads, log_slice, direction, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 130, in _build_basetree +z, r, self._potential_energy, self._inverse_mass_matrix, step_size, z_grads=z_grads) +File ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 68, in single_step_velocity_verlet +z_grads, potential_energy = _potential_grad(potential_fn, z_next) +File ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 79, in _potential_grad +potential_energy = potential_fn(z) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 170, in _potential_energy +potential_energy = -self._compute_trace_log_prob(trace) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 154, in _compute_trace_log_prob +return self._trace_prob_evaluator.log_prob(model_trace) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/util.py"", line 132, in log_prob +return model_trace.log_prob_sum() +File ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 130, in log_prob_sum +log_p = site[""fn""].log_prob(site[""value""], *site[""args""], **site[""kwargs""]) +File ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/transformed_distribution.py"", line 86, in log_prob +log_prob += _sum_rightmost(self.base_dist.log_prob(y), +File ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/exponential.py"", line 51, in log_prob +self._validate_sample(value) +File ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/distribution.py"", line 221, in _validate_sample +raise ValueError('The value argument must be within the support')",KeyError +"def main(args): + pyro.set_rng_seed(args.rng_seed) + baseball_dataset = pd.read_csv(DATA_URL, ""\\t"") + train, _, player_names = train_test_split(baseball_dataset) + at_bats, hits = train[:, 0], train[:, 1] + nuts_kernel = NUTS(conditioned_model) + logging.info(""Original Dataset:"") + logging.info(baseball_dataset) + + # (1) Full Pooling Model + posterior_fully_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(fully_pooled, at_bats, hits) + logging.info(""\\nModel: Fully Pooled"") + logging.info(""==================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_fully_pooled, sites=[""phi""], player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(fully_pooled, + posterior_fully_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(fully_pooled, posterior_fully_pooled, baseball_dataset) + + # (2) No Pooling Model + posterior_not_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(not_pooled, at_bats, hits) + logging.info(""\\nModel: Not Pooled"") + logging.info(""================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_not_pooled, sites=[""phi""], player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(not_pooled, + posterior_not_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(not_pooled, posterior_not_pooled, baseball_dataset) + + # (3) Partially Pooled Model + # TODO: remove once htps://github.com/uber/pyro/issues/1458 is resolved + if ""CI"" not in os.environ: + posterior_partially_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(partially_pooled, at_bats, hits) + logging.info(""\\nModel: Partially Pooled"") + logging.info(""======================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_partially_pooled, sites=[""phi""], + player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(partially_pooled, + posterior_partially_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(partially_pooled, posterior_partially_pooled, baseball_dataset) + + # (4) Partially Pooled with Logit Model + posterior_partially_pooled_with_logit = MCMC(nuts_kernel, num_samples=args.num_samples, + warmup_steps=args.warmup_steps) \\ + .run(partially_pooled_with_logit, at_bats, hits) + logging.info(""\\nModel: Partially Pooled with Logit"") + logging.info(""=================================="") + logging.info(""\\nSigmoid(alpha):"") + logging.info(summary(posterior_partially_pooled_with_logit, + sites=[""alpha""], + player_names=player_names, + transforms={""alpha"": lambda x: 1. / (1 + np.exp(-x))})[""alpha""]) + posterior_predictive = TracePredictive(partially_pooled_with_logit, + posterior_partially_pooled_with_logit, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(partially_pooled_with_logit, + posterior_partially_pooled_with_logit, baseball_dataset)","def main(args): + baseball_dataset = pd.read_csv(DATA_URL, ""\\t"") + train, _, player_names = train_test_split(baseball_dataset) + at_bats, hits = train[:, 0], train[:, 1] + nuts_kernel = NUTS(conditioned_model) + logging.info(""Original Dataset:"") + logging.info(baseball_dataset) + + # (1) Full Pooling Model + posterior_fully_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(fully_pooled, at_bats, hits) + logging.info(""\\nModel: Fully Pooled"") + logging.info(""==================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_fully_pooled, sites=[""phi""], player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(fully_pooled, + posterior_fully_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(fully_pooled, posterior_fully_pooled, baseball_dataset) + + # (2) No Pooling Model + posterior_not_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(not_pooled, at_bats, hits) + logging.info(""\\nModel: Not Pooled"") + logging.info(""================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_not_pooled, sites=[""phi""], player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(not_pooled, + posterior_not_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(not_pooled, posterior_not_pooled, baseball_dataset) + + # (3) Partially Pooled Model + # TODO: remove once htps://github.com/uber/pyro/issues/1458 is resolved + if ""CI"" not in os.environ: + posterior_partially_pooled = MCMC(nuts_kernel, num_samples=args.num_samples, warmup_steps=args.warmup_steps) \\ + .run(partially_pooled, at_bats, hits) + logging.info(""\\nModel: Partially Pooled"") + logging.info(""======================="") + logging.info(""\\nphi:"") + logging.info(summary(posterior_partially_pooled, sites=[""phi""], + player_names=player_names)[""phi""]) + posterior_predictive = TracePredictive(partially_pooled, + posterior_partially_pooled, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(partially_pooled, posterior_partially_pooled, baseball_dataset) + + # (4) Partially Pooled with Logit Model + posterior_partially_pooled_with_logit = MCMC(nuts_kernel, num_samples=args.num_samples, + warmup_steps=args.warmup_steps) \\ + .run(partially_pooled_with_logit, at_bats, hits) + logging.info(""\\nModel: Partially Pooled with Logit"") + logging.info(""=================================="") + logging.info(""\\nSigmoid(alpha):"") + logging.info(summary(posterior_partially_pooled_with_logit, + sites=[""alpha""], + player_names=player_names, + transforms={""alpha"": lambda x: 1. / (1 + np.exp(-x))})[""alpha""]) + posterior_predictive = TracePredictive(partially_pooled_with_logit, + posterior_partially_pooled_with_logit, + num_samples=args.num_samples) + sample_posterior_predictive(posterior_predictive, baseball_dataset) + evaluate_log_predictive_density(partially_pooled_with_logit, + posterior_partially_pooled_with_logit, baseball_dataset)","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 128, in log_prob_sum\\nlog_p = site[""log_prob_sum""]\\nKeyError: \\'log_prob_sum\\'\\nDuring handling of the above exception, another exception occurred:\\nTraceback (most recent call last):\\nFile ""/home/travis/build/uber/pyro/examples/baseball.py"", line 309, in \\nmain(args)\\nFile ""/home/travis/build/uber/pyro/examples/baseball.py"", line 272, in main\\n.run(partially_pooled, at_bats, hits)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/abstract_infer.py"", line 84, in run\\nfor tr, logit in self._traces(*args, **kwargs):\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 51, in _traces\\nfor trace in self._gen_samples(self.num_samples, trace):\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 35, in _gen_samples\\ntrace = self.kernel.sample(trace)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 276, in sample\\ndirection, tree_depth, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 159, in _build_tree\\ndirection, tree_depth-1, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree\\ndirection, tree_depth-1, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree\\ndirection, tree_depth-1, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 155, in _build_tree\\nreturn self._build_basetree(z, r, z_grads, log_slice, direction, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 130, in _build_basetree\\nz, r, self._potential_energy, self._inverse_mass_matrix, step_size, z_grads=z_grads)\\nFile ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 68, in single_step_velocity_verlet\\nz_grads, potential_energy = _potential_grad(potential_fn, z_next)\\nFile ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 79, in _potential_grad\\npotential_energy = potential_fn(z)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 170, in _potential_energy\\npotential_energy = -self._compute_trace_log_prob(trace)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 154, in _compute_trace_log_prob\\nreturn self._trace_prob_evaluator.log_prob(model_trace)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/util.py"", line 132, in log_prob\\nreturn model_trace.log_prob_sum()\\nFile ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 130, in log_prob_sum\\nlog_p = site[""fn""].log_prob(site[""value""], *site[""args""], **site[""kwargs""])\\nFile ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/transformed_distribution.py"", line 86, in log_prob\\nlog_prob += _sum_rightmost(self.base_dist.log_prob(y),\\nFile ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/exponential.py"", line 51, in log_prob\\nself._validate_sample(value)\\nFile ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/distribution.py"", line 221, in _validate_sample\\nraise ValueError(\\'The value argument must be within the support\\')'}]","Traceback (most recent call last): +File ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 128, in log_prob_sum +log_p = site[""log_prob_sum""] +KeyError: 'log_prob_sum' +During handling of the above exception, another exception occurred: +Traceback (most recent call last): +File ""/home/travis/build/uber/pyro/examples/baseball.py"", line 309, in +main(args) +File ""/home/travis/build/uber/pyro/examples/baseball.py"", line 272, in main +.run(partially_pooled, at_bats, hits) +File ""/home/travis/build/uber/pyro/pyro/infer/abstract_infer.py"", line 84, in run +for tr, logit in self._traces(*args, **kwargs): +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 51, in _traces +for trace in self._gen_samples(self.num_samples, trace): +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 35, in _gen_samples +trace = self.kernel.sample(trace) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 276, in sample +direction, tree_depth, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 159, in _build_tree +direction, tree_depth-1, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree +direction, tree_depth-1, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree +direction, tree_depth-1, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 155, in _build_tree +return self._build_basetree(z, r, z_grads, log_slice, direction, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 130, in _build_basetree +z, r, self._potential_energy, self._inverse_mass_matrix, step_size, z_grads=z_grads) +File ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 68, in single_step_velocity_verlet +z_grads, potential_energy = _potential_grad(potential_fn, z_next) +File ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 79, in _potential_grad +potential_energy = potential_fn(z) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 170, in _potential_energy +potential_energy = -self._compute_trace_log_prob(trace) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 154, in _compute_trace_log_prob +return self._trace_prob_evaluator.log_prob(model_trace) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/util.py"", line 132, in log_prob +return model_trace.log_prob_sum() +File ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 130, in log_prob_sum +log_p = site[""fn""].log_prob(site[""value""], *site[""args""], **site[""kwargs""]) +File ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/transformed_distribution.py"", line 86, in log_prob +log_prob += _sum_rightmost(self.base_dist.log_prob(y), +File ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/exponential.py"", line 51, in log_prob +self._validate_sample(value) +File ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/distribution.py"", line 221, in _validate_sample +raise ValueError('The value argument must be within the support')",KeyError +" def _kinetic_energy(self, r): + # TODO: revert to `torch.dot` in pytorch==1.0 + # See: https://github.com/uber/pyro/issues/1458 + r_flat = torch.cat([r[site_name].reshape(-1) for site_name in sorted(r)]) + if self.full_mass: + return 0.5 * (r_flat * (self._inverse_mass_matrix.matmul(r_flat))).sum() + else: + return 0.5 * (self._inverse_mass_matrix * (r_flat ** 2)).sum()"," def _kinetic_energy(self, r): + r_flat = torch.cat([r[site_name].reshape(-1) for site_name in sorted(r)]) + if self.full_mass: + return 0.5 * r_flat.dot(self._inverse_mass_matrix.matmul(r_flat)) + else: + return 0.5 * self._inverse_mass_matrix.dot(r_flat ** 2)","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 128, in log_prob_sum\\nlog_p = site[""log_prob_sum""]\\nKeyError: \\'log_prob_sum\\'\\nDuring handling of the above exception, another exception occurred:\\nTraceback (most recent call last):\\nFile ""/home/travis/build/uber/pyro/examples/baseball.py"", line 309, in \\nmain(args)\\nFile ""/home/travis/build/uber/pyro/examples/baseball.py"", line 272, in main\\n.run(partially_pooled, at_bats, hits)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/abstract_infer.py"", line 84, in run\\nfor tr, logit in self._traces(*args, **kwargs):\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 51, in _traces\\nfor trace in self._gen_samples(self.num_samples, trace):\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 35, in _gen_samples\\ntrace = self.kernel.sample(trace)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 276, in sample\\ndirection, tree_depth, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 159, in _build_tree\\ndirection, tree_depth-1, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree\\ndirection, tree_depth-1, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree\\ndirection, tree_depth-1, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 155, in _build_tree\\nreturn self._build_basetree(z, r, z_grads, log_slice, direction, energy_current)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 130, in _build_basetree\\nz, r, self._potential_energy, self._inverse_mass_matrix, step_size, z_grads=z_grads)\\nFile ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 68, in single_step_velocity_verlet\\nz_grads, potential_energy = _potential_grad(potential_fn, z_next)\\nFile ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 79, in _potential_grad\\npotential_energy = potential_fn(z)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 170, in _potential_energy\\npotential_energy = -self._compute_trace_log_prob(trace)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 154, in _compute_trace_log_prob\\nreturn self._trace_prob_evaluator.log_prob(model_trace)\\nFile ""/home/travis/build/uber/pyro/pyro/infer/mcmc/util.py"", line 132, in log_prob\\nreturn model_trace.log_prob_sum()\\nFile ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 130, in log_prob_sum\\nlog_p = site[""fn""].log_prob(site[""value""], *site[""args""], **site[""kwargs""])\\nFile ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/transformed_distribution.py"", line 86, in log_prob\\nlog_prob += _sum_rightmost(self.base_dist.log_prob(y),\\nFile ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/exponential.py"", line 51, in log_prob\\nself._validate_sample(value)\\nFile ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/distribution.py"", line 221, in _validate_sample\\nraise ValueError(\\'The value argument must be within the support\\')'}]","Traceback (most recent call last): +File ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 128, in log_prob_sum +log_p = site[""log_prob_sum""] +KeyError: 'log_prob_sum' +During handling of the above exception, another exception occurred: +Traceback (most recent call last): +File ""/home/travis/build/uber/pyro/examples/baseball.py"", line 309, in +main(args) +File ""/home/travis/build/uber/pyro/examples/baseball.py"", line 272, in main +.run(partially_pooled, at_bats, hits) +File ""/home/travis/build/uber/pyro/pyro/infer/abstract_infer.py"", line 84, in run +for tr, logit in self._traces(*args, **kwargs): +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 51, in _traces +for trace in self._gen_samples(self.num_samples, trace): +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/mcmc.py"", line 35, in _gen_samples +trace = self.kernel.sample(trace) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 276, in sample +direction, tree_depth, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 159, in _build_tree +direction, tree_depth-1, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree +direction, tree_depth-1, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 178, in _build_tree +direction, tree_depth-1, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 155, in _build_tree +return self._build_basetree(z, r, z_grads, log_slice, direction, energy_current) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/nuts.py"", line 130, in _build_basetree +z, r, self._potential_energy, self._inverse_mass_matrix, step_size, z_grads=z_grads) +File ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 68, in single_step_velocity_verlet +z_grads, potential_energy = _potential_grad(potential_fn, z_next) +File ""/home/travis/build/uber/pyro/pyro/ops/integrator.py"", line 79, in _potential_grad +potential_energy = potential_fn(z) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 170, in _potential_energy +potential_energy = -self._compute_trace_log_prob(trace) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/hmc.py"", line 154, in _compute_trace_log_prob +return self._trace_prob_evaluator.log_prob(model_trace) +File ""/home/travis/build/uber/pyro/pyro/infer/mcmc/util.py"", line 132, in log_prob +return model_trace.log_prob_sum() +File ""/home/travis/build/uber/pyro/pyro/poutine/trace_struct.py"", line 130, in log_prob_sum +log_p = site[""fn""].log_prob(site[""value""], *site[""args""], **site[""kwargs""]) +File ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/transformed_distribution.py"", line 86, in log_prob +log_prob += _sum_rightmost(self.base_dist.log_prob(y), +File ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/exponential.py"", line 51, in log_prob +self._validate_sample(value) +File ""/home/travis/virtualenv/python3.5.6/lib/python3.5/site-packages/torch/distributions/distribution.py"", line 221, in _validate_sample +raise ValueError('The value argument must be within the support')",KeyError +" def model(self, xs, ys=None): + """""" + The model corresponds to the following generative process: + p(z) = normal(0,I) # handwriting style (latent) + p(y|x) = categorical(I/10.) # which digit (semi-supervised) + p(x|y,z) = bernoulli(mu(y,z)) # an image + mu is given by a neural network `decoder` + + :param xs: a batch of scaled vectors of pixels from an image + :param ys: (optional) a batch of the class labels i.e. + the digit corresponding to the image(s) + :return: None + """""" + # register this pytorch module and all of its sub-modules with pyro + pyro.module(""ss_vae"", self) + + batch_size = xs.size(0) + with pyro.iarange(""independent""): + + # sample the handwriting style from the constant prior distribution + prior_mu = Variable(torch.zeros([batch_size, self.z_dim])) + prior_sigma = Variable(torch.ones([batch_size, self.z_dim])) + zs = pyro.sample(""z"", dist.normal, prior_mu, prior_sigma, extra_event_dims=1) + + # if the label y (which digit to write) is supervised, sample from the + # constant prior, otherwise, observe the value (i.e. score it against the constant prior) + alpha_prior = Variable(torch.ones([batch_size, self.output_size]) / (1.0 * self.output_size)) + if ys is None: + ys = pyro.sample(""y"", dist.one_hot_categorical, alpha_prior) + else: + pyro.sample(""y"", dist.one_hot_categorical, alpha_prior, obs=ys) + + # finally, score the image (x) using the handwriting style (z) and + # the class label y (which digit to write) against the + # parametrized distribution p(x|y,z) = bernoulli(decoder(y,z)) + # where `decoder` is a neural network + mu = self.decoder.forward([zs, ys]) + pyro.sample(""x"", dist.bernoulli, mu, extra_event_dims=1, obs=xs)"," def model(self, xs, ys=None): + """""" + The model corresponds to the following generative process: + p(z) = normal(0,I) # handwriting style (latent) + p(y|x) = categorical(I/10.) # which digit (semi-supervised) + p(x|y,z) = bernoulli(mu(y,z)) # an image + mu is given by a neural network `decoder` + + :param xs: a batch of scaled vectors of pixels from an image + :param ys: (optional) a batch of the class labels i.e. + the digit corresponding to the image(s) + :return: None + """""" + # register this pytorch module and all of its sub-modules with pyro + pyro.module(""ss_vae"", self) + + batch_size = xs.size(0) + with pyro.iarange(""independent""): + + # sample the handwriting style from the constant prior distribution + prior_mu = Variable(torch.zeros([batch_size, self.z_dim])) + prior_sigma = Variable(torch.ones([batch_size, self.z_dim])) + zs = pyro.sample(""z"", dist.normal, prior_mu, prior_sigma) + + # if the label y (which digit to write) is supervised, sample from the + # constant prior, otherwise, observe the value (i.e. score it against the constant prior) + alpha_prior = Variable(torch.ones([batch_size, self.output_size]) / (1.0 * self.output_size)) + if ys is None: + ys = pyro.sample(""y"", dist.one_hot_categorical, alpha_prior) + else: + pyro.sample(""y"", dist.one_hot_categorical, alpha_prior, obs=ys) + + # finally, score the image (x) using the handwriting style (z) and + # the class label y (which digit to write) against the + # parametrized distribution p(x|y,z) = bernoulli(decoder(y,z)) + # where `decoder` is a neural network + mu = self.decoder.forward([zs, ys]) + pyro.sample(""x"", dist.bernoulli, mu, obs=xs)","[{'piece_type': 'error message', 'piece_content': '$ python ss_vae_M2.py -enum\\nTraceback (most recent call last):\\nFile ""ss_vae_M2.py"", line 464, in \\nrun_inference_ss_vae(args)\\nFile ""ss_vae_M2.py"", line 371, in run_inference_ss_vae\\nrun_inference_for_epoch(data_loaders, losses, periodic_interval_batches)\\nFile ""ss_vae_M2.py"", line 268, in run_inference_for_epoch\\nnew_loss = losses[loss_id].step(xs)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/svi.py"", line 98, in step\\nloss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/elbo.py"", line 65, in loss_and_grads\\nreturn self.which_elbo.loss_and_grads(model, guide, *args, **kwargs)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 146, in loss_and_grads\\nfor weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs):\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 79, in _get_traces\\ncheck_enum_discrete_can_run(model_trace, guide_trace)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 45, in check_enum_discrete_can_run\\nfor shape, (source, name) in sorted(shapes.items())])))\\nNotImplementedError: enum_discrete does not support mixture of batched and un-batched variables. Try rewriting your model to avoid batching or running with enum_discrete=False. Found the following variables of different batch shapes:\\nguide y: shape = (200,)\\nguide z: shape = (200, 50)\\nmodel x: shape = (200, 784)'}]","$ python ss_vae_M2.py -enum +Traceback (most recent call last): +File ""ss_vae_M2.py"", line 464, in +run_inference_ss_vae(args) +File ""ss_vae_M2.py"", line 371, in run_inference_ss_vae +run_inference_for_epoch(data_loaders, losses, periodic_interval_batches) +File ""ss_vae_M2.py"", line 268, in run_inference_for_epoch +new_loss = losses[loss_id].step(xs) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/svi.py"", line 98, in step +loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/elbo.py"", line 65, in loss_and_grads +return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 146, in loss_and_grads +for weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs): +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 79, in _get_traces +check_enum_discrete_can_run(model_trace, guide_trace) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 45, in check_enum_discrete_can_run +for shape, (source, name) in sorted(shapes.items())]))) +NotImplementedError: enum_discrete does not support mixture of batched and un-batched variables. Try rewriting your model to avoid batching or running with enum_discrete=False. Found the following variables of different batch shapes: +guide y: shape = (200,) +guide z: shape = (200, 50) +model x: shape = (200, 784)",NotImplementedError +" def guide(self, xs, ys=None): + """""" + The guide corresponds to the following: + q(y|x) = categorical(alpha(x)) # infer digit from an image + q(z|x,y) = normal(mu(x,y),sigma(x,y)) # infer handwriting style from an image and the digit + mu, sigma are given by a neural network `encoder_z` + alpha is given by a neural network `encoder_y` + :param xs: a batch of scaled vectors of pixels from an image + :param ys: (optional) a batch of the class labels i.e. + the digit corresponding to the image(s) + :return: None + """""" + # inform Pyro that the variables in the batch of xs, ys are conditionally independent + with pyro.iarange(""independent""): + + # if the class label (the digit) is not supervised, sample + # (and score) the digit with the variational distribution + # q(y|x) = categorical(alpha(x)) + if ys is None: + alpha = self.encoder_y.forward(xs) + ys = pyro.sample(""y"", dist.one_hot_categorical, alpha) + + # sample (and score) the latent handwriting-style with the variational + # distribution q(z|x,y) = normal(mu(x,y),sigma(x,y)) + mu, sigma = self.encoder_z.forward([xs, ys]) + pyro.sample(""z"", dist.normal, mu, sigma, extra_event_dims=1)"," def guide(self, xs, ys=None): + """""" + The guide corresponds to the following: + q(y|x) = categorical(alpha(x)) # infer digit from an image + q(z|x,y) = normal(mu(x,y),sigma(x,y)) # infer handwriting style from an image and the digit + mu, sigma are given by a neural network `encoder_z` + alpha is given by a neural network `encoder_y` + :param xs: a batch of scaled vectors of pixels from an image + :param ys: (optional) a batch of the class labels i.e. + the digit corresponding to the image(s) + :return: None + """""" + # inform Pyro that the variables in the batch of xs, ys are conditionally independent + with pyro.iarange(""independent""): + + # if the class label (the digit) is not supervised, sample + # (and score) the digit with the variational distribution + # q(y|x) = categorical(alpha(x)) + if ys is None: + alpha = self.encoder_y.forward(xs) + ys = pyro.sample(""y"", dist.one_hot_categorical, alpha) + + # sample (and score) the latent handwriting-style with the variational + # distribution q(z|x,y) = normal(mu(x,y),sigma(x,y)) + mu, sigma = self.encoder_z.forward([xs, ys]) + zs = pyro.sample(""z"", dist.normal, mu, sigma) # noqa: F841","[{'piece_type': 'error message', 'piece_content': '$ python ss_vae_M2.py -enum\\nTraceback (most recent call last):\\nFile ""ss_vae_M2.py"", line 464, in \\nrun_inference_ss_vae(args)\\nFile ""ss_vae_M2.py"", line 371, in run_inference_ss_vae\\nrun_inference_for_epoch(data_loaders, losses, periodic_interval_batches)\\nFile ""ss_vae_M2.py"", line 268, in run_inference_for_epoch\\nnew_loss = losses[loss_id].step(xs)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/svi.py"", line 98, in step\\nloss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/elbo.py"", line 65, in loss_and_grads\\nreturn self.which_elbo.loss_and_grads(model, guide, *args, **kwargs)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 146, in loss_and_grads\\nfor weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs):\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 79, in _get_traces\\ncheck_enum_discrete_can_run(model_trace, guide_trace)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 45, in check_enum_discrete_can_run\\nfor shape, (source, name) in sorted(shapes.items())])))\\nNotImplementedError: enum_discrete does not support mixture of batched and un-batched variables. Try rewriting your model to avoid batching or running with enum_discrete=False. Found the following variables of different batch shapes:\\nguide y: shape = (200,)\\nguide z: shape = (200, 50)\\nmodel x: shape = (200, 784)'}]","$ python ss_vae_M2.py -enum +Traceback (most recent call last): +File ""ss_vae_M2.py"", line 464, in +run_inference_ss_vae(args) +File ""ss_vae_M2.py"", line 371, in run_inference_ss_vae +run_inference_for_epoch(data_loaders, losses, periodic_interval_batches) +File ""ss_vae_M2.py"", line 268, in run_inference_for_epoch +new_loss = losses[loss_id].step(xs) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/svi.py"", line 98, in step +loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/elbo.py"", line 65, in loss_and_grads +return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 146, in loss_and_grads +for weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs): +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 79, in _get_traces +check_enum_discrete_can_run(model_trace, guide_trace) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 45, in check_enum_discrete_can_run +for shape, (source, name) in sorted(shapes.items())]))) +NotImplementedError: enum_discrete does not support mixture of batched and un-batched variables. Try rewriting your model to avoid batching or running with enum_discrete=False. Found the following variables of different batch shapes: +guide y: shape = (200,) +guide z: shape = (200, 50) +model x: shape = (200, 784)",NotImplementedError +" def model_sample(self, ys, batch_size=1): + # sample the handwriting style from the constant prior distribution + prior_mu = Variable(torch.zeros([batch_size, self.z_dim])) + prior_sigma = Variable(torch.ones([batch_size, self.z_dim])) + zs = pyro.sample(""z"", dist.normal, prior_mu, prior_sigma, extra_event_dims=1) + + # sample an image using the decoder + mu = self.decoder.forward([zs, ys]) + xs = pyro.sample(""sample"", dist.bernoulli, mu, extra_event_dims=1) + return xs, mu"," def model_sample(self, ys, batch_size=1): + # sample the handwriting style from the constant prior distribution + prior_mu = Variable(torch.zeros([batch_size, self.z_dim])) + prior_sigma = Variable(torch.ones([batch_size, self.z_dim])) + zs = pyro.sample(""z"", dist.normal, prior_mu, prior_sigma) + + # sample an image using the decoder + mu = self.decoder.forward([zs, ys]) + xs = pyro.sample(""sample"", dist.bernoulli, mu) + return xs, mu","[{'piece_type': 'error message', 'piece_content': '$ python ss_vae_M2.py -enum\\nTraceback (most recent call last):\\nFile ""ss_vae_M2.py"", line 464, in \\nrun_inference_ss_vae(args)\\nFile ""ss_vae_M2.py"", line 371, in run_inference_ss_vae\\nrun_inference_for_epoch(data_loaders, losses, periodic_interval_batches)\\nFile ""ss_vae_M2.py"", line 268, in run_inference_for_epoch\\nnew_loss = losses[loss_id].step(xs)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/svi.py"", line 98, in step\\nloss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/elbo.py"", line 65, in loss_and_grads\\nreturn self.which_elbo.loss_and_grads(model, guide, *args, **kwargs)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 146, in loss_and_grads\\nfor weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs):\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 79, in _get_traces\\ncheck_enum_discrete_can_run(model_trace, guide_trace)\\nFile ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 45, in check_enum_discrete_can_run\\nfor shape, (source, name) in sorted(shapes.items())])))\\nNotImplementedError: enum_discrete does not support mixture of batched and un-batched variables. Try rewriting your model to avoid batching or running with enum_discrete=False. Found the following variables of different batch shapes:\\nguide y: shape = (200,)\\nguide z: shape = (200, 50)\\nmodel x: shape = (200, 784)'}]","$ python ss_vae_M2.py -enum +Traceback (most recent call last): +File ""ss_vae_M2.py"", line 464, in +run_inference_ss_vae(args) +File ""ss_vae_M2.py"", line 371, in run_inference_ss_vae +run_inference_for_epoch(data_loaders, losses, periodic_interval_batches) +File ""ss_vae_M2.py"", line 268, in run_inference_for_epoch +new_loss = losses[loss_id].step(xs) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/svi.py"", line 98, in step +loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/elbo.py"", line 65, in loss_and_grads +return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 146, in loss_and_grads +for weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs): +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 79, in _get_traces +check_enum_discrete_can_run(model_trace, guide_trace) +File ""/home/jbaik/.pyenv/versions/3.6.4/lib/python3.6/site-packages/pyro_ppl-0.1.2-py3.6.egg/pyro/infer/trace_elbo.py"", line 45, in check_enum_discrete_can_run +for shape, (source, name) in sorted(shapes.items())]))) +NotImplementedError: enum_discrete does not support mixture of batched and un-batched variables. Try rewriting your model to avoid batching or running with enum_discrete=False. Found the following variables of different batch shapes: +guide y: shape = (200,) +guide z: shape = (200, 50) +model x: shape = (200, 784)",NotImplementedError +"def torch_multinomial(input, num_samples, replacement=False): + """""" + Like `torch.multinomial()` but works with cuda tensors. + Does not support keyword argument `out`. + """""" + if input.is_cuda: + return torch.multinomial(input.cpu(), num_samples, replacement).cuda(input.get_device()) + else: + return torch.multinomial(input, num_samples, replacement)","def torch_multinomial(input, num_samples, replacement=False): + """""" + Like `torch.multinomial()` but works with cuda tensors. + Does not support keyword argument `out`. + """""" + if input.is_cuda: + return torch_multinomial(input.cpu(), num_samples, replacement).cuda() + else: + return torch.multinomial(input, num_samples, replacement)","[{'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nRuntimeError Traceback (most recent call last)\\n in ()\\n----> 1 train()\\n\\n in train()\\n33\\n34 # Train and score\\n---> 35 train_loss += svi.step(input_batch, target_batch)\\n36\\n37 # Store history\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs)\\n96 """"""\\n97 # get loss and compute gradients\\n---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\n99\\n100 # get active params\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs)\\n63 :rtype: float\\n64 """"""\\n---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs)\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs)\\n149 guide_site = guide_trace.nodes[name]\\n150 lp_lq = model_site[log_pdf] - guide_site[log_pdf]\\n--> 151 elbo_particle += lp_lq\\n152 if guide_site[""fn""].reparameterized:\\n153 surrogate_elbo_particle += lp_lq\\n\\nRuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 \\'other\\''}, {'piece_type': 'source code', 'piece_content': 'for inputs, targets in train_loader:\\n\\n# Put batch on GPU\\ninput_batch = Variable(inputs.cuda(device=CUDA_ID, async=use_async)) # Pinned memory with async transfer\\ntarget_batch = Variable(targets.cuda(device=CUDA_ID, async=use_async))\\n\\n# Train and score\\ntrain_loss += svi.step(input_batch, target_batch)\\n\\n# Store history\\ntrain_losses += [train_loss / n_train_samples]'}]","--------------------------------------------------------------------------- +RuntimeError Traceback (most recent call last) + in () +----> 1 train() + + in train() +33 +34 # Train and score +---> 35 train_loss += svi.step(input_batch, target_batch) +36 +37 # Store history + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs) +96 """""" +97 # get loss and compute gradients +---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +99 +100 # get active params + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) +63 :rtype: float +64 """""" +---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) +149 guide_site = guide_trace.nodes[name] +150 lp_lq = model_site[log_pdf] - guide_site[log_pdf] +--> 151 elbo_particle += lp_lq +152 if guide_site[""fn""].reparameterized: +153 surrogate_elbo_particle += lp_lq + +RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 'other'",RuntimeError +"def iter_discrete_traces(graph_type, fn, *args, **kwargs): + """""" + Iterate over all discrete choices of a stochastic function. + + When sampling continuous random variables, this behaves like `fn`. + When sampling discrete random variables, this iterates over all choices. + + This yields `(scale, trace)` pairs, where `scale` is the probability of the + discrete choices made in the `trace`. + + :param str graph_type: The type of the graph, e.g. ""flat"" or ""dense"". + :param callable fn: A stochastic function. + :returns: An iterator over (scale, trace) pairs. + """""" + queue = LifoQueue() + queue.put(Trace()) + while not queue.empty(): + partial_trace = queue.get() + escape_fn = functools.partial(util.discrete_escape, partial_trace) + traced_fn = poutine.trace(poutine.escape(poutine.replay(fn, partial_trace), escape_fn), + graph_type=graph_type) + try: + full_trace = traced_fn.get_trace(*args, **kwargs) + except util.NonlocalExit as e: + for extended_trace in util.enum_extend(traced_fn.trace.copy(), e.site): + queue.put(extended_trace) + continue + + # Scale trace by probability of discrete choices. + log_pdf = full_trace.batch_log_pdf(site_filter=site_is_discrete) + if isinstance(log_pdf, Variable): + scale = torch.exp(log_pdf.detach()) + else: + scale = math.exp(log_pdf) + yield scale, full_trace","def iter_discrete_traces(graph_type, fn, *args, **kwargs): + """""" + Iterate over all discrete choices of a stochastic function. + + When sampling continuous random variables, this behaves like `fn`. + When sampling discrete random variables, this iterates over all choices. + + This yields `(scale, trace)` pairs, where `scale` is the probability of the + discrete choices made in the `trace`. + + :param str graph_type: The type of the graph, e.g. ""flat"" or ""dense"". + :param callable fn: A stochastic function. + :returns: An iterator over (scale, trace) pairs. + """""" + queue = LifoQueue() + queue.put(Trace()) + while not queue.empty(): + partial_trace = queue.get() + escape_fn = functools.partial(util.discrete_escape, partial_trace) + traced_fn = poutine.trace(poutine.escape(poutine.replay(fn, partial_trace), escape_fn), + graph_type=graph_type) + try: + full_trace = traced_fn.get_trace(*args, **kwargs) + except util.NonlocalExit as e: + for extended_trace in util.enum_extend(traced_fn.trace.copy(), e.site): + queue.put(extended_trace) + continue + + # Scale trace by probability of discrete choices. + log_pdf = full_trace.batch_log_pdf(site_filter=site_is_discrete) + if isinstance(log_pdf, float): + log_pdf = torch.Tensor([log_pdf]) + if isinstance(log_pdf, torch.Tensor): + log_pdf = Variable(log_pdf) + scale = torch.exp(log_pdf.detach()) + yield scale, full_trace","[{'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nRuntimeError Traceback (most recent call last)\\n in ()\\n----> 1 train()\\n\\n in train()\\n33\\n34 # Train and score\\n---> 35 train_loss += svi.step(input_batch, target_batch)\\n36\\n37 # Store history\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs)\\n96 """"""\\n97 # get loss and compute gradients\\n---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\n99\\n100 # get active params\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs)\\n63 :rtype: float\\n64 """"""\\n---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs)\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs)\\n149 guide_site = guide_trace.nodes[name]\\n150 lp_lq = model_site[log_pdf] - guide_site[log_pdf]\\n--> 151 elbo_particle += lp_lq\\n152 if guide_site[""fn""].reparameterized:\\n153 surrogate_elbo_particle += lp_lq\\n\\nRuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 \\'other\\''}, {'piece_type': 'source code', 'piece_content': 'for inputs, targets in train_loader:\\n\\n# Put batch on GPU\\ninput_batch = Variable(inputs.cuda(device=CUDA_ID, async=use_async)) # Pinned memory with async transfer\\ntarget_batch = Variable(targets.cuda(device=CUDA_ID, async=use_async))\\n\\n# Train and score\\ntrain_loss += svi.step(input_batch, target_batch)\\n\\n# Store history\\ntrain_losses += [train_loss / n_train_samples]'}]","--------------------------------------------------------------------------- +RuntimeError Traceback (most recent call last) + in () +----> 1 train() + + in train() +33 +34 # Train and score +---> 35 train_loss += svi.step(input_batch, target_batch) +36 +37 # Store history + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs) +96 """""" +97 # get loss and compute gradients +---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +99 +100 # get active params + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) +63 :rtype: float +64 """""" +---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) +149 guide_site = guide_trace.nodes[name] +150 lp_lq = model_site[log_pdf] - guide_site[log_pdf] +--> 151 elbo_particle += lp_lq +152 if guide_site[""fn""].reparameterized: +153 surrogate_elbo_particle += lp_lq + +RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 'other'",RuntimeError +" def loss(self, model, guide, *args, **kwargs): + """""" + :returns: returns an estimate of the ELBO + :rtype: float + + Evaluates the ELBO with an estimator that uses num_particles many samples/particles. + """""" + elbo = 0.0 + for weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs): + elbo_particle = weight * 0 + + if (self.enum_discrete and isinstance(weight, Variable) and weight.size(0) > 1): + log_pdf = ""batch_log_pdf"" + else: + log_pdf = ""log_pdf"" + for name in model_trace.nodes.keys(): + if model_trace.nodes[name][""type""] == ""sample"": + if model_trace.nodes[name][""is_observed""]: + elbo_particle += model_trace.nodes[name][log_pdf] + else: + elbo_particle += model_trace.nodes[name][log_pdf] + elbo_particle -= guide_trace.nodes[name][log_pdf] + + # drop terms of weight zero to avoid nans + if isinstance(weight, numbers.Number): + if weight == 0.0: + elbo_particle = torch_zeros_like(elbo_particle) + else: + elbo_particle[weight == 0] = 0.0 + + elbo += torch_data_sum(weight * elbo_particle) + + loss = -elbo + if np.isnan(loss): + warnings.warn('Encountered NAN loss') + return loss"," def loss(self, model, guide, *args, **kwargs): + """""" + :returns: returns an estimate of the ELBO + :rtype: float + + Evaluates the ELBO with an estimator that uses num_particles many samples/particles. + """""" + elbo = 0.0 + for weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs): + elbo_particle = weight * 0 + + log_pdf = ""batch_log_pdf"" if (self.enum_discrete and weight.size(0) > 1) else ""log_pdf"" + for name in model_trace.nodes.keys(): + if model_trace.nodes[name][""type""] == ""sample"": + if model_trace.nodes[name][""is_observed""]: + elbo_particle += model_trace.nodes[name][log_pdf] + else: + elbo_particle += model_trace.nodes[name][log_pdf] + elbo_particle -= guide_trace.nodes[name][log_pdf] + + # drop terms of weight zero to avoid nans + if isinstance(weight, numbers.Number): + if weight == 0.0: + elbo_particle = torch_zeros_like(elbo_particle) + else: + elbo_particle[weight == 0] = 0.0 + + elbo += torch_data_sum(weight * elbo_particle) + + loss = -elbo + if np.isnan(loss): + warnings.warn('Encountered NAN loss') + return loss","[{'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nRuntimeError Traceback (most recent call last)\\n in ()\\n----> 1 train()\\n\\n in train()\\n33\\n34 # Train and score\\n---> 35 train_loss += svi.step(input_batch, target_batch)\\n36\\n37 # Store history\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs)\\n96 """"""\\n97 # get loss and compute gradients\\n---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\n99\\n100 # get active params\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs)\\n63 :rtype: float\\n64 """"""\\n---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs)\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs)\\n149 guide_site = guide_trace.nodes[name]\\n150 lp_lq = model_site[log_pdf] - guide_site[log_pdf]\\n--> 151 elbo_particle += lp_lq\\n152 if guide_site[""fn""].reparameterized:\\n153 surrogate_elbo_particle += lp_lq\\n\\nRuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 \\'other\\''}, {'piece_type': 'source code', 'piece_content': 'for inputs, targets in train_loader:\\n\\n# Put batch on GPU\\ninput_batch = Variable(inputs.cuda(device=CUDA_ID, async=use_async)) # Pinned memory with async transfer\\ntarget_batch = Variable(targets.cuda(device=CUDA_ID, async=use_async))\\n\\n# Train and score\\ntrain_loss += svi.step(input_batch, target_batch)\\n\\n# Store history\\ntrain_losses += [train_loss / n_train_samples]'}]","--------------------------------------------------------------------------- +RuntimeError Traceback (most recent call last) + in () +----> 1 train() + + in train() +33 +34 # Train and score +---> 35 train_loss += svi.step(input_batch, target_batch) +36 +37 # Store history + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs) +96 """""" +97 # get loss and compute gradients +---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +99 +100 # get active params + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) +63 :rtype: float +64 """""" +---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) +149 guide_site = guide_trace.nodes[name] +150 lp_lq = model_site[log_pdf] - guide_site[log_pdf] +--> 151 elbo_particle += lp_lq +152 if guide_site[""fn""].reparameterized: +153 surrogate_elbo_particle += lp_lq + +RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 'other'",RuntimeError +" def loss_and_grads(self, model, guide, *args, **kwargs): + """""" + :returns: returns an estimate of the ELBO + :rtype: float + + Computes the ELBO as well as the surrogate ELBO that is used to form the gradient estimator. + Performs backward on the latter. Num_particle many samples are used to form the estimators. + """""" + elbo = 0.0 + # grab a trace from the generator + for weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs): + elbo_particle = weight * 0 + surrogate_elbo_particle = weight * 0 + # compute elbo and surrogate elbo + if (self.enum_discrete and isinstance(weight, Variable) and weight.size(0) > 1): + log_pdf = ""batch_log_pdf"" + else: + log_pdf = ""log_pdf"" + for name, model_site in model_trace.nodes.items(): + if model_site[""type""] == ""sample"": + if model_site[""is_observed""]: + elbo_particle += model_site[log_pdf] + surrogate_elbo_particle += model_site[log_pdf] + else: + guide_site = guide_trace.nodes[name] + lp_lq = model_site[log_pdf] - guide_site[log_pdf] + elbo_particle += lp_lq + if guide_site[""fn""].reparameterized: + surrogate_elbo_particle += lp_lq + else: + # XXX should the user be able to control inclusion of the -logq term below? + guide_log_pdf = guide_site[log_pdf] / guide_site[""scale""] # not scaled by subsampling + surrogate_elbo_particle += model_site[log_pdf] + log_r.detach() * guide_log_pdf + + # drop terms of weight zero to avoid nans + if isinstance(weight, numbers.Number): + if weight == 0.0: + elbo_particle = torch_zeros_like(elbo_particle) + surrogate_elbo_particle = torch_zeros_like(surrogate_elbo_particle) + else: + weight_eq_zero = (weight == 0) + elbo_particle[weight_eq_zero] = 0.0 + surrogate_elbo_particle[weight_eq_zero] = 0.0 + + elbo += torch_data_sum(weight * elbo_particle) + surrogate_elbo_particle = torch_sum(weight * surrogate_elbo_particle) + + # collect parameters to train from model and guide + trainable_params = set(site[""value""] + for trace in (model_trace, guide_trace) + for site in trace.nodes.values() + if site[""type""] == ""param"") + + if trainable_params: + surrogate_loss_particle = -surrogate_elbo_particle + torch_backward(surrogate_loss_particle) + pyro.get_param_store().mark_params_active(trainable_params) + + loss = -elbo + if np.isnan(loss): + warnings.warn('Encountered NAN loss') + return loss"," def loss_and_grads(self, model, guide, *args, **kwargs): + """""" + :returns: returns an estimate of the ELBO + :rtype: float + + Computes the ELBO as well as the surrogate ELBO that is used to form the gradient estimator. + Performs backward on the latter. Num_particle many samples are used to form the estimators. + """""" + elbo = 0.0 + # grab a trace from the generator + for weight, model_trace, guide_trace, log_r in self._get_traces(model, guide, *args, **kwargs): + elbo_particle = weight * 0 + surrogate_elbo_particle = weight * 0 + # compute elbo and surrogate elbo + log_pdf = ""batch_log_pdf"" if (self.enum_discrete and weight.size(0) > 1) else ""log_pdf"" + for name, model_site in model_trace.nodes.items(): + if model_site[""type""] == ""sample"": + if model_site[""is_observed""]: + elbo_particle += model_site[log_pdf] + surrogate_elbo_particle += model_site[log_pdf] + else: + guide_site = guide_trace.nodes[name] + lp_lq = model_site[log_pdf] - guide_site[log_pdf] + elbo_particle += lp_lq + if guide_site[""fn""].reparameterized: + surrogate_elbo_particle += lp_lq + else: + # XXX should the user be able to control inclusion of the -logq term below? + guide_log_pdf = guide_site[log_pdf] / guide_site[""scale""] # not scaled by subsampling + surrogate_elbo_particle += model_site[log_pdf] + log_r.detach() * guide_log_pdf + + # drop terms of weight zero to avoid nans + if isinstance(weight, numbers.Number): + if weight == 0.0: + elbo_particle = torch_zeros_like(elbo_particle) + surrogate_elbo_particle = torch_zeros_like(surrogate_elbo_particle) + else: + weight_eq_zero = (weight == 0) + elbo_particle[weight_eq_zero] = 0.0 + surrogate_elbo_particle[weight_eq_zero] = 0.0 + + elbo += torch_data_sum(weight * elbo_particle) + surrogate_elbo_particle = torch_sum(weight * surrogate_elbo_particle) + + # collect parameters to train from model and guide + trainable_params = set(site[""value""] + for trace in (model_trace, guide_trace) + for site in trace.nodes.values() + if site[""type""] == ""param"") + + if trainable_params: + surrogate_loss_particle = -surrogate_elbo_particle + torch_backward(surrogate_loss_particle) + pyro.get_param_store().mark_params_active(trainable_params) + + loss = -elbo + if np.isnan(loss): + warnings.warn('Encountered NAN loss') + return loss","[{'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nRuntimeError Traceback (most recent call last)\\n in ()\\n----> 1 train()\\n\\n in train()\\n33\\n34 # Train and score\\n---> 35 train_loss += svi.step(input_batch, target_batch)\\n36\\n37 # Store history\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs)\\n96 """"""\\n97 # get loss and compute gradients\\n---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)\\n99\\n100 # get active params\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs)\\n63 :rtype: float\\n64 """"""\\n---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs)\\n\\n/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs)\\n149 guide_site = guide_trace.nodes[name]\\n150 lp_lq = model_site[log_pdf] - guide_site[log_pdf]\\n--> 151 elbo_particle += lp_lq\\n152 if guide_site[""fn""].reparameterized:\\n153 surrogate_elbo_particle += lp_lq\\n\\nRuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 \\'other\\''}, {'piece_type': 'source code', 'piece_content': 'for inputs, targets in train_loader:\\n\\n# Put batch on GPU\\ninput_batch = Variable(inputs.cuda(device=CUDA_ID, async=use_async)) # Pinned memory with async transfer\\ntarget_batch = Variable(targets.cuda(device=CUDA_ID, async=use_async))\\n\\n# Train and score\\ntrain_loss += svi.step(input_batch, target_batch)\\n\\n# Store history\\ntrain_losses += [train_loss / n_train_samples]'}]","--------------------------------------------------------------------------- +RuntimeError Traceback (most recent call last) + in () +----> 1 train() + + in train() +33 +34 # Train and score +---> 35 train_loss += svi.step(input_batch, target_batch) +36 +37 # Store history + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/svi.pyc in step(self, *args, **kwargs) +96 """""" +97 # get loss and compute gradients +---> 98 loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs) +99 +100 # get active params + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) +63 :rtype: float +64 """""" +---> 65 return self.which_elbo.loss_and_grads(model, guide, *args, **kwargs) + +/home/reinier/anaconda2/lib/python2.7/site-packages/pyro/infer/trace_elbo.pyc in loss_and_grads(self, model, guide, *args, **kwargs) +149 guide_site = guide_trace.nodes[name] +150 lp_lq = model_site[log_pdf] - guide_site[log_pdf] +--> 151 elbo_particle += lp_lq +152 if guide_site[""fn""].reparameterized: +153 surrogate_elbo_particle += lp_lq + +RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 'other'",RuntimeError +"def resolve_is_lower_case(tokenizer): + if isinstance(tokenizer, transformers.BertTokenizer): + return tokenizer.basic_tokenizer.do_lower_case + if isinstance(tokenizer, transformers.AlbertTokenizer): + return tokenizer.do_lower_case + else: + return False","def resolve_is_lower_case(tokenizer): + if isinstance(tokenizer, (transformers.BertTokenizer, transformers.AlbertTokenizer)): + return tokenizer.basic_tokenizer.do_lower_case + else: + return False","[{'piece_type': 'other', 'piece_content': 'MODEL_NAME=albert-xxlarge-v2\\nTASK_NAME=qamr\\npython ${JIANT_PATH}/proj/main/tokenize_and_cache.py \\\\\\n--task_config_path ${DATA_DIR}/configs/${TASK_NAME}_config.json \\\\\\n--model_type ${MODEL_NAME} \\\\\\n--model_tokenizer_path ${MODELS_DIR}/${MODEL_NAME}/tokenizer \\\\\\n--phases train,val,test \\\\\\n--max_seq_length 256 \\\\\\n--do_iter \\\\\\n--smart_truncate \\\\\\n--output_dir ${CACHE_DIR}/${MODEL_NAME}/${TASK_NAME}'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 214, in \\nmain(args=RunConfiguration.run_cli_json_prepend())\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 168, in main\\nargs=args,\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 53, in chunk_and_save\\nargs=args,\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 129, in iter_chunk_and_save\\nrecorder_callback=max_valid_length_recorder,\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/shared/caching.py"", line 91, in iter_chunk_and_save\\nfor datum in data:\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py"", line 145, in iter_chunk_convert_examples_to_dataset\\nverbose=verbose,\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py"", line 216, in iter_chunk_tokenize_and_featurize\\nyield example.tokenize(tokenizer).featurize(tokenizer, feat_spec)\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/tasks/lib/templates/span_prediction.py"", line 38, in tokenize\\nself.answer_char_span[0], self.answer_char_span[1], inclusive=True\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py"", line 276, in project_char_to_token_span\\nmat=self.source_char_idx_to_target_token_idx, start=start, end=end, inclusive=inclusive\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py"", line 192, in _project_span\\nraise ValueError(f""Project {(start, end)} into empty span in target sequence"")\\nValueError: Project (0, 2) into empty span in target sequence'}]","Traceback (most recent call last): +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 214, in +main(args=RunConfiguration.run_cli_json_prepend()) +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 168, in main +args=args, +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 53, in chunk_and_save +args=args, +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 129, in iter_chunk_and_save +recorder_callback=max_valid_length_recorder, +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/shared/caching.py"", line 91, in iter_chunk_and_save +for datum in data: +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py"", line 145, in iter_chunk_convert_examples_to_dataset +verbose=verbose, +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py"", line 216, in iter_chunk_tokenize_and_featurize +yield example.tokenize(tokenizer).featurize(tokenizer, feat_spec) +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/tasks/lib/templates/span_prediction.py"", line 38, in tokenize +self.answer_char_span[0], self.answer_char_span[1], inclusive=True +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py"", line 276, in project_char_to_token_span +mat=self.source_char_idx_to_target_token_idx, start=start, end=end, inclusive=inclusive +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py"", line 192, in _project_span +raise ValueError(f""Project {(start, end)} into empty span in target sequence"") +ValueError: Project (0, 2) into empty span in target sequence",ValueError +" def tokenize(self, tokenizer): + passage = ( + self.passage.lower() + if model_resolution.resolve_is_lower_case(tokenizer=tokenizer) + else self.passage + ) + passage_tokens = tokenizer.tokenize(passage) + token_aligner = TokenAligner(source=passage, target=passage_tokens) + answer_token_span = token_aligner.project_char_to_token_span( + self.answer_char_span[0], self.answer_char_span[1], inclusive=True + ) + + return TokenizedExample( + guid=self.guid, + passage=passage_tokens, + question=tokenizer.tokenize(self.question), + answer_str=self.answer, + passage_str=passage, + answer_token_span=answer_token_span, + token_idx_to_char_idx_map=token_aligner.source_char_idx_to_target_token_idx.T, + )"," def tokenize(self, tokenizer): + passage = ( + self.passage.lower() if resolve_is_lower_case(tokenizer=tokenizer) else self.passage + ) + passage_tokens = tokenizer.tokenize(passage) + token_aligner = TokenAligner(source=passage, target=passage_tokens) + answer_token_span = token_aligner.project_char_to_token_span( + self.answer_char_span[0], self.answer_char_span[1], inclusive=True + ) + + return TokenizedExample( + guid=self.guid, + passage=passage_tokens, + question=tokenizer.tokenize(self.question), + answer_str=self.answer, + passage_str=passage, + answer_token_span=answer_token_span, + token_idx_to_char_idx_map=token_aligner.source_char_idx_to_target_token_idx.T, + )","[{'piece_type': 'other', 'piece_content': 'MODEL_NAME=albert-xxlarge-v2\\nTASK_NAME=qamr\\npython ${JIANT_PATH}/proj/main/tokenize_and_cache.py \\\\\\n--task_config_path ${DATA_DIR}/configs/${TASK_NAME}_config.json \\\\\\n--model_type ${MODEL_NAME} \\\\\\n--model_tokenizer_path ${MODELS_DIR}/${MODEL_NAME}/tokenizer \\\\\\n--phases train,val,test \\\\\\n--max_seq_length 256 \\\\\\n--do_iter \\\\\\n--smart_truncate \\\\\\n--output_dir ${CACHE_DIR}/${MODEL_NAME}/${TASK_NAME}'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 214, in \\nmain(args=RunConfiguration.run_cli_json_prepend())\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 168, in main\\nargs=args,\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 53, in chunk_and_save\\nargs=args,\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 129, in iter_chunk_and_save\\nrecorder_callback=max_valid_length_recorder,\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/shared/caching.py"", line 91, in iter_chunk_and_save\\nfor datum in data:\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py"", line 145, in iter_chunk_convert_examples_to_dataset\\nverbose=verbose,\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py"", line 216, in iter_chunk_tokenize_and_featurize\\nyield example.tokenize(tokenizer).featurize(tokenizer, feat_spec)\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/tasks/lib/templates/span_prediction.py"", line 38, in tokenize\\nself.answer_char_span[0], self.answer_char_span[1], inclusive=True\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py"", line 276, in project_char_to_token_span\\nmat=self.source_char_idx_to_target_token_idx, start=start, end=end, inclusive=inclusive\\nFile ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py"", line 192, in _project_span\\nraise ValueError(f""Project {(start, end)} into empty span in target sequence"")\\nValueError: Project (0, 2) into empty span in target sequence'}]","Traceback (most recent call last): +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 214, in +main(args=RunConfiguration.run_cli_json_prepend()) +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 168, in main +args=args, +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 53, in chunk_and_save +args=args, +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/tokenize_and_cache.py"", line 129, in iter_chunk_and_save +recorder_callback=max_valid_length_recorder, +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/shared/caching.py"", line 91, in iter_chunk_and_save +for datum in data: +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py"", line 145, in iter_chunk_convert_examples_to_dataset +verbose=verbose, +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/proj/main/preprocessing.py"", line 216, in iter_chunk_tokenize_and_featurize +yield example.tokenize(tokenizer).featurize(tokenizer, feat_spec) +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/tasks/lib/templates/span_prediction.py"", line 38, in tokenize +self.answer_char_span[0], self.answer_char_span[1], inclusive=True +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py"", line 276, in project_char_to_token_span +mat=self.source_char_idx_to_target_token_idx, start=start, end=end, inclusive=inclusive +File ""/scratch/pmh330/nyu-mll-jiant/jiant/jiant/utils/retokenize.py"", line 192, in _project_span +raise ValueError(f""Project {(start, end)} into empty span in target sequence"") +ValueError: Project (0, 2) into empty span in target sequence",ValueError +"def get_task_specific_params(args, task_name): + """""" Search args for parameters specific to task. + Args: + args: main-program args, a config.Params object + task_name: (string) + Returns: + AllenNLP Params object of task-specific params. + """""" + + def _get_task_attr(attr_name, default=None): + return config.get_task_attr(args, task_name, attr_name, default) + + params = {} + params[""cls_type""] = _get_task_attr(""classifier"") + params[""d_hid""] = _get_task_attr(""classifier_hid_dim"") + params[""d_proj""] = _get_task_attr(""d_proj"") + params[""shared_pair_attn""] = args.shared_pair_attn + if args.shared_pair_attn: + params[""attn""] = args.pair_attn + params[""d_hid_attn""] = args.d_hid_attn + params[""dropout""] = args.classifier_dropout + else: + params[""attn""] = _get_task_attr(""pair_attn"") + params[""d_hid_attn""] = _get_task_attr(""d_hid_attn"") + params[""dropout""] = _get_task_attr(""classifier_dropout"") + + # Used for span/edge classification. Other tasks can safely ignore. + params[""cls_loss_fn""] = _get_task_attr(""span_classifier_loss_fn"") + params[""cls_span_pooling""] = _get_task_attr(""classifier_span_pooling"") + params[""edgeprobe_cnn_context""] = _get_task_attr(""edgeprobe_cnn_context"") + + # For NLI probing tasks, might want to use a classifier trained on + # something else (typically 'mnli'). + cls_task_name = _get_task_attr(""use_classifier"") + # default to this task + params[""use_classifier""] = cls_task_name or task_name + + return Params(params)","def get_task_specific_params(args, task_name): + """""" Search args for parameters specific to task. + Args: + args: main-program args, a config.Params object + task_name: (string) + Returns: + AllenNLP Params object of task-specific params. + """""" + + def _get_task_attr(attr_name, default=None): + return config.get_task_attr(args, task_name, attr_name, default) + + params = {} + params[""cls_type""] = _get_task_attr(""classifier"") + params[""d_hid""] = _get_task_attr(""classifier_hid_dim"") + params[""d_proj""] = _get_task_attr(""d_proj"") + params[""shared_pair_attn""] = args.shared_pair_attn + if args.shared_pair_attn: + params[""attn""] = args.pair_attn + params[""d_hid_attn""] = args.d_hid_attn + params[""dropout""] = args.classifier_dropout + else: + params[""attn""] = _get_task_attr(""pair_attn"") + params[""d_hid_attn""] = _get_task_attr(""d_hid_attn"") + params[""dropout""] = _get_task_attr(""classifier_dropout"") + + # Used for edge probing. Other tasks can safely ignore. + params[""cls_loss_fn""] = _get_task_attr(""classifier_loss_fn"") + params[""cls_span_pooling""] = _get_task_attr(""classifier_span_pooling"") + params[""edgeprobe_cnn_context""] = _get_task_attr(""edgeprobe_cnn_context"") + + # For NLI probing tasks, might want to use a classifier trained on + # something else (typically 'mnli'). + cls_task_name = _get_task_attr(""use_classifier"") + # default to this task + params[""use_classifier""] = cls_task_name or task_name + + return Params(params)","[{'piece_type': 'other', 'piece_content': 'rm -r $JIANT_PROJECT_PREFIX/jiant-demo; python main.py --config config/demo.conf --overrides ""target_tasks = winograd-coreference""'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward\\nout[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss\\nraise ValueError(""Unsupported loss type \\'%s\\' "" ""for edge probing."" % self.loss_type)\\nValueError: Unsupported loss type \\'\\' for edge probing.\\nTraceback (most recent call last):\\nFile ""main.py"", line 577, in \\nraise e # re-raise exception, in case debugger is attached.\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward\\nout[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss\\nraise ValueError(""Unsupported loss type \\'%s\\' "" ""for edge probing."" % self.loss_type)\\nValueError: Unsupported loss type \\'\\' for edge probing.'}, {'piece_type': 'other', 'piece_content': 'rm -r $JIANT_PROJECT_PREFIX/jiant-demo; python main.py --config config/demo.conf --overrides ""target_tasks = winograd-coreference, classifier_loss_fn = softmax, classifier_span_pooling = attn""'}, {'piece_type': 'error message', 'piece_content': '06/27 05:11:20 PM: Beginning training with stopping criteria based on metric: winograd-coreference_acc\\n06/27 05:11:20 PM: Fatal error in main():\\nTraceback (most recent call last):\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 137, in forward\\ntask.update_metrics(predictions, batch[""labels""].squeeze(dim=1), tagmask=tagmask)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2554, in update_metrics\\nbinary_preds = make_one_hot(logits, depth=2)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2551, in make_one_hot\\nones = torch.sparse.torch.eye(depth).cuda()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 162, in _lazy_init\\n_check_driver()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 75, in _check_driver\\nraise AssertionError(""Torch not compiled with CUDA enabled"")\\nAssertionError: Torch not compiled with CUDA enabled\\nTraceback (most recent call last):\\nFile ""main.py"", line 577, in \\nraise e # re-raise exception, in case debugger is attached.\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 137, in forward\\ntask.update_metrics(predictions, batch[""labels""].squeeze(dim=1), tagmask=tagmask)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2554, in update_metrics\\nbinary_preds = make_one_hot(logits, depth=2)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2551, in make_one_hot\\nones = torch.sparse.torch.eye(depth).cuda()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 162, in _lazy_init\\n_check_driver()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 75, in _check_driver\\nraise AssertionError(""Torch not compiled with CUDA enabled"")\\nAssertionError: Torch not compiled with CUDA enabled'}]","Traceback (most recent call last): +File ""main.py"", line 566, in +main(sys.argv[1:]) +File ""main.py"", line 534, in main +phase=""target_train"", +File ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train +output_dict = self._forward(batch, task=task) +File ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward +model_out = self._model.forward(task, tensor_batch) +File ""/Users/srbowman/jiant/src/models.py"", line 830, in forward +out = self._span_forward(batch, task, predict) +File ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward +out = module.forward(batch, sent_embs, sent_mask, task, predict) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward +out[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss +raise ValueError(""Unsupported loss type '%s' "" ""for edge probing."" % self.loss_type) +ValueError: Unsupported loss type '' for edge probing. +Traceback (most recent call last): +File ""main.py"", line 577, in +raise e # re-raise exception, in case debugger is attached. +File ""main.py"", line 566, in +main(sys.argv[1:]) +File ""main.py"", line 534, in main +phase=""target_train"", +File ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train +output_dict = self._forward(batch, task=task) +File ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward +model_out = self._model.forward(task, tensor_batch) +File ""/Users/srbowman/jiant/src/models.py"", line 830, in forward +out = self._span_forward(batch, task, predict) +File ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward +out = module.forward(batch, sent_embs, sent_mask, task, predict) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward +out[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss +raise ValueError(""Unsupported loss type '%s' "" ""for edge probing."" % self.loss_type) +ValueError: Unsupported loss type '' for edge probing.",ValueError +" def update_metrics(self, logits, labels, tagmask=None): + logits, labels = logits.detach(), labels.detach() + + def make_one_hot(batch, depth=2): + """""" + Creates a one-hot embedding of dimension 2. + Parameters: + batch: list of size batch_size of class predictions + Returns: + one hot encoding of size [batch_size, 2] + """""" + ones = torch.sparse.torch.eye(depth) + if torch.cuda.is_available(): + ones = ones.cuda() + return ones.index_select(0, batch) + + binary_preds = make_one_hot(logits, depth=2) + # Make label_ints a batch_size list of labels + label_ints = torch.argmax(labels, dim=1) + self.f1_scorer(binary_preds, label_ints) + self.acc_scorer(binary_preds.long(), labels.long())"," def update_metrics(self, logits, labels, tagmask=None): + logits, labels = logits.detach(), labels.detach() + + def make_one_hot(batch, depth=2): + """""" + Creates a one-hot embedding of dimension 2. + Parameters: + batch: list of size batch_size of class predictions + Returns: + one hot encoding of size [batch_size, 2] + """""" + ones = torch.sparse.torch.eye(depth).cuda() + return ones.index_select(0, batch) + + binary_preds = make_one_hot(logits, depth=2) + # Make label_ints a batch_size list of labels + label_ints = torch.argmax(labels, dim=1) + self.f1_scorer(binary_preds, label_ints) + self.acc_scorer(binary_preds.long(), labels.long())","[{'piece_type': 'other', 'piece_content': 'rm -r $JIANT_PROJECT_PREFIX/jiant-demo; python main.py --config config/demo.conf --overrides ""target_tasks = winograd-coreference""'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward\\nout[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss\\nraise ValueError(""Unsupported loss type \\'%s\\' "" ""for edge probing."" % self.loss_type)\\nValueError: Unsupported loss type \\'\\' for edge probing.\\nTraceback (most recent call last):\\nFile ""main.py"", line 577, in \\nraise e # re-raise exception, in case debugger is attached.\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward\\nout[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss\\nraise ValueError(""Unsupported loss type \\'%s\\' "" ""for edge probing."" % self.loss_type)\\nValueError: Unsupported loss type \\'\\' for edge probing.'}, {'piece_type': 'other', 'piece_content': 'rm -r $JIANT_PROJECT_PREFIX/jiant-demo; python main.py --config config/demo.conf --overrides ""target_tasks = winograd-coreference, classifier_loss_fn = softmax, classifier_span_pooling = attn""'}, {'piece_type': 'error message', 'piece_content': '06/27 05:11:20 PM: Beginning training with stopping criteria based on metric: winograd-coreference_acc\\n06/27 05:11:20 PM: Fatal error in main():\\nTraceback (most recent call last):\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 137, in forward\\ntask.update_metrics(predictions, batch[""labels""].squeeze(dim=1), tagmask=tagmask)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2554, in update_metrics\\nbinary_preds = make_one_hot(logits, depth=2)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2551, in make_one_hot\\nones = torch.sparse.torch.eye(depth).cuda()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 162, in _lazy_init\\n_check_driver()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 75, in _check_driver\\nraise AssertionError(""Torch not compiled with CUDA enabled"")\\nAssertionError: Torch not compiled with CUDA enabled\\nTraceback (most recent call last):\\nFile ""main.py"", line 577, in \\nraise e # re-raise exception, in case debugger is attached.\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 137, in forward\\ntask.update_metrics(predictions, batch[""labels""].squeeze(dim=1), tagmask=tagmask)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2554, in update_metrics\\nbinary_preds = make_one_hot(logits, depth=2)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2551, in make_one_hot\\nones = torch.sparse.torch.eye(depth).cuda()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 162, in _lazy_init\\n_check_driver()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 75, in _check_driver\\nraise AssertionError(""Torch not compiled with CUDA enabled"")\\nAssertionError: Torch not compiled with CUDA enabled'}]","Traceback (most recent call last): +File ""main.py"", line 566, in +main(sys.argv[1:]) +File ""main.py"", line 534, in main +phase=""target_train"", +File ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train +output_dict = self._forward(batch, task=task) +File ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward +model_out = self._model.forward(task, tensor_batch) +File ""/Users/srbowman/jiant/src/models.py"", line 830, in forward +out = self._span_forward(batch, task, predict) +File ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward +out = module.forward(batch, sent_embs, sent_mask, task, predict) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward +out[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss +raise ValueError(""Unsupported loss type '%s' "" ""for edge probing."" % self.loss_type) +ValueError: Unsupported loss type '' for edge probing. +Traceback (most recent call last): +File ""main.py"", line 577, in +raise e # re-raise exception, in case debugger is attached. +File ""main.py"", line 566, in +main(sys.argv[1:]) +File ""main.py"", line 534, in main +phase=""target_train"", +File ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train +output_dict = self._forward(batch, task=task) +File ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward +model_out = self._model.forward(task, tensor_batch) +File ""/Users/srbowman/jiant/src/models.py"", line 830, in forward +out = self._span_forward(batch, task, predict) +File ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward +out = module.forward(batch, sent_embs, sent_mask, task, predict) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward +out[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss +raise ValueError(""Unsupported loss type '%s' "" ""for edge probing."" % self.loss_type) +ValueError: Unsupported loss type '' for edge probing.",ValueError +" def make_one_hot(batch, depth=2): + """""" + Creates a one-hot embedding of dimension 2. + Parameters: + batch: list of size batch_size of class predictions + Returns: + one hot encoding of size [batch_size, 2] + """""" + ones = torch.sparse.torch.eye(depth) + if torch.cuda.is_available(): + ones = ones.cuda() + return ones.index_select(0, batch)"," def make_one_hot(batch, depth=2): + """""" + Creates a one-hot embedding of dimension 2. + Parameters: + batch: list of size batch_size of class predictions + Returns: + one hot encoding of size [batch_size, 2] + """""" + ones = torch.sparse.torch.eye(depth).cuda() + return ones.index_select(0, batch)","[{'piece_type': 'other', 'piece_content': 'rm -r $JIANT_PROJECT_PREFIX/jiant-demo; python main.py --config config/demo.conf --overrides ""target_tasks = winograd-coreference""'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward\\nout[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss\\nraise ValueError(""Unsupported loss type \\'%s\\' "" ""for edge probing."" % self.loss_type)\\nValueError: Unsupported loss type \\'\\' for edge probing.\\nTraceback (most recent call last):\\nFile ""main.py"", line 577, in \\nraise e # re-raise exception, in case debugger is attached.\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward\\nout[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss\\nraise ValueError(""Unsupported loss type \\'%s\\' "" ""for edge probing."" % self.loss_type)\\nValueError: Unsupported loss type \\'\\' for edge probing.'}, {'piece_type': 'other', 'piece_content': 'rm -r $JIANT_PROJECT_PREFIX/jiant-demo; python main.py --config config/demo.conf --overrides ""target_tasks = winograd-coreference, classifier_loss_fn = softmax, classifier_span_pooling = attn""'}, {'piece_type': 'error message', 'piece_content': '06/27 05:11:20 PM: Beginning training with stopping criteria based on metric: winograd-coreference_acc\\n06/27 05:11:20 PM: Fatal error in main():\\nTraceback (most recent call last):\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 137, in forward\\ntask.update_metrics(predictions, batch[""labels""].squeeze(dim=1), tagmask=tagmask)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2554, in update_metrics\\nbinary_preds = make_one_hot(logits, depth=2)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2551, in make_one_hot\\nones = torch.sparse.torch.eye(depth).cuda()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 162, in _lazy_init\\n_check_driver()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 75, in _check_driver\\nraise AssertionError(""Torch not compiled with CUDA enabled"")\\nAssertionError: Torch not compiled with CUDA enabled\\nTraceback (most recent call last):\\nFile ""main.py"", line 577, in \\nraise e # re-raise exception, in case debugger is attached.\\nFile ""main.py"", line 566, in \\nmain(sys.argv[1:])\\nFile ""main.py"", line 534, in main\\nphase=""target_train"",\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train\\noutput_dict = self._forward(batch, task=task)\\nFile ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward\\nmodel_out = self._model.forward(task, tensor_batch)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 830, in forward\\nout = self._span_forward(batch, task, predict)\\nFile ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward\\nout = module.forward(batch, sent_embs, sent_mask, task, predict)\\nFile ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 137, in forward\\ntask.update_metrics(predictions, batch[""labels""].squeeze(dim=1), tagmask=tagmask)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2554, in update_metrics\\nbinary_preds = make_one_hot(logits, depth=2)\\nFile ""/Users/srbowman/jiant/src/tasks/tasks.py"", line 2551, in make_one_hot\\nones = torch.sparse.torch.eye(depth).cuda()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 162, in _lazy_init\\n_check_driver()\\nFile ""/Users/srbowman/miniconda3/envs/jiant/lib/python3.6/site-packages/torch/cuda/__init__.py"", line 75, in _check_driver\\nraise AssertionError(""Torch not compiled with CUDA enabled"")\\nAssertionError: Torch not compiled with CUDA enabled'}]","Traceback (most recent call last): +File ""main.py"", line 566, in +main(sys.argv[1:]) +File ""main.py"", line 534, in main +phase=""target_train"", +File ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train +output_dict = self._forward(batch, task=task) +File ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward +model_out = self._model.forward(task, tensor_batch) +File ""/Users/srbowman/jiant/src/models.py"", line 830, in forward +out = self._span_forward(batch, task, predict) +File ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward +out = module.forward(batch, sent_embs, sent_mask, task, predict) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward +out[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss +raise ValueError(""Unsupported loss type '%s' "" ""for edge probing."" % self.loss_type) +ValueError: Unsupported loss type '' for edge probing. +Traceback (most recent call last): +File ""main.py"", line 577, in +raise e # re-raise exception, in case debugger is attached. +File ""main.py"", line 566, in +main(sys.argv[1:]) +File ""main.py"", line 534, in main +phase=""target_train"", +File ""/Users/srbowman/jiant/src/trainer.py"", line 594, in train +output_dict = self._forward(batch, task=task) +File ""/Users/srbowman/jiant/src/trainer.py"", line 1035, in _forward +model_out = self._model.forward(task, tensor_batch) +File ""/Users/srbowman/jiant/src/models.py"", line 830, in forward +out = self._span_forward(batch, task, predict) +File ""/Users/srbowman/jiant/src/models.py"", line 917, in _span_forward +out = module.forward(batch, sent_embs, sent_mask, task, predict) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 134, in forward +out[""loss""] = self.compute_loss(logits, batch[""labels""].squeeze(dim=1), task) +File ""/Users/srbowman/jiant/src/modules/span_modules.py"", line 184, in compute_loss +raise ValueError(""Unsupported loss type '%s' "" ""for edge probing."" % self.loss_type) +ValueError: Unsupported loss type '' for edge probing.",ValueError +" def parse(self, file): + data = [] + file = EncodedIO(file) + file = io.TextIOWrapper(file, encoding=file.encoding) + + # Add check exception + + field_parsers = { + ""ne"": lambda line, i: conllu.parser.parse_nullable_value(line[i]), + } + + gen_parser = conllu.parse_incr( + file, + fields=(""form"", ""ne""), + field_parsers=field_parsers + ) + + try: + for sentence in gen_parser: + if not sentence: + continue + if len(data) >= settings.IMPORT_BATCH_SIZE: + yield data + data = [] + words, labels = [], [] + for item in sentence: + word = item.get(""form"") + tag = item.get(""ne"") + + if tag is not None: + char_left = sum(map(len, words)) + len(words) + char_right = char_left + len(word) + span = [char_left, char_right, tag] + labels.append(span) + + words.append(word) + + # Create and add JSONL + data.append({'text': ' '.join(words), 'labels': labels}) + + except conllu.parser.ParseException as e: + raise FileParseException(line_num=-1, line=str(e)) + + if data: + yield data"," def parse(self, file): + data = [] + file = io.TextIOWrapper(file, encoding='utf-8') + + # Add check exception + + field_parsers = { + ""ne"": lambda line, i: conllu.parser.parse_nullable_value(line[i]), + } + + gen_parser = conllu.parse_incr( + file, + fields=(""form"", ""ne""), + field_parsers=field_parsers + ) + + try: + for sentence in gen_parser: + if not sentence: + continue + if len(data) >= settings.IMPORT_BATCH_SIZE: + yield data + data = [] + words, labels = [], [] + for item in sentence: + word = item.get(""form"") + tag = item.get(""ne"") + + if tag is not None: + char_left = sum(map(len, words)) + len(words) + char_right = char_left + len(word) + span = [char_left, char_right, tag] + labels.append(span) + + words.append(word) + + # Create and add JSONL + data.append({'text': ' '.join(words), 'labels': labels}) + + except conllu.parser.ParseException as e: + raise FileParseException(line_num=-1, line=str(e)) + + if data: + yield data","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/app/server/views.py"", line 121, in post\\ndocuments = self.csv_to_documents(project, file)\\nFile ""/app/server/views.py"", line 77, in csv_to_documents\\nmaybe_header = next(reader)\\nFile ""/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py"", line 321, in decode\\n(result, consumed) = self._buffer_decode(data, self.errors, final)\\nUnicodeDecodeError: \\'utf-8\\' codec can\\'t decode byte 0xff in position 0: invalid start byte'}]","Traceback (most recent call last): +File ""/app/server/views.py"", line 121, in post +documents = self.csv_to_documents(project, file) +File ""/app/server/views.py"", line 77, in csv_to_documents +maybe_header = next(reader) +File ""/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py"", line 321, in decode +(result, consumed) = self._buffer_decode(data, self.errors, final) +UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte",UnicodeDecodeError +" def parse(self, file): + file = EncodedIO(file) + file = io.TextIOWrapper(file, encoding=file.encoding) + while True: + batch = list(itertools.islice(file, settings.IMPORT_BATCH_SIZE)) + if not batch: + break + yield [{'text': line.strip()} for line in batch]"," def parse(self, file): + file = io.TextIOWrapper(file, encoding='utf-8') + while True: + batch = list(itertools.islice(file, settings.IMPORT_BATCH_SIZE)) + if not batch: + break + yield [{'text': line.strip()} for line in batch]","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/app/server/views.py"", line 121, in post\\ndocuments = self.csv_to_documents(project, file)\\nFile ""/app/server/views.py"", line 77, in csv_to_documents\\nmaybe_header = next(reader)\\nFile ""/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py"", line 321, in decode\\n(result, consumed) = self._buffer_decode(data, self.errors, final)\\nUnicodeDecodeError: \\'utf-8\\' codec can\\'t decode byte 0xff in position 0: invalid start byte'}]","Traceback (most recent call last): +File ""/app/server/views.py"", line 121, in post +documents = self.csv_to_documents(project, file) +File ""/app/server/views.py"", line 77, in csv_to_documents +maybe_header = next(reader) +File ""/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py"", line 321, in decode +(result, consumed) = self._buffer_decode(data, self.errors, final) +UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte",UnicodeDecodeError +" def parse(self, file): + file = EncodedIO(file) + file = io.TextIOWrapper(file, encoding=file.encoding) + reader = csv.reader(file) + yield from ExcelParser.parse_excel_csv_reader(reader)"," def parse(self, file): + file = io.TextIOWrapper(file, encoding='utf-8') + reader = csv.reader(file) + yield from ExcelParser.parse_excel_csv_reader(reader)","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/app/server/views.py"", line 121, in post\\ndocuments = self.csv_to_documents(project, file)\\nFile ""/app/server/views.py"", line 77, in csv_to_documents\\nmaybe_header = next(reader)\\nFile ""/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py"", line 321, in decode\\n(result, consumed) = self._buffer_decode(data, self.errors, final)\\nUnicodeDecodeError: \\'utf-8\\' codec can\\'t decode byte 0xff in position 0: invalid start byte'}]","Traceback (most recent call last): +File ""/app/server/views.py"", line 121, in post +documents = self.csv_to_documents(project, file) +File ""/app/server/views.py"", line 77, in csv_to_documents +maybe_header = next(reader) +File ""/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py"", line 321, in decode +(result, consumed) = self._buffer_decode(data, self.errors, final) +UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte",UnicodeDecodeError +" def parse(self, file): + file = EncodedIO(file) + file = io.TextIOWrapper(file, encoding=file.encoding) + data = [] + for i, line in enumerate(file, start=1): + if len(data) >= settings.IMPORT_BATCH_SIZE: + yield data + data = [] + try: + j = json.loads(line) + j['meta'] = json.dumps(j.get('meta', {})) + data.append(j) + except json.decoder.JSONDecodeError: + raise FileParseException(line_num=i, line=line) + if data: + yield data"," def parse(self, file): + file = io.TextIOWrapper(file, encoding='utf-8') + data = [] + for i, line in enumerate(file, start=1): + if len(data) >= settings.IMPORT_BATCH_SIZE: + yield data + data = [] + try: + j = json.loads(line) + j['meta'] = json.dumps(j.get('meta', {})) + data.append(j) + except json.decoder.JSONDecodeError: + raise FileParseException(line_num=i, line=line) + if data: + yield data","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/app/server/views.py"", line 121, in post\\ndocuments = self.csv_to_documents(project, file)\\nFile ""/app/server/views.py"", line 77, in csv_to_documents\\nmaybe_header = next(reader)\\nFile ""/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py"", line 321, in decode\\n(result, consumed) = self._buffer_decode(data, self.errors, final)\\nUnicodeDecodeError: \\'utf-8\\' codec can\\'t decode byte 0xff in position 0: invalid start byte'}]","Traceback (most recent call last): +File ""/app/server/views.py"", line 121, in post +documents = self.csv_to_documents(project, file) +File ""/app/server/views.py"", line 77, in csv_to_documents +maybe_header = next(reader) +File ""/virtualenvs/doccano-HEgudFLz/bin/../lib/python3.6/codecs.py"", line 321, in decode +(result, consumed) = self._buffer_decode(data, self.errors, final) +UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte",UnicodeDecodeError +" def label_per_data(self, project): + annotation_class = project.get_annotation_class() + return annotation_class.objects.get_label_per_data(project=project)"," def label_per_data(self, project): + label_count = Counter() + user_count = Counter() + annotation_class = project.get_annotation_class() + docs = project.documents.all() + annotations = annotation_class.objects.filter(document_id__in=docs.all()) + for d in annotations.values('label__text', 'user__username').annotate(Count('label'), Count('user')): + label_count[d['label__text']] += d['label__count'] + user_count[d['user__username']] += d['user__count'] + return label_count, user_count","[{'piece_type': 'error message', 'piece_content': 'Internal Server Error: /v1/projects/4/statistics\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py"", line 34, in inner\\nresponse = get_response(request)\\nFile ""/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py"", line 126, in _get_response\\nresponse = self.process_exception_by_middleware(e, request)\\nFile ""/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py"", line 124, in _get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\nFile ""/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py"", line 54, in wrapped_view\\nreturn view_func(*args, **kwargs)\\nFile ""/usr/local/lib/python3.6/site-packages/django/views/generic/base.py"", line 68, in view\\nreturn self.dispatch(request, *args, **kwargs)\\nFile ""/usr/local/lib/python3.6/site-packages/rest_framework/views.py"", line 483, in dispatch\\nresponse = self.handle_exception(exc)\\nFile ""/usr/local/lib/python3.6/site-packages/rest_framework/views.py"", line 443, in handle_exception\\nself.raise_uncaught_exception(exc)\\nFile ""/usr/local/lib/python3.6/site-packages/rest_framework/views.py"", line 480, in dispatch\\nresponse = handler(request, *args, **kwargs)\\nFile ""/doccano/app/api/views.py"", line 70, in get\\nlabel_count, user_count = self.label_per_data(p)\\nFile ""/doccano/app/api/views.py"", line 94, in label_per_data\\nfor d in annotations.values(\\'label__text\\', \\'user__username\\').annotate(Count(\\'label\\'), Count(\\'user\\')):\\nFile ""/usr/local/lib/python3.6/site-packages/django/db/models/query.py"", line 750, in values\\nclone = self._values(*fields, **expressions)\\nFile ""/usr/local/lib/python3.6/site-packages/django/db/models/query.py"", line 745, in _values\\nclone.query.set_values(fields)\\nFile ""/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py"", line 1987, in set_values\\nself.add_fields(field_names, True)\\nFile ""/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py"", line 1735, in add_fields\\njoin_info = self.setup_joins(name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m)\\nFile ""/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py"", line 1473, in setup_joins\\nnames[:pivot], opts, allow_many, fail_on_missing=True,\\nFile ""/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py"", line 1389, in names_to_path\\n""Choices are: %s"" % (name, "", "".join(available)))\\ndjango.core.exceptions.FieldError: Cannot resolve keyword \\'label\\' into field. Choices are: created_at, document, document_id, id, manual, prob, text, updated_at, user, user_id'}, {'piece_type': 'error message', 'piece_content': 'Internal Server Error: /v1/projects/4/docs/download\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py"", line 34, in inner\\nresponse = get_response(request)\\nFile ""/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py"", line 126, in _get_response\\nresponse = self.process_exception_by_middleware(e, request)\\nFile ""/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py"", line 124, in _get_response\\nresponse = wrapped_callback(request, *callback_args, **callback_kwargs)\\nFile ""/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py"", line 54, in wrapped_view\\nreturn view_func(*args, **kwargs)\\nFile ""/usr/local/lib/python3.6/site-packages/django/views/generic/base.py"", line 68, in view\\nreturn self.dispatch(request, *args, **kwargs)\\nFile ""/usr/local/lib/python3.6/site-packages/rest_framework/views.py"", line 483, in dispatch\\nresponse = self.handle_exception(exc)\\nFile ""/usr/local/lib/python3.6/site-packages/rest_framework/views.py"", line 443, in handle_exception\\nself.raise_uncaught_exception(exc)\\nFile ""/usr/local/lib/python3.6/site-packages/rest_framework/views.py"", line 480, in dispatch\\nresponse = handler(request, *args, **kwargs)\\nFile ""/doccano/app/api/views.py"", line 312, in get\\ndata = painter.paint(documents)\\nFile ""/doccano/app/api/utils.py"", line 412, in paint\\ndata = super().paint(documents)\\nFile ""/doccano/app/api/utils.py"", line 385, in paint\\na.pop(\\'prob\\')\\nKeyError: \\'prob\\''}]","Internal Server Error: /v1/projects/4/statistics +Traceback (most recent call last): +File ""/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py"", line 34, in inner +response = get_response(request) +File ""/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py"", line 126, in _get_response +response = self.process_exception_by_middleware(e, request) +File ""/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py"", line 124, in _get_response +response = wrapped_callback(request, *callback_args, **callback_kwargs) +File ""/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py"", line 54, in wrapped_view +return view_func(*args, **kwargs) +File ""/usr/local/lib/python3.6/site-packages/django/views/generic/base.py"", line 68, in view +return self.dispatch(request, *args, **kwargs) +File ""/usr/local/lib/python3.6/site-packages/rest_framework/views.py"", line 483, in dispatch +response = self.handle_exception(exc) +File ""/usr/local/lib/python3.6/site-packages/rest_framework/views.py"", line 443, in handle_exception +self.raise_uncaught_exception(exc) +File ""/usr/local/lib/python3.6/site-packages/rest_framework/views.py"", line 480, in dispatch +response = handler(request, *args, **kwargs) +File ""/doccano/app/api/views.py"", line 70, in get +label_count, user_count = self.label_per_data(p) +File ""/doccano/app/api/views.py"", line 94, in label_per_data +for d in annotations.values('label__text', 'user__username').annotate(Count('label'), Count('user')): +File ""/usr/local/lib/python3.6/site-packages/django/db/models/query.py"", line 750, in values +clone = self._values(*fields, **expressions) +File ""/usr/local/lib/python3.6/site-packages/django/db/models/query.py"", line 745, in _values +clone.query.set_values(fields) +File ""/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py"", line 1987, in set_values +self.add_fields(field_names, True) +File ""/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py"", line 1735, in add_fields +join_info = self.setup_joins(name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m) +File ""/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py"", line 1473, in setup_joins +names[:pivot], opts, allow_many, fail_on_missing=True, +File ""/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py"", line 1389, in names_to_path +""Choices are: %s"" % (name, "", "".join(available))) +django.core.exceptions.FieldError: Cannot resolve keyword 'label' into field. Choices are: created_at, document, document_id, id, manual, prob, text, updated_at, user, user_id",django.core.exceptions.FieldError +" def get(cls, language): + try: + if PYCOUNTRY: + lang = (languages.get(alpha_2=language) + or languages.get(alpha_3=language) + or languages.get(bibliographic=language) + or languages.get(name=language)) + if not lang: + raise KeyError(language) + return Language( + # some languages don't have an alpha_2 code + getattr(lang, ""alpha_2"", """"), + lang.alpha_3, + lang.name, + getattr(lang, ""bibliographic"", """") + ) + else: + lang = None + if len(language) == 2: + lang = languages.get(alpha2=language) + elif len(language) == 3: + for code_type in ['part2b', 'part2t', 'part3']: + try: + lang = languages.get(**{code_type: language}) + break + except KeyError: + pass + if not lang: + raise KeyError(language) + else: + raise KeyError(language) + return Language(lang.alpha2, lang.part3, lang.name, lang.part2b or lang.part2t) + except (LookupError, KeyError): + raise LookupError(""Invalid language code: {0}"".format(language))"," def get(cls, language): + try: + if PYCOUNTRY: + # lookup workaround for alpha_2 language codes + lang = languages.get(alpha_2=language) if re.match(r""^[a-z]{2}$"", language) else languages.lookup(language) + return Language(lang.alpha_2, lang.alpha_3, lang.name, getattr(lang, ""bibliographic"", None)) + else: + lang = None + if len(language) == 2: + lang = languages.get(alpha2=language) + elif len(language) == 3: + for code_type in ['part2b', 'part2t', 'part3']: + try: + lang = languages.get(**{code_type: language}) + break + except KeyError: + pass + if not lang: + raise KeyError(language) + else: + raise KeyError(language) + return Language(lang.alpha2, lang.part3, lang.name, lang.part2b or lang.part2t) + except (LookupError, KeyError): + raise LookupError(""Invalid language code: {0}"".format(language))","[{'piece_type': 'error message', 'piece_content': '$ streamlink --loglevel debug https://www.raiplay.it/dirette/rai1\\n[cli][debug] OS: Linux-5.4.80-gentoo-r1-2-x86_64-Intel-R-_Core-TM-2_Duo_CPU_E8400_@_3.00GHz-with-glibc2.2.5\\n[cli][debug] Python: 3.8.7\\n[cli][debug] Streamlink: 2.0.0+25.g7a74e18\\n[cli][debug] Requests(2.25.1), Socks(1.7.1), Websocket(0.57.0)\\n[cli][info] Found matching plugin raiplay for URL https://www.raiplay.it/dirette/rai1\\n[plugins.raiplay][debug] Found JSON URL: https://www.raiplay.it/dirette/rai1.json\\n[plugins.raiplay][debug] Found stream URL: https://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=2606803\\n[utils.l10n][debug] Language code: en_US\\nTraceback (most recent call last):\\nFile ""/usr/bin/streamlink"", line 33, in \\nsys.exit(load_entry_point(\\'streamlink==2.0.0+25.g7a74e18\\', \\'console_scripts\\', \\'streamlink\\')())\\nFile ""/usr/lib/python3.8/site-packages/streamlink_cli/main.py"", line 1052, in main\\nhandle_url()\\nFile ""/usr/lib/python3.8/site-packages/streamlink_cli/main.py"", line 580, in handle_url\\nstreams = fetch_streams(plugin)\\nFile ""/usr/lib/python3.8/site-packages/streamlink_cli/main.py"", line 459, in fetch_streams\\nreturn plugin.streams(stream_types=args.stream_types,\\nFile ""/usr/lib/python3.8/site-packages/streamlink/plugin/plugin.py"", line 323, in streams\\nostreams = list(ostreams)\\nFile ""/usr/lib/python3.8/site-packages/streamlink/plugins/raiplay.py"", line 49, in _get_streams\\nyield from HLSStream.parse_variant_playlist(self.session, stream_url).items()\\nFile ""/usr/lib/python3.8/site-packages/streamlink/stream/hls.py"", line 494, in parse_variant_playlist\\nif not default_audio and (media.autoselect and locale.equivalent(language=media.language)):\\nFile ""/usr/lib/python3.8/site-packages/streamlink/utils/l10n.py"", line 155, in equivalent\\nequivalent = equivalent and (not language or self.language == self.get_language(language))\\nFile ""/usr/lib/python3.8/site-packages/streamlink/utils/l10n.py"", line 169, in get_language\\nreturn Language.get(language)\\nFile ""/usr/lib/python3.8/site-packages/streamlink/utils/l10n.py"", line 73, in get\\nreturn Language(lang.alpha_2, lang.alpha_3, lang.name, getattr(lang, ""bibliographic"", None))\\nFile ""/usr/lib/python3.8/site-packages/pycountry/db.py"", line 19, in __getattr__\\nraise AttributeError\\nAttributeError'}]","$ streamlink --loglevel debug https://www.raiplay.it/dirette/rai1 +[cli][debug] OS: Linux-5.4.80-gentoo-r1-2-x86_64-Intel-R-_Core-TM-2_Duo_CPU_E8400_@_3.00GHz-with-glibc2.2.5 +[cli][debug] Python: 3.8.7 +[cli][debug] Streamlink: 2.0.0+25.g7a74e18 +[cli][debug] Requests(2.25.1), Socks(1.7.1), Websocket(0.57.0) +[cli][info] Found matching plugin raiplay for URL https://www.raiplay.it/dirette/rai1 +[plugins.raiplay][debug] Found JSON URL: https://www.raiplay.it/dirette/rai1.json +[plugins.raiplay][debug] Found stream URL: https://mediapolis.rai.it/relinker/relinkerServlet.htm?cont=2606803 +[utils.l10n][debug] Language code: en_US +Traceback (most recent call last): +File ""/usr/bin/streamlink"", line 33, in +sys.exit(load_entry_point('streamlink==2.0.0+25.g7a74e18', 'console_scripts', 'streamlink')()) +File ""/usr/lib/python3.8/site-packages/streamlink_cli/main.py"", line 1052, in main +handle_url() +File ""/usr/lib/python3.8/site-packages/streamlink_cli/main.py"", line 580, in handle_url +streams = fetch_streams(plugin) +File ""/usr/lib/python3.8/site-packages/streamlink_cli/main.py"", line 459, in fetch_streams +return plugin.streams(stream_types=args.stream_types, +File ""/usr/lib/python3.8/site-packages/streamlink/plugin/plugin.py"", line 323, in streams +ostreams = list(ostreams) +File ""/usr/lib/python3.8/site-packages/streamlink/plugins/raiplay.py"", line 49, in _get_streams +yield from HLSStream.parse_variant_playlist(self.session, stream_url).items() +File ""/usr/lib/python3.8/site-packages/streamlink/stream/hls.py"", line 494, in parse_variant_playlist +if not default_audio and (media.autoselect and locale.equivalent(language=media.language)): +File ""/usr/lib/python3.8/site-packages/streamlink/utils/l10n.py"", line 155, in equivalent +equivalent = equivalent and (not language or self.language == self.get_language(language)) +File ""/usr/lib/python3.8/site-packages/streamlink/utils/l10n.py"", line 169, in get_language +return Language.get(language) +File ""/usr/lib/python3.8/site-packages/streamlink/utils/l10n.py"", line 73, in get +return Language(lang.alpha_2, lang.alpha_3, lang.name, getattr(lang, ""bibliographic"", None)) +File ""/usr/lib/python3.8/site-packages/pycountry/db.py"", line 19, in __getattr__ +raise AttributeError +AttributeError",AttributeError +" def close(self): + if self.closed: + return + + log.debug(""Closing ffmpeg thread"") + if self.process: + # kill ffmpeg + self.process.kill() + self.process.stdout.close() + + # close the streams + for stream in self.streams: + if hasattr(stream, ""close"") and callable(stream.close): + stream.close() + + log.debug(""Closed all the substreams"") + + if self.close_errorlog: + self.errorlog.close() + self.errorlog = None + + super().close()"," def close(self): + log.debug(""Closing ffmpeg thread"") + if self.process: + # kill ffmpeg + self.process.kill() + self.process.stdout.close() + + # close the streams + for stream in self.streams: + if hasattr(stream, ""close""): + stream.close() + + log.debug(""Closed all the substreams"") + if self.close_errorlog: + self.errorlog.close() + self.errorlog = None","[{'piece_type': 'other', 'piece_content': '$ streamlink ""https://www.youtube.com/watch?v=VaU6GR8OHNU"" -l trace\\n[16:50:38,702][cli][debug] OS: Linux-5.8.0-29-generic-x86_64-with-glibc2.32\\n[16:50:38,702][cli][debug] Python: 3.8.6\\n[16:50:38,702][cli][debug] Streamlink: 1.7.0+20.g9ac40cb\\n[16:50:38,702][cli][debug] Requests(2.25.0), Socks(1.7.1), Websocket(0.57.0)\\n[16:50:38,702][cli][info] Found matching plugin youtube for URL https://www.youtube.com/watch?v=VaU6GR8OHNU\\n[16:50:38,702][plugin.youtube][debug] Video ID from URL\\n[16:50:38,702][plugin.youtube][debug] Using video ID: VaU6GR8OHNU\\n[16:50:39,757][plugin.youtube][debug] get_video_info - 1: Found data\\n[16:50:39,759][plugin.youtube][debug] MuxedStream: v 135 a 251 = 480p\\n[16:50:39,759][plugin.youtube][debug] MuxedStream: v 133 a 251 = 240p\\n[16:50:39,759][plugin.youtube][debug] MuxedStream: v 160 a 251 = 144p\\n[16:50:39,759][cli][info] Available streams: audio_mp4a, audio_opus, 144p (worst), 240p, 360p, 480p (best)\\n[16:50:39,759][cli][info] Opening stream: 480p (muxed-stream)\\n[16:50:39,759][stream.ffmpegmux][debug] Opening http substream\\n[16:50:39,859][stream.ffmpegmux][debug] Opening http substream\\n[16:50:39,947][stream.ffmpegmux][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-9457-466 -i /tmp/ffmpeg-9457-333 -c:v copy -c:a copy -map 0 -map 1 -f matroska pipe:1\\n[16:50:39,947][stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-9457-466\\n[16:50:39,948][stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-9457-333\\n[16:50:39,950][cli][debug] Pre-buffering 8192 bytes\\n[16:50:40,002][cli][info] Starting player: /usr/bin/mpv\\n[16:50:40,002][cli.output][debug] Opening subprocess: /usr/bin/mpv ""--title=Christmas Music 2020 🎅 Top Christmas Songs Playlist 2020 🎄 Best Christmas Songs Ever"" -\\n[16:50:40,505][cli][debug] Writing stream to output\\n[16:50:46,869][cli][info] Player closed\\n[16:50:46,869][stream.ffmpegmux][debug] Closing ffmpeg thread\\n[16:50:46,870][stream.ffmpegmux][debug] Pipe copy complete: /tmp/ffmpeg-9457-466\\n[16:50:46,873][stream.ffmpegmux][error] Pipe copy aborted: /tmp/ffmpeg-9457-333\\n[16:50:46,954][stream.ffmpegmux][debug] Closed all the substreams\\n[16:50:46,954][cli][info] Stream ended\\n[16:50:46,954][cli][info] Closing currently open stream...\\n[16:50:46,954][stream.ffmpegmux][debug] Closing ffmpeg thread\\n[16:50:46,954][stream.ffmpegmux][debug] Closed all the substreams\\n[16:50:46,969][stream.ffmpegmux][debug] Closing ffmpeg thread\\n[16:50:46,969][stream.ffmpegmux][debug] Closed all the substreams'}, {'piece_type': 'error message', 'piece_content': '$ streamlink ""https://www.youtube.com/watch?v=VaU6GR8OHNU"" -l trace\\n[16:51:11.763092][cli][debug] OS: Linux-5.8.0-29-generic-x86_64-with-glibc2.32\\n[16:51:11.763170][cli][debug] Python: 3.8.6\\n[16:51:11.763193][cli][debug] Streamlink: 1.7.0+21.g70dc809\\n[16:51:11.763212][cli][debug] Requests(2.25.0), Socks(1.7.1), Websocket(0.57.0)\\n[16:51:11.763245][cli][info] Found matching plugin youtube for URL https://www.youtube.com/watch?v=VaU6GR8OHNU\\n[16:51:11.763275][plugin.youtube][debug] Video ID from URL\\n[16:51:11.763295][plugin.youtube][debug] Using video ID: VaU6GR8OHNU\\n[16:51:12.669559][plugin.youtube][debug] get_video_info - 1: Found data\\n[16:51:12.670741][plugin.youtube][debug] MuxedStream: v 135 a 251 = 480p\\n[16:51:12.670780][plugin.youtube][debug] MuxedStream: v 133 a 251 = 240p\\n[16:51:12.670804][plugin.youtube][debug] MuxedStream: v 160 a 251 = 144p\\n[16:51:12.671317][cli][info] Available streams: audio_mp4a, audio_opus, 144p (worst), 240p, 360p, 480p (best)\\n[16:51:12.671355][cli][info] Opening stream: 480p (muxed-stream)\\n[16:51:12.671386][stream.ffmpegmux][debug] Opening http substream\\n[16:51:12.750200][stream.ffmpegmux][debug] Opening http substream\\n[16:51:12.813040][stream.ffmpegmux][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-9607-784 -i /tmp/ffmpeg-9607-270 -c:v copy -c:a copy -map 0 -map 1 -f matroska pipe:1\\n[16:51:12.813226][stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-9607-784\\n[16:51:12.813344][stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-9607-270\\n[16:51:12.815867][cli][debug] Pre-buffering 8192 bytes\\n[16:51:12.875782][cli][info] Starting player: /usr/bin/mpv\\n[16:51:12.876152][cli.output][debug] Opening subprocess: /usr/bin/mpv ""--title=Christmas Music 2020 🎅 Top Christmas Songs Playlist 2020 🎄 Best Christmas Songs Ever"" -\\n[16:51:13.378673][cli][debug] Writing stream to output\\n[16:51:19.777326][cli][info] Player closed\\n[16:51:19.777459][stream.ffmpegmux][debug] Closing ffmpeg thread\\n[16:51:19.779916][stream.ffmpegmux][error] Pipe copy aborted: /tmp/ffmpeg-9607-270\\n[16:51:19.780000][stream.ffmpegmux][error] Pipe copy aborted: /tmp/ffmpeg-9607-784\\n[16:51:26.824121][stream.ffmpegmux][debug] Closed all the substreams\\n[16:51:26.824246][cli][info] Stream ended\\n[16:51:26.824434][cli][info] Closing currently open stream...\\n[16:51:26.824477][stream.ffmpegmux][debug] Closing ffmpeg thread\\n[16:51:26.824539][stream.ffmpegmux][debug] Closed all the substreams\\n--- Logging error ---\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 1081, in emit\\nmsg = self.format(record)\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 925, in format\\nreturn fmt.format(record)\\nFile ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 54, in format\\nreturn super().format(record)\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 666, in format\\nrecord.asctime = self.formatTime(record, self.datefmt)\\nFile ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 41, in formatTime\\nreturn tdt.strftime(datefmt or self.default_time_format)\\nImportError: sys.meta_path is None, Python is likely shutting down\\nCall stack:\\nFile ""venv3/lib/python3.8/site-packages/streamlink/stream/ffmpegmux.py"", line 158, in close\\nlog.debug(""Closing ffmpeg thread"")\\nMessage: \\'Closing ffmpeg thread\\'\\nArguments: ()\\n--- Logging error ---\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 1081, in emit\\nmsg = self.format(record)\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 925, in format\\nreturn fmt.format(record)\\nFile ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 54, in format\\nreturn super().format(record)\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 666, in format\\nrecord.asctime = self.formatTime(record, self.datefmt)\\nFile ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 41, in formatTime\\nreturn tdt.strftime(datefmt or self.default_time_format)\\nImportError: sys.meta_path is None, Python is likely shutting down\\nCall stack:\\nFile ""venv3/lib/python3.8/site-packages/streamlink/stream/ffmpegmux.py"", line 169, in close\\nlog.debug(""Closed all the substreams"")\\nMessage: \\'Closed all the substreams\\'\\nArguments: ()'}, {'piece_type': 'error message', 'piece_content': '$ streamlink ""https://www.youtube.com/watch?v=VaU6GR8OHNU"" -l trace\\n[16:54:12.507281][cli][debug] OS: Linux-5.8.0-29-generic-x86_64-with-glibc2.32\\n[16:54:12.507359][cli][debug] Python: 3.8.6\\n[16:54:12.507383][cli][debug] Streamlink: 1.7.0+78.g3e8fbe6\\n[16:54:12.507402][cli][debug] Requests(2.25.0), Socks(1.7.1), Websocket(0.57.0)\\n[16:54:12.507437][cli][info] Found matching plugin youtube for URL https://www.youtube.com/watch?v=VaU6GR8OHNU\\n[16:54:12.507464][plugin.youtube][debug] Video ID from URL\\n[16:54:12.507485][plugin.youtube][debug] Using video ID: VaU6GR8OHNU\\n[16:54:13.673312][plugin.youtube][debug] get_video_info - 1: Found data\\n[16:54:13.674497][plugin.youtube][debug] MuxedStream: v 135 a 251 = 480p\\n[16:54:13.674534][plugin.youtube][debug] MuxedStream: v 133 a 251 = 240p\\n[16:54:13.674558][plugin.youtube][debug] MuxedStream: v 160 a 251 = 144p\\n[16:54:13.675102][cli][info] Available streams: audio_mp4a, audio_opus, 144p (worst), 240p, 360p, 480p (best)\\n[16:54:13.675143][cli][info] Opening stream: 480p (muxed-stream)\\n[16:54:13.675175][stream.ffmpegmux][debug] Opening http substream\\n[16:54:13.753371][stream.ffmpegmux][debug] Opening http substream\\n[16:54:13.833386][stream.ffmpegmux][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-9811-893 -i /tmp/ffmpeg-9811-933 -c:v copy -c:a copy -map 0 -map 1 -f matroska pipe:1\\n[16:54:13.833582][stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-9811-893\\n[16:54:13.833781][stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-9811-933\\n[16:54:13.836427][cli][debug] Pre-buffering 8192 bytes\\n[16:54:13.894765][cli][info] Starting player: /usr/bin/mpv\\n[16:54:13.895198][cli.output][debug] Opening subprocess: /usr/bin/mpv ""--title=Christmas Music 2020 🎅 Top Christmas Songs Playlist 2020 🎄 Best Christmas Songs Ever"" -\\n[16:54:14.398240][cli][debug] Writing stream to output\\n[16:54:34.826911][cli][info] Player closed\\n[16:54:34.827058][stream.ffmpegmux][debug] Closing ffmpeg thread\\n[16:54:34.829721][stream.ffmpegmux][error] Pipe copy aborted: /tmp/ffmpeg-9811-893\\n[16:54:34.829823][stream.ffmpegmux][error] Pipe copy aborted: /tmp/ffmpeg-9811-933\\n[16:54:34.941941][stream.ffmpegmux][debug] Closed all the substreams\\n[16:54:34.942041][cli][info] Stream ended\\n[16:54:34.942232][cli][info] Closing currently open stream...\\n[16:54:34.942273][stream.ffmpegmux][debug] Closing ffmpeg thread\\n[16:54:34.942333][stream.ffmpegmux][debug] Closed all the substreams\\n--- Logging error ---\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 1081, in emit\\nmsg = self.format(record)\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 925, in format\\nreturn fmt.format(record)\\nFile ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 53, in format\\nreturn super().format(record)\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 666, in format\\nrecord.asctime = self.formatTime(record, self.datefmt)\\nFile ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 40, in formatTime\\nreturn tdt.strftime(datefmt or self.default_time_format)\\nImportError: sys.meta_path is None, Python is likely shutting down\\nCall stack:\\nFile ""venv3/lib/python3.8/site-packages/streamlink/stream/ffmpegmux.py"", line 156, in close\\nlog.debug(""Closing ffmpeg thread"")\\nMessage: \\'Closing ffmpeg thread\\'\\nArguments: ()\\n--- Logging error ---\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 1081, in emit\\nmsg = self.format(record)\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 925, in format\\nreturn fmt.format(record)\\nFile ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 53, in format\\nreturn super().format(record)\\nFile ""/usr/lib/python3.8/logging/__init__.py"", line 666, in format\\nrecord.asctime = self.formatTime(record, self.datefmt)\\nFile ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 40, in formatTime\\nreturn tdt.strftime(datefmt or self.default_time_format)\\nImportError: sys.meta_path is None, Python is likely shutting down\\nCall stack:\\nFile ""venv3/lib/python3.8/site-packages/streamlink/stream/ffmpegmux.py"", line 167, in close\\nlog.debug(""Closed all the substreams"")\\nMessage: \\'Closed all the substreams\\'\\nArguments: ()'}]","$ streamlink ""https://www.youtube.com/watch?v=VaU6GR8OHNU"" -l trace +[16:51:11.763092][cli][debug] OS: Linux-5.8.0-29-generic-x86_64-with-glibc2.32 +[16:51:11.763170][cli][debug] Python: 3.8.6 +[16:51:11.763193][cli][debug] Streamlink: 1.7.0+21.g70dc809 +[16:51:11.763212][cli][debug] Requests(2.25.0), Socks(1.7.1), Websocket(0.57.0) +[16:51:11.763245][cli][info] Found matching plugin youtube for URL https://www.youtube.com/watch?v=VaU6GR8OHNU +[16:51:11.763275][plugin.youtube][debug] Video ID from URL +[16:51:11.763295][plugin.youtube][debug] Using video ID: VaU6GR8OHNU +[16:51:12.669559][plugin.youtube][debug] get_video_info - 1: Found data +[16:51:12.670741][plugin.youtube][debug] MuxedStream: v 135 a 251 = 480p +[16:51:12.670780][plugin.youtube][debug] MuxedStream: v 133 a 251 = 240p +[16:51:12.670804][plugin.youtube][debug] MuxedStream: v 160 a 251 = 144p +[16:51:12.671317][cli][info] Available streams: audio_mp4a, audio_opus, 144p (worst), 240p, 360p, 480p (best) +[16:51:12.671355][cli][info] Opening stream: 480p (muxed-stream) +[16:51:12.671386][stream.ffmpegmux][debug] Opening http substream +[16:51:12.750200][stream.ffmpegmux][debug] Opening http substream +[16:51:12.813040][stream.ffmpegmux][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-9607-784 -i /tmp/ffmpeg-9607-270 -c:v copy -c:a copy -map 0 -map 1 -f matroska pipe:1 +[16:51:12.813226][stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-9607-784 +[16:51:12.813344][stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-9607-270 +[16:51:12.815867][cli][debug] Pre-buffering 8192 bytes +[16:51:12.875782][cli][info] Starting player: /usr/bin/mpv +[16:51:12.876152][cli.output][debug] Opening subprocess: /usr/bin/mpv ""--title=Christmas Music 2020 🎅 Top Christmas Songs Playlist 2020 🎄 Best Christmas Songs Ever"" - +[16:51:13.378673][cli][debug] Writing stream to output +[16:51:19.777326][cli][info] Player closed +[16:51:19.777459][stream.ffmpegmux][debug] Closing ffmpeg thread +[16:51:19.779916][stream.ffmpegmux][error] Pipe copy aborted: /tmp/ffmpeg-9607-270 +[16:51:19.780000][stream.ffmpegmux][error] Pipe copy aborted: /tmp/ffmpeg-9607-784 +[16:51:26.824121][stream.ffmpegmux][debug] Closed all the substreams +[16:51:26.824246][cli][info] Stream ended +[16:51:26.824434][cli][info] Closing currently open stream... +[16:51:26.824477][stream.ffmpegmux][debug] Closing ffmpeg thread +[16:51:26.824539][stream.ffmpegmux][debug] Closed all the substreams +--- Logging error --- +Traceback (most recent call last): +File ""/usr/lib/python3.8/logging/__init__.py"", line 1081, in emit +msg = self.format(record) +File ""/usr/lib/python3.8/logging/__init__.py"", line 925, in format +return fmt.format(record) +File ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 54, in format +return super().format(record) +File ""/usr/lib/python3.8/logging/__init__.py"", line 666, in format +record.asctime = self.formatTime(record, self.datefmt) +File ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 41, in formatTime +return tdt.strftime(datefmt or self.default_time_format) +ImportError: sys.meta_path is None, Python is likely shutting down +Call stack: +File ""venv3/lib/python3.8/site-packages/streamlink/stream/ffmpegmux.py"", line 158, in close +log.debug(""Closing ffmpeg thread"") +Message: 'Closing ffmpeg thread' +Arguments: () +--- Logging error --- +Traceback (most recent call last): +File ""/usr/lib/python3.8/logging/__init__.py"", line 1081, in emit +msg = self.format(record) +File ""/usr/lib/python3.8/logging/__init__.py"", line 925, in format +return fmt.format(record) +File ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 54, in format +return super().format(record) +File ""/usr/lib/python3.8/logging/__init__.py"", line 666, in format +record.asctime = self.formatTime(record, self.datefmt) +File ""venv3/lib/python3.8/site-packages/streamlink/logger.py"", line 41, in formatTime +return tdt.strftime(datefmt or self.default_time_format) +ImportError: sys.meta_path is None, Python is likely shutting down +Call stack: +File ""venv3/lib/python3.8/site-packages/streamlink/stream/ffmpegmux.py"", line 169, in close +log.debug(""Closed all the substreams"") +Message: 'Closed all the substreams' +Arguments: ()",ImportError +" def authenticate(self): + try: + data = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema) + except CrunchyrollAPIError: + self.auth = None + self.cache.set(""auth"", None, expires_at=0) + log.warning(""Saved credentials have expired"") + return + + log.debug(""Credentials expire at: {}"".format(data[""expires""])) + self.cache.set(""auth"", self.auth, expires_at=data[""expires""]) + return data"," def authenticate(self): + data = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema) + self.auth = data[""auth""] + self.cache.set(""auth"", data[""auth""], expires_at=data[""expires""]) + return data","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""runpy.py"", line 193, in _run_module_as_main\\nFile ""runpy.py"", line 85, in _run_code\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\bin\\\\streamlink.exe\\\\__main__.py"", line 18, in \\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 1024, in main\\nhandle_url()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 585, in handle_url\\nstreams = fetch_streams(plugin)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 465, in fetch_streams\\nsorting_excludes=args.stream_sorting_excludes)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugin\\\\plugin.py"", line 317, in streams\\nostreams = self._get_streams()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 306, in _get_streams\\napi = self._create_api()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 369, in _create_api\\nlogin = api.authenticate()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 217, in authenticate\\ndata = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 173, in _api_call\\nraise CrunchyrollAPIError(err_msg, err_code)\\nstreamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.'}, {'piece_type': 'error message', 'piece_content': '[cli][debug] OS: Windows 10\\n[cli][debug] Python: 3.6.6\\n[cli][debug] Streamlink: 1.5.0\\n[cli][debug] Requests(2.24.0), Socks(1.7.1), Websocket(0.57.0)\\n[cli][info] Found matching plugin crunchyroll for URL https://www.crunchyroll.com/my-teen-romantic-comedy-snafu/episode-9-a-whiff-of-that-fragrance-will-always-bring-memories-of-that-season-796536\\n[cli][debug] Plugin specific arguments:\\n[cli][debug] --crunchyroll-username=******** (username)\\n[cli][debug] --crunchyroll-password=******** (password)\\n[utils.l10n][debug] Language code: en_US\\n[plugin.crunchyroll][debug] Creating session with locale: en_US\\n[plugin.crunchyroll][debug] Session created with ID: c492ba4c706943f73dbf9819a8237465\\n[plugin.crunchyroll][debug] Using saved credentials\\nTraceback (most recent call last):\\nFile ""runpy.py"", line 193, in _run_module_as_main\\nFile ""runpy.py"", line 85, in _run_code\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\bin\\\\streamlink.exe\\\\__main__.py"", line 18, in \\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 1024, in main\\nhandle_url()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 585, in handle_url\\nstreams = fetch_streams(plugin)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 465, in fetch_streams\\nsorting_excludes=args.stream_sorting_excludes)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugin\\\\plugin.py"", line 317, in streams\\nostreams = self._get_streams()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 306, in _get_streams\\napi = self._create_api()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 369, in _create_api\\nlogin = api.authenticate()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 217, in authenticate\\ndata = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 173, in _api_call\\nraise CrunchyrollAPIError(err_msg, err_code)\\nstreamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.'}]","Traceback (most recent call last): +File ""runpy.py"", line 193, in _run_module_as_main +File ""runpy.py"", line 85, in _run_code +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\bin\\streamlink.exe\\__main__.py"", line 18, in +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 1024, in main +handle_url() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 585, in handle_url +streams = fetch_streams(plugin) +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 465, in fetch_streams +sorting_excludes=args.stream_sorting_excludes) +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugin\\plugin.py"", line 317, in streams +ostreams = self._get_streams() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 306, in _get_streams +api = self._create_api() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 369, in _create_api +login = api.authenticate() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 217, in authenticate +data = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema) +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 173, in _api_call +raise CrunchyrollAPIError(err_msg, err_code) +streamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.",streamlink.plugin.crunchyroll.CrunchyrollAPIError +" def _get_streams(self): + api = self._create_api() + match = _url_re.match(self.url) + media_id = int(match.group(""media_id"")) + + try: + # the media.stream_data field is required, no stream data is returned otherwise + info = api.get_info(media_id, fields=[""media.stream_data""], schema=_media_schema) + except CrunchyrollAPIError as err: + raise PluginError(u""Media lookup error: {0}"".format(err.msg)) + + if not info: + return + + streams = {} + + # The adaptive quality stream sometimes a subset of all the other streams listed, ultra is no included + has_adaptive = any([s[u""quality""] == u""adaptive"" for s in info[u""streams""]]) + if has_adaptive: + log.debug(u""Loading streams from adaptive playlist"") + for stream in filter(lambda x: x[u""quality""] == u""adaptive"", info[u""streams""]): + for q, s in HLSStream.parse_variant_playlist(self.session, stream[u""url""]).items(): + # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams + name = STREAM_NAMES.get(q, q) + streams[name] = s + + # If there is no adaptive quality stream then parse each individual result + for stream in info[u""streams""]: + if stream[u""quality""] != u""adaptive"": + # the video_encode_id indicates that the stream is not a variant playlist + if u""video_encode_id"" in stream: + streams[stream[u""quality""]] = HLSStream(self.session, stream[u""url""]) + else: + # otherwise the stream url is actually a list of stream qualities + for q, s in HLSStream.parse_variant_playlist(self.session, stream[u""url""]).items(): + # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams + name = STREAM_NAMES.get(q, q) + streams[name] = s + + return streams"," def _get_streams(self): + api = self._create_api() + match = _url_re.match(self.url) + media_id = int(match.group(""media_id"")) + + try: + # the media.stream_data field is required, no stream data is returned otherwise + info = api.get_info(media_id, fields=[""media.stream_data""], schema=_media_schema) + except CrunchyrollAPIError as err: + raise PluginError(u""Media lookup error: {0}"".format(err.msg)) + + if not info: + return + + streams = {} + + # The adaptive quality stream sometimes a subset of all the other streams listed, ultra is no included + has_adaptive = any([s[u""quality""] == u""adaptive"" for s in info[u""streams""]]) + if has_adaptive: + self.logger.debug(u""Loading streams from adaptive playlist"") + for stream in filter(lambda x: x[u""quality""] == u""adaptive"", info[u""streams""]): + for q, s in HLSStream.parse_variant_playlist(self.session, stream[u""url""]).items(): + # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams + name = STREAM_NAMES.get(q, q) + streams[name] = s + + # If there is no adaptive quality stream then parse each individual result + for stream in info[u""streams""]: + if stream[u""quality""] != u""adaptive"": + # the video_encode_id indicates that the stream is not a variant playlist + if u""video_encode_id"" in stream: + streams[stream[u""quality""]] = HLSStream(self.session, stream[u""url""]) + else: + # otherwise the stream url is actually a list of stream qualities + for q, s in HLSStream.parse_variant_playlist(self.session, stream[u""url""]).items(): + # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams + name = STREAM_NAMES.get(q, q) + streams[name] = s + + return streams","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""runpy.py"", line 193, in _run_module_as_main\\nFile ""runpy.py"", line 85, in _run_code\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\bin\\\\streamlink.exe\\\\__main__.py"", line 18, in \\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 1024, in main\\nhandle_url()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 585, in handle_url\\nstreams = fetch_streams(plugin)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 465, in fetch_streams\\nsorting_excludes=args.stream_sorting_excludes)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugin\\\\plugin.py"", line 317, in streams\\nostreams = self._get_streams()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 306, in _get_streams\\napi = self._create_api()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 369, in _create_api\\nlogin = api.authenticate()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 217, in authenticate\\ndata = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 173, in _api_call\\nraise CrunchyrollAPIError(err_msg, err_code)\\nstreamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.'}, {'piece_type': 'error message', 'piece_content': '[cli][debug] OS: Windows 10\\n[cli][debug] Python: 3.6.6\\n[cli][debug] Streamlink: 1.5.0\\n[cli][debug] Requests(2.24.0), Socks(1.7.1), Websocket(0.57.0)\\n[cli][info] Found matching plugin crunchyroll for URL https://www.crunchyroll.com/my-teen-romantic-comedy-snafu/episode-9-a-whiff-of-that-fragrance-will-always-bring-memories-of-that-season-796536\\n[cli][debug] Plugin specific arguments:\\n[cli][debug] --crunchyroll-username=******** (username)\\n[cli][debug] --crunchyroll-password=******** (password)\\n[utils.l10n][debug] Language code: en_US\\n[plugin.crunchyroll][debug] Creating session with locale: en_US\\n[plugin.crunchyroll][debug] Session created with ID: c492ba4c706943f73dbf9819a8237465\\n[plugin.crunchyroll][debug] Using saved credentials\\nTraceback (most recent call last):\\nFile ""runpy.py"", line 193, in _run_module_as_main\\nFile ""runpy.py"", line 85, in _run_code\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\bin\\\\streamlink.exe\\\\__main__.py"", line 18, in \\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 1024, in main\\nhandle_url()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 585, in handle_url\\nstreams = fetch_streams(plugin)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 465, in fetch_streams\\nsorting_excludes=args.stream_sorting_excludes)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugin\\\\plugin.py"", line 317, in streams\\nostreams = self._get_streams()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 306, in _get_streams\\napi = self._create_api()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 369, in _create_api\\nlogin = api.authenticate()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 217, in authenticate\\ndata = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 173, in _api_call\\nraise CrunchyrollAPIError(err_msg, err_code)\\nstreamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.'}]","Traceback (most recent call last): +File ""runpy.py"", line 193, in _run_module_as_main +File ""runpy.py"", line 85, in _run_code +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\bin\\streamlink.exe\\__main__.py"", line 18, in +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 1024, in main +handle_url() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 585, in handle_url +streams = fetch_streams(plugin) +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 465, in fetch_streams +sorting_excludes=args.stream_sorting_excludes) +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugin\\plugin.py"", line 317, in streams +ostreams = self._get_streams() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 306, in _get_streams +api = self._create_api() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 369, in _create_api +login = api.authenticate() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 217, in authenticate +data = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema) +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 173, in _api_call +raise CrunchyrollAPIError(err_msg, err_code) +streamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.",streamlink.plugin.crunchyroll.CrunchyrollAPIError +" def _create_api(self): + """"""Creates a new CrunchyrollAPI object, initiates it's session and + tries to authenticate it either by using saved credentials or the + user's username and password. + """""" + if self.options.get(""purge_credentials""): + self.cache.set(""session_id"", None, 0) + self.cache.set(""auth"", None, 0) + self.cache.set(""session_id"", None, 0) + + # use the crunchyroll locale as an override, for backwards compatibility + locale = self.get_option(""locale"") or self.session.localization.language_code + api = CrunchyrollAPI(self.cache, + self.session, + session_id=self.get_option(""session_id""), + locale=locale) + + if not self.get_option(""session_id""): + log.debug(""Creating session with locale: {0}"", locale) + api.start_session() + + if api.auth: + log.debug(""Using saved credentials"") + login = api.authenticate() + if login: + log.info(""Successfully logged in as '{0}'"", + login[""user""][""username""] or login[""user""][""email""]) + if not api.auth and self.options.get(""username""): + try: + log.debug(""Attempting to login using username and password"") + api.login(self.options.get(""username""), + self.options.get(""password"")) + login = api.authenticate() + log.info(""Logged in as '{0}'"", + login[""user""][""username""] or login[""user""][""email""]) + + except CrunchyrollAPIError as err: + raise PluginError(u""Authentication error: {0}"".format(err.msg)) + if not api.auth: + log.warning( + ""No authentication provided, you won't be able to access "" + ""premium restricted content"" + ) + + return api"," def _create_api(self): + """"""Creates a new CrunchyrollAPI object, initiates it's session and + tries to authenticate it either by using saved credentials or the + user's username and password. + """""" + if self.options.get(""purge_credentials""): + self.cache.set(""session_id"", None, 0) + self.cache.set(""auth"", None, 0) + self.cache.set(""session_id"", None, 0) + + # use the crunchyroll locale as an override, for backwards compatibility + locale = self.get_option(""locale"") or self.session.localization.language_code + api = CrunchyrollAPI(self.cache, + self.session, + session_id=self.get_option(""session_id""), + locale=locale) + + if not self.get_option(""session_id""): + self.logger.debug(""Creating session with locale: {0}"", locale) + api.start_session() + + if api.auth: + self.logger.debug(""Using saved credentials"") + login = api.authenticate() + self.logger.info(""Successfully logged in as '{0}'"", + login[""user""][""username""] or login[""user""][""email""]) + elif self.options.get(""username""): + try: + self.logger.debug(""Attempting to login using username and password"") + api.login(self.options.get(""username""), + self.options.get(""password"")) + login = api.authenticate() + self.logger.info(""Logged in as '{0}'"", + login[""user""][""username""] or login[""user""][""email""]) + + except CrunchyrollAPIError as err: + raise PluginError(u""Authentication error: {0}"".format(err.msg)) + else: + self.logger.warning( + ""No authentication provided, you won't be able to access "" + ""premium restricted content"" + ) + + return api","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""runpy.py"", line 193, in _run_module_as_main\\nFile ""runpy.py"", line 85, in _run_code\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\bin\\\\streamlink.exe\\\\__main__.py"", line 18, in \\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 1024, in main\\nhandle_url()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 585, in handle_url\\nstreams = fetch_streams(plugin)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 465, in fetch_streams\\nsorting_excludes=args.stream_sorting_excludes)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugin\\\\plugin.py"", line 317, in streams\\nostreams = self._get_streams()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 306, in _get_streams\\napi = self._create_api()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 369, in _create_api\\nlogin = api.authenticate()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 217, in authenticate\\ndata = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 173, in _api_call\\nraise CrunchyrollAPIError(err_msg, err_code)\\nstreamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.'}, {'piece_type': 'error message', 'piece_content': '[cli][debug] OS: Windows 10\\n[cli][debug] Python: 3.6.6\\n[cli][debug] Streamlink: 1.5.0\\n[cli][debug] Requests(2.24.0), Socks(1.7.1), Websocket(0.57.0)\\n[cli][info] Found matching plugin crunchyroll for URL https://www.crunchyroll.com/my-teen-romantic-comedy-snafu/episode-9-a-whiff-of-that-fragrance-will-always-bring-memories-of-that-season-796536\\n[cli][debug] Plugin specific arguments:\\n[cli][debug] --crunchyroll-username=******** (username)\\n[cli][debug] --crunchyroll-password=******** (password)\\n[utils.l10n][debug] Language code: en_US\\n[plugin.crunchyroll][debug] Creating session with locale: en_US\\n[plugin.crunchyroll][debug] Session created with ID: c492ba4c706943f73dbf9819a8237465\\n[plugin.crunchyroll][debug] Using saved credentials\\nTraceback (most recent call last):\\nFile ""runpy.py"", line 193, in _run_module_as_main\\nFile ""runpy.py"", line 85, in _run_code\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\bin\\\\streamlink.exe\\\\__main__.py"", line 18, in \\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 1024, in main\\nhandle_url()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 585, in handle_url\\nstreams = fetch_streams(plugin)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 465, in fetch_streams\\nsorting_excludes=args.stream_sorting_excludes)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugin\\\\plugin.py"", line 317, in streams\\nostreams = self._get_streams()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 306, in _get_streams\\napi = self._create_api()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 369, in _create_api\\nlogin = api.authenticate()\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 217, in authenticate\\ndata = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema)\\nFile ""C:\\\\Users\\\\kg\\\\AppData\\\\Local\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\crunchyroll.py"", line 173, in _api_call\\nraise CrunchyrollAPIError(err_msg, err_code)\\nstreamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.'}]","Traceback (most recent call last): +File ""runpy.py"", line 193, in _run_module_as_main +File ""runpy.py"", line 85, in _run_code +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\bin\\streamlink.exe\\__main__.py"", line 18, in +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 1024, in main +handle_url() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 585, in handle_url +streams = fetch_streams(plugin) +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 465, in fetch_streams +sorting_excludes=args.stream_sorting_excludes) +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugin\\plugin.py"", line 317, in streams +ostreams = self._get_streams() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 306, in _get_streams +api = self._create_api() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 369, in _create_api +login = api.authenticate() +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 217, in authenticate +data = self._api_call(""authenticate"", {""auth"": self.auth}, schema=_login_schema) +File ""C:\\Users\\kg\\AppData\\Local\\Streamlink\\pkgs\\streamlink\\plugins\\crunchyroll.py"", line 173, in _api_call +raise CrunchyrollAPIError(err_msg, err_code) +streamlink.plugin.crunchyroll.CrunchyrollAPIError: User could not be found.",streamlink.plugin.crunchyroll.CrunchyrollAPIError +"def create_title(plugin=None): + if args.title and plugin: + title = LazyFormatter.format( + maybe_decode(args.title, get_filesystem_encoding()), + title=lambda: plugin.get_title() or DEFAULT_STREAM_METADATA[""title""], + author=lambda: plugin.get_author() or DEFAULT_STREAM_METADATA[""author""], + category=lambda: plugin.get_category() or DEFAULT_STREAM_METADATA[""category""], + game=lambda: plugin.get_category() or DEFAULT_STREAM_METADATA[""game""], + url=plugin.url + ) + else: + title = args.url + return title","def create_title(plugin=None): + if args.title and plugin: + title = LazyFormatter.format( + maybe_encode(args.title), + title=lambda: plugin.get_title() or DEFAULT_STREAM_METADATA[""title""], + author=lambda: plugin.get_author() or DEFAULT_STREAM_METADATA[""author""], + category=lambda: plugin.get_category() or DEFAULT_STREAM_METADATA[""category""], + game=lambda: plugin.get_category() or DEFAULT_STREAM_METADATA[""game""], + url=plugin.url + ) + else: + title = args.url + return title","[{'piece_type': 'error message', 'piece_content': 'OS: macOS 10.14.2\\nPython: 2.7.14\\nStreamlink: 1.1.1\\nRequests(2.21.0), Socks(1.6.7), Websocket(0.47.0)\\nFound matching plugin twitch for URL twitch.tv/quickybaby\\nPlugin specific arguments:\\n--twitch-oauth-token=******** (oauth_token)\\n--twitch-disable-hosting=True (disable_hosting)\\n--twitch-disable-ads=True (disable_ads)\\nGetting live HLS streams for quickybaby\\nAttempting to authenticate using OAuth token\\nSuccessfully logged in as DELETE\\n[utils.l10n][debug] Language code: en_US\\nAvailable streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best)\\nOpening stream: 1080p60 (hls)\\nStarting player: /Applications/mpv.app/Contents/MacOS/mpv\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/streamlink"", line 11, in \\nload_entry_point(\\'streamlink==1.1.1\\', \\'console_scripts\\', \\'streamlink\\')()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main\\nhandle_url()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url\\nhandle_stream(plugin, streams, stream_name)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream\\nsuccess = output_stream_passthrough(plugin, stream)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough\\noutput.open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open\\nself._open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open\\nself._open_call()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call\\nlog.debug(u""Calling: {0}"".format(fargs))\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 141: ordinal not in range(128)'}]","OS: macOS 10.14.2 +Python: 2.7.14 +Streamlink: 1.1.1 +Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) +Found matching plugin twitch for URL twitch.tv/quickybaby +Plugin specific arguments: +--twitch-oauth-token=******** (oauth_token) +--twitch-disable-hosting=True (disable_hosting) +--twitch-disable-ads=True (disable_ads) +Getting live HLS streams for quickybaby +Attempting to authenticate using OAuth token +Successfully logged in as DELETE +[utils.l10n][debug] Language code: en_US +Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) +Opening stream: 1080p60 (hls) +Starting player: /Applications/mpv.app/Contents/MacOS/mpv +Traceback (most recent call last): +File ""/usr/local/bin/streamlink"", line 11, in +load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main +handle_url() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url +handle_stream(plugin, streams, stream_name) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream +success = output_stream_passthrough(plugin, stream) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough +output.open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open +self._open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open +self._open_call() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call +log.debug(u""Calling: {0}"".format(fargs)) +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)",UnicodeDecodeError +" def _create_arguments(self): + if self.namedpipe: + filename = self.namedpipe.path + elif self.filename: + filename = self.filename + elif self.http: + filename = self.http.url + else: + filename = ""-"" + extra_args = [] + + if self.title is not None: + # vlc + if self.player_name == ""vlc"": + # see https://wiki.videolan.org/Documentation:Format_String/, allow escaping with \\$ + self.title = self.title.replace(""$"", ""$$"").replace(r'\\$$', ""$"") + extra_args.extend([u""--input-title-format"", self.title]) + + # mpv + if self.player_name == ""mpv"": + # see https://mpv.io/manual/stable/#property-expansion, allow escaping with \\$, respect mpv's $> + self.title = self._mpv_title_escape(self.title) + extra_args.append(u""--title={}"".format(self.title)) + + # potplayer + if self.player_name == ""potplayer"": + if filename != ""-"": + # PotPlayer - About - Command Line + # You can specify titles for URLs by separating them with a backslash (\\) at the end of URLs. + # eg. ""http://...\\title of this url"" + self.title = self.title.replace('""', '') + filename = filename[:-1] + '\\\\' + self.title + filename[-1] + + args = self.args.format(filename=filename) + cmd = self.cmd + + # player command + if is_win32: + eargs = maybe_decode(subprocess.list2cmdline(extra_args)) + # do not insert and extra "" "" when there are no extra_args + return u' '.join([cmd] + ([eargs] if eargs else []) + [args]) + return shlex.split(cmd) + extra_args + shlex.split(args)"," def _create_arguments(self): + if self.namedpipe: + filename = self.namedpipe.path + elif self.filename: + filename = self.filename + elif self.http: + filename = self.http.url + else: + filename = ""-"" + extra_args = [] + + if self.title is not None: + # vlc + if self.player_name == ""vlc"": + # see https://wiki.videolan.org/Documentation:Format_String/, allow escaping with \\$ + self.title = self.title.replace(""$"", ""$$"").replace(r'\\$$', ""$"") + extra_args.extend([""--input-title-format"", self.title]) + + # mpv + if self.player_name == ""mpv"": + # see https://mpv.io/manual/stable/#property-expansion, allow escaping with \\$, respect mpv's $> + self.title = self._mpv_title_escape(self.title) + extra_args.append(""--title={}"".format(self.title)) + + # potplayer + if self.player_name == ""potplayer"": + if filename != ""-"": + # PotPlayer - About - Command Line + # You can specify titles for URLs by separating them with a backslash (\\) at the end of URLs. + # eg. ""http://...\\title of this url"" + self.title = self.title.replace('""', '') + filename = filename[:-1] + '\\\\' + self.title + filename[-1] + + args = self.args.format(filename=filename) + cmd = self.cmd + + # player command + if is_win32: + eargs = maybe_decode(subprocess.list2cmdline(extra_args)) + # do not insert and extra "" "" when there are no extra_args + return maybe_encode(u' '.join([cmd] + ([eargs] if eargs else []) + [args]), + encoding=get_filesystem_encoding()) + return shlex.split(cmd) + extra_args + shlex.split(args)","[{'piece_type': 'error message', 'piece_content': 'OS: macOS 10.14.2\\nPython: 2.7.14\\nStreamlink: 1.1.1\\nRequests(2.21.0), Socks(1.6.7), Websocket(0.47.0)\\nFound matching plugin twitch for URL twitch.tv/quickybaby\\nPlugin specific arguments:\\n--twitch-oauth-token=******** (oauth_token)\\n--twitch-disable-hosting=True (disable_hosting)\\n--twitch-disable-ads=True (disable_ads)\\nGetting live HLS streams for quickybaby\\nAttempting to authenticate using OAuth token\\nSuccessfully logged in as DELETE\\n[utils.l10n][debug] Language code: en_US\\nAvailable streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best)\\nOpening stream: 1080p60 (hls)\\nStarting player: /Applications/mpv.app/Contents/MacOS/mpv\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/streamlink"", line 11, in \\nload_entry_point(\\'streamlink==1.1.1\\', \\'console_scripts\\', \\'streamlink\\')()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main\\nhandle_url()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url\\nhandle_stream(plugin, streams, stream_name)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream\\nsuccess = output_stream_passthrough(plugin, stream)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough\\noutput.open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open\\nself._open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open\\nself._open_call()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call\\nlog.debug(u""Calling: {0}"".format(fargs))\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 141: ordinal not in range(128)'}]","OS: macOS 10.14.2 +Python: 2.7.14 +Streamlink: 1.1.1 +Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) +Found matching plugin twitch for URL twitch.tv/quickybaby +Plugin specific arguments: +--twitch-oauth-token=******** (oauth_token) +--twitch-disable-hosting=True (disable_hosting) +--twitch-disable-ads=True (disable_ads) +Getting live HLS streams for quickybaby +Attempting to authenticate using OAuth token +Successfully logged in as DELETE +[utils.l10n][debug] Language code: en_US +Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) +Opening stream: 1080p60 (hls) +Starting player: /Applications/mpv.app/Contents/MacOS/mpv +Traceback (most recent call last): +File ""/usr/local/bin/streamlink"", line 11, in +load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main +handle_url() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url +handle_stream(plugin, streams, stream_name) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream +success = output_stream_passthrough(plugin, stream) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough +output.open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open +self._open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open +self._open_call() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call +log.debug(u""Calling: {0}"".format(fargs)) +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)",UnicodeDecodeError +" def _open_call(self): + args = self._create_arguments() + if is_win32: + fargs = args + else: + fargs = subprocess.list2cmdline(args) + log.debug(u""Calling: {0}"".format(fargs)) + + subprocess.call(maybe_encode(args, get_filesystem_encoding()), + stdout=self.stdout, + stderr=self.stderr)"," def _open_call(self): + args = self._create_arguments() + if is_win32: + fargs = args + else: + fargs = subprocess.list2cmdline(args) + log.debug(u""Calling: {0}"".format(maybe_decode(fargs))) + subprocess.call(args, + stdout=self.stdout, + stderr=self.stderr)","[{'piece_type': 'error message', 'piece_content': 'OS: macOS 10.14.2\\nPython: 2.7.14\\nStreamlink: 1.1.1\\nRequests(2.21.0), Socks(1.6.7), Websocket(0.47.0)\\nFound matching plugin twitch for URL twitch.tv/quickybaby\\nPlugin specific arguments:\\n--twitch-oauth-token=******** (oauth_token)\\n--twitch-disable-hosting=True (disable_hosting)\\n--twitch-disable-ads=True (disable_ads)\\nGetting live HLS streams for quickybaby\\nAttempting to authenticate using OAuth token\\nSuccessfully logged in as DELETE\\n[utils.l10n][debug] Language code: en_US\\nAvailable streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best)\\nOpening stream: 1080p60 (hls)\\nStarting player: /Applications/mpv.app/Contents/MacOS/mpv\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/streamlink"", line 11, in \\nload_entry_point(\\'streamlink==1.1.1\\', \\'console_scripts\\', \\'streamlink\\')()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main\\nhandle_url()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url\\nhandle_stream(plugin, streams, stream_name)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream\\nsuccess = output_stream_passthrough(plugin, stream)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough\\noutput.open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open\\nself._open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open\\nself._open_call()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call\\nlog.debug(u""Calling: {0}"".format(fargs))\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 141: ordinal not in range(128)'}]","OS: macOS 10.14.2 +Python: 2.7.14 +Streamlink: 1.1.1 +Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) +Found matching plugin twitch for URL twitch.tv/quickybaby +Plugin specific arguments: +--twitch-oauth-token=******** (oauth_token) +--twitch-disable-hosting=True (disable_hosting) +--twitch-disable-ads=True (disable_ads) +Getting live HLS streams for quickybaby +Attempting to authenticate using OAuth token +Successfully logged in as DELETE +[utils.l10n][debug] Language code: en_US +Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) +Opening stream: 1080p60 (hls) +Starting player: /Applications/mpv.app/Contents/MacOS/mpv +Traceback (most recent call last): +File ""/usr/local/bin/streamlink"", line 11, in +load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main +handle_url() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url +handle_stream(plugin, streams, stream_name) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream +success = output_stream_passthrough(plugin, stream) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough +output.open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open +self._open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open +self._open_call() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call +log.debug(u""Calling: {0}"".format(fargs)) +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)",UnicodeDecodeError +" def _open_subprocess(self): + # Force bufsize=0 on all Python versions to avoid writing the + # unflushed buffer when closing a broken input pipe + args = self._create_arguments() + if is_win32: + fargs = args + else: + fargs = subprocess.list2cmdline(args) + log.debug(u""Opening subprocess: {0}"".format(fargs)) + + self.player = subprocess.Popen(maybe_encode(args, get_filesystem_encoding()), + stdin=self.stdin, bufsize=0, + stdout=self.stdout, + stderr=self.stderr) + # Wait 0.5 seconds to see if program exited prematurely + if not self.running: + raise OSError(""Process exited prematurely"") + + if self.namedpipe: + self.namedpipe.open(""wb"") + elif self.http: + self.http.open()"," def _open_subprocess(self): + # Force bufsize=0 on all Python versions to avoid writing the + # unflushed buffer when closing a broken input pipe + args = self._create_arguments() + if is_win32: + fargs = args + else: + fargs = subprocess.list2cmdline(args) + + log.debug(u""Opening subprocess: {0}"".format(maybe_decode(fargs))) + self.player = subprocess.Popen(args, + stdin=self.stdin, bufsize=0, + stdout=self.stdout, + stderr=self.stderr) + # Wait 0.5 seconds to see if program exited prematurely + if not self.running: + raise OSError(""Process exited prematurely"") + + if self.namedpipe: + self.namedpipe.open(""wb"") + elif self.http: + self.http.open()","[{'piece_type': 'error message', 'piece_content': 'OS: macOS 10.14.2\\nPython: 2.7.14\\nStreamlink: 1.1.1\\nRequests(2.21.0), Socks(1.6.7), Websocket(0.47.0)\\nFound matching plugin twitch for URL twitch.tv/quickybaby\\nPlugin specific arguments:\\n--twitch-oauth-token=******** (oauth_token)\\n--twitch-disable-hosting=True (disable_hosting)\\n--twitch-disable-ads=True (disable_ads)\\nGetting live HLS streams for quickybaby\\nAttempting to authenticate using OAuth token\\nSuccessfully logged in as DELETE\\n[utils.l10n][debug] Language code: en_US\\nAvailable streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best)\\nOpening stream: 1080p60 (hls)\\nStarting player: /Applications/mpv.app/Contents/MacOS/mpv\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/streamlink"", line 11, in \\nload_entry_point(\\'streamlink==1.1.1\\', \\'console_scripts\\', \\'streamlink\\')()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main\\nhandle_url()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url\\nhandle_stream(plugin, streams, stream_name)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream\\nsuccess = output_stream_passthrough(plugin, stream)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough\\noutput.open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open\\nself._open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open\\nself._open_call()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call\\nlog.debug(u""Calling: {0}"".format(fargs))\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 141: ordinal not in range(128)'}]","OS: macOS 10.14.2 +Python: 2.7.14 +Streamlink: 1.1.1 +Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) +Found matching plugin twitch for URL twitch.tv/quickybaby +Plugin specific arguments: +--twitch-oauth-token=******** (oauth_token) +--twitch-disable-hosting=True (disable_hosting) +--twitch-disable-ads=True (disable_ads) +Getting live HLS streams for quickybaby +Attempting to authenticate using OAuth token +Successfully logged in as DELETE +[utils.l10n][debug] Language code: en_US +Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) +Opening stream: 1080p60 (hls) +Starting player: /Applications/mpv.app/Contents/MacOS/mpv +Traceback (most recent call last): +File ""/usr/local/bin/streamlink"", line 11, in +load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main +handle_url() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url +handle_stream(plugin, streams, stream_name) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream +success = output_stream_passthrough(plugin, stream) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough +output.open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open +self._open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open +self._open_call() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call +log.debug(u""Calling: {0}"".format(fargs)) +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)",UnicodeDecodeError +"def maybe_encode(text, encoding=""utf8""): + if is_py2: + if isinstance(text, unicode): + return text.encode(encoding) + else: + return text + else: + return text","def maybe_encode(text, encoding=""utf8""): + if is_py2: + return text.encode(encoding) + else: + return text","[{'piece_type': 'error message', 'piece_content': 'OS: macOS 10.14.2\\nPython: 2.7.14\\nStreamlink: 1.1.1\\nRequests(2.21.0), Socks(1.6.7), Websocket(0.47.0)\\nFound matching plugin twitch for URL twitch.tv/quickybaby\\nPlugin specific arguments:\\n--twitch-oauth-token=******** (oauth_token)\\n--twitch-disable-hosting=True (disable_hosting)\\n--twitch-disable-ads=True (disable_ads)\\nGetting live HLS streams for quickybaby\\nAttempting to authenticate using OAuth token\\nSuccessfully logged in as DELETE\\n[utils.l10n][debug] Language code: en_US\\nAvailable streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best)\\nOpening stream: 1080p60 (hls)\\nStarting player: /Applications/mpv.app/Contents/MacOS/mpv\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/streamlink"", line 11, in \\nload_entry_point(\\'streamlink==1.1.1\\', \\'console_scripts\\', \\'streamlink\\')()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main\\nhandle_url()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url\\nhandle_stream(plugin, streams, stream_name)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream\\nsuccess = output_stream_passthrough(plugin, stream)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough\\noutput.open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open\\nself._open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open\\nself._open_call()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call\\nlog.debug(u""Calling: {0}"".format(fargs))\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 141: ordinal not in range(128)'}]","OS: macOS 10.14.2 +Python: 2.7.14 +Streamlink: 1.1.1 +Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) +Found matching plugin twitch for URL twitch.tv/quickybaby +Plugin specific arguments: +--twitch-oauth-token=******** (oauth_token) +--twitch-disable-hosting=True (disable_hosting) +--twitch-disable-ads=True (disable_ads) +Getting live HLS streams for quickybaby +Attempting to authenticate using OAuth token +Successfully logged in as DELETE +[utils.l10n][debug] Language code: en_US +Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) +Opening stream: 1080p60 (hls) +Starting player: /Applications/mpv.app/Contents/MacOS/mpv +Traceback (most recent call last): +File ""/usr/local/bin/streamlink"", line 11, in +load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main +handle_url() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url +handle_stream(plugin, streams, stream_name) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream +success = output_stream_passthrough(plugin, stream) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough +output.open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open +self._open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open +self._open_call() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call +log.debug(u""Calling: {0}"".format(fargs)) +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)",UnicodeDecodeError +" def _open_call(self): + args = self._create_arguments() + if is_win32: + fargs = args + else: + fargs = subprocess.list2cmdline(args) + log.debug(u""Calling: {0}"".format(maybe_decode(fargs))) + subprocess.call(args, + stdout=self.stdout, + stderr=self.stderr)"," def _open_call(self): + args = self._create_arguments() + if is_win32: + fargs = args + else: + fargs = subprocess.list2cmdline(args) + log.debug(u""Calling: {0}"".format(fargs)) + subprocess.call(args, + stdout=self.stdout, + stderr=self.stderr)","[{'piece_type': 'error message', 'piece_content': 'OS: macOS 10.14.2\\nPython: 2.7.14\\nStreamlink: 1.1.1\\nRequests(2.21.0), Socks(1.6.7), Websocket(0.47.0)\\nFound matching plugin twitch for URL twitch.tv/quickybaby\\nPlugin specific arguments:\\n--twitch-oauth-token=******** (oauth_token)\\n--twitch-disable-hosting=True (disable_hosting)\\n--twitch-disable-ads=True (disable_ads)\\nGetting live HLS streams for quickybaby\\nAttempting to authenticate using OAuth token\\nSuccessfully logged in as DELETE\\n[utils.l10n][debug] Language code: en_US\\nAvailable streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best)\\nOpening stream: 1080p60 (hls)\\nStarting player: /Applications/mpv.app/Contents/MacOS/mpv\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/streamlink"", line 11, in \\nload_entry_point(\\'streamlink==1.1.1\\', \\'console_scripts\\', \\'streamlink\\')()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main\\nhandle_url()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url\\nhandle_stream(plugin, streams, stream_name)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream\\nsuccess = output_stream_passthrough(plugin, stream)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough\\noutput.open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open\\nself._open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open\\nself._open_call()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call\\nlog.debug(u""Calling: {0}"".format(fargs))\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 141: ordinal not in range(128)'}]","OS: macOS 10.14.2 +Python: 2.7.14 +Streamlink: 1.1.1 +Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) +Found matching plugin twitch for URL twitch.tv/quickybaby +Plugin specific arguments: +--twitch-oauth-token=******** (oauth_token) +--twitch-disable-hosting=True (disable_hosting) +--twitch-disable-ads=True (disable_ads) +Getting live HLS streams for quickybaby +Attempting to authenticate using OAuth token +Successfully logged in as DELETE +[utils.l10n][debug] Language code: en_US +Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) +Opening stream: 1080p60 (hls) +Starting player: /Applications/mpv.app/Contents/MacOS/mpv +Traceback (most recent call last): +File ""/usr/local/bin/streamlink"", line 11, in +load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main +handle_url() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url +handle_stream(plugin, streams, stream_name) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream +success = output_stream_passthrough(plugin, stream) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough +output.open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open +self._open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open +self._open_call() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call +log.debug(u""Calling: {0}"".format(fargs)) +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)",UnicodeDecodeError +" def _open_subprocess(self): + # Force bufsize=0 on all Python versions to avoid writing the + # unflushed buffer when closing a broken input pipe + args = self._create_arguments() + if is_win32: + fargs = args + else: + fargs = subprocess.list2cmdline(args) + + log.debug(u""Opening subprocess: {0}"".format(maybe_decode(fargs))) + self.player = subprocess.Popen(args, + stdin=self.stdin, bufsize=0, + stdout=self.stdout, + stderr=self.stderr) + # Wait 0.5 seconds to see if program exited prematurely + if not self.running: + raise OSError(""Process exited prematurely"") + + if self.namedpipe: + self.namedpipe.open(""wb"") + elif self.http: + self.http.open()"," def _open_subprocess(self): + # Force bufsize=0 on all Python versions to avoid writing the + # unflushed buffer when closing a broken input pipe + args = self._create_arguments() + if is_win32: + fargs = args + else: + fargs = subprocess.list2cmdline(args) + log.debug(u""Opening subprocess: {0}"".format(fargs)) + self.player = subprocess.Popen(args, + stdin=self.stdin, bufsize=0, + stdout=self.stdout, + stderr=self.stderr) + # Wait 0.5 seconds to see if program exited prematurely + if not self.running: + raise OSError(""Process exited prematurely"") + + if self.namedpipe: + self.namedpipe.open(""wb"") + elif self.http: + self.http.open()","[{'piece_type': 'error message', 'piece_content': 'OS: macOS 10.14.2\\nPython: 2.7.14\\nStreamlink: 1.1.1\\nRequests(2.21.0), Socks(1.6.7), Websocket(0.47.0)\\nFound matching plugin twitch for URL twitch.tv/quickybaby\\nPlugin specific arguments:\\n--twitch-oauth-token=******** (oauth_token)\\n--twitch-disable-hosting=True (disable_hosting)\\n--twitch-disable-ads=True (disable_ads)\\nGetting live HLS streams for quickybaby\\nAttempting to authenticate using OAuth token\\nSuccessfully logged in as DELETE\\n[utils.l10n][debug] Language code: en_US\\nAvailable streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best)\\nOpening stream: 1080p60 (hls)\\nStarting player: /Applications/mpv.app/Contents/MacOS/mpv\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/streamlink"", line 11, in \\nload_entry_point(\\'streamlink==1.1.1\\', \\'console_scripts\\', \\'streamlink\\')()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main\\nhandle_url()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url\\nhandle_stream(plugin, streams, stream_name)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream\\nsuccess = output_stream_passthrough(plugin, stream)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough\\noutput.open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open\\nself._open()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open\\nself._open_call()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call\\nlog.debug(u""Calling: {0}"".format(fargs))\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xc3 in position 141: ordinal not in range(128)'}]","OS: macOS 10.14.2 +Python: 2.7.14 +Streamlink: 1.1.1 +Requests(2.21.0), Socks(1.6.7), Websocket(0.47.0) +Found matching plugin twitch for URL twitch.tv/quickybaby +Plugin specific arguments: +--twitch-oauth-token=******** (oauth_token) +--twitch-disable-hosting=True (disable_hosting) +--twitch-disable-ads=True (disable_ads) +Getting live HLS streams for quickybaby +Attempting to authenticate using OAuth token +Successfully logged in as DELETE +[utils.l10n][debug] Language code: en_US +Available streams: audio_only, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) +Opening stream: 1080p60 (hls) +Starting player: /Applications/mpv.app/Contents/MacOS/mpv +Traceback (most recent call last): +File ""/usr/local/bin/streamlink"", line 11, in +load_entry_point('streamlink==1.1.1', 'console_scripts', 'streamlink')() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 1033, in main +handle_url() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 594, in handle_url +handle_stream(plugin, streams, stream_name) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 437, in handle_stream +success = output_stream_passthrough(plugin, stream) +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/main.py"", line 262, in output_stream_passthrough +output.open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 24, in open +self._open() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 219, in _open +self._open_call() +File ""/usr/local/lib/python2.7/site-packages/streamlink-1.1.1-py2.7.egg/streamlink_cli/output.py"", line 234, in _open_call +log.debug(u""Calling: {0}"".format(fargs)) +UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 141: ordinal not in range(128)",UnicodeDecodeError +" def fetch(self, segment, retries=None): + if self.closed or not retries: + return + + try: + request_args = copy.deepcopy(self.reader.stream.args) + headers = request_args.pop(""headers"", {}) + now = datetime.datetime.now(tz=utc) + if segment.available_at > now: + time_to_wait = (segment.available_at - now).total_seconds() + fname = os.path.basename(urlparse(segment.url).path) + log.debug(""Waiting for segment: {fname} ({wait:.01f}s)"".format(fname=fname, wait=time_to_wait)) + sleep_until(segment.available_at) + + if segment.range: + start, length = segment.range + if length: + end = start + length - 1 + else: + end = """" + headers[""Range""] = ""bytes={0}-{1}"".format(start, end) + + return self.session.http.get(segment.url, + timeout=self.timeout, + exception=StreamError, + headers=headers, + **request_args) + except StreamError as err: + log.error(""Failed to open segment {0}: {1}"", segment.url, err) + return self.fetch(segment, retries - 1)"," def fetch(self, segment, retries=None): + if self.closed or not retries: + return + + try: + headers = {} + now = datetime.datetime.now(tz=utc) + if segment.available_at > now: + time_to_wait = (segment.available_at - now).total_seconds() + fname = os.path.basename(urlparse(segment.url).path) + log.debug(""Waiting for segment: {fname} ({wait:.01f}s)"".format(fname=fname, wait=time_to_wait)) + sleep_until(segment.available_at) + + if segment.range: + start, length = segment.range + if length: + end = start + length - 1 + else: + end = """" + headers[""Range""] = ""bytes={0}-{1}"".format(start, end) + + return self.session.http.get(segment.url, + timeout=self.timeout, + exception=StreamError, + headers=headers) + except StreamError as err: + log.error(""Failed to open segment {0}: {1}"", segment.url, err) + return self.fetch(segment, retries - 1)","[{'piece_type': 'error message', 'piece_content': '$ streamlink https://www.tf1.fr/lci/direct 576p_dash\\n[cli][debug] OS: Linux\\n[cli][debug] Python: 3.6.7\\n[cli][debug] Streamlink: 1.0.0+3.g4100688.dirty\\n[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.54.0)\\n[cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/lci/direct\\n[plugin.tf1][debug] Found channel lci\\n[plugin.tf1][debug] Got dash stream https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=\\n[utils.l10n][debug] Language code: en_US\\n[stream.dash][debug] Available languages for DASH audio streams: NONE (using: n/a)\\n[plugin.tf1][debug] Got hls stream https://lci-hls-live-ssl.tf1.fr/lci/1/hls/master_4000000.m3u8?e=&st=\\n[utils.l10n][debug] Language code: en_US\\n[cli][info] Available streams: 234p_dash, 360p_dash, 576p_dash, 234p (worst), 360p, 576p_alt, 576p, 720p (best)\\n[cli][info] Opening stream: 576p_dash (dash)\\n[stream.dash][debug] Opening DASH reader for: live_1828_H264 (video/mp4)\\n[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_1828_H264))\\n[stream.dash][debug] Reloading manifest (live_1828_H264:video/mp4)\\n[stream.dash][debug] Opening DASH reader for: live_2328_AAC (audio/mp4)\\n[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_2328_AAC))\\n[stream.dash][debug] Reloading manifest (live_2328_AAC:audio/mp4)\\n[stream.mp4mux-ffmpeg][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-2811-460 -i /tmp/ffmpeg-2811-532 -c:v copy -c:a copy -copyts -f matroska pipe:1\\n[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-460\\n[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-532\\n[cli][debug] Pre-buffering 8192 bytes\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/init.m4v complete\\nException in thread Thread-DASHStreamWorker:\\nTraceback (most recent call last):\\nFile ""src/streamlink/plugin/api/http_session.py"", line 166, in request\\nres.raise_for_status()\\nFile ""env/lib/python3.6/site-packages/requests/models.py"", line 940, in raise_for_status\\nraise HTTPError(http_error_msg, response=self)\\nrequests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.6/threading.py"", line 916, in _bootstrap_inner\\nself.run()\\nFile ""src/streamlink/stream/segmented.py"", line 59, in run\\nfor segment in self.iter_segments():\\nFile ""src/streamlink/stream/dash.py"", line 97, in iter_segments\\nif not self.reload():\\nFile ""src/streamlink/stream/dash.py"", line 111, in reload\\nres = self.session.http.get(self.mpd.url, exception=StreamError)\\nFile ""env/lib/python3.6/site-packages/requests/sessions.py"", line 546, in get\\nreturn self.request(\\'GET\\', url, **kwargs)\\nFile ""src/streamlink/plugin/api/http_session.py"", line 175, in request\\nraise err\\nstreamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=\\n(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=)\\nException in thread Thread-DASHStreamWorker:\\nTraceback (most recent call last):\\nFile ""src/streamlink/plugin/api/http_session.py"", line 166, in request\\nres.raise_for_status()\\nFile ""env/lib/python3.6/site-packages/requests/models.py"", line 940, in raise_for_status\\nraise HTTPError(http_error_msg, response=self)\\nrequests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.6/threading.py"", line 916, in _bootstrap_inner\\nself.run()\\nFile ""src/streamlink/stream/segmented.py"", line 59, in run\\nfor segment in self.iter_segments():\\nFile ""src/streamlink/stream/dash.py"", line 97, in iter_segments\\nif not self.reload():\\nFile ""src/streamlink/stream/dash.py"", line 111, in reload\\nres = self.session.http.get(self.mpd.url, exception=StreamError)\\nFile ""env/lib/python3.6/site-packages/requests/sessions.py"", line 546, in get\\nreturn self.request(\\'GET\\', url, **kwargs)\\nFile ""src/streamlink/plugin/api/http_session.py"", line 175, in request\\nraise err\\nstreamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=\\n(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=)\\n\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/init.m4a complete\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65796000.m4a complete\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65800000.m4a complete\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65804000.m4a complete\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/65792000.m4v complete'}]","$ streamlink https://www.tf1.fr/lci/direct 576p_dash +[cli][debug] OS: Linux +[cli][debug] Python: 3.6.7 +[cli][debug] Streamlink: 1.0.0+3.g4100688.dirty +[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.54.0) +[cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/lci/direct +[plugin.tf1][debug] Found channel lci +[plugin.tf1][debug] Got dash stream https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st= +[utils.l10n][debug] Language code: en_US +[stream.dash][debug] Available languages for DASH audio streams: NONE (using: n/a) +[plugin.tf1][debug] Got hls stream https://lci-hls-live-ssl.tf1.fr/lci/1/hls/master_4000000.m3u8?e=&st= +[utils.l10n][debug] Language code: en_US +[cli][info] Available streams: 234p_dash, 360p_dash, 576p_dash, 234p (worst), 360p, 576p_alt, 576p, 720p (best) +[cli][info] Opening stream: 576p_dash (dash) +[stream.dash][debug] Opening DASH reader for: live_1828_H264 (video/mp4) +[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_1828_H264)) +[stream.dash][debug] Reloading manifest (live_1828_H264:video/mp4) +[stream.dash][debug] Opening DASH reader for: live_2328_AAC (audio/mp4) +[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_2328_AAC)) +[stream.dash][debug] Reloading manifest (live_2328_AAC:audio/mp4) +[stream.mp4mux-ffmpeg][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-2811-460 -i /tmp/ffmpeg-2811-532 -c:v copy -c:a copy -copyts -f matroska pipe:1 +[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-460 +[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-532 +[cli][debug] Pre-buffering 8192 bytes +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/init.m4v complete +Exception in thread Thread-DASHStreamWorker: +Traceback (most recent call last): +File ""src/streamlink/plugin/api/http_session.py"", line 166, in request +res.raise_for_status() +File ""env/lib/python3.6/site-packages/requests/models.py"", line 940, in raise_for_status +raise HTTPError(http_error_msg, response=self) +requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st= + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/usr/lib/python3.6/threading.py"", line 916, in _bootstrap_inner +self.run() +File ""src/streamlink/stream/segmented.py"", line 59, in run +for segment in self.iter_segments(): +File ""src/streamlink/stream/dash.py"", line 97, in iter_segments +if not self.reload(): +File ""src/streamlink/stream/dash.py"", line 111, in reload +res = self.session.http.get(self.mpd.url, exception=StreamError) +File ""env/lib/python3.6/site-packages/requests/sessions.py"", line 546, in get +return self.request('GET', url, **kwargs) +File ""src/streamlink/plugin/api/http_session.py"", line 175, in request +raise err +streamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st= +(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=) +Exception in thread Thread-DASHStreamWorker: +Traceback (most recent call last): +File ""src/streamlink/plugin/api/http_session.py"", line 166, in request +res.raise_for_status() +File ""env/lib/python3.6/site-packages/requests/models.py"", line 940, in raise_for_status +raise HTTPError(http_error_msg, response=self) +requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st= + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/usr/lib/python3.6/threading.py"", line 916, in _bootstrap_inner +self.run() +File ""src/streamlink/stream/segmented.py"", line 59, in run +for segment in self.iter_segments(): +File ""src/streamlink/stream/dash.py"", line 97, in iter_segments +if not self.reload(): +File ""src/streamlink/stream/dash.py"", line 111, in reload +res = self.session.http.get(self.mpd.url, exception=StreamError) +File ""env/lib/python3.6/site-packages/requests/sessions.py"", line 546, in get +return self.request('GET', url, **kwargs) +File ""src/streamlink/plugin/api/http_session.py"", line 175, in request +raise err +streamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st= +(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=) + +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/init.m4a complete +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65796000.m4a complete +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65800000.m4a complete +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65804000.m4a complete +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/65792000.m4v complete",requests.exceptions.HTTPError +" def reload(self): + if self.closed: + return + + self.reader.buffer.wait_free() + log.debug(""Reloading manifest ({0}:{1})"".format(self.reader.representation_id, self.reader.mime_type)) + res = self.session.http.get(self.mpd.url, exception=StreamError, **self.stream.args) + + new_mpd = MPD(self.session.http.xml(res, ignore_ns=True), + base_url=self.mpd.base_url, + url=self.mpd.url, + timelines=self.mpd.timelines) + + new_rep = self.get_representation(new_mpd, self.reader.representation_id, self.reader.mime_type) + with freeze_timeline(new_mpd): + changed = len(list(itertools.islice(new_rep.segments(), 1))) > 0 + + if changed: + self.mpd = new_mpd + + return changed"," def reload(self): + if self.closed: + return + + self.reader.buffer.wait_free() + log.debug(""Reloading manifest ({0}:{1})"".format(self.reader.representation_id, self.reader.mime_type)) + res = self.session.http.get(self.mpd.url, exception=StreamError) + + new_mpd = MPD(self.session.http.xml(res, ignore_ns=True), + base_url=self.mpd.base_url, + url=self.mpd.url, + timelines=self.mpd.timelines) + + new_rep = self.get_representation(new_mpd, self.reader.representation_id, self.reader.mime_type) + with freeze_timeline(new_mpd): + changed = len(list(itertools.islice(new_rep.segments(), 1))) > 0 + + if changed: + self.mpd = new_mpd + + return changed","[{'piece_type': 'error message', 'piece_content': '$ streamlink https://www.tf1.fr/lci/direct 576p_dash\\n[cli][debug] OS: Linux\\n[cli][debug] Python: 3.6.7\\n[cli][debug] Streamlink: 1.0.0+3.g4100688.dirty\\n[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.54.0)\\n[cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/lci/direct\\n[plugin.tf1][debug] Found channel lci\\n[plugin.tf1][debug] Got dash stream https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=\\n[utils.l10n][debug] Language code: en_US\\n[stream.dash][debug] Available languages for DASH audio streams: NONE (using: n/a)\\n[plugin.tf1][debug] Got hls stream https://lci-hls-live-ssl.tf1.fr/lci/1/hls/master_4000000.m3u8?e=&st=\\n[utils.l10n][debug] Language code: en_US\\n[cli][info] Available streams: 234p_dash, 360p_dash, 576p_dash, 234p (worst), 360p, 576p_alt, 576p, 720p (best)\\n[cli][info] Opening stream: 576p_dash (dash)\\n[stream.dash][debug] Opening DASH reader for: live_1828_H264 (video/mp4)\\n[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_1828_H264))\\n[stream.dash][debug] Reloading manifest (live_1828_H264:video/mp4)\\n[stream.dash][debug] Opening DASH reader for: live_2328_AAC (audio/mp4)\\n[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_2328_AAC))\\n[stream.dash][debug] Reloading manifest (live_2328_AAC:audio/mp4)\\n[stream.mp4mux-ffmpeg][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-2811-460 -i /tmp/ffmpeg-2811-532 -c:v copy -c:a copy -copyts -f matroska pipe:1\\n[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-460\\n[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-532\\n[cli][debug] Pre-buffering 8192 bytes\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/init.m4v complete\\nException in thread Thread-DASHStreamWorker:\\nTraceback (most recent call last):\\nFile ""src/streamlink/plugin/api/http_session.py"", line 166, in request\\nres.raise_for_status()\\nFile ""env/lib/python3.6/site-packages/requests/models.py"", line 940, in raise_for_status\\nraise HTTPError(http_error_msg, response=self)\\nrequests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.6/threading.py"", line 916, in _bootstrap_inner\\nself.run()\\nFile ""src/streamlink/stream/segmented.py"", line 59, in run\\nfor segment in self.iter_segments():\\nFile ""src/streamlink/stream/dash.py"", line 97, in iter_segments\\nif not self.reload():\\nFile ""src/streamlink/stream/dash.py"", line 111, in reload\\nres = self.session.http.get(self.mpd.url, exception=StreamError)\\nFile ""env/lib/python3.6/site-packages/requests/sessions.py"", line 546, in get\\nreturn self.request(\\'GET\\', url, **kwargs)\\nFile ""src/streamlink/plugin/api/http_session.py"", line 175, in request\\nraise err\\nstreamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=\\n(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=)\\nException in thread Thread-DASHStreamWorker:\\nTraceback (most recent call last):\\nFile ""src/streamlink/plugin/api/http_session.py"", line 166, in request\\nres.raise_for_status()\\nFile ""env/lib/python3.6/site-packages/requests/models.py"", line 940, in raise_for_status\\nraise HTTPError(http_error_msg, response=self)\\nrequests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.6/threading.py"", line 916, in _bootstrap_inner\\nself.run()\\nFile ""src/streamlink/stream/segmented.py"", line 59, in run\\nfor segment in self.iter_segments():\\nFile ""src/streamlink/stream/dash.py"", line 97, in iter_segments\\nif not self.reload():\\nFile ""src/streamlink/stream/dash.py"", line 111, in reload\\nres = self.session.http.get(self.mpd.url, exception=StreamError)\\nFile ""env/lib/python3.6/site-packages/requests/sessions.py"", line 546, in get\\nreturn self.request(\\'GET\\', url, **kwargs)\\nFile ""src/streamlink/plugin/api/http_session.py"", line 175, in request\\nraise err\\nstreamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=\\n(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=)\\n\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/init.m4a complete\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65796000.m4a complete\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65800000.m4a complete\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65804000.m4a complete\\n[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/65792000.m4v complete'}]","$ streamlink https://www.tf1.fr/lci/direct 576p_dash +[cli][debug] OS: Linux +[cli][debug] Python: 3.6.7 +[cli][debug] Streamlink: 1.0.0+3.g4100688.dirty +[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.54.0) +[cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/lci/direct +[plugin.tf1][debug] Found channel lci +[plugin.tf1][debug] Got dash stream https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st= +[utils.l10n][debug] Language code: en_US +[stream.dash][debug] Available languages for DASH audio streams: NONE (using: n/a) +[plugin.tf1][debug] Got hls stream https://lci-hls-live-ssl.tf1.fr/lci/1/hls/master_4000000.m3u8?e=&st= +[utils.l10n][debug] Language code: en_US +[cli][info] Available streams: 234p_dash, 360p_dash, 576p_dash, 234p (worst), 360p, 576p_alt, 576p, 720p (best) +[cli][info] Opening stream: 576p_dash (dash) +[stream.dash][debug] Opening DASH reader for: live_1828_H264 (video/mp4) +[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_1828_H264)) +[stream.dash][debug] Reloading manifest (live_1828_H264:video/mp4) +[stream.dash][debug] Opening DASH reader for: live_2328_AAC (audio/mp4) +[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_2328_AAC)) +[stream.dash][debug] Reloading manifest (live_2328_AAC:audio/mp4) +[stream.mp4mux-ffmpeg][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-2811-460 -i /tmp/ffmpeg-2811-532 -c:v copy -c:a copy -copyts -f matroska pipe:1 +[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-460 +[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-532 +[cli][debug] Pre-buffering 8192 bytes +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/init.m4v complete +Exception in thread Thread-DASHStreamWorker: +Traceback (most recent call last): +File ""src/streamlink/plugin/api/http_session.py"", line 166, in request +res.raise_for_status() +File ""env/lib/python3.6/site-packages/requests/models.py"", line 940, in raise_for_status +raise HTTPError(http_error_msg, response=self) +requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st= + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/usr/lib/python3.6/threading.py"", line 916, in _bootstrap_inner +self.run() +File ""src/streamlink/stream/segmented.py"", line 59, in run +for segment in self.iter_segments(): +File ""src/streamlink/stream/dash.py"", line 97, in iter_segments +if not self.reload(): +File ""src/streamlink/stream/dash.py"", line 111, in reload +res = self.session.http.get(self.mpd.url, exception=StreamError) +File ""env/lib/python3.6/site-packages/requests/sessions.py"", line 546, in get +return self.request('GET', url, **kwargs) +File ""src/streamlink/plugin/api/http_session.py"", line 175, in request +raise err +streamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st= +(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=) +Exception in thread Thread-DASHStreamWorker: +Traceback (most recent call last): +File ""src/streamlink/plugin/api/http_session.py"", line 166, in request +res.raise_for_status() +File ""env/lib/python3.6/site-packages/requests/models.py"", line 940, in raise_for_status +raise HTTPError(http_error_msg, response=self) +requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st= + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/usr/lib/python3.6/threading.py"", line 916, in _bootstrap_inner +self.run() +File ""src/streamlink/stream/segmented.py"", line 59, in run +for segment in self.iter_segments(): +File ""src/streamlink/stream/dash.py"", line 97, in iter_segments +if not self.reload(): +File ""src/streamlink/stream/dash.py"", line 111, in reload +res = self.session.http.get(self.mpd.url, exception=StreamError) +File ""env/lib/python3.6/site-packages/requests/sessions.py"", line 546, in get +return self.request('GET', url, **kwargs) +File ""src/streamlink/plugin/api/http_session.py"", line 175, in request +raise err +streamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st= +(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=) + +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/init.m4a complete +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65796000.m4a complete +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65800000.m4a complete +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65804000.m4a complete +[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/65792000.m4v complete",requests.exceptions.HTTPError +" def _get_streams(self): + match = _url_re.match(self.url) + if not match: + return + + channel, media_id = match.group(""channel"", ""media_id"") + self.logger.debug(""Matched URL: channel={0}, media_id={1}"".format(channel, media_id)) + if not media_id: + res = http.get(LIVE_API.format(channel)) + livestream = http.json(res, schema=_live_schema) + if livestream.get(""media_hosted_media""): + hosted = _live_schema.validate(livestream[""media_hosted_media""]) + self.logger.info(""{0} is hosting {1}"", livestream[""media_user_name""], hosted[""media_user_name""]) + livestream = hosted + + if not livestream[""media_is_live""]: + return + + media_id = livestream[""media_id""] + media_type = ""live"" + else: + media_type = ""video"" + + res = http.get(PLAYER_API.format(media_type, media_id)) + player = http.json(res, schema=_player_schema) + + if media_type == ""live"": + return self._get_live_streams(player) + else: + return self._get_video_streams(player)"," def _get_streams(self): + match = _url_re.match(self.url) + if not match: + return + + channel, media_id = match.group(""channel"", ""media_id"") + self.logger.debug(""Matched URL: channel={0}, media_id={1}"".format(channel, media_id)) + if not media_id: + res = http.get(LIVE_API.format(channel)) + livestream = http.json(res, schema=_live_schema) + if livestream[""media_hosted_media""]: + hosted = _live_schema.validate(livestream[""media_hosted_media""]) + self.logger.info(""{0} is hosting {1}"", livestream[""media_user_name""], hosted[""media_user_name""]) + livestream = hosted + + if not livestream[""media_is_live""]: + return + + media_id = livestream[""media_id""] + media_type = ""live"" + else: + media_type = ""video"" + + res = http.get(PLAYER_API.format(media_type, media_id)) + player = http.json(res, schema=_player_schema) + + if media_type == ""live"": + return self._get_live_streams(player) + else: + return self._get_video_streams(player)","[{'piece_type': 'error message', 'piece_content': 'streamlink smashcast.tv/greatvaluesmash best\\n[cli][info] Found matching plugin hitbox for URL smashcast.tv/greatvaluesmash\\nTraceback (most recent call last):\\nFile ""C:\\\\Program Files (x86)\\\\Streamlink\\\\bin\\\\streamlink-script.py"", line 15, in\\n\\nmain()\\nFile ""C:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 103\\n8, in main\\nhandle_url()\\nFile ""C:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 482\\n, in handle_url\\nstreams = fetch_streams(plugin)\\nFile ""C:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 394\\n, in fetch_streams\\nsorting_excludes=args.stream_sorting_excludes)\\nFile ""C:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugin\\\\plugin.py"", lin\\ne 345, in get_streams\\nreturn self.streams(*args, **kwargs)\\nFile ""C:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugin\\\\plugin.py"", lin\\ne 248, in streams\\nostreams = self._get_streams()\\nFile ""C:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink\\\\plugins\\\\hitbox.py"", li\\nne 181, in _get_streams\\nif livestream[""media_hosted_media""]:\\nKeyError: \\'media_hosted_media\\''}]","streamlink smashcast.tv/greatvaluesmash best +[cli][info] Found matching plugin hitbox for URL smashcast.tv/greatvaluesmash +Traceback (most recent call last): +File ""C:\\Program Files (x86)\\Streamlink\\bin\\streamlink-script.py"", line 15, in + +main() +File ""C:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 103 +8, in main +handle_url() +File ""C:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 482 +, in handle_url +streams = fetch_streams(plugin) +File ""C:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 394 +, in fetch_streams +sorting_excludes=args.stream_sorting_excludes) +File ""C:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink\\plugin\\plugin.py"", lin +e 345, in get_streams +return self.streams(*args, **kwargs) +File ""C:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink\\plugin\\plugin.py"", lin +e 248, in streams +ostreams = self._get_streams() +File ""C:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink\\plugins\\hitbox.py"", li +ne 181, in _get_streams +if livestream[""media_hosted_media""]: +KeyError: 'media_hosted_media'",KeyError +" def close(self, client_only=False): + if self.conn: + self.conn.close() + + if not client_only: + try: + self.socket.shutdown(2) + except (OSError, socket.error): + pass + self.socket.close()"," def close(self, client_only=False): + if self.conn: + self.conn.close() + + if not client_only: + try: + self.socket.shutdown(2) + except OSError: + pass + self.socket.close()","[{'piece_type': 'error message', 'piece_content': '[cli][info] Closing currently open stream...\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/streamlink"", line 11, in \\nload_entry_point(\\'streamlink==0.6.0\\', \\'console_scripts\\', \\'streamlink\\')()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py"", line 1027, in main\\nhandle_url()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py"", line 502, in handle_url\\nhandle_stream(plugin, streams, stream_name)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py"", line 380, in handle_stream\\nreturn output_stream_http(plugin, streams)\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py"", line 192, in output_stream_http\\nserver.close()\\nFile ""/usr/local/lib/python2.7/site-packages/streamlink_cli/utils/http_server.py"", line 116, in close\\nself.socket.shutdown(2)\\nFile ""/usr/local/lib/python2.7/socket.py"", line 228, in meth\\nreturn getattr(self._sock,name)(*args)\\nsocket.error: [Errno 57] Socket is not connected'}, {'piece_type': 'other', 'piece_content': 'player-continuous-http\\ndefault-stream=best\\nhls-segment-threads=10'}]","[cli][info] Closing currently open stream... +Traceback (most recent call last): +File ""/usr/local/bin/streamlink"", line 11, in +load_entry_point('streamlink==0.6.0', 'console_scripts', 'streamlink')() +File ""/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py"", line 1027, in main +handle_url() +File ""/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py"", line 502, in handle_url +handle_stream(plugin, streams, stream_name) +File ""/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py"", line 380, in handle_stream +return output_stream_http(plugin, streams) +File ""/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py"", line 192, in output_stream_http +server.close() +File ""/usr/local/lib/python2.7/site-packages/streamlink_cli/utils/http_server.py"", line 116, in close +self.socket.shutdown(2) +File ""/usr/local/lib/python2.7/socket.py"", line 228, in meth +return getattr(self._sock,name)(*args) +socket.error: [Errno 57] Socket is not connected",socket.error +" def close(self, client_only=False): + if self.conn: + self.conn.close() + + if not client_only: + try: + self.socket.shutdown(2) + except OSError: + pass + self.socket.close()"," def close(self, client_only=False): + if self.conn: + self.conn.close() + + if not client_only: + self.socket.shutdown(2) + self.socket.close()","[{'piece_type': 'error message', 'piece_content': '[cli][info] Player closed\\n[cli][info] Stream ended\\n[cli][info] Closing currently open stream...\\nTraceback (most recent call last):\\nFile ""d:\\\\Program Files (x86)\\\\Streamlink\\\\bin\\\\streamlink-script.py"", line 12, in\\n\\nmain()\\nFile ""d:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 952\\n, in main\\nhandle_url()\\nFile ""d:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 499\\n, in handle_url\\nhandle_stream(plugin, streams, stream_name)\\nFile ""d:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 381\\n, in handle_stream\\nsuccess = output_stream(stream)\\nFile ""d:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\main.py"", line 270\\n, in output_stream\\nread_stream(stream_fd, output, prebuffer)\\nFile ""contextlib.py"", line 159, in __exit__\\nFile ""d:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\output.py"", line 2\\n8, in close\\nself._close()\\nFile ""d:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\output.py"", line 1\\n58, in _close\\nself.http.close()\\nFile ""d:\\\\Program Files (x86)\\\\Streamlink\\\\pkgs\\\\streamlink_cli\\\\utils\\\\http_server.\\npy"", line 115, in close\\nself.socket.shutdown(2)\\nOSError: [WinError 10057] A request to send or receive data was disallowed becau\\nse the socket is not connected and (when sending on a datagram socket using a se\\nndto call) no address was supplied'}]","[cli][info] Player closed +[cli][info] Stream ended +[cli][info] Closing currently open stream... +Traceback (most recent call last): +File ""d:\\Program Files (x86)\\Streamlink\\bin\\streamlink-script.py"", line 12, in + +main() +File ""d:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 952 +, in main +handle_url() +File ""d:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 499 +, in handle_url +handle_stream(plugin, streams, stream_name) +File ""d:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 381 +, in handle_stream +success = output_stream(stream) +File ""d:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink_cli\\main.py"", line 270 +, in output_stream +read_stream(stream_fd, output, prebuffer) +File ""contextlib.py"", line 159, in __exit__ +File ""d:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink_cli\\output.py"", line 2 +8, in close +self._close() +File ""d:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink_cli\\output.py"", line 1 +58, in _close +self.http.close() +File ""d:\\Program Files (x86)\\Streamlink\\pkgs\\streamlink_cli\\utils\\http_server. +py"", line 115, in close +self.socket.shutdown(2) +OSError: [WinError 10057] A request to send or receive data was disallowed becau +se the socket is not connected and (when sending on a datagram socket using a se +ndto call) no address was supplied",OSError +" def write(self, sequence, res, chunk_size=8192, retries=None): + retries = retries or self.retries + if retries == 0: + self.logger.error(""Failed to open segment {0}"", sequence.num) + return + try: + if sequence.segment.key and sequence.segment.key.method != ""NONE"": + try: + decryptor = self.create_decryptor(sequence.segment.key, + sequence.num) + except StreamError as err: + self.logger.error(""Failed to create decryptor: {0}"", err) + self.close() + return + + for chunk in res.iter_content(chunk_size): + # If the input data is not a multiple of 16, cut off any garbage + garbage_len = len(chunk) % 16 + if garbage_len: + self.logger.debug(""Cutting off {0} bytes of garbage "" + ""before decrypting"", garbage_len) + decrypted_chunk = decryptor.decrypt(chunk[:-garbage_len]) + else: + decrypted_chunk = decryptor.decrypt(chunk) + self.reader.buffer.write(decrypted_chunk) + else: + for chunk in res.iter_content(chunk_size): + self.reader.buffer.write(chunk) + except StreamError as err: + self.logger.error(""Failed to open segment {0}: {1}"", sequence.num, err) + return self.write(sequence, + self.fetch(sequence, retries=self.retries), + chunk_size=chunk_size, + retries=retries - 1) + + self.logger.debug(""Download of segment {0} complete"", sequence.num)"," def write(self, sequence, res, chunk_size=8192): + if sequence.segment.key and sequence.segment.key.method != ""NONE"": + try: + decryptor = self.create_decryptor(sequence.segment.key, + sequence.num) + except StreamError as err: + self.logger.error(""Failed to create decryptor: {0}"", err) + self.close() + return + + for chunk in res.iter_content(chunk_size): + # If the input data is not a multiple of 16, cut off any garbage + garbage_len = len(chunk) % 16 + if garbage_len: + self.logger.debug(""Cutting off {0} bytes of garbage "" + ""before decrypting"", garbage_len) + decrypted_chunk = decryptor.decrypt(chunk[:-garbage_len]) + else: + decrypted_chunk = decryptor.decrypt(chunk) + self.reader.buffer.write(decrypted_chunk) + else: + for chunk in res.iter_content(chunk_size): + self.reader.buffer.write(chunk) + + self.logger.debug(""Download of segment {0} complete"", sequence.num)","[{'piece_type': 'error message', 'piece_content': 'Exception in thread Thread-1:\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py"", line 232, in _error_catcher\\nyield\\nFile ""/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py"", line 314, in read\\ndata = self._fp.read(amt)\\nFile ""/usr/local/lib/python3.5/http/client.py"", line 448, in read\\nn = self.readinto(b)\\nFile ""/usr/local/lib/python3.5/http/client.py"", line 488, in readinto\\nn = self.fp.readinto(b)\\nFile ""/usr/local/lib/python3.5/socket.py"", line 575, in readinto\\nreturn self._sock.recv_into(b)\\nFile ""/usr/local/lib/python3.5/ssl.py"", line 929, in recv_into\\nreturn self.read(nbytes, buffer)\\nFile ""/usr/local/lib/python3.5/ssl.py"", line 791, in read\\nreturn self._sslobj.read(len, buffer)\\nFile ""/usr/local/lib/python3.5/ssl.py"", line 575, in read\\nv = self._sslobj.read(len, buffer)\\nsocket.timeout: The read operation timed out\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python3.5/site-packages/requests/models.py"", line 676, in generate\\nfor chunk in self.raw.stream(chunk_size, decode_content=True):\\nFile ""/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py"", line 357, in stream\\ndata = self.read(amt=amt, decode_content=decode_content)\\nFile ""/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py"", line 324, in read\\nflush_decoder = True\\nFile ""/usr/local/lib/python3.5/contextlib.py"", line 77, in __exit__\\nself.gen.throw(type, value, traceback)\\nFile ""/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py"", line 237, in _error_catcher\\nraise ReadTimeoutError(self._pool, None, \\'Read timed out.\\')\\nrequests.packages.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host=\\'video-edge-835ef0.ord02.hls.ttvnw.net\\', port=443): Read timed out.\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/usr/local/lib/python3.5/threading.py"", line 914, in _bootstrap_inner\\nself.run()\\nFile ""/usr/local/lib/python3.5/site-packages/streamlink/stream/segmented.py"", line 160, in run\\nself.write(segment, result)\\nFile ""/usr/local/lib/python3.5/site-packages/streamlink/stream/hls.py"", line 111, in write\\nfor chunk in res.iter_content(chunk_size):\\nFile ""/usr/local/lib/python3.5/site-packages/requests/models.py"", line 683, in generate\\nraise ConnectionError(e)\\nrequests.exceptions.ConnectionError: HTTPSConnectionPool(host=\\'video-edge-835ef0.ord02.hls.ttvnw.net\\', port=443): Read timed out.'}, {'piece_type': 'other', 'piece_content': 'player-continuous-http\\ndefault-stream=best\\nhls-segment-threads=10'}]","Exception in thread Thread-1: +Traceback (most recent call last): +File ""/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py"", line 232, in _error_catcher +yield +File ""/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py"", line 314, in read +data = self._fp.read(amt) +File ""/usr/local/lib/python3.5/http/client.py"", line 448, in read +n = self.readinto(b) +File ""/usr/local/lib/python3.5/http/client.py"", line 488, in readinto +n = self.fp.readinto(b) +File ""/usr/local/lib/python3.5/socket.py"", line 575, in readinto +return self._sock.recv_into(b) +File ""/usr/local/lib/python3.5/ssl.py"", line 929, in recv_into +return self.read(nbytes, buffer) +File ""/usr/local/lib/python3.5/ssl.py"", line 791, in read +return self._sslobj.read(len, buffer) +File ""/usr/local/lib/python3.5/ssl.py"", line 575, in read +v = self._sslobj.read(len, buffer) +socket.timeout: The read operation timed out + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/usr/local/lib/python3.5/site-packages/requests/models.py"", line 676, in generate +for chunk in self.raw.stream(chunk_size, decode_content=True): +File ""/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py"", line 357, in stream +data = self.read(amt=amt, decode_content=decode_content) +File ""/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py"", line 324, in read +flush_decoder = True +File ""/usr/local/lib/python3.5/contextlib.py"", line 77, in __exit__ +self.gen.throw(type, value, traceback) +File ""/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py"", line 237, in _error_catcher +raise ReadTimeoutError(self._pool, None, 'Read timed out.') +requests.packages.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='video-edge-835ef0.ord02.hls.ttvnw.net', port=443): Read timed out. + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/usr/local/lib/python3.5/threading.py"", line 914, in _bootstrap_inner +self.run() +File ""/usr/local/lib/python3.5/site-packages/streamlink/stream/segmented.py"", line 160, in run +self.write(segment, result) +File ""/usr/local/lib/python3.5/site-packages/streamlink/stream/hls.py"", line 111, in write +for chunk in res.iter_content(chunk_size): +File ""/usr/local/lib/python3.5/site-packages/requests/models.py"", line 683, in generate +raise ConnectionError(e) +requests.exceptions.ConnectionError: HTTPSConnectionPool(host='video-edge-835ef0.ord02.hls.ttvnw.net', port=443): Read timed out.",requests.packages.urllib3.exceptions.ReadTimeoutError +" def write(self, vals): + res = super(OpStudent, self).write(vals) + if vals.get('parent_ids', False): + user_ids = [] + if self.parent_ids: + for parent in self.parent_ids: + if parent.user_id: + user_ids = [x.user_id.id for x in parent.student_ids + if x.user_id] + parent.user_id.child_ids = [(6, 0, user_ids)] + else: + user_ids = self.env['res.users'].search([ + ('child_ids', 'in', self.user_id.id)]) + for user_id in user_ids: + child_ids = user_id.child_ids.ids + child_ids.remove(self.user_id.id) + user_id.child_ids = [(6, 0, child_ids)] + if vals.get('user_id', False): + for parent_id in self.parent_ids: + if parent_id.user_id: + child_ids = parent_id.user_id.child_ids.ids + child_ids.append(vals['user_id']) + parent_id.name.user_id.child_ids = [(6, 0, child_ids)] + self.clear_caches() + return res"," def write(self, vals): + res = super(OpStudent, self).write(vals) + if vals.get('parent_ids', False): + user_ids = [] + if self.parent_ids: + for parent in self.parent_ids: + if parent.user_id: + user_ids = [x.user_id.id for x in parent.student_ids + if x.user_id] + parent.user_id.child_ids = [(6, 0, user_ids)] + else: + user_ids = self.env['res.users'].search([ + ('child_ids', 'in', self.user_id.id)]) + for user_id in user_ids: + child_ids = user_id.child_ids.ids + child_ids.remove(self.user_id.id) + user_id.child_ids = [(6, 0, child_ids)] + if vals.get('user_id', False): + for parent_id in self.parent_ids: + child_ids = parent_id.user_id.child_ids.ids + child_ids.append(vals['user_id']) + parent_id.name.user_id.child_ids = [(6, 0, child_ids)] + self.clear_caches() + return res","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/models.py"", line 4718, in ensure_one\\n\\n_id, = self._ids\\n\\nValueError: not enough values to unpack (expected 1, got 0)\\n\\n\\n\\nDuring handling of the above exception, another exception occurred:\\n\\n\\n\\nTraceback (most recent call last):\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 656, in _handle_exception\\n\\nreturn super(JsonRequest, self)._handle_exception(exception)\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 314, in _handle_exception\\n\\nraise pycompat.reraise(type(exception), exception, sys.exc_info()[2])\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/tools/pycompat.py"", line 87, in reraise\\n\\nraise value\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 698, in dispatch\\n\\nresult = self._call_function(**self.params)\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 346, in _call_function\\n\\nreturn checked_call(self.db, *args, **kwargs)\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/service/model.py"", line 97, in wrapper\\n\\nreturn f(dbname, *args, **kwargs)\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 339, in checked_call\\n\\nresult = self.endpoint(*a, **kw)\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 941, in __call__\\n\\nreturn self.method(*args, **kw)\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 519, in response_wrap\\n\\nresponse = f(*args, **kw)\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/addons/web/controllers/main.py"", line 966, in call_button\\n\\naction = self._call_kw(model, method, args, {})\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/addons/web/controllers/main.py"", line 954, in _call_kw\\n\\nreturn call_kw(request.env[model], method, args, kwargs)\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/api.py"", line 749, in call_kw\\n\\nreturn _call_kw_multi(method, model, args, kwargs)\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/api.py"", line 736, in _call_kw_multi\\n\\nresult = method(recs, *args, **kwargs)\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/openeducat/openeducat_core/models/student.py"", line 118, in create_student_user\\n\\nrecord.user_id = user_id\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/fields.py"", line 1024, in __set__\\n\\nrecord.write({self.name: write_value})\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/openeducat/openeducat_parent/models/parent.py"", line 134, in write\\n\\nparent_id.name.user_id.child_ids = [(6, 0, child_ids)]\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/fields.py"", line 1000, in __set__\\n\\nrecord.ensure_one()\\n\\nFile ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/models.py"", line 4721, in ensure_one\\n\\nraise ValueError(""Expected singleton: %s"" % self)\\n\\nValueError: Expected singleton: res.users()'}]","Traceback (most recent call last): + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/models.py"", line 4718, in ensure_one + +_id, = self._ids + +ValueError: not enough values to unpack (expected 1, got 0) + + + +During handling of the above exception, another exception occurred: + + + +Traceback (most recent call last): + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 656, in _handle_exception + +return super(JsonRequest, self)._handle_exception(exception) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 314, in _handle_exception + +raise pycompat.reraise(type(exception), exception, sys.exc_info()[2]) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/tools/pycompat.py"", line 87, in reraise + +raise value + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 698, in dispatch + +result = self._call_function(**self.params) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 346, in _call_function + +return checked_call(self.db, *args, **kwargs) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/service/model.py"", line 97, in wrapper + +return f(dbname, *args, **kwargs) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 339, in checked_call + +result = self.endpoint(*a, **kw) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 941, in __call__ + +return self.method(*args, **kw) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py"", line 519, in response_wrap + +response = f(*args, **kw) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/addons/web/controllers/main.py"", line 966, in call_button + +action = self._call_kw(model, method, args, {}) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/addons/web/controllers/main.py"", line 954, in _call_kw + +return call_kw(request.env[model], method, args, kwargs) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/api.py"", line 749, in call_kw + +return _call_kw_multi(method, model, args, kwargs) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/api.py"", line 736, in _call_kw_multi + +result = method(recs, *args, **kwargs) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/openeducat/openeducat_core/models/student.py"", line 118, in create_student_user + +record.user_id = user_id + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/fields.py"", line 1024, in __set__ + +record.write({self.name: write_value}) + +File ""/media/linux_data/progetti/odoo/odoo12-dev/openeducat/openeducat_parent/models/parent.py"", line 134, in write + +parent_id.name.user_id.child_ids = [(6, 0, child_ids)] + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/fields.py"", line 1000, in __set__ + +record.ensure_one() + +File ""/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/models.py"", line 4721, in ensure_one + +raise ValueError(""Expected singleton: %s"" % self) + +ValueError: Expected singleton: res.users()",ValueError +" def parse_exif_values(self, _path_file): + # Disable exifread log + logging.getLogger('exifread').setLevel(logging.CRITICAL) + + with open(_path_file, 'rb') as f: + tags = exifread.process_file(f, details=False) + try: + if 'Image Make' in tags: + try: + self.camera_make = tags['Image Make'].values + except UnicodeDecodeError: + log.ODM_WARNING(""EXIF Image Make might be corrupted"") + self.camera_make = ""unknown"" + if 'Image Model' in tags: + try: + self.camera_model = tags['Image Model'].values + except UnicodeDecodeError: + log.ODM_WARNING(""EXIF Image Model might be corrupted"") + self.camera_model = ""unknown"" + if 'GPS GPSAltitude' in tags: + self.altitude = self.float_value(tags['GPS GPSAltitude']) + if 'GPS GPSAltitudeRef' in tags and self.int_value(tags['GPS GPSAltitudeRef']) > 0: + self.altitude *= -1 + if 'GPS GPSLatitude' in tags and 'GPS GPSLatitudeRef' in tags: + self.latitude = self.dms_to_decimal(tags['GPS GPSLatitude'], tags['GPS GPSLatitudeRef']) + if 'GPS GPSLongitude' in tags and 'GPS GPSLongitudeRef' in tags: + self.longitude = self.dms_to_decimal(tags['GPS GPSLongitude'], tags['GPS GPSLongitudeRef']) + except IndexError as e: + log.ODM_WARNING(""Cannot read basic EXIF tags for %s: %s"" % (_path_file, str(e))) + + try: + if 'Image Tag 0xC61A' in tags: + self.black_level = self.list_values(tags['Image Tag 0xC61A']) + elif 'BlackLevel' in tags: + self.black_level = self.list_values(tags['BlackLevel']) + + if 'EXIF ExposureTime' in tags: + self.exposure_time = self.float_value(tags['EXIF ExposureTime']) + + if 'EXIF FNumber' in tags: + self.fnumber = self.float_value(tags['EXIF FNumber']) + + if 'EXIF ISOSpeed' in tags: + self.iso_speed = self.int_value(tags['EXIF ISOSpeed']) + elif 'EXIF PhotographicSensitivity' in tags: + self.iso_speed = self.int_value(tags['EXIF PhotographicSensitivity']) + elif 'EXIF ISOSpeedRatings' in tags: + self.iso_speed = self.int_value(tags['EXIF ISOSpeedRatings']) + + + if 'Image BitsPerSample' in tags: + self.bits_per_sample = self.int_value(tags['Image BitsPerSample']) + if 'EXIF DateTimeOriginal' in tags: + str_time = tags['EXIF DateTimeOriginal'].values + utc_time = datetime.strptime(str_time, ""%Y:%m:%d %H:%M:%S"") + subsec = 0 + if 'EXIF SubSecTime' in tags: + subsec = self.int_value(tags['EXIF SubSecTime']) + negative = 1.0 + if subsec < 0: + negative = -1.0 + subsec *= -1.0 + subsec = float('0.{}'.format(int(subsec))) + subsec *= negative + ms = subsec * 1e3 + utc_time += timedelta(milliseconds = ms) + timezone = pytz.timezone('UTC') + epoch = timezone.localize(datetime.utcfromtimestamp(0)) + self.utc_time = (timezone.localize(utc_time) - epoch).total_seconds() * 1000.0 + except Exception as e: + log.ODM_WARNING(""Cannot read extended EXIF tags for %s: %s"" % (_path_file, str(e))) + + + # Extract XMP tags + f.seek(0) + xmp = self.get_xmp(f) + + for tags in xmp: + try: + band_name = self.get_xmp_tag(tags, ['Camera:BandName', '@Camera:BandName']) + if band_name is not None: + self.band_name = band_name.replace("" "", """") + + self.set_attr_from_xmp_tag('band_index', tags, [ + 'DLS:SensorId', # Micasense RedEdge + '@Camera:RigCameraIndex', # Parrot Sequoia, Sentera 21244-00_3.2MP-GS-0001 + 'Camera:RigCameraIndex', # MicaSense Altum + ]) + self.set_attr_from_xmp_tag('radiometric_calibration', tags, [ + 'MicaSense:RadiometricCalibration', + ]) + + self.set_attr_from_xmp_tag('vignetting_center', tags, [ + 'Camera:VignettingCenter', + 'Sentera:VignettingCenter', + ]) + + self.set_attr_from_xmp_tag('vignetting_polynomial', tags, [ + 'Camera:VignettingPolynomial', + 'Sentera:VignettingPolynomial', + ]) + + self.set_attr_from_xmp_tag('horizontal_irradiance', tags, [ + 'Camera:HorizontalIrradiance' + ], float) + + self.set_attr_from_xmp_tag('irradiance_scale_to_si', tags, [ + 'Camera:IrradianceScaleToSIUnits' + ], float) + + self.set_attr_from_xmp_tag('sun_sensor', tags, [ + 'Camera:SunSensor', + ], float) + + self.set_attr_from_xmp_tag('spectral_irradiance', tags, [ + 'Camera:SpectralIrradiance', + 'Camera:Irradiance', + ], float) + + # Phantom 4 RTK + if '@drone-dji:RtkStdLon' in tags: + y = float(self.get_xmp_tag(tags, '@drone-dji:RtkStdLon')) + x = float(self.get_xmp_tag(tags, '@drone-dji:RtkStdLat')) + self.gps_xy_stddev = max(x, y) + + if '@drone-dji:RtkStdHgt' in tags: + self.gps_z_stddev = float(self.get_xmp_tag(tags, '@drone-dji:RtkStdHgt')) + else: + self.set_attr_from_xmp_tag('gps_xy_stddev', tags, [ + '@Camera:GPSXYAccuracy', + 'GPSXYAccuracy' + ], float) + self.set_attr_from_xmp_tag('gps_z_stddev', tags, [ + '@Camera:GPSZAccuracy', + 'GPSZAccuracy' + ], float) + + if 'DLS:Yaw' in tags: + self.set_attr_from_xmp_tag('dls_yaw', tags, ['DLS:Yaw'], float) + self.set_attr_from_xmp_tag('dls_pitch', tags, ['DLS:Pitch'], float) + self.set_attr_from_xmp_tag('dls_roll', tags, ['DLS:Roll'], float) + except Exception as e: + log.ODM_WARNING(""Cannot read XMP tags for %s: %s"" % (_path_file, str(e))) + + # self.set_attr_from_xmp_tag('center_wavelength', tags, [ + # 'Camera:CentralWavelength' + # ], float) + + # self.set_attr_from_xmp_tag('bandwidth', tags, [ + # 'Camera:WavelengthFWHM' + # ], float) + + self.width, self.height = get_image_size.get_image_size(_path_file) + # Sanitize band name since we use it in folder paths + self.band_name = re.sub('[^A-Za-z0-9]+', '', self.band_name)"," def parse_exif_values(self, _path_file): + # Disable exifread log + logging.getLogger('exifread').setLevel(logging.CRITICAL) + + with open(_path_file, 'rb') as f: + tags = exifread.process_file(f, details=False) + try: + if 'Image Make' in tags: + try: + self.camera_make = tags['Image Make'].values + except UnicodeDecodeError: + log.ODM_WARNING(""EXIF Image Make might be corrupted"") + self.camera_make = ""unknown"" + if 'Image Model' in tags: + try: + self.camera_model = tags['Image Model'].values + except UnicodeDecodeError: + log.ODM_WARNING(""EXIF Image Model might be corrupted"") + self.camera_model = ""unknown"" + if 'GPS GPSAltitude' in tags: + self.altitude = self.float_value(tags['GPS GPSAltitude']) + if 'GPS GPSAltitudeRef' in tags and self.int_value(tags['GPS GPSAltitudeRef']) > 0: + self.altitude *= -1 + if 'GPS GPSLatitude' in tags and 'GPS GPSLatitudeRef' in tags: + self.latitude = self.dms_to_decimal(tags['GPS GPSLatitude'], tags['GPS GPSLatitudeRef']) + if 'GPS GPSLongitude' in tags and 'GPS GPSLongitudeRef' in tags: + self.longitude = self.dms_to_decimal(tags['GPS GPSLongitude'], tags['GPS GPSLongitudeRef']) + except IndexError as e: + log.ODM_WARNING(""Cannot read basic EXIF tags for %s: %s"" % (_path_file, e.message)) + + try: + if 'Image Tag 0xC61A' in tags: + self.black_level = self.list_values(tags['Image Tag 0xC61A']) + elif 'BlackLevel' in tags: + self.black_level = self.list_values(tags['BlackLevel']) + + if 'EXIF ExposureTime' in tags: + self.exposure_time = self.float_value(tags['EXIF ExposureTime']) + + if 'EXIF FNumber' in tags: + self.fnumber = self.float_value(tags['EXIF FNumber']) + + if 'EXIF ISOSpeed' in tags: + self.iso_speed = self.int_value(tags['EXIF ISOSpeed']) + elif 'EXIF PhotographicSensitivity' in tags: + self.iso_speed = self.int_value(tags['EXIF PhotographicSensitivity']) + elif 'EXIF ISOSpeedRatings' in tags: + self.iso_speed = self.int_value(tags['EXIF ISOSpeedRatings']) + + + if 'Image BitsPerSample' in tags: + self.bits_per_sample = self.int_value(tags['Image BitsPerSample']) + if 'EXIF DateTimeOriginal' in tags: + str_time = tags['EXIF DateTimeOriginal'].values + utc_time = datetime.strptime(str_time, ""%Y:%m:%d %H:%M:%S"") + subsec = 0 + if 'EXIF SubSecTime' in tags: + subsec = self.int_value(tags['EXIF SubSecTime']) + negative = 1.0 + if subsec < 0: + negative = -1.0 + subsec *= -1.0 + subsec = float('0.{}'.format(int(subsec))) + subsec *= negative + ms = subsec * 1e3 + utc_time += timedelta(milliseconds = ms) + timezone = pytz.timezone('UTC') + epoch = timezone.localize(datetime.utcfromtimestamp(0)) + self.utc_time = (timezone.localize(utc_time) - epoch).total_seconds() * 1000.0 + except Exception as e: + log.ODM_WARNING(""Cannot read extended EXIF tags for %s: %s"" % (_path_file, str(e))) + + + # Extract XMP tags + f.seek(0) + xmp = self.get_xmp(f) + + for tags in xmp: + try: + band_name = self.get_xmp_tag(tags, ['Camera:BandName', '@Camera:BandName']) + if band_name is not None: + self.band_name = band_name.replace("" "", """") + + self.set_attr_from_xmp_tag('band_index', tags, [ + 'DLS:SensorId', # Micasense RedEdge + '@Camera:RigCameraIndex', # Parrot Sequoia, Sentera 21244-00_3.2MP-GS-0001 + 'Camera:RigCameraIndex', # MicaSense Altum + ]) + self.set_attr_from_xmp_tag('radiometric_calibration', tags, [ + 'MicaSense:RadiometricCalibration', + ]) + + self.set_attr_from_xmp_tag('vignetting_center', tags, [ + 'Camera:VignettingCenter', + 'Sentera:VignettingCenter', + ]) + + self.set_attr_from_xmp_tag('vignetting_polynomial', tags, [ + 'Camera:VignettingPolynomial', + 'Sentera:VignettingPolynomial', + ]) + + self.set_attr_from_xmp_tag('horizontal_irradiance', tags, [ + 'Camera:HorizontalIrradiance' + ], float) + + self.set_attr_from_xmp_tag('irradiance_scale_to_si', tags, [ + 'Camera:IrradianceScaleToSIUnits' + ], float) + + self.set_attr_from_xmp_tag('sun_sensor', tags, [ + 'Camera:SunSensor', + ], float) + + self.set_attr_from_xmp_tag('spectral_irradiance', tags, [ + 'Camera:SpectralIrradiance', + 'Camera:Irradiance', + ], float) + + # Phantom 4 RTK + if '@drone-dji:RtkStdLon' in tags: + y = float(self.get_xmp_tag(tags, '@drone-dji:RtkStdLon')) + x = float(self.get_xmp_tag(tags, '@drone-dji:RtkStdLat')) + self.gps_xy_stddev = max(x, y) + + if '@drone-dji:RtkStdHgt' in tags: + self.gps_z_stddev = float(self.get_xmp_tag(tags, '@drone-dji:RtkStdHgt')) + else: + self.set_attr_from_xmp_tag('gps_xy_stddev', tags, [ + '@Camera:GPSXYAccuracy', + 'GPSXYAccuracy' + ], float) + self.set_attr_from_xmp_tag('gps_z_stddev', tags, [ + '@Camera:GPSZAccuracy', + 'GPSZAccuracy' + ], float) + + if 'DLS:Yaw' in tags: + self.set_attr_from_xmp_tag('dls_yaw', tags, ['DLS:Yaw'], float) + self.set_attr_from_xmp_tag('dls_pitch', tags, ['DLS:Pitch'], float) + self.set_attr_from_xmp_tag('dls_roll', tags, ['DLS:Roll'], float) + except Exception as e: + log.ODM_WARNING(""Cannot read XMP tags for %s: %s"" % (_path_file, e.message)) + + # self.set_attr_from_xmp_tag('center_wavelength', tags, [ + # 'Camera:CentralWavelength' + # ], float) + + # self.set_attr_from_xmp_tag('bandwidth', tags, [ + # 'Camera:WavelengthFWHM' + # ], float) + + self.width, self.height = get_image_size.get_image_size(_path_file) + # Sanitize band name since we use it in folder paths + self.band_name = re.sub('[^A-Za-z0-9]+', '', self.band_name)","[{'piece_type': 'error message', 'piece_content': '[INFO] Loading 4 images\\nTraceback (most recent call last):\\nFile ""/code/opendm/photo.py"", line 225, in parse_exif_values\\n], float)\\nFile ""/code/opendm/photo.py"", line 256, in set_attr_from_xmp_tag\\nsetattr(self, attr, cast(v))\\nValueError: could not convert string to float: \\'610/1000\\'\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/code/run.py"", line 68, in \\napp.execute()\\nFile ""/code/stages/odm_app.py"", line 95, in execute\\nself.first_stage.run()\\nFile ""/code/opendm/types.py"", line 337, in run\\nself.process(self.args, outputs)\\nFile ""/code/stages/dataset.py"", line 109, in process\\np = types.ODM_Photo(f)\\nFile ""/code/opendm/photo.py"", line 70, in __init__\\nself.parse_exif_values(path_file)\\nFile ""/code/opendm/photo.py"", line 236, in parse_exif_values\\nlog.ODM_WARNING(""Cannot read XMP tags for %s: %s"" % (_path_file, e.message))\\nAttributeError: \\'ValueError\\' object has no attribute \\'message\\''}, {'piece_type': 'other', 'piece_content': '""GPSXYAccuracy"": ""610/1000""'}]","[INFO] Loading 4 images +Traceback (most recent call last): +File ""/code/opendm/photo.py"", line 225, in parse_exif_values +], float) +File ""/code/opendm/photo.py"", line 256, in set_attr_from_xmp_tag +setattr(self, attr, cast(v)) +ValueError: could not convert string to float: '610/1000' + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/code/run.py"", line 68, in +app.execute() +File ""/code/stages/odm_app.py"", line 95, in execute +self.first_stage.run() +File ""/code/opendm/types.py"", line 337, in run +self.process(self.args, outputs) +File ""/code/stages/dataset.py"", line 109, in process +p = types.ODM_Photo(f) +File ""/code/opendm/photo.py"", line 70, in __init__ +self.parse_exif_values(path_file) +File ""/code/opendm/photo.py"", line 236, in parse_exif_values +log.ODM_WARNING(""Cannot read XMP tags for %s: %s"" % (_path_file, e.message)) +AttributeError: 'ValueError' object has no attribute 'message'",ValueError +" def set_attr_from_xmp_tag(self, attr, xmp_tags, tags, cast=None): + v = self.get_xmp_tag(xmp_tags, tags) + if v is not None: + if cast is None: + setattr(self, attr, v) + else: + # Handle fractions + if (cast == float or cast == int) and ""/"" in v: + v = self.try_parse_fraction(v) + setattr(self, attr, cast(v))"," def set_attr_from_xmp_tag(self, attr, xmp_tags, tags, cast=None): + v = self.get_xmp_tag(xmp_tags, tags) + if v is not None: + if cast is None: + setattr(self, attr, v) + else: + setattr(self, attr, cast(v))","[{'piece_type': 'error message', 'piece_content': '[INFO] Loading 4 images\\nTraceback (most recent call last):\\nFile ""/code/opendm/photo.py"", line 225, in parse_exif_values\\n], float)\\nFile ""/code/opendm/photo.py"", line 256, in set_attr_from_xmp_tag\\nsetattr(self, attr, cast(v))\\nValueError: could not convert string to float: \\'610/1000\\'\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/code/run.py"", line 68, in \\napp.execute()\\nFile ""/code/stages/odm_app.py"", line 95, in execute\\nself.first_stage.run()\\nFile ""/code/opendm/types.py"", line 337, in run\\nself.process(self.args, outputs)\\nFile ""/code/stages/dataset.py"", line 109, in process\\np = types.ODM_Photo(f)\\nFile ""/code/opendm/photo.py"", line 70, in __init__\\nself.parse_exif_values(path_file)\\nFile ""/code/opendm/photo.py"", line 236, in parse_exif_values\\nlog.ODM_WARNING(""Cannot read XMP tags for %s: %s"" % (_path_file, e.message))\\nAttributeError: \\'ValueError\\' object has no attribute \\'message\\''}, {'piece_type': 'other', 'piece_content': '""GPSXYAccuracy"": ""610/1000""'}]","[INFO] Loading 4 images +Traceback (most recent call last): +File ""/code/opendm/photo.py"", line 225, in parse_exif_values +], float) +File ""/code/opendm/photo.py"", line 256, in set_attr_from_xmp_tag +setattr(self, attr, cast(v)) +ValueError: could not convert string to float: '610/1000' + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/code/run.py"", line 68, in +app.execute() +File ""/code/stages/odm_app.py"", line 95, in execute +self.first_stage.run() +File ""/code/opendm/types.py"", line 337, in run +self.process(self.args, outputs) +File ""/code/stages/dataset.py"", line 109, in process +p = types.ODM_Photo(f) +File ""/code/opendm/photo.py"", line 70, in __init__ +self.parse_exif_values(path_file) +File ""/code/opendm/photo.py"", line 236, in parse_exif_values +log.ODM_WARNING(""Cannot read XMP tags for %s: %s"" % (_path_file, e.message)) +AttributeError: 'ValueError' object has no attribute 'message'",ValueError +" def process(self, args, outputs): + tree = outputs['tree'] + reconstruction = outputs['reconstruction'] + photos = reconstruction.photos + + if not photos: + log.ODM_ERROR('Not enough photos in photos array to start OpenSfM') + exit(1) + + octx = OSFMContext(tree.opensfm) + octx.setup(args, tree.dataset_raw, photos, reconstruction=reconstruction, rerun=self.rerun()) + octx.extract_metadata(self.rerun()) + self.update_progress(20) + octx.feature_matching(self.rerun()) + self.update_progress(30) + octx.reconstruct(self.rerun()) + octx.extract_cameras(tree.path(""cameras.json""), self.rerun()) + self.update_progress(70) + + if args.optimize_disk_space: + for folder in [""features"", ""matches"", ""exif"", ""reports""]: + folder_path = octx.path(folder) + if os.path.islink(folder_path): + os.unlink(folder_path) + else: + shutil.rmtree(folder_path) + + # If we find a special flag file for split/merge we stop right here + if os.path.exists(octx.path(""split_merge_stop_at_reconstruction.txt"")): + log.ODM_INFO(""Stopping OpenSfM early because we found: %s"" % octx.path(""split_merge_stop_at_reconstruction.txt"")) + self.next_stage = None + return + + if args.fast_orthophoto: + output_file = octx.path('reconstruction.ply') + elif args.use_opensfm_dense: + output_file = tree.opensfm_model + else: + output_file = tree.opensfm_reconstruction + + updated_config_flag_file = octx.path('updated_config.txt') + + # Make sure it's capped by the depthmap-resolution arg, + # since the undistorted images are used for MVS + outputs['undist_image_max_size'] = max( + gsd.image_max_size(photos, args.orthophoto_resolution, tree.opensfm_reconstruction, ignore_gsd=args.ignore_gsd, has_gcp=reconstruction.has_gcp()), + args.depthmap_resolution + ) + + if not io.file_exists(updated_config_flag_file) or self.rerun(): + octx.update_config({'undistorted_image_max_size': outputs['undist_image_max_size']}) + octx.touch(updated_config_flag_file) + + # These will be used for texturing / MVS + if args.radiometric_calibration == ""none"": + octx.convert_and_undistort(self.rerun()) + else: + def radiometric_calibrate(shot_id, image): + photo = reconstruction.get_photo(shot_id) + return multispectral.dn_to_reflectance(photo, image, use_sun_sensor=args.radiometric_calibration==""camera+sun"") + + octx.convert_and_undistort(self.rerun(), radiometric_calibrate) + + self.update_progress(80) + + if reconstruction.multi_camera: + # Dump band image lists + log.ODM_INFO(""Multiple bands found"") + for band in reconstruction.multi_camera: + log.ODM_INFO(""Exporting %s band"" % band['name']) + image_list_file = octx.path(""image_list_%s.txt"" % band['name'].lower()) + + if not io.file_exists(image_list_file) or self.rerun(): + with open(image_list_file, ""w"") as f: + f.write(""\\n"".join([p.filename for p in band['photos']])) + log.ODM_INFO(""Wrote %s"" % image_list_file) + else: + log.ODM_WARNING(""Found a valid image list in %s for %s band"" % (image_list_file, band['name'])) + + nvm_file = octx.path(""undistorted"", ""reconstruction_%s.nvm"" % band['name'].lower()) + if not io.file_exists(nvm_file) or self.rerun(): + octx.run('export_visualsfm --points --image_list ""%s""' % image_list_file) + os.rename(tree.opensfm_reconstruction_nvm, nvm_file) + else: + log.ODM_WARNING(""Found a valid NVM file in %s for %s band"" % (nvm_file, band['name'])) + + if not io.file_exists(tree.opensfm_reconstruction_nvm) or self.rerun(): + octx.run('export_visualsfm --points') + else: + log.ODM_WARNING('Found a valid OpenSfM NVM reconstruction file in: %s' % + tree.opensfm_reconstruction_nvm) + + self.update_progress(85) + + # Skip dense reconstruction if necessary and export + # sparse reconstruction instead + if args.fast_orthophoto: + if not io.file_exists(output_file) or self.rerun(): + octx.run('export_ply --no-cameras') + else: + log.ODM_WARNING(""Found a valid PLY reconstruction in %s"" % output_file) + + elif args.use_opensfm_dense: + if not io.file_exists(output_file) or self.rerun(): + octx.run('compute_depthmaps') + else: + log.ODM_WARNING(""Found a valid dense reconstruction in %s"" % output_file) + + self.update_progress(90) + + if reconstruction.is_georeferenced() and (not io.file_exists(tree.opensfm_transformation) or self.rerun()): + octx.run('export_geocoords --transformation --proj \\'%s\\'' % reconstruction.georef.proj4()) + else: + log.ODM_WARNING(""Will skip exporting %s"" % tree.opensfm_transformation) + + if args.optimize_disk_space: + os.remove(octx.path(""tracks.csv"")) + os.remove(octx.path(""undistorted"", ""tracks.csv"")) + os.remove(octx.path(""undistorted"", ""reconstruction.json"")) + if io.dir_exists(octx.path(""undistorted"", ""depthmaps"")): + files = glob.glob(octx.path(""undistorted"", ""depthmaps"", ""*.npz"")) + for f in files: + os.remove(f)"," def process(self, args, outputs): + tree = outputs['tree'] + reconstruction = outputs['reconstruction'] + photos = reconstruction.photos + + if not photos: + log.ODM_ERROR('Not enough photos in photos array to start OpenSfM') + exit(1) + + octx = OSFMContext(tree.opensfm) + octx.setup(args, tree.dataset_raw, photos, reconstruction=reconstruction, rerun=self.rerun()) + octx.extract_metadata(self.rerun()) + self.update_progress(20) + octx.feature_matching(self.rerun()) + self.update_progress(30) + octx.reconstruct(self.rerun()) + octx.extract_cameras(tree.path(""cameras.json""), self.rerun()) + self.update_progress(70) + + if args.optimize_disk_space: + shutil.rmtree(octx.path(""features"")) + shutil.rmtree(octx.path(""matches"")) + shutil.rmtree(octx.path(""exif"")) + shutil.rmtree(octx.path(""reports"")) + + # If we find a special flag file for split/merge we stop right here + if os.path.exists(octx.path(""split_merge_stop_at_reconstruction.txt"")): + log.ODM_INFO(""Stopping OpenSfM early because we found: %s"" % octx.path(""split_merge_stop_at_reconstruction.txt"")) + self.next_stage = None + return + + if args.fast_orthophoto: + output_file = octx.path('reconstruction.ply') + elif args.use_opensfm_dense: + output_file = tree.opensfm_model + else: + output_file = tree.opensfm_reconstruction + + updated_config_flag_file = octx.path('updated_config.txt') + + # Make sure it's capped by the depthmap-resolution arg, + # since the undistorted images are used for MVS + outputs['undist_image_max_size'] = max( + gsd.image_max_size(photos, args.orthophoto_resolution, tree.opensfm_reconstruction, ignore_gsd=args.ignore_gsd, has_gcp=reconstruction.has_gcp()), + args.depthmap_resolution + ) + + if not io.file_exists(updated_config_flag_file) or self.rerun(): + octx.update_config({'undistorted_image_max_size': outputs['undist_image_max_size']}) + octx.touch(updated_config_flag_file) + + # These will be used for texturing / MVS + if args.radiometric_calibration == ""none"": + octx.convert_and_undistort(self.rerun()) + else: + def radiometric_calibrate(shot_id, image): + photo = reconstruction.get_photo(shot_id) + return multispectral.dn_to_reflectance(photo, image, use_sun_sensor=args.radiometric_calibration==""camera+sun"") + + octx.convert_and_undistort(self.rerun(), radiometric_calibrate) + + self.update_progress(80) + + if reconstruction.multi_camera: + # Dump band image lists + log.ODM_INFO(""Multiple bands found"") + for band in reconstruction.multi_camera: + log.ODM_INFO(""Exporting %s band"" % band['name']) + image_list_file = octx.path(""image_list_%s.txt"" % band['name'].lower()) + + if not io.file_exists(image_list_file) or self.rerun(): + with open(image_list_file, ""w"") as f: + f.write(""\\n"".join([p.filename for p in band['photos']])) + log.ODM_INFO(""Wrote %s"" % image_list_file) + else: + log.ODM_WARNING(""Found a valid image list in %s for %s band"" % (image_list_file, band['name'])) + + nvm_file = octx.path(""undistorted"", ""reconstruction_%s.nvm"" % band['name'].lower()) + if not io.file_exists(nvm_file) or self.rerun(): + octx.run('export_visualsfm --points --image_list ""%s""' % image_list_file) + os.rename(tree.opensfm_reconstruction_nvm, nvm_file) + else: + log.ODM_WARNING(""Found a valid NVM file in %s for %s band"" % (nvm_file, band['name'])) + + if not io.file_exists(tree.opensfm_reconstruction_nvm) or self.rerun(): + octx.run('export_visualsfm --points') + else: + log.ODM_WARNING('Found a valid OpenSfM NVM reconstruction file in: %s' % + tree.opensfm_reconstruction_nvm) + + self.update_progress(85) + + # Skip dense reconstruction if necessary and export + # sparse reconstruction instead + if args.fast_orthophoto: + if not io.file_exists(output_file) or self.rerun(): + octx.run('export_ply --no-cameras') + else: + log.ODM_WARNING(""Found a valid PLY reconstruction in %s"" % output_file) + + elif args.use_opensfm_dense: + if not io.file_exists(output_file) or self.rerun(): + octx.run('compute_depthmaps') + else: + log.ODM_WARNING(""Found a valid dense reconstruction in %s"" % output_file) + + self.update_progress(90) + + if reconstruction.is_georeferenced() and (not io.file_exists(tree.opensfm_transformation) or self.rerun()): + octx.run('export_geocoords --transformation --proj \\'%s\\'' % reconstruction.georef.proj4()) + else: + log.ODM_WARNING(""Will skip exporting %s"" % tree.opensfm_transformation) + + if args.optimize_disk_space: + os.remove(octx.path(""tracks.csv"")) + os.remove(octx.path(""undistorted"", ""tracks.csv"")) + os.remove(octx.path(""undistorted"", ""reconstruction.json"")) + if io.dir_exists(octx.path(""undistorted"", ""depthmaps"")): + files = glob.glob(octx.path(""undistorted"", ""depthmaps"", ""*.npz"")) + for f in files: + os.remove(f)","[{'piece_type': 'error message', 'piece_content': '[INFO] Finished dataset stage\\n[INFO] Running split stage\\n[INFO] Normal dataset, will process all at once.\\n[INFO] Finished split stage\\n[INFO] Running merge stage\\n[INFO] Normal dataset, nothing to merge.\\n[INFO] Finished merge stage\\n[INFO] Running opensfm stage\\n[WARNING] /datasets/project/submodels/submodel_0000/opensfm/image_list.txt already exists, not rerunning OpenSfM setup\\n[WARNING] Detect features already done: /datasets/project/submodels/submodel_0000/opensfm/features exists\\n[WARNING] Match features already done: /datasets/project/submodels/submodel_0000/opensfm/matches exists\\n[WARNING] Found a valid OpenSfM tracks file in: /datasets/project/submodels/submodel_0000/opensfm/tracks.csv\\n[WARNING] Found a valid OpenSfM reconstruction file in: /datasets/project/submodels/submodel_0000/opensfm/reconstruction.json\\n[INFO] Already extracted cameras Traceback (most recent call last):\\nFile ""/code/run.py"", line 62, in \\napp.execute()\\nFile ""/code/stages/odm_app.py"", line 95, in execute\\nself.first_stage.run()\\nFile ""/code/opendm/types.py"", line 350, in run\\nself.next_stage.run(outputs)\\nFile ""/code/opendm/types.py"", line 350, in run\\nself.next_stage.run(outputs)\\nFile ""/code/opendm/types.py"", line 350, in run\\nself.next_stage.run(outputs)\\nFile ""/code/opendm/types.py"", line 331, in run\\nself.process(self.args, outputs)\\nFile ""/code/stages/run_opensfm.py"", line 37, in process\\nshutil.rmtree(octx.path(""features""))\\nFile ""/usr/lib/python2.7/shutil.py"", line 232, in rmtree\\nonerror(os.path.islink, path, sys.exc_info())\\nFile ""/usr/lib/python2.7/shutil.py"", line 230, in rmtree\\nraise OSError(""Cannot call rmtree on a symbolic link"")\\nOSError: Cannot call rmtree on a symbolic link\\nTraceback (most recent call last):\\nFile ""/code/run.py"", line 62, in \\napp.execute()\\nFile ""/code/stages/odm_app.py"", line 95, in execute\\nself.first_stage.run()\\nFile ""/code/opendm/types.py"", line 350, in run\\nself.next_stage.run(outputs)\\nFile ""/code/opendm/types.py"", line 331, in run\\nself.process(self.args, outputs)\\nFile ""/code/stages/splitmerge.py"", line 219, in process\\nsystem.run("" "".join(map(quote, argv)), env_vars=os.environ.copy())\\nFile ""/code/opendm/system.py"", line 76, in run\\nraise Exception(""Child returned {}"".format(retcode))\\nException: Child returned 1'}, {'piece_type': 'other', 'piece_content': 'docker run -ti --rm -v ""$(pwd)"":/datasets odm:v1.0.2 --project-path /datasets project --dsm --orthophoto-resolution 15 --radiometric-calibration camera --dem-resolution 15 --split 200 --split-overlap 50 --pc-las --use-hybrid-bundle-adjustment --max-concurrency 3 --use-opensfm-dense --optimize-disk-space'}]","[INFO] Finished dataset stage +[INFO] Running split stage +[INFO] Normal dataset, will process all at once. +[INFO] Finished split stage +[INFO] Running merge stage +[INFO] Normal dataset, nothing to merge. +[INFO] Finished merge stage +[INFO] Running opensfm stage +[WARNING] /datasets/project/submodels/submodel_0000/opensfm/image_list.txt already exists, not rerunning OpenSfM setup +[WARNING] Detect features already done: /datasets/project/submodels/submodel_0000/opensfm/features exists +[WARNING] Match features already done: /datasets/project/submodels/submodel_0000/opensfm/matches exists +[WARNING] Found a valid OpenSfM tracks file in: /datasets/project/submodels/submodel_0000/opensfm/tracks.csv +[WARNING] Found a valid OpenSfM reconstruction file in: /datasets/project/submodels/submodel_0000/opensfm/reconstruction.json +[INFO] Already extracted cameras Traceback (most recent call last): +File ""/code/run.py"", line 62, in +app.execute() +File ""/code/stages/odm_app.py"", line 95, in execute +self.first_stage.run() +File ""/code/opendm/types.py"", line 350, in run +self.next_stage.run(outputs) +File ""/code/opendm/types.py"", line 350, in run +self.next_stage.run(outputs) +File ""/code/opendm/types.py"", line 350, in run +self.next_stage.run(outputs) +File ""/code/opendm/types.py"", line 331, in run +self.process(self.args, outputs) +File ""/code/stages/run_opensfm.py"", line 37, in process +shutil.rmtree(octx.path(""features"")) +File ""/usr/lib/python2.7/shutil.py"", line 232, in rmtree +onerror(os.path.islink, path, sys.exc_info()) +File ""/usr/lib/python2.7/shutil.py"", line 230, in rmtree +raise OSError(""Cannot call rmtree on a symbolic link"") +OSError: Cannot call rmtree on a symbolic link +Traceback (most recent call last): +File ""/code/run.py"", line 62, in +app.execute() +File ""/code/stages/odm_app.py"", line 95, in execute +self.first_stage.run() +File ""/code/opendm/types.py"", line 350, in run +self.next_stage.run(outputs) +File ""/code/opendm/types.py"", line 331, in run +self.process(self.args, outputs) +File ""/code/stages/splitmerge.py"", line 219, in process +system.run("" "".join(map(quote, argv)), env_vars=os.environ.copy()) +File ""/code/opendm/system.py"", line 76, in run +raise Exception(""Child returned {}"".format(retcode)) +Exception: Child returned 1",OSError +"def build_block_parser(md, **kwargs): + """""" Build the default block parser used by Markdown. """""" + parser = BlockParser(md) + parser.blockprocessors.register(EmptyBlockProcessor(parser), 'empty', 100) + parser.blockprocessors.register(ListIndentProcessor(parser), 'indent', 90) + parser.blockprocessors.register(CodeBlockProcessor(parser), 'code', 80) + parser.blockprocessors.register(HashHeaderProcessor(parser), 'hashheader', 70) + parser.blockprocessors.register(SetextHeaderProcessor(parser), 'setextheader', 60) + parser.blockprocessors.register(HRProcessor(parser), 'hr', 50) + parser.blockprocessors.register(OListProcessor(parser), 'olist', 40) + parser.blockprocessors.register(UListProcessor(parser), 'ulist', 30) + parser.blockprocessors.register(BlockQuoteProcessor(parser), 'quote', 20) + parser.blockprocessors.register(ReferenceProcessor(parser), 'reference', 15) + parser.blockprocessors.register(ParagraphProcessor(parser), 'paragraph', 10) + return parser","def build_block_parser(md, **kwargs): + """""" Build the default block parser used by Markdown. """""" + parser = BlockParser(md) + parser.blockprocessors.register(EmptyBlockProcessor(parser), 'empty', 100) + parser.blockprocessors.register(ListIndentProcessor(parser), 'indent', 90) + parser.blockprocessors.register(CodeBlockProcessor(parser), 'code', 80) + parser.blockprocessors.register(HashHeaderProcessor(parser), 'hashheader', 70) + parser.blockprocessors.register(SetextHeaderProcessor(parser), 'setextheader', 60) + parser.blockprocessors.register(HRProcessor(parser), 'hr', 50) + parser.blockprocessors.register(OListProcessor(parser), 'olist', 40) + parser.blockprocessors.register(UListProcessor(parser), 'ulist', 30) + parser.blockprocessors.register(BlockQuoteProcessor(parser), 'quote', 20) + parser.blockprocessors.register(ParagraphProcessor(parser), 'paragraph', 10) + return parser","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def extendMarkdown(self, md): + """""" Insert AbbrPreprocessor before ReferencePreprocessor. """""" + md.parser.blockprocessors.register(AbbrPreprocessor(md.parser), 'abbr', 16)"," def extendMarkdown(self, md): + """""" Insert AbbrPreprocessor before ReferencePreprocessor. """""" + md.preprocessors.register(AbbrPreprocessor(md), 'abbr', 12)","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def run(self, parent, blocks): + ''' + Find and remove all Abbreviation references from the text. + Each reference is set as a new AbbrPattern in the markdown instance. + + ''' + block = blocks.pop(0) + m = self.RE.search(block) + if m: + abbr = m.group('abbr').strip() + title = m.group('title').strip() + self.parser.md.inlinePatterns.register( + AbbrInlineProcessor(self._generate_pattern(abbr), title), 'abbr-%s' % abbr, 2 + ) + if block[m.end():].strip(): + # Add any content after match back to blocks as separate block + blocks.insert(0, block[m.end():].lstrip('\\n')) + if block[:m.start()].strip(): + # Add any content before match back to blocks as separate block + blocks.insert(0, block[:m.start()].rstrip('\\n')) + return True + # No match. Restore block. + blocks.insert(0, block) + return False"," def run(self, lines): + ''' + Find and remove all Abbreviation references from the text. + Each reference is set as a new AbbrPattern in the markdown instance. + + ''' + new_text = [] + for line in lines: + m = ABBR_REF_RE.match(line) + if m: + abbr = m.group('abbr').strip() + title = m.group('title').strip() + self.md.inlinePatterns.register( + AbbrInlineProcessor(self._generate_pattern(abbr), title), 'abbr-%s' % abbr, 2 + ) + # Preserve the line to prevent raw HTML indexing issue. + # https://github.com/Python-Markdown/markdown/issues/584 + new_text.append('') + else: + new_text.append(line) + return new_text","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def extendMarkdown(self, md): + """""" Add pieces to Markdown. """""" + md.registerExtension(self) + self.parser = md.parser + self.md = md + # Insert a blockprocessor before ReferencePreprocessor + md.parser.blockprocessors.register(FootnoteBlockProcessor(self), 'footnote', 17) + + # Insert an inline pattern before ImageReferencePattern + FOOTNOTE_RE = r'\\[\\^([^\\]]*)\\]' # blah blah [^1] blah + md.inlinePatterns.register(FootnoteInlineProcessor(FOOTNOTE_RE, self), 'footnote', 175) + # Insert a tree-processor that would actually add the footnote div + # This must be before all other treeprocessors (i.e., inline and + # codehilite) so they can run on the the contents of the div. + md.treeprocessors.register(FootnoteTreeprocessor(self), 'footnote', 50) + + # Insert a tree-processor that will run after inline is done. + # In this tree-processor we want to check our duplicate footnote tracker + # And add additional backrefs to the footnote pointing back to the + # duplicated references. + md.treeprocessors.register(FootnotePostTreeprocessor(self), 'footnote-duplicate', 15) + + # Insert a postprocessor after amp_substitute processor + md.postprocessors.register(FootnotePostprocessor(self), 'footnote', 25)"," def extendMarkdown(self, md): + """""" Add pieces to Markdown. """""" + md.registerExtension(self) + self.parser = md.parser + self.md = md + # Insert a preprocessor before ReferencePreprocessor + md.preprocessors.register(FootnotePreprocessor(self), 'footnote', 15) + + # Insert an inline pattern before ImageReferencePattern + FOOTNOTE_RE = r'\\[\\^([^\\]]*)\\]' # blah blah [^1] blah + md.inlinePatterns.register(FootnoteInlineProcessor(FOOTNOTE_RE, self), 'footnote', 175) + # Insert a tree-processor that would actually add the footnote div + # This must be before all other treeprocessors (i.e., inline and + # codehilite) so they can run on the the contents of the div. + md.treeprocessors.register(FootnoteTreeprocessor(self), 'footnote', 50) + + # Insert a tree-processor that will run after inline is done. + # In this tree-processor we want to check our duplicate footnote tracker + # And add additional backrefs to the footnote pointing back to the + # duplicated references. + md.treeprocessors.register(FootnotePostTreeprocessor(self), 'footnote-duplicate', 15) + + # Insert a postprocessor after amp_substitute processor + md.postprocessors.register(FootnotePostprocessor(self), 'footnote', 25)","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def detectTabbed(self, blocks): + """""" Find indented text and remove indent before further proccesing. + + Returns: a list of blocks with indentation removed. + """""" + fn_blocks = [] + while blocks: + if blocks[0].startswith(' '*4): + block = blocks.pop(0) + # Check for new footnotes within this block and split at new footnote. + m = self.RE.search(block) + if m: + # Another footnote exists in this block. + # Any content before match is continuation of this footnote, which may be lazily indented. + before = block[:m.start()].rstrip('\\n') + fn_blocks.append(self.detab(before)) + # Add back to blocks everything from begining of match forward for next iteration. + blocks.insert(0, block[m.start():]) + # End of this footnote. + break + else: + # Entire block is part of this footnote. + fn_blocks.append(self.detab(block)) + else: + # End of this footnote. + break + return fn_blocks"," def detectTabbed(self, lines): + """""" Find indented text and remove indent before further proccesing. + + Keyword arguments: + + * lines: an array of strings + + Returns: a list of post processed items and the index of last line. + + """""" + items = [] + blank_line = False # have we encountered a blank line yet? + i = 0 # to keep track of where we are + + def detab(line): + match = TABBED_RE.match(line) + if match: + return match.group(4) + + for line in lines: + if line.strip(): # Non-blank line + detabbed_line = detab(line) + if detabbed_line: + items.append(detabbed_line) + i += 1 + continue + elif not blank_line and not DEF_RE.match(line): + # not tabbed but still part of first par. + items.append(line) + i += 1 + continue + else: + return items, i+1 + + else: # Blank line: _maybe_ we are done. + blank_line = True + i += 1 # advance + + # Find the next non-blank line + for j in range(i, len(lines)): + if lines[j].strip(): + next_line = lines[j] + break + else: + # Include extreaneous padding to prevent raw HTML + # parsing issue: https://github.com/Python-Markdown/markdown/issues/584 + items.append("""") + i += 1 + else: + break # There is no more text; we are done. + + # Check if the next non-blank line is tabbed + if detab(next_line): # Yes, more work to do. + items.append("""") + continue + else: + break # No, we are done. + else: + i += 1 + + return items, i","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def detab(self, block): + """""" Remove one level of indent from a block. + + Preserve lazily indented blocks by only removing indent from indented lines. + """""" + lines = block.split('\\n') + for i, line in enumerate(lines): + if line.startswith(' '*4): + lines[i] = line[4:] + return '\\n'.join(lines)"," def detab(line): + match = TABBED_RE.match(line) + if match: + return match.group(4)","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def run(self, parent, blocks): + m = util.HTML_PLACEHOLDER_RE.match(blocks[0]) + if m: + index = int(m.group(1)) + element = self.parser.md.htmlStash.rawHtmlBlocks[index] + if isinstance(element, etree.Element): + # We have a matched element. Process it. + blocks.pop(0) + self.parse_element_content(element) + parent.append(element) + # Cleanup stash. Replace element with empty string to avoid confusing postprocessor. + self.parser.md.htmlStash.rawHtmlBlocks.pop(index) + self.parser.md.htmlStash.rawHtmlBlocks.insert(index, '') + # Comfirm the match to the blockparser. + return True + # No match found. + return False"," def run(self, parent, blocks, tail=None, nest=False): + self._tag_data = self.parser.md.htmlStash.tag_data + + self.parser.blockprocessors.tag_counter += 1 + tag = self._tag_data[self.parser.blockprocessors.tag_counter] + + # Create Element + markdown_value = tag['attrs'].pop('markdown') + element = etree.SubElement(parent, tag['tag'], tag['attrs']) + + # Slice Off Block + if nest: + self.parser.parseBlocks(parent, tail) # Process Tail + block = blocks[1:] + else: # includes nests since a third level of nesting isn't supported + block = blocks[tag['left_index'] + 1: tag['right_index']] + del blocks[:tag['right_index']] + + # Process Text + if (self.parser.blockprocessors.contain_span_tags.match( # Span Mode + tag['tag']) and markdown_value != 'block') or \\ + markdown_value == 'span': + element.text = '\\n'.join(block) + else: # Block Mode + i = self.parser.blockprocessors.tag_counter + 1 + if len(self._tag_data) > i and self._tag_data[i]['left_index']: + first_subelement_index = self._tag_data[i]['left_index'] - 1 + self.parser.parseBlocks( + element, block[:first_subelement_index]) + if not nest: + block = self._process_nests(element, block) + else: + self.parser.parseBlocks(element, block)","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def extendMarkdown(self, md): + """""" Register extension instances. """""" + + # Replace raw HTML preprocessor + md.preprocessors.register(HtmlBlockPreprocessor(md), 'html_block', 20) + # Add blockprocessor which handles the placeholders for etree elements + md.parser.blockprocessors.register( + MarkdownInHtmlProcessor(md.parser), 'markdown_block', 105 + )"," def extendMarkdown(self, md): + """""" Register extension instances. """""" + + # Turn on processing of markdown text within raw html + md.preprocessors['html_block'].markdown_in_raw = True + md.parser.blockprocessors.register( + MarkdownInHtmlProcessor(md.parser), 'markdown_block', 105 + ) + md.parser.blockprocessors.tag_counter = -1 + md.parser.blockprocessors.contain_span_tags = re.compile( + r'^(p|h[1-6]|li|dd|dt|td|th|legend|address)$', re.IGNORECASE)","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def run(self, text): + """""" Iterate over html stash and restore html. """""" + replacements = OrderedDict() + for i in range(self.md.htmlStash.html_counter): + html = self.md.htmlStash.rawHtmlBlocks[i] + if self.isblocklevel(html): + replacements[""

{}

"".format( + self.md.htmlStash.get_placeholder(i))] = html + replacements[self.md.htmlStash.get_placeholder(i)] = html + + if replacements: + pattern = re.compile(""|"".join(re.escape(k) for k in replacements)) + processed_text = pattern.sub(lambda m: replacements[m.group(0)], text) + else: + return text + + if processed_text == text: + return processed_text + else: + return self.run(processed_text)"," def run(self, text): + """""" Iterate over html stash and restore html. """""" + replacements = OrderedDict() + for i in range(self.md.htmlStash.html_counter): + html = self.md.htmlStash.rawHtmlBlocks[i] + if self.isblocklevel(html): + replacements[""

%s

"" % + (self.md.htmlStash.get_placeholder(i))] = \\ + html + ""\\n"" + replacements[self.md.htmlStash.get_placeholder(i)] = html + + if replacements: + pattern = re.compile(""|"".join(re.escape(k) for k in replacements)) + processed_text = pattern.sub(lambda m: replacements[m.group(0)], text) + else: + return text + + if processed_text == text: + return processed_text + else: + return self.run(processed_text)","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +"def build_preprocessors(md, **kwargs): + """""" Build the default set of preprocessors used by Markdown. """""" + preprocessors = util.Registry() + preprocessors.register(NormalizeWhitespace(md), 'normalize_whitespace', 30) + preprocessors.register(HtmlBlockPreprocessor(md), 'html_block', 20) + return preprocessors","def build_preprocessors(md, **kwargs): + """""" Build the default set of preprocessors used by Markdown. """""" + preprocessors = util.Registry() + preprocessors.register(NormalizeWhitespace(md), 'normalize_whitespace', 30) + preprocessors.register(HtmlBlockPreprocessor(md), 'html_block', 20) + preprocessors.register(ReferencePreprocessor(md), 'reference', 10) + return preprocessors","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def run(self, lines): + source = '\\n'.join(lines) + parser = HTMLExtractor(self.md) + parser.feed(source) + parser.close() + return ''.join(parser.cleandoc).split('\\n')"," def run(self, lines): + text = ""\\n"".join(lines) + new_blocks = [] + text = text.rsplit(""\\n\\n"") + items = [] + left_tag = '' + right_tag = '' + in_tag = False # flag + + while text: + block = text[0] + if block.startswith(""\\n""): + block = block[1:] + text = text[1:] + + if block.startswith(""\\n""): + block = block[1:] + + if not in_tag: + if block.startswith(""<"") and len(block.strip()) > 1: + + if block[1:4] == ""!--"": + # is a comment block + left_tag, left_index, attrs = ""--"", 2, {} + else: + left_tag, left_index, attrs = self._get_left_tag(block) + right_tag, data_index = self._get_right_tag(left_tag, + left_index, + block) + # keep checking conditions below and maybe just append + + if data_index < len(block) and (self.md.is_block_level(left_tag) or left_tag == '--'): + text.insert(0, block[data_index:]) + block = block[:data_index] + + if not (self.md.is_block_level(left_tag) or block[1] in [""!"", ""?"", ""@"", ""%""]): + new_blocks.append(block) + continue + + if self._is_oneliner(left_tag): + new_blocks.append(block.strip()) + continue + + if block.rstrip().endswith("">"") \\ + and self._equal_tags(left_tag, right_tag): + if self.markdown_in_raw and 'markdown' in attrs.keys(): + block = block[left_index:-len(right_tag) - 2] + new_blocks.append(self.md.htmlStash. + store_tag(left_tag, attrs, 0, 2)) + new_blocks.extend([block]) + else: + new_blocks.append( + self.md.htmlStash.store(block.strip())) + continue + else: + # if is block level tag and is not complete + if (not self._equal_tags(left_tag, right_tag)) and \\ + (self.md.is_block_level(left_tag) or left_tag == ""--""): + items.append(block.strip()) + in_tag = True + else: + new_blocks.append( + self.md.htmlStash.store(block.strip()) + ) + continue + + else: + new_blocks.append(block) + + else: + items.append(block) + + # Need to evaluate all items so we can calculate relative to the left index. + right_tag, data_index = self._get_right_tag(left_tag, left_index, ''.join(items)) + # Adjust data_index: relative to items -> relative to last block + prev_block_length = 0 + for item in items[:-1]: + prev_block_length += len(item) + data_index -= prev_block_length + + if self._equal_tags(left_tag, right_tag): + # if find closing tag + + if data_index < len(block): + # we have more text after right_tag + items[-1] = block[:data_index] + text.insert(0, block[data_index:]) + + in_tag = False + if self.markdown_in_raw and 'markdown' in attrs.keys(): + items[0] = items[0][left_index:] + items[-1] = items[-1][:-len(right_tag) - 2] + if items[len(items) - 1]: # not a newline/empty string + right_index = len(items) + 3 + else: + right_index = len(items) + 2 + new_blocks.append(self.md.htmlStash.store_tag( + left_tag, attrs, 0, right_index)) + placeholderslen = len(self.md.htmlStash.tag_data) + new_blocks.extend( + self._nested_markdown_in_html(items)) + nests = len(self.md.htmlStash.tag_data) - \\ + placeholderslen + self.md.htmlStash.tag_data[-1 - nests][ + 'right_index'] += nests - 2 + else: + new_blocks.append( + self.md.htmlStash.store('\\n\\n'.join(items))) + items = [] + + if items: + if self.markdown_in_raw and 'markdown' in attrs.keys(): + items[0] = items[0][left_index:] + items[-1] = items[-1][:-len(right_tag) - 2] + if items[len(items) - 1]: # not a newline/empty string + right_index = len(items) + 3 + else: + right_index = len(items) + 2 + new_blocks.append( + self.md.htmlStash.store_tag( + left_tag, attrs, 0, right_index)) + placeholderslen = len(self.md.htmlStash.tag_data) + new_blocks.extend(self._nested_markdown_in_html(items)) + nests = len(self.md.htmlStash.tag_data) - placeholderslen + self.md.htmlStash.tag_data[-1 - nests][ + 'right_index'] += nests - 2 + else: + new_blocks.append( + self.md.htmlStash.store('\\n\\n'.join(items))) + new_blocks.append('\\n') + + new_text = ""\\n\\n"".join(new_blocks) + return new_text.split(""\\n"")","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def run(self, lines): + source = '\\n'.join(lines) + parser = HTMLExtractor(self.md) + parser.feed(source) + parser.close() + return ''.join(parser.cleandoc).split('\\n')"," def run(self, lines): + new_text = [] + while lines: + line = lines.pop(0) + m = self.RE.match(line) + if m: + id = m.group(1).strip().lower() + link = m.group(2).lstrip('<').rstrip('>') + t = m.group(5) or m.group(6) or m.group(7) + if not t: + # Check next line for title + tm = self.TITLE_RE.match(lines[0]) + if tm: + lines.pop(0) + t = tm.group(2) or tm.group(3) or tm.group(4) + self.md.references[id] = (link, t) + # Preserve the line to prevent raw HTML indexing issue. + # https://github.com/Python-Markdown/markdown/issues/584 + new_text.append('') + else: + new_text.append(line) + + return new_text # + ""\\n""","[{'piece_type': 'other', 'piece_content': '
\\n
\\n**SomeText**\\n
\\n\\n
\\n\\n**blod text**\\n( small)\\n\\n
\\n* item1\\n* item2\\n
\\n\\nmore text\\n\\n
\\n
'}, {'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test\\noutput = markdown(input, **kwargs)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown\\nreturn md.convert(text)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run\\nblock = self._process_nests(element, block)\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests\\nblock[nest_index[-1][1]:], True) # nest\\nFile ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run\\ntag = self._tag_data[self.parser.blockprocessors.tag_counter]\\nIndexError: list index out of range'}]","Traceback (most recent call last): +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py"", line 117, in test +output = markdown(input, **kwargs) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 391, in markdown +return md.convert(text) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py"", line 268, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 92, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 107, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py"", line 125, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 127, in run +block = self._process_nests(element, block) +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 95, in _process_nests +block[nest_index[-1][1]:], True) # nest +File ""/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py"", line 101, in run +tag = self._tag_data[self.parser.blockprocessors.tag_counter] +IndexError: list index out of range",IndexError +" def run(self, lines): + ''' + Find and remove all Abbreviation references from the text. + Each reference is set as a new AbbrPattern in the markdown instance. + + ''' + new_text = [] + for line in lines: + m = ABBR_REF_RE.match(line) + if m: + abbr = m.group('abbr').strip() + title = m.group('title').strip() + self.markdown.inlinePatterns['abbr-%s' % abbr] = \\ + AbbrPattern(self._generate_pattern(abbr), title) + # Preserve the line to prevent raw HTML indexing issue. + # https://github.com/Python-Markdown/markdown/issues/584 + new_text.append('') + else: + new_text.append(line) + return new_text"," def run(self, lines): + ''' + Find and remove all Abbreviation references from the text. + Each reference is set as a new AbbrPattern in the markdown instance. + + ''' + new_text = [] + for line in lines: + m = ABBR_REF_RE.match(line) + if m: + abbr = m.group('abbr').strip() + title = m.group('title').strip() + self.markdown.inlinePatterns['abbr-%s' % abbr] = \\ + AbbrPattern(self._generate_pattern(abbr), title) + else: + new_text.append(line) + return new_text","[{'piece_type': 'other', 'piece_content': '
\\n\\n[link]: a_link\\n\\n
\\n\\n
\\n\\n
'}, {'piece_type': 'error message', 'piece_content': 'doc-pelican (0.7)$ python3 test.py\\nMarkdown 2.6.9\\nTraceback (most recent call last):\\nFile ""test.py"", line 22, in \\nprint(md.convert(text))\\nFile ""/usr/lib/python3/dist-packages/markdown/__init__.py"", line 371, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 65, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 80, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 98, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 130, in run\\nblock = self._process_nests(element, block)\\nFile ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 97, in _process_nests\\nself.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last\\nIndexError: list index out of range'}]","doc-pelican (0.7)$ python3 test.py +Markdown 2.6.9 +Traceback (most recent call last): +File ""test.py"", line 22, in +print(md.convert(text)) +File ""/usr/lib/python3/dist-packages/markdown/__init__.py"", line 371, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 65, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 80, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 98, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 130, in run +block = self._process_nests(element, block) +File ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 97, in _process_nests +self.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last +IndexError: list index out of range",IndexError +" def run(self, lines): + """""" + Loop through lines and find, set, and remove footnote definitions. + + Keywords: + + * lines: A list of lines of text + + Return: A list of lines of text with footnote definitions removed. + + """""" + newlines = [] + i = 0 + while True: + m = DEF_RE.match(lines[i]) + if m: + fn, _i = self.detectTabbed(lines[i+1:]) + fn.insert(0, m.group(2)) + i += _i-1 # skip past footnote + footnote = ""\\n"".join(fn) + self.footnotes.setFootnote(m.group(1), footnote.rstrip()) + # Preserve a line for each block to prevent raw HTML indexing issue. + # https://github.com/Python-Markdown/markdown/issues/584 + num_blocks = (len(footnote.split('\\n\\n')) * 2) + newlines.extend([''] * (num_blocks)) + else: + newlines.append(lines[i]) + if len(lines) > i+1: + i += 1 + else: + break + return newlines"," def run(self, lines): + """""" + Loop through lines and find, set, and remove footnote definitions. + + Keywords: + + * lines: A list of lines of text + + Return: A list of lines of text with footnote definitions removed. + + """""" + newlines = [] + i = 0 + while True: + m = DEF_RE.match(lines[i]) + if m: + fn, _i = self.detectTabbed(lines[i+1:]) + fn.insert(0, m.group(2)) + i += _i-1 # skip past footnote + self.footnotes.setFootnote(m.group(1), ""\\n"".join(fn)) + else: + newlines.append(lines[i]) + if len(lines) > i+1: + i += 1 + else: + break + return newlines","[{'piece_type': 'other', 'piece_content': '
\\n\\n[link]: a_link\\n\\n
\\n\\n
\\n\\n
'}, {'piece_type': 'error message', 'piece_content': 'doc-pelican (0.7)$ python3 test.py\\nMarkdown 2.6.9\\nTraceback (most recent call last):\\nFile ""test.py"", line 22, in \\nprint(md.convert(text))\\nFile ""/usr/lib/python3/dist-packages/markdown/__init__.py"", line 371, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 65, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 80, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 98, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 130, in run\\nblock = self._process_nests(element, block)\\nFile ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 97, in _process_nests\\nself.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last\\nIndexError: list index out of range'}]","doc-pelican (0.7)$ python3 test.py +Markdown 2.6.9 +Traceback (most recent call last): +File ""test.py"", line 22, in +print(md.convert(text)) +File ""/usr/lib/python3/dist-packages/markdown/__init__.py"", line 371, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 65, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 80, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 98, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 130, in run +block = self._process_nests(element, block) +File ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 97, in _process_nests +self.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last +IndexError: list index out of range",IndexError +" def detectTabbed(self, lines): + """""" Find indented text and remove indent before further proccesing. + + Keyword arguments: + + * lines: an array of strings + + Returns: a list of post processed items and the index of last line. + + """""" + items = [] + blank_line = False # have we encountered a blank line yet? + i = 0 # to keep track of where we are + + def detab(line): + match = TABBED_RE.match(line) + if match: + return match.group(4) + + for line in lines: + if line.strip(): # Non-blank line + detabbed_line = detab(line) + if detabbed_line: + items.append(detabbed_line) + i += 1 + continue + elif not blank_line and not DEF_RE.match(line): + # not tabbed but still part of first par. + items.append(line) + i += 1 + continue + else: + return items, i+1 + + else: # Blank line: _maybe_ we are done. + blank_line = True + i += 1 # advance + + # Find the next non-blank line + for j in range(i, len(lines)): + if lines[j].strip(): + next_line = lines[j] + break + else: + # Include extreaneous padding to prevent raw HTML + # parsing issue: https://github.com/Python-Markdown/markdown/issues/584 + items.append("""") + i += 1 + else: + break # There is no more text; we are done. + + # Check if the next non-blank line is tabbed + if detab(next_line): # Yes, more work to do. + items.append("""") + continue + else: + break # No, we are done. + else: + i += 1 + + return items, i"," def detectTabbed(self, lines): + """""" Find indented text and remove indent before further proccesing. + + Keyword arguments: + + * lines: an array of strings + + Returns: a list of post processed items and the index of last line. + + """""" + items = [] + blank_line = False # have we encountered a blank line yet? + i = 0 # to keep track of where we are + + def detab(line): + match = TABBED_RE.match(line) + if match: + return match.group(4) + + for line in lines: + if line.strip(): # Non-blank line + detabbed_line = detab(line) + if detabbed_line: + items.append(detabbed_line) + i += 1 + continue + elif not blank_line and not DEF_RE.match(line): + # not tabbed but still part of first par. + items.append(line) + i += 1 + continue + else: + return items, i+1 + + else: # Blank line: _maybe_ we are done. + blank_line = True + i += 1 # advance + + # Find the next non-blank line + for j in range(i, len(lines)): + if lines[j].strip(): + next_line = lines[j] + break + else: + break # There is no more text; we are done. + + # Check if the next non-blank line is tabbed + if detab(next_line): # Yes, more work to do. + items.append("""") + continue + else: + break # No, we are done. + else: + i += 1 + + return items, i","[{'piece_type': 'other', 'piece_content': '
\\n\\n[link]: a_link\\n\\n
\\n\\n
\\n\\n
'}, {'piece_type': 'error message', 'piece_content': 'doc-pelican (0.7)$ python3 test.py\\nMarkdown 2.6.9\\nTraceback (most recent call last):\\nFile ""test.py"", line 22, in \\nprint(md.convert(text))\\nFile ""/usr/lib/python3/dist-packages/markdown/__init__.py"", line 371, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 65, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 80, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 98, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 130, in run\\nblock = self._process_nests(element, block)\\nFile ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 97, in _process_nests\\nself.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last\\nIndexError: list index out of range'}]","doc-pelican (0.7)$ python3 test.py +Markdown 2.6.9 +Traceback (most recent call last): +File ""test.py"", line 22, in +print(md.convert(text)) +File ""/usr/lib/python3/dist-packages/markdown/__init__.py"", line 371, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 65, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 80, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 98, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 130, in run +block = self._process_nests(element, block) +File ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 97, in _process_nests +self.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last +IndexError: list index out of range",IndexError +" def run(self, lines): + new_text = [] + while lines: + line = lines.pop(0) + m = self.RE.match(line) + if m: + id = m.group(1).strip().lower() + link = m.group(2).lstrip('<').rstrip('>') + t = m.group(5) or m.group(6) or m.group(7) + if not t: + # Check next line for title + tm = self.TITLE_RE.match(lines[0]) + if tm: + lines.pop(0) + t = tm.group(2) or tm.group(3) or tm.group(4) + self.markdown.references[id] = (link, t) + # Preserve the line to prevent raw HTML indexing issue. + # https://github.com/Python-Markdown/markdown/issues/584 + new_text.append('') + else: + new_text.append(line) + + return new_text # + ""\\n"""," def run(self, lines): + new_text = [] + while lines: + line = lines.pop(0) + m = self.RE.match(line) + if m: + id = m.group(1).strip().lower() + link = m.group(2).lstrip('<').rstrip('>') + t = m.group(5) or m.group(6) or m.group(7) + if not t: + # Check next line for title + tm = self.TITLE_RE.match(lines[0]) + if tm: + lines.pop(0) + t = tm.group(2) or tm.group(3) or tm.group(4) + self.markdown.references[id] = (link, t) + else: + new_text.append(line) + + return new_text # + ""\\n""","[{'piece_type': 'other', 'piece_content': '
\\n\\n[link]: a_link\\n\\n
\\n\\n
\\n\\n
'}, {'piece_type': 'error message', 'piece_content': 'doc-pelican (0.7)$ python3 test.py\\nMarkdown 2.6.9\\nTraceback (most recent call last):\\nFile ""test.py"", line 22, in \\nprint(md.convert(text))\\nFile ""/usr/lib/python3/dist-packages/markdown/__init__.py"", line 371, in convert\\nroot = self.parser.parseDocument(self.lines).getroot()\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 65, in parseDocument\\nself.parseChunk(self.root, \\'\\\\n\\'.join(lines))\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 80, in parseChunk\\nself.parseBlocks(parent, text.split(\\'\\\\n\\\\n\\'))\\nFile ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 98, in parseBlocks\\nif processor.run(parent, blocks) is not False:\\nFile ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 130, in run\\nblock = self._process_nests(element, block)\\nFile ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 97, in _process_nests\\nself.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last\\nIndexError: list index out of range'}]","doc-pelican (0.7)$ python3 test.py +Markdown 2.6.9 +Traceback (most recent call last): +File ""test.py"", line 22, in +print(md.convert(text)) +File ""/usr/lib/python3/dist-packages/markdown/__init__.py"", line 371, in convert +root = self.parser.parseDocument(self.lines).getroot() +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 65, in parseDocument +self.parseChunk(self.root, '\\n'.join(lines)) +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 80, in parseChunk +self.parseBlocks(parent, text.split('\\n\\n')) +File ""/usr/lib/python3/dist-packages/markdown/blockparser.py"", line 98, in parseBlocks +if processor.run(parent, blocks) is not False: +File ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 130, in run +block = self._process_nests(element, block) +File ""/usr/lib/python3/dist-packages/markdown/extensions/extra.py"", line 97, in _process_nests +self.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last +IndexError: list index out of range",IndexError +" def run(self, root): + """""" Add linebreaks to ElementTree root object. """""" + + self._prettifyETree(root) + # Do
's seperately as they are often in the middle of + # inline content and missed by _prettifyETree. + brs = root.iter('br') + for br in brs: + if not br.tail or not br.tail.strip(): + br.tail = '\\n' + else: + br.tail = '\\n%s' % br.tail + # Clean up extra empty lines at end of code blocks. + pres = root.iter('pre') + for pre in pres: + if len(pre) and pre[0].tag == 'code': + pre[0].text = util.AtomicString(pre[0].text.rstrip() + '\\n')"," def run(self, root): + """""" Add linebreaks to ElementTree root object. """""" + + self._prettifyETree(root) + # Do
's seperately as they are often in the middle of + # inline content and missed by _prettifyETree. + brs = root.getiterator('br') + for br in brs: + if not br.tail or not br.tail.strip(): + br.tail = '\\n' + else: + br.tail = '\\n%s' % br.tail + # Clean up extra empty lines at end of code blocks. + pres = root.getiterator('pre') + for pre in pres: + if len(pre) and pre[0].tag == 'code': + pre[0].text = util.AtomicString(pre[0].text.rstrip() + '\\n')","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile """", line 1, in \\nFile ""/tmp/pip-build-hiv4fz31/Markdown/setup.py"", line 270, in \\n\\'Topic :: Text Processing :: Markup :: HTML\\'\\nFile ""/usr/local/lib/python3.6/distutils/core.py"", line 148, in setup\\ndist.run_commands()\\nFile ""/usr/local/lib/python3.6/distutils/dist.py"", line 955, in run_commands\\nself.run_command(cmd)\\nFile ""/usr/local/lib/python3.6/distutils/dist.py"", line 974, in run_command\\ncmd_obj.run()\\nFile ""/usr/local/lib/python3.6/site-packages/setuptools/command/install.py"", line 61, in run\\nreturn orig.install.run(self)\\nFile ""/usr/local/lib/python3.6/distutils/command/install.py"", line 545, in run\\nself.run_command(\\'build\\')\\nFile ""/usr/local/lib/python3.6/distutils/cmd.py"", line 313, in run_command\\nself.distribution.run_command(command)\\nFile ""/usr/local/lib/python3.6/distutils/dist.py"", line 974, in run_command\\ncmd_obj.run()\\nFile ""/usr/local/lib/python3.6/distutils/command/build.py"", line 135, in run\\nself.run_command(cmd_name)\\nFile ""/usr/local/lib/python3.6/distutils/cmd.py"", line 313, in run_command\\nself.distribution.run_command(command)\\nFile ""/usr/local/lib/python3.6/distutils/dist.py"", line 974, in run_command\\ncmd_obj.run()\\nFile ""/tmp/pip-build-hiv4fz31/Markdown/setup.py"", line 184, in run\\nout = template % self._get_context(src, outfile)\\nFile ""/tmp/pip-build-hiv4fz31/Markdown/setup.py"", line 116, in _get_context\\nc[\\'body\\'] = self.md.convert(src)\\nFile ""build/lib/markdown/__init__.py"", line 375, in convert\\nnewRoot = treeprocessor.run(root)\\nFile ""build/lib/markdown/treeprocessors.py"", line 361, in run\\nbrs = root.getiterator(\\'br\\')\\nSystemError: Python/getargs.c:1508: bad argument to internal function'}]","Traceback (most recent call last): +File """", line 1, in +File ""/tmp/pip-build-hiv4fz31/Markdown/setup.py"", line 270, in +'Topic :: Text Processing :: Markup :: HTML' +File ""/usr/local/lib/python3.6/distutils/core.py"", line 148, in setup +dist.run_commands() +File ""/usr/local/lib/python3.6/distutils/dist.py"", line 955, in run_commands +self.run_command(cmd) +File ""/usr/local/lib/python3.6/distutils/dist.py"", line 974, in run_command +cmd_obj.run() +File ""/usr/local/lib/python3.6/site-packages/setuptools/command/install.py"", line 61, in run +return orig.install.run(self) +File ""/usr/local/lib/python3.6/distutils/command/install.py"", line 545, in run +self.run_command('build') +File ""/usr/local/lib/python3.6/distutils/cmd.py"", line 313, in run_command +self.distribution.run_command(command) +File ""/usr/local/lib/python3.6/distutils/dist.py"", line 974, in run_command +cmd_obj.run() +File ""/usr/local/lib/python3.6/distutils/command/build.py"", line 135, in run +self.run_command(cmd_name) +File ""/usr/local/lib/python3.6/distutils/cmd.py"", line 313, in run_command +self.distribution.run_command(command) +File ""/usr/local/lib/python3.6/distutils/dist.py"", line 974, in run_command +cmd_obj.run() +File ""/tmp/pip-build-hiv4fz31/Markdown/setup.py"", line 184, in run +out = template % self._get_context(src, outfile) +File ""/tmp/pip-build-hiv4fz31/Markdown/setup.py"", line 116, in _get_context +c['body'] = self.md.convert(src) +File ""build/lib/markdown/__init__.py"", line 375, in convert +newRoot = treeprocessor.run(root) +File ""build/lib/markdown/treeprocessors.py"", line 361, in run +brs = root.getiterator('br') +SystemError: Python/getargs.c:1508: bad argument to internal function",SystemError +" def unescape(self, text): + """""" Return unescaped text given text with an inline placeholder. """""" + try: + stash = self.markdown.treeprocessors['inline'].stashed_nodes + except KeyError: + return text + def get_stash(m): + id = m.group(1) + if id in stash: + text = stash.get(id) + if isinstance(text, basestring): + return text + else: + return self.markdown.serializer(text) + return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)"," def unescape(self, text): + """""" Return unescaped text given text with an inline placeholder. """""" + try: + stash = self.markdown.treeprocessors['inline'].stashed_nodes + except KeyError: + return text + def get_stash(m): + id = m.group(1) + if id in stash: + return stash.get(id) + return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)","[{'piece_type': 'source code', 'piece_content': ""markdown.Markdown(safe_mode='escape').convert('<@`x`>')""}, {'piece_type': 'error message', 'piece_content': 'In [1]: import markdown\\n\\nIn [2]: markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n---------------------------------------------------------------------------\\nTypeError Traceback (most recent call last)\\n in ()\\n----> 1 markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n\\nPython-Markdown/markdown/__init__.pyc in convert(self, source)\\n300 # Run the tree-processors\\n301 for treeprocessor in self.treeprocessors.values():\\n--> 302 newRoot = treeprocessor.run(root)\\n303 if newRoot:\\n304 root = newRoot\\n\\nPython-Markdown/markdown/treeprocessors.pyc in run(self, tree)\\n287 child.text = None\\n288 lst = self.__processPlaceholders(self.__handleInline(\\n--> 289 text), child)\\n290 stack += lst\\n291 insertQueue.append((child, lst))\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)\\n108 data, matched, startIndex = self.__applyPattern(\\n109 self.markdown.inlinePatterns.value_for_index(patternIndex),\\n--> 110 data, patternIndex, startIndex)\\n111 if not matched:\\n112 patternIndex += 1\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)\\n235 return data, False, 0\\n236\\n--> 237 node = pattern.handleMatch(match)\\n238\\n239 if node is None:\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)\\n436 def handleMatch(self, m):\\n437 el = util.etree.Element(\\'a\\')\\n--> 438 email = self.unescape(m.group(2))\\n439 if email.startswith(""mailto:""):\\n440 email = email[len(""mailto:""):]\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)\\n196 if id in stash:\\n197 return stash.get(id)\\n--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)\\n199\\n200\\n\\nTypeError: sequence item 1: expected string or Unicode, Element found'}]","In [1]: import markdown + +In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>') +--------------------------------------------------------------------------- +TypeError Traceback (most recent call last) + in () +----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>') + +Python-Markdown/markdown/__init__.pyc in convert(self, source) +300 # Run the tree-processors +301 for treeprocessor in self.treeprocessors.values(): +--> 302 newRoot = treeprocessor.run(root) +303 if newRoot: +304 root = newRoot + +Python-Markdown/markdown/treeprocessors.pyc in run(self, tree) +287 child.text = None +288 lst = self.__processPlaceholders(self.__handleInline( +--> 289 text), child) +290 stack += lst +291 insertQueue.append((child, lst)) + +Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex) +108 data, matched, startIndex = self.__applyPattern( +109 self.markdown.inlinePatterns.value_for_index(patternIndex), +--> 110 data, patternIndex, startIndex) +111 if not matched: +112 patternIndex += 1 + +Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex) +235 return data, False, 0 +236 +--> 237 node = pattern.handleMatch(match) +238 +239 if node is None: + +Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m) +436 def handleMatch(self, m): +437 el = util.etree.Element('a') +--> 438 email = self.unescape(m.group(2)) +439 if email.startswith(""mailto:""): +440 email = email[len(""mailto:""):] + +Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text) +196 if id in stash: +197 return stash.get(id) +--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text) +199 +200 + +TypeError: sequence item 1: expected string or Unicode, Element found",TypeError +" def get_stash(m): + id = m.group(1) + if id in stash: + text = stash.get(id) + if isinstance(text, basestring): + return text + else: + return self.markdown.serializer(text)"," def get_stash(m): + id = m.group(1) + if id in stash: + return stash.get(id)","[{'piece_type': 'source code', 'piece_content': ""markdown.Markdown(safe_mode='escape').convert('<@`x`>')""}, {'piece_type': 'error message', 'piece_content': 'In [1]: import markdown\\n\\nIn [2]: markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n---------------------------------------------------------------------------\\nTypeError Traceback (most recent call last)\\n in ()\\n----> 1 markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n\\nPython-Markdown/markdown/__init__.pyc in convert(self, source)\\n300 # Run the tree-processors\\n301 for treeprocessor in self.treeprocessors.values():\\n--> 302 newRoot = treeprocessor.run(root)\\n303 if newRoot:\\n304 root = newRoot\\n\\nPython-Markdown/markdown/treeprocessors.pyc in run(self, tree)\\n287 child.text = None\\n288 lst = self.__processPlaceholders(self.__handleInline(\\n--> 289 text), child)\\n290 stack += lst\\n291 insertQueue.append((child, lst))\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)\\n108 data, matched, startIndex = self.__applyPattern(\\n109 self.markdown.inlinePatterns.value_for_index(patternIndex),\\n--> 110 data, patternIndex, startIndex)\\n111 if not matched:\\n112 patternIndex += 1\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)\\n235 return data, False, 0\\n236\\n--> 237 node = pattern.handleMatch(match)\\n238\\n239 if node is None:\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)\\n436 def handleMatch(self, m):\\n437 el = util.etree.Element(\\'a\\')\\n--> 438 email = self.unescape(m.group(2))\\n439 if email.startswith(""mailto:""):\\n440 email = email[len(""mailto:""):]\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)\\n196 if id in stash:\\n197 return stash.get(id)\\n--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)\\n199\\n200\\n\\nTypeError: sequence item 1: expected string or Unicode, Element found'}]","In [1]: import markdown + +In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>') +--------------------------------------------------------------------------- +TypeError Traceback (most recent call last) + in () +----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>') + +Python-Markdown/markdown/__init__.pyc in convert(self, source) +300 # Run the tree-processors +301 for treeprocessor in self.treeprocessors.values(): +--> 302 newRoot = treeprocessor.run(root) +303 if newRoot: +304 root = newRoot + +Python-Markdown/markdown/treeprocessors.pyc in run(self, tree) +287 child.text = None +288 lst = self.__processPlaceholders(self.__handleInline( +--> 289 text), child) +290 stack += lst +291 insertQueue.append((child, lst)) + +Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex) +108 data, matched, startIndex = self.__applyPattern( +109 self.markdown.inlinePatterns.value_for_index(patternIndex), +--> 110 data, patternIndex, startIndex) +111 if not matched: +112 patternIndex += 1 + +Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex) +235 return data, False, 0 +236 +--> 237 node = pattern.handleMatch(match) +238 +239 if node is None: + +Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m) +436 def handleMatch(self, m): +437 el = util.etree.Element('a') +--> 438 email = self.unescape(m.group(2)) +439 if email.startswith(""mailto:""): +440 email = email[len(""mailto:""):] + +Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text) +196 if id in stash: +197 return stash.get(id) +--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text) +199 +200 + +TypeError: sequence item 1: expected string or Unicode, Element found",TypeError +" def unescape(self, text): + """""" Return unescaped text given text with an inline placeholder. """""" + try: + stash = self.markdown.treeprocessors['inline'].stashed_nodes + except KeyError: + return text + def itertext(el): + ' Reimplement Element.itertext for older python versions ' + tag = el.tag + if not isinstance(tag, basestring) and tag is not None: + return + if el.text: + yield el.text + for e in el: + for s in itertext(e): + yield s + if e.tail: + yield e.tail + def get_stash(m): + id = m.group(1) + if id in stash: + value = stash.get(id) + if isinstance(value, basestring): + return value + else: + # An etree Element - return text content only + return ''.join(itertext(value)) + return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)"," def unescape(self, text): + """""" Return unescaped text given text with an inline placeholder. """""" + try: + stash = self.markdown.treeprocessors['inline'].stashed_nodes + except KeyError: + return text + def get_stash(m): + id = m.group(1) + if id in stash: + text = stash.get(id) + if isinstance(text, basestring): + return text + else: + return self.markdown.serializer(text) + return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)","[{'piece_type': 'source code', 'piece_content': ""markdown.Markdown(safe_mode='escape').convert('<@`x`>')""}, {'piece_type': 'error message', 'piece_content': 'In [1]: import markdown\\n\\nIn [2]: markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n---------------------------------------------------------------------------\\nTypeError Traceback (most recent call last)\\n in ()\\n----> 1 markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n\\nPython-Markdown/markdown/__init__.pyc in convert(self, source)\\n300 # Run the tree-processors\\n301 for treeprocessor in self.treeprocessors.values():\\n--> 302 newRoot = treeprocessor.run(root)\\n303 if newRoot:\\n304 root = newRoot\\n\\nPython-Markdown/markdown/treeprocessors.pyc in run(self, tree)\\n287 child.text = None\\n288 lst = self.__processPlaceholders(self.__handleInline(\\n--> 289 text), child)\\n290 stack += lst\\n291 insertQueue.append((child, lst))\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)\\n108 data, matched, startIndex = self.__applyPattern(\\n109 self.markdown.inlinePatterns.value_for_index(patternIndex),\\n--> 110 data, patternIndex, startIndex)\\n111 if not matched:\\n112 patternIndex += 1\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)\\n235 return data, False, 0\\n236\\n--> 237 node = pattern.handleMatch(match)\\n238\\n239 if node is None:\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)\\n436 def handleMatch(self, m):\\n437 el = util.etree.Element(\\'a\\')\\n--> 438 email = self.unescape(m.group(2))\\n439 if email.startswith(""mailto:""):\\n440 email = email[len(""mailto:""):]\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)\\n196 if id in stash:\\n197 return stash.get(id)\\n--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)\\n199\\n200\\n\\nTypeError: sequence item 1: expected string or Unicode, Element found'}]","In [1]: import markdown + +In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>') +--------------------------------------------------------------------------- +TypeError Traceback (most recent call last) + in () +----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>') + +Python-Markdown/markdown/__init__.pyc in convert(self, source) +300 # Run the tree-processors +301 for treeprocessor in self.treeprocessors.values(): +--> 302 newRoot = treeprocessor.run(root) +303 if newRoot: +304 root = newRoot + +Python-Markdown/markdown/treeprocessors.pyc in run(self, tree) +287 child.text = None +288 lst = self.__processPlaceholders(self.__handleInline( +--> 289 text), child) +290 stack += lst +291 insertQueue.append((child, lst)) + +Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex) +108 data, matched, startIndex = self.__applyPattern( +109 self.markdown.inlinePatterns.value_for_index(patternIndex), +--> 110 data, patternIndex, startIndex) +111 if not matched: +112 patternIndex += 1 + +Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex) +235 return data, False, 0 +236 +--> 237 node = pattern.handleMatch(match) +238 +239 if node is None: + +Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m) +436 def handleMatch(self, m): +437 el = util.etree.Element('a') +--> 438 email = self.unescape(m.group(2)) +439 if email.startswith(""mailto:""): +440 email = email[len(""mailto:""):] + +Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text) +196 if id in stash: +197 return stash.get(id) +--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text) +199 +200 + +TypeError: sequence item 1: expected string or Unicode, Element found",TypeError +" def get_stash(m): + id = m.group(1) + value = stash.get(id) + if value is not None: + try: + return self.markdown.serializer(text) + except: + return '\\%s' % value"," def get_stash(m): + id = m.group(1) + value = stash.get(id) + if value is not None: + try: + return self.markdown.serializer(value) + except: + return '\\%s' % value","[{'piece_type': 'source code', 'piece_content': ""markdown.Markdown(safe_mode='escape').convert('<@`x`>')""}, {'piece_type': 'error message', 'piece_content': 'In [1]: import markdown\\n\\nIn [2]: markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n---------------------------------------------------------------------------\\nTypeError Traceback (most recent call last)\\n in ()\\n----> 1 markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n\\nPython-Markdown/markdown/__init__.pyc in convert(self, source)\\n300 # Run the tree-processors\\n301 for treeprocessor in self.treeprocessors.values():\\n--> 302 newRoot = treeprocessor.run(root)\\n303 if newRoot:\\n304 root = newRoot\\n\\nPython-Markdown/markdown/treeprocessors.pyc in run(self, tree)\\n287 child.text = None\\n288 lst = self.__processPlaceholders(self.__handleInline(\\n--> 289 text), child)\\n290 stack += lst\\n291 insertQueue.append((child, lst))\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)\\n108 data, matched, startIndex = self.__applyPattern(\\n109 self.markdown.inlinePatterns.value_for_index(patternIndex),\\n--> 110 data, patternIndex, startIndex)\\n111 if not matched:\\n112 patternIndex += 1\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)\\n235 return data, False, 0\\n236\\n--> 237 node = pattern.handleMatch(match)\\n238\\n239 if node is None:\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)\\n436 def handleMatch(self, m):\\n437 el = util.etree.Element(\\'a\\')\\n--> 438 email = self.unescape(m.group(2))\\n439 if email.startswith(""mailto:""):\\n440 email = email[len(""mailto:""):]\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)\\n196 if id in stash:\\n197 return stash.get(id)\\n--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)\\n199\\n200\\n\\nTypeError: sequence item 1: expected string or Unicode, Element found'}]","In [1]: import markdown + +In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>') +--------------------------------------------------------------------------- +TypeError Traceback (most recent call last) + in () +----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>') + +Python-Markdown/markdown/__init__.pyc in convert(self, source) +300 # Run the tree-processors +301 for treeprocessor in self.treeprocessors.values(): +--> 302 newRoot = treeprocessor.run(root) +303 if newRoot: +304 root = newRoot + +Python-Markdown/markdown/treeprocessors.pyc in run(self, tree) +287 child.text = None +288 lst = self.__processPlaceholders(self.__handleInline( +--> 289 text), child) +290 stack += lst +291 insertQueue.append((child, lst)) + +Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex) +108 data, matched, startIndex = self.__applyPattern( +109 self.markdown.inlinePatterns.value_for_index(patternIndex), +--> 110 data, patternIndex, startIndex) +111 if not matched: +112 patternIndex += 1 + +Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex) +235 return data, False, 0 +236 +--> 237 node = pattern.handleMatch(match) +238 +239 if node is None: + +Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m) +436 def handleMatch(self, m): +437 el = util.etree.Element('a') +--> 438 email = self.unescape(m.group(2)) +439 if email.startswith(""mailto:""): +440 email = email[len(""mailto:""):] + +Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text) +196 if id in stash: +197 return stash.get(id) +--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text) +199 +200 + +TypeError: sequence item 1: expected string or Unicode, Element found",TypeError +" def get_stash(m): + id = m.group(1) + if id in stash: + value = stash.get(id) + if isinstance(value, basestring): + return value + else: + # An etree Element - return text content only + return ''.join(itertext(value)) "," def get_stash(m): + id = m.group(1) + if id in stash: + text = stash.get(id) + if isinstance(text, basestring): + return text + else: + return self.markdown.serializer(text)","[{'piece_type': 'source code', 'piece_content': ""markdown.Markdown(safe_mode='escape').convert('<@`x`>')""}, {'piece_type': 'error message', 'piece_content': 'In [1]: import markdown\\n\\nIn [2]: markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n---------------------------------------------------------------------------\\nTypeError Traceback (most recent call last)\\n in ()\\n----> 1 markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n\\nPython-Markdown/markdown/__init__.pyc in convert(self, source)\\n300 # Run the tree-processors\\n301 for treeprocessor in self.treeprocessors.values():\\n--> 302 newRoot = treeprocessor.run(root)\\n303 if newRoot:\\n304 root = newRoot\\n\\nPython-Markdown/markdown/treeprocessors.pyc in run(self, tree)\\n287 child.text = None\\n288 lst = self.__processPlaceholders(self.__handleInline(\\n--> 289 text), child)\\n290 stack += lst\\n291 insertQueue.append((child, lst))\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)\\n108 data, matched, startIndex = self.__applyPattern(\\n109 self.markdown.inlinePatterns.value_for_index(patternIndex),\\n--> 110 data, patternIndex, startIndex)\\n111 if not matched:\\n112 patternIndex += 1\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)\\n235 return data, False, 0\\n236\\n--> 237 node = pattern.handleMatch(match)\\n238\\n239 if node is None:\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)\\n436 def handleMatch(self, m):\\n437 el = util.etree.Element(\\'a\\')\\n--> 438 email = self.unescape(m.group(2))\\n439 if email.startswith(""mailto:""):\\n440 email = email[len(""mailto:""):]\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)\\n196 if id in stash:\\n197 return stash.get(id)\\n--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)\\n199\\n200\\n\\nTypeError: sequence item 1: expected string or Unicode, Element found'}]","In [1]: import markdown + +In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>') +--------------------------------------------------------------------------- +TypeError Traceback (most recent call last) + in () +----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>') + +Python-Markdown/markdown/__init__.pyc in convert(self, source) +300 # Run the tree-processors +301 for treeprocessor in self.treeprocessors.values(): +--> 302 newRoot = treeprocessor.run(root) +303 if newRoot: +304 root = newRoot + +Python-Markdown/markdown/treeprocessors.pyc in run(self, tree) +287 child.text = None +288 lst = self.__processPlaceholders(self.__handleInline( +--> 289 text), child) +290 stack += lst +291 insertQueue.append((child, lst)) + +Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex) +108 data, matched, startIndex = self.__applyPattern( +109 self.markdown.inlinePatterns.value_for_index(patternIndex), +--> 110 data, patternIndex, startIndex) +111 if not matched: +112 patternIndex += 1 + +Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex) +235 return data, False, 0 +236 +--> 237 node = pattern.handleMatch(match) +238 +239 if node is None: + +Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m) +436 def handleMatch(self, m): +437 el = util.etree.Element('a') +--> 438 email = self.unescape(m.group(2)) +439 if email.startswith(""mailto:""): +440 email = email[len(""mailto:""):] + +Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text) +196 if id in stash: +197 return stash.get(id) +--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text) +199 +200 + +TypeError: sequence item 1: expected string or Unicode, Element found",TypeError +" def unescape(self, text): + """""" Return unescaped text given text with an inline placeholder. """""" + try: + stash = self.markdown.treeprocessors['inline'].stashed_nodes + except KeyError: + return text + def get_stash(m): + id = m.group(1) + value = stash.get(id) + if value is not None: + try: + return self.markdown.serializer(text) + except: + return '\\%s' % value + + return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)"," def unescape(self, text): + """""" Return unescaped text given text with an inline placeholder. """""" + try: + stash = self.markdown.treeprocessors['inline'].stashed_nodes + except KeyError: + return text + def get_stash(m): + id = m.group(1) + value = stash.get(id) + if value is not None: + try: + return self.markdown.serializer(value) + except: + return '\\%s' % value + + return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)","[{'piece_type': 'source code', 'piece_content': ""markdown.Markdown(safe_mode='escape').convert('<@`x`>')""}, {'piece_type': 'error message', 'piece_content': 'In [1]: import markdown\\n\\nIn [2]: markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n---------------------------------------------------------------------------\\nTypeError Traceback (most recent call last)\\n in ()\\n----> 1 markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n\\nPython-Markdown/markdown/__init__.pyc in convert(self, source)\\n300 # Run the tree-processors\\n301 for treeprocessor in self.treeprocessors.values():\\n--> 302 newRoot = treeprocessor.run(root)\\n303 if newRoot:\\n304 root = newRoot\\n\\nPython-Markdown/markdown/treeprocessors.pyc in run(self, tree)\\n287 child.text = None\\n288 lst = self.__processPlaceholders(self.__handleInline(\\n--> 289 text), child)\\n290 stack += lst\\n291 insertQueue.append((child, lst))\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)\\n108 data, matched, startIndex = self.__applyPattern(\\n109 self.markdown.inlinePatterns.value_for_index(patternIndex),\\n--> 110 data, patternIndex, startIndex)\\n111 if not matched:\\n112 patternIndex += 1\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)\\n235 return data, False, 0\\n236\\n--> 237 node = pattern.handleMatch(match)\\n238\\n239 if node is None:\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)\\n436 def handleMatch(self, m):\\n437 el = util.etree.Element(\\'a\\')\\n--> 438 email = self.unescape(m.group(2))\\n439 if email.startswith(""mailto:""):\\n440 email = email[len(""mailto:""):]\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)\\n196 if id in stash:\\n197 return stash.get(id)\\n--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)\\n199\\n200\\n\\nTypeError: sequence item 1: expected string or Unicode, Element found'}]","In [1]: import markdown + +In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>') +--------------------------------------------------------------------------- +TypeError Traceback (most recent call last) + in () +----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>') + +Python-Markdown/markdown/__init__.pyc in convert(self, source) +300 # Run the tree-processors +301 for treeprocessor in self.treeprocessors.values(): +--> 302 newRoot = treeprocessor.run(root) +303 if newRoot: +304 root = newRoot + +Python-Markdown/markdown/treeprocessors.pyc in run(self, tree) +287 child.text = None +288 lst = self.__processPlaceholders(self.__handleInline( +--> 289 text), child) +290 stack += lst +291 insertQueue.append((child, lst)) + +Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex) +108 data, matched, startIndex = self.__applyPattern( +109 self.markdown.inlinePatterns.value_for_index(patternIndex), +--> 110 data, patternIndex, startIndex) +111 if not matched: +112 patternIndex += 1 + +Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex) +235 return data, False, 0 +236 +--> 237 node = pattern.handleMatch(match) +238 +239 if node is None: + +Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m) +436 def handleMatch(self, m): +437 el = util.etree.Element('a') +--> 438 email = self.unescape(m.group(2)) +439 if email.startswith(""mailto:""): +440 email = email[len(""mailto:""):] + +Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text) +196 if id in stash: +197 return stash.get(id) +--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text) +199 +200 + +TypeError: sequence item 1: expected string or Unicode, Element found",TypeError +" def makeTag(self, href, title, text): + el = util.etree.Element(""img"") + el.set(""src"", self.sanitize_url(href)) + if title: + el.set(""title"", title) + el.set(""alt"", self.unescape(text)) + return el"," def makeTag(self, href, title, text): + el = util.etree.Element(""img"") + el.set(""src"", self.sanitize_url(href)) + if title: + el.set(""title"", title) + el.set(""alt"", text) + return el","[{'piece_type': 'source code', 'piece_content': ""markdown.Markdown(safe_mode='escape').convert('<@`x`>')""}, {'piece_type': 'error message', 'piece_content': 'In [1]: import markdown\\n\\nIn [2]: markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n---------------------------------------------------------------------------\\nTypeError Traceback (most recent call last)\\n in ()\\n----> 1 markdown.Markdown(safe_mode=\\'escape\\').convert(\\'<@`x`>\\')\\n\\nPython-Markdown/markdown/__init__.pyc in convert(self, source)\\n300 # Run the tree-processors\\n301 for treeprocessor in self.treeprocessors.values():\\n--> 302 newRoot = treeprocessor.run(root)\\n303 if newRoot:\\n304 root = newRoot\\n\\nPython-Markdown/markdown/treeprocessors.pyc in run(self, tree)\\n287 child.text = None\\n288 lst = self.__processPlaceholders(self.__handleInline(\\n--> 289 text), child)\\n290 stack += lst\\n291 insertQueue.append((child, lst))\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)\\n108 data, matched, startIndex = self.__applyPattern(\\n109 self.markdown.inlinePatterns.value_for_index(patternIndex),\\n--> 110 data, patternIndex, startIndex)\\n111 if not matched:\\n112 patternIndex += 1\\n\\nPython-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)\\n235 return data, False, 0\\n236\\n--> 237 node = pattern.handleMatch(match)\\n238\\n239 if node is None:\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)\\n436 def handleMatch(self, m):\\n437 el = util.etree.Element(\\'a\\')\\n--> 438 email = self.unescape(m.group(2))\\n439 if email.startswith(""mailto:""):\\n440 email = email[len(""mailto:""):]\\n\\nPython-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)\\n196 if id in stash:\\n197 return stash.get(id)\\n--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)\\n199\\n200\\n\\nTypeError: sequence item 1: expected string or Unicode, Element found'}]","In [1]: import markdown + +In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>') +--------------------------------------------------------------------------- +TypeError Traceback (most recent call last) + in () +----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>') + +Python-Markdown/markdown/__init__.pyc in convert(self, source) +300 # Run the tree-processors +301 for treeprocessor in self.treeprocessors.values(): +--> 302 newRoot = treeprocessor.run(root) +303 if newRoot: +304 root = newRoot + +Python-Markdown/markdown/treeprocessors.pyc in run(self, tree) +287 child.text = None +288 lst = self.__processPlaceholders(self.__handleInline( +--> 289 text), child) +290 stack += lst +291 insertQueue.append((child, lst)) + +Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex) +108 data, matched, startIndex = self.__applyPattern( +109 self.markdown.inlinePatterns.value_for_index(patternIndex), +--> 110 data, patternIndex, startIndex) +111 if not matched: +112 patternIndex += 1 + +Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex) +235 return data, False, 0 +236 +--> 237 node = pattern.handleMatch(match) +238 +239 if node is None: + +Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m) +436 def handleMatch(self, m): +437 el = util.etree.Element('a') +--> 438 email = self.unescape(m.group(2)) +439 if email.startswith(""mailto:""): +440 email = email[len(""mailto:""):] + +Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text) +196 if id in stash: +197 return stash.get(id) +--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text) +199 +200 + +TypeError: sequence item 1: expected string or Unicode, Element found",TypeError +" def _get_left_tag(self, block): + m = self.left_tag_re.match(block) + if m: + tag = m.group('tag') + raw_attrs = m.group('attrs') + attrs = {} + if raw_attrs: + for ma in self.attrs_re.finditer(raw_attrs): + if ma.group('attr'): + if ma.group('value'): + attrs[ma.group('attr').strip()] = ma.group('value') + else: + attrs[ma.group('attr').strip()] = """" + elif ma.group('attr1'): + if ma.group('value1'): + attrs[ma.group('attr1').strip()] = ma.group('value1') + else: + attrs[ma.group('attr1').strip()] = """" + elif ma.group('attr2'): + attrs[ma.group('attr2').strip()] = """" + return tag, len(m.group(0)), attrs + else: + tag = block[1:].split("">"", 1)[0].lower() + return tag, len(tag)+2, {}"," def _get_left_tag(self, block): + m = self.left_tag_re.match(block) + if m: + tag = m.group('tag') + raw_attrs = m.group('attrs') + attrs = {} + if raw_attrs: + for ma in self.attrs_re.finditer(raw_attrs): + if ma.group('attr'): + if ma.group('value'): + attrs[ma.group('attr').strip()] = ma.group('value') + else: + attrs[ma.group('attr').strip()] = """" + elif ma.group('attr1'): + if ma.group('value1'): + attrs[ma.group('attr1').strip()] = ma.group('value1') + else: + attrs[ma.group('attr1').strip()] = """" + elif ma.group('attr2'): + attrs[ma.group('attr2').strip()] = """" + return tag, len(m.group(0)), attrs + else: + tag = block[1:].replace("">"", "" "", 1).split()[0].lower() + return tag, len(tag)+2, {}","[{'piece_type': 'error message', 'piece_content': 'markdown.markdown(\\'<>\\')\\nTraceback (most recent call last):\\nFile """", line 1, in \\nFile ""/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/__init__.py"", line 386, in markdown\\nreturn md.convert(text)\\nFile ""/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/__init__.py"", line 280, in convert\\nself.lines = prep.run(self.lines)\\nFile ""/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/preprocessors.py"", line 146, in run\\nleft_tag, left_index, attrs = self._get_left_tag(block)\\nFile ""/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/preprocessors.py"", line 81, in _get_left_tag\\ntag = block[1:].replace("">"", "" "", 1).split()[0].lower()\\nIndexError: list index out of range'}]","markdown.markdown('<>') +Traceback (most recent call last): +File """", line 1, in +File ""/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/__init__.py"", line 386, in markdown +return md.convert(text) +File ""/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/__init__.py"", line 280, in convert +self.lines = prep.run(self.lines) +File ""/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/preprocessors.py"", line 146, in run +left_tag, left_index, attrs = self._get_left_tag(block) +File ""/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/preprocessors.py"", line 81, in _get_left_tag +tag = block[1:].replace("">"", "" "", 1).split()[0].lower() +IndexError: list index out of range",IndexError +"def sort_imports( + file_name: str, + config: Config, + check: bool = False, + ask_to_apply: bool = False, + write_to_stdout: bool = False, + **kwargs: Any, +) -> Optional[SortAttempt]: + incorrectly_sorted: bool = False + skipped: bool = False + try: + if check: + try: + incorrectly_sorted = not api.check_file(file_name, config=config, **kwargs) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped, True) + + try: + incorrectly_sorted = not api.sort_file( + file_name, + config=config, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + **kwargs, + ) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped, True) + except (OSError, ValueError) as error: + warn(f""Unable to parse file {file_name} due to {error}"") + return None + except UnsupportedEncoding: + if config.verbose: + warn(f""Encoding not supported for {file_name}"") + return SortAttempt(incorrectly_sorted, skipped, False) + except KeyError as error: + if error.args[0] not in DEFAULT_CONFIG.sections: + _print_hard_fail(config, offending_file=file_name) + raise + msg = ( + f""Found {error} imports while parsing, but {error} was not included "" + ""in the `sections` setting of your config. Please add it before continuing\\n"" + ""See https://pycqa.github.io/isort/#custom-sections-and-ordering "" + ""for more info."" + ) + _print_hard_fail(config, message=msg) + sys.exit(os.EX_CONFIG) + except Exception: + _print_hard_fail(config, offending_file=file_name) + raise","def sort_imports( + file_name: str, + config: Config, + check: bool = False, + ask_to_apply: bool = False, + write_to_stdout: bool = False, + **kwargs: Any, +) -> Optional[SortAttempt]: + incorrectly_sorted: bool = False + skipped: bool = False + try: + if check: + try: + incorrectly_sorted = not api.check_file(file_name, config=config, **kwargs) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped, True) + + try: + incorrectly_sorted = not api.sort_file( + file_name, + config=config, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + **kwargs, + ) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped, True) + except (OSError, ValueError) as error: + warn(f""Unable to parse file {file_name} due to {error}"") + return None + except UnsupportedEncoding: + if config.verbose: + warn(f""Encoding not supported for {file_name}"") + return SortAttempt(incorrectly_sorted, skipped, False) + except Exception: + printer = create_terminal_printer(color=config.color_output) + printer.error( + f""Unrecoverable exception thrown when parsing {file_name}! "" + ""This should NEVER happen.\\n"" + ""If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new"" + ) + raise","[{'piece_type': 'error message', 'piece_content': 'ERROR: Unrecoverable exception thrown when parsing src/eduid_webapp/eidas/app.py! This should NEVER happen.\\nIf encountered, please open an issue: https://github.com/PyCQA/isort/issues/new\\nTraceback (most recent call last):\\nFile ""/home/lundberg/python-environments/eduid-webapp/bin/isort"", line 8, in \\nsys.exit(main())\\nFile ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/main.py"", line 953, in main\\nfor sort_attempt in attempt_iterator:\\nFile ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/main.py"", line 939, in \\nsort_imports( # type: ignore\\nFile ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/main.py"", line 95, in sort_imports\\nincorrectly_sorted = not api.sort_file(\\nFile ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/api.py"", line 324, in sort_file\\nchanged = sort_stream(\\nFile ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/api.py"", line 158, in sort_stream\\nchanged = core.process(\\nFile ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/core.py"", line 332, in process\\nparsed_content = parse.file_contents(import_section, config=config)\\nFile ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/parse.py"", line 432, in file_contents\\nroot = imports[placed_module][type_of_import] # type: ignore\\nKeyError: \\'LOCALFOLDER\\''}]","ERROR: Unrecoverable exception thrown when parsing src/eduid_webapp/eidas/app.py! This should NEVER happen. +If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new +Traceback (most recent call last): +File ""/home/lundberg/python-environments/eduid-webapp/bin/isort"", line 8, in +sys.exit(main()) +File ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/main.py"", line 953, in main +for sort_attempt in attempt_iterator: +File ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/main.py"", line 939, in +sort_imports( # type: ignore +File ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/main.py"", line 95, in sort_imports +incorrectly_sorted = not api.sort_file( +File ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/api.py"", line 324, in sort_file +changed = sort_stream( +File ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/api.py"", line 158, in sort_stream +changed = core.process( +File ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/core.py"", line 332, in process +parsed_content = parse.file_contents(import_section, config=config) +File ""/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/parse.py"", line 432, in file_contents +root = imports[placed_module][type_of_import] # type: ignore +KeyError: 'LOCALFOLDER'",KeyError +" def __init__( + self, + filename: Union[str, Path], + ): + super().__init__(f""Unknown or unsupported encoding in {filename}"") + self.filename = filename"," def __init__(self, unsupported_settings: Dict[str, Dict[str, str]]): + errors = ""\\n"".join( + self._format_option(name, **option) for name, option in unsupported_settings.items() + ) + + super().__init__( + ""isort was provided settings that it doesn't support:\\n\\n"" + f""{errors}\\n\\n"" + ""For a complete and up-to-date listing of supported settings see: "" + ""https://pycqa.github.io/isort/docs/configuration/options/.\\n"" + ) + self.unsupported_settings = unsupported_settings","[{'piece_type': 'error message', 'piece_content': 'ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.\\nIf encountered, please open an issue: https://github.com/PyCQA/isort/issues/new\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie\\ncodec = lookup(encoding)\\nLookupError: unknown encoding: IBO-8859-1\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in \\nsys.exit(main())\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main\\nfor sort_attempt in attempt_iterator:\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in \\nsort_imports( # type: ignore\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports\\nincorrectly_sorted = not api.sort_file(\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file\\nwith io.File.read(filename) as source_file:\\nFile ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__\\nreturn next(self.gen)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read\\nstream = File._open(file_path)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open\\nencoding, _ = tokenize.detect_encoding(buffer.readline)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding\\nencoding = find_cookie(second)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie\\nraise SyntaxError(msg)\\nSyntaxError: unknown encoding for \\'/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py\\': IBO-8859-1'}]","ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen. +If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new +Traceback (most recent call last): +File ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie +codec = lookup(encoding) +LookupError: unknown encoding: IBO-8859-1 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in +sys.exit(main()) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main +for sort_attempt in attempt_iterator: +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in +sort_imports( # type: ignore +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports +incorrectly_sorted = not api.sort_file( +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file +with io.File.read(filename) as source_file: +File ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__ +return next(self.gen) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read +stream = File._open(file_path) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open +encoding, _ = tokenize.detect_encoding(buffer.readline) +File ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding +encoding = find_cookie(second) +File ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie +raise SyntaxError(msg) +SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1",LookupError +" def from_contents(contents: str, filename: str) -> ""File"": + encoding = File.detect_encoding(filename, BytesIO(contents.encode(""utf-8"")).readline) + return File(StringIO(contents), path=Path(filename).resolve(), encoding=encoding)"," def from_contents(contents: str, filename: str) -> ""File"": + encoding, _ = tokenize.detect_encoding(BytesIO(contents.encode(""utf-8"")).readline) + return File(StringIO(contents), path=Path(filename).resolve(), encoding=encoding)","[{'piece_type': 'error message', 'piece_content': 'ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.\\nIf encountered, please open an issue: https://github.com/PyCQA/isort/issues/new\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie\\ncodec = lookup(encoding)\\nLookupError: unknown encoding: IBO-8859-1\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in \\nsys.exit(main())\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main\\nfor sort_attempt in attempt_iterator:\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in \\nsort_imports( # type: ignore\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports\\nincorrectly_sorted = not api.sort_file(\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file\\nwith io.File.read(filename) as source_file:\\nFile ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__\\nreturn next(self.gen)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read\\nstream = File._open(file_path)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open\\nencoding, _ = tokenize.detect_encoding(buffer.readline)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding\\nencoding = find_cookie(second)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie\\nraise SyntaxError(msg)\\nSyntaxError: unknown encoding for \\'/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py\\': IBO-8859-1'}]","ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen. +If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new +Traceback (most recent call last): +File ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie +codec = lookup(encoding) +LookupError: unknown encoding: IBO-8859-1 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in +sys.exit(main()) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main +for sort_attempt in attempt_iterator: +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in +sort_imports( # type: ignore +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports +incorrectly_sorted = not api.sort_file( +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file +with io.File.read(filename) as source_file: +File ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__ +return next(self.gen) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read +stream = File._open(file_path) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open +encoding, _ = tokenize.detect_encoding(buffer.readline) +File ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding +encoding = find_cookie(second) +File ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie +raise SyntaxError(msg) +SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1",LookupError +" def _open(filename): + """"""Open a file in read only mode using the encoding detected by + detect_encoding(). + """""" + buffer = open(filename, ""rb"") + try: + encoding = File.detect_encoding(filename, buffer.readline) + buffer.seek(0) + text = TextIOWrapper(buffer, encoding, line_buffering=True, newline="""") + text.mode = ""r"" # type: ignore + return text + except Exception: + buffer.close() + raise"," def _open(filename): + """"""Open a file in read only mode using the encoding detected by + detect_encoding(). + """""" + buffer = open(filename, ""rb"") + try: + encoding, _ = tokenize.detect_encoding(buffer.readline) + buffer.seek(0) + text = TextIOWrapper(buffer, encoding, line_buffering=True, newline="""") + text.mode = ""r"" # type: ignore + return text + except Exception: + buffer.close() + raise","[{'piece_type': 'error message', 'piece_content': 'ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.\\nIf encountered, please open an issue: https://github.com/PyCQA/isort/issues/new\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie\\ncodec = lookup(encoding)\\nLookupError: unknown encoding: IBO-8859-1\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in \\nsys.exit(main())\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main\\nfor sort_attempt in attempt_iterator:\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in \\nsort_imports( # type: ignore\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports\\nincorrectly_sorted = not api.sort_file(\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file\\nwith io.File.read(filename) as source_file:\\nFile ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__\\nreturn next(self.gen)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read\\nstream = File._open(file_path)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open\\nencoding, _ = tokenize.detect_encoding(buffer.readline)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding\\nencoding = find_cookie(second)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie\\nraise SyntaxError(msg)\\nSyntaxError: unknown encoding for \\'/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py\\': IBO-8859-1'}]","ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen. +If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new +Traceback (most recent call last): +File ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie +codec = lookup(encoding) +LookupError: unknown encoding: IBO-8859-1 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in +sys.exit(main()) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main +for sort_attempt in attempt_iterator: +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in +sort_imports( # type: ignore +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports +incorrectly_sorted = not api.sort_file( +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file +with io.File.read(filename) as source_file: +File ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__ +return next(self.gen) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read +stream = File._open(file_path) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open +encoding, _ = tokenize.detect_encoding(buffer.readline) +File ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding +encoding = find_cookie(second) +File ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie +raise SyntaxError(msg) +SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1",LookupError +" def __init__(self, incorrectly_sorted: bool, skipped: bool, supported_encoding: bool) -> None: + self.incorrectly_sorted = incorrectly_sorted + self.skipped = skipped + self.supported_encoding = supported_encoding"," def __init__(self, incorrectly_sorted: bool, skipped: bool) -> None: + self.incorrectly_sorted = incorrectly_sorted + self.skipped = skipped","[{'piece_type': 'error message', 'piece_content': 'ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.\\nIf encountered, please open an issue: https://github.com/PyCQA/isort/issues/new\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie\\ncodec = lookup(encoding)\\nLookupError: unknown encoding: IBO-8859-1\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in \\nsys.exit(main())\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main\\nfor sort_attempt in attempt_iterator:\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in \\nsort_imports( # type: ignore\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports\\nincorrectly_sorted = not api.sort_file(\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file\\nwith io.File.read(filename) as source_file:\\nFile ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__\\nreturn next(self.gen)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read\\nstream = File._open(file_path)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open\\nencoding, _ = tokenize.detect_encoding(buffer.readline)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding\\nencoding = find_cookie(second)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie\\nraise SyntaxError(msg)\\nSyntaxError: unknown encoding for \\'/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py\\': IBO-8859-1'}]","ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen. +If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new +Traceback (most recent call last): +File ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie +codec = lookup(encoding) +LookupError: unknown encoding: IBO-8859-1 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in +sys.exit(main()) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main +for sort_attempt in attempt_iterator: +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in +sort_imports( # type: ignore +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports +incorrectly_sorted = not api.sort_file( +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file +with io.File.read(filename) as source_file: +File ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__ +return next(self.gen) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read +stream = File._open(file_path) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open +encoding, _ = tokenize.detect_encoding(buffer.readline) +File ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding +encoding = find_cookie(second) +File ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie +raise SyntaxError(msg) +SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1",LookupError +"def sort_imports( + file_name: str, + config: Config, + check: bool = False, + ask_to_apply: bool = False, + write_to_stdout: bool = False, + **kwargs: Any, +) -> Optional[SortAttempt]: + try: + incorrectly_sorted: bool = False + skipped: bool = False + if check: + try: + incorrectly_sorted = not api.check_file(file_name, config=config, **kwargs) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped, True) + else: + try: + incorrectly_sorted = not api.sort_file( + file_name, + config=config, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + **kwargs, + ) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped, True) + except (OSError, ValueError) as error: + warn(f""Unable to parse file {file_name} due to {error}"") + return None + except UnsupportedEncoding: + if config.verbose: + warn(f""Encoding not supported for {file_name}"") + return SortAttempt(incorrectly_sorted, skipped, False) + except Exception: + printer = create_terminal_printer(color=config.color_output) + printer.error( + f""Unrecoverable exception thrown when parsing {file_name}! "" + ""This should NEVER happen.\\n"" + ""If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new"" + ) + raise","def sort_imports( + file_name: str, + config: Config, + check: bool = False, + ask_to_apply: bool = False, + write_to_stdout: bool = False, + **kwargs: Any, +) -> Optional[SortAttempt]: + try: + incorrectly_sorted: bool = False + skipped: bool = False + if check: + try: + incorrectly_sorted = not api.check_file(file_name, config=config, **kwargs) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped) + else: + try: + incorrectly_sorted = not api.sort_file( + file_name, + config=config, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + **kwargs, + ) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped) + except (OSError, ValueError) as error: + warn(f""Unable to parse file {file_name} due to {error}"") + return None + except Exception: + printer = create_terminal_printer(color=config.color_output) + printer.error( + f""Unrecoverable exception thrown when parsing {file_name}! "" + ""This should NEVER happen.\\n"" + ""If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new"" + ) + raise","[{'piece_type': 'error message', 'piece_content': 'ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.\\nIf encountered, please open an issue: https://github.com/PyCQA/isort/issues/new\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie\\ncodec = lookup(encoding)\\nLookupError: unknown encoding: IBO-8859-1\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in \\nsys.exit(main())\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main\\nfor sort_attempt in attempt_iterator:\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in \\nsort_imports( # type: ignore\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports\\nincorrectly_sorted = not api.sort_file(\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file\\nwith io.File.read(filename) as source_file:\\nFile ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__\\nreturn next(self.gen)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read\\nstream = File._open(file_path)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open\\nencoding, _ = tokenize.detect_encoding(buffer.readline)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding\\nencoding = find_cookie(second)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie\\nraise SyntaxError(msg)\\nSyntaxError: unknown encoding for \\'/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py\\': IBO-8859-1'}]","ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen. +If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new +Traceback (most recent call last): +File ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie +codec = lookup(encoding) +LookupError: unknown encoding: IBO-8859-1 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in +sys.exit(main()) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main +for sort_attempt in attempt_iterator: +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in +sort_imports( # type: ignore +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports +incorrectly_sorted = not api.sort_file( +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file +with io.File.read(filename) as source_file: +File ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__ +return next(self.gen) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read +stream = File._open(file_path) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open +encoding, _ = tokenize.detect_encoding(buffer.readline) +File ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding +encoding = find_cookie(second) +File ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie +raise SyntaxError(msg) +SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1",LookupError +"def main(argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None) -> None: + arguments = parse_args(argv) + if arguments.get(""show_version""): + print(ASCII_ART) + return + + show_config: bool = arguments.pop(""show_config"", False) + show_files: bool = arguments.pop(""show_files"", False) + if show_config and show_files: + sys.exit(""Error: either specify show-config or show-files not both."") + + if ""settings_path"" in arguments: + if os.path.isfile(arguments[""settings_path""]): + arguments[""settings_file""] = os.path.abspath(arguments[""settings_path""]) + arguments[""settings_path""] = os.path.dirname(arguments[""settings_file""]) + else: + arguments[""settings_path""] = os.path.abspath(arguments[""settings_path""]) + + if ""virtual_env"" in arguments: + venv = arguments[""virtual_env""] + arguments[""virtual_env""] = os.path.abspath(venv) + if not os.path.isdir(arguments[""virtual_env""]): + warn(f""virtual_env dir does not exist: {arguments['virtual_env']}"") + + file_names = arguments.pop(""files"", []) + if not file_names and not show_config: + print(QUICK_GUIDE) + if arguments: + sys.exit(""Error: arguments passed in without any paths or content."") + else: + return + if ""settings_path"" not in arguments: + arguments[""settings_path""] = ( + os.path.abspath(file_names[0] if file_names else ""."") or os.getcwd() + ) + if not os.path.isdir(arguments[""settings_path""]): + arguments[""settings_path""] = os.path.dirname(arguments[""settings_path""]) + + config_dict = arguments.copy() + ask_to_apply = config_dict.pop(""ask_to_apply"", False) + jobs = config_dict.pop(""jobs"", ()) + check = config_dict.pop(""check"", False) + show_diff = config_dict.pop(""show_diff"", False) + write_to_stdout = config_dict.pop(""write_to_stdout"", False) + deprecated_flags = config_dict.pop(""deprecated_flags"", False) + remapped_deprecated_args = config_dict.pop(""remapped_deprecated_args"", False) + wrong_sorted_files = False + all_attempt_broken = False + no_valid_encodings = False + + if ""src_paths"" in config_dict: + config_dict[""src_paths""] = { + Path(src_path).resolve() for src_path in config_dict.get(""src_paths"", ()) + } + + config = Config(**config_dict) + if show_config: + print(json.dumps(config.__dict__, indent=4, separators=("","", "": ""), default=_preconvert)) + return + elif file_names == [""-""]: + if show_files: + sys.exit(""Error: can't show files for streaming input."") + + if check: + incorrectly_sorted = not api.check_stream( + input_stream=sys.stdin if stdin is None else stdin, + config=config, + show_diff=show_diff, + ) + + wrong_sorted_files = incorrectly_sorted + else: + api.sort_stream( + input_stream=sys.stdin if stdin is None else stdin, + output_stream=sys.stdout, + config=config, + show_diff=show_diff, + ) + else: + skipped: List[str] = [] + broken: List[str] = [] + + if config.filter_files: + filtered_files = [] + for file_name in file_names: + if config.is_skipped(Path(file_name)): + skipped.append(file_name) + else: + filtered_files.append(file_name) + file_names = filtered_files + + file_names = iter_source_code(file_names, config, skipped, broken) + if show_files: + for file_name in file_names: + print(file_name) + return + num_skipped = 0 + num_broken = 0 + num_invalid_encoding = 0 + if config.verbose: + print(ASCII_ART) + + if jobs: + import multiprocessing + + executor = multiprocessing.Pool(jobs) + attempt_iterator = executor.imap( + functools.partial( + sort_imports, + config=config, + check=check, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + ), + file_names, + ) + else: + # https://github.com/python/typeshed/pull/2814 + attempt_iterator = ( + sort_imports( # type: ignore + file_name, + config=config, + check=check, + ask_to_apply=ask_to_apply, + show_diff=show_diff, + write_to_stdout=write_to_stdout, + ) + for file_name in file_names + ) + + # If any files passed in are missing considered as error, should be removed + is_no_attempt = True + any_encoding_valid = False + for sort_attempt in attempt_iterator: + if not sort_attempt: + continue # pragma: no cover - shouldn't happen, satisfies type constraint + incorrectly_sorted = sort_attempt.incorrectly_sorted + if arguments.get(""check"", False) and incorrectly_sorted: + wrong_sorted_files = True + if sort_attempt.skipped: + num_skipped += ( + 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code + ) + + if not sort_attempt.supported_encoding: + num_invalid_encoding += 1 + else: + any_encoding_valid = True + + is_no_attempt = False + + num_skipped += len(skipped) + if num_skipped and not arguments.get(""quiet"", False): + if config.verbose: + for was_skipped in skipped: + warn( + f""{was_skipped} was skipped as it's listed in 'skip' setting"" + "" or matches a glob in 'skip_glob' setting"" + ) + print(f""Skipped {num_skipped} files"") + + num_broken += len(broken) + if num_broken and not arguments.get(""quite"", False): + if config.verbose: + for was_broken in broken: + warn(f""{was_broken} was broken path, make sure it exists correctly"") + print(f""Broken {num_broken} paths"") + + if num_broken > 0 and is_no_attempt: + all_attempt_broken = True + if num_invalid_encoding > 0 and not any_encoding_valid: + no_valid_encodings = True + + if not config.quiet and (remapped_deprecated_args or deprecated_flags): + if remapped_deprecated_args: + warn( + ""W0502: The following deprecated single dash CLI flags were used and translated: "" + f""{', '.join(remapped_deprecated_args)}!"" + ) + if deprecated_flags: + warn( + ""W0501: The following deprecated CLI flags were used and ignored: "" + f""{', '.join(deprecated_flags)}!"" + ) + warn( + ""W0500: Please see the 5.0.0 Upgrade guide: "" + ""https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0/"" + ) + + if wrong_sorted_files: + sys.exit(1) + + if all_attempt_broken: + sys.exit(1) + + if no_valid_encodings: + printer = create_terminal_printer(color=config.color_output) + printer.error(""No valid encodings."") + sys.exit(1)","def main(argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None) -> None: + arguments = parse_args(argv) + if arguments.get(""show_version""): + print(ASCII_ART) + return + + show_config: bool = arguments.pop(""show_config"", False) + show_files: bool = arguments.pop(""show_files"", False) + if show_config and show_files: + sys.exit(""Error: either specify show-config or show-files not both."") + + if ""settings_path"" in arguments: + if os.path.isfile(arguments[""settings_path""]): + arguments[""settings_file""] = os.path.abspath(arguments[""settings_path""]) + arguments[""settings_path""] = os.path.dirname(arguments[""settings_file""]) + else: + arguments[""settings_path""] = os.path.abspath(arguments[""settings_path""]) + + if ""virtual_env"" in arguments: + venv = arguments[""virtual_env""] + arguments[""virtual_env""] = os.path.abspath(venv) + if not os.path.isdir(arguments[""virtual_env""]): + warn(f""virtual_env dir does not exist: {arguments['virtual_env']}"") + + file_names = arguments.pop(""files"", []) + if not file_names and not show_config: + print(QUICK_GUIDE) + if arguments: + sys.exit(""Error: arguments passed in without any paths or content."") + else: + return + if ""settings_path"" not in arguments: + arguments[""settings_path""] = ( + os.path.abspath(file_names[0] if file_names else ""."") or os.getcwd() + ) + if not os.path.isdir(arguments[""settings_path""]): + arguments[""settings_path""] = os.path.dirname(arguments[""settings_path""]) + + config_dict = arguments.copy() + ask_to_apply = config_dict.pop(""ask_to_apply"", False) + jobs = config_dict.pop(""jobs"", ()) + check = config_dict.pop(""check"", False) + show_diff = config_dict.pop(""show_diff"", False) + write_to_stdout = config_dict.pop(""write_to_stdout"", False) + deprecated_flags = config_dict.pop(""deprecated_flags"", False) + remapped_deprecated_args = config_dict.pop(""remapped_deprecated_args"", False) + wrong_sorted_files = False + all_attempt_broken = False + + if ""src_paths"" in config_dict: + config_dict[""src_paths""] = { + Path(src_path).resolve() for src_path in config_dict.get(""src_paths"", ()) + } + + config = Config(**config_dict) + if show_config: + print(json.dumps(config.__dict__, indent=4, separators=("","", "": ""), default=_preconvert)) + return + elif file_names == [""-""]: + if show_files: + sys.exit(""Error: can't show files for streaming input."") + + if check: + incorrectly_sorted = not api.check_stream( + input_stream=sys.stdin if stdin is None else stdin, + config=config, + show_diff=show_diff, + ) + + wrong_sorted_files = incorrectly_sorted + else: + api.sort_stream( + input_stream=sys.stdin if stdin is None else stdin, + output_stream=sys.stdout, + config=config, + show_diff=show_diff, + ) + else: + skipped: List[str] = [] + broken: List[str] = [] + + if config.filter_files: + filtered_files = [] + for file_name in file_names: + if config.is_skipped(Path(file_name)): + skipped.append(file_name) + else: + filtered_files.append(file_name) + file_names = filtered_files + + file_names = iter_source_code(file_names, config, skipped, broken) + if show_files: + for file_name in file_names: + print(file_name) + return + num_skipped = 0 + num_broken = 0 + if config.verbose: + print(ASCII_ART) + + if jobs: + import multiprocessing + + executor = multiprocessing.Pool(jobs) + attempt_iterator = executor.imap( + functools.partial( + sort_imports, + config=config, + check=check, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + ), + file_names, + ) + else: + # https://github.com/python/typeshed/pull/2814 + attempt_iterator = ( + sort_imports( # type: ignore + file_name, + config=config, + check=check, + ask_to_apply=ask_to_apply, + show_diff=show_diff, + write_to_stdout=write_to_stdout, + ) + for file_name in file_names + ) + + # If any files passed in are missing considered as error, should be removed + is_no_attempt = True + for sort_attempt in attempt_iterator: + if not sort_attempt: + continue # pragma: no cover - shouldn't happen, satisfies type constraint + incorrectly_sorted = sort_attempt.incorrectly_sorted + if arguments.get(""check"", False) and incorrectly_sorted: + wrong_sorted_files = True + if sort_attempt.skipped: + num_skipped += ( + 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code + ) + is_no_attempt = False + + num_skipped += len(skipped) + if num_skipped and not arguments.get(""quiet"", False): + if config.verbose: + for was_skipped in skipped: + warn( + f""{was_skipped} was skipped as it's listed in 'skip' setting"" + "" or matches a glob in 'skip_glob' setting"" + ) + print(f""Skipped {num_skipped} files"") + + num_broken += len(broken) + if num_broken and not arguments.get(""quite"", False): + if config.verbose: + for was_broken in broken: + warn(f""{was_broken} was broken path, make sure it exists correctly"") + print(f""Broken {num_broken} paths"") + + if num_broken > 0 and is_no_attempt: + all_attempt_broken = True + + if not config.quiet and (remapped_deprecated_args or deprecated_flags): + if remapped_deprecated_args: + warn( + ""W0502: The following deprecated single dash CLI flags were used and translated: "" + f""{', '.join(remapped_deprecated_args)}!"" + ) + if deprecated_flags: + warn( + ""W0501: The following deprecated CLI flags were used and ignored: "" + f""{', '.join(deprecated_flags)}!"" + ) + warn( + ""W0500: Please see the 5.0.0 Upgrade guide: "" + ""https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0/"" + ) + + if wrong_sorted_files: + sys.exit(1) + + if all_attempt_broken: + sys.exit(1)","[{'piece_type': 'error message', 'piece_content': 'ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.\\nIf encountered, please open an issue: https://github.com/PyCQA/isort/issues/new\\nTraceback (most recent call last):\\nFile ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie\\ncodec = lookup(encoding)\\nLookupError: unknown encoding: IBO-8859-1\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in \\nsys.exit(main())\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main\\nfor sort_attempt in attempt_iterator:\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in \\nsort_imports( # type: ignore\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports\\nincorrectly_sorted = not api.sort_file(\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file\\nwith io.File.read(filename) as source_file:\\nFile ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__\\nreturn next(self.gen)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read\\nstream = File._open(file_path)\\nFile ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open\\nencoding, _ = tokenize.detect_encoding(buffer.readline)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding\\nencoding = find_cookie(second)\\nFile ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie\\nraise SyntaxError(msg)\\nSyntaxError: unknown encoding for \\'/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py\\': IBO-8859-1'}]","ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen. +If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new +Traceback (most recent call last): +File ""/usr/lib/python3.8/tokenize.py"", line 342, in find_cookie +codec = lookup(encoding) +LookupError: unknown encoding: IBO-8859-1 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort"", line 8, in +sys.exit(main()) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 886, in main +for sort_attempt in attempt_iterator: +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 875, in +sort_imports( # type: ignore +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py"", line 94, in sort_imports +incorrectly_sorted = not api.sort_file( +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py"", line 300, in sort_file +with io.File.read(filename) as source_file: +File ""/usr/lib/python3.8/contextlib.py"", line 113, in __enter__ +return next(self.gen) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 48, in read +stream = File._open(file_path) +File ""/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py"", line 33, in _open +encoding, _ = tokenize.detect_encoding(buffer.readline) +File ""/usr/lib/python3.8/tokenize.py"", line 381, in detect_encoding +encoding = find_cookie(second) +File ""/usr/lib/python3.8/tokenize.py"", line 350, in find_cookie +raise SyntaxError(msg) +SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1",LookupError +"def _known_pattern(name: str, config: Config) -> Optional[Tuple[str, str]]: + parts = name.split(""."") + module_names_to_check = (""."".join(parts[:first_k]) for first_k in range(len(parts), 0, -1)) + for module_name_to_check in module_names_to_check: + for pattern, placement in config.known_patterns: + if placement in config.sections and pattern.match(module_name_to_check): + return (placement, f""Matched configured known pattern {pattern}"") + + return None","def _known_pattern(name: str, config: Config) -> Optional[Tuple[str, str]]: + parts = name.split(""."") + module_names_to_check = (""."".join(parts[:first_k]) for first_k in range(len(parts), 0, -1)) + for module_name_to_check in module_names_to_check: + for pattern, placement in config.known_patterns: + if pattern.match(module_name_to_check): + return (placement, f""Matched configured known pattern {pattern}"") + + return None","[{'piece_type': 'error message', 'piece_content': 'lint installed: appdirs==1.4.4,black==20.8b1,bleach==3.2.1,check-manifest==0.43,click==7.1.2,docutils==0.16,flake8==3.8.3,isort==5.5.3,mccabe==0.6.1,mypy-extensions==0.4.3,packaging==20.4,pathspec==0.8.0,pep517==0.8.2,pycodestyle==2.6.0,pyflakes==2.2.0,Pygments==2.7.1,pyparsing==2.4.7,readme-renderer==26.0,regex==2020.9.27,six==1.15.0,toml==0.10.1,typed-ast==1.4.1,typing-extensions==3.7.4.3,webencodings==0.5.1\\nlint run-test-pre: PYTHONHASHSEED=\\'979047687\\'\\nlint run-test: commands[0] | flake8 src/pyramid tests setup.py\\nlint run-test: commands[1] | isort --check-only --df src/pyramid tests setup.py\\nERROR: Unrecoverable exception thrown when parsing src/pyramid/predicates.py! This should NEVER happen.\\nIf encountered, please open an issue: https://github.com/PyCQA/isort/issues/new\\nTraceback (most recent call last):\\nFile ""/home/runner/work/pyramid/pyramid/.tox/lint/bin/isort"", line 8, in \\nsys.exit(main())\\nFile ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/main.py"", line 886, in main\\nfor sort_attempt in attempt_iterator:\\nFile ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/main.py"", line 875, in \\nsort_imports( # type: ignore\\nFile ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/main.py"", line 88, in sort_imports\\nincorrectly_sorted = not api.check_file(file_name, config=config, **kwargs)\\nFile ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/api.py"", line 264, in check_file\\nreturn check_stream(\\nFile ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/api.py"", line 203, in check_stream\\nchanged: bool = sort_stream(\\nFile ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/api.py"", line 158, in sort_stream\\nchanged = core.process(\\nFile ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/core.py"", line 326, in process\\nparse.file_contents(import_section, config=config),\\nFile ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/parse.py"", line 474, in file_contents\\nstraight_import |= imports[placed_module][type_of_import].get( # type: ignore\\nKeyError: \\'STDLIB\\'\\nERROR: InvocationError for command /home/runner/work/pyramid/pyramid/.tox/lint/bin/isort --check-only --df src/pyramid tests setup.py (exited with code 1)\\n___________________________________ summary ____________________________________\\nERROR: lint: commands failed\\nError: Process completed with exit code 1.'}]","lint installed: appdirs==1.4.4,black==20.8b1,bleach==3.2.1,check-manifest==0.43,click==7.1.2,docutils==0.16,flake8==3.8.3,isort==5.5.3,mccabe==0.6.1,mypy-extensions==0.4.3,packaging==20.4,pathspec==0.8.0,pep517==0.8.2,pycodestyle==2.6.0,pyflakes==2.2.0,Pygments==2.7.1,pyparsing==2.4.7,readme-renderer==26.0,regex==2020.9.27,six==1.15.0,toml==0.10.1,typed-ast==1.4.1,typing-extensions==3.7.4.3,webencodings==0.5.1 +lint run-test-pre: PYTHONHASHSEED='979047687' +lint run-test: commands[0] | flake8 src/pyramid tests setup.py +lint run-test: commands[1] | isort --check-only --df src/pyramid tests setup.py +ERROR: Unrecoverable exception thrown when parsing src/pyramid/predicates.py! This should NEVER happen. +If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new +Traceback (most recent call last): +File ""/home/runner/work/pyramid/pyramid/.tox/lint/bin/isort"", line 8, in +sys.exit(main()) +File ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/main.py"", line 886, in main +for sort_attempt in attempt_iterator: +File ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/main.py"", line 875, in +sort_imports( # type: ignore +File ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/main.py"", line 88, in sort_imports +incorrectly_sorted = not api.check_file(file_name, config=config, **kwargs) +File ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/api.py"", line 264, in check_file +return check_stream( +File ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/api.py"", line 203, in check_stream +changed: bool = sort_stream( +File ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/api.py"", line 158, in sort_stream +changed = core.process( +File ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/core.py"", line 326, in process +parse.file_contents(import_section, config=config), +File ""/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/parse.py"", line 474, in file_contents +straight_import |= imports[placed_module][type_of_import].get( # type: ignore +KeyError: 'STDLIB' +ERROR: InvocationError for command /home/runner/work/pyramid/pyramid/.tox/lint/bin/isort --check-only --df src/pyramid tests setup.py (exited with code 1) +___________________________________ summary ____________________________________ +ERROR: lint: commands failed +Error: Process completed with exit code 1.",KeyError +"def process( + input_stream: TextIO, + output_stream: TextIO, + extension: str = ""py"", + config: Config = DEFAULT_CONFIG, +) -> bool: + """"""Parses stream identifying sections of contiguous imports and sorting them + + Code with unsorted imports is read from the provided `input_stream`, sorted and then + outputted to the specified `output_stream`. + + - `input_stream`: Text stream with unsorted import sections. + - `output_stream`: Text stream to output sorted inputs into. + - `config`: Config settings to use when sorting imports. Defaults settings. + - *Default*: `isort.settings.DEFAULT_CONFIG`. + - `extension`: The file extension or file extension rules that should be used. + - *Default*: `""py""`. + - *Choices*: `[""py"", ""pyi"", ""pyx""]`. + + Returns `True` if there were changes that needed to be made (errors present) from what + was provided in the input_stream, otherwise `False`. + """""" + line_separator: str = config.line_ending + add_imports: List[str] = [format_natural(addition) for addition in config.add_imports] + import_section: str = """" + next_import_section: str = """" + next_cimports: bool = False + in_quote: str = """" + first_comment_index_start: int = -1 + first_comment_index_end: int = -1 + contains_imports: bool = False + in_top_comment: bool = False + first_import_section: bool = True + section_comments = [f""# {heading}"" for heading in config.import_headings.values()] + indent: str = """" + isort_off: bool = False + code_sorting: Union[bool, str] = False + code_sorting_section: str = """" + code_sorting_indent: str = """" + cimports: bool = False + made_changes: bool = False + stripped_line: str = """" + end_of_file: bool = False + + if config.float_to_top: + new_input = """" + current = """" + isort_off = False + for line in chain(input_stream, (None,)): + if isort_off and line is not None: + if line == ""# isort: on\\n"": + isort_off = False + new_input += line + elif line in (""# isort: split\\n"", ""# isort: off\\n"", None) or str(line).endswith( + ""# isort: split\\n"" + ): + if line == ""# isort: off\\n"": + isort_off = True + if current: + parsed = parse.file_contents(current, config=config) + extra_space = """" + while current and current[-1] == ""\\n"": + extra_space += ""\\n"" + current = current[:-1] + extra_space = extra_space.replace(""\\n"", """", 1) + sorted_output = output.sorted_imports( + parsed, config, extension, import_type=""import"" + ) + made_changes = made_changes or _has_changed( + before=current, + after=sorted_output, + line_separator=parsed.line_separator, + ignore_whitespace=config.ignore_whitespace, + ) + new_input += sorted_output + new_input += extra_space + current = """" + new_input += line or """" + else: + current += line or """" + + input_stream = StringIO(new_input) + + for index, line in enumerate(chain(input_stream, (None,))): + if line is None: + if index == 0 and not config.force_adds: + return False + + not_imports = True + end_of_file = True + line = """" + if not line_separator: + line_separator = ""\\n"" + + if code_sorting and code_sorting_section: + output_stream.write( + textwrap.indent( + isort.literal.assignment( + code_sorting_section, + str(code_sorting), + extension, + config=_indented_config(config, indent), + ), + code_sorting_indent, + ) + ) + else: + stripped_line = line.strip() + if stripped_line and not line_separator: + line_separator = line[len(line.rstrip()) :].replace("" "", """").replace(""\\t"", """") + + for file_skip_comment in FILE_SKIP_COMMENTS: + if file_skip_comment in line: + raise FileSkipComment(""Passed in content"") + + if not in_quote and stripped_line == ""# isort: off"": + isort_off = True + + if ( + (index == 0 or (index in (1, 2) and not contains_imports)) + and stripped_line.startswith(""#"") + and stripped_line not in section_comments + ): + in_top_comment = True + elif in_top_comment: + if not line.startswith(""#"") or stripped_line in section_comments: + in_top_comment = False + first_comment_index_end = index - 1 + + if (not stripped_line.startswith(""#"") or in_quote) and '""' in line or ""'"" in line: + char_index = 0 + if first_comment_index_start == -1 and ( + line.startswith('""') or line.startswith(""'"") + ): + first_comment_index_start = index + while char_index < len(line): + if line[char_index] == ""\\\\"": + char_index += 1 + elif in_quote: + if line[char_index : char_index + len(in_quote)] == in_quote: + in_quote = """" + if first_comment_index_end < first_comment_index_start: + first_comment_index_end = index + elif line[char_index] in (""'"", '""'): + long_quote = line[char_index : char_index + 3] + if long_quote in ('""""""', ""'''""): + in_quote = long_quote + char_index += 2 + else: + in_quote = line[char_index] + elif line[char_index] == ""#"": + break + char_index += 1 + + not_imports = bool(in_quote) or in_top_comment or isort_off + if not (in_quote or in_top_comment): + if isort_off: + if stripped_line == ""# isort: on"": + isort_off = False + elif stripped_line.endswith(""# isort: split""): + not_imports = True + elif stripped_line in CODE_SORT_COMMENTS: + code_sorting = stripped_line.split(""isort: "")[1].strip() + code_sorting_indent = line[: -len(line.lstrip())] + not_imports = True + elif code_sorting: + if not stripped_line: + output_stream.write( + textwrap.indent( + isort.literal.assignment( + code_sorting_section, + str(code_sorting), + extension, + config=_indented_config(config, indent), + ), + code_sorting_indent, + ) + ) + not_imports = True + code_sorting = False + code_sorting_section = """" + code_sorting_indent = """" + else: + code_sorting_section += line + line = """" + elif stripped_line in config.section_comments and not import_section: + import_section += line + indent = line[: -len(line.lstrip())] + elif not (stripped_line or contains_imports): + not_imports = True + elif ( + not stripped_line + or stripped_line.startswith(""#"") + and (not indent or indent + line.lstrip() == line) + and not config.treat_all_comments_as_code + and stripped_line not in config.treat_comments_as_code + ): + import_section += line + elif stripped_line.startswith(IMPORT_START_IDENTIFIERS): + contains_imports = True + + new_indent = line[: -len(line.lstrip())] + import_statement = line + stripped_line = line.strip().split(""#"")[0] + while stripped_line.endswith(""\\\\"") or ( + ""("" in stripped_line and "")"" not in stripped_line + ): + if stripped_line.endswith(""\\\\""): + while stripped_line and stripped_line.endswith(""\\\\""): + line = input_stream.readline() + stripped_line = line.strip().split(""#"")[0] + import_statement += line + else: + while "")"" not in stripped_line: + line = input_stream.readline() + stripped_line = line.strip().split(""#"")[0] + import_statement += line + + cimport_statement: bool = False + if ( + import_statement.lstrip().startswith(CIMPORT_IDENTIFIERS) + or "" cimport "" in import_statement + or "" cimport*"" in import_statement + or "" cimport("" in import_statement + or "".cimport"" in import_statement + ): + cimport_statement = True + + if cimport_statement != cimports or (new_indent != indent and import_section): + if import_section: + next_cimports = cimport_statement + next_import_section = import_statement + import_statement = """" + not_imports = True + line = """" + else: + cimports = cimport_statement + + indent = new_indent + import_section += import_statement + else: + not_imports = True + + if not_imports: + raw_import_section: str = import_section + if ( + add_imports + and (stripped_line or end_of_file) + and not config.append_only + and not in_top_comment + and not in_quote + and not import_section + and not line.lstrip().startswith(COMMENT_INDICATORS) + ): + import_section = line_separator.join(add_imports) + line_separator + if end_of_file and index != 0: + output_stream.write(line_separator) + contains_imports = True + add_imports = [] + + if next_import_section and not import_section: # pragma: no cover + raw_import_section = import_section = next_import_section + next_import_section = """" + + if import_section: + if add_imports and not indent: + import_section = ( + line_separator.join(add_imports) + line_separator + import_section + ) + contains_imports = True + add_imports = [] + + if not indent: + import_section += line + raw_import_section += line + if not contains_imports: + output_stream.write(import_section) + else: + leading_whitespace = import_section[: -len(import_section.lstrip())] + trailing_whitespace = import_section[len(import_section.rstrip()) :] + if first_import_section and not import_section.lstrip( + line_separator + ).startswith(COMMENT_INDICATORS): + import_section = import_section.lstrip(line_separator) + raw_import_section = raw_import_section.lstrip(line_separator) + first_import_section = False + + if indent: + import_section = """".join( + line[len(indent) :] for line in import_section.splitlines(keepends=True) + ) + + sorted_import_section = output.sorted_imports( + parse.file_contents(import_section, config=config), + _indented_config(config, indent), + extension, + import_type=""cimport"" if cimports else ""import"", + ) + if not (import_section.strip() and not sorted_import_section): + if indent: + sorted_import_section = ( + leading_whitespace + + textwrap.indent(sorted_import_section, indent).strip() + + trailing_whitespace + ) + + made_changes = made_changes or _has_changed( + before=raw_import_section, + after=sorted_import_section, + line_separator=line_separator, + ignore_whitespace=config.ignore_whitespace, + ) + + output_stream.write(sorted_import_section) + if not line and not indent and next_import_section: + output_stream.write(line_separator) + + if indent: + output_stream.write(line) + if not next_import_section: + indent = """" + + if next_import_section: + cimports = next_cimports + contains_imports = True + else: + contains_imports = False + import_section = next_import_section + next_import_section = """" + else: + output_stream.write(line) + not_imports = False + + return made_changes","def process( + input_stream: TextIO, + output_stream: TextIO, + extension: str = ""py"", + config: Config = DEFAULT_CONFIG, +) -> bool: + """"""Parses stream identifying sections of contiguous imports and sorting them + + Code with unsorted imports is read from the provided `input_stream`, sorted and then + outputted to the specified `output_stream`. + + - `input_stream`: Text stream with unsorted import sections. + - `output_stream`: Text stream to output sorted inputs into. + - `config`: Config settings to use when sorting imports. Defaults settings. + - *Default*: `isort.settings.DEFAULT_CONFIG`. + - `extension`: The file extension or file extension rules that should be used. + - *Default*: `""py""`. + - *Choices*: `[""py"", ""pyi"", ""pyx""]`. + + Returns `True` if there were changes that needed to be made (errors present) from what + was provided in the input_stream, otherwise `False`. + """""" + line_separator: str = config.line_ending + add_imports: List[str] = [format_natural(addition) for addition in config.add_imports] + import_section: str = """" + next_import_section: str = """" + next_cimports: bool = False + in_quote: str = """" + first_comment_index_start: int = -1 + first_comment_index_end: int = -1 + contains_imports: bool = False + in_top_comment: bool = False + first_import_section: bool = True + section_comments = [f""# {heading}"" for heading in config.import_headings.values()] + indent: str = """" + isort_off: bool = False + code_sorting: Union[bool, str] = False + code_sorting_section: str = """" + code_sorting_indent: str = """" + cimports: bool = False + made_changes: bool = False + stripped_line: str = """" + end_of_file: bool = False + + if config.float_to_top: + new_input = """" + current = """" + isort_off = False + for line in chain(input_stream, (None,)): + if isort_off and line is not None: + if line == ""# isort: on\\n"": + isort_off = False + new_input += line + elif line in (""# isort: split\\n"", ""# isort: off\\n"", None) or str(line).endswith( + ""# isort: split\\n"" + ): + if line == ""# isort: off\\n"": + isort_off = True + if current: + parsed = parse.file_contents(current, config=config) + extra_space = """" + while current[-1] == ""\\n"": + extra_space += ""\\n"" + current = current[:-1] + extra_space = extra_space.replace(""\\n"", """", 1) + sorted_output = output.sorted_imports( + parsed, config, extension, import_type=""import"" + ) + made_changes = made_changes or _has_changed( + before=current, + after=sorted_output, + line_separator=parsed.line_separator, + ignore_whitespace=config.ignore_whitespace, + ) + new_input += sorted_output + new_input += extra_space + current = """" + new_input += line or """" + else: + current += line or """" + + input_stream = StringIO(new_input) + + for index, line in enumerate(chain(input_stream, (None,))): + if line is None: + if index == 0 and not config.force_adds: + return False + + not_imports = True + end_of_file = True + line = """" + if not line_separator: + line_separator = ""\\n"" + + if code_sorting and code_sorting_section: + output_stream.write( + textwrap.indent( + isort.literal.assignment( + code_sorting_section, + str(code_sorting), + extension, + config=_indented_config(config, indent), + ), + code_sorting_indent, + ) + ) + else: + stripped_line = line.strip() + if stripped_line and not line_separator: + line_separator = line[len(line.rstrip()) :].replace("" "", """").replace(""\\t"", """") + + for file_skip_comment in FILE_SKIP_COMMENTS: + if file_skip_comment in line: + raise FileSkipComment(""Passed in content"") + + if not in_quote and stripped_line == ""# isort: off"": + isort_off = True + + if ( + (index == 0 or (index in (1, 2) and not contains_imports)) + and stripped_line.startswith(""#"") + and stripped_line not in section_comments + ): + in_top_comment = True + elif in_top_comment: + if not line.startswith(""#"") or stripped_line in section_comments: + in_top_comment = False + first_comment_index_end = index - 1 + + if (not stripped_line.startswith(""#"") or in_quote) and '""' in line or ""'"" in line: + char_index = 0 + if first_comment_index_start == -1 and ( + line.startswith('""') or line.startswith(""'"") + ): + first_comment_index_start = index + while char_index < len(line): + if line[char_index] == ""\\\\"": + char_index += 1 + elif in_quote: + if line[char_index : char_index + len(in_quote)] == in_quote: + in_quote = """" + if first_comment_index_end < first_comment_index_start: + first_comment_index_end = index + elif line[char_index] in (""'"", '""'): + long_quote = line[char_index : char_index + 3] + if long_quote in ('""""""', ""'''""): + in_quote = long_quote + char_index += 2 + else: + in_quote = line[char_index] + elif line[char_index] == ""#"": + break + char_index += 1 + + not_imports = bool(in_quote) or in_top_comment or isort_off + if not (in_quote or in_top_comment): + if isort_off: + if stripped_line == ""# isort: on"": + isort_off = False + elif stripped_line.endswith(""# isort: split""): + not_imports = True + elif stripped_line in CODE_SORT_COMMENTS: + code_sorting = stripped_line.split(""isort: "")[1].strip() + code_sorting_indent = line[: -len(line.lstrip())] + not_imports = True + elif code_sorting: + if not stripped_line: + output_stream.write( + textwrap.indent( + isort.literal.assignment( + code_sorting_section, + str(code_sorting), + extension, + config=_indented_config(config, indent), + ), + code_sorting_indent, + ) + ) + not_imports = True + code_sorting = False + code_sorting_section = """" + code_sorting_indent = """" + else: + code_sorting_section += line + line = """" + elif stripped_line in config.section_comments and not import_section: + import_section += line + indent = line[: -len(line.lstrip())] + elif not (stripped_line or contains_imports): + not_imports = True + elif ( + not stripped_line + or stripped_line.startswith(""#"") + and (not indent or indent + line.lstrip() == line) + and not config.treat_all_comments_as_code + and stripped_line not in config.treat_comments_as_code + ): + import_section += line + elif stripped_line.startswith(IMPORT_START_IDENTIFIERS): + contains_imports = True + + new_indent = line[: -len(line.lstrip())] + import_statement = line + stripped_line = line.strip().split(""#"")[0] + while stripped_line.endswith(""\\\\"") or ( + ""("" in stripped_line and "")"" not in stripped_line + ): + if stripped_line.endswith(""\\\\""): + while stripped_line and stripped_line.endswith(""\\\\""): + line = input_stream.readline() + stripped_line = line.strip().split(""#"")[0] + import_statement += line + else: + while "")"" not in stripped_line: + line = input_stream.readline() + stripped_line = line.strip().split(""#"")[0] + import_statement += line + + cimport_statement: bool = False + if ( + import_statement.lstrip().startswith(CIMPORT_IDENTIFIERS) + or "" cimport "" in import_statement + or "" cimport*"" in import_statement + or "" cimport("" in import_statement + or "".cimport"" in import_statement + ): + cimport_statement = True + + if cimport_statement != cimports or (new_indent != indent and import_section): + if import_section: + next_cimports = cimport_statement + next_import_section = import_statement + import_statement = """" + not_imports = True + line = """" + else: + cimports = cimport_statement + + indent = new_indent + import_section += import_statement + else: + not_imports = True + + if not_imports: + raw_import_section: str = import_section + if ( + add_imports + and (stripped_line or end_of_file) + and not config.append_only + and not in_top_comment + and not in_quote + and not import_section + and not line.lstrip().startswith(COMMENT_INDICATORS) + ): + import_section = line_separator.join(add_imports) + line_separator + if end_of_file and index != 0: + output_stream.write(line_separator) + contains_imports = True + add_imports = [] + + if next_import_section and not import_section: # pragma: no cover + raw_import_section = import_section = next_import_section + next_import_section = """" + + if import_section: + if add_imports and not indent: + import_section = ( + line_separator.join(add_imports) + line_separator + import_section + ) + contains_imports = True + add_imports = [] + + if not indent: + import_section += line + raw_import_section += line + if not contains_imports: + output_stream.write(import_section) + else: + leading_whitespace = import_section[: -len(import_section.lstrip())] + trailing_whitespace = import_section[len(import_section.rstrip()) :] + if first_import_section and not import_section.lstrip( + line_separator + ).startswith(COMMENT_INDICATORS): + import_section = import_section.lstrip(line_separator) + raw_import_section = raw_import_section.lstrip(line_separator) + first_import_section = False + + if indent: + import_section = """".join( + line[len(indent) :] for line in import_section.splitlines(keepends=True) + ) + + sorted_import_section = output.sorted_imports( + parse.file_contents(import_section, config=config), + _indented_config(config, indent), + extension, + import_type=""cimport"" if cimports else ""import"", + ) + if not (import_section.strip() and not sorted_import_section): + if indent: + sorted_import_section = ( + leading_whitespace + + textwrap.indent(sorted_import_section, indent).strip() + + trailing_whitespace + ) + + made_changes = made_changes or _has_changed( + before=raw_import_section, + after=sorted_import_section, + line_separator=line_separator, + ignore_whitespace=config.ignore_whitespace, + ) + + output_stream.write(sorted_import_section) + if not line and not indent and next_import_section: + output_stream.write(line_separator) + + if indent: + output_stream.write(line) + if not next_import_section: + indent = """" + + if next_import_section: + cimports = next_cimports + contains_imports = True + else: + contains_imports = False + import_section = next_import_section + next_import_section = """" + else: + output_stream.write(line) + not_imports = False + + return made_changes","[{'piece_type': 'error message', 'piece_content': '$ echo ""\\\\n"" > example.py\\n$ .venv/bin/isort --float-to-top example.py\\nTraceback (most recent call last):\\nFile "".venv/bin/isort"", line 10, in \\nsys.exit(main())\\nFile "".venv/lib/python3.8/site-packages/isort/main.py"", line 876, in main\\nfor sort_attempt in attempt_iterator:\\nFile "".venv/lib/python3.8/site-packages/isort/main.py"", line 865, in \\nsort_imports( # type: ignore\\nFile "".venv/lib/python3.8/site-packages/isort/main.py"", line 93, in sort_imports\\nincorrectly_sorted = not api.sort_file(\\nFile "".venv/lib/python3.8/site-packages/isort/api.py"", line 321, in sort_file\\nchanged = sort_stream(\\nFile "".venv/lib/python3.8/site-packages/isort/api.py"", line 158, in sort_stream\\nchanged = core.process(\\nFile "".venv/lib/python3.8/site-packages/isort/core.py"", line 89, in process\\nwhile current[-1] == ""\\\\n"":\\nIndexError: string index out of range'}]","$ echo ""\\n"" > example.py +$ .venv/bin/isort --float-to-top example.py +Traceback (most recent call last): +File "".venv/bin/isort"", line 10, in +sys.exit(main()) +File "".venv/lib/python3.8/site-packages/isort/main.py"", line 876, in main +for sort_attempt in attempt_iterator: +File "".venv/lib/python3.8/site-packages/isort/main.py"", line 865, in +sort_imports( # type: ignore +File "".venv/lib/python3.8/site-packages/isort/main.py"", line 93, in sort_imports +incorrectly_sorted = not api.sort_file( +File "".venv/lib/python3.8/site-packages/isort/api.py"", line 321, in sort_file +changed = sort_stream( +File "".venv/lib/python3.8/site-packages/isort/api.py"", line 158, in sort_stream +changed = core.process( +File "".venv/lib/python3.8/site-packages/isort/core.py"", line 89, in process +while current[-1] == ""\\n"": +IndexError: string index out of range",IndexError +"def sort_imports( + file_name: str, + config: Config, + check: bool = False, + ask_to_apply: bool = False, + write_to_stdout: bool = False, + **kwargs: Any, +) -> Optional[SortAttempt]: + try: + incorrectly_sorted: bool = False + skipped: bool = False + if check: + try: + incorrectly_sorted = not api.check_file(file_name, config=config, **kwargs) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped) + else: + try: + incorrectly_sorted = not api.sort_file( + file_name, + config=config, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + **kwargs, + ) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped) + except (OSError, ValueError) as error: + warn(f""Unable to parse file {file_name} due to {error}"") + return None + except Exception: + printer = create_terminal_printer(color=config.color_output) + printer.error( + f""Unrecoverable exception thrown when parsing {file_name}! "" + ""This should NEVER happen.\\n"" + ""If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new"" + ) + raise","def sort_imports( + file_name: str, + config: Config, + check: bool = False, + ask_to_apply: bool = False, + write_to_stdout: bool = False, + **kwargs: Any, +) -> Optional[SortAttempt]: + try: + incorrectly_sorted: bool = False + skipped: bool = False + if check: + try: + incorrectly_sorted = not api.check_file(file_name, config=config, **kwargs) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped) + else: + try: + incorrectly_sorted = not api.sort_file( + file_name, + config=config, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + **kwargs, + ) + except FileSkipped: + skipped = True + return SortAttempt(incorrectly_sorted, skipped) + except (OSError, ValueError) as error: + warn(f""Unable to parse file {file_name} due to {error}"") + return None","[{'piece_type': 'error message', 'piece_content': '$ echo ""\\\\n"" > example.py\\n$ .venv/bin/isort --float-to-top example.py\\nTraceback (most recent call last):\\nFile "".venv/bin/isort"", line 10, in \\nsys.exit(main())\\nFile "".venv/lib/python3.8/site-packages/isort/main.py"", line 876, in main\\nfor sort_attempt in attempt_iterator:\\nFile "".venv/lib/python3.8/site-packages/isort/main.py"", line 865, in \\nsort_imports( # type: ignore\\nFile "".venv/lib/python3.8/site-packages/isort/main.py"", line 93, in sort_imports\\nincorrectly_sorted = not api.sort_file(\\nFile "".venv/lib/python3.8/site-packages/isort/api.py"", line 321, in sort_file\\nchanged = sort_stream(\\nFile "".venv/lib/python3.8/site-packages/isort/api.py"", line 158, in sort_stream\\nchanged = core.process(\\nFile "".venv/lib/python3.8/site-packages/isort/core.py"", line 89, in process\\nwhile current[-1] == ""\\\\n"":\\nIndexError: string index out of range'}]","$ echo ""\\n"" > example.py +$ .venv/bin/isort --float-to-top example.py +Traceback (most recent call last): +File "".venv/bin/isort"", line 10, in +sys.exit(main()) +File "".venv/lib/python3.8/site-packages/isort/main.py"", line 876, in main +for sort_attempt in attempt_iterator: +File "".venv/lib/python3.8/site-packages/isort/main.py"", line 865, in +sort_imports( # type: ignore +File "".venv/lib/python3.8/site-packages/isort/main.py"", line 93, in sort_imports +incorrectly_sorted = not api.sort_file( +File "".venv/lib/python3.8/site-packages/isort/api.py"", line 321, in sort_file +changed = sort_stream( +File "".venv/lib/python3.8/site-packages/isort/api.py"", line 158, in sort_stream +changed = core.process( +File "".venv/lib/python3.8/site-packages/isort/core.py"", line 89, in process +while current[-1] == ""\\n"": +IndexError: string index out of range",IndexError +"def main(argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None) -> None: + arguments = parse_args(argv) + if arguments.get(""show_version""): + print(ASCII_ART) + return + + show_config: bool = arguments.pop(""show_config"", False) + + if ""settings_path"" in arguments: + if os.path.isfile(arguments[""settings_path""]): + arguments[""settings_file""] = os.path.abspath(arguments[""settings_path""]) + arguments[""settings_path""] = os.path.dirname(arguments[""settings_file""]) + else: + arguments[""settings_path""] = os.path.abspath(arguments[""settings_path""]) + + if ""virtual_env"" in arguments: + venv = arguments[""virtual_env""] + arguments[""virtual_env""] = os.path.abspath(venv) + if not os.path.isdir(arguments[""virtual_env""]): + warn(f""virtual_env dir does not exist: {arguments['virtual_env']}"") + + file_names = arguments.pop(""files"", []) + if not file_names and not show_config: + print(QUICK_GUIDE) + if arguments: + sys.exit(""Error: arguments passed in without any paths or content."") + else: + return + if ""settings_path"" not in arguments: + arguments[""settings_path""] = ( + os.path.abspath(file_names[0] if file_names else ""."") or os.getcwd() + ) + if not os.path.isdir(arguments[""settings_path""]): + arguments[""settings_path""] = os.path.dirname(arguments[""settings_path""]) + + config_dict = arguments.copy() + ask_to_apply = config_dict.pop(""ask_to_apply"", False) + jobs = config_dict.pop(""jobs"", ()) + check = config_dict.pop(""check"", False) + show_diff = config_dict.pop(""show_diff"", False) + write_to_stdout = config_dict.pop(""write_to_stdout"", False) + deprecated_flags = config_dict.pop(""deprecated_flags"", False) + remapped_deprecated_args = config_dict.pop(""remapped_deprecated_args"", False) + wrong_sorted_files = False + + if ""src_paths"" in config_dict: + config_dict[""src_paths""] = { + Path(src_path).resolve() for src_path in config_dict.get(""src_paths"", ()) + } + + config = Config(**config_dict) + if show_config: + print(json.dumps(config.__dict__, indent=4, separators=("","", "": ""), default=_preconvert)) + return + elif file_names == [""-""]: + api.sort_stream( + input_stream=sys.stdin if stdin is None else stdin, + output_stream=sys.stdout, + config=config, + ) + else: + skipped: List[str] = [] + + if config.filter_files: + filtered_files = [] + for file_name in file_names: + if config.is_skipped(Path(file_name)): + skipped.append(file_name) + else: + filtered_files.append(file_name) + file_names = filtered_files + + file_names = iter_source_code(file_names, config, skipped) + num_skipped = 0 + if config.verbose: + print(ASCII_ART) + + if jobs: + import multiprocessing + + executor = multiprocessing.Pool(jobs) + attempt_iterator = executor.imap( + functools.partial( + sort_imports, + config=config, + check=check, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + ), + file_names, + ) + else: + # https://github.com/python/typeshed/pull/2814 + attempt_iterator = ( + sort_imports( # type: ignore + file_name, + config=config, + check=check, + ask_to_apply=ask_to_apply, + show_diff=show_diff, + write_to_stdout=write_to_stdout, + ) + for file_name in file_names + ) + + for sort_attempt in attempt_iterator: + if not sort_attempt: + continue # pragma: no cover - shouldn't happen, satisfies type constraint + incorrectly_sorted = sort_attempt.incorrectly_sorted + if arguments.get(""check"", False) and incorrectly_sorted: + wrong_sorted_files = True + if sort_attempt.skipped: + num_skipped += ( + 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code + ) + + num_skipped += len(skipped) + if num_skipped and not arguments.get(""quiet"", False): + if config.verbose: + for was_skipped in skipped: + warn( + f""{was_skipped} was skipped as it's listed in 'skip' setting"" + "" or matches a glob in 'skip_glob' setting"" + ) + print(f""Skipped {num_skipped} files"") + + if not config.quiet and (remapped_deprecated_args or deprecated_flags): + if remapped_deprecated_args: + warn( + ""W0502: The following deprecated single dash CLI flags were used and translated: "" + f""{', '.join(remapped_deprecated_args)}!"" + ) + if deprecated_flags: + warn( + ""W0501: The following deprecated CLI flags were used and ignored: "" + f""{', '.join(deprecated_flags)}!"" + ) + warn( + ""W0500: Please see the 5.0.0 Upgrade guide: "" + ""https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0/"" + ) + + if wrong_sorted_files: + sys.exit(1)","def main(argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None) -> None: + arguments = parse_args(argv) + if arguments.get(""show_version""): + print(ASCII_ART) + return + + show_config: bool = arguments.pop(""show_config"", False) + + if ""settings_path"" in arguments: + if os.path.isfile(arguments[""settings_path""]): + arguments[""settings_file""] = os.path.abspath(arguments[""settings_path""]) + arguments[""settings_path""] = os.path.dirname(arguments[""settings_file""]) + else: + arguments[""settings_path""] = os.path.abspath(arguments[""settings_path""]) + + if ""virtual_env"" in arguments: + venv = arguments[""virtual_env""] + arguments[""virtual_env""] = os.path.abspath(venv) + if not os.path.isdir(arguments[""virtual_env""]): + warn(f""virtual_env dir does not exist: {arguments['virtual_env']}"") + + file_names = arguments.pop(""files"", []) + if not file_names and not show_config: + print(QUICK_GUIDE) + if arguments: + sys.exit(""Error: arguments passed in without any paths or content."") + else: + return + if ""settings_path"" not in arguments: + arguments[""settings_path""] = ( + os.path.abspath(file_names[0] if file_names else ""."") or os.getcwd() + ) + if not os.path.isdir(arguments[""settings_path""]): + arguments[""settings_path""] = os.path.dirname(arguments[""settings_path""]) + + config_dict = arguments.copy() + ask_to_apply = config_dict.pop(""ask_to_apply"", False) + jobs = config_dict.pop(""jobs"", ()) + check = config_dict.pop(""check"", False) + show_diff = config_dict.pop(""show_diff"", False) + write_to_stdout = config_dict.pop(""write_to_stdout"", False) + deprecated_flags = config_dict.pop(""deprecated_flags"", False) + remapped_deprecated_args = config_dict.pop(""remapped_deprecated_args"", False) + wrong_sorted_files = False + + if ""src_paths"" in config_dict: + config_dict[""src_paths""] = { + Path(src_path).resolve() for src_path in config_dict.get(""src_paths"", ()) + } + + config = Config(**config_dict) + if show_config: + print(json.dumps(config.__dict__, indent=4, separators=("","", "": ""), default=_preconvert)) + return + elif file_names == [""-""]: + arguments.setdefault(""settings_path"", os.getcwd()) + api.sort_stream( + input_stream=sys.stdin if stdin is None else stdin, + output_stream=sys.stdout, + **arguments, + ) + else: + skipped: List[str] = [] + + if config.filter_files: + filtered_files = [] + for file_name in file_names: + if config.is_skipped(Path(file_name)): + skipped.append(file_name) + else: + filtered_files.append(file_name) + file_names = filtered_files + + file_names = iter_source_code(file_names, config, skipped) + num_skipped = 0 + if config.verbose: + print(ASCII_ART) + + if jobs: + import multiprocessing + + executor = multiprocessing.Pool(jobs) + attempt_iterator = executor.imap( + functools.partial( + sort_imports, + config=config, + check=check, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + ), + file_names, + ) + else: + # https://github.com/python/typeshed/pull/2814 + attempt_iterator = ( + sort_imports( # type: ignore + file_name, + config=config, + check=check, + ask_to_apply=ask_to_apply, + show_diff=show_diff, + write_to_stdout=write_to_stdout, + ) + for file_name in file_names + ) + + for sort_attempt in attempt_iterator: + if not sort_attempt: + continue # pragma: no cover - shouldn't happen, satisfies type constraint + incorrectly_sorted = sort_attempt.incorrectly_sorted + if arguments.get(""check"", False) and incorrectly_sorted: + wrong_sorted_files = True + if sort_attempt.skipped: + num_skipped += ( + 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code + ) + + num_skipped += len(skipped) + if num_skipped and not arguments.get(""quiet"", False): + if config.verbose: + for was_skipped in skipped: + warn( + f""{was_skipped} was skipped as it's listed in 'skip' setting"" + "" or matches a glob in 'skip_glob' setting"" + ) + print(f""Skipped {num_skipped} files"") + + if not config.quiet and (remapped_deprecated_args or deprecated_flags): + if remapped_deprecated_args: + warn( + ""W0502: The following deprecated single dash CLI flags were used and translated: "" + f""{', '.join(remapped_deprecated_args)}!"" + ) + if deprecated_flags: + warn( + ""W0501: The following deprecated CLI flags were used and ignored: "" + f""{', '.join(deprecated_flags)}!"" + ) + warn( + ""W0500: Please see the 5.0.0 Upgrade guide: "" + ""https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0/"" + ) + + if wrong_sorted_files: + sys.exit(1)","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""C:\\\\Users\\\\karraj\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python38\\\\lib\\\\runpy.py"", line 193, in _run_module_as_main\\nreturn _run_code(code, main_globals, None,\\nFile ""C:\\\\Users\\\\karraj\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python38\\\\lib\\\\runpy.py"", line 86, in _run_code\\nexec(code, run_globals)\\nFile ""C:\\\\Users\\\\karraj\\\\Desktop\\\\imports\\\\.isort5\\\\Scripts\\\\isort.exe\\\\__main__.py"", line 9, in \\nFile ""c:\\\\users\\\\karraj\\\\desktop\\\\imports\\\\.isort5\\\\lib\\\\site-packages\\\\isort\\\\main.py"", line 828, in main\\napi.sort_stream(\\nFile ""c:\\\\users\\\\karraj\\\\desktop\\\\imports\\\\.isort5\\\\lib\\\\site-packages\\\\isort\\\\api.py"", line 118, in sort_stream\\nchanged = sort_stream(\\nFile ""c:\\\\users\\\\karraj\\\\desktop\\\\imports\\\\.isort5\\\\lib\\\\site-packages\\\\isort\\\\api.py"", line 137, in sort_stream\\nconfig = _config(path=file_path, config=config, **config_kwargs)\\nFile ""c:\\\\users\\\\karraj\\\\desktop\\\\imports\\\\.isort5\\\\lib\\\\site-packages\\\\isort\\\\api.py"", line 381, in _config\\nconfig = Config(**config_kwargs)\\nFile ""c:\\\\users\\\\karraj\\\\desktop\\\\imports\\\\.isort5\\\\lib\\\\site-packages\\\\isort\\\\settings.py"", line 423, in __init__\\nsuper().__init__(sources=tuple(sources), **combined_config) # type: ignore\\nTypeError: __init__() got an unexpected keyword argument \\'remapped_deprecated_args\\''}, {'piece_type': 'other', 'piece_content': '--- C:\\\\Users\\\\karraj\\\\Desktop\\\\imports\\\\before.py:before 2020-09-01 02:59:53.017777\\n+++ C:\\\\Users\\\\karraj\\\\Desktop\\\\imports\\\\before.py:after 2020-09-01 04:00:37.012947\\n@@ -1,3 +1 @@\\n-from third_party import (lib1, lib2, lib3,\\n- lib4, lib5, lib6,\\n- lib7, lib8, lib9)\\n+from third_party import lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9\\nc:\\\\users\\\\karraj\\\\desktop\\\\imports\\\\.isort5\\\\lib\\\\site-packages\\\\isort\\\\main.py:901: UserWarning: W0502: The following deprecated single dash CLI flags were used and translated: -sp!\\nwarn(\\nc:\\\\users\\\\karraj\\\\desktop\\\\imports\\\\.isort5\\\\lib\\\\site-packages\\\\isort\\\\main.py:910: UserWarning: W0500: Please see the 5.0.0 Upgrade guide: https://timothycrosley.github.io/isort/docs/upgrade_guides/5.0.0/\\nwarn('}]","Traceback (most recent call last): +File ""C:\\Users\\karraj\\AppData\\Local\\Programs\\Python\\Python38\\lib\\runpy.py"", line 193, in _run_module_as_main +return _run_code(code, main_globals, None, +File ""C:\\Users\\karraj\\AppData\\Local\\Programs\\Python\\Python38\\lib\\runpy.py"", line 86, in _run_code +exec(code, run_globals) +File ""C:\\Users\\karraj\\Desktop\\imports\\.isort5\\Scripts\\isort.exe\\__main__.py"", line 9, in +File ""c:\\users\\karraj\\desktop\\imports\\.isort5\\lib\\site-packages\\isort\\main.py"", line 828, in main +api.sort_stream( +File ""c:\\users\\karraj\\desktop\\imports\\.isort5\\lib\\site-packages\\isort\\api.py"", line 118, in sort_stream +changed = sort_stream( +File ""c:\\users\\karraj\\desktop\\imports\\.isort5\\lib\\site-packages\\isort\\api.py"", line 137, in sort_stream +config = _config(path=file_path, config=config, **config_kwargs) +File ""c:\\users\\karraj\\desktop\\imports\\.isort5\\lib\\site-packages\\isort\\api.py"", line 381, in _config +config = Config(**config_kwargs) +File ""c:\\users\\karraj\\desktop\\imports\\.isort5\\lib\\site-packages\\isort\\settings.py"", line 423, in __init__ +super().__init__(sources=tuple(sources), **combined_config) # type: ignore +TypeError: __init__() got an unexpected keyword argument 'remapped_deprecated_args'",TypeError +"def parse_args(argv: Optional[Sequence[str]] = None) -> Dict[str, Any]: + argv = sys.argv[1:] if argv is None else list(argv) + remapped_deprecated_args = [] + for index, arg in enumerate(argv): + if arg in DEPRECATED_SINGLE_DASH_ARGS: + remapped_deprecated_args.append(arg) + argv[index] = f""-{arg}"" + + parser = _build_arg_parser() + arguments = {key: value for key, value in vars(parser.parse_args(argv)).items() if value} + if remapped_deprecated_args: + arguments[""remapped_deprecated_args""] = remapped_deprecated_args + if ""dont_order_by_type"" in arguments: + arguments[""order_by_type""] = False + del arguments[""dont_order_by_type""] + multi_line_output = arguments.get(""multi_line_output"", None) + if multi_line_output: + if multi_line_output.isdigit(): + arguments[""multi_line_output""] = WrapModes(int(multi_line_output)) + else: + arguments[""multi_line_output""] = WrapModes[multi_line_output] + return arguments","def parse_args(argv: Optional[Sequence[str]] = None) -> Dict[str, Any]: + argv = sys.argv[1:] if argv is None else list(argv) + remapped_deprecated_args = [] + for index, arg in enumerate(argv): + if arg in DEPRECATED_SINGLE_DASH_ARGS: + remapped_deprecated_args.append(arg) + argv[index] = f""-{arg}"" + + parser = _build_arg_parser() + arguments = {key: value for key, value in vars(parser.parse_args(argv)).items() if value} + if remapped_deprecated_args: + arguments[""remapped_deprecated_args""] = remapped_deprecated_args + if ""dont_order_by_type"" in arguments: + arguments[""order_by_type""] = False + multi_line_output = arguments.get(""multi_line_output"", None) + if multi_line_output: + if multi_line_output.isdigit(): + arguments[""multi_line_output""] = WrapModes(int(multi_line_output)) + else: + arguments[""multi_line_output""] = WrapModes[multi_line_output] + return arguments","[{'piece_type': 'error message', 'piece_content': '✗ isort myfile.py --dont-order-by-type\\nTraceback (most recent call last):\\nFile ""/usr/local/bin/isort"", line 8, in \\nsys.exit(main())\\nFile ""/usr/local/lib/python3.7/site-packages/isort/main.py"", line 812, in main\\nconfig = Config(**config_dict)\\nFile ""/usr/local/lib/python3.7/site-packages/isort/settings.py"", line 422, in __init__\\nsuper().__init__(sources=tuple(sources), **combined_config) # type: ignore\\nTypeError: __init__() got an unexpected keyword argument \\'dont_order_by_type\\''}]","✗ isort myfile.py --dont-order-by-type +Traceback (most recent call last): +File ""/usr/local/bin/isort"", line 8, in +sys.exit(main()) +File ""/usr/local/lib/python3.7/site-packages/isort/main.py"", line 812, in main +config = Config(**config_dict) +File ""/usr/local/lib/python3.7/site-packages/isort/settings.py"", line 422, in __init__ +super().__init__(sources=tuple(sources), **combined_config) # type: ignore +TypeError: __init__() got an unexpected keyword argument 'dont_order_by_type'",TypeError +"def sort_stream( + input_stream: TextIO, + output_stream: TextIO, + extension: Optional[str] = None, + config: Config = DEFAULT_CONFIG, + file_path: Optional[Path] = None, + disregard_skip: bool = False, + show_diff: bool = False, + **config_kwargs, +): + """"""Sorts any imports within the provided code stream, outputs to the provided output stream. + Directly returns nothing. + + - **input_stream**: The stream of code with imports that need to be sorted. + - **output_stream**: The stream where sorted imports should be written to. + - **extension**: The file extension that contains imports. Defaults to filename extension or py. + - **config**: The config object to use when sorting imports. + - **file_path**: The disk location where the code string was pulled from. + - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file. + - ****config_kwargs**: Any config modifications. + """""" + if show_diff: + _output_stream = StringIO() + _input_stream = StringIO(input_stream.read()) + changed = sort_stream( + input_stream=_input_stream, + output_stream=_output_stream, + extension=extension, + config=config, + file_path=file_path, + disregard_skip=disregard_skip, + **config_kwargs, + ) + _output_stream.seek(0) + _input_stream.seek(0) + show_unified_diff( + file_input=_input_stream.read(), + file_output=_output_stream.read(), + file_path=file_path, + output=output_stream, + ) + return changed + + config = _config(path=file_path, config=config, **config_kwargs) + content_source = str(file_path or ""Passed in content"") + if not disregard_skip: + if file_path and config.is_skipped(file_path): + raise FileSkipSetting(content_source) + + _internal_output = output_stream + + if config.atomic: + try: + file_content = input_stream.read() + compile(file_content, content_source, ""exec"", 0, 1) + input_stream = StringIO(file_content) + except SyntaxError: + raise ExistingSyntaxErrors(content_source) + + if not output_stream.readable(): + _internal_output = StringIO() + + try: + changed = _sort_imports( + input_stream, + _internal_output, + extension=extension or (file_path and file_path.suffix.lstrip(""."")) or ""py"", + config=config, + ) + except FileSkipComment: + raise FileSkipComment(content_source) + + if config.atomic: + _internal_output.seek(0) + try: + compile(_internal_output.read(), content_source, ""exec"", 0, 1) + _internal_output.seek(0) + if _internal_output != output_stream: + output_stream.write(_internal_output.read()) + except SyntaxError: # pragma: no cover + raise IntroducedSyntaxErrors(content_source) + + return changed","def sort_stream( + input_stream: TextIO, + output_stream: TextIO, + extension: Optional[str] = None, + config: Config = DEFAULT_CONFIG, + file_path: Optional[Path] = None, + disregard_skip: bool = False, + **config_kwargs, +): + """"""Sorts any imports within the provided code stream, outputs to the provided output stream. + Directly returns nothing. + + - **input_stream**: The stream of code with imports that need to be sorted. + - **output_stream**: The stream where sorted imports should be written to. + - **extension**: The file extension that contains imports. Defaults to filename extension or py. + - **config**: The config object to use when sorting imports. + - **file_path**: The disk location where the code string was pulled from. + - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file. + - ****config_kwargs**: Any config modifications. + """""" + config = _config(path=file_path, config=config, **config_kwargs) + content_source = str(file_path or ""Passed in content"") + if not disregard_skip: + if file_path and config.is_skipped(file_path): + raise FileSkipSetting(content_source) + + _internal_output = output_stream + + if config.atomic: + try: + file_content = input_stream.read() + compile(file_content, content_source, ""exec"", 0, 1) + input_stream = StringIO(file_content) + except SyntaxError: + raise ExistingSyntaxErrors(content_source) + + if not output_stream.readable(): + _internal_output = StringIO() + + try: + changed = _sort_imports( + input_stream, + _internal_output, + extension=extension or (file_path and file_path.suffix.lstrip(""."")) or ""py"", + config=config, + ) + except FileSkipComment: + raise FileSkipComment(content_source) + + if config.atomic: + _internal_output.seek(0) + try: + compile(_internal_output.read(), content_source, ""exec"", 0, 1) + _internal_output.seek(0) + if _internal_output != output_stream: + output_stream.write(_internal_output.read()) + except SyntaxError: # pragma: no cover + raise IntroducedSyntaxErrors(content_source) + + return changed","[{'piece_type': 'error message', 'piece_content': '$ cat demo.py\\nimport os, sys, collections\\n\\n$ isort --diff - < demo.py\\nTraceback (most recent call last):\\nFile ""/home/peter/.virtualenvs/isort/bin/isort"", line 11, in \\nload_entry_point(\\'isort\\', \\'console_scripts\\', \\'isort\\')()\\nFile ""/home/play/isort/isort/main.py"", line 600, in main\\n**arguments,\\nFile ""/home/play/isort/isort/api.py"", line 104, in sorted_imports\\nconfig = _config(path=file_path, config=config, **config_kwargs)\\nFile ""/home/play/isort/isort/api.py"", line 47, in _config\\nconfig = Config(**config_kwargs)\\nFile ""/home/play/isort/isort/settings.py"", line 300, in __init__\\nsuper().__init__(sources=tuple(sources), **combined_config) # type: ignore\\nTypeError: __init__() got an unexpected keyword argument \\'show_diff\\''}, {'piece_type': 'other', 'piece_content': '$ isort --diff demo.py\\n--- /tmp/isort-bug/demo.py:before\\t2020-05-05 22:00:57.723864\\n+++ /tmp/isort-bug/demo.py:after\\t2020-05-05 22:04:46.469076\\n@@ -1 +1,3 @@\\n-import os, sys, collections\\n+import os\\n+import sys\\n+import collections\\nFixing /tmp/isort-bug/demo.py'}]","$ cat demo.py +import os, sys, collections + +$ isort --diff - < demo.py +Traceback (most recent call last): +File ""/home/peter/.virtualenvs/isort/bin/isort"", line 11, in +load_entry_point('isort', 'console_scripts', 'isort')() +File ""/home/play/isort/isort/main.py"", line 600, in main +**arguments, +File ""/home/play/isort/isort/api.py"", line 104, in sorted_imports +config = _config(path=file_path, config=config, **config_kwargs) +File ""/home/play/isort/isort/api.py"", line 47, in _config +config = Config(**config_kwargs) +File ""/home/play/isort/isort/settings.py"", line 300, in __init__ +super().__init__(sources=tuple(sources), **combined_config) # type: ignore +TypeError: __init__() got an unexpected keyword argument 'show_diff'",TypeError +"def show_unified_diff( + *, file_input: str, file_output: str, file_path: Optional[Path], output=sys.stdout +): + file_name = """" if file_path is None else str(file_path) + file_mtime = str( + datetime.now() if file_path is None else datetime.fromtimestamp(file_path.stat().st_mtime) + ) + + unified_diff_lines = unified_diff( + file_input.splitlines(keepends=True), + file_output.splitlines(keepends=True), + fromfile=file_name + "":before"", + tofile=file_name + "":after"", + fromfiledate=file_mtime, + tofiledate=str(datetime.now()), + ) + for line in unified_diff_lines: + output.write(line)","def show_unified_diff(*, file_input: str, file_output: str, file_path: Optional[Path]): + file_name = """" if file_path is None else str(file_path) + file_mtime = str( + datetime.now() if file_path is None else datetime.fromtimestamp(file_path.stat().st_mtime) + ) + + unified_diff_lines = unified_diff( + file_input.splitlines(keepends=True), + file_output.splitlines(keepends=True), + fromfile=file_name + "":before"", + tofile=file_name + "":after"", + fromfiledate=file_mtime, + tofiledate=str(datetime.now()), + ) + for line in unified_diff_lines: + sys.stdout.write(line)","[{'piece_type': 'error message', 'piece_content': '$ cat demo.py\\nimport os, sys, collections\\n\\n$ isort --diff - < demo.py\\nTraceback (most recent call last):\\nFile ""/home/peter/.virtualenvs/isort/bin/isort"", line 11, in \\nload_entry_point(\\'isort\\', \\'console_scripts\\', \\'isort\\')()\\nFile ""/home/play/isort/isort/main.py"", line 600, in main\\n**arguments,\\nFile ""/home/play/isort/isort/api.py"", line 104, in sorted_imports\\nconfig = _config(path=file_path, config=config, **config_kwargs)\\nFile ""/home/play/isort/isort/api.py"", line 47, in _config\\nconfig = Config(**config_kwargs)\\nFile ""/home/play/isort/isort/settings.py"", line 300, in __init__\\nsuper().__init__(sources=tuple(sources), **combined_config) # type: ignore\\nTypeError: __init__() got an unexpected keyword argument \\'show_diff\\''}, {'piece_type': 'other', 'piece_content': '$ isort --diff demo.py\\n--- /tmp/isort-bug/demo.py:before\\t2020-05-05 22:00:57.723864\\n+++ /tmp/isort-bug/demo.py:after\\t2020-05-05 22:04:46.469076\\n@@ -1 +1,3 @@\\n-import os, sys, collections\\n+import os\\n+import sys\\n+import collections\\nFixing /tmp/isort-bug/demo.py'}]","$ cat demo.py +import os, sys, collections + +$ isort --diff - < demo.py +Traceback (most recent call last): +File ""/home/peter/.virtualenvs/isort/bin/isort"", line 11, in +load_entry_point('isort', 'console_scripts', 'isort')() +File ""/home/play/isort/isort/main.py"", line 600, in main +**arguments, +File ""/home/play/isort/isort/api.py"", line 104, in sorted_imports +config = _config(path=file_path, config=config, **config_kwargs) +File ""/home/play/isort/isort/api.py"", line 47, in _config +config = Config(**config_kwargs) +File ""/home/play/isort/isort/settings.py"", line 300, in __init__ +super().__init__(sources=tuple(sources), **combined_config) # type: ignore +TypeError: __init__() got an unexpected keyword argument 'show_diff'",TypeError +"def _build_arg_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=""Sort Python import definitions alphabetically "" + ""within logical sections. Run with no arguments to run "" + ""interactively. Run with `-` as the first argument to read from "" + ""stdin. Otherwise provide a list of files to sort."" + ) + inline_args_group = parser.add_mutually_exclusive_group() + parser.add_argument( + ""--src"", + ""--src-path"", + dest=""src_paths"", + action=""append"", + help=""Add an explicitly defined source path "" + ""(modules within src paths have their imports automatically catorgorized as first_party)."", + ) + parser.add_argument( + ""-a"", + ""--add-import"", + dest=""add_imports"", + action=""append"", + help=""Adds the specified import line to all files, "" + ""automatically determining correct placement."", + ) + parser.add_argument( + ""--ac"", + ""--atomic"", + dest=""atomic"", + action=""store_true"", + help=""Ensures the output doesn't save if the resulting file contains syntax errors."", + ) + parser.add_argument( + ""--af"", + ""--force-adds"", + dest=""force_adds"", + action=""store_true"", + help=""Forces import adds even if the original file is empty."", + ) + parser.add_argument( + ""-b"", + ""--builtin"", + dest=""known_standard_library"", + action=""append"", + help=""Force isort to recognize a module as part of the python standard library."", + ) + parser.add_argument( + ""-c"", + ""--check-only"", + ""--check"", + action=""store_true"", + dest=""check"", + help=""Checks the file for unsorted / unformatted imports and prints them to the "" + ""command line without modifying the file."", + ) + parser.add_argument( + ""--ca"", + ""--combine-as"", + dest=""combine_as_imports"", + action=""store_true"", + help=""Combines as imports on the same line."", + ) + parser.add_argument( + ""--cs"", + ""--combine-star"", + dest=""combine_star"", + action=""store_true"", + help=""Ensures that if a star import is present, "" + ""nothing else is imported from that namespace."", + ) + parser.add_argument( + ""-d"", + ""--stdout"", + help=""Force resulting output to stdout, instead of in-place."", + dest=""write_to_stdout"", + action=""store_true"", + ) + parser.add_argument( + ""--df"", + ""--diff"", + dest=""show_diff"", + action=""store_true"", + help=""Prints a diff of all the changes isort would make to a file, instead of "" + ""changing it in place"", + ) + parser.add_argument( + ""--ds"", + ""--no-sections"", + help=""Put all imports into the same section bucket"", + dest=""no_sections"", + action=""store_true"", + ) + parser.add_argument( + ""-e"", + ""--balanced"", + dest=""balanced_wrapping"", + action=""store_true"", + help=""Balances wrapping to produce the most consistent line length possible"", + ) + parser.add_argument( + ""-f"", + ""--future"", + dest=""known_future_library"", + action=""append"", + help=""Force isort to recognize a module as part of the future compatibility libraries."", + ) + parser.add_argument( + ""--fas"", + ""--force-alphabetical-sort"", + action=""store_true"", + dest=""force_alphabetical_sort"", + help=""Force all imports to be sorted as a single section"", + ) + parser.add_argument( + ""--fass"", + ""--force-alphabetical-sort-within-sections"", + action=""store_true"", + dest=""force_alphabetical_sort"", + help=""Force all imports to be sorted alphabetically within a section"", + ) + parser.add_argument( + ""--ff"", + ""--from-first"", + dest=""from_first"", + help=""Switches the typical ordering preference, "" + ""showing from imports first then straight ones."", + ) + parser.add_argument( + ""--fgw"", + ""--force-grid-wrap"", + nargs=""?"", + const=2, + type=int, + dest=""force_grid_wrap"", + help=""Force number of from imports (defaults to 2) to be grid wrapped regardless of line "" + ""length"", + ) + parser.add_argument( + ""--fss"", + ""--force-sort-within-sections"", + action=""store_true"", + dest=""force_sort_within_sections"", + help=""Force imports to be sorted by module, independent of import_type"", + ) + parser.add_argument( + ""-i"", + ""--indent"", + help='String to place for indents defaults to "" "" (4 spaces).', + dest=""indent"", + type=str, + ) + parser.add_argument( + ""-j"", ""--jobs"", help=""Number of files to process in parallel."", dest=""jobs"", type=int + ) + parser.add_argument( + ""-k"", + ""--keep-direct-and-as"", + dest=""keep_direct_and_as_imports"", + action=""store_true"", + help=""Turns off default behavior that removes direct imports when as imports exist."", + ) + parser.add_argument(""--lai"", ""--lines-after-imports"", dest=""lines_after_imports"", type=int) + parser.add_argument(""--lbt"", ""--lines-between-types"", dest=""lines_between_types"", type=int) + parser.add_argument( + ""--le"", + ""--line-ending"", + dest=""line_ending"", + help=""Forces line endings to the specified value. "" + ""If not set, values will be guessed per-file."", + ) + parser.add_argument( + ""--ls"", + ""--length-sort"", + help=""Sort imports by their string length."", + dest=""length_sort"", + action=""store_true"", + ) + parser.add_argument( + ""-m"", + ""--multi-line"", + dest=""multi_line_output"", + choices=list(WrapModes.__members__.keys()) + + [str(mode.value) for mode in WrapModes.__members__.values()], + type=str, + help=""Multi line output (0-grid, 1-vertical, 2-hanging, 3-vert-hanging, 4-vert-grid, "" + ""5-vert-grid-grouped, 6-vert-grid-grouped-no-comma)."", + ) + parser.add_argument( + ""-n"", + ""--ensure-newline-before-comments"", + dest=""ensure_newline_before_comments"", + action=""store_true"", + help=""Inserts a blank line before a comment following an import."", + ) + inline_args_group.add_argument( + ""--nis"", + ""--no-inline-sort"", + dest=""no_inline_sort"", + action=""store_true"", + help=""Leaves `from` imports with multiple imports 'as-is' "" + ""(e.g. `from foo import a, c ,b`)."", + ) + parser.add_argument( + ""--nlb"", + ""--no-lines-before"", + help=""Sections which should not be split with previous by empty lines"", + dest=""no_lines_before"", + action=""append"", + ) + parser.add_argument( + ""-o"", + ""--thirdparty"", + dest=""known_third_party"", + action=""append"", + help=""Force isort to recognize a module as being part of a third party library."", + ) + parser.add_argument( + ""--ot"", + ""--order-by-type"", + dest=""order_by_type"", + action=""store_true"", + help=""Order imports by type in addition to alphabetically"", + ) + parser.add_argument( + ""--dt"", + ""--dont-order-by-type"", + dest=""dont_order_by_type"", + action=""store_true"", + help=""Don't order imports by type in addition to alphabetically"", + ) + parser.add_argument( + ""-p"", + ""--project"", + dest=""known_first_party"", + action=""append"", + help=""Force isort to recognize a module as being part of the current python project."", + ) + parser.add_argument( + ""-q"", + ""--quiet"", + action=""store_true"", + dest=""quiet"", + help=""Shows extra quiet output, only errors are outputted."", + ) + parser.add_argument( + ""--rm"", + ""--remove-import"", + dest=""remove_imports"", + action=""append"", + help=""Removes the specified import from all files."", + ) + parser.add_argument( + ""--rr"", + ""--reverse-relative"", + dest=""reverse_relative"", + action=""store_true"", + help=""Reverse order of relative imports."", + ) + parser.add_argument( + ""-s"", + ""--skip"", + help=""Files that sort imports should skip over. If you want to skip multiple "" + ""files you should specify twice: --skip file1 --skip file2."", + dest=""skip"", + action=""append"", + ) + parser.add_argument( + ""--sd"", + ""--section-default"", + dest=""default_section"", + help=""Sets the default section for imports (by default FIRSTPARTY) options: "" + + str(sections.DEFAULT), + ) + parser.add_argument( + ""--sg"", + ""--skip-glob"", + help=""Files that sort imports should skip over."", + dest=""skip_glob"", + action=""append"", + ) + inline_args_group.add_argument( + ""--sl"", + ""--force-single-line-imports"", + dest=""force_single_line"", + action=""store_true"", + help=""Forces all from imports to appear on their own line"", + ) + parser.add_argument( + ""--nsl"", + ""--single-line-exclusions"", + help=""One or more modules to exclude from the single line rule."", + dest=""single_line_exclusions"", + action=""append"", + ) + parser.add_argument( + ""--sp"", + ""--settings-path"", + ""--settings-file"", + ""--settings"", + dest=""settings_path"", + help=""Explicitly set the settings path or file instead of auto determining "" + ""based on file location."", + ) + parser.add_argument( + ""-t"", + ""--top"", + help=""Force specific imports to the top of their appropriate section."", + dest=""force_to_top"", + action=""append"", + ) + parser.add_argument( + ""--tc"", + ""--trailing-comma"", + dest=""include_trailing_comma"", + action=""store_true"", + help=""Includes a trailing comma on multi line imports that include parentheses."", + ) + parser.add_argument( + ""--up"", + ""--use-parentheses"", + dest=""use_parentheses"", + action=""store_true"", + help=""Use parenthesis for line continuation on length limit instead of slashes."", + ) + parser.add_argument( + ""-V"", + ""--version"", + action=""store_true"", + dest=""show_version"", + help=""Displays the currently installed version of isort."", + ) + parser.add_argument( + ""-v"", + ""--verbose"", + action=""store_true"", + dest=""verbose"", + help=""Shows verbose output, such as when files are skipped or when a check is successful."", + ) + parser.add_argument( + ""--virtual-env"", + dest=""virtual_env"", + help=""Virtual environment to use for determining whether a package is third-party"", + ) + parser.add_argument( + ""--conda-env"", + dest=""conda_env"", + help=""Conda environment to use for determining whether a package is third-party"", + ) + parser.add_argument( + ""--vn"", + ""--version-number"", + action=""version"", + version=__version__, + help=""Returns just the current version number without the logo"", + ) + parser.add_argument( + ""-l"", + ""-w"", + ""--line-length"", + ""--line-width"", + help=""The max length of an import line (used for wrapping long imports)."", + dest=""line_length"", + type=int, + ) + parser.add_argument( + ""--wl"", + ""--wrap-length"", + dest=""wrap_length"", + type=int, + help=""Specifies how long lines that are wrapped should be, if not set line_length is used."" + ""\\nNOTE: wrap_length must be LOWER than or equal to line_length."", + ) + parser.add_argument( + ""--ws"", + ""--ignore-whitespace"", + action=""store_true"", + dest=""ignore_whitespace"", + help=""Tells isort to ignore whitespace differences when --check-only is being used."", + ) + parser.add_argument( + ""--case-sensitive"", + dest=""case_sensitive"", + action=""store_true"", + help=""Tells isort to include casing when sorting module names"", + ) + parser.add_argument( + ""--filter-files"", + dest=""filter_files"", + action=""store_true"", + help=""Tells isort to filter files even when they are explicitly passed in as "" + ""part of the command"", + ) + parser.add_argument( + ""files"", nargs=""*"", help=""One or more Python source files that need their imports sorted."" + ) + parser.add_argument( + ""--py"", + ""--python-version"", + action=""store"", + dest=""py_version"", + choices=tuple(VALID_PY_TARGETS) + (""auto"",), + help=""Tells isort to set the known standard library based on the the specified Python "" + ""version. Default is to assume any Python 3 version could be the target, and use a union "" + ""off all stdlib modules across versions. If auto is specified, the version of the "" + ""interpreter used to run isort "" + f""(currently: {sys.version_info.major}{sys.version_info.minor}) will be used."", + ) + parser.add_argument( + ""--profile"", + dest=""profile"", + choices=list(profiles.keys()), + type=str, + help=""Base profile type to use for configuration."", + ) + parser.add_argument( + ""--interactive"", + dest=""ask_to_apply"", + action=""store_true"", + help=""Tells isort to apply changes interactively."", + ) + parser.add_argument( + ""--old-finders"", + ""--magic"", + dest=""old_finders"", + action=""store_true"", + help=""Use the old deprecated finder logic that relies on environment introspection magic."", + ) + parser.add_argument( + ""--show-config"", + dest=""show_config"", + action=""store_true"", + help=""See isort's determined config, as well as sources of config options."", + ) + return parser","def _build_arg_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=""Sort Python import definitions alphabetically "" + ""within logical sections. Run with no arguments to run "" + ""interactively. Run with `-` as the first argument to read from "" + ""stdin. Otherwise provide a list of files to sort."" + ) + inline_args_group = parser.add_mutually_exclusive_group() + parser.add_argument( + ""--src"", + ""--src-path"", + dest=""source_paths"", + action=""append"", + help=""Add an explicitly defined source path "" + ""(modules within src paths have their imports automatically catorgorized as first_party)."", + ) + parser.add_argument( + ""-a"", + ""--add-import"", + dest=""add_imports"", + action=""append"", + help=""Adds the specified import line to all files, "" + ""automatically determining correct placement."", + ) + parser.add_argument( + ""--ac"", + ""--atomic"", + dest=""atomic"", + action=""store_true"", + help=""Ensures the output doesn't save if the resulting file contains syntax errors."", + ) + parser.add_argument( + ""--af"", + ""--force-adds"", + dest=""force_adds"", + action=""store_true"", + help=""Forces import adds even if the original file is empty."", + ) + parser.add_argument( + ""-b"", + ""--builtin"", + dest=""known_standard_library"", + action=""append"", + help=""Force isort to recognize a module as part of the python standard library."", + ) + parser.add_argument( + ""-c"", + ""--check-only"", + ""--check"", + action=""store_true"", + dest=""check"", + help=""Checks the file for unsorted / unformatted imports and prints them to the "" + ""command line without modifying the file."", + ) + parser.add_argument( + ""--ca"", + ""--combine-as"", + dest=""combine_as_imports"", + action=""store_true"", + help=""Combines as imports on the same line."", + ) + parser.add_argument( + ""--cs"", + ""--combine-star"", + dest=""combine_star"", + action=""store_true"", + help=""Ensures that if a star import is present, "" + ""nothing else is imported from that namespace."", + ) + parser.add_argument( + ""-d"", + ""--stdout"", + help=""Force resulting output to stdout, instead of in-place."", + dest=""write_to_stdout"", + action=""store_true"", + ) + parser.add_argument( + ""--df"", + ""--diff"", + dest=""show_diff"", + action=""store_true"", + help=""Prints a diff of all the changes isort would make to a file, instead of "" + ""changing it in place"", + ) + parser.add_argument( + ""--ds"", + ""--no-sections"", + help=""Put all imports into the same section bucket"", + dest=""no_sections"", + action=""store_true"", + ) + parser.add_argument( + ""-e"", + ""--balanced"", + dest=""balanced_wrapping"", + action=""store_true"", + help=""Balances wrapping to produce the most consistent line length possible"", + ) + parser.add_argument( + ""-f"", + ""--future"", + dest=""known_future_library"", + action=""append"", + help=""Force isort to recognize a module as part of the future compatibility libraries."", + ) + parser.add_argument( + ""--fas"", + ""--force-alphabetical-sort"", + action=""store_true"", + dest=""force_alphabetical_sort"", + help=""Force all imports to be sorted as a single section"", + ) + parser.add_argument( + ""--fass"", + ""--force-alphabetical-sort-within-sections"", + action=""store_true"", + dest=""force_alphabetical_sort"", + help=""Force all imports to be sorted alphabetically within a section"", + ) + parser.add_argument( + ""--ff"", + ""--from-first"", + dest=""from_first"", + help=""Switches the typical ordering preference, "" + ""showing from imports first then straight ones."", + ) + parser.add_argument( + ""--fgw"", + ""--force-grid-wrap"", + nargs=""?"", + const=2, + type=int, + dest=""force_grid_wrap"", + help=""Force number of from imports (defaults to 2) to be grid wrapped regardless of line "" + ""length"", + ) + parser.add_argument( + ""--fss"", + ""--force-sort-within-sections"", + action=""store_true"", + dest=""force_sort_within_sections"", + help=""Force imports to be sorted by module, independent of import_type"", + ) + parser.add_argument( + ""-i"", + ""--indent"", + help='String to place for indents defaults to "" "" (4 spaces).', + dest=""indent"", + type=str, + ) + parser.add_argument( + ""-j"", ""--jobs"", help=""Number of files to process in parallel."", dest=""jobs"", type=int + ) + parser.add_argument( + ""-k"", + ""--keep-direct-and-as"", + dest=""keep_direct_and_as_imports"", + action=""store_true"", + help=""Turns off default behavior that removes direct imports when as imports exist."", + ) + parser.add_argument(""--lai"", ""--lines-after-imports"", dest=""lines_after_imports"", type=int) + parser.add_argument(""--lbt"", ""--lines-between-types"", dest=""lines_between_types"", type=int) + parser.add_argument( + ""--le"", + ""--line-ending"", + dest=""line_ending"", + help=""Forces line endings to the specified value. "" + ""If not set, values will be guessed per-file."", + ) + parser.add_argument( + ""--ls"", + ""--length-sort"", + help=""Sort imports by their string length."", + dest=""length_sort"", + action=""store_true"", + ) + parser.add_argument( + ""-m"", + ""--multi-line"", + dest=""multi_line_output"", + choices=list(WrapModes.__members__.keys()) + + [str(mode.value) for mode in WrapModes.__members__.values()], + type=str, + help=""Multi line output (0-grid, 1-vertical, 2-hanging, 3-vert-hanging, 4-vert-grid, "" + ""5-vert-grid-grouped, 6-vert-grid-grouped-no-comma)."", + ) + parser.add_argument( + ""-n"", + ""--ensure-newline-before-comments"", + dest=""ensure_newline_before_comments"", + action=""store_true"", + help=""Inserts a blank line before a comment following an import."", + ) + inline_args_group.add_argument( + ""--nis"", + ""--no-inline-sort"", + dest=""no_inline_sort"", + action=""store_true"", + help=""Leaves `from` imports with multiple imports 'as-is' "" + ""(e.g. `from foo import a, c ,b`)."", + ) + parser.add_argument( + ""--nlb"", + ""--no-lines-before"", + help=""Sections which should not be split with previous by empty lines"", + dest=""no_lines_before"", + action=""append"", + ) + parser.add_argument( + ""-o"", + ""--thirdparty"", + dest=""known_third_party"", + action=""append"", + help=""Force isort to recognize a module as being part of a third party library."", + ) + parser.add_argument( + ""--ot"", + ""--order-by-type"", + dest=""order_by_type"", + action=""store_true"", + help=""Order imports by type in addition to alphabetically"", + ) + parser.add_argument( + ""--dt"", + ""--dont-order-by-type"", + dest=""dont_order_by_type"", + action=""store_true"", + help=""Don't order imports by type in addition to alphabetically"", + ) + parser.add_argument( + ""-p"", + ""--project"", + dest=""known_first_party"", + action=""append"", + help=""Force isort to recognize a module as being part of the current python project."", + ) + parser.add_argument( + ""-q"", + ""--quiet"", + action=""store_true"", + dest=""quiet"", + help=""Shows extra quiet output, only errors are outputted."", + ) + parser.add_argument( + ""--rm"", + ""--remove-import"", + dest=""remove_imports"", + action=""append"", + help=""Removes the specified import from all files."", + ) + parser.add_argument( + ""--rr"", + ""--reverse-relative"", + dest=""reverse_relative"", + action=""store_true"", + help=""Reverse order of relative imports."", + ) + parser.add_argument( + ""-s"", + ""--skip"", + help=""Files that sort imports should skip over. If you want to skip multiple "" + ""files you should specify twice: --skip file1 --skip file2."", + dest=""skip"", + action=""append"", + ) + parser.add_argument( + ""--sd"", + ""--section-default"", + dest=""default_section"", + help=""Sets the default section for imports (by default FIRSTPARTY) options: "" + + str(sections.DEFAULT), + ) + parser.add_argument( + ""--sg"", + ""--skip-glob"", + help=""Files that sort imports should skip over."", + dest=""skip_glob"", + action=""append"", + ) + inline_args_group.add_argument( + ""--sl"", + ""--force-single-line-imports"", + dest=""force_single_line"", + action=""store_true"", + help=""Forces all from imports to appear on their own line"", + ) + parser.add_argument( + ""--nsl"", + ""--single-line-exclusions"", + help=""One or more modules to exclude from the single line rule."", + dest=""single_line_exclusions"", + action=""append"", + ) + parser.add_argument( + ""--sp"", + ""--settings-path"", + ""--settings-file"", + ""--settings"", + dest=""settings_path"", + help=""Explicitly set the settings path or file instead of auto determining "" + ""based on file location."", + ) + parser.add_argument( + ""-t"", + ""--top"", + help=""Force specific imports to the top of their appropriate section."", + dest=""force_to_top"", + action=""append"", + ) + parser.add_argument( + ""--tc"", + ""--trailing-comma"", + dest=""include_trailing_comma"", + action=""store_true"", + help=""Includes a trailing comma on multi line imports that include parentheses."", + ) + parser.add_argument( + ""--up"", + ""--use-parentheses"", + dest=""use_parentheses"", + action=""store_true"", + help=""Use parenthesis for line continuation on length limit instead of slashes."", + ) + parser.add_argument( + ""-V"", + ""--version"", + action=""store_true"", + dest=""show_version"", + help=""Displays the currently installed version of isort."", + ) + parser.add_argument( + ""-v"", + ""--verbose"", + action=""store_true"", + dest=""verbose"", + help=""Shows verbose output, such as when files are skipped or when a check is successful."", + ) + parser.add_argument( + ""--virtual-env"", + dest=""virtual_env"", + help=""Virtual environment to use for determining whether a package is third-party"", + ) + parser.add_argument( + ""--conda-env"", + dest=""conda_env"", + help=""Conda environment to use for determining whether a package is third-party"", + ) + parser.add_argument( + ""--vn"", + ""--version-number"", + action=""version"", + version=__version__, + help=""Returns just the current version number without the logo"", + ) + parser.add_argument( + ""-l"", + ""-w"", + ""--line-length"", + ""--line-width"", + help=""The max length of an import line (used for wrapping long imports)."", + dest=""line_length"", + type=int, + ) + parser.add_argument( + ""--wl"", + ""--wrap-length"", + dest=""wrap_length"", + type=int, + help=""Specifies how long lines that are wrapped should be, if not set line_length is used."" + ""\\nNOTE: wrap_length must be LOWER than or equal to line_length."", + ) + parser.add_argument( + ""--ws"", + ""--ignore-whitespace"", + action=""store_true"", + dest=""ignore_whitespace"", + help=""Tells isort to ignore whitespace differences when --check-only is being used."", + ) + parser.add_argument( + ""--case-sensitive"", + dest=""case_sensitive"", + action=""store_true"", + help=""Tells isort to include casing when sorting module names"", + ) + parser.add_argument( + ""--filter-files"", + dest=""filter_files"", + action=""store_true"", + help=""Tells isort to filter files even when they are explicitly passed in as "" + ""part of the command"", + ) + parser.add_argument( + ""files"", nargs=""*"", help=""One or more Python source files that need their imports sorted."" + ) + parser.add_argument( + ""--py"", + ""--python-version"", + action=""store"", + dest=""py_version"", + choices=tuple(VALID_PY_TARGETS) + (""auto"",), + help=""Tells isort to set the known standard library based on the the specified Python "" + ""version. Default is to assume any Python 3 version could be the target, and use a union "" + ""off all stdlib modules across versions. If auto is specified, the version of the "" + ""interpreter used to run isort "" + f""(currently: {sys.version_info.major}{sys.version_info.minor}) will be used."", + ) + parser.add_argument( + ""--profile"", + dest=""profile"", + choices=list(profiles.keys()), + type=str, + help=""Base profile type to use for configuration."", + ) + parser.add_argument( + ""--interactive"", + dest=""ask_to_apply"", + action=""store_true"", + help=""Tells isort to apply changes interactively."", + ) + parser.add_argument( + ""--old-finders"", + ""--magic"", + dest=""old_finders"", + action=""store_true"", + help=""Use the old deprecated finder logic that relies on environment introspection magic."", + ) + parser.add_argument( + ""--show-config"", + dest=""show_config"", + action=""store_true"", + help=""See isort's determined config, as well as sources of config options."", + ) + return parser","[{'piece_type': 'error message', 'piece_content': '$ isort --src-path=. .\\nTraceback (most recent call last):\\nFile """", line 1, in \\nFile ""/home/anders/python/isort/isort/main.py"", line 647, in main\\nconfig = Config(**config_dict)\\nFile ""/home/anders/python/isort/isort/settings.py"", line 329, in __init__\\nsuper().__init__(sources=tuple(sources), **combined_config) # type: ignore\\nTypeError: __init__() got an unexpected keyword argument \\'source_paths\\''}]","$ isort --src-path=. . +Traceback (most recent call last): +File """", line 1, in +File ""/home/anders/python/isort/isort/main.py"", line 647, in main +config = Config(**config_dict) +File ""/home/anders/python/isort/isort/settings.py"", line 329, in __init__ +super().__init__(sources=tuple(sources), **combined_config) # type: ignore +TypeError: __init__() got an unexpected keyword argument 'source_paths'",TypeError +"def main(argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None) -> None: + arguments = parse_args(argv) + if arguments.get(""show_version""): + print(ASCII_ART) + return + + show_config: bool = arguments.pop(""show_config"", False) + + if ""settings_path"" in arguments: + if os.path.isfile(arguments[""settings_path""]): + arguments[""settings_file""] = os.path.abspath(arguments[""settings_path""]) + arguments[""settings_path""] = os.path.dirname(arguments[""settings_file""]) + elif not os.path.isdir(arguments[""settings_path""]): + warn(f""settings_path dir does not exist: {arguments['settings_path']}"") + else: + arguments[""settings_path""] = os.path.abspath(arguments[""settings_path""]) + + if ""virtual_env"" in arguments: + venv = arguments[""virtual_env""] + arguments[""virtual_env""] = os.path.abspath(venv) + if not os.path.isdir(arguments[""virtual_env""]): + warn(f""virtual_env dir does not exist: {arguments['virtual_env']}"") + + file_names = arguments.pop(""files"", []) + if not file_names and not show_config: + print(QUICK_GUIDE) + return + elif file_names == [""-""] and not show_config: + api.sort_stream( + input_stream=sys.stdin if stdin is None else stdin, + output_stream=sys.stdout, + **arguments, + ) + return + + if ""settings_path"" not in arguments: + arguments[""settings_path""] = ( + os.path.abspath(file_names[0] if file_names else ""."") or os.getcwd() + ) + if not os.path.isdir(arguments[""settings_path""]): + arguments[""settings_path""] = os.path.dirname(arguments[""settings_path""]) + + config_dict = arguments.copy() + ask_to_apply = config_dict.pop(""ask_to_apply"", False) + jobs = config_dict.pop(""jobs"", ()) + filter_files = config_dict.pop(""filter_files"", False) + check = config_dict.pop(""check"", False) + show_diff = config_dict.pop(""show_diff"", False) + write_to_stdout = config_dict.pop(""write_to_stdout"", False) + + src_paths = set(config_dict.setdefault(""src_paths"", ())) + for file_name in file_names: + if os.path.isdir(file_name): + src_paths.add(Path(file_name).resolve()) + else: + src_paths.add(Path(file_name).parent.resolve()) + + config = Config(**config_dict) + if show_config: + print(json.dumps(config.__dict__, indent=4, separators=("","", "": ""), default=_preconvert)) + return + + wrong_sorted_files = False + skipped: List[str] = [] + + if filter_files: + filtered_files = [] + for file_name in file_names: + if config.is_skipped(Path(file_name)): + skipped.append(file_name) + else: + filtered_files.append(file_name) + file_names = filtered_files + + file_names = iter_source_code(file_names, config, skipped) + num_skipped = 0 + if config.verbose: + print(ASCII_ART) + + if jobs: + import multiprocessing + + executor = multiprocessing.Pool(jobs) + attempt_iterator = executor.imap( + functools.partial( + sort_imports, + config=config, + check=check, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + ), + file_names, + ) + else: + # https://github.com/python/typeshed/pull/2814 + attempt_iterator = ( + sort_imports( # type: ignore + file_name, + config=config, + check=check, + ask_to_apply=ask_to_apply, + show_diff=show_diff, + write_to_stdout=write_to_stdout, + ) + for file_name in file_names + ) + + for sort_attempt in attempt_iterator: + if not sort_attempt: + continue # pragma: no cover - shouldn't happen, satisfies type constraint + incorrectly_sorted = sort_attempt.incorrectly_sorted + if arguments.get(""check"", False) and incorrectly_sorted: + wrong_sorted_files = True + if sort_attempt.skipped: + num_skipped += 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code + + if wrong_sorted_files: + sys.exit(1) + + num_skipped += len(skipped) + if num_skipped and not arguments.get(""quiet"", False): + if config.verbose: + for was_skipped in skipped: + warn( + f""{was_skipped} was skipped as it's listed in 'skip' setting"" + "" or matches a glob in 'skip_glob' setting"" + ) + print(f""Skipped {num_skipped} files"")","def main(argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None) -> None: + arguments = parse_args(argv) + if arguments.get(""show_version""): + print(ASCII_ART) + return + + show_config: bool = arguments.pop(""show_config"", False) + + if ""settings_path"" in arguments: + if os.path.isfile(arguments[""settings_path""]): + arguments[""settings_file""] = os.path.abspath(arguments[""settings_path""]) + arguments[""settings_path""] = os.path.dirname(arguments[""settings_file""]) + elif not os.path.isdir(arguments[""settings_path""]): + warn(f""settings_path dir does not exist: {arguments['settings_path']}"") + else: + arguments[""settings_path""] = os.path.abspath(arguments[""settings_path""]) + + if ""virtual_env"" in arguments: + venv = arguments[""virtual_env""] + arguments[""virtual_env""] = os.path.abspath(venv) + if not os.path.isdir(arguments[""virtual_env""]): + warn(f""virtual_env dir does not exist: {arguments['virtual_env']}"") + + file_names = arguments.pop(""files"", []) + if not file_names and not show_config: + print(QUICK_GUIDE) + return + elif file_names == [""-""] and not show_config: + api.sort_stream( + input_stream=sys.stdin if stdin is None else stdin, + output_stream=sys.stdout, + **arguments, + ) + return + + if ""settings_path"" not in arguments: + arguments[""settings_path""] = ( + os.path.abspath(file_names[0] if file_names else ""."") or os.getcwd() + ) + if not os.path.isdir(arguments[""settings_path""]): + arguments[""settings_path""] = os.path.dirname(arguments[""settings_path""]) + + config_dict = arguments.copy() + ask_to_apply = config_dict.pop(""ask_to_apply"", False) + jobs = config_dict.pop(""jobs"", ()) + filter_files = config_dict.pop(""filter_files"", False) + check = config_dict.pop(""check"", False) + show_diff = config_dict.pop(""show_diff"", False) + write_to_stdout = config_dict.pop(""write_to_stdout"", False) + + src_paths = config_dict.setdefault(""src_paths"", set()) + for file_name in file_names: + if os.path.isdir(file_name): + src_paths.add(Path(file_name).resolve()) + else: + src_paths.add(Path(file_name).parent.resolve()) + + config = Config(**config_dict) + if show_config: + print(json.dumps(config.__dict__, indent=4, separators=("","", "": ""), default=_preconvert)) + return + + wrong_sorted_files = False + skipped: List[str] = [] + + if filter_files: + filtered_files = [] + for file_name in file_names: + if config.is_skipped(Path(file_name)): + skipped.append(file_name) + else: + filtered_files.append(file_name) + file_names = filtered_files + + file_names = iter_source_code(file_names, config, skipped) + num_skipped = 0 + if config.verbose: + print(ASCII_ART) + + if jobs: + import multiprocessing + + executor = multiprocessing.Pool(jobs) + attempt_iterator = executor.imap( + functools.partial( + sort_imports, + config=config, + check=check, + ask_to_apply=ask_to_apply, + write_to_stdout=write_to_stdout, + ), + file_names, + ) + else: + # https://github.com/python/typeshed/pull/2814 + attempt_iterator = ( + sort_imports( # type: ignore + file_name, + config=config, + check=check, + ask_to_apply=ask_to_apply, + show_diff=show_diff, + write_to_stdout=write_to_stdout, + ) + for file_name in file_names + ) + + for sort_attempt in attempt_iterator: + if not sort_attempt: + continue # pragma: no cover - shouldn't happen, satisfies type constraint + incorrectly_sorted = sort_attempt.incorrectly_sorted + if arguments.get(""check"", False) and incorrectly_sorted: + wrong_sorted_files = True + if sort_attempt.skipped: + num_skipped += 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code + + if wrong_sorted_files: + sys.exit(1) + + num_skipped += len(skipped) + if num_skipped and not arguments.get(""quiet"", False): + if config.verbose: + for was_skipped in skipped: + warn( + f""{was_skipped} was skipped as it's listed in 'skip' setting"" + "" or matches a glob in 'skip_glob' setting"" + ) + print(f""Skipped {num_skipped} files"")","[{'piece_type': 'error message', 'piece_content': '$ isort --src-path=. .\\nTraceback (most recent call last):\\nFile """", line 1, in \\nFile ""/home/anders/python/isort/isort/main.py"", line 647, in main\\nconfig = Config(**config_dict)\\nFile ""/home/anders/python/isort/isort/settings.py"", line 329, in __init__\\nsuper().__init__(sources=tuple(sources), **combined_config) # type: ignore\\nTypeError: __init__() got an unexpected keyword argument \\'source_paths\\''}]","$ isort --src-path=. . +Traceback (most recent call last): +File """", line 1, in +File ""/home/anders/python/isort/isort/main.py"", line 647, in main +config = Config(**config_dict) +File ""/home/anders/python/isort/isort/settings.py"", line 329, in __init__ +super().__init__(sources=tuple(sources), **combined_config) # type: ignore +TypeError: __init__() got an unexpected keyword argument 'source_paths'",TypeError +" def find(self, module_name): + for finder in self.finders: + try: + section = finder.find(module_name) + except Exception as exception: + # isort has to be able to keep trying to identify the correct import section even if one approach fails + if config.get('verbose', False): + print('{} encountered an error ({}) while trying to identify the {} module'.format(finder.__name__, + str(exception), + module_name)) + if section is not None: + return section"," def find(self, module_name): + for finder in self.finders: + section = finder.find(module_name) + if section is not None: + return section","[{'piece_type': 'error message', 'piece_content': '$ isort\\nTraceback (most recent call last):\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/packaging/requirements.py"", line 93, in __init__\\nreq = REQUIREMENT.parseString(requirement_string)\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 1814, in parseString\\nraise exc\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 1804, in parseString\\nloc, tokens = self._parse( instring, 0 )\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 1548, in _parseNoCache\\nloc,tokens = self.parseImpl( instring, preloc, doActions )\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 3722, in parseImpl\\nloc, exprtokens = e._parse( instring, loc, doActions )\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 1552, in _parseNoCache\\nloc,tokens = self.parseImpl( instring, preloc, doActions )\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 3502, in parseImpl\\nraise ParseException(instring, loc, self.errmsg, self)\\npip._vendor.pyparsing.ParseException: Expected stringEnd (at char 7), (line:1, col:8)\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/constructors.py"", line 285, in install_req_from_line\\nreq = Requirement(req_as_string)\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/packaging/requirements.py"", line 97, in __init__\\nrequirement_string[e.loc : e.loc + 8], e.msg\\npip._vendor.packaging.requirements.InvalidRequirement: Parse error at ""\\'otherwis\\'"": Expected stringEnd\\n\\nDuring handling of the above exception, another exception occurred:\\n\\nTraceback (most recent call last):\\nFile ""/home/vagrant/python/bin/isort"", line 10, in \\nsys.exit(main())\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/isort/main.py"", line 348, in main\\nfor sort_attempt in attempt_iterator:\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/isort/main.py"", line 346, in \\nattempt_iterator = (sort_imports(file_name, **arguments) for file_name in file_names)\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/isort/main.py"", line 86, in sort_imports\\nresult = SortImports(file_name, **arguments)\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/isort/isort.py"", line 141, in __init__\\nself.finder = FindersManager(config=self.config, sections=self.sections)\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py"", line 326, in __init__\\nself.finders = tuple(finder(config, sections) for finder in self.finders)\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py"", line 326, in \\nself.finders = tuple(finder(config, sections) for finder in self.finders)\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py"", line 184, in __init__\\nself.names = self._load_names()\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py"", line 206, in _load_names\\nfor name in self._get_names(path):\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py"", line 288, in _get_names\\nfor req in requirements:\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/req_file.py"", line 112, in parse_requirements\\nfor req in req_iter:\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/req_file.py"", line 193, in process_line\\nisolated=isolated, options=req_options, wheel_cache=wheel_cache\\nFile ""/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/constructors.py"", line 296, in install_req_from_line\\n""Invalid requirement: \\'%s\\'\\\\n%s"" % (req_as_string, add_msg)\\npip._internal.exceptions.InstallationError: Invalid requirement: \\'Unless otherwise stated, this license applies to all files contained\\''}]","$ isort +Traceback (most recent call last): +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/packaging/requirements.py"", line 93, in __init__ +req = REQUIREMENT.parseString(requirement_string) +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 1814, in parseString +raise exc +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 1804, in parseString +loc, tokens = self._parse( instring, 0 ) +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 1548, in _parseNoCache +loc,tokens = self.parseImpl( instring, preloc, doActions ) +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 3722, in parseImpl +loc, exprtokens = e._parse( instring, loc, doActions ) +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 1552, in _parseNoCache +loc,tokens = self.parseImpl( instring, preloc, doActions ) +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py"", line 3502, in parseImpl +raise ParseException(instring, loc, self.errmsg, self) +pip._vendor.pyparsing.ParseException: Expected stringEnd (at char 7), (line:1, col:8) + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/constructors.py"", line 285, in install_req_from_line +req = Requirement(req_as_string) +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/packaging/requirements.py"", line 97, in __init__ +requirement_string[e.loc : e.loc + 8], e.msg +pip._vendor.packaging.requirements.InvalidRequirement: Parse error at ""'otherwis'"": Expected stringEnd + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): +File ""/home/vagrant/python/bin/isort"", line 10, in +sys.exit(main()) +File ""/home/vagrant/python/lib/python3.6/site-packages/isort/main.py"", line 348, in main +for sort_attempt in attempt_iterator: +File ""/home/vagrant/python/lib/python3.6/site-packages/isort/main.py"", line 346, in +attempt_iterator = (sort_imports(file_name, **arguments) for file_name in file_names) +File ""/home/vagrant/python/lib/python3.6/site-packages/isort/main.py"", line 86, in sort_imports +result = SortImports(file_name, **arguments) +File ""/home/vagrant/python/lib/python3.6/site-packages/isort/isort.py"", line 141, in __init__ +self.finder = FindersManager(config=self.config, sections=self.sections) +File ""/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py"", line 326, in __init__ +self.finders = tuple(finder(config, sections) for finder in self.finders) +File ""/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py"", line 326, in +self.finders = tuple(finder(config, sections) for finder in self.finders) +File ""/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py"", line 184, in __init__ +self.names = self._load_names() +File ""/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py"", line 206, in _load_names +for name in self._get_names(path): +File ""/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py"", line 288, in _get_names +for req in requirements: +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/req_file.py"", line 112, in parse_requirements +for req in req_iter: +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/req_file.py"", line 193, in process_line +isolated=isolated, options=req_options, wheel_cache=wheel_cache +File ""/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/constructors.py"", line 296, in install_req_from_line +""Invalid requirement: '%s'\\n%s"" % (req_as_string, add_msg) +pip._internal.exceptions.InstallationError: Invalid requirement: 'Unless otherwise stated, this license applies to all files contained'",pip._internal.exceptions.InstallationError +" def create_domain_name(self, + protocol, # type: str + domain_name, # type: str + endpoint_type, # type: str + certificate_arn, # type: str + security_policy=None, # type: Optional[str] + tags=None, # type: StrMap + ): + # type: (...) -> DomainNameResponse + if protocol == 'HTTP': + kwargs = { + 'domainName': domain_name, + 'endpointConfiguration': { + 'types': [endpoint_type], + }, + } + if security_policy is not None: + kwargs['securityPolicy'] = security_policy + if endpoint_type == 'EDGE': + kwargs['certificateArn'] = certificate_arn + else: + kwargs['regionalCertificateArn'] = certificate_arn + if tags is not None: + kwargs['tags'] = tags + created_domain_name = self._create_domain_name(kwargs) + elif protocol == 'WEBSOCKET': + kwargs = self.get_custom_domain_params_v2( + domain_name=domain_name, + endpoint_type=endpoint_type, + security_policy=security_policy, + certificate_arn=certificate_arn, + tags=tags + ) + created_domain_name = self._create_domain_name_v2(kwargs) + else: + raise ValueError(""Unsupported protocol value."") + return created_domain_name"," def create_domain_name(self, + protocol, # type: str + domain_name, # type: str + endpoint_type, # type: str + certificate_arn, # type: str + security_policy=None, # type: Optional[str] + tags=None, # type: StrMap + ): + # type: (...) -> Dict[str, Any] + if protocol == 'HTTP': + kwargs = { + 'domainName': domain_name, + 'endpointConfiguration': { + 'types': [endpoint_type], + }, + } + if security_policy is not None: + kwargs['securityPolicy'] = security_policy + if endpoint_type == 'EDGE': + kwargs['certificateArn'] = certificate_arn + else: + kwargs['regionalCertificateArn'] = certificate_arn + if tags is not None: + kwargs['tags'] = tags + created_domain_name = self._create_domain_name(kwargs) + elif protocol == 'WEBSOCKET': + kwargs = self.get_custom_domain_params_v2( + domain_name=domain_name, + endpoint_type=endpoint_type, + security_policy=security_policy, + certificate_arn=certificate_arn, + tags=tags + ) + created_domain_name = self._create_domain_name_v2(kwargs) + else: + raise ValueError(""Unsupported protocol value."") + return created_domain_name","[{'piece_type': 'error message', 'piece_content': 'Updating custom domain name: api.transferbank.com.br\\nTraceback (most recent call last):\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main\\nreturn cli(obj={})\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main\\nrv = self.invoke(ctx)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func\\nreturn f(get_current_context(), *args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy\\ndeployed_values = d.deploy(config, chalice_stage_name=stage)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy\\nreturn self._deploy(config, chalice_stage_name)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy\\nself._executor.execute(plan)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute\\ngetattr(self, \\'_do_%s\\' % instruction.__class__.__name__.lower(),\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall\\nresult = method(**final_kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name\\nupdated_domain_name = self._update_domain_name_v2(kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2\\n\\'hosted_zone_id\\': result_data[\\'HostedZoneId\\'],\\nKeyError: \\'HostedZoneId\\''}, {'piece_type': 'other', 'piece_content': '""websocket_api_custom_domain"": {\\n""domain_name"": ""api.transferbank.com.br"",\\n""certificate_arn"": ""arn:aws:acm:us-east-1:073289305372:certificate/d995959e-6f7d-4fcb-9c56-bf370ca1a382"",\\n""url_prefix"": ""tb_wst_channel_manager""\\n},'}]","Updating custom domain name: api.transferbank.com.br +Traceback (most recent call last): +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main +return cli(obj={}) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__ +return self.main(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main +rv = self.invoke(ctx) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke +return callback(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func +return f(get_current_context(), *args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy +deployed_values = d.deploy(config, chalice_stage_name=stage) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy +return self._deploy(config, chalice_stage_name) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy +self._executor.execute(plan) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute +getattr(self, '_do_%s' % instruction.__class__.__name__.lower(), +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall +result = method(**final_kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name +updated_domain_name = self._update_domain_name_v2(kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2 +'hosted_zone_id': result_data['HostedZoneId'], +KeyError: 'HostedZoneId'",KeyError +" def _create_domain_name(self, api_args): + # type: (Dict[str, Any]) -> DomainNameResponse + client = self._client('apigateway') + exceptions = ( + client.exceptions.TooManyRequestsException, + ) + result = self._call_client_method_with_retries( + client.create_domain_name, + api_args, max_attempts=6, + should_retry=lambda x: True, + retryable_exceptions=exceptions + ) + if result.get('regionalHostedZoneId'): + hosted_zone_id = result['regionalHostedZoneId'] + else: + hosted_zone_id = result['distributionHostedZoneId'] + + if result.get('regionalCertificateArn'): + certificate_arn = result['regionalCertificateArn'] + else: + certificate_arn = result['certificateArn'] + + if result.get('regionalDomainName') is not None: + alias_domain_name = result['regionalDomainName'] + else: + alias_domain_name = result['distributionDomainName'] + domain_name = { + 'domain_name': result['domainName'], + 'security_policy': result['securityPolicy'], + 'hosted_zone_id': hosted_zone_id, + 'certificate_arn': certificate_arn, + 'alias_domain_name': alias_domain_name, + } # type: DomainNameResponse + return domain_name"," def _create_domain_name(self, api_args): + # type: (Dict[str, Any]) -> Dict[str, Any] + client = self._client('apigateway') + exceptions = ( + client.exceptions.TooManyRequestsException, + ) + result = self._call_client_method_with_retries( + client.create_domain_name, + api_args, max_attempts=6, + should_retry=lambda x: True, + retryable_exceptions=exceptions + ) + domain_name = { + 'domain_name': result['domainName'], + 'endpoint_configuration': result['endpointConfiguration'], + 'security_policy': result['securityPolicy'], + } + if result.get('regionalHostedZoneId'): + domain_name['hosted_zone_id'] = result['regionalHostedZoneId'] + else: + domain_name['hosted_zone_id'] = result['distributionHostedZoneId'] + + if result.get('regionalCertificateArn'): + domain_name['certificate_arn'] = result['regionalCertificateArn'] + else: + domain_name['certificate_arn'] = result['certificateArn'] + + if result.get('regionalDomainName') is not None: + domain_name['alias_domain_name'] = result['regionalDomainName'] + else: + domain_name['alias_domain_name'] = result['distributionDomainName'] + return domain_name","[{'piece_type': 'error message', 'piece_content': 'Updating custom domain name: api.transferbank.com.br\\nTraceback (most recent call last):\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main\\nreturn cli(obj={})\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main\\nrv = self.invoke(ctx)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func\\nreturn f(get_current_context(), *args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy\\ndeployed_values = d.deploy(config, chalice_stage_name=stage)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy\\nreturn self._deploy(config, chalice_stage_name)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy\\nself._executor.execute(plan)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute\\ngetattr(self, \\'_do_%s\\' % instruction.__class__.__name__.lower(),\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall\\nresult = method(**final_kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name\\nupdated_domain_name = self._update_domain_name_v2(kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2\\n\\'hosted_zone_id\\': result_data[\\'HostedZoneId\\'],\\nKeyError: \\'HostedZoneId\\''}, {'piece_type': 'other', 'piece_content': '""websocket_api_custom_domain"": {\\n""domain_name"": ""api.transferbank.com.br"",\\n""certificate_arn"": ""arn:aws:acm:us-east-1:073289305372:certificate/d995959e-6f7d-4fcb-9c56-bf370ca1a382"",\\n""url_prefix"": ""tb_wst_channel_manager""\\n},'}]","Updating custom domain name: api.transferbank.com.br +Traceback (most recent call last): +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main +return cli(obj={}) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__ +return self.main(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main +rv = self.invoke(ctx) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke +return callback(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func +return f(get_current_context(), *args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy +deployed_values = d.deploy(config, chalice_stage_name=stage) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy +return self._deploy(config, chalice_stage_name) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy +self._executor.execute(plan) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute +getattr(self, '_do_%s' % instruction.__class__.__name__.lower(), +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall +result = method(**final_kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name +updated_domain_name = self._update_domain_name_v2(kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2 +'hosted_zone_id': result_data['HostedZoneId'], +KeyError: 'HostedZoneId'",KeyError +" def _create_domain_name_v2(self, api_args): + # type: (Dict[str, Any]) -> DomainNameResponse + client = self._client('apigatewayv2') + exceptions = ( + client.exceptions.TooManyRequestsException, + ) + result = self._call_client_method_with_retries( + client.create_domain_name, + api_args, max_attempts=6, + should_retry=lambda x: True, + retryable_exceptions=exceptions + ) + result_data = result['DomainNameConfigurations'][0] + domain_name = { + 'domain_name': result['DomainName'], + 'alias_domain_name': result_data['ApiGatewayDomainName'], + 'security_policy': result_data['SecurityPolicy'], + 'hosted_zone_id': result_data['HostedZoneId'], + 'certificate_arn': result_data['CertificateArn'] + } # type: DomainNameResponse + return domain_name"," def _create_domain_name_v2(self, api_args): + # type: (Dict[str, Any]) -> Dict[str, Any] + client = self._client('apigatewayv2') + exceptions = ( + client.exceptions.TooManyRequestsException, + ) + result = self._call_client_method_with_retries( + client.create_domain_name, + api_args, max_attempts=6, + should_retry=lambda x: True, + retryable_exceptions=exceptions + ) + result_data = result['DomainNameConfigurations'][0] + domain_name = { + 'domain_name': result_data['ApiGatewayDomainName'], + 'endpoint_type': result_data['EndpointType'], + 'security_policy': result_data['SecurityPolicy'], + 'hosted_zone_id': result_data['HostedZoneId'], + 'certificate_arn': result_data['CertificateArn'] + } + return domain_name","[{'piece_type': 'error message', 'piece_content': 'Updating custom domain name: api.transferbank.com.br\\nTraceback (most recent call last):\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main\\nreturn cli(obj={})\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main\\nrv = self.invoke(ctx)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func\\nreturn f(get_current_context(), *args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy\\ndeployed_values = d.deploy(config, chalice_stage_name=stage)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy\\nreturn self._deploy(config, chalice_stage_name)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy\\nself._executor.execute(plan)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute\\ngetattr(self, \\'_do_%s\\' % instruction.__class__.__name__.lower(),\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall\\nresult = method(**final_kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name\\nupdated_domain_name = self._update_domain_name_v2(kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2\\n\\'hosted_zone_id\\': result_data[\\'HostedZoneId\\'],\\nKeyError: \\'HostedZoneId\\''}, {'piece_type': 'other', 'piece_content': '""websocket_api_custom_domain"": {\\n""domain_name"": ""api.transferbank.com.br"",\\n""certificate_arn"": ""arn:aws:acm:us-east-1:073289305372:certificate/d995959e-6f7d-4fcb-9c56-bf370ca1a382"",\\n""url_prefix"": ""tb_wst_channel_manager""\\n},'}]","Updating custom domain name: api.transferbank.com.br +Traceback (most recent call last): +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main +return cli(obj={}) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__ +return self.main(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main +rv = self.invoke(ctx) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke +return callback(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func +return f(get_current_context(), *args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy +deployed_values = d.deploy(config, chalice_stage_name=stage) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy +return self._deploy(config, chalice_stage_name) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy +self._executor.execute(plan) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute +getattr(self, '_do_%s' % instruction.__class__.__name__.lower(), +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall +result = method(**final_kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name +updated_domain_name = self._update_domain_name_v2(kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2 +'hosted_zone_id': result_data['HostedZoneId'], +KeyError: 'HostedZoneId'",KeyError +" def update_domain_name(self, + protocol, # type: str + domain_name, # type: str + endpoint_type, # type: str + certificate_arn, # type: str + security_policy=None, # type: Optional[str] + tags=None, # type: StrMap + ): + # type: (...) -> DomainNameResponse + if protocol == 'HTTP': + patch_operations = self.get_custom_domain_patch_operations( + certificate_arn, + endpoint_type, + security_policy, + ) + updated_domain_name = self._update_domain_name( + domain_name, patch_operations + ) + elif protocol == 'WEBSOCKET': + kwargs = self.get_custom_domain_params_v2( + domain_name=domain_name, + endpoint_type=endpoint_type, + security_policy=security_policy, + certificate_arn=certificate_arn, + ) + updated_domain_name = self._update_domain_name_v2(kwargs) + else: + raise ValueError('Unsupported protocol value.') + resource_arn = 'arn:aws:apigateway:{region_name}:' \\ + ':/domainnames/{domain_name}'\\ + .format( + region_name=self.region_name, + domain_name=domain_name + ) + self._update_resource_tags(resource_arn, tags) + return updated_domain_name"," def update_domain_name(self, + protocol, # type: str + domain_name, # type: str + endpoint_type, # type: str + certificate_arn, # type: str + security_policy=None, # type: Optional[str] + tags=None, # type: StrMap + ): + # type: (...) -> Dict[str, Any] + if protocol == 'HTTP': + patch_operations = self.get_custom_domain_patch_operations( + certificate_arn, + endpoint_type, + security_policy, + ) + updated_domain_name = self._update_domain_name( + domain_name, patch_operations + ) + elif protocol == 'WEBSOCKET': + kwargs = self.get_custom_domain_params_v2( + domain_name=domain_name, + endpoint_type=endpoint_type, + security_policy=security_policy, + certificate_arn=certificate_arn, + ) + updated_domain_name = self._update_domain_name_v2(kwargs) + else: + raise ValueError('Unsupported protocol value.') + resource_arn = 'arn:aws:apigateway:{region_name}:' \\ + ':/domainnames/{domain_name}'\\ + .format( + region_name=self.region_name, + domain_name=domain_name + ) + self._update_resource_tags(resource_arn, tags) + return updated_domain_name","[{'piece_type': 'error message', 'piece_content': 'Updating custom domain name: api.transferbank.com.br\\nTraceback (most recent call last):\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main\\nreturn cli(obj={})\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main\\nrv = self.invoke(ctx)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func\\nreturn f(get_current_context(), *args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy\\ndeployed_values = d.deploy(config, chalice_stage_name=stage)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy\\nreturn self._deploy(config, chalice_stage_name)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy\\nself._executor.execute(plan)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute\\ngetattr(self, \\'_do_%s\\' % instruction.__class__.__name__.lower(),\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall\\nresult = method(**final_kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name\\nupdated_domain_name = self._update_domain_name_v2(kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2\\n\\'hosted_zone_id\\': result_data[\\'HostedZoneId\\'],\\nKeyError: \\'HostedZoneId\\''}, {'piece_type': 'other', 'piece_content': '""websocket_api_custom_domain"": {\\n""domain_name"": ""api.transferbank.com.br"",\\n""certificate_arn"": ""arn:aws:acm:us-east-1:073289305372:certificate/d995959e-6f7d-4fcb-9c56-bf370ca1a382"",\\n""url_prefix"": ""tb_wst_channel_manager""\\n},'}]","Updating custom domain name: api.transferbank.com.br +Traceback (most recent call last): +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main +return cli(obj={}) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__ +return self.main(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main +rv = self.invoke(ctx) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke +return callback(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func +return f(get_current_context(), *args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy +deployed_values = d.deploy(config, chalice_stage_name=stage) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy +return self._deploy(config, chalice_stage_name) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy +self._executor.execute(plan) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute +getattr(self, '_do_%s' % instruction.__class__.__name__.lower(), +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall +result = method(**final_kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name +updated_domain_name = self._update_domain_name_v2(kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2 +'hosted_zone_id': result_data['HostedZoneId'], +KeyError: 'HostedZoneId'",KeyError +" def _update_domain_name(self, custom_domain_name, patch_operations): + # type: (str, List[Dict[str, str]]) -> DomainNameResponse + client = self._client('apigateway') + exceptions = ( + client.exceptions.TooManyRequestsException, + ) + result = {} + for patch_operation in patch_operations: + api_args = { + 'domainName': custom_domain_name, + 'patchOperations': [patch_operation] + } + response = self._call_client_method_with_retries( + client.update_domain_name, + api_args, max_attempts=6, + should_retry=lambda x: True, + retryable_exceptions=exceptions + ) + result.update(response) + + if result.get('regionalCertificateArn'): + certificate_arn = result['regionalCertificateArn'] + else: + certificate_arn = result['certificateArn'] + + if result.get('regionalHostedZoneId'): + hosted_zone_id = result['regionalHostedZoneId'] + else: + hosted_zone_id = result['distributionHostedZoneId'] + + if result.get('regionalDomainName') is not None: + alias_domain_name = result['regionalDomainName'] + else: + alias_domain_name = result['distributionDomainName'] + domain_name = { + 'domain_name': result['domainName'], + 'security_policy': result['securityPolicy'], + 'certificate_arn': certificate_arn, + 'hosted_zone_id': hosted_zone_id, + 'alias_domain_name': alias_domain_name + } # type: DomainNameResponse + return domain_name"," def _update_domain_name(self, custom_domain_name, patch_operations): + # type: (str, List[Dict[str, str]]) -> Dict[str, Any] + client = self._client('apigateway') + exceptions = ( + client.exceptions.TooManyRequestsException, + ) + result = {} + for patch_operation in patch_operations: + api_args = { + 'domainName': custom_domain_name, + 'patchOperations': [patch_operation] + } + response = self._call_client_method_with_retries( + client.update_domain_name, + api_args, max_attempts=6, + should_retry=lambda x: True, + retryable_exceptions=exceptions + ) + result.update(response) + + domain_name = { + 'domain_name': result['domainName'], + 'endpoint_configuration': result['endpointConfiguration'], + 'security_policy': result['securityPolicy'], + } + if result.get('regionalCertificateArn'): + domain_name['certificate_arn'] = result['regionalCertificateArn'] + else: + domain_name['certificate_arn'] = result['certificateArn'] + + if result.get('regionalHostedZoneId'): + domain_name['hosted_zone_id'] = result['regionalHostedZoneId'] + else: + domain_name['hosted_zone_id'] = result['distributionHostedZoneId'] + + if result.get('regionalDomainName') is not None: + domain_name['alias_domain_name'] = result['regionalDomainName'] + else: + domain_name['alias_domain_name'] = result['distributionDomainName'] + return domain_name","[{'piece_type': 'error message', 'piece_content': 'Updating custom domain name: api.transferbank.com.br\\nTraceback (most recent call last):\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main\\nreturn cli(obj={})\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main\\nrv = self.invoke(ctx)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func\\nreturn f(get_current_context(), *args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy\\ndeployed_values = d.deploy(config, chalice_stage_name=stage)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy\\nreturn self._deploy(config, chalice_stage_name)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy\\nself._executor.execute(plan)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute\\ngetattr(self, \\'_do_%s\\' % instruction.__class__.__name__.lower(),\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall\\nresult = method(**final_kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name\\nupdated_domain_name = self._update_domain_name_v2(kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2\\n\\'hosted_zone_id\\': result_data[\\'HostedZoneId\\'],\\nKeyError: \\'HostedZoneId\\''}, {'piece_type': 'other', 'piece_content': '""websocket_api_custom_domain"": {\\n""domain_name"": ""api.transferbank.com.br"",\\n""certificate_arn"": ""arn:aws:acm:us-east-1:073289305372:certificate/d995959e-6f7d-4fcb-9c56-bf370ca1a382"",\\n""url_prefix"": ""tb_wst_channel_manager""\\n},'}]","Updating custom domain name: api.transferbank.com.br +Traceback (most recent call last): +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main +return cli(obj={}) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__ +return self.main(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main +rv = self.invoke(ctx) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke +return callback(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func +return f(get_current_context(), *args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy +deployed_values = d.deploy(config, chalice_stage_name=stage) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy +return self._deploy(config, chalice_stage_name) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy +self._executor.execute(plan) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute +getattr(self, '_do_%s' % instruction.__class__.__name__.lower(), +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall +result = method(**final_kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name +updated_domain_name = self._update_domain_name_v2(kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2 +'hosted_zone_id': result_data['HostedZoneId'], +KeyError: 'HostedZoneId'",KeyError +" def _update_domain_name_v2(self, api_args): + # type: (Dict[str, Any]) -> DomainNameResponse + client = self._client('apigatewayv2') + exceptions = ( + client.exceptions.TooManyRequestsException, + ) + + result = self._call_client_method_with_retries( + client.update_domain_name, + api_args, max_attempts=6, + should_retry=lambda x: True, + retryable_exceptions=exceptions + ) + result_data = result['DomainNameConfigurations'][0] + domain_name = { + 'domain_name': result['DomainName'], + 'alias_domain_name': result_data['ApiGatewayDomainName'], + 'security_policy': result_data['SecurityPolicy'], + 'hosted_zone_id': result_data['HostedZoneId'], + 'certificate_arn': result_data['CertificateArn'] + } # type: DomainNameResponse + return domain_name"," def _update_domain_name_v2(self, api_args): + # type: (Dict[str, Any]) -> Dict[str, Any] + client = self._client('apigatewayv2') + exceptions = ( + client.exceptions.TooManyRequestsException, + ) + + result = self._call_client_method_with_retries( + client.update_domain_name, + api_args, max_attempts=6, + should_retry=lambda x: True, + retryable_exceptions=exceptions + ) + result_data = result['DomainNameConfigurations'][0] + domain_name = { + 'domain_name': result['DomainName'], + 'endpoint_configuration': result_data['EndpointType'], + 'security_policy': result_data['SecurityPolicy'], + 'hosted_zone_id': result_data['HostedZoneId'], + 'certificate_arn': result_data['CertificateArn'] + } + return domain_name","[{'piece_type': 'error message', 'piece_content': 'Updating custom domain name: api.transferbank.com.br\\nTraceback (most recent call last):\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main\\nreturn cli(obj={})\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main\\nrv = self.invoke(ctx)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func\\nreturn f(get_current_context(), *args, **kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy\\ndeployed_values = d.deploy(config, chalice_stage_name=stage)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy\\nreturn self._deploy(config, chalice_stage_name)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy\\nself._executor.execute(plan)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute\\ngetattr(self, \\'_do_%s\\' % instruction.__class__.__name__.lower(),\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall\\nresult = method(**final_kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name\\nupdated_domain_name = self._update_domain_name_v2(kwargs)\\nFile ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2\\n\\'hosted_zone_id\\': result_data[\\'HostedZoneId\\'],\\nKeyError: \\'HostedZoneId\\''}, {'piece_type': 'other', 'piece_content': '""websocket_api_custom_domain"": {\\n""domain_name"": ""api.transferbank.com.br"",\\n""certificate_arn"": ""arn:aws:acm:us-east-1:073289305372:certificate/d995959e-6f7d-4fcb-9c56-bf370ca1a382"",\\n""url_prefix"": ""tb_wst_channel_manager""\\n},'}]","Updating custom domain name: api.transferbank.com.br +Traceback (most recent call last): +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 646, in main +return cli(obj={}) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 829, in __call__ +return self.main(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 782, in main +rv = self.invoke(ctx) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1259, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 1066, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py"", line 610, in invoke +return callback(*args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py"", line 21, in new_func +return f(get_current_context(), *args, **kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py"", line 206, in deploy +deployed_values = d.deploy(config, chalice_stage_name=stage) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 374, in deploy +return self._deploy(config, chalice_stage_name) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py"", line 390, in _deploy +self._executor.execute(plan) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 42, in execute +getattr(self, '_do_%s' % instruction.__class__.__name__.lower(), +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py"", line 55, in _do_apicall +result = method(**final_kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 702, in update_domain_name +updated_domain_name = self._update_domain_name_v2(kwargs) +File ""/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py"", line 802, in _update_domain_name_v2 +'hosted_zone_id': result_data['HostedZoneId'], +KeyError: 'HostedZoneId'",KeyError +" def iter_log_events(self, log_group_name, interleaved=True): + # type: (str, bool) -> Iterator[Dict[str, Any]] + logs = self._client('logs') + paginator = logs.get_paginator('filter_log_events') + pages = paginator.paginate(logGroupName=log_group_name, + interleaved=True) + try: + for log_message in self._iter_log_messages(pages): + yield log_message + except logs.exceptions.ResourceNotFoundException: + # If the lambda function exists but has not been invoked yet, + # it's possible that the log group does not exist and we'll get + # a ResourceNotFoundException. If this happens we return instead + # of propagating an exception back to the user. + pass"," def iter_log_events(self, log_group_name, interleaved=True): + # type: (str, bool) -> Iterator[Dict[str, Any]] + logs = self._client('logs') + paginator = logs.get_paginator('filter_log_events') + for page in paginator.paginate(logGroupName=log_group_name, + interleaved=True): + events = page['events'] + for event in events: + # timestamp is modeled as a 'long', so we'll + # convert to a datetime to make it easier to use + # in python. + event['ingestionTime'] = self._convert_to_datetime( + event['ingestionTime']) + event['timestamp'] = self._convert_to_datetime( + event['timestamp']) + yield event","[{'piece_type': 'error message', 'piece_content': '$ cat app.py\\nfrom chalice import Chalice\\n\\napp = Chalice(app_name=\\'testlambda\\')\\n\\n\\n@app.lambda_function()\\ndef index(event, context):\\nprint(""foo bar baz"")\\nreturn {\\'hello\\': \\'world\\'}\\n\\n$ chalice deploy\\n...\\n$ chalice logs -n index\\nTraceback (most recent call last):\\nFile ""chalice/chalice/cli/__init__.py"", line 485, in main\\nreturn cli(obj={})\\nFile "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py"", line 722, in __call__\\nreturn self.main(*args, **kwargs)\\nFile "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py"", line 697, in main\\nrv = self.invoke(ctx)\\nFile "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py"", line 1066, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py"", line 895, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py"", line 535, in invoke\\nreturn callback(*args, **kwargs)\\nFile "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/decorators.py"", line 17, in new_func\\nreturn f(get_current_context(), *args, **kwargs)\\nFile ""chalice/chalice/cli/__init__.py"", line 292, in logs\\nsys.stdout)\\nFile ""chalice/chalice/logs.py"", line 19, in display_logs\\nfor event in events:\\nFile ""S File ""S File ""S File ""S File ""S File ""rc File ""/Users/jamessarient.py"", line 677, in iter_log_events\\nfor log_message in self._iter_log_messages(pages):\\nFile ""chalice/chalice/awsclient.py"", line 681, in _iter_log_messages\\nfor page in pages:\\nFile "".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/paginate.py"", line 255, in __iter__\\nresponse = self._make_request(current_kwargs)\\nFile "".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/paginate.py"", line 332, in _make_request\\nreturn self._method(**current_kwargs)\\nFile "".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/client.py"", line 357, in _api_call\\nreturn self._make_api_call(operation_name, kwargs)\\nFile "".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/client.py"", line 661, in _make_api_call\\nraise error_class(parsed_response, operation_name)\\nbotocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the FilterLogEvents operation: The specified log group does not exist.'}]","$ cat app.py +from chalice import Chalice + +app = Chalice(app_name='testlambda') + + +@app.lambda_function() +def index(event, context): +print(""foo bar baz"") +return {'hello': 'world'} + +$ chalice deploy +... +$ chalice logs -n index +Traceback (most recent call last): +File ""chalice/chalice/cli/__init__.py"", line 485, in main +return cli(obj={}) +File "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py"", line 722, in __call__ +return self.main(*args, **kwargs) +File "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py"", line 697, in main +rv = self.invoke(ctx) +File "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py"", line 1066, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py"", line 895, in invoke +return ctx.invoke(self.callback, **ctx.params) +File "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py"", line 535, in invoke +return callback(*args, **kwargs) +File "".virtualenvs/chalice-37/lib/python3.7/site-packages/click/decorators.py"", line 17, in new_func +return f(get_current_context(), *args, **kwargs) +File ""chalice/chalice/cli/__init__.py"", line 292, in logs +sys.stdout) +File ""chalice/chalice/logs.py"", line 19, in display_logs +for event in events: +File ""S File ""S File ""S File ""S File ""S File ""rc File ""/Users/jamessarient.py"", line 677, in iter_log_events +for log_message in self._iter_log_messages(pages): +File ""chalice/chalice/awsclient.py"", line 681, in _iter_log_messages +for page in pages: +File "".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/paginate.py"", line 255, in __iter__ +response = self._make_request(current_kwargs) +File "".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/paginate.py"", line 332, in _make_request +return self._method(**current_kwargs) +File "".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/client.py"", line 357, in _api_call +return self._make_api_call(operation_name, kwargs) +File "".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/client.py"", line 661, in _make_api_call +raise error_class(parsed_response, operation_name) +botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the FilterLogEvents operation: The specified log group does not exist.",botocore.errorfactory.ResourceNotFoundException +" def __init__(self, osutils=None, import_string=None): + # type: (Optional[OSUtils], OptStr) -> None + if osutils is None: + osutils = OSUtils() + self._osutils = osutils + if import_string is None: + import_string = pip_import_string() + self._import_string = import_string"," def __init__(self, osutils=None): + # type: (Optional[OSUtils]) -> None + if osutils is None: + osutils = OSUtils() + self._osutils = osutils","[{'piece_type': 'error message', 'piece_content': 'chalice.deploy.packager.PackageDownloadError: Traceback (most recent call last):\\nFile """", line 1, in \\nAttributeError: module \\'pip\\' has no attribute \\'main\\''}]","chalice.deploy.packager.PackageDownloadError: Traceback (most recent call last): +File """", line 1, in +AttributeError: module 'pip' has no attribute 'main'",AttributeError +" def main(self, args, env_vars=None, shim=None): + # type: (List[str], EnvVars, OptStr) -> Tuple[int, Optional[bytes]] + if env_vars is None: + env_vars = self._osutils.environ() + if shim is None: + shim = '' + python_exe = sys.executable + run_pip = ( + 'import sys; %s; sys.exit(main(%s))' + ) % (self._import_string, args) + exec_string = '%s%s' % (shim, run_pip) + invoke_pip = [python_exe, '-c', exec_string] + p = self._osutils.popen(invoke_pip, + stdout=self._osutils.pipe, + stderr=self._osutils.pipe, + env=env_vars) + _, err = p.communicate() + rc = p.returncode + return rc, err"," def main(self, args, env_vars=None, shim=None): + # type: (List[str], EnvVars, OptStr) -> Tuple[int, Optional[bytes]] + if env_vars is None: + env_vars = self._osutils.environ() + if shim is None: + shim = '' + python_exe = sys.executable + run_pip = 'import pip, sys; sys.exit(pip.main(%s))' % args + exec_string = '%s%s' % (shim, run_pip) + invoke_pip = [python_exe, '-c', exec_string] + p = subprocess.Popen(invoke_pip, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=env_vars) + _, err = p.communicate() + rc = p.returncode + return rc, err","[{'piece_type': 'error message', 'piece_content': 'chalice.deploy.packager.PackageDownloadError: Traceback (most recent call last):\\nFile """", line 1, in \\nAttributeError: module \\'pip\\' has no attribute \\'main\\''}]","chalice.deploy.packager.PackageDownloadError: Traceback (most recent call last): +File """", line 1, in +AttributeError: module 'pip' has no attribute 'main'",AttributeError +" def index(self, locale): + if locale not in self.appbuilder.bm.languages: + abort(404, description=""Locale not supported."") + session[""locale""] = locale + refresh() + self.update_redirect() + return redirect(self.get_redirect())"," def index(self, locale): + session[""locale""] = locale + refresh() + self.update_redirect() + return redirect(self.get_redirect())","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\app.py"", line 2464, in __call__\\nreturn self.wsgi_app(environ, start_response)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\app.py"", line 2450, in wsgi_app\\nresponse = self.handle_exception(e)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\app.py"", line 1867, in handle_exception\\nreraise(exc_type, exc_value, tb)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\_compat.py"", line 39, in reraise\\nraise value\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\app.py"", line 2447, in wsgi_app\\nresponse = self.full_dispatch_request()\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\app.py"", line 1952, in full_dispatch_request\\nrv = self.handle_user_exception(e)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\app.py"", line 1821, in handle_user_exception\\nreraise(exc_type, exc_value, tb)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\_compat.py"", line 39, in reraise\\nraise value\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\app.py"", line 1950, in full_dispatch_request\\nrv = self.dispatch_request()\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\app.py"", line 1936, in dispatch_request\\nreturn self.view_functions[rule.endpoint](**req.view_args)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask_appbuilder\\\\views.py"", line 41, in index\\nreturn self.render_template(self.index_template, appbuilder=self.appbuilder)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask_appbuilder\\\\baseviews.py"", line 280, in render_template\\nreturn render_template(\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\templating.py"", line 137, in render_template\\nreturn _render(\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask\\\\templating.py"", line 120, in _render\\nrv = template.render(context)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\jinja2\\\\environment.py"", line 1090, in render\\nself.environment.handle_exception()\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\jinja2\\\\environment.py"", line 832, in handle_exception\\nreraise(*rewrite_traceback_stack(source=source))\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\jinja2\\\\_compat.py"", line 28, in reraise\\nraise value.with_traceback(tb)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\app\\\\templates\\\\index.html"", line 1, in top-level template code\\n{% extends ""appbuilder/base.html"" %}\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask_appbuilder\\\\templates\\\\appbuilder\\\\base.html"", line 1, in top-level template code\\n{% extends base_template %}\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\app\\\\templates\\\\mybase.html"", line 1, in top-level template code\\n{% extends \\'appbuilder/baselayout.html\\' %}\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask_appbuilder\\\\templates\\\\appbuilder\\\\baselayout.html"", line 2, in top-level template code\\n{% import \\'appbuilder/baselib.html\\' as baselib %}\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask_appbuilder\\\\templates\\\\appbuilder\\\\init.html"", line 46, in top-level template code\\n{% block body %}\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask_appbuilder\\\\templates\\\\appbuilder\\\\baselayout.html"", line 5, in block ""body""\\n{% include \\'appbuilder/general/confirm.html\\' %}\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask_appbuilder\\\\templates\\\\appbuilder\\\\general\\\\confirm.html"", line 6, in top-level template code\\n{{_(\\'User confirmation needed\\')}}\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\jinja2\\\\ext.py"", line 144, in _gettext_alias\\nreturn __context.call(__context.resolve(""gettext""), *args, **kwargs)\\nFile ""C:\\\\Users\\\\myuserPycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\jinja2\\\\ext.py"", line 150, in gettext\\nrv = __context.call(func, __string)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask_babel\\\\__init__.py"", line 110, in \\nlambda x: get_translations().ugettext(x),\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask_babel\\\\__init__.py"", line 221, in get_translations\\n[get_locale()],\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\flask_babel\\\\__init__.py"", line 255, in get_locale\\nlocale = Locale.parse(rv)\\nFile ""C:\\\\Users\\\\myuser\\\\PycharmProjects\\\\FAB-test-site\\\\venv\\\\Lib\\\\site-packages\\\\babel\\\\core.py"", line 331, in parse\\nraise UnknownLocaleError(input_id)\\nbabel.core.UnknownLocaleError: unknown locale \\'nonexistentlanguage\\''}]","Traceback (most recent call last): +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\app.py"", line 2464, in __call__ +return self.wsgi_app(environ, start_response) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\app.py"", line 2450, in wsgi_app +response = self.handle_exception(e) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\app.py"", line 1867, in handle_exception +reraise(exc_type, exc_value, tb) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\_compat.py"", line 39, in reraise +raise value +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\app.py"", line 2447, in wsgi_app +response = self.full_dispatch_request() +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\app.py"", line 1952, in full_dispatch_request +rv = self.handle_user_exception(e) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\app.py"", line 1821, in handle_user_exception +reraise(exc_type, exc_value, tb) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\_compat.py"", line 39, in reraise +raise value +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\app.py"", line 1950, in full_dispatch_request +rv = self.dispatch_request() +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\app.py"", line 1936, in dispatch_request +return self.view_functions[rule.endpoint](**req.view_args) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask_appbuilder\\views.py"", line 41, in index +return self.render_template(self.index_template, appbuilder=self.appbuilder) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask_appbuilder\\baseviews.py"", line 280, in render_template +return render_template( +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\templating.py"", line 137, in render_template +return _render( +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask\\templating.py"", line 120, in _render +rv = template.render(context) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\jinja2\\environment.py"", line 1090, in render +self.environment.handle_exception() +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\jinja2\\environment.py"", line 832, in handle_exception +reraise(*rewrite_traceback_stack(source=source)) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\jinja2\\_compat.py"", line 28, in reraise +raise value.with_traceback(tb) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\app\\templates\\index.html"", line 1, in top-level template code +{% extends ""appbuilder/base.html"" %} +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask_appbuilder\\templates\\appbuilder\\base.html"", line 1, in top-level template code +{% extends base_template %} +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\app\\templates\\mybase.html"", line 1, in top-level template code +{% extends 'appbuilder/baselayout.html' %} +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask_appbuilder\\templates\\appbuilder\\baselayout.html"", line 2, in top-level template code +{% import 'appbuilder/baselib.html' as baselib %} +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask_appbuilder\\templates\\appbuilder\\init.html"", line 46, in top-level template code +{% block body %} +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask_appbuilder\\templates\\appbuilder\\baselayout.html"", line 5, in block ""body"" +{% include 'appbuilder/general/confirm.html' %} +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask_appbuilder\\templates\\appbuilder\\general\\confirm.html"", line 6, in top-level template code +{{_('User confirmation needed')}} +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\jinja2\\ext.py"", line 144, in _gettext_alias +return __context.call(__context.resolve(""gettext""), *args, **kwargs) +File ""C:\\Users\\myuserPycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\jinja2\\ext.py"", line 150, in gettext +rv = __context.call(func, __string) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask_babel\\__init__.py"", line 110, in +lambda x: get_translations().ugettext(x), +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask_babel\\__init__.py"", line 221, in get_translations +[get_locale()], +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\flask_babel\\__init__.py"", line 255, in get_locale +locale = Locale.parse(rv) +File ""C:\\Users\\myuser\\PycharmProjects\\FAB-test-site\\venv\\Lib\\site-packages\\babel\\core.py"", line 331, in parse +raise UnknownLocaleError(input_id) +babel.core.UnknownLocaleError: unknown locale 'nonexistentlanguage'",babel.core.UnknownLocaleError +" def login(self, flag=True): + @self.appbuilder.sm.oid.loginhandler + def login_handler(self): + if g.user is not None and g.user.is_authenticated: + return redirect(self.appbuilder.get_url_for_index) + form = LoginForm_oid() + if form.validate_on_submit(): + session[""remember_me""] = form.remember_me.data + return self.appbuilder.sm.oid.try_login( + form.openid.data, + ask_for=self.oid_ask_for, + ask_for_optional=self.oid_ask_for_optional, + ) + return self.render_template( + self.login_template, + title=self.title, + form=form, + providers=self.appbuilder.sm.openid_providers, + appbuilder=self.appbuilder, + ) + + @self.appbuilder.sm.oid.after_login + def after_login(resp): + if resp.email is None or resp.email == """": + flash(as_unicode(self.invalid_login_message), ""warning"") + return redirect(self.appbuilder.get_url_for_login) + user = self.appbuilder.sm.auth_user_oid(resp.email) + if user is None: + flash(as_unicode(self.invalid_login_message), ""warning"") + return redirect(self.appbuilder.get_url_for_login) + remember_me = False + if ""remember_me"" in session: + remember_me = session[""remember_me""] + session.pop(""remember_me"", None) + + login_user(user, remember=remember_me) + return redirect(self.appbuilder.get_url_for_index) + + return login_handler(self)"," def login(self, flag=True): + @self.appbuilder.sm.oid.loginhandler + def login_handler(self): + if g.user is not None and g.user.is_authenticated: + return redirect(self.appbuilder.get_url_for_index) + form = LoginForm_oid() + if form.validate_on_submit(): + session[""remember_me""] = form.remember_me.data + return self.appbuilder.sm.oid.try_login( + form.openid.data, + ask_for=self.oid_ask_for, + ask_for_optional=self.oid_ask_for_optional, + ) + return self.render_template( + self.login_template, + title=self.title, + form=form, + providers=self.appbuilder.sm.openid_providers, + appbuilder=self.appbuilder, + ) + + @self.appbuilder.sm.oid.after_login + def after_login(resp): + if resp.email is None or resp.email == """": + flash(as_unicode(self.invalid_login_message), ""warning"") + return redirect(""login"") + user = self.appbuilder.sm.auth_user_oid(resp.email) + if user is None: + flash(as_unicode(self.invalid_login_message), ""warning"") + return redirect(""login"") + remember_me = False + if ""remember_me"" in session: + remember_me = session[""remember_me""] + session.pop(""remember_me"", None) + + login_user(user, remember=remember_me) + return redirect(self.appbuilder.get_url_for_index) + + return login_handler(self)","[{'piece_type': 'source code', 'piece_content': ""resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()\\nKeyError: 'login'""}, {'piece_type': 'error message', 'piece_content': 'File ""/home/aman/superset/lib/python3.6/site-packages/flask_appbuilder/security/views.py"", line 678, in oauth_authorized\\nresp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()\\nKeyError: \\'login\\''}, {'piece_type': 'other', 'piece_content': 'ROW_LIMIT = 5000\\nSUPERSET_WORKERS = 4\\nSUPERSET_WEBSERVER_PORT = 8088\\nimport os\\nfrom flask import Flask\\n\\nimport logging\\nfrom flask_appbuilder.security.manager import AUTH_OID, AUTH_REMOTE_USER, AUTH_DB, AUTH_LDAP, AUTH_OAUTH\\nfrom superset.security import SupersetSecurityManager\\nimport logging\\nfrom flask_appbuilder import SQLA, AppBuilder\\n\\nclass CustomSsoSecurityManager(SupersetSecurityManager):\\n#@appbuilder.sm.oauth_user_info_getter\\ndef oauth_user_info(self, provider, response=None):\\nif provider == \\'boilerplate\\':\\n\\nres = self.appbuilder.sm.oauth_remotes[provider].get(\\'userinfo\\')\\nprint(res)\\nif res.status != 200:\\nlogger.error(\\'Failed to obtain user info: %s\\', res.data)\\nreturn\\nme = res.data\\nlogger.debug("" user_data: %s"", me)\\nprefix = \\'Superset\\'\\nreturn {\\n\\'username\\' : me[\\'email\\'],\\n\\'name\\' : me[\\'name\\'],\\n\\'email\\' : me[\\'email\\'],\\n\\'first_name\\': me[\\'given_name\\'],\\n\\'last_name\\': me[\\'family_name\\'],\\n}\\n\\n# from superset.security import SupersetSecurityManager\\n\\n# class CustomSsoSecurityManager(SupersetSecurityManager):\\n# #@appbuilder.sm.oauth_user_info\\n# def oauth_user_info(self, provider, response=None):\\n# logging.debug(""Oauth2 provider: {0}."".format(provider))\\n# if provider == \\'boilerplate\\':\\n# # As example, this line request a GET to base_url + \\'/\\' + userDetails with Bearer Authentication,\\n# # and expects that authorization server checks the token, and response with user details\\n# me = self.appbuilder.sm.oauth_remotes[provider].get(\\'userinfo\\').data\\n# logging.debug(""user_data: {0}"".format(me))\\n# return { \\'name\\' : me[\\'name\\'], \\'email\\' : me[\\'email\\'], \\'id\\' : me[\\'user_name\\'], \\'username\\' : me[\\'user_name\\'], \\'first_name\\':\\'\\', \\'last_name\\':\\'\\'}\\n\\nCUSTOM_SECURITY_MANAGER = CustomSsoSecurityManager\\nAUTH_TYPE = AUTH_OAUTH\\nAUTH_ROLE_PUBLIC = \\'Public\\'\\nAUTH_USER_REGISTRATION = True\\nAUTH_USER_REGISTRATION_ROLE = \\'Public\\'\\nCSRF_ENABLED = True\\nENABLE_PROXY_FIX = True\\nPREFERRED_URL_SCHEME = \\'https\\'\\n\\nOAUTH_PROVIDERS = [\\n\\n{\\n\\'name\\': \\'boilerplate\\',\\n#\\'whitelist\\': [\\'@company.com\\'],\\n\\'icon\\': \\'fa-google\\',\\n\\'token_key\\': \\'access_token\\',\\n\\'remote_app\\': {\\n\\'base_url\\': \\'https://www.googleapis.com/oauth2/v2/\\',\\n\\'request_token_params\\': {\\n#\\'scope\\': \\'email profile\\'\\n},\\n\\'request_token_url\\': None,\\n\\'access_token_url\\':\\'https://*****/backend/o/token/\\',\\n\\'authorize_url\\': \\'https://******/backend/o/authorize/\\',\\n\\'consumer_key\\': \\'kDFoe0pypcM6VuNBHbw5NTOXpuzX7dCU\\',\\n\\'consumer_secret\\': \\'SHLYleMGfuHyqNJvMI03RgRf4qIzfHvMf4GKOV43AzRVvc6v3IjIxTMvI5mOrjSq8YBkOasYKMiKWzltUQtCb5qZ0rHk\\'\\n}\\n}\\n]'}]","File ""/home/aman/superset/lib/python3.6/site-packages/flask_appbuilder/security/views.py"", line 678, in oauth_authorized +resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response() +KeyError: 'login'",KeyError +" def after_login(resp): + if resp.email is None or resp.email == """": + flash(as_unicode(self.invalid_login_message), ""warning"") + return redirect(self.appbuilder.get_url_for_login) + user = self.appbuilder.sm.auth_user_oid(resp.email) + if user is None: + flash(as_unicode(self.invalid_login_message), ""warning"") + return redirect(self.appbuilder.get_url_for_login) + remember_me = False + if ""remember_me"" in session: + remember_me = session[""remember_me""] + session.pop(""remember_me"", None) + + login_user(user, remember=remember_me) + return redirect(self.appbuilder.get_url_for_index)"," def after_login(resp): + if resp.email is None or resp.email == """": + flash(as_unicode(self.invalid_login_message), ""warning"") + return redirect(""login"") + user = self.appbuilder.sm.auth_user_oid(resp.email) + if user is None: + flash(as_unicode(self.invalid_login_message), ""warning"") + return redirect(""login"") + remember_me = False + if ""remember_me"" in session: + remember_me = session[""remember_me""] + session.pop(""remember_me"", None) + + login_user(user, remember=remember_me) + return redirect(self.appbuilder.get_url_for_index)","[{'piece_type': 'source code', 'piece_content': ""resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()\\nKeyError: 'login'""}, {'piece_type': 'error message', 'piece_content': 'File ""/home/aman/superset/lib/python3.6/site-packages/flask_appbuilder/security/views.py"", line 678, in oauth_authorized\\nresp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()\\nKeyError: \\'login\\''}, {'piece_type': 'other', 'piece_content': 'ROW_LIMIT = 5000\\nSUPERSET_WORKERS = 4\\nSUPERSET_WEBSERVER_PORT = 8088\\nimport os\\nfrom flask import Flask\\n\\nimport logging\\nfrom flask_appbuilder.security.manager import AUTH_OID, AUTH_REMOTE_USER, AUTH_DB, AUTH_LDAP, AUTH_OAUTH\\nfrom superset.security import SupersetSecurityManager\\nimport logging\\nfrom flask_appbuilder import SQLA, AppBuilder\\n\\nclass CustomSsoSecurityManager(SupersetSecurityManager):\\n#@appbuilder.sm.oauth_user_info_getter\\ndef oauth_user_info(self, provider, response=None):\\nif provider == \\'boilerplate\\':\\n\\nres = self.appbuilder.sm.oauth_remotes[provider].get(\\'userinfo\\')\\nprint(res)\\nif res.status != 200:\\nlogger.error(\\'Failed to obtain user info: %s\\', res.data)\\nreturn\\nme = res.data\\nlogger.debug("" user_data: %s"", me)\\nprefix = \\'Superset\\'\\nreturn {\\n\\'username\\' : me[\\'email\\'],\\n\\'name\\' : me[\\'name\\'],\\n\\'email\\' : me[\\'email\\'],\\n\\'first_name\\': me[\\'given_name\\'],\\n\\'last_name\\': me[\\'family_name\\'],\\n}\\n\\n# from superset.security import SupersetSecurityManager\\n\\n# class CustomSsoSecurityManager(SupersetSecurityManager):\\n# #@appbuilder.sm.oauth_user_info\\n# def oauth_user_info(self, provider, response=None):\\n# logging.debug(""Oauth2 provider: {0}."".format(provider))\\n# if provider == \\'boilerplate\\':\\n# # As example, this line request a GET to base_url + \\'/\\' + userDetails with Bearer Authentication,\\n# # and expects that authorization server checks the token, and response with user details\\n# me = self.appbuilder.sm.oauth_remotes[provider].get(\\'userinfo\\').data\\n# logging.debug(""user_data: {0}"".format(me))\\n# return { \\'name\\' : me[\\'name\\'], \\'email\\' : me[\\'email\\'], \\'id\\' : me[\\'user_name\\'], \\'username\\' : me[\\'user_name\\'], \\'first_name\\':\\'\\', \\'last_name\\':\\'\\'}\\n\\nCUSTOM_SECURITY_MANAGER = CustomSsoSecurityManager\\nAUTH_TYPE = AUTH_OAUTH\\nAUTH_ROLE_PUBLIC = \\'Public\\'\\nAUTH_USER_REGISTRATION = True\\nAUTH_USER_REGISTRATION_ROLE = \\'Public\\'\\nCSRF_ENABLED = True\\nENABLE_PROXY_FIX = True\\nPREFERRED_URL_SCHEME = \\'https\\'\\n\\nOAUTH_PROVIDERS = [\\n\\n{\\n\\'name\\': \\'boilerplate\\',\\n#\\'whitelist\\': [\\'@company.com\\'],\\n\\'icon\\': \\'fa-google\\',\\n\\'token_key\\': \\'access_token\\',\\n\\'remote_app\\': {\\n\\'base_url\\': \\'https://www.googleapis.com/oauth2/v2/\\',\\n\\'request_token_params\\': {\\n#\\'scope\\': \\'email profile\\'\\n},\\n\\'request_token_url\\': None,\\n\\'access_token_url\\':\\'https://*****/backend/o/token/\\',\\n\\'authorize_url\\': \\'https://******/backend/o/authorize/\\',\\n\\'consumer_key\\': \\'kDFoe0pypcM6VuNBHbw5NTOXpuzX7dCU\\',\\n\\'consumer_secret\\': \\'SHLYleMGfuHyqNJvMI03RgRf4qIzfHvMf4GKOV43AzRVvc6v3IjIxTMvI5mOrjSq8YBkOasYKMiKWzltUQtCb5qZ0rHk\\'\\n}\\n}\\n]'}]","File ""/home/aman/superset/lib/python3.6/site-packages/flask_appbuilder/security/views.py"", line 678, in oauth_authorized +resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response() +KeyError: 'login'",KeyError +" def oauth_authorized(self, provider): + log.debug(""Authorized init"") + resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response() + if resp is None: + flash(u""You denied the request to sign in."", ""warning"") + return redirect(self.appbuilder.get_url_for_login) + log.debug(""OAUTH Authorized resp: {0}"".format(resp)) + # Retrieves specific user info from the provider + try: + self.appbuilder.sm.set_oauth_session(provider, resp) + userinfo = self.appbuilder.sm.oauth_user_info(provider, resp) + except Exception as e: + log.error(""Error returning OAuth user info: {0}"".format(e)) + user = None + else: + log.debug(""User info retrieved from {0}: {1}"".format(provider, userinfo)) + # User email is not whitelisted + if provider in self.appbuilder.sm.oauth_whitelists: + whitelist = self.appbuilder.sm.oauth_whitelists[provider] + allow = False + for e in whitelist: + if re.search(e, userinfo[""email""]): + allow = True + break + if not allow: + flash(u""You are not authorized."", ""warning"") + return redirect(self.appbuilder.get_url_for_login) + else: + log.debug(""No whitelist for OAuth provider"") + user = self.appbuilder.sm.auth_user_oauth(userinfo) + + if user is None: + flash(as_unicode(self.invalid_login_message), ""warning"") + return redirect(self.appbuilder.get_url_for_login) + else: + login_user(user) + try: + state = jwt.decode( + request.args[""state""], + self.appbuilder.app.config[""SECRET_KEY""], + algorithms=[""HS256""], + ) + except jwt.InvalidTokenError: + raise Exception(""State signature is not valid!"") + + try: + next_url = state[""next""][0] or self.appbuilder.get_url_for_index + except (KeyError, IndexError): + next_url = self.appbuilder.get_url_for_index + + return redirect(next_url)"," def oauth_authorized(self, provider): + log.debug(""Authorized init"") + resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response() + if resp is None: + flash(u""You denied the request to sign in."", ""warning"") + return redirect(""login"") + log.debug(""OAUTH Authorized resp: {0}"".format(resp)) + # Retrieves specific user info from the provider + try: + self.appbuilder.sm.set_oauth_session(provider, resp) + userinfo = self.appbuilder.sm.oauth_user_info(provider, resp) + except Exception as e: + log.error(""Error returning OAuth user info: {0}"".format(e)) + user = None + else: + log.debug(""User info retrieved from {0}: {1}"".format(provider, userinfo)) + # User email is not whitelisted + if provider in self.appbuilder.sm.oauth_whitelists: + whitelist = self.appbuilder.sm.oauth_whitelists[provider] + allow = False + for e in whitelist: + if re.search(e, userinfo[""email""]): + allow = True + break + if not allow: + flash(u""You are not authorized."", ""warning"") + return redirect(""login"") + else: + log.debug(""No whitelist for OAuth provider"") + user = self.appbuilder.sm.auth_user_oauth(userinfo) + + if user is None: + flash(as_unicode(self.invalid_login_message), ""warning"") + return redirect(""login"") + else: + login_user(user) + try: + state = jwt.decode( + request.args[""state""], + self.appbuilder.app.config[""SECRET_KEY""], + algorithms=[""HS256""], + ) + except jwt.InvalidTokenError: + raise Exception(""State signature is not valid!"") + + try: + next_url = state[""next""][0] or self.appbuilder.get_url_for_index + except (KeyError, IndexError): + next_url = self.appbuilder.get_url_for_index + + return redirect(next_url)","[{'piece_type': 'source code', 'piece_content': ""resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()\\nKeyError: 'login'""}, {'piece_type': 'error message', 'piece_content': 'File ""/home/aman/superset/lib/python3.6/site-packages/flask_appbuilder/security/views.py"", line 678, in oauth_authorized\\nresp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()\\nKeyError: \\'login\\''}, {'piece_type': 'other', 'piece_content': 'ROW_LIMIT = 5000\\nSUPERSET_WORKERS = 4\\nSUPERSET_WEBSERVER_PORT = 8088\\nimport os\\nfrom flask import Flask\\n\\nimport logging\\nfrom flask_appbuilder.security.manager import AUTH_OID, AUTH_REMOTE_USER, AUTH_DB, AUTH_LDAP, AUTH_OAUTH\\nfrom superset.security import SupersetSecurityManager\\nimport logging\\nfrom flask_appbuilder import SQLA, AppBuilder\\n\\nclass CustomSsoSecurityManager(SupersetSecurityManager):\\n#@appbuilder.sm.oauth_user_info_getter\\ndef oauth_user_info(self, provider, response=None):\\nif provider == \\'boilerplate\\':\\n\\nres = self.appbuilder.sm.oauth_remotes[provider].get(\\'userinfo\\')\\nprint(res)\\nif res.status != 200:\\nlogger.error(\\'Failed to obtain user info: %s\\', res.data)\\nreturn\\nme = res.data\\nlogger.debug("" user_data: %s"", me)\\nprefix = \\'Superset\\'\\nreturn {\\n\\'username\\' : me[\\'email\\'],\\n\\'name\\' : me[\\'name\\'],\\n\\'email\\' : me[\\'email\\'],\\n\\'first_name\\': me[\\'given_name\\'],\\n\\'last_name\\': me[\\'family_name\\'],\\n}\\n\\n# from superset.security import SupersetSecurityManager\\n\\n# class CustomSsoSecurityManager(SupersetSecurityManager):\\n# #@appbuilder.sm.oauth_user_info\\n# def oauth_user_info(self, provider, response=None):\\n# logging.debug(""Oauth2 provider: {0}."".format(provider))\\n# if provider == \\'boilerplate\\':\\n# # As example, this line request a GET to base_url + \\'/\\' + userDetails with Bearer Authentication,\\n# # and expects that authorization server checks the token, and response with user details\\n# me = self.appbuilder.sm.oauth_remotes[provider].get(\\'userinfo\\').data\\n# logging.debug(""user_data: {0}"".format(me))\\n# return { \\'name\\' : me[\\'name\\'], \\'email\\' : me[\\'email\\'], \\'id\\' : me[\\'user_name\\'], \\'username\\' : me[\\'user_name\\'], \\'first_name\\':\\'\\', \\'last_name\\':\\'\\'}\\n\\nCUSTOM_SECURITY_MANAGER = CustomSsoSecurityManager\\nAUTH_TYPE = AUTH_OAUTH\\nAUTH_ROLE_PUBLIC = \\'Public\\'\\nAUTH_USER_REGISTRATION = True\\nAUTH_USER_REGISTRATION_ROLE = \\'Public\\'\\nCSRF_ENABLED = True\\nENABLE_PROXY_FIX = True\\nPREFERRED_URL_SCHEME = \\'https\\'\\n\\nOAUTH_PROVIDERS = [\\n\\n{\\n\\'name\\': \\'boilerplate\\',\\n#\\'whitelist\\': [\\'@company.com\\'],\\n\\'icon\\': \\'fa-google\\',\\n\\'token_key\\': \\'access_token\\',\\n\\'remote_app\\': {\\n\\'base_url\\': \\'https://www.googleapis.com/oauth2/v2/\\',\\n\\'request_token_params\\': {\\n#\\'scope\\': \\'email profile\\'\\n},\\n\\'request_token_url\\': None,\\n\\'access_token_url\\':\\'https://*****/backend/o/token/\\',\\n\\'authorize_url\\': \\'https://******/backend/o/authorize/\\',\\n\\'consumer_key\\': \\'kDFoe0pypcM6VuNBHbw5NTOXpuzX7dCU\\',\\n\\'consumer_secret\\': \\'SHLYleMGfuHyqNJvMI03RgRf4qIzfHvMf4GKOV43AzRVvc6v3IjIxTMvI5mOrjSq8YBkOasYKMiKWzltUQtCb5qZ0rHk\\'\\n}\\n}\\n]'}]","File ""/home/aman/superset/lib/python3.6/site-packages/flask_appbuilder/security/views.py"", line 678, in oauth_authorized +resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response() +KeyError: 'login'",KeyError +" def _query_select_options(self, query, select_columns=None): + """""" + Add select load options to query. The goal + is to only SQL select what is requested + + :param query: SQLAlchemy Query obj + :param select_columns: (list) of columns + :return: SQLAlchemy Query obj + """""" + if select_columns: + _load_options = list() + for column in select_columns: + query, relation_tuple = self._query_join_dotted_column( + query, + column, + ) + model_relation, relation_join = relation_tuple or (None, None) + if model_relation: + _load_options.append( + Load(model_relation).load_only(column.split(""."")[1]) + ) + else: + # is a custom property method field? + if hasattr(getattr(self.obj, column), ""fget""): + pass + # is not a relation and not a function? + elif not self.is_relation(column) and not hasattr( + getattr(self.obj, column), ""__call__"" + ): + _load_options.append(Load(self.obj).load_only(column)) + else: + _load_options.append(Load(self.obj)) + query = query.options(*tuple(_load_options)) + return query"," def _query_select_options(self, query, select_columns=None): + """""" + Add select load options to query. The goal + is to only SQL select what is requested + + :param query: SQLAlchemy Query obj + :param select_columns: (list) of columns + :return: SQLAlchemy Query obj + """""" + if select_columns: + _load_options = list() + for column in select_columns: + if ""."" in column: + model_relation = self.get_related_model(column.split(""."")[0]) + if not self.is_model_already_joinded(query, model_relation): + query = query.join(model_relation) + _load_options.append( + Load(model_relation).load_only(column.split(""."")[1]) + ) + else: + # is a custom property method field? + if hasattr(getattr(self.obj, column), ""fget""): + pass + # is not a relation and not a function? + elif not self.is_relation(column) and not hasattr( + getattr(self.obj, column), ""__call__"" + ): + _load_options.append(Load(self.obj).load_only(column)) + else: + _load_options.append(Load(self.obj)) + query = query.options(*tuple(_load_options)) + return query","[{'piece_type': 'source code', 'piece_content': 'class ProjectView(ModelRestApi):\\nlist_columns = [\\'name\\', ""last_user.username""]\\n\\nclass Project(Model, PinpointMixin):\\n__tablename__ = TABLE_PREFIX + \\'project\\'\\nid = Column(Integer, primary_key=True, autoincrement=True)\\nlast_user_id = Column(Integer, ForeignKey(\\'ab_user.id\\'), nullable=True)\\nlast_user = relationship(""User"", primaryjoin=""User.id==Project.last_user_id"", foreign_keys=[last_user_id])\\nlast_user_id2 = Column(Integer, ForeignKey(\\'ab_user.id\\'), nullable=True)\\nlast_user2 = relationship(""User"", primaryjoin=""User.id==Project.last_user_id2"", foreign_keys=[last_user_id2])'}, {'piece_type': 'error message', 'piece_content': ""sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'project' and 'ab_user'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.""}]",sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'project' and 'ab_user'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.,sqlalchemy.exc.AmbiguousForeignKeysError +" def query( + self, + filters=None, + order_column="""", + order_direction="""", + page=None, + page_size=None, + select_columns=None, + ): + """""" + QUERY + :param filters: + dict with filters {: + :param page: + the current page + :param page_size: + the current page size + + """""" + query = self.session.query(self.obj) + query, relation_tuple = self._query_join_dotted_column(query, order_column) + query = self._query_select_options(query, select_columns) + query_count = self.session.query(func.count('*')).select_from(self.obj) + + query_count = self._get_base_query(query=query_count, filters=filters) + query = self._get_base_query( + query=query, + filters=filters, + order_column=order_column, + order_direction=order_direction, + ) + + count = query_count.scalar() + + if page: + query = query.offset(page * page_size) + if page_size: + query = query.limit(page_size) + return count, query.all()"," def query( + self, + filters=None, + order_column="""", + order_direction="""", + page=None, + page_size=None, + select_columns=None, + ): + """""" + QUERY + :param filters: + dict with filters {: + :param page: + the current page + :param page_size: + the current page size + + """""" + query = self.session.query(self.obj) + query = self._query_select_options(query, select_columns) + if len(order_column.split('.')) >= 2: + for join_relation in order_column.split('.')[:-1]: + relation_tuple = self.get_related_model_and_join(join_relation) + model_relation, relation_join = relation_tuple + if not self.is_model_already_joinded(query, model_relation): + query = query.join(model_relation, relation_join, isouter=True) + query_count = self.session.query(func.count('*')).select_from(self.obj) + + query_count = self._get_base_query(query=query_count, filters=filters) + query = self._get_base_query( + query=query, + filters=filters, + order_column=order_column, + order_direction=order_direction, + ) + + count = query_count.scalar() + + if page: + query = query.offset(page * page_size) + if page_size: + query = query.limit(page_size) + return count, query.all()","[{'piece_type': 'source code', 'piece_content': 'class ProjectView(ModelRestApi):\\nlist_columns = [\\'name\\', ""last_user.username""]\\n\\nclass Project(Model, PinpointMixin):\\n__tablename__ = TABLE_PREFIX + \\'project\\'\\nid = Column(Integer, primary_key=True, autoincrement=True)\\nlast_user_id = Column(Integer, ForeignKey(\\'ab_user.id\\'), nullable=True)\\nlast_user = relationship(""User"", primaryjoin=""User.id==Project.last_user_id"", foreign_keys=[last_user_id])\\nlast_user_id2 = Column(Integer, ForeignKey(\\'ab_user.id\\'), nullable=True)\\nlast_user2 = relationship(""User"", primaryjoin=""User.id==Project.last_user_id2"", foreign_keys=[last_user_id2])'}, {'piece_type': 'error message', 'piece_content': ""sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'project' and 'ab_user'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.""}]",sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'project' and 'ab_user'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.,sqlalchemy.exc.AmbiguousForeignKeysError +" def auth_user_ldap(self, username, password): + """""" + Method for authenticating user, auth LDAP style. + depends on ldap module that is not mandatory requirement + for F.A.B. + + :param username: + The username + :param password: + The password + """""" + if username is None or username == """": + return None + user = self.find_user(username=username) + if user is not None and (not user.is_active()): + return None + else: + try: + import ldap + except: + raise Exception(""No ldap library for python."") + try: + if self.auth_ldap_allow_self_signed: + ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) + con = ldap.initialize(self.auth_ldap_server) + con.set_option(ldap.OPT_REFERRALS, 0) + if self.auth_ldap_use_tls: + try: + con.start_tls_s() + except Exception: + log.info(LOGMSG_ERR_SEC_AUTH_LDAP_TLS.format(self.auth_ldap_server)) + return None + # Authenticate user + if not self._bind_ldap(ldap, con, username, password): + if user: + self.update_user_auth_stat(user, False) + log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username)) + return None + # If user does not exist on the DB and not self user registration, go away + if not user and not self.auth_user_registration: + return None + # User does not exist, create one if self registration. + elif not user and self.auth_user_registration: + new_user = self._search_ldap(ldap, con, username) + if not new_user: + log.warning(LOGMSG_WAR_SEC_NOLDAP_OBJ.format(username)) + return None + ldap_user_info = new_user[0][1] + if self.auth_user_registration and user is None: + user = self.add_user( + username=username, + first_name=self.ldap_extract(ldap_user_info, self.auth_ldap_firstname_field, username), + last_name=self.ldap_extract(ldap_user_info, self.auth_ldap_lastname_field, username), + email=self.ldap_extract(ldap_user_info, self.auth_ldap_email_field, username + '@email.notfound'), + role=self.find_role(self.auth_user_registration_role) + ) + + self.update_user_auth_stat(user) + return user + + except ldap.LDAPError as e: + if type(e.message) == dict and 'desc' in e.message: + log.error(LOGMSG_ERR_SEC_AUTH_LDAP.format(e.message['desc'])) + return None + else: + log.error(e) + return None"," def auth_user_ldap(self, username, password): + """""" + Method for authenticating user, auth LDAP style. + depends on ldap module that is not mandatory requirement + for F.A.B. + + :param username: + The username + :param password: + The password + """""" + if username is None or username == """": + return None + user = self.find_user(username=username) + if user is not None and (not user.is_active()): + return None + else: + try: + import ldap + except: + raise Exception(""No ldap library for python."") + try: + if self.auth_ldap_allow_self_signed: + ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) + con = ldap.initialize(self.auth_ldap_server) + con.set_option(ldap.OPT_REFERRALS, 0) + if self.auth_ldap_use_tls: + try: + con.start_tls_s() + except Exception: + log.info(LOGMSG_ERR_SEC_AUTH_LDAP_TLS.format(self.auth_ldap_server)) + return None + # Authenticate user + if not self._bind_ldap(ldap, con, username, password): + if user: + self.update_user_auth_stat(user, False) + log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username)) + return None + # If user does not exist on the DB and not self user registration, go away + if not user and not self.auth_user_registration: + return None + # User does not exist, create one if self registration. + elif not user and self.auth_user_registration: + new_user = self._search_ldap(ldap, con, username) + if not new_user: + log.warning(LOGMSG_WAR_SEC_NOLDAP_OBJ.format(username)) + return None + ldap_user_info = new_user[0][1] + if self.auth_user_registration and user is None: + user = self.add_user( + username=username, + first_name=ldap_user_info.get(self.auth_ldap_firstname_field, [username])[0], + last_name=ldap_user_info.get(self.auth_ldap_lastname_field, [username])[0], + email=ldap_user_info.get(self.auth_ldap_email_field, [username + '@email.notfound'])[0], + role=self.find_role(self.auth_user_registration_role) + ) + + self.update_user_auth_stat(user) + return user + + except ldap.LDAPError as e: + if type(e.message) == dict and 'desc' in e.message: + log.error(LOGMSG_ERR_SEC_AUTH_LDAP.format(e.message['desc'])) + return None + else: + log.error(e) + return None","[{'piece_type': 'other', 'piece_content': ""query = query.order_by(order_column + ' ' + order_direction)""}, {'piece_type': 'other', 'piece_content': ""http://127.0.0.1/dashboardmodelview/list/?_oc_DashboardModelView='""}, {'piece_type': 'error message', 'piece_content': 'Sorry, something went wrong\\n\\n500 - Internal Server Error\\n\\nStacktrace\\n\\nTraceback (most recent call last):\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app\\nresponse = self.full_dispatch_request()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request\\nrv = self.handle_user_exception(e)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception\\nreraise(exc_type, exc_value, tb)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request\\nrv = self.dispatch_request()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request\\nreturn self.view_functions[rule.endpoint](**req.view_args)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py"", line 26, in wraps\\nreturn f(self, *args, **kwargs)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py"", line 450, in list\\nwidgets = self._list()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 870, in _list\\npage_size=page_size)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 786, in _get_list_widget\\ncount, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 103, in query\\norder_direction=order_direction)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 67, in _get_base_query\\nquery = query.order_by(order_column + \\' \\' + order_direction)\\nTypeError: coercing to Unicode: need string or buffer, NoneType found'}]","Sorry, something went wrong + +500 - Internal Server Error + +Stacktrace + +Traceback (most recent call last): +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app +response = self.full_dispatch_request() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request +rv = self.handle_user_exception(e) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception +reraise(exc_type, exc_value, tb) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request +rv = self.dispatch_request() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request +return self.view_functions[rule.endpoint](**req.view_args) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py"", line 26, in wraps +return f(self, *args, **kwargs) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py"", line 450, in list +widgets = self._list() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 870, in _list +page_size=page_size) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 786, in _get_list_widget +count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 103, in query +order_direction=order_direction) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 67, in _get_base_query +query = query.order_by(order_column + ' ' + order_direction) +TypeError: coercing to Unicode: need string or buffer, NoneType found",TypeError +" def _get_base_query(self, query=None, filters=None, order_column='', order_direction=''): + if filters: + query = filters.apply_all(query) + if order_column != '': + # if Model has custom decorator **renders('')** + # this decorator will add a property to the method named *_col_name* + if hasattr(self.obj, order_column): + if hasattr(getattr(self.obj, order_column), '_col_name'): + order_column = getattr(getattr(self.obj, order_column), '_col_name') + query = query.order_by(""%s %s"" % (order_column, order_direction)) + return query"," def _get_base_query(self, query=None, filters=None, order_column='', order_direction=''): + if filters: + query = filters.apply_all(query) + if order_column != '': + # if Model has custom decorator **renders('')** + # this decorator will add a property to the method named *_col_name* + if hasattr(self.obj, order_column): + if hasattr(getattr(self.obj, order_column), '_col_name'): + order_column = getattr(getattr(self.obj, order_column), '_col_name') + query = query.order_by(order_column + ' ' + order_direction) + return query","[{'piece_type': 'other', 'piece_content': ""query = query.order_by(order_column + ' ' + order_direction)""}, {'piece_type': 'other', 'piece_content': ""http://127.0.0.1/dashboardmodelview/list/?_oc_DashboardModelView='""}, {'piece_type': 'error message', 'piece_content': 'Sorry, something went wrong\\n\\n500 - Internal Server Error\\n\\nStacktrace\\n\\nTraceback (most recent call last):\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app\\nresponse = self.full_dispatch_request()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request\\nrv = self.handle_user_exception(e)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception\\nreraise(exc_type, exc_value, tb)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request\\nrv = self.dispatch_request()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request\\nreturn self.view_functions[rule.endpoint](**req.view_args)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py"", line 26, in wraps\\nreturn f(self, *args, **kwargs)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py"", line 450, in list\\nwidgets = self._list()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 870, in _list\\npage_size=page_size)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 786, in _get_list_widget\\ncount, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 103, in query\\norder_direction=order_direction)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 67, in _get_base_query\\nquery = query.order_by(order_column + \\' \\' + order_direction)\\nTypeError: coercing to Unicode: need string or buffer, NoneType found'}]","Sorry, something went wrong + +500 - Internal Server Error + +Stacktrace + +Traceback (most recent call last): +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app +response = self.full_dispatch_request() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request +rv = self.handle_user_exception(e) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception +reraise(exc_type, exc_value, tb) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request +rv = self.dispatch_request() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request +return self.view_functions[rule.endpoint](**req.view_args) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py"", line 26, in wraps +return f(self, *args, **kwargs) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py"", line 450, in list +widgets = self._list() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 870, in _list +page_size=page_size) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 786, in _get_list_widget +count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 103, in query +order_direction=order_direction) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 67, in _get_base_query +query = query.order_by(order_column + ' ' + order_direction) +TypeError: coercing to Unicode: need string or buffer, NoneType found",TypeError +"def get_order_args(): + """""" + Get order arguments, return a dictionary + { : (ORDER_COL, ORDER_DIRECTION) } + + Arguments are passed like: _oc_=&_od_='asc'|'desc' + + """""" + orders = {} + for arg in request.args: + re_match = re.findall('_oc_(.*)', arg) + if re_match: + order_direction = request.args.get('_od_' + re_match[0]) + if order_direction in ('asc', 'desc'): + orders[re_match[0]] = (request.args.get(arg), order_direction) + return orders","def get_order_args(): + """""" + Get order arguments, return a dictionary + { : (ORDER_COL, ORDER_DIRECTION) } + + Arguments are passed like: _oc_=&_od_='asc'|'desc' + + """""" + orders = {} + for arg in request.args: + re_match = re.findall('_oc_(.*)', arg) + if re_match: + orders[re_match[0]] = (request.args.get(arg), request.args.get('_od_' + re_match[0])) + return orders","[{'piece_type': 'other', 'piece_content': ""query = query.order_by(order_column + ' ' + order_direction)""}, {'piece_type': 'other', 'piece_content': ""http://127.0.0.1/dashboardmodelview/list/?_oc_DashboardModelView='""}, {'piece_type': 'error message', 'piece_content': 'Sorry, something went wrong\\n\\n500 - Internal Server Error\\n\\nStacktrace\\n\\nTraceback (most recent call last):\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app\\nresponse = self.full_dispatch_request()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request\\nrv = self.handle_user_exception(e)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception\\nreraise(exc_type, exc_value, tb)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request\\nrv = self.dispatch_request()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request\\nreturn self.view_functions[rule.endpoint](**req.view_args)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py"", line 26, in wraps\\nreturn f(self, *args, **kwargs)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py"", line 450, in list\\nwidgets = self._list()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 870, in _list\\npage_size=page_size)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 786, in _get_list_widget\\ncount, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 103, in query\\norder_direction=order_direction)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 67, in _get_base_query\\nquery = query.order_by(order_column + \\' \\' + order_direction)\\nTypeError: coercing to Unicode: need string or buffer, NoneType found'}]","Sorry, something went wrong + +500 - Internal Server Error + +Stacktrace + +Traceback (most recent call last): +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app +response = self.full_dispatch_request() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request +rv = self.handle_user_exception(e) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception +reraise(exc_type, exc_value, tb) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request +rv = self.dispatch_request() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request +return self.view_functions[rule.endpoint](**req.view_args) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py"", line 26, in wraps +return f(self, *args, **kwargs) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py"", line 450, in list +widgets = self._list() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 870, in _list +page_size=page_size) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 786, in _get_list_widget +count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 103, in query +order_direction=order_direction) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 67, in _get_base_query +query = query.order_by(order_column + ' ' + order_direction) +TypeError: coercing to Unicode: need string or buffer, NoneType found",TypeError +" def _get_attr_value(item, col): + if not hasattr(item, col): + # it's an inner obj attr + try: + return reduce(getattr, col.split('.'), item) + except Exception as e: + return '' + if hasattr(getattr(item, col), '__call__'): + # its a function + return getattr(item, col)() + else: + # its an attribute + value = getattr(item, col) + # if value is an Enum instance than list and show widgets should display + # its .value rather than its .name: + if _has_enum and isinstance(value, enum.Enum): + return value.value + return value"," def _get_attr_value(self, item, col): + if not hasattr(item, col): + # it's an inner obj attr + try: + return reduce(getattr, col.split('.'), item) + except Exception as e: + return '' + if hasattr(getattr(item, col), '__call__'): + # its a function + return getattr(item, col)() + else: + # its an attribute + value = getattr(item, col) + # if value is an Enum instance than list and show widgets should display + # its .value rather than its .name: + if _has_enum and isinstance(value, enum.Enum): + return value.value + return value","[{'piece_type': 'other', 'piece_content': ""query = query.order_by(order_column + ' ' + order_direction)""}, {'piece_type': 'other', 'piece_content': ""http://127.0.0.1/dashboardmodelview/list/?_oc_DashboardModelView='""}, {'piece_type': 'error message', 'piece_content': 'Sorry, something went wrong\\n\\n500 - Internal Server Error\\n\\nStacktrace\\n\\nTraceback (most recent call last):\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app\\nresponse = self.full_dispatch_request()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request\\nrv = self.handle_user_exception(e)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception\\nreraise(exc_type, exc_value, tb)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request\\nrv = self.dispatch_request()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request\\nreturn self.view_functions[rule.endpoint](**req.view_args)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py"", line 26, in wraps\\nreturn f(self, *args, **kwargs)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py"", line 450, in list\\nwidgets = self._list()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 870, in _list\\npage_size=page_size)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 786, in _get_list_widget\\ncount, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 103, in query\\norder_direction=order_direction)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 67, in _get_base_query\\nquery = query.order_by(order_column + \\' \\' + order_direction)\\nTypeError: coercing to Unicode: need string or buffer, NoneType found'}]","Sorry, something went wrong + +500 - Internal Server Error + +Stacktrace + +Traceback (most recent call last): +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app +response = self.full_dispatch_request() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request +rv = self.handle_user_exception(e) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception +reraise(exc_type, exc_value, tb) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request +rv = self.dispatch_request() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request +return self.view_functions[rule.endpoint](**req.view_args) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py"", line 26, in wraps +return f(self, *args, **kwargs) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py"", line 450, in list +widgets = self._list() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 870, in _list +page_size=page_size) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 786, in _get_list_widget +count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 103, in query +order_direction=order_direction) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 67, in _get_base_query +query = query.order_by(order_column + ' ' + order_direction) +TypeError: coercing to Unicode: need string or buffer, NoneType found",TypeError +" def _get_base_query(self, query=None, filters=None, order_column='', order_direction=''): + if filters: + query = filters.apply_all(query) + if order_column != '': + # if Model has custom decorator **renders('')** + # this decorator will add a property to the method named *_col_name* + if hasattr(self.obj, order_column): + if hasattr(getattr(self.obj, order_column), '_col_name'): + order_column = getattr(self._get_attr(order_column), '_col_name') + if order_direction == 'asc': + query = query.order_by(self._get_attr(order_column).asc()) + else: + query = query.order_by(self._get_attr(order_column).desc()) + return query"," def _get_base_query(self, query=None, filters=None, order_column='', order_direction=''): + if filters: + query = filters.apply_all(query) + if order_column != '': + # if Model has custom decorator **renders('')** + # this decorator will add a property to the method named *_col_name* + if hasattr(self.obj, order_column): + if hasattr(getattr(self.obj, order_column), '_col_name'): + order_column = getattr(getattr(self.obj, order_column), '_col_name') + query = query.order_by(""%s %s"" % (order_column, order_direction)) + return query","[{'piece_type': 'other', 'piece_content': ""query = query.order_by(order_column + ' ' + order_direction)""}, {'piece_type': 'other', 'piece_content': ""http://127.0.0.1/dashboardmodelview/list/?_oc_DashboardModelView='""}, {'piece_type': 'error message', 'piece_content': 'Sorry, something went wrong\\n\\n500 - Internal Server Error\\n\\nStacktrace\\n\\nTraceback (most recent call last):\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app\\nresponse = self.full_dispatch_request()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request\\nrv = self.handle_user_exception(e)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception\\nreraise(exc_type, exc_value, tb)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request\\nrv = self.dispatch_request()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request\\nreturn self.view_functions[rule.endpoint](**req.view_args)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py"", line 26, in wraps\\nreturn f(self, *args, **kwargs)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py"", line 450, in list\\nwidgets = self._list()\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 870, in _list\\npage_size=page_size)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 786, in _get_list_widget\\ncount, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 103, in query\\norder_direction=order_direction)\\nFile ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 67, in _get_base_query\\nquery = query.order_by(order_column + \\' \\' + order_direction)\\nTypeError: coercing to Unicode: need string or buffer, NoneType found'}]","Sorry, something went wrong + +500 - Internal Server Error + +Stacktrace + +Traceback (most recent call last): +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app +response = self.full_dispatch_request() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request +rv = self.handle_user_exception(e) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception +reraise(exc_type, exc_value, tb) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request +rv = self.dispatch_request() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request +return self.view_functions[rule.endpoint](**req.view_args) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py"", line 26, in wraps +return f(self, *args, **kwargs) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py"", line 450, in list +widgets = self._list() +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 870, in _list +page_size=page_size) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py"", line 786, in _get_list_widget +count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 103, in query +order_direction=order_direction) +File ""/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py"", line 67, in _get_base_query +query = query.order_by(order_column + ' ' + order_direction) +TypeError: coercing to Unicode: need string or buffer, NoneType found",TypeError +" def solve(self, problem: QuadraticProgram) -> ADMMOptimizationResult: + """"""Tries to solves the given problem using ADMM algorithm. + + Args: + problem: The problem to be solved. + + Returns: + The result of the optimizer applied to the problem. + + Raises: + QiskitOptimizationError: If the problem is not compatible with the ADMM optimizer. + """""" + self._verify_compatibility(problem) + + # debug + self._log.debug(""Initial problem: %s"", problem.export_as_lp_string()) + + # map integer variables to binary variables + from ..converters.integer_to_binary import IntegerToBinary + int2bin = IntegerToBinary() + original_problem = problem + problem = int2bin.convert(problem) + + # we deal with minimization in the optimizer, so turn the problem to minimization + problem, sense = self._turn_to_minimization(problem) + + # create our computation state. + self._state = ADMMState(problem, self._params.rho_initial) + + # parse problem and convert to an ADMM specific representation. + self._state.binary_indices = self._get_variable_indices(problem, Variable.Type.BINARY) + self._state.continuous_indices = self._get_variable_indices(problem, + Variable.Type.CONTINUOUS) + if self._params.warm_start: + # warm start injection for the initial values of the variables + self._warm_start(problem) + + # convert optimization problem to a set of matrices and vector that are used + # at each iteration. + self._convert_problem_representation() + + start_time = time.time() + # we have not stated our computations yet, so elapsed time initialized as zero. + elapsed_time = 0.0 + iteration = 0 + residual = 1.e+2 + + while (iteration < self._params.maxiter and residual > self._params.tol) \\ + and (elapsed_time < self._params.max_time): + if self._state.step1_absolute_indices: + op1 = self._create_step1_problem() + self._state.x0 = self._update_x0(op1) + # debug + self._log.debug(""Step 1 sub-problem: %s"", op1.export_as_lp_string()) + # else, no binary variables exist, and no update to be done in this case. + # debug + self._log.debug(""x0=%s"", self._state.x0) + + op2 = self._create_step2_problem() + self._state.u, self._state.z = self._update_x1(op2) + # debug + self._log.debug(""Step 2 sub-problem: %s"", op2.export_as_lp_string()) + self._log.debug(""u=%s"", self._state.u) + self._log.debug(""z=%s"", self._state.z) + + if self._params.three_block: + if self._state.binary_indices: + op3 = self._create_step3_problem() + self._state.y = self._update_y(op3) + # debug + self._log.debug(""Step 3 sub-problem: %s"", op3.export_as_lp_string()) + # debug + self._log.debug(""y=%s"", self._state.y) + + self._state.lambda_mult = self._update_lambda_mult() + # debug + self._log.debug(""lambda: %s"", self._state.lambda_mult) + + cost_iterate = self._get_objective_value() + constraint_residual = self._get_constraint_residual() + residual, dual_residual = self._get_solution_residuals(iteration) + merit = self._get_merit(cost_iterate, constraint_residual) + # debug + self._log.debug(""cost_iterate=%s, cr=%s, merit=%s"", + cost_iterate, constraint_residual, merit) + + # costs are saved with their original sign. + self._state.cost_iterates.append(cost_iterate) + self._state.residuals.append(residual) + self._state.dual_residuals.append(dual_residual) + self._state.cons_r.append(constraint_residual) + self._state.merits.append(merit) + self._state.lambdas.append(np.linalg.norm(self._state.lambda_mult)) + + self._state.x0_saved.append(self._state.x0) + self._state.u_saved.append(self._state.u) + self._state.z_saved.append(self._state.z) + self._state.z_saved.append(self._state.y) + + self._update_rho(residual, dual_residual) + + iteration += 1 + elapsed_time = time.time() - start_time + + binary_vars, continuous_vars, objective_value = self._get_best_merit_solution() + solution = self._revert_solution_indexes(binary_vars, continuous_vars) + + # flip the objective sign again if required + objective_value = objective_value * sense + + # convert back integer to binary + base_result = OptimizationResult(solution, objective_value, problem.variables, + OptimizationResultStatus.SUCCESS) + base_result = int2bin.interpret(base_result) + + # third parameter is our internal state of computations. + result = ADMMOptimizationResult(x=base_result.x, fval=base_result.fval, + variables=original_problem.variables, + state=self._state, + status=self._get_feasibility_status(original_problem, + base_result.x)) + + # debug + self._log.debug(""solution=%s, objective=%s at iteration=%s"", + solution, objective_value, iteration) + return result"," def solve(self, problem: QuadraticProgram) -> ADMMOptimizationResult: + """"""Tries to solves the given problem using ADMM algorithm. + + Args: + problem: The problem to be solved. + + Returns: + The result of the optimizer applied to the problem. + + Raises: + QiskitOptimizationError: If the problem is not compatible with the ADMM optimizer. + """""" + self._verify_compatibility(problem) + + # debug + self._log.debug(""Initial problem: %s"", problem.export_as_lp_string()) + + # map integer variables to binary variables + from ..converters.integer_to_binary import IntegerToBinary + int2bin = IntegerToBinary() + original_variables = problem.variables + problem = int2bin.convert(problem) + + # we deal with minimization in the optimizer, so turn the problem to minimization + problem, sense = self._turn_to_minimization(problem) + + # create our computation state. + self._state = ADMMState(problem, self._params.rho_initial) + + # parse problem and convert to an ADMM specific representation. + self._state.binary_indices = self._get_variable_indices(problem, Variable.Type.BINARY) + self._state.continuous_indices = self._get_variable_indices(problem, + Variable.Type.CONTINUOUS) + if self._params.warm_start: + # warm start injection for the initial values of the variables + self._warm_start(problem) + + # convert optimization problem to a set of matrices and vector that are used + # at each iteration. + self._convert_problem_representation() + + start_time = time.time() + # we have not stated our computations yet, so elapsed time initialized as zero. + elapsed_time = 0.0 + iteration = 0 + residual = 1.e+2 + + while (iteration < self._params.maxiter and residual > self._params.tol) \\ + and (elapsed_time < self._params.max_time): + if self._state.step1_absolute_indices: + op1 = self._create_step1_problem() + self._state.x0 = self._update_x0(op1) + # debug + self._log.debug(""Step 1 sub-problem: %s"", op1.export_as_lp_string()) + # else, no binary variables exist, and no update to be done in this case. + # debug + self._log.debug(""x0=%s"", self._state.x0) + + op2 = self._create_step2_problem() + self._state.u, self._state.z = self._update_x1(op2) + # debug + self._log.debug(""Step 2 sub-problem: %s"", op2.export_as_lp_string()) + self._log.debug(""u=%s"", self._state.u) + self._log.debug(""z=%s"", self._state.z) + + if self._params.three_block: + if self._state.binary_indices: + op3 = self._create_step3_problem() + self._state.y = self._update_y(op3) + # debug + self._log.debug(""Step 3 sub-problem: %s"", op3.export_as_lp_string()) + # debug + self._log.debug(""y=%s"", self._state.y) + + self._state.lambda_mult = self._update_lambda_mult() + # debug + self._log.debug(""lambda: %s"", self._state.lambda_mult) + + cost_iterate = self._get_objective_value() + constraint_residual = self._get_constraint_residual() + residual, dual_residual = self._get_solution_residuals(iteration) + merit = self._get_merit(cost_iterate, constraint_residual) + # debug + self._log.debug(""cost_iterate=%s, cr=%s, merit=%s"", + cost_iterate, constraint_residual, merit) + + # costs are saved with their original sign. + self._state.cost_iterates.append(cost_iterate) + self._state.residuals.append(residual) + self._state.dual_residuals.append(dual_residual) + self._state.cons_r.append(constraint_residual) + self._state.merits.append(merit) + self._state.lambdas.append(np.linalg.norm(self._state.lambda_mult)) + + self._state.x0_saved.append(self._state.x0) + self._state.u_saved.append(self._state.u) + self._state.z_saved.append(self._state.z) + self._state.z_saved.append(self._state.y) + + self._update_rho(residual, dual_residual) + + iteration += 1 + elapsed_time = time.time() - start_time + + binary_vars, continuous_vars, objective_value = self._get_best_merit_solution() + solution = self._revert_solution_indexes(binary_vars, continuous_vars) + + # flip the objective sign again if required + objective_value = objective_value * sense + + # convert back integer to binary + base_result = OptimizationResult(solution, objective_value, original_variables, + OptimizationResultStatus.SUCCESS) + base_result = int2bin.interpret(base_result) + + # third parameter is our internal state of computations. + result = ADMMOptimizationResult(x=base_result.x, fval=base_result.fval, + variables=base_result.variables, + state=self._state, + status=self._get_feasibility_status(problem, base_result.x)) + + # debug + self._log.debug(""solution=%s, objective=%s at iteration=%s"", + solution, objective_value, iteration) + return result","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile "".../admmprove.py"", line 53, in \\nresult_q = admm_q.solve(qp)\\nFile "".../qiskit-aqua/qiskit/optimization/algorithms/admm_optimizer.py"", line 381, in solve\\nOptimizationResultStatus.SUCCESS)\\nFile "".../qiskit-aqua/qiskit/optimization/algorithms/optimization_algorithm.py"", line 106, in __init__\\n[v.name for v in variables]))\\nqiskit.optimization.exceptions.QiskitOptimizationError: ""Inconsistent size of optimal value and variables. x: size 6 [0. 0. 0. 0. 0. 0.], variables: size 4 [\\'v\\', \\'w\\', \\'t\\', \\'u\\']""'}, {'piece_type': 'reproducing source code', 'piece_content': 'from docplex.mp.model import Model\\n\\nfrom qiskit import BasicAer\\nfrom qiskit.aqua.algorithms import QAOA, NumPyMinimumEigensolver\\nfrom qiskit.optimization.algorithms import CobylaOptimizer, MinimumEigenOptimizer\\nfrom qiskit.optimization.algorithms.admm_optimizer import ADMMParameters, ADMMOptimizer\\nfrom qiskit.optimization.problems import QuadraticProgram\\n\\n# define COBYLA optimizer to handle convex continuous problems.\\ncobyla = CobylaOptimizer()\\n\\n# define QAOA via the minimum eigen optimizer\\nqaoa = MinimumEigenOptimizer(QAOA(quantum_instance=BasicAer.get_backend(\\'statevector_simulator\\')))\\n\\n# exact QUBO solver as classical benchmark\\nexact = MinimumEigenOptimizer(NumPyMinimumEigensolver()) # to solve QUBOs\\n\\n# construct model using docplex\\nmdl = Model(\\'ex6\\')\\n\\nv = mdl.integer_var(1, 8, name=\\'v\\')\\nw = mdl.binary_var(name=\\'w\\')\\nt = mdl.binary_var(name=\\'t\\')\\nu = mdl.binary_var(name=\\'u\\')\\n\\nmdl.maximize(t + u + w + v)\\n\\n# load quadratic program from docplex model\\nqp = QuadraticProgram()\\nqp.from_docplex(mdl)\\nprint(qp.export_as_lp_string())\\n\\nadmm_params = ADMMParameters(\\nrho_initial=1001,\\nbeta=1000,\\nfactor_c=900,\\nmaxiter=100,\\nthree_block=True, tol=8\\n)\\n\\n# define QUBO optimizer\\nqubo_optimizer = qaoa\\n\\n# define classical optimizer\\nconvex_optimizer = cobyla\\n# convex_optimizer = cplex # uncomment to use CPLEX instead\\n\\n# initialize ADMM with quantum QUBO optimizer and classical convex optimizer\\nadmm_q = ADMMOptimizer(params=admm_params,\\nqubo_optimizer=qubo_optimizer,\\ncontinuous_optimizer=convex_optimizer)\\n\\nresult_q = admm_q.solve(qp)\\nprint(""x={}"".format(result_q.x))\\nprint(""fval={:.2f}"".format(result_q.fval))'}]","Traceback (most recent call last): +File "".../admmprove.py"", line 53, in +result_q = admm_q.solve(qp) +File "".../qiskit-aqua/qiskit/optimization/algorithms/admm_optimizer.py"", line 381, in solve +OptimizationResultStatus.SUCCESS) +File "".../qiskit-aqua/qiskit/optimization/algorithms/optimization_algorithm.py"", line 106, in __init__ +[v.name for v in variables])) +qiskit.optimization.exceptions.QiskitOptimizationError: ""Inconsistent size of optimal value and variables. x: size 6 [0. 0. 0. 0. 0. 0.], variables: size 4 ['v', 'w', 't', 'u']""",qiskit.optimization.exceptions.QiskitOptimizationError +" def solve(self, problem: QuadraticProgram) -> OptimizationResult: + """"""Tries to solves the given problem using the grover optimizer. + + Runs the optimizer to try to solve the optimization problem. If the problem cannot be, + converted to a QUBO, this optimizer raises an exception due to incompatibility. + + Args: + problem: The problem to be solved. + + Returns: + The result of the optimizer applied to the problem. + + Raises: + AttributeError: If the quantum instance has not been set. + QiskitOptimizationError: If the problem is incompatible with the optimizer. + """""" + if self.quantum_instance is None: + raise AttributeError('The quantum instance or backend has not been set.') + + self._verify_compatibility(problem) + + # convert problem to QUBO + problem_ = self._convert(problem, self._converters) + problem_init = deepcopy(problem_) + + # convert to minimization problem + sense = problem_.objective.sense + if sense == problem_.objective.Sense.MAXIMIZE: + problem_.objective.sense = problem_.objective.Sense.MINIMIZE + problem_.objective.constant = -problem_.objective.constant + for i, val in problem_.objective.linear.to_dict().items(): + problem_.objective.linear[i] = -val + for (i, j), val in problem_.objective.quadratic.to_dict().items(): + problem_.objective.quadratic[i, j] = -val + self._num_key_qubits = len(problem_.objective.linear.to_array()) # type: ignore + + # Variables for tracking the optimum. + optimum_found = False + optimum_key = math.inf + optimum_value = math.inf + threshold = 0 + n_key = len(problem_.variables) + n_value = self._num_value_qubits + + # Variables for tracking the solutions encountered. + num_solutions = 2 ** n_key + keys_measured = [] + + # Variables for result object. + operation_count = {} + iteration = 0 + + # Variables for stopping if we've hit the rotation max. + rotations = 0 + max_rotations = int(np.ceil(100 * np.pi / 4)) + + # Initialize oracle helper object. + qr_key_value = QuantumRegister(self._num_key_qubits + self._num_value_qubits) + orig_constant = problem_.objective.constant + measurement = not self.quantum_instance.is_statevector + oracle, is_good_state = self._get_oracle(qr_key_value) + + while not optimum_found: + m = 1 + improvement_found = False + + # Get oracle O and the state preparation operator A for the current threshold. + problem_.objective.constant = orig_constant - threshold + a_operator = self._get_a_operator(qr_key_value, problem_) + + # Iterate until we measure a negative. + loops_with_no_improvement = 0 + while not improvement_found: + # Determine the number of rotations. + loops_with_no_improvement += 1 + rotation_count = int(np.ceil(aqua_globals.random.uniform(0, m - 1))) + rotations += rotation_count + # Apply Grover's Algorithm to find values below the threshold. + # TODO: Utilize Grover's incremental feature - requires changes to Grover. + grover = Grover(oracle, + state_preparation=a_operator, + good_state=is_good_state) + circuit = grover.construct_circuit(rotation_count, measurement=measurement) + + # Get the next outcome. + outcome = self._measure(circuit) + k = int(outcome[0:n_key], 2) + v = outcome[n_key:n_key + n_value] + int_v = self._bin_to_int(v, n_value) + threshold + v = self._twos_complement(int_v, n_value) + logger.info('Outcome: %s', outcome) + logger.info('Value: %s = %s', v, int_v) + + # If the value is an improvement, we update the iteration parameters (e.g. oracle). + if int_v < optimum_value: + optimum_key = k + optimum_value = int_v + logger.info('Current Optimum Key: %s', optimum_key) + logger.info('Current Optimum Value: %s', optimum_value) + if v.startswith('1'): + improvement_found = True + threshold = optimum_value + else: + # Using Durr and Hoyer method, increase m. + m = int(np.ceil(min(m * 8 / 7, 2 ** (n_key / 2)))) + logger.info('No Improvement. M: %s', m) + + # Check if we've already seen this value. + if k not in keys_measured: + keys_measured.append(k) + + # Assume the optimal if any of the stop parameters are true. + if loops_with_no_improvement >= self._n_iterations or \\ + len(keys_measured) == num_solutions or rotations >= max_rotations: + improvement_found = True + optimum_found = True + + # Track the operation count. + operations = circuit.count_ops() + operation_count[iteration] = operations + iteration += 1 + logger.info('Operation Count: %s\\n', operations) + + # If the constant is 0 and we didn't find a negative, the answer is likely 0. + if optimum_value >= 0 and orig_constant == 0: + optimum_key = 0 + + opt_x = np.array([1 if s == '1' else 0 for s in ('{0:%sb}' % n_key).format(optimum_key)]) + + # Compute function value + fval = problem_init.objective.evaluate(opt_x) + result = OptimizationResult(x=opt_x, fval=fval, variables=problem_.variables, + status=OptimizationResultStatus.SUCCESS) + + # cast binaries back to integers + result = self._interpret(result, self._converters) + + return GroverOptimizationResult(x=result.x, fval=result.fval, variables=result.variables, + operation_counts=operation_count, n_input_qubits=n_key, + n_output_qubits=n_value, intermediate_fval=fval, + threshold=threshold, + status=self._get_feasibility_status(problem, result.x))"," def solve(self, problem: QuadraticProgram) -> OptimizationResult: + """"""Tries to solves the given problem using the grover optimizer. + + Runs the optimizer to try to solve the optimization problem. If the problem cannot be, + converted to a QUBO, this optimizer raises an exception due to incompatibility. + + Args: + problem: The problem to be solved. + + Returns: + The result of the optimizer applied to the problem. + + Raises: + AttributeError: If the quantum instance has not been set. + QiskitOptimizationError: If the problem is incompatible with the optimizer. + """""" + if self.quantum_instance is None: + raise AttributeError('The quantum instance or backend has not been set.') + + self._verify_compatibility(problem) + + # convert problem to QUBO + problem_ = self._convert(problem, self._converters) + problem_init = deepcopy(problem_) + + # convert to minimization problem + sense = problem_.objective.sense + if sense == problem_.objective.Sense.MAXIMIZE: + problem_.objective.sense = problem_.objective.Sense.MINIMIZE + problem_.objective.constant = -problem_.objective.constant + for i, val in problem_.objective.linear.to_dict().items(): + problem_.objective.linear[i] = -val + for (i, j), val in problem_.objective.quadratic.to_dict().items(): + problem_.objective.quadratic[i, j] = -val + self._num_key_qubits = len(problem_.objective.linear.to_array()) # type: ignore + + # Variables for tracking the optimum. + optimum_found = False + optimum_key = math.inf + optimum_value = math.inf + threshold = 0 + n_key = len(problem_.variables) + n_value = self._num_value_qubits + + # Variables for tracking the solutions encountered. + num_solutions = 2 ** n_key + keys_measured = [] + + # Variables for result object. + operation_count = {} + iteration = 0 + + # Variables for stopping if we've hit the rotation max. + rotations = 0 + max_rotations = int(np.ceil(100 * np.pi / 4)) + + # Initialize oracle helper object. + qr_key_value = QuantumRegister(self._num_key_qubits + self._num_value_qubits) + orig_constant = problem_.objective.constant + measurement = not self.quantum_instance.is_statevector + oracle, is_good_state = self._get_oracle(qr_key_value) + + while not optimum_found: + m = 1 + improvement_found = False + + # Get oracle O and the state preparation operator A for the current threshold. + problem_.objective.constant = orig_constant - threshold + a_operator = self._get_a_operator(qr_key_value, problem_) + + # Iterate until we measure a negative. + loops_with_no_improvement = 0 + while not improvement_found: + # Determine the number of rotations. + loops_with_no_improvement += 1 + rotation_count = int(np.ceil(aqua_globals.random.uniform(0, m - 1))) + rotations += rotation_count + + # Apply Grover's Algorithm to find values below the threshold. + if rotation_count > 0: + # TODO: Utilize Grover's incremental feature - requires changes to Grover. + grover = Grover(oracle, + state_preparation=a_operator, + good_state=is_good_state) + circuit = grover.construct_circuit(rotation_count, measurement=measurement) + else: + circuit = a_operator + + # Get the next outcome. + outcome = self._measure(circuit) + k = int(outcome[0:n_key], 2) + v = outcome[n_key:n_key + n_value] + int_v = self._bin_to_int(v, n_value) + threshold + v = self._twos_complement(int_v, n_value) + logger.info('Outcome: %s', outcome) + logger.info('Value: %s = %s', v, int_v) + + # If the value is an improvement, we update the iteration parameters (e.g. oracle). + if int_v < optimum_value: + optimum_key = k + optimum_value = int_v + logger.info('Current Optimum Key: %s', optimum_key) + logger.info('Current Optimum Value: %s', optimum_value) + if v.startswith('1'): + improvement_found = True + threshold = optimum_value + else: + # Using Durr and Hoyer method, increase m. + m = int(np.ceil(min(m * 8 / 7, 2 ** (n_key / 2)))) + logger.info('No Improvement. M: %s', m) + + # Check if we've already seen this value. + if k not in keys_measured: + keys_measured.append(k) + + # Assume the optimal if any of the stop parameters are true. + if loops_with_no_improvement >= self._n_iterations or \\ + len(keys_measured) == num_solutions or rotations >= max_rotations: + improvement_found = True + optimum_found = True + + # Track the operation count. + operations = circuit.count_ops() + operation_count[iteration] = operations + iteration += 1 + logger.info('Operation Count: %s\\n', operations) + + # If the constant is 0 and we didn't find a negative, the answer is likely 0. + if optimum_value >= 0 and orig_constant == 0: + optimum_key = 0 + + opt_x = np.array([1 if s == '1' else 0 for s in ('{0:%sb}' % n_key).format(optimum_key)]) + + # Compute function value + fval = problem_init.objective.evaluate(opt_x) + result = OptimizationResult(x=opt_x, fval=fval, variables=problem_.variables, + status=OptimizationResultStatus.SUCCESS) + + # cast binaries back to integers + result = self._interpret(result, self._converters) + + return GroverOptimizationResult(x=result.x, fval=result.fval, variables=result.variables, + operation_counts=operation_count, n_input_qubits=n_key, + n_output_qubits=n_value, intermediate_fval=fval, + threshold=threshold, + status=self._get_feasibility_status(problem, result.x))","[{'piece_type': 'other', 'piece_content': ""from qiskit.aqua.algorithms import NumPyMinimumEigensolver\\nfrom qiskit.optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer\\nfrom qiskit.optimization.problems import QuadraticProgram\\nfrom qiskit import BasicAer\\nfrom docplex.mp.model import Model\\n\\nbackend = BasicAer.get_backend('qasm_simulator')\\n\\nmodel = Model()\\nx0 = model.binary_var(name='x0')\\nx1 = model.binary_var(name='x1')\\nx2 = model.binary_var(name='x2')\\nmodel.minimize(-x0+2*x1-3*x2-2*x0*x2-1*x1*x2)\\nqp = QuadraticProgram()\\nqp.from_docplex(model)\\n\\ngrover_optimizer = GroverOptimizer(6, num_iterations=10, quantum_instance=backend)\\nresults = grover_optimizer.solve(qp)""}, {'piece_type': 'error message', 'piece_content': 'No classical registers in circuit ""circuit9"", counts will be empty.\\nTraceback (most recent call last):\\nFile ""scratch.py"", line 101, in \\nresults = grover_optimizer.solve(qp)\\nFile ""/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py"", line 218, in solve\\noutcome = self._measure(circuit)\\nFile ""/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py"", line 283, in _measure\\nfreq[-1] = (freq[-1][0], 1.0 - sum(x[1] for x in freq[0:len(freq) - 1]))\\nIndexError: list index out of range'}]","No classical registers in circuit ""circuit9"", counts will be empty. +Traceback (most recent call last): +File ""scratch.py"", line 101, in +results = grover_optimizer.solve(qp) +File ""/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py"", line 218, in solve +outcome = self._measure(circuit) +File ""/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py"", line 283, in _measure +freq[-1] = (freq[-1][0], 1.0 - sum(x[1] for x in freq[0:len(freq) - 1])) +IndexError: list index out of range",IndexError +" def _get_probs(self, qc: QuantumCircuit) -> Dict[str, float]: + """"""Gets probabilities from a given backend."""""" + # Execute job and filter results. + result = self.quantum_instance.execute(qc) + if self.quantum_instance.is_statevector: + state = np.round(result.get_statevector(qc), 5) + keys = [bin(i)[2::].rjust(int(np.log2(len(state))), '0')[::-1] + for i in range(0, len(state))] + probs = [np.round(abs(a) * abs(a), 5) for a in state] + hist = dict(zip(keys, probs)) + else: + state = result.get_counts(qc) + shots = self.quantum_instance.run_config.shots + hist = {} + for key in state: + hist[key[::-1]] = state[key] / shots + hist = dict(filter(lambda p: p[1] > 0, hist.items())) + return hist"," def _get_probs(self, qc: QuantumCircuit) -> Dict[str, float]: + """"""Gets probabilities from a given backend."""""" + # Execute job and filter results. + result = self.quantum_instance.execute(qc) + if self.quantum_instance.is_statevector: + state = np.round(result.get_statevector(qc), 5) + keys = [bin(i)[2::].rjust(int(np.log2(len(state))), '0')[::-1] + for i in range(0, len(state))] + probs = [np.round(abs(a) * abs(a), 5) for a in state] + hist = dict(zip(keys, probs)) + else: + state = result.get_counts(qc) + shots = self.quantum_instance.run_config.shots + hist = {} + for key in state: + hist[key] = state[key] / shots + hist = dict(filter(lambda p: p[1] > 0, hist.items())) + + return hist","[{'piece_type': 'other', 'piece_content': ""from qiskit.aqua.algorithms import NumPyMinimumEigensolver\\nfrom qiskit.optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer\\nfrom qiskit.optimization.problems import QuadraticProgram\\nfrom qiskit import BasicAer\\nfrom docplex.mp.model import Model\\n\\nbackend = BasicAer.get_backend('qasm_simulator')\\n\\nmodel = Model()\\nx0 = model.binary_var(name='x0')\\nx1 = model.binary_var(name='x1')\\nx2 = model.binary_var(name='x2')\\nmodel.minimize(-x0+2*x1-3*x2-2*x0*x2-1*x1*x2)\\nqp = QuadraticProgram()\\nqp.from_docplex(model)\\n\\ngrover_optimizer = GroverOptimizer(6, num_iterations=10, quantum_instance=backend)\\nresults = grover_optimizer.solve(qp)""}, {'piece_type': 'error message', 'piece_content': 'No classical registers in circuit ""circuit9"", counts will be empty.\\nTraceback (most recent call last):\\nFile ""scratch.py"", line 101, in \\nresults = grover_optimizer.solve(qp)\\nFile ""/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py"", line 218, in solve\\noutcome = self._measure(circuit)\\nFile ""/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py"", line 283, in _measure\\nfreq[-1] = (freq[-1][0], 1.0 - sum(x[1] for x in freq[0:len(freq) - 1]))\\nIndexError: list index out of range'}]","No classical registers in circuit ""circuit9"", counts will be empty. +Traceback (most recent call last): +File ""scratch.py"", line 101, in +results = grover_optimizer.solve(qp) +File ""/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py"", line 218, in solve +outcome = self._measure(circuit) +File ""/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py"", line 283, in _measure +freq[-1] = (freq[-1][0], 1.0 - sum(x[1] for x in freq[0:len(freq) - 1])) +IndexError: list index out of range",IndexError +" def get_kernel_matrix(quantum_instance, feature_map, x1_vec, x2_vec=None, enforce_psd=True): + """""" + Construct kernel matrix, if x2_vec is None, self-innerproduct is conducted. + + Notes: + When using `statevector_simulator`, + we only build the circuits for Psi(x1)|0> rather than + Psi(x2)^dagger Psi(x1)|0>, and then we perform the inner product classically. + That is, for `statevector_simulator`, + the total number of circuits will be O(N) rather than + O(N^2) for `qasm_simulator`. + + Args: + quantum_instance (QuantumInstance): quantum backend with all settings + feature_map (FeatureMap): a feature map that maps data to feature space + x1_vec (numpy.ndarray): data points, 2-D array, N1xD, where N1 is the number of data, + D is the feature dimension + x2_vec (numpy.ndarray): data points, 2-D array, N2xD, where N2 is the number of data, + D is the feature dimension + enforce_psd (bool): enforces that the kernel matrix is positive semi-definite by setting + negative eigenvalues to zero. This is only applied in the symmetric + case, i.e., if `x2_vec == None`. + Returns: + numpy.ndarray: 2-D matrix, N1xN2 + """""" + + if isinstance(feature_map, QuantumCircuit): + use_parameterized_circuits = True + else: + use_parameterized_circuits = feature_map.support_parameterized_circuit + + if x2_vec is None: + is_symmetric = True + x2_vec = x1_vec + else: + is_symmetric = False + + is_statevector_sim = quantum_instance.is_statevector + + measurement = not is_statevector_sim + measurement_basis = '0' * feature_map.num_qubits + mat = np.ones((x1_vec.shape[0], x2_vec.shape[0])) + + # get all indices + if is_symmetric: + mus, nus = np.triu_indices(x1_vec.shape[0], k=1) # remove diagonal term + else: + mus, nus = np.indices((x1_vec.shape[0], x2_vec.shape[0])) + mus = np.asarray(mus.flat) + nus = np.asarray(nus.flat) + + if is_statevector_sim: + if is_symmetric: + to_be_computed_data = x1_vec + else: + to_be_computed_data = np.concatenate((x1_vec, x2_vec)) + + if use_parameterized_circuits: + # build parameterized circuits, it could be slower for building circuit + # but overall it should be faster since it only transpile one circuit + feature_map_params = ParameterVector('x', feature_map.feature_dimension) + parameterized_circuit = QSVM._construct_circuit( + (feature_map_params, feature_map_params), feature_map, measurement, + is_statevector_sim=is_statevector_sim) + parameterized_circuit = quantum_instance.transpile(parameterized_circuit)[0] + circuits = [parameterized_circuit.assign_parameters({feature_map_params: x}) + for x in to_be_computed_data] + else: + # the second x is redundant + to_be_computed_data_pair = [(x, x) for x in to_be_computed_data] + if logger.isEnabledFor(logging.DEBUG): + logger.debug(""Building circuits:"") + TextProgressBar(sys.stderr) + circuits = parallel_map(QSVM._construct_circuit, + to_be_computed_data_pair, + task_args=(feature_map, measurement, is_statevector_sim), + num_processes=aqua_globals.num_processes) + + results = quantum_instance.execute(circuits, + had_transpiled=use_parameterized_circuits) + + if logger.isEnabledFor(logging.DEBUG): + logger.debug(""Calculating overlap:"") + TextProgressBar(sys.stderr) + + offset = 0 if is_symmetric else len(x1_vec) + matrix_elements = parallel_map(QSVM._compute_overlap, list(zip(mus, nus + offset)), + task_args=(results, + is_statevector_sim, measurement_basis), + num_processes=aqua_globals.num_processes) + + for i, j, value in zip(mus, nus, matrix_elements): + mat[i, j] = value + if is_symmetric: + mat[j, i] = mat[i, j] + else: + for idx in range(0, len(mus), QSVM.BATCH_SIZE): + to_be_computed_data_pair = [] + to_be_computed_index = [] + for sub_idx in range(idx, min(idx + QSVM.BATCH_SIZE, len(mus))): + i = mus[sub_idx] + j = nus[sub_idx] + x1 = x1_vec[i] + x2 = x2_vec[j] + if not np.all(x1 == x2): + to_be_computed_data_pair.append((x1, x2)) + to_be_computed_index.append((i, j)) + + if use_parameterized_circuits: + # build parameterized circuits, it could be slower for building circuit + # but overall it should be faster since it only transpile one circuit + feature_map_params_x = ParameterVector('x', feature_map.feature_dimension) + feature_map_params_y = ParameterVector('y', feature_map.feature_dimension) + parameterized_circuit = QSVM._construct_circuit( + (feature_map_params_x, feature_map_params_y), feature_map, measurement, + is_statevector_sim=is_statevector_sim) + parameterized_circuit = quantum_instance.transpile(parameterized_circuit)[0] + circuits = [parameterized_circuit.assign_parameters({feature_map_params_x: x, + feature_map_params_y: y}) + for x, y in to_be_computed_data_pair] + else: + if logger.isEnabledFor(logging.DEBUG): + logger.debug(""Building circuits:"") + TextProgressBar(sys.stderr) + circuits = parallel_map(QSVM._construct_circuit, + to_be_computed_data_pair, + task_args=(feature_map, measurement), + num_processes=aqua_globals.num_processes) + + results = quantum_instance.execute(circuits, + had_transpiled=use_parameterized_circuits) + + if logger.isEnabledFor(logging.DEBUG): + logger.debug(""Calculating overlap:"") + TextProgressBar(sys.stderr) + matrix_elements = parallel_map(QSVM._compute_overlap, range(len(circuits)), + task_args=(results, + is_statevector_sim, measurement_basis), + num_processes=aqua_globals.num_processes) + + for (i, j), value in zip(to_be_computed_index, matrix_elements): + mat[i, j] = value + if is_symmetric: + mat[j, i] = mat[i, j] + + if enforce_psd and is_symmetric and not is_statevector_sim: + # Find the closest positive semi-definite approximation to kernel matrix, in case it is + # symmetric. The (symmetric) matrix should always be positive semi-definite by + # construction, but this can be violated in case of noise, such as sampling noise, thus, + # the adjustment is only done if NOT using the statevector simulation. + D, U = np.linalg.eig(mat) + mat = U @ np.diag(np.maximum(0, D)) @ U.transpose() + + return mat"," def get_kernel_matrix(quantum_instance, feature_map, x1_vec, x2_vec=None): + """""" + Construct kernel matrix, if x2_vec is None, self-innerproduct is conducted. + + Notes: + When using `statevector_simulator`, + we only build the circuits for Psi(x1)|0> rather than + Psi(x2)^dagger Psi(x1)|0>, and then we perform the inner product classically. + That is, for `statevector_simulator`, + the total number of circuits will be O(N) rather than + O(N^2) for `qasm_simulator`. + + Args: + quantum_instance (QuantumInstance): quantum backend with all settings + feature_map (FeatureMap): a feature map that maps data to feature space + x1_vec (numpy.ndarray): data points, 2-D array, N1xD, where N1 is the number of data, + D is the feature dimension + x2_vec (numpy.ndarray): data points, 2-D array, N2xD, where N2 is the number of data, + D is the feature dimension + Returns: + numpy.ndarray: 2-D matrix, N1xN2 + """""" + + if isinstance(feature_map, QuantumCircuit): + use_parameterized_circuits = True + else: + use_parameterized_circuits = feature_map.support_parameterized_circuit + + if x2_vec is None: + is_symmetric = True + x2_vec = x1_vec + else: + is_symmetric = False + + is_statevector_sim = quantum_instance.is_statevector + + measurement = not is_statevector_sim + measurement_basis = '0' * feature_map.num_qubits + mat = np.ones((x1_vec.shape[0], x2_vec.shape[0])) + + # get all indices + if is_symmetric: + mus, nus = np.triu_indices(x1_vec.shape[0], k=1) # remove diagonal term + else: + mus, nus = np.indices((x1_vec.shape[0], x2_vec.shape[0])) + mus = np.asarray(mus.flat) + nus = np.asarray(nus.flat) + + if is_statevector_sim: + if is_symmetric: + to_be_computed_data = x1_vec + else: + to_be_computed_data = np.concatenate((x1_vec, x2_vec)) + + if use_parameterized_circuits: + # build parameterized circuits, it could be slower for building circuit + # but overall it should be faster since it only transpile one circuit + feature_map_params = ParameterVector('x', feature_map.feature_dimension) + parameterized_circuit = QSVM._construct_circuit( + (feature_map_params, feature_map_params), feature_map, measurement, + is_statevector_sim=is_statevector_sim) + parameterized_circuit = quantum_instance.transpile(parameterized_circuit)[0] + circuits = [parameterized_circuit.assign_parameters({feature_map_params: x}) + for x in to_be_computed_data] + else: + # the second x is redundant + to_be_computed_data_pair = [(x, x) for x in to_be_computed_data] + if logger.isEnabledFor(logging.DEBUG): + logger.debug(""Building circuits:"") + TextProgressBar(sys.stderr) + circuits = parallel_map(QSVM._construct_circuit, + to_be_computed_data_pair, + task_args=(feature_map, measurement, is_statevector_sim), + num_processes=aqua_globals.num_processes) + + results = quantum_instance.execute(circuits, + had_transpiled=use_parameterized_circuits) + + if logger.isEnabledFor(logging.DEBUG): + logger.debug(""Calculating overlap:"") + TextProgressBar(sys.stderr) + + offset = 0 if is_symmetric else len(x1_vec) + matrix_elements = parallel_map(QSVM._compute_overlap, list(zip(mus, nus + offset)), + task_args=(results, + is_statevector_sim, measurement_basis), + num_processes=aqua_globals.num_processes) + + for i, j, value in zip(mus, nus, matrix_elements): + mat[i, j] = value + if is_symmetric: + mat[j, i] = mat[i, j] + else: + for idx in range(0, len(mus), QSVM.BATCH_SIZE): + to_be_computed_data_pair = [] + to_be_computed_index = [] + for sub_idx in range(idx, min(idx + QSVM.BATCH_SIZE, len(mus))): + i = mus[sub_idx] + j = nus[sub_idx] + x1 = x1_vec[i] + x2 = x2_vec[j] + if not np.all(x1 == x2): + to_be_computed_data_pair.append((x1, x2)) + to_be_computed_index.append((i, j)) + + if use_parameterized_circuits: + # build parameterized circuits, it could be slower for building circuit + # but overall it should be faster since it only transpile one circuit + feature_map_params_x = ParameterVector('x', feature_map.feature_dimension) + feature_map_params_y = ParameterVector('y', feature_map.feature_dimension) + parameterized_circuit = QSVM._construct_circuit( + (feature_map_params_x, feature_map_params_y), feature_map, measurement, + is_statevector_sim=is_statevector_sim) + parameterized_circuit = quantum_instance.transpile(parameterized_circuit)[0] + circuits = [parameterized_circuit.assign_parameters({feature_map_params_x: x, + feature_map_params_y: y}) + for x, y in to_be_computed_data_pair] + else: + if logger.isEnabledFor(logging.DEBUG): + logger.debug(""Building circuits:"") + TextProgressBar(sys.stderr) + circuits = parallel_map(QSVM._construct_circuit, + to_be_computed_data_pair, + task_args=(feature_map, measurement), + num_processes=aqua_globals.num_processes) + + results = quantum_instance.execute(circuits, + had_transpiled=use_parameterized_circuits) + + if logger.isEnabledFor(logging.DEBUG): + logger.debug(""Calculating overlap:"") + TextProgressBar(sys.stderr) + matrix_elements = parallel_map(QSVM._compute_overlap, range(len(circuits)), + task_args=(results, + is_statevector_sim, measurement_basis), + num_processes=aqua_globals.num_processes) + + for (i, j), value in zip(to_be_computed_index, matrix_elements): + mat[i, j] = value + if is_symmetric: + mat[j, i] = mat[i, j] + + return mat","[{'piece_type': 'reproducing source code', 'piece_content': 'seed = 10598\\n\\nfeature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement=\\'linear\\')\\nqsvm = QSVM(feature_map, training_input, test_input, datapoints[0])\\n\\nbackend = Aer.get_backend(\\'qasm_simulator\\')\\nquantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)\\n\\nresult = qsvm.run(quantum_instance)\\n\\nprint(""testing success ratio: {}"".format(result[\\'testing_accuracy\\']))\\nprint(""preduction of datapoints:"")\\nprint(""ground truth: {}"".format(map_label_to_class_name(datapoints[1], qsvm.label_to_class)))\\nprint(""prediction: {}"".format(result[\\'predicted_classes\\']))'}, {'piece_type': 'error message', 'piece_content': '---------------------------------------------------------------------------\\nDQCPError Traceback (most recent call last)\\nin\\n7 quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)\\n8\\n----> 9 result = qsvm.run(quantum_instance)\\n10\\n11 print(""testing success ratio: {}"".format(result[\\'testing_accuracy\\']))\\n\\n~/github/qiskit/aqua/qiskit/aqua/algorithms/quantum_algorithm.py in run(self, quantum_instance, **kwargs)\\n68 self.quantum_instance = quantum_instance\\n69\\n---> 70 return self._run()\\n71\\n72 @abstractmethod\\n\\n~/github/qiskit/aqua/qiskit/aqua/algorithms/classifiers/qsvm/qsvm.py in _run(self)\\n456\\n457 def _run(self):\\n--> 458 return self.instance.run()\\n459\\n460 @property\\n\\n~/github/qiskit/aqua/qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py in run(self)\\n134 def run(self):\\n135 """"""Put the train, test, predict together.""""""\\n--> 136 self.train(self._qalgo.training_dataset[0], self._qalgo.training_dataset[1])\\n137 if self._qalgo.test_dataset is not None:\\n138 self.test(self._qalgo.test_dataset[0], self._qalgo.test_dataset[1])\\n\\n~/github/qiskit/aqua/qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py in train(self, data, labels)\\n81 labels = labels * 2 - 1 # map label from 0 --> -1 and 1 --> 1\\n82 labels = labels.astype(np.float)\\n---> 83 [alpha, b, support] = optimize_svm(kernel_matrix, labels, scaling=scaling)\\n84 support_index = np.where(support)\\n85 alphas = alpha[support_index]\\n\\n~/github/qiskit/aqua/qiskit/aqua/utils/qp_solver.py in optimize_svm(kernel_matrix, y, scaling, maxiter, show_progress, max_iters)\\n88 [G@x <= h,\\n89 A@x == b])\\n---> 90 prob.solve(verbose=show_progress, qcp=True)\\n91 result = np.asarray(x.value).reshape((n, 1))\\n92 alpha = result * scaling\\n\\n~/envs/qopt/lib/python3.7/site-packages/cvxpy/problems/problem.py in solve(self, *args, **kwargs)\\n393 else:\\n394 solve_func = Problem._solve\\n--> 395 return solve_func(self, *args, **kwargs)\\n396\\n397 @classmethod\\n\\n~/envs/qopt/lib/python3.7/site-packages/cvxpy/problems/problem.py in _solve(self, solver, warm_start, verbose, gp, qcp, requires_grad, enforce_dpp, **kwargs)\\n731 if qcp and not self.is_dcp():\\n732 if not self.is_dqcp():\\n--> 733 raise error.DQCPError(""The problem is not DQCP."")\\n734 reductions = [dqcp2dcp.Dqcp2Dcp()]\\n735 if type(self.objective) == Maximize:\\n\\nDQCPError: The problem is not DQCP.'}]","--------------------------------------------------------------------------- +DQCPError Traceback (most recent call last) +in +7 quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) +8 +----> 9 result = qsvm.run(quantum_instance) +10 +11 print(""testing success ratio: {}"".format(result['testing_accuracy'])) + +~/github/qiskit/aqua/qiskit/aqua/algorithms/quantum_algorithm.py in run(self, quantum_instance, **kwargs) +68 self.quantum_instance = quantum_instance +69 +---> 70 return self._run() +71 +72 @abstractmethod + +~/github/qiskit/aqua/qiskit/aqua/algorithms/classifiers/qsvm/qsvm.py in _run(self) +456 +457 def _run(self): +--> 458 return self.instance.run() +459 +460 @property + +~/github/qiskit/aqua/qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py in run(self) +134 def run(self): +135 """"""Put the train, test, predict together."""""" +--> 136 self.train(self._qalgo.training_dataset[0], self._qalgo.training_dataset[1]) +137 if self._qalgo.test_dataset is not None: +138 self.test(self._qalgo.test_dataset[0], self._qalgo.test_dataset[1]) + +~/github/qiskit/aqua/qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py in train(self, data, labels) +81 labels = labels * 2 - 1 # map label from 0 --> -1 and 1 --> 1 +82 labels = labels.astype(np.float) +---> 83 [alpha, b, support] = optimize_svm(kernel_matrix, labels, scaling=scaling) +84 support_index = np.where(support) +85 alphas = alpha[support_index] + +~/github/qiskit/aqua/qiskit/aqua/utils/qp_solver.py in optimize_svm(kernel_matrix, y, scaling, maxiter, show_progress, max_iters) +88 [G@x <= h, +89 A@x == b]) +---> 90 prob.solve(verbose=show_progress, qcp=True) +91 result = np.asarray(x.value).reshape((n, 1)) +92 alpha = result * scaling + +~/envs/qopt/lib/python3.7/site-packages/cvxpy/problems/problem.py in solve(self, *args, **kwargs) +393 else: +394 solve_func = Problem._solve +--> 395 return solve_func(self, *args, **kwargs) +396 +397 @classmethod + +~/envs/qopt/lib/python3.7/site-packages/cvxpy/problems/problem.py in _solve(self, solver, warm_start, verbose, gp, qcp, requires_grad, enforce_dpp, **kwargs) +731 if qcp and not self.is_dcp(): +732 if not self.is_dqcp(): +--> 733 raise error.DQCPError(""The problem is not DQCP."") +734 reductions = [dqcp2dcp.Dqcp2Dcp()] +735 if type(self.objective) == Maximize: + +DQCPError: The problem is not DQCP.",DQCPError +" def optimize(self, num_vars, objective_function, gradient_function=None, + variable_bounds=None, initial_point=None): + num_procs = multiprocessing.cpu_count() - 1 + num_procs = \\ + num_procs if self._max_processes is None else min(num_procs, self._max_processes) + num_procs = num_procs if num_procs >= 0 else 0 + + if platform.system() == 'Darwin': + # Changed in version 3.8: On macOS, the spawn start method is now the + # default. The fork start method should be considered unsafe as it can + # lead to crashes. + # However P_BFGS doesn't support spawn, so we revert to single process. + major, minor, _ = platform.python_version_tuple() + if major > '3' or (major == '3' and minor >= '8'): + num_procs = 0 + logger.warning(""For MacOS, python >= 3.8, using only current process. "" + ""Multiple core use not supported."") + elif platform.system() == 'Windows': + num_procs = 0 + logger.warning(""For Windows, using only current process. "" + ""Multiple core use not supported."") + + queue = multiprocessing.Queue() + # bounds for additional initial points in case bounds has any None values + threshold = 2 * np.pi + if variable_bounds is None: + variable_bounds = [(-threshold, threshold)] * num_vars + low = [(l if l is not None else -threshold) for (l, u) in variable_bounds] + high = [(u if u is not None else threshold) for (l, u) in variable_bounds] + + def optimize_runner(_queue, _i_pt): # Multi-process sampling + _sol, _opt, _nfev = self._optimize(num_vars, objective_function, + gradient_function, variable_bounds, _i_pt) + _queue.put((_sol, _opt, _nfev)) + + # Start off as many other processes running the optimize (can be 0) + processes = [] + for _ in range(num_procs): + i_pt = aqua_globals.random.uniform(low, high) # Another random point in bounds + p = multiprocessing.Process(target=optimize_runner, args=(queue, i_pt)) + processes.append(p) + p.start() + + # While the one _optimize in this process below runs the other processes will + # be running to. This one runs + # with the supplied initial point. The process ones have their own random one + sol, opt, nfev = self._optimize(num_vars, objective_function, + gradient_function, variable_bounds, initial_point) + + for p in processes: + # For each other process we wait now for it to finish and see if it has + # a better result than above + p.join() + p_sol, p_opt, p_nfev = queue.get() + if p_opt < opt: + sol, opt = p_sol, p_opt + nfev += p_nfev + + return sol, opt, nfev"," def optimize(self, num_vars, objective_function, gradient_function=None, + variable_bounds=None, initial_point=None): + num_procs = multiprocessing.cpu_count() - 1 + num_procs = \\ + num_procs if self._max_processes is None else min(num_procs, self._max_processes) + num_procs = num_procs if num_procs >= 0 else 0 + + if platform.system() == ""Windows"": + num_procs = 0 + logger.warning(""Using only current process. Multiple core use not supported in Windows"") + + queue = multiprocessing.Queue() + # bounds for additional initial points in case bounds has any None values + threshold = 2 * np.pi + if variable_bounds is None: + variable_bounds = [(-threshold, threshold)] * num_vars + low = [(l if l is not None else -threshold) for (l, u) in variable_bounds] + high = [(u if u is not None else threshold) for (l, u) in variable_bounds] + + def optimize_runner(_queue, _i_pt): # Multi-process sampling + _sol, _opt, _nfev = self._optimize(num_vars, objective_function, + gradient_function, variable_bounds, _i_pt) + _queue.put((_sol, _opt, _nfev)) + + # Start off as many other processes running the optimize (can be 0) + processes = [] + for _ in range(num_procs): + i_pt = aqua_globals.random.uniform(low, high) # Another random point in bounds + p = multiprocessing.Process(target=optimize_runner, args=(queue, i_pt)) + processes.append(p) + p.start() + + # While the one _optimize in this process below runs the other processes will + # be running to. This one runs + # with the supplied initial point. The process ones have their own random one + sol, opt, nfev = self._optimize(num_vars, objective_function, + gradient_function, variable_bounds, initial_point) + + for p in processes: + # For each other process we wait now for it to finish and see if it has + # a better result than above + p.join() + p_sol, p_opt, p_nfev = queue.get() + if p_opt < opt: + sol, opt = p_sol, p_opt + nfev += p_nfev + + return sol, opt, nfev","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\n\\nFile ""/qiskit-aqua/test/aqua/test_optimizers.py"", line 68, in test_p_bfgs\\nres = self._optimize(optimizer)\\n\\nFile ""/qiskit-aqua/test/aqua/test_optimizers.py"", line 37, in _optimize\\nres = optimizer.optimize(len(x_0), rosen, initial_point=x_0)\\n\\nFile ""/qiskit-aqua/qiskit/aqua/components/optimizers/p_bfgs.py"", line 120, in optimize\\np.start()\\n\\nFile ""/multiprocessing/process.py"", line 121, in start\\nself._popen = self._Popen(self)\\n\\nFile ""/multiprocessing/context.py"", line 224, in _Popen\\nreturn _default_context.get_context().Process._Popen(process_obj)\\n\\nFile ""/multiprocessing/context.py"", line 283, in _Popen\\nreturn Popen(process_obj)\\n\\nFile ""/multiprocessing/popen_spawn_posix.py"", line 32, in __init__\\nsuper().__init__(process_obj)\\n\\nFile ""/multiprocessing/popen_fork.py"", line 19, in __init__\\nself._launch(process_obj)\\n\\nFile ""/multiprocessing/popen_spawn_posix.py"", line 47, in _launch\\nreduction.dump(process_obj, fp)\\n\\nFile ""/multiprocessing/reduction.py"", line 60, in dump\\nForkingPickler(file, protocol).dump(obj)\\n\\nAttributeError: Can\\'t pickle local object \\'P_BFGS.optimize..optimize_runner\\''}]","Traceback (most recent call last): + +File ""/qiskit-aqua/test/aqua/test_optimizers.py"", line 68, in test_p_bfgs +res = self._optimize(optimizer) + +File ""/qiskit-aqua/test/aqua/test_optimizers.py"", line 37, in _optimize +res = optimizer.optimize(len(x_0), rosen, initial_point=x_0) + +File ""/qiskit-aqua/qiskit/aqua/components/optimizers/p_bfgs.py"", line 120, in optimize +p.start() + +File ""/multiprocessing/process.py"", line 121, in start +self._popen = self._Popen(self) + +File ""/multiprocessing/context.py"", line 224, in _Popen +return _default_context.get_context().Process._Popen(process_obj) + +File ""/multiprocessing/context.py"", line 283, in _Popen +return Popen(process_obj) + +File ""/multiprocessing/popen_spawn_posix.py"", line 32, in __init__ +super().__init__(process_obj) + +File ""/multiprocessing/popen_fork.py"", line 19, in __init__ +self._launch(process_obj) + +File ""/multiprocessing/popen_spawn_posix.py"", line 47, in _launch +reduction.dump(process_obj, fp) + +File ""/multiprocessing/reduction.py"", line 60, in dump +ForkingPickler(file, protocol).dump(obj) + +AttributeError: Can't pickle local object 'P_BFGS.optimize..optimize_runner'",AttributeError +" def solve(self, problem: QuadraticProgram) -> MinimumEigenOptimizerResult: + """"""Tries to solves the given problem using the optimizer. + + Runs the optimizer to try to solve the optimization problem. + + Args: + problem: The problem to be solved. + + Returns: + The result of the optimizer applied to the problem. + + Raises: + QiskitOptimizationError: If problem not compatible. + """""" + # check compatibility and raise exception if incompatible + msg = self.get_compatibility_msg(problem) + if len(msg) > 0: + raise QiskitOptimizationError('Incompatible problem: {}'.format(msg)) + + # convert problem to QUBO + qubo_converter = QuadraticProgramToQubo() + problem_ = qubo_converter.encode(problem) + + # construct operator and offset + operator_converter = QuadraticProgramToIsing() + operator, offset = operator_converter.encode(problem_) + + # only try to solve non-empty Ising Hamiltonians + if operator.num_qubits > 0: + + # approximate ground state of operator using min eigen solver + eigen_results = self._min_eigen_solver.compute_minimum_eigenvalue(operator) + + # analyze results + samples = eigenvector_to_solutions(eigen_results.eigenstate, operator) + samples = [(res[0], problem_.objective.sense.value * (res[1] + offset), res[2]) + for res in samples] + samples.sort(key=lambda x: problem_.objective.sense.value * x[1]) + x = samples[0][0] + fval = samples[0][1] + + # if Hamiltonian is empty, then the objective function is constant to the offset + else: + x = [0]*problem_.get_num_binary_vars() + fval = offset + x_str = '0'*problem_.get_num_binary_vars() + samples = [(x_str, offset, 1.0)] + + # translate result back to integers + opt_res = MinimumEigenOptimizerResult(x, fval, samples, qubo_converter) + opt_res = qubo_converter.decode(opt_res) + + # translate results back to original problem + return opt_res"," def solve(self, problem: QuadraticProgram) -> MinimumEigenOptimizerResult: + """"""Tries to solves the given problem using the optimizer. + + Runs the optimizer to try to solve the optimization problem. + + Args: + problem: The problem to be solved. + + Returns: + The result of the optimizer applied to the problem. + + Raises: + QiskitOptimizationError: If problem not compatible. + """""" + # check compatibility and raise exception if incompatible + msg = self.get_compatibility_msg(problem) + if len(msg) > 0: + raise QiskitOptimizationError('Incompatible problem: {}'.format(msg)) + + # convert problem to QUBO + qubo_converter = QuadraticProgramToQubo() + problem_ = qubo_converter.encode(problem) + + # construct operator and offset + operator_converter = QuadraticProgramToIsing() + operator, offset = operator_converter.encode(problem_) + + # approximate ground state of operator using min eigen solver + eigen_results = self._min_eigen_solver.compute_minimum_eigenvalue(operator) + + # analyze results + samples = eigenvector_to_solutions(eigen_results.eigenstate, operator) + samples = [(res[0], problem_.objective.sense.value * (res[1] + offset), res[2]) + for res in samples] + samples.sort(key=lambda x: problem_.objective.sense.value * x[1]) + + # translate result back to integers + opt_res = MinimumEigenOptimizerResult(samples[0][0], samples[0][1], samples, qubo_converter) + opt_res = qubo_converter.decode(opt_res) + + # translate results back to original problem + return opt_res","[{'piece_type': 'error message', 'piece_content': '------------------\\nrqaoa_result = rqaoa.solve(qubo)\\nprint(rqaoa_result)\\n------------------\\n\\n---------------------------------------------------------------------------\\nQiskitOptimizationError Traceback (most recent call last)\\n in \\n----> 1 rqaoa_result = rqaoa.solve(qubo)\\n2 print(rqaoa_result)\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py in solve(self, problem)\\n171\\n172 # 2. replace x_i by -x_j\\n--> 173 problem_ = problem_.substitute_variables(variables={i: (j, -1)})\\n174 if problem_.status == QuadraticProgram.Status.INFEASIBLE:\\n175 raise QiskitOptimizationError(\\'Infeasible due to variable substitution\\')\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, constants, variables)\\n856 - Coefficient of variable substitution is zero.\\n857 """"""\\n--> 858 return SubstituteVariables().substitute_variables(self, constants, variables)\\n859\\n860\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, src, constants, variables)\\n901 self._src = src\\n902 self._dst = QuadraticProgram(src.name)\\n--> 903 self._subs_dict(constants, variables)\\n904 results = [\\n905 self._variables(),\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in _subs_dict(self, constants, variables)\\n960 j_2 = self._src.get_variable(j).name\\n961 if i_2 == j_2:\\n--> 962 raise QiskitOptimizationError(\\n963 \\'Cannot substitute the same variable: {} <- {} {}\\'.format(i, j, v))\\n964 if i_2 in subs:\\n\\nQiskitOptimizationError: \\'Cannot substitute the same variable: 0 <- 0 -1\\'\\nQiskitOptimizationError: \\'Cannot substitute the same variable: 0 <- 0 -1\\''}]","------------------ +rqaoa_result = rqaoa.solve(qubo) +print(rqaoa_result) +------------------ + +--------------------------------------------------------------------------- +QiskitOptimizationError Traceback (most recent call last) + in +----> 1 rqaoa_result = rqaoa.solve(qubo) +2 print(rqaoa_result) + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py in solve(self, problem) +171 +172 # 2. replace x_i by -x_j +--> 173 problem_ = problem_.substitute_variables(variables={i: (j, -1)}) +174 if problem_.status == QuadraticProgram.Status.INFEASIBLE: +175 raise QiskitOptimizationError('Infeasible due to variable substitution') + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, constants, variables) +856 - Coefficient of variable substitution is zero. +857 """""" +--> 858 return SubstituteVariables().substitute_variables(self, constants, variables) +859 +860 + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, src, constants, variables) +901 self._src = src +902 self._dst = QuadraticProgram(src.name) +--> 903 self._subs_dict(constants, variables) +904 results = [ +905 self._variables(), + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in _subs_dict(self, constants, variables) +960 j_2 = self._src.get_variable(j).name +961 if i_2 == j_2: +--> 962 raise QiskitOptimizationError( +963 'Cannot substitute the same variable: {} <- {} {}'.format(i, j, v)) +964 if i_2 in subs: + +QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1' +QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'",QiskitOptimizationError +" def solve(self, problem: QuadraticProgram) -> OptimizationResult: + """"""Tries to solve the given problem using the recursive optimizer. + + Runs the optimizer to try to solve the optimization problem. + + Args: + problem: The problem to be solved. + + Returns: + The result of the optimizer applied to the problem. + + Raises: + QiskitOptimizationError: Incompatible problem. + QiskitOptimizationError: Infeasible due to variable substitution + """""" + # check compatibility and raise exception if incompatible + msg = self.get_compatibility_msg(problem) + if len(msg) > 0: + raise QiskitOptimizationError('Incompatible problem: {}'.format(msg)) + + # convert problem to QUBO, this implicitly checks if the problem is compatible + qubo_converter = QuadraticProgramToQubo() + problem_ = qubo_converter.encode(problem) + problem_ref = deepcopy(problem_) + + # run recursive optimization until the resulting problem is small enough + replacements = {} + while problem_.get_num_vars() > self._min_num_vars: + + # solve current problem with optimizer + result = self._min_eigen_optimizer.solve(problem_) + + # analyze results to get strongest correlation + correlations = result.get_correlations() + i, j = self._find_strongest_correlation(correlations) + + x_i = problem_.variables[i].name + x_j = problem_.variables[j].name + if correlations[i, j] > 0: + # set x_i = x_j + problem_ = problem_.substitute_variables(variables={i: (j, 1)}) + if problem_.status == QuadraticProgram.Status.INFEASIBLE: + raise QiskitOptimizationError('Infeasible due to variable substitution') + replacements[x_i] = (x_j, 1) + else: + # set x_i = 1 - x_j, this is done in two steps: + # 1. set x_i = 1 + x_i + # 2. set x_i = -x_j + + # 1a. get additional offset + constant = problem_.objective.constant + constant += problem_.objective.linear[i] + constant += problem_.objective.quadratic[i, i] + problem_.objective.constant = constant + + # 1b. get additional linear part + for k in range(problem_.get_num_vars()): + coeff = problem_.objective.linear[k] + if k == i: + coeff += 2*problem_.objective.quadratic[i, k] + else: + coeff += problem_.objective.quadratic[i, k] + + # set new coefficient if not too small + if np.abs(coeff) > 1e-10: + problem_.objective.linear[k] = coeff + else: + problem_.objective.linear[k] = 0 + + # 2. replace x_i by -x_j + problem_ = problem_.substitute_variables(variables={i: (j, -1)}) + if problem_.status == QuadraticProgram.Status.INFEASIBLE: + raise QiskitOptimizationError('Infeasible due to variable substitution') + replacements[x_i] = (x_j, -1) + + # solve remaining problem + result = self._min_num_vars_optimizer.solve(problem_) + + # unroll replacements + var_values = {} + for i, x in enumerate(problem_.variables): + var_values[x.name] = result.x[i] + + def find_value(x, replacements, var_values): + if x in var_values: + # if value for variable is known, return it + return var_values[x] + elif x in replacements: + # get replacement for variable + (y, sgn) = replacements[x] + # find details for replacing variable + value = find_value(y, replacements, var_values) + # construct, set, and return new value + var_values[x] = value if sgn == 1 else 1 - value + return var_values[x] + else: + raise QiskitOptimizationError('Invalid values!') + + # loop over all variables to set their values + for x_i in problem_ref.variables: + if x_i.name not in var_values: + find_value(x_i.name, replacements, var_values) + + # construct result + x = [var_values[x_aux.name] for x_aux in problem_ref.variables] + fval = result.fval + results = OptimizationResult(x, fval, (replacements, qubo_converter)) + results = qubo_converter.decode(results) + return results"," def solve(self, problem: QuadraticProgram) -> OptimizationResult: + """"""Tries to solve the given problem using the recursive optimizer. + + Runs the optimizer to try to solve the optimization problem. + + Args: + problem: The problem to be solved. + + Returns: + The result of the optimizer applied to the problem. + + Raises: + QiskitOptimizationError: Incompatible problem. + QiskitOptimizationError: Infeasible due to variable substitution + """""" + # check compatibility and raise exception if incompatible + msg = self.get_compatibility_msg(problem) + if len(msg) > 0: + raise QiskitOptimizationError('Incompatible problem: {}'.format(msg)) + + # convert problem to QUBO, this implicitly checks if the problem is compatible + qubo_converter = QuadraticProgramToQubo() + problem_ = qubo_converter.encode(problem) + problem_ref = deepcopy(problem_) + + # run recursive optimization until the resulting problem is small enough + replacements = {} + while problem_.get_num_vars() > self._min_num_vars: + + # solve current problem with optimizer + result = self._min_eigen_optimizer.solve(problem_) + + # analyze results to get strongest correlation + correlations = result.get_correlations() + i, j = self._find_strongest_correlation(correlations) + + x_i = problem_.variables[i].name + x_j = problem_.variables[j].name + if correlations[i, j] > 0: + # set x_i = x_j + problem_.substitute_variables() + problem_ = problem_.substitute_variables(variables={i: (j, 1)}) + if problem_.status == QuadraticProgram.Status.INFEASIBLE: + raise QiskitOptimizationError('Infeasible due to variable substitution') + replacements[x_i] = (x_j, 1) + else: + # set x_i = 1 - x_j, this is done in two steps: + # 1. set x_i = 1 + x_i + # 2. set x_i = -x_j + + # 1a. get additional offset + constant = problem_.objective.constant + constant += problem_.objective.quadratic[i, i] + constant += problem_.objective.linear[i] + problem_.objective.constant = constant + + # 1b. get additional linear part + for k in range(problem_.get_num_vars()): + coeff = problem_.objective.quadratic[i, k] + if np.abs(coeff) > 1e-10: + coeff += problem_.objective.linear[k] + problem_.objective.linear[k] = coeff + + # 2. replace x_i by -x_j + problem_ = problem_.substitute_variables(variables={i: (j, -1)}) + if problem_.status == QuadraticProgram.Status.INFEASIBLE: + raise QiskitOptimizationError('Infeasible due to variable substitution') + replacements[x_i] = (x_j, -1) + + # solve remaining problem + result = self._min_num_vars_optimizer.solve(problem_) + + # unroll replacements + var_values = {} + for i, x in enumerate(problem_.variables): + var_values[x.name] = result.x[i] + + def find_value(x, replacements, var_values): + if x in var_values: + # if value for variable is known, return it + return var_values[x] + elif x in replacements: + # get replacement for variable + (y, sgn) = replacements[x] + # find details for replacing variable + value = find_value(y, replacements, var_values) + # construct, set, and return new value + var_values[x] = value if sgn == 1 else 1 - value + return var_values[x] + else: + raise QiskitOptimizationError('Invalid values!') + + # loop over all variables to set their values + for x_i in problem_ref.variables: + if x_i.name not in var_values: + find_value(x_i.name, replacements, var_values) + + # construct result + x = [var_values[x_aux.name] for x_aux in problem_ref.variables] + fval = result.fval + results = OptimizationResult(x, fval, (replacements, qubo_converter)) + results = qubo_converter.decode(results) + return results","[{'piece_type': 'error message', 'piece_content': '------------------\\nrqaoa_result = rqaoa.solve(qubo)\\nprint(rqaoa_result)\\n------------------\\n\\n---------------------------------------------------------------------------\\nQiskitOptimizationError Traceback (most recent call last)\\n in \\n----> 1 rqaoa_result = rqaoa.solve(qubo)\\n2 print(rqaoa_result)\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py in solve(self, problem)\\n171\\n172 # 2. replace x_i by -x_j\\n--> 173 problem_ = problem_.substitute_variables(variables={i: (j, -1)})\\n174 if problem_.status == QuadraticProgram.Status.INFEASIBLE:\\n175 raise QiskitOptimizationError(\\'Infeasible due to variable substitution\\')\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, constants, variables)\\n856 - Coefficient of variable substitution is zero.\\n857 """"""\\n--> 858 return SubstituteVariables().substitute_variables(self, constants, variables)\\n859\\n860\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, src, constants, variables)\\n901 self._src = src\\n902 self._dst = QuadraticProgram(src.name)\\n--> 903 self._subs_dict(constants, variables)\\n904 results = [\\n905 self._variables(),\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in _subs_dict(self, constants, variables)\\n960 j_2 = self._src.get_variable(j).name\\n961 if i_2 == j_2:\\n--> 962 raise QiskitOptimizationError(\\n963 \\'Cannot substitute the same variable: {} <- {} {}\\'.format(i, j, v))\\n964 if i_2 in subs:\\n\\nQiskitOptimizationError: \\'Cannot substitute the same variable: 0 <- 0 -1\\'\\nQiskitOptimizationError: \\'Cannot substitute the same variable: 0 <- 0 -1\\''}]","------------------ +rqaoa_result = rqaoa.solve(qubo) +print(rqaoa_result) +------------------ + +--------------------------------------------------------------------------- +QiskitOptimizationError Traceback (most recent call last) + in +----> 1 rqaoa_result = rqaoa.solve(qubo) +2 print(rqaoa_result) + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py in solve(self, problem) +171 +172 # 2. replace x_i by -x_j +--> 173 problem_ = problem_.substitute_variables(variables={i: (j, -1)}) +174 if problem_.status == QuadraticProgram.Status.INFEASIBLE: +175 raise QiskitOptimizationError('Infeasible due to variable substitution') + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, constants, variables) +856 - Coefficient of variable substitution is zero. +857 """""" +--> 858 return SubstituteVariables().substitute_variables(self, constants, variables) +859 +860 + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, src, constants, variables) +901 self._src = src +902 self._dst = QuadraticProgram(src.name) +--> 903 self._subs_dict(constants, variables) +904 results = [ +905 self._variables(), + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in _subs_dict(self, constants, variables) +960 j_2 = self._src.get_variable(j).name +961 if i_2 == j_2: +--> 962 raise QiskitOptimizationError( +963 'Cannot substitute the same variable: {} <- {} {}'.format(i, j, v)) +964 if i_2 in subs: + +QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1' +QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'",QiskitOptimizationError +" def _find_strongest_correlation(self, correlations): + + # get absolute values and set diagonal to -1 to make sure maximum is always on off-diagonal + abs_correlations = np.abs(correlations) + for i in range(len(correlations)): + abs_correlations[i, i] = -1 + + # get index of maximum (by construction on off-diagonal) + m_max = np.argmax(abs_correlations.flatten()) + + # translate back to indices + i = int(m_max // len(correlations)) + j = int(m_max - i*len(correlations)) + return (i, j)"," def _find_strongest_correlation(self, correlations): + m_max = np.argmax(np.abs(correlations.flatten())) + i = int(m_max // len(correlations)) + j = int(m_max - i*len(correlations)) + return (i, j)","[{'piece_type': 'error message', 'piece_content': '------------------\\nrqaoa_result = rqaoa.solve(qubo)\\nprint(rqaoa_result)\\n------------------\\n\\n---------------------------------------------------------------------------\\nQiskitOptimizationError Traceback (most recent call last)\\n in \\n----> 1 rqaoa_result = rqaoa.solve(qubo)\\n2 print(rqaoa_result)\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py in solve(self, problem)\\n171\\n172 # 2. replace x_i by -x_j\\n--> 173 problem_ = problem_.substitute_variables(variables={i: (j, -1)})\\n174 if problem_.status == QuadraticProgram.Status.INFEASIBLE:\\n175 raise QiskitOptimizationError(\\'Infeasible due to variable substitution\\')\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, constants, variables)\\n856 - Coefficient of variable substitution is zero.\\n857 """"""\\n--> 858 return SubstituteVariables().substitute_variables(self, constants, variables)\\n859\\n860\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, src, constants, variables)\\n901 self._src = src\\n902 self._dst = QuadraticProgram(src.name)\\n--> 903 self._subs_dict(constants, variables)\\n904 results = [\\n905 self._variables(),\\n\\n/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in _subs_dict(self, constants, variables)\\n960 j_2 = self._src.get_variable(j).name\\n961 if i_2 == j_2:\\n--> 962 raise QiskitOptimizationError(\\n963 \\'Cannot substitute the same variable: {} <- {} {}\\'.format(i, j, v))\\n964 if i_2 in subs:\\n\\nQiskitOptimizationError: \\'Cannot substitute the same variable: 0 <- 0 -1\\'\\nQiskitOptimizationError: \\'Cannot substitute the same variable: 0 <- 0 -1\\''}]","------------------ +rqaoa_result = rqaoa.solve(qubo) +print(rqaoa_result) +------------------ + +--------------------------------------------------------------------------- +QiskitOptimizationError Traceback (most recent call last) + in +----> 1 rqaoa_result = rqaoa.solve(qubo) +2 print(rqaoa_result) + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py in solve(self, problem) +171 +172 # 2. replace x_i by -x_j +--> 173 problem_ = problem_.substitute_variables(variables={i: (j, -1)}) +174 if problem_.status == QuadraticProgram.Status.INFEASIBLE: +175 raise QiskitOptimizationError('Infeasible due to variable substitution') + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, constants, variables) +856 - Coefficient of variable substitution is zero. +857 """""" +--> 858 return SubstituteVariables().substitute_variables(self, constants, variables) +859 +860 + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, src, constants, variables) +901 self._src = src +902 self._dst = QuadraticProgram(src.name) +--> 903 self._subs_dict(constants, variables) +904 results = [ +905 self._variables(), + +/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in _subs_dict(self, constants, variables) +960 j_2 = self._src.get_variable(j).name +961 if i_2 == j_2: +--> 962 raise QiskitOptimizationError( +963 'Cannot substitute the same variable: {} <- {} {}'.format(i, j, v)) +964 if i_2 in subs: + +QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1' +QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'",QiskitOptimizationError +"def _livereload(host, port, config, builder, site_dir): + + # We are importing here for anyone that has issues with livereload. Even if + # this fails, the --no-livereload alternative should still work. + _init_asyncio_patch() + from livereload import Server + import livereload.handlers + + class LiveReloadServer(Server): + + def get_web_handlers(self, script): + handlers = super(LiveReloadServer, self).get_web_handlers(script) + # replace livereload handler + return [(handlers[0][0], _get_handler(site_dir, livereload.handlers.StaticFileHandler), handlers[0][2],)] + + server = LiveReloadServer() + + # Watch the documentation files, the config file and the theme files. + server.watch(config['docs_dir'], builder) + server.watch(config['config_file_path'], builder) + + for d in config['theme'].dirs: + server.watch(d, builder) + + # Run `serve` plugin events. + server = config['plugins'].run_event('serve', server, config=config) + + server.serve(root=site_dir, host=host, port=port, restart_delay=0)","def _livereload(host, port, config, builder, site_dir): + + # We are importing here for anyone that has issues with livereload. Even if + # this fails, the --no-livereload alternative should still work. + from livereload import Server + import livereload.handlers + + class LiveReloadServer(Server): + + def get_web_handlers(self, script): + handlers = super(LiveReloadServer, self).get_web_handlers(script) + # replace livereload handler + return [(handlers[0][0], _get_handler(site_dir, livereload.handlers.StaticFileHandler), handlers[0][2],)] + + server = LiveReloadServer() + + # Watch the documentation files, the config file and the theme files. + server.watch(config['docs_dir'], builder) + server.watch(config['config_file_path'], builder) + + for d in config['theme'].dirs: + server.watch(d, builder) + + # Run `serve` plugin events. + server = config['plugins'].run_event('serve', server, config=config) + + server.serve(root=site_dir, host=host, port=port, restart_delay=0)","[{'piece_type': 'error message', 'piece_content': 'C:\\\\dev\\\\testing\\nλ mkdocs serve\\nINFO - Building documentation...\\nINFO - Cleaning site directory\\n[I 191017 14:49:48 server:296] Serving on http://127.0.0.1:8000\\nTraceback (most recent call last):\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\runpy.py"", line 192, in _run_module_as_main\\nreturn _run_code(code, main_globals, None,\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""C:\\\\Users\\\\aleksandr.skobelev\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python38\\\\Scripts\\\\mkdocs.exe\\\\__main__.py"", line 9, in \\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 764, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 717, in main\\nrv = self.invoke(ctx)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 1137, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 956, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 555, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\mkdocs\\\\__main__.py"", line 128, in serve_command\\nserve.serve(\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\mkdocs\\\\commands\\\\serve.py"", line 124, in serve\\n_livereload(host, port, config, builder, site_dir)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\mkdocs\\\\commands\\\\serve.py"", line 58, in _livereload\\nserver.serve(root=site_dir, host=host, port=port, restart_delay=0)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\livereload\\\\server.py"", line 298, in serve\\nself.application(\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\livereload\\\\server.py"", line 253, in application\\napp.listen(port, address=host)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\tornado\\\\web.py"", line 2112, in listen\\nserver.listen(port, address)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\tornado\\\\tcpserver.py"", line 152, in listen\\nself.add_sockets(sockets)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\tornado\\\\tcpserver.py"", line 165, in add_sockets\\nself._handlers[sock.fileno()] = add_accept_handler(\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\tornado\\\\netutil.py"", line 279, in add_accept_handler\\nio_loop.add_handler(sock, accept_handler, IOLoop.READ)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\tornado\\\\platform\\\\asyncio.py"", line 99, in add_handler\\nself.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\asyncio\\\\events.py"", line 501, in add_reader\\nraise NotImplementedError\\nNotImplementedError'}]","C:\\dev\\testing +λ mkdocs serve +INFO - Building documentation... +INFO - Cleaning site directory +[I 191017 14:49:48 server:296] Serving on http://127.0.0.1:8000 +Traceback (most recent call last): +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\runpy.py"", line 192, in _run_module_as_main +return _run_code(code, main_globals, None, +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""C:\\Users\\aleksandr.skobelev\\AppData\\Local\\Programs\\Python\\Python38\\Scripts\\mkdocs.exe\\__main__.py"", line 9, in +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\click\\core.py"", line 764, in __call__ +return self.main(*args, **kwargs) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\click\\core.py"", line 717, in main +rv = self.invoke(ctx) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\click\\core.py"", line 1137, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\click\\core.py"", line 956, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\click\\core.py"", line 555, in invoke +return callback(*args, **kwargs) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\mkdocs\\__main__.py"", line 128, in serve_command +serve.serve( +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\mkdocs\\commands\\serve.py"", line 124, in serve +_livereload(host, port, config, builder, site_dir) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\mkdocs\\commands\\serve.py"", line 58, in _livereload +server.serve(root=site_dir, host=host, port=port, restart_delay=0) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\livereload\\server.py"", line 298, in serve +self.application( +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\livereload\\server.py"", line 253, in application +app.listen(port, address=host) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\tornado\\web.py"", line 2112, in listen +server.listen(port, address) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\tornado\\tcpserver.py"", line 152, in listen +self.add_sockets(sockets) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\tornado\\tcpserver.py"", line 165, in add_sockets +self._handlers[sock.fileno()] = add_accept_handler( +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\tornado\\netutil.py"", line 279, in add_accept_handler +io_loop.add_handler(sock, accept_handler, IOLoop.READ) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\tornado\\platform\\asyncio.py"", line 99, in add_handler +self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\asyncio\\events.py"", line 501, in add_reader +raise NotImplementedError +NotImplementedError",NotImplementedError +"def _static_server(host, port, site_dir): + + # Importing here to seperate the code paths from the --livereload + # alternative. + _init_asyncio_patch() + from tornado import ioloop + from tornado import web + + application = web.Application([ + (r""/(.*)"", _get_handler(site_dir, web.StaticFileHandler), { + ""path"": site_dir, + ""default_filename"": ""index.html"" + }), + ]) + application.listen(port=port, address=host) + + log.info('Running at: http://%s:%s/', host, port) + log.info('Hold ctrl+c to quit.') + try: + ioloop.IOLoop.instance().start() + except KeyboardInterrupt: + log.info('Stopping server...')","def _static_server(host, port, site_dir): + + # Importing here to seperate the code paths from the --livereload + # alternative. + from tornado import ioloop + from tornado import web + + application = web.Application([ + (r""/(.*)"", _get_handler(site_dir, web.StaticFileHandler), { + ""path"": site_dir, + ""default_filename"": ""index.html"" + }), + ]) + application.listen(port=port, address=host) + + log.info('Running at: http://%s:%s/', host, port) + log.info('Hold ctrl+c to quit.') + try: + ioloop.IOLoop.instance().start() + except KeyboardInterrupt: + log.info('Stopping server...')","[{'piece_type': 'error message', 'piece_content': 'C:\\\\dev\\\\testing\\nλ mkdocs serve\\nINFO - Building documentation...\\nINFO - Cleaning site directory\\n[I 191017 14:49:48 server:296] Serving on http://127.0.0.1:8000\\nTraceback (most recent call last):\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\runpy.py"", line 192, in _run_module_as_main\\nreturn _run_code(code, main_globals, None,\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""C:\\\\Users\\\\aleksandr.skobelev\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python38\\\\Scripts\\\\mkdocs.exe\\\\__main__.py"", line 9, in \\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 764, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 717, in main\\nrv = self.invoke(ctx)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 1137, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 956, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 555, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\mkdocs\\\\__main__.py"", line 128, in serve_command\\nserve.serve(\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\mkdocs\\\\commands\\\\serve.py"", line 124, in serve\\n_livereload(host, port, config, builder, site_dir)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\mkdocs\\\\commands\\\\serve.py"", line 58, in _livereload\\nserver.serve(root=site_dir, host=host, port=port, restart_delay=0)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\livereload\\\\server.py"", line 298, in serve\\nself.application(\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\livereload\\\\server.py"", line 253, in application\\napp.listen(port, address=host)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\tornado\\\\web.py"", line 2112, in listen\\nserver.listen(port, address)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\tornado\\\\tcpserver.py"", line 152, in listen\\nself.add_sockets(sockets)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\tornado\\\\tcpserver.py"", line 165, in add_sockets\\nself._handlers[sock.fileno()] = add_accept_handler(\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\tornado\\\\netutil.py"", line 279, in add_accept_handler\\nio_loop.add_handler(sock, accept_handler, IOLoop.READ)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\site-packages\\\\tornado\\\\platform\\\\asyncio.py"", line 99, in add_handler\\nself.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)\\nFile ""c:\\\\users\\\\aleksandr.skobelev\\\\appdata\\\\local\\\\programs\\\\python\\\\python38\\\\lib\\\\asyncio\\\\events.py"", line 501, in add_reader\\nraise NotImplementedError\\nNotImplementedError'}]","C:\\dev\\testing +λ mkdocs serve +INFO - Building documentation... +INFO - Cleaning site directory +[I 191017 14:49:48 server:296] Serving on http://127.0.0.1:8000 +Traceback (most recent call last): +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\runpy.py"", line 192, in _run_module_as_main +return _run_code(code, main_globals, None, +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""C:\\Users\\aleksandr.skobelev\\AppData\\Local\\Programs\\Python\\Python38\\Scripts\\mkdocs.exe\\__main__.py"", line 9, in +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\click\\core.py"", line 764, in __call__ +return self.main(*args, **kwargs) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\click\\core.py"", line 717, in main +rv = self.invoke(ctx) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\click\\core.py"", line 1137, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\click\\core.py"", line 956, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\click\\core.py"", line 555, in invoke +return callback(*args, **kwargs) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\mkdocs\\__main__.py"", line 128, in serve_command +serve.serve( +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\mkdocs\\commands\\serve.py"", line 124, in serve +_livereload(host, port, config, builder, site_dir) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\mkdocs\\commands\\serve.py"", line 58, in _livereload +server.serve(root=site_dir, host=host, port=port, restart_delay=0) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\livereload\\server.py"", line 298, in serve +self.application( +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\livereload\\server.py"", line 253, in application +app.listen(port, address=host) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\tornado\\web.py"", line 2112, in listen +server.listen(port, address) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\tornado\\tcpserver.py"", line 152, in listen +self.add_sockets(sockets) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\tornado\\tcpserver.py"", line 165, in add_sockets +self._handlers[sock.fileno()] = add_accept_handler( +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\tornado\\netutil.py"", line 279, in add_accept_handler +io_loop.add_handler(sock, accept_handler, IOLoop.READ) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\tornado\\platform\\asyncio.py"", line 99, in add_handler +self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ) +File ""c:\\users\\aleksandr.skobelev\\appdata\\local\\programs\\python\\python38\\lib\\asyncio\\events.py"", line 501, in add_reader +raise NotImplementedError +NotImplementedError",NotImplementedError +"def serve(config_file=None, dev_addr=None, strict=None, theme=None, + theme_dir=None, livereload='livereload'): + """""" + Start the MkDocs development server + + By default it will serve the documentation on http://localhost:8000/ and + it will rebuild the documentation and refresh the page automatically + whenever a file is edited. + """""" + + # Create a temporary build directory, and set some options to serve it + # PY2 returns a byte string by default. The Unicode prefix ensures a Unicode + # string is returned. And it makes MkDocs temp dirs easier to identify. + site_dir = tempfile.mkdtemp(prefix='mkdocs_') + + def builder(): + log.info(""Building documentation..."") + config = load_config( + config_file=config_file, + dev_addr=dev_addr, + strict=strict, + theme=theme, + theme_dir=theme_dir, + site_dir=site_dir + ) + # Override a few config settings after validation + config['site_url'] = 'http://{0}/'.format(config['dev_addr']) + + live_server = livereload in ['dirty', 'livereload'] + dirty = livereload == 'dirty' + build(config, live_server=live_server, dirty=dirty) + return config + + try: + # Perform the initial build + config = builder() + + host, port = config['dev_addr'] + + if livereload in ['livereload', 'dirty']: + _livereload(host, port, config, builder, site_dir) + else: + _static_server(host, port, site_dir) + finally: + shutil.rmtree(site_dir)","def serve(config_file=None, dev_addr=None, strict=None, theme=None, + theme_dir=None, livereload='livereload'): + """""" + Start the MkDocs development server + + By default it will serve the documentation on http://localhost:8000/ and + it will rebuild the documentation and refresh the page automatically + whenever a file is edited. + """""" + + # Create a temporary build directory, and set some options to serve it + tempdir = tempfile.mkdtemp() + + def builder(): + log.info(""Building documentation..."") + config = load_config( + config_file=config_file, + dev_addr=dev_addr, + strict=strict, + theme=theme, + theme_dir=theme_dir + ) + # Override a few config settings after validation + config['site_dir'] = tempdir + config['site_url'] = 'http://{0}/'.format(config['dev_addr']) + + live_server = livereload in ['dirty', 'livereload'] + dirty = livereload == 'dirty' + build(config, live_server=live_server, dirty=dirty) + return config + + try: + # Perform the initial build + config = builder() + + host, port = config['dev_addr'] + + if livereload in ['livereload', 'dirty']: + _livereload(host, port, config, builder, tempdir) + else: + _static_server(host, port, tempdir) + finally: + shutil.rmtree(tempdir)","[{'piece_type': 'other', 'piece_content': 'mkdocs serve -f mkdocs/tests/integration/unicode/mkdocs.yml'}, {'piece_type': 'error message', 'piece_content': 'Exception in callback >\\nTraceback (most recent call last):\\nFile ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/tornado/ioloop.py"", line 1209, in _run\\nreturn self.callback()\\nFile ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/handlers.py"", line 67, in poll_tasks\\nfilepath, delay = cls.watcher.examine()\\nFile ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/watcher.py"", line 73, in examine\\nfunc and func()\\nFile ""/Users/waylan/Code/mkdocs/mkdocs/commands/serve.py"", line 112, in builder\\nbuild(config, live_server=live_server, dirty=dirty)\\nFile ""/Users/waylan/Code/mkdocs/mkdocs/commands/build.py"", line 265, in build\\nutils.clean_directory(config[\\'site_dir\\'])\\nFile ""/Users/waylan/Code/mkdocs/mkdocs/utils/__init__.py"", line 144, in clean_directory\\nif entry.startswith(\\'.\\'):\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xcc in position 1: ordinal not in range(128)'}]","Exception in callback > +Traceback (most recent call last): +File ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/tornado/ioloop.py"", line 1209, in _run +return self.callback() +File ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/handlers.py"", line 67, in poll_tasks +filepath, delay = cls.watcher.examine() +File ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/watcher.py"", line 73, in examine +func and func() +File ""/Users/waylan/Code/mkdocs/mkdocs/commands/serve.py"", line 112, in builder +build(config, live_server=live_server, dirty=dirty) +File ""/Users/waylan/Code/mkdocs/mkdocs/commands/build.py"", line 265, in build +utils.clean_directory(config['site_dir']) +File ""/Users/waylan/Code/mkdocs/mkdocs/utils/__init__.py"", line 144, in clean_directory +if entry.startswith('.'): +UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 1: ordinal not in range(128)",UnicodeDecodeError +" def builder(): + log.info(""Building documentation..."") + config = load_config( + config_file=config_file, + dev_addr=dev_addr, + strict=strict, + theme=theme, + theme_dir=theme_dir, + site_dir=site_dir + ) + # Override a few config settings after validation + config['site_url'] = 'http://{0}/'.format(config['dev_addr']) + + live_server = livereload in ['dirty', 'livereload'] + dirty = livereload == 'dirty' + build(config, live_server=live_server, dirty=dirty) + return config"," def builder(): + log.info(""Building documentation..."") + config = load_config( + config_file=config_file, + dev_addr=dev_addr, + strict=strict, + theme=theme, + theme_dir=theme_dir + ) + # Override a few config settings after validation + config['site_dir'] = tempdir + config['site_url'] = 'http://{0}/'.format(config['dev_addr']) + + live_server = livereload in ['dirty', 'livereload'] + dirty = livereload == 'dirty' + build(config, live_server=live_server, dirty=dirty) + return config","[{'piece_type': 'other', 'piece_content': 'mkdocs serve -f mkdocs/tests/integration/unicode/mkdocs.yml'}, {'piece_type': 'error message', 'piece_content': 'Exception in callback >\\nTraceback (most recent call last):\\nFile ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/tornado/ioloop.py"", line 1209, in _run\\nreturn self.callback()\\nFile ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/handlers.py"", line 67, in poll_tasks\\nfilepath, delay = cls.watcher.examine()\\nFile ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/watcher.py"", line 73, in examine\\nfunc and func()\\nFile ""/Users/waylan/Code/mkdocs/mkdocs/commands/serve.py"", line 112, in builder\\nbuild(config, live_server=live_server, dirty=dirty)\\nFile ""/Users/waylan/Code/mkdocs/mkdocs/commands/build.py"", line 265, in build\\nutils.clean_directory(config[\\'site_dir\\'])\\nFile ""/Users/waylan/Code/mkdocs/mkdocs/utils/__init__.py"", line 144, in clean_directory\\nif entry.startswith(\\'.\\'):\\nUnicodeDecodeError: \\'ascii\\' codec can\\'t decode byte 0xcc in position 1: ordinal not in range(128)'}]","Exception in callback > +Traceback (most recent call last): +File ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/tornado/ioloop.py"", line 1209, in _run +return self.callback() +File ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/handlers.py"", line 67, in poll_tasks +filepath, delay = cls.watcher.examine() +File ""/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/watcher.py"", line 73, in examine +func and func() +File ""/Users/waylan/Code/mkdocs/mkdocs/commands/serve.py"", line 112, in builder +build(config, live_server=live_server, dirty=dirty) +File ""/Users/waylan/Code/mkdocs/mkdocs/commands/build.py"", line 265, in build +utils.clean_directory(config['site_dir']) +File ""/Users/waylan/Code/mkdocs/mkdocs/utils/__init__.py"", line 144, in clean_directory +if entry.startswith('.'): +UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 1: ordinal not in range(128)",UnicodeDecodeError +"def copy_file(source_path, output_path): + """""" + Copy source_path to output_path, making sure any parent directories exist. + + The output_path may be a directory. + """""" + output_dir = os.path.dirname(output_path) + if not os.path.exists(output_dir): + os.makedirs(output_dir) + if os.path.isdir(output_path): + output_path = os.path.join(output_path, os.path.basename(source_path)) + shutil.copyfile(source_path, output_path)","def copy_file(source_path, output_path): + """""" + Copy source_path to output_path, making sure any parent directories exist. + """""" + + output_dir = os.path.dirname(output_path) + if not os.path.exists(output_dir): + os.makedirs(output_dir) + shutil.copy(source_path, output_path)","[{'piece_type': 'error message', 'piece_content': '$ mkdocs build\\nWARNING - Config value: \\'extra_javascript\\'. Warning: The following files have been automatically included in the documentation build and will be added to the HTML: highlight/theme/js/highlight.pack.js. This behavior is deprecated. In version 1.0 and later they will need to be explicitly listed in the \\'extra_javascript\\' config setting.\\nINFO - Cleaning site directory\\nINFO - Building documentation to directory: /build/site\\nTraceback (most recent call last):\\nFile ""/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/bin/.mkdocs-wrapped"", line 12, in \\nsys.exit(cli())\\nFile ""/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py"", line 722, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py"", line 697, in main\\nrv = self.invoke(ctx)\\nFile ""/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py"", line 1066, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py"", line 895, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py"", line 535, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/__main__.py"", line 156, in build_command\\n), dirty=not clean)\\nFile ""/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/commands/build.py"", line 373, in build\\ntheme_dir, config[\\'site_dir\\'], exclude=[\\'*.py\\', \\'*.pyc\\', \\'*.html\\'], dirty=dirty\\nFile ""/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/utils/__init__.py"", line 175, in copy_media_files\\ncopy_file(source_path, output_path)\\nFile ""/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/utils/__init__.py"", line 110, in copy_file\\nshutil.copy(source_path, output_path)\\nFile ""/nix/store/w8zld7z4gq4b36z0szgrh6yv5zi30915-python-2.7.13/lib/python2.7/shutil.py"", line 119, in copy\\ncopyfile(src, dst)\\nFile ""/nix/store/w8zld7z4gq4b36z0szgrh6yv5zi30915-python-2.7.13/lib/python2.7/shutil.py"", line 83, in copyfile\\nwith open(dst, \\'wb\\') as fdst:\\nIOError: [Errno 13] Permission denied: u\\'/build/site/js/highlight.pack.js\\'\\n\\n$ ls -l build/site/js/\\ntotal 396\\n-r--r--r-- 1 kirelagin staff 300764 Sep 26 16:03 highlight.pack.js\\n-r--r--r-- 1 kirelagin staff 84245 Sep 26 16:03 jquery-2.1.1.min.js\\n-r--r--r-- 1 kirelagin staff 11084 Sep 26 16:03 modernizr-2.8.3.min.js\\n-r--r--r-- 1 kirelagin staff 2676 Sep 26 16:03 theme.js\\n\\n$ ls -ld build/site/js/\\ndrwxr-xr-x 6 kirelagin staff 204 Sep 26 16:03 build/site/js/'}]","$ mkdocs build +WARNING - Config value: 'extra_javascript'. Warning: The following files have been automatically included in the documentation build and will be added to the HTML: highlight/theme/js/highlight.pack.js. This behavior is deprecated. In version 1.0 and later they will need to be explicitly listed in the 'extra_javascript' config setting. +INFO - Cleaning site directory +INFO - Building documentation to directory: /build/site +Traceback (most recent call last): +File ""/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/bin/.mkdocs-wrapped"", line 12, in +sys.exit(cli()) +File ""/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py"", line 722, in __call__ +return self.main(*args, **kwargs) +File ""/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py"", line 697, in main +rv = self.invoke(ctx) +File ""/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py"", line 1066, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py"", line 895, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py"", line 535, in invoke +return callback(*args, **kwargs) +File ""/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/__main__.py"", line 156, in build_command +), dirty=not clean) +File ""/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/commands/build.py"", line 373, in build +theme_dir, config['site_dir'], exclude=['*.py', '*.pyc', '*.html'], dirty=dirty +File ""/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/utils/__init__.py"", line 175, in copy_media_files +copy_file(source_path, output_path) +File ""/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/utils/__init__.py"", line 110, in copy_file +shutil.copy(source_path, output_path) +File ""/nix/store/w8zld7z4gq4b36z0szgrh6yv5zi30915-python-2.7.13/lib/python2.7/shutil.py"", line 119, in copy +copyfile(src, dst) +File ""/nix/store/w8zld7z4gq4b36z0szgrh6yv5zi30915-python-2.7.13/lib/python2.7/shutil.py"", line 83, in copyfile +with open(dst, 'wb') as fdst: +IOError: [Errno 13] Permission denied: u'/build/site/js/highlight.pack.js' + +$ ls -l build/site/js/ +total 396 +-r--r--r-- 1 kirelagin staff 300764 Sep 26 16:03 highlight.pack.js +-r--r--r-- 1 kirelagin staff 84245 Sep 26 16:03 jquery-2.1.1.min.js +-r--r--r-- 1 kirelagin staff 11084 Sep 26 16:03 modernizr-2.8.3.min.js +-r--r--r-- 1 kirelagin staff 2676 Sep 26 16:03 theme.js + +$ ls -ld build/site/js/ +drwxr-xr-x 6 kirelagin staff 204 Sep 26 16:03 build/site/js/",IOError +"def _livereload(host, port, config, builder, site_dir): + + # We are importing here for anyone that has issues with livereload. Even if + # this fails, the --no-livereload alternative should still work. + from livereload import Server + import livereload.handlers + + class LiveReloadServer(Server): + + def get_web_handlers(self, script): + handlers = super(LiveReloadServer, self).get_web_handlers(script) + # replace livereload handler + return [(handlers[0][0], _get_handler(site_dir, livereload.handlers.StaticFileHandler), handlers[0][2],)] + + server = LiveReloadServer() + + # Watch the documentation files, the config file and the theme files. + server.watch(config['docs_dir'], builder) + server.watch(config['config_file_path'], builder) + + for d in config['theme_dir']: + server.watch(d, builder) + + server.serve(root=site_dir, host=host, port=port, restart_delay=0)","def _livereload(host, port, config, builder, site_dir): + + # We are importing here for anyone that has issues with livereload. Even if + # this fails, the --no-livereload alternative should still work. + from livereload import Server + import livereload.handlers + + class LiveReloadServer(Server): + + def get_web_handlers(self, script): + handlers = super(LiveReloadServer, self).get_web_handlers(script) + # replace livereload handler + return [(handlers[0][0], _get_handler(site_dir, livereload.handlers.StaticFileHandler), handlers[0][2],)] + + server = LiveReloadServer() + + # Watch the documentation files, the config file and the theme files. + server.watch(config['docs_dir'], builder) + server.watch(config['config_file_path'], builder) + + for d in config['theme_dir']: + server.watch(d, builder) + + server.serve(root=site_dir, host=host, port=int(port), restart_delay=0)","[{'piece_type': 'error message', 'piece_content': 'INFO - Building documentation...\\nINFO - Cleaning site directory\\nTraceback (most recent call last):\\nFile ""/home/sybren/.virtualenvs/flamenco/bin/mkdocs"", line 11, in \\nsys.exit(cli())\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 722, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 697, in main\\nrv = self.invoke(ctx)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 1066, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 895, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 535, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/__main__.py"", line 127, in serve_command\\nlivereload=livereload\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 116, in serve\\n_livereload(host, port, config, builder, tempdir)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 55, in _livereload\\nserver.serve(root=site_dir, host=host, port=int(port), restart_delay=0)\\nValueError: invalid literal for int() with base 10: \\':0]:8081\\''}]","INFO - Building documentation... +INFO - Cleaning site directory +Traceback (most recent call last): +File ""/home/sybren/.virtualenvs/flamenco/bin/mkdocs"", line 11, in +sys.exit(cli()) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 722, in __call__ +return self.main(*args, **kwargs) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 697, in main +rv = self.invoke(ctx) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 1066, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 895, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 535, in invoke +return callback(*args, **kwargs) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/__main__.py"", line 127, in serve_command +livereload=livereload +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 116, in serve +_livereload(host, port, config, builder, tempdir) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 55, in _livereload +server.serve(root=site_dir, host=host, port=int(port), restart_delay=0) +ValueError: invalid literal for int() with base 10: ':0]:8081'",ValueError +"def _static_server(host, port, site_dir): + + # Importing here to seperate the code paths from the --livereload + # alternative. + from tornado import ioloop + from tornado import web + + application = web.Application([ + (r""/(.*)"", _get_handler(site_dir, web.StaticFileHandler), { + ""path"": site_dir, + ""default_filename"": ""index.html"" + }), + ]) + application.listen(port=port, address=host) + + log.info('Running at: http://%s:%s/', host, port) + log.info('Hold ctrl+c to quit.') + try: + ioloop.IOLoop.instance().start() + except KeyboardInterrupt: + log.info('Stopping server...')","def _static_server(host, port, site_dir): + + # Importing here to seperate the code paths from the --livereload + # alternative. + from tornado import ioloop + from tornado import web + + application = web.Application([ + (r""/(.*)"", _get_handler(site_dir, web.StaticFileHandler), { + ""path"": site_dir, + ""default_filename"": ""index.html"" + }), + ]) + application.listen(port=int(port), address=host) + + log.info('Running at: http://%s:%s/', host, port) + log.info('Hold ctrl+c to quit.') + try: + ioloop.IOLoop.instance().start() + except KeyboardInterrupt: + log.info('Stopping server...')","[{'piece_type': 'error message', 'piece_content': 'INFO - Building documentation...\\nINFO - Cleaning site directory\\nTraceback (most recent call last):\\nFile ""/home/sybren/.virtualenvs/flamenco/bin/mkdocs"", line 11, in \\nsys.exit(cli())\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 722, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 697, in main\\nrv = self.invoke(ctx)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 1066, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 895, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 535, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/__main__.py"", line 127, in serve_command\\nlivereload=livereload\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 116, in serve\\n_livereload(host, port, config, builder, tempdir)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 55, in _livereload\\nserver.serve(root=site_dir, host=host, port=int(port), restart_delay=0)\\nValueError: invalid literal for int() with base 10: \\':0]:8081\\''}]","INFO - Building documentation... +INFO - Cleaning site directory +Traceback (most recent call last): +File ""/home/sybren/.virtualenvs/flamenco/bin/mkdocs"", line 11, in +sys.exit(cli()) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 722, in __call__ +return self.main(*args, **kwargs) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 697, in main +rv = self.invoke(ctx) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 1066, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 895, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 535, in invoke +return callback(*args, **kwargs) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/__main__.py"", line 127, in serve_command +livereload=livereload +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 116, in serve +_livereload(host, port, config, builder, tempdir) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 55, in _livereload +server.serve(root=site_dir, host=host, port=int(port), restart_delay=0) +ValueError: invalid literal for int() with base 10: ':0]:8081'",ValueError +"def serve(config_file=None, dev_addr=None, strict=None, theme=None, + theme_dir=None, livereload='livereload'): + """""" + Start the MkDocs development server + + By default it will serve the documentation on http://localhost:8000/ and + it will rebuild the documentation and refresh the page automatically + whenever a file is edited. + """""" + + # Create a temporary build directory, and set some options to serve it + tempdir = tempfile.mkdtemp() + + def builder(): + log.info(""Building documentation..."") + config = load_config( + config_file=config_file, + dev_addr=dev_addr, + strict=strict, + theme=theme, + theme_dir=theme_dir + ) + config['site_dir'] = tempdir + live_server = livereload in ['dirty', 'livereload'] + dirty = livereload == 'dirty' + build(config, live_server=live_server, dirty=dirty) + return config + + try: + # Perform the initial build + config = builder() + + host, port = config['dev_addr'] + + if livereload in ['livereload', 'dirty']: + _livereload(host, port, config, builder, tempdir) + else: + _static_server(host, port, tempdir) + finally: + shutil.rmtree(tempdir)","def serve(config_file=None, dev_addr=None, strict=None, theme=None, + theme_dir=None, livereload='livereload'): + """""" + Start the MkDocs development server + + By default it will serve the documentation on http://localhost:8000/ and + it will rebuild the documentation and refresh the page automatically + whenever a file is edited. + """""" + + # Create a temporary build directory, and set some options to serve it + tempdir = tempfile.mkdtemp() + + def builder(): + log.info(""Building documentation..."") + config = load_config( + config_file=config_file, + dev_addr=dev_addr, + strict=strict, + theme=theme, + theme_dir=theme_dir + ) + config['site_dir'] = tempdir + live_server = livereload in ['dirty', 'livereload'] + dirty = livereload == 'dirty' + build(config, live_server=live_server, dirty=dirty) + return config + + # Perform the initial build + config = builder() + + host, port = config['dev_addr'].split(':', 1) + + try: + if livereload in ['livereload', 'dirty']: + _livereload(host, port, config, builder, tempdir) + else: + _static_server(host, port, tempdir) + finally: + shutil.rmtree(tempdir)","[{'piece_type': 'error message', 'piece_content': 'INFO - Building documentation...\\nINFO - Cleaning site directory\\nTraceback (most recent call last):\\nFile ""/home/sybren/.virtualenvs/flamenco/bin/mkdocs"", line 11, in \\nsys.exit(cli())\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 722, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 697, in main\\nrv = self.invoke(ctx)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 1066, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 895, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 535, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/__main__.py"", line 127, in serve_command\\nlivereload=livereload\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 116, in serve\\n_livereload(host, port, config, builder, tempdir)\\nFile ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 55, in _livereload\\nserver.serve(root=site_dir, host=host, port=int(port), restart_delay=0)\\nValueError: invalid literal for int() with base 10: \\':0]:8081\\''}]","INFO - Building documentation... +INFO - Cleaning site directory +Traceback (most recent call last): +File ""/home/sybren/.virtualenvs/flamenco/bin/mkdocs"", line 11, in +sys.exit(cli()) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 722, in __call__ +return self.main(*args, **kwargs) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 697, in main +rv = self.invoke(ctx) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 1066, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 895, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py"", line 535, in invoke +return callback(*args, **kwargs) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/__main__.py"", line 127, in serve_command +livereload=livereload +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 116, in serve +_livereload(host, port, config, builder, tempdir) +File ""/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py"", line 55, in _livereload +server.serve(root=site_dir, host=host, port=int(port), restart_delay=0) +ValueError: invalid literal for int() with base 10: ':0]:8081'",ValueError +"def try_rebase(remote, branch): + cmd = ['git', 'rev-list', '--max-count=1', '%s/%s' % (remote, branch)] + p = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE) + (rev, _) = p.communicate() + if p.wait() != 0: + return True + cmd = ['git', 'update-ref', 'refs/heads/%s' % branch, dec(rev.strip())] + if sp.call(cmd) != 0: + return False + return True","def try_rebase(remote, branch): + cmd = ['git', 'rev-list', '--max-count=1', '%s/%s' % (remote, branch)] + p = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE) + (rev, _) = p.communicate() + if p.wait() != 0: + return True + cmd = ['git', 'update-ref', 'refs/heads/%s' % branch, rev.strip()] + if sp.call(cmd) != 0: + return False + return True","[{'piece_type': 'error message', 'piece_content': 'c:\\\\docs>mkdocs gh-deploy --clean\\nINFO - Cleaning site directory\\nINFO - Building documentation to directory: c:\\\\docs\\\\site\\nINFO - Copying \\'c:\\\\docs\\\\site\\' to \\'gh-pages\\' branch and pushing to GitHub.\\nTraceback (most recent call last):\\nFile ""C:\\\\Python34\\\\lib\\\\runpy.py"", line 170, in _run_module_as_main\\n""__main__"", mod_spec)\\nFile ""C:\\\\Python34\\\\lib\\\\runpy.py"", line 85, in _run_code\\nexec(code, run_globals)\\nFile ""c:\\\\Python34\\\\Scripts\\\\mkdocs.exe\\\\__main__.py"", line 9, in \\nFile ""C:\\\\Python34\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 664, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""C:\\\\Python34\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 644, in main\\nrv = self.invoke(ctx)\\nFile ""C:\\\\Python34\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 991, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""C:\\\\Python34\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 837, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""C:\\\\Python34\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 464, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""C:\\\\Python34\\\\lib\\\\site-packages\\\\mkdocs\\\\cli.py"", line 186, in gh_deploy_command\\ngh_deploy.gh_deploy(config, message=message)\\nFile ""C:\\\\Python34\\\\lib\\\\site-packages\\\\mkdocs\\\\gh_deploy.py"", line 69, in gh_deploy\\nremote_branch)\\nFile ""C:\\\\Python34\\\\lib\\\\site-packages\\\\mkdocs\\\\utils\\\\ghp_import.py"", line 163, in ghp_import\\nif not try_rebase(remote, branch):\\nFile ""C:\\\\Python34\\\\lib\\\\site-packages\\\\mkdocs\\\\utils\\\\ghp_import.py"", line 78, in try_rebase\\nif sp.call(cmd) != 0:\\nFile ""C:\\\\Python34\\\\lib\\\\subprocess.py"", line 537, in call\\nwith Popen(*popenargs, **kwargs) as p:\\nFile ""C:\\\\Python34\\\\lib\\\\subprocess.py"", line 859, in __init__\\nrestore_signals, start_new_session)\\nFile ""C:\\\\Python34\\\\lib\\\\subprocess.py"", line 1086, in _execute_child\\nargs = list2cmdline(args)\\nFile ""C:\\\\Python34\\\\lib\\\\subprocess.py"", line 663, in list2cmdline\\nneedquote = ("" "" in arg) or (""\\\\t"" in arg) or not arg\\nTypeError: \\'str\\' does not support the buffer interface'}]","c:\\docs>mkdocs gh-deploy --clean +INFO - Cleaning site directory +INFO - Building documentation to directory: c:\\docs\\site +INFO - Copying 'c:\\docs\\site' to 'gh-pages' branch and pushing to GitHub. +Traceback (most recent call last): +File ""C:\\Python34\\lib\\runpy.py"", line 170, in _run_module_as_main +""__main__"", mod_spec) +File ""C:\\Python34\\lib\\runpy.py"", line 85, in _run_code +exec(code, run_globals) +File ""c:\\Python34\\Scripts\\mkdocs.exe\\__main__.py"", line 9, in +File ""C:\\Python34\\lib\\site-packages\\click\\core.py"", line 664, in __call__ +return self.main(*args, **kwargs) +File ""C:\\Python34\\lib\\site-packages\\click\\core.py"", line 644, in main +rv = self.invoke(ctx) +File ""C:\\Python34\\lib\\site-packages\\click\\core.py"", line 991, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""C:\\Python34\\lib\\site-packages\\click\\core.py"", line 837, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""C:\\Python34\\lib\\site-packages\\click\\core.py"", line 464, in invoke +return callback(*args, **kwargs) +File ""C:\\Python34\\lib\\site-packages\\mkdocs\\cli.py"", line 186, in gh_deploy_command +gh_deploy.gh_deploy(config, message=message) +File ""C:\\Python34\\lib\\site-packages\\mkdocs\\gh_deploy.py"", line 69, in gh_deploy +remote_branch) +File ""C:\\Python34\\lib\\site-packages\\mkdocs\\utils\\ghp_import.py"", line 163, in ghp_import +if not try_rebase(remote, branch): +File ""C:\\Python34\\lib\\site-packages\\mkdocs\\utils\\ghp_import.py"", line 78, in try_rebase +if sp.call(cmd) != 0: +File ""C:\\Python34\\lib\\subprocess.py"", line 537, in call +with Popen(*popenargs, **kwargs) as p: +File ""C:\\Python34\\lib\\subprocess.py"", line 859, in __init__ +restore_signals, start_new_session) +File ""C:\\Python34\\lib\\subprocess.py"", line 1086, in _execute_child +args = list2cmdline(args) +File ""C:\\Python34\\lib\\subprocess.py"", line 663, in list2cmdline +needquote = ("" "" in arg) or (""\\t"" in arg) or not arg +TypeError: 'str' does not support the buffer interface",TypeError +"def path_to_url(path): + """"""Convert a system path to a URL."""""" + + if os.path.sep == '/': + return path + + if sys.version_info < (3, 0): + path = path.encode('utf8') + return pathname2url(path)","def path_to_url(path): + """"""Convert a system path to a URL."""""" + + if os.path.sep == '/': + return path + + return pathname2url(path)","[{'piece_type': 'other', 'piece_content': '/Kapitel\\n1. Einstieg\\n2. Übersicht\\n3. Etcetera'}, {'piece_type': 'error message', 'piece_content': 'C:\\\\Python27\\\\lib\\\\urllib.py:1303: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal\\nreturn \\'\\'.join(map(quoter, s))\\nERROR - Error building page Allgemeines\\\\1. Richtlinien.md\\nTraceback (most recent call last):\\nFile ""C:\\\\Python27\\\\lib\\\\runpy.py"", line 162, in _run_module_as_main\\n""__main__"", fname, loader, pkg_name)\\nFile ""C:\\\\Python27\\\\lib\\\\runpy.py"", line 72, in _run_code\\nexec code in run_globals\\nFile ""C:\\\\Python27\\\\Scripts\\\\mkdocs.exe\\\\__main__.py"", line 9, in \\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 716, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 696, in main\\nrv = self.invoke(ctx)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 1060, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 889, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\click\\\\core.py"", line 534, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\mkdocs\\\\__main__.py"", line 115, in serve_command\\nlivereload=livereload,\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\mkdocs\\\\commands\\\\serve.py"", line 78, in serve\\nconfig = builder()\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\mkdocs\\\\commands\\\\serve.py"", line 74, in builder\\nbuild(config, live_server=True, clean_site_dir=True)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\mkdocs\\\\commands\\\\build.py"", line 289, in build\\nbuild_pages(config)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\mkdocs\\\\commands\\\\build.py"", line 249, in build_pages\\ndump_json)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\mkdocs\\\\commands\\\\build.py"", line 184, in _build_page\\noutput_content = template.render(context)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\jinja2\\\\environment.py"", line 989, in render\\nreturn self.environment.handle_exception(exc_info, True)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\jinja2\\\\environment.py"", line 754, in handle_exception\\nreraise(exc_type, exc_value, tb)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\material\\\\base.html"", line 102, in top-level template code\\n{% include ""drawer.html"" %}\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\material\\\\drawer.html"", line 41, in top-level template code\\n{% include ""nav.html"" %}\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\material\\\\nav.html"", line 6, in top-level template code\\n{% include \\'nav.html\\' %}\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\material\\\\nav.html"", line 12, in top-level template code\\n\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\jinja2\\\\environment.py"", line 408, in getattr\\nreturn getattr(obj, attribute)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\mkdocs\\\\nav.py"", line 153, in url\\nreturn self.url_context.make_relative(self.abs_url)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\mkdocs\\\\nav.py"", line 105, in make_relative\\nreturn utils.path_to_url(relative_path)\\nFile ""C:\\\\Python27\\\\lib\\\\site-packages\\\\mkdocs\\\\utils\\\\__init__.py"", line 324, in path_to_url\\nreturn pathname2url(path)\\nFile ""C:\\\\Python27\\\\lib\\\\nturl2path.py"", line 54, in pathname2url\\nreturn urllib.quote(\\'/\\'.join(components))\\nFile ""C:\\\\Python27\\\\lib\\\\urllib.py"", line 1303, in quote\\nreturn \\'\\'.join(map(quoter, s))\\nKeyError: u\\'\\\\xdc\\''}]","C:\\Python27\\lib\\urllib.py:1303: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal +return ''.join(map(quoter, s)) +ERROR - Error building page Allgemeines\\1. Richtlinien.md +Traceback (most recent call last): +File ""C:\\Python27\\lib\\runpy.py"", line 162, in _run_module_as_main +""__main__"", fname, loader, pkg_name) +File ""C:\\Python27\\lib\\runpy.py"", line 72, in _run_code +exec code in run_globals +File ""C:\\Python27\\Scripts\\mkdocs.exe\\__main__.py"", line 9, in +File ""C:\\Python27\\lib\\site-packages\\click\\core.py"", line 716, in __call__ +return self.main(*args, **kwargs) +File ""C:\\Python27\\lib\\site-packages\\click\\core.py"", line 696, in main +rv = self.invoke(ctx) +File ""C:\\Python27\\lib\\site-packages\\click\\core.py"", line 1060, in invoke +return _process_result(sub_ctx.command.invoke(sub_ctx)) +File ""C:\\Python27\\lib\\site-packages\\click\\core.py"", line 889, in invoke +return ctx.invoke(self.callback, **ctx.params) +File ""C:\\Python27\\lib\\site-packages\\click\\core.py"", line 534, in invoke +return callback(*args, **kwargs) +File ""C:\\Python27\\lib\\site-packages\\mkdocs\\__main__.py"", line 115, in serve_command +livereload=livereload, +File ""C:\\Python27\\lib\\site-packages\\mkdocs\\commands\\serve.py"", line 78, in serve +config = builder() +File ""C:\\Python27\\lib\\site-packages\\mkdocs\\commands\\serve.py"", line 74, in builder +build(config, live_server=True, clean_site_dir=True) +File ""C:\\Python27\\lib\\site-packages\\mkdocs\\commands\\build.py"", line 289, in build +build_pages(config) +File ""C:\\Python27\\lib\\site-packages\\mkdocs\\commands\\build.py"", line 249, in build_pages +dump_json) +File ""C:\\Python27\\lib\\site-packages\\mkdocs\\commands\\build.py"", line 184, in _build_page +output_content = template.render(context) +File ""C:\\Python27\\lib\\site-packages\\jinja2\\environment.py"", line 989, in render +return self.environment.handle_exception(exc_info, True) +File ""C:\\Python27\\lib\\site-packages\\jinja2\\environment.py"", line 754, in handle_exception +reraise(exc_type, exc_value, tb) +File ""C:\\Python27\\lib\\site-packages\\material\\base.html"", line 102, in top-level template code +{% include ""drawer.html"" %} +File ""C:\\Python27\\lib\\site-packages\\material\\drawer.html"", line 41, in top-level template code +{% include ""nav.html"" %} +File ""C:\\Python27\\lib\\site-packages\\material\\nav.html"", line 6, in top-level template code +{% include 'nav.html' %} +File ""C:\\Python27\\lib\\site-packages\\material\\nav.html"", line 12, in top-level template code + +File ""C:\\Python27\\lib\\site-packages\\jinja2\\environment.py"", line 408, in getattr +return getattr(obj, attribute) +File ""C:\\Python27\\lib\\site-packages\\mkdocs\\nav.py"", line 153, in url +return self.url_context.make_relative(self.abs_url) +File ""C:\\Python27\\lib\\site-packages\\mkdocs\\nav.py"", line 105, in make_relative +return utils.path_to_url(relative_path) +File ""C:\\Python27\\lib\\site-packages\\mkdocs\\utils\\__init__.py"", line 324, in path_to_url +return pathname2url(path) +File ""C:\\Python27\\lib\\nturl2path.py"", line 54, in pathname2url +return urllib.quote('/'.join(components)) +File ""C:\\Python27\\lib\\urllib.py"", line 1303, in quote +return ''.join(map(quoter, s)) +KeyError: u'\\xdc'",KeyError +" def walk_docs_dir(self, docs_dir): + + if self.file_match is None: + raise StopIteration + + for (dirpath, dirs, filenames) in os.walk(docs_dir): + dirs.sort() + for filename in sorted(filenames): + fullpath = os.path.join(dirpath, filename) + + # Some editors (namely Emacs) will create temporary symlinks + # for internal magic. We can just ignore these files. + if os.path.islink(fullpath): + if not os.path.exists(os.readlink(fullpath)): + continue + + relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir)) + if self.file_match(relpath): + yield relpath"," def walk_docs_dir(self, docs_dir): + + if self.file_match is None: + raise StopIteration + + for (dirpath, dirs, filenames) in os.walk(docs_dir): + dirs.sort() + for filename in sorted(filenames): + fullpath = os.path.join(dirpath, filename) + relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir)) + if self.file_match(relpath): + yield relpath","[{'piece_type': 'other', 'piece_content': '➜ docs git:(master) ✗ ls -al .#*\\nlrwxrwxrwx 1 paulproteus paulproteus 36 Jun 17 17:24 .#index.md -> paulproteus@charkha.27783:1434311808'}, {'piece_type': 'error message', 'piece_content': 'INFO - Building documentation...\\nERROR - file not found: /home/paulproteus/projects/sandstorm/docs/.#index.md\\nERROR - Error building page .#index.md\\n[E 150617 17:22:21 ioloop:612] Exception in callback (3, )\\nTraceback (most recent call last):\\nFile ""/home/paulproteus/.local/lib/python2.7/site-packages/tornado/ioloop.py"", line 866, in start\\nhandler_func(fd_obj, events)\\nFile ""/home/paulproteus/.local/lib/python2.7/site-packages/tornado/stack_context.py"", line 275, in null_wrapper\\nreturn fn(*args, **kwargs)\\nFile ""/usr/lib/python2.7/dist-packages/pyinotify.py"", line 1604, in handle_read\\nself.process_events()\\nFile ""/usr/lib/python2.7/dist-packages/pyinotify.py"", line 1321, in process_events\\nself._default_proc_fun(revent)\\nFile ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py"", line 152, in inotify_event\\nself.callback()\\nFile ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/handlers.py"", line 65, in poll_tasks\\nfilepath, delay = cls.watcher.examine()\\nFile ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py"", line 72, in examine\\nfunc and func()\\nFile ""/usr/lib/python2.7/dist-packages/mkdocs/serve.py"", line 74, in builder\\nbuild(config, live_server=True)\\nFile ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 299, in build\\nbuild_pages(config)\\nFile ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 259, in build_pages\\ndump_json)\\nFile ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 171, in _build_page\\ninput_content = io.open(input_path, \\'r\\', encoding=\\'utf-8\\').read()\\nIOError: [Errno 2] No such file or directory: \\'/home/paulproteus/projects/sandstorm/docs/.#index.md\\''}]","INFO - Building documentation... +ERROR - file not found: /home/paulproteus/projects/sandstorm/docs/.#index.md +ERROR - Error building page .#index.md +[E 150617 17:22:21 ioloop:612] Exception in callback (3, ) +Traceback (most recent call last): +File ""/home/paulproteus/.local/lib/python2.7/site-packages/tornado/ioloop.py"", line 866, in start +handler_func(fd_obj, events) +File ""/home/paulproteus/.local/lib/python2.7/site-packages/tornado/stack_context.py"", line 275, in null_wrapper +return fn(*args, **kwargs) +File ""/usr/lib/python2.7/dist-packages/pyinotify.py"", line 1604, in handle_read +self.process_events() +File ""/usr/lib/python2.7/dist-packages/pyinotify.py"", line 1321, in process_events +self._default_proc_fun(revent) +File ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py"", line 152, in inotify_event +self.callback() +File ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/handlers.py"", line 65, in poll_tasks +filepath, delay = cls.watcher.examine() +File ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py"", line 72, in examine +func and func() +File ""/usr/lib/python2.7/dist-packages/mkdocs/serve.py"", line 74, in builder +build(config, live_server=True) +File ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 299, in build +build_pages(config) +File ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 259, in build_pages +dump_json) +File ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 171, in _build_page +input_content = io.open(input_path, 'r', encoding='utf-8').read() +IOError: [Errno 2] No such file or directory: '/home/paulproteus/projects/sandstorm/docs/.#index.md'",IOError +" def walk_docs_dir(self, docs_dir): + + if self.file_match is None: + raise StopIteration + + for (dirpath, dirs, filenames) in os.walk(docs_dir): + dirs.sort() + for filename in sorted(filenames): + fullpath = os.path.join(dirpath, filename) + + # Some editors (namely Emacs) will create temporary symlinks + # for internal magic. We can just ignore these files. + if os.path.islink(fullpath): + fp = os.path.join(dirpath, os.readlink(fullpath)) + if not os.path.exists(fp): + continue + + relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir)) + if self.file_match(relpath): + yield relpath"," def walk_docs_dir(self, docs_dir): + + if self.file_match is None: + raise StopIteration + + for (dirpath, dirs, filenames) in os.walk(docs_dir): + dirs.sort() + for filename in sorted(filenames): + fullpath = os.path.join(dirpath, filename) + + # Some editors (namely Emacs) will create temporary symlinks + # for internal magic. We can just ignore these files. + if os.path.islink(fullpath): + if not os.path.exists(os.readlink(fullpath)): + continue + + relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir)) + if self.file_match(relpath): + yield relpath","[{'piece_type': 'other', 'piece_content': '➜ docs git:(master) ✗ ls -al .#*\\nlrwxrwxrwx 1 paulproteus paulproteus 36 Jun 17 17:24 .#index.md -> paulproteus@charkha.27783:1434311808'}, {'piece_type': 'error message', 'piece_content': 'INFO - Building documentation...\\nERROR - file not found: /home/paulproteus/projects/sandstorm/docs/.#index.md\\nERROR - Error building page .#index.md\\n[E 150617 17:22:21 ioloop:612] Exception in callback (3, )\\nTraceback (most recent call last):\\nFile ""/home/paulproteus/.local/lib/python2.7/site-packages/tornado/ioloop.py"", line 866, in start\\nhandler_func(fd_obj, events)\\nFile ""/home/paulproteus/.local/lib/python2.7/site-packages/tornado/stack_context.py"", line 275, in null_wrapper\\nreturn fn(*args, **kwargs)\\nFile ""/usr/lib/python2.7/dist-packages/pyinotify.py"", line 1604, in handle_read\\nself.process_events()\\nFile ""/usr/lib/python2.7/dist-packages/pyinotify.py"", line 1321, in process_events\\nself._default_proc_fun(revent)\\nFile ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py"", line 152, in inotify_event\\nself.callback()\\nFile ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/handlers.py"", line 65, in poll_tasks\\nfilepath, delay = cls.watcher.examine()\\nFile ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py"", line 72, in examine\\nfunc and func()\\nFile ""/usr/lib/python2.7/dist-packages/mkdocs/serve.py"", line 74, in builder\\nbuild(config, live_server=True)\\nFile ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 299, in build\\nbuild_pages(config)\\nFile ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 259, in build_pages\\ndump_json)\\nFile ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 171, in _build_page\\ninput_content = io.open(input_path, \\'r\\', encoding=\\'utf-8\\').read()\\nIOError: [Errno 2] No such file or directory: \\'/home/paulproteus/projects/sandstorm/docs/.#index.md\\''}]","INFO - Building documentation... +ERROR - file not found: /home/paulproteus/projects/sandstorm/docs/.#index.md +ERROR - Error building page .#index.md +[E 150617 17:22:21 ioloop:612] Exception in callback (3, ) +Traceback (most recent call last): +File ""/home/paulproteus/.local/lib/python2.7/site-packages/tornado/ioloop.py"", line 866, in start +handler_func(fd_obj, events) +File ""/home/paulproteus/.local/lib/python2.7/site-packages/tornado/stack_context.py"", line 275, in null_wrapper +return fn(*args, **kwargs) +File ""/usr/lib/python2.7/dist-packages/pyinotify.py"", line 1604, in handle_read +self.process_events() +File ""/usr/lib/python2.7/dist-packages/pyinotify.py"", line 1321, in process_events +self._default_proc_fun(revent) +File ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py"", line 152, in inotify_event +self.callback() +File ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/handlers.py"", line 65, in poll_tasks +filepath, delay = cls.watcher.examine() +File ""/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py"", line 72, in examine +func and func() +File ""/usr/lib/python2.7/dist-packages/mkdocs/serve.py"", line 74, in builder +build(config, live_server=True) +File ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 299, in build +build_pages(config) +File ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 259, in build_pages +dump_json) +File ""/usr/lib/python2.7/dist-packages/mkdocs/build.py"", line 171, in _build_page +input_content = io.open(input_path, 'r', encoding='utf-8').read() +IOError: [Errno 2] No such file or directory: '/home/paulproteus/projects/sandstorm/docs/.#index.md'",IOError +" def __init__(self, file_match=None, **kwargs): + super(Extras, self).__init__(**kwargs) + self.file_match = file_match"," def __init__(self, file_match, **kwargs): + super(Extras, self).__init__(**kwargs) + self.file_match = file_match","[{'piece_type': 'error message', 'piece_content': 'Traceback (most recent call last):\\nFile ""/srv/mkdocs_head/bin/mkdocs"", line 9, in \\nload_entry_point(\\'mkdocs==0.14.0.dev\\', \\'console_scripts\\', \\'mkdocs\\')()\\nFile ""/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py"", line 664, in __call__\\nreturn self.main(*args, **kwargs)\\nFile ""/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py"", line 644, in main\\nrv = self.invoke(ctx)\\nFile ""/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py"", line 991, in invoke\\nreturn _process_result(sub_ctx.command.invoke(sub_ctx))\\nFile ""/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py"", line 837, in invoke\\nreturn ctx.invoke(self.callback, **ctx.params)\\nFile ""/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py"", line 464, in invoke\\nreturn callback(*args, **kwargs)\\nFile ""/home/zmousm/mkdocs/mkdocs/cli.py"", line 134, in build_command\\n), clean_site_dir=clean)\\nFile ""/home/zmousm/mkdocs/mkdocs/build.py"", line 299, in build\\nbuild_pages(config)\\nFile ""/home/zmousm/mkdocs/mkdocs/build.py"", line 252, in build_pages\\nbuild_extra_templates(config[\\'extra_templates\\'], config, site_navigation)\\nFile ""/home/zmousm/mkdocs/mkdocs/build.py"", line 230, in build_extra_templates\\noutput_content = template.render(context)\\nFile ""/srv/mkdocs_head/local/lib/python2.7/site-packages/jinja2/environment.py"", line 969, in render\\nreturn self.environment.handle_exception(exc_info, True)\\nFile ""/srv/mkdocs_head/local/lib/python2.7/site-packages/jinja2/environment.py"", line 742, in handle_exception\\nreraise(exc_type, exc_value, tb)\\nFile ""