after_merge
stringlengths
28
79.6k
before_merge
stringlengths
20
79.6k
url
stringlengths
38
71
full_traceback
stringlengths
43
922k
traceback_type
stringclasses
555 values
def load(config_details): """Load the configuration from a working directory and a list of configuration files. Files are loaded in order, and merged on top of each other to create the final configuration. Return a fully interpolated, extended and validated configuration. """ def build_service(filename, service_name, service_dict): loader = ServiceLoader( config_details.working_dir, filename, service_name, service_dict ) service_dict = loader.make_service_dict() validate_paths(service_dict) return service_dict def load_file(filename, config): processed_config = interpolate_environment_variables(config) validate_against_fields_schema(processed_config) return [ build_service(filename, name, service_config) for name, service_config in processed_config.items() ] def merge_services(base, override): all_service_names = set(base) | set(override) return { name: merge_service_dicts(base.get(name, {}), override.get(name, {})) for name in all_service_names } config_file = config_details.config_files[0] validate_top_level_object(config_file.config) for next_file in config_details.config_files[1:]: validate_top_level_object(next_file.config) config_file = ConfigFile( config_file.filename, merge_services(config_file.config, next_file.config) ) return load_file(config_file.filename, config_file.config)
def load(config_details): """Load the configuration from a working directory and a list of configuration files. Files are loaded in order, and merged on top of each other to create the final configuration. Return a fully interpolated, extended and validated configuration. """ def build_service(filename, service_name, service_dict): loader = ServiceLoader( config_details.working_dir, filename, service_name, service_dict ) service_dict = loader.make_service_dict() validate_paths(service_dict) return service_dict def load_file(filename, config): processed_config = pre_process_config(config) validate_against_fields_schema(processed_config) return [ build_service(filename, name, service_config) for name, service_config in processed_config.items() ] def merge_services(base, override): all_service_names = set(base) | set(override) return { name: merge_service_dicts(base.get(name, {}), override.get(name, {})) for name in all_service_names } config_file = config_details.config_files[0] for next_file in config_details.config_files[1:]: config_file = ConfigFile( config_file.filename, merge_services(config_file.config, next_file.config) ) return load_file(config_file.filename, config_file.config)
https://github.com/docker/compose/issues/2203
Traceback (most recent call last): File "<string>", line 3, in <module> File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 53, in main File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 23, in sys_dispatch File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 26, in dispatch File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 163, in perform_command File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 54, in project_from_options File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 90, in get_project File "/compose/build/docker-compose/out00-PYZ.pyz/compose.config.config", line 215, in load File "/compose/build/docker-compose/out00-PYZ.pyz/compose.config.config", line 205, in merge_services TypeError: 'NoneType' object is not iterable
TypeError
def load_file(filename, config): processed_config = interpolate_environment_variables(config) validate_against_fields_schema(processed_config) return [ build_service(filename, name, service_config) for name, service_config in processed_config.items() ]
def load_file(filename, config): processed_config = pre_process_config(config) validate_against_fields_schema(processed_config) return [ build_service(filename, name, service_config) for name, service_config in processed_config.items() ]
https://github.com/docker/compose/issues/2203
Traceback (most recent call last): File "<string>", line 3, in <module> File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 53, in main File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 23, in sys_dispatch File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 26, in dispatch File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 163, in perform_command File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 54, in project_from_options File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 90, in get_project File "/compose/build/docker-compose/out00-PYZ.pyz/compose.config.config", line 215, in load File "/compose/build/docker-compose/out00-PYZ.pyz/compose.config.config", line 205, in merge_services TypeError: 'NoneType' object is not iterable
TypeError
def validate_and_construct_extends(self): extends = self.service_dict["extends"] if not isinstance(extends, dict): extends = {"service": extends} validate_extends_file_path(self.service_name, extends, self.filename) self.extended_config_path = self.get_extended_config_path(extends) self.extended_service_name = extends["service"] config = load_yaml(self.extended_config_path) validate_top_level_object(config) full_extended_config = interpolate_environment_variables(config) validate_extended_service_exists( self.extended_service_name, full_extended_config, self.extended_config_path ) validate_against_fields_schema(full_extended_config) self.extended_config = full_extended_config[self.extended_service_name]
def validate_and_construct_extends(self): extends = self.service_dict["extends"] if not isinstance(extends, dict): extends = {"service": extends} validate_extends_file_path(self.service_name, extends, self.filename) self.extended_config_path = self.get_extended_config_path(extends) self.extended_service_name = extends["service"] full_extended_config = pre_process_config(load_yaml(self.extended_config_path)) validate_extended_service_exists( self.extended_service_name, full_extended_config, self.extended_config_path ) validate_against_fields_schema(full_extended_config) self.extended_config = full_extended_config[self.extended_service_name]
https://github.com/docker/compose/issues/2203
Traceback (most recent call last): File "<string>", line 3, in <module> File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 53, in main File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 23, in sys_dispatch File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 26, in dispatch File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 163, in perform_command File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 54, in project_from_options File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 90, in get_project File "/compose/build/docker-compose/out00-PYZ.pyz/compose.config.config", line 215, in load File "/compose/build/docker-compose/out00-PYZ.pyz/compose.config.config", line 205, in merge_services TypeError: 'NoneType' object is not iterable
TypeError
def validate_service_names(config): for service_name in config.keys(): if not isinstance(service_name, six.string_types): raise ConfigurationError( "Service name: {} needs to be a string, eg '{}'".format( service_name, service_name ) )
def validate_service_names(func): @wraps(func) def func_wrapper(config): for service_name in config.keys(): if type(service_name) is int: raise ConfigurationError( "Service name: {} needs to be a string, eg '{}'".format( service_name, service_name ) ) return func(config) return func_wrapper
https://github.com/docker/compose/issues/2203
Traceback (most recent call last): File "<string>", line 3, in <module> File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 53, in main File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 23, in sys_dispatch File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 26, in dispatch File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 163, in perform_command File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 54, in project_from_options File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 90, in get_project File "/compose/build/docker-compose/out00-PYZ.pyz/compose.config.config", line 215, in load File "/compose/build/docker-compose/out00-PYZ.pyz/compose.config.config", line 205, in merge_services TypeError: 'NoneType' object is not iterable
TypeError
def validate_top_level_object(config): if not isinstance(config, dict): raise ConfigurationError( "Top level object needs to be a dictionary. Check your .yml file " "that you have defined a service at the top level." ) validate_service_names(config)
def validate_top_level_object(func): @wraps(func) def func_wrapper(config): if not isinstance(config, dict): raise ConfigurationError( "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level." ) return func(config) return func_wrapper
https://github.com/docker/compose/issues/2203
Traceback (most recent call last): File "<string>", line 3, in <module> File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 53, in main File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 23, in sys_dispatch File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 26, in dispatch File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 163, in perform_command File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 54, in project_from_options File "/compose/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 90, in get_project File "/compose/build/docker-compose/out00-PYZ.pyz/compose.config.config", line 215, in load File "/compose/build/docker-compose/out00-PYZ.pyz/compose.config.config", line 205, in merge_services TypeError: 'NoneType' object is not iterable
TypeError
def friendly_error_message(): try: yield except SSLError as e: raise errors.UserError("SSL error: %s" % e) except ConnectionError: if call_silently(["which", "docker"]) != 0: if is_mac(): raise errors.DockerNotFoundMac() elif is_ubuntu(): raise errors.DockerNotFoundUbuntu() else: raise errors.DockerNotFoundGeneric() elif call_silently(["which", "docker-machine"]) == 0: raise errors.ConnectionErrorDockerMachine() else: raise errors.ConnectionErrorGeneric(get_client().base_url)
def friendly_error_message(): try: yield except SSLError as e: raise errors.UserError("SSL error: %s" % e) except ConnectionError: if call_silently(["which", "docker"]) != 0: if is_mac(): raise errors.DockerNotFoundMac() elif is_ubuntu(): raise errors.DockerNotFoundUbuntu() else: raise errors.DockerNotFoundGeneric() elif call_silently(["which", "boot2docker"]) == 0: raise errors.ConnectionErrorDockerMachine() else: raise errors.ConnectionErrorGeneric(self.get_client().base_url)
https://github.com/docker/compose/issues/2133
Traceback (most recent call last): File "C:\Python27\Scripts\docker-compose-script.py", line 9, in <module> load_entry_point('docker-compose==1.5.0.dev0', 'console_scripts', 'docker-compose')() File "C:\Python27\lib\site-packages\compose\cli\main.py", line 51, in main command.sys_dispatch() File "C:\Python27\lib\site-packages\compose\cli\docopt_command.py", line 23, in sys_dispatch self.dispatch(sys.argv[1:], None) File "C:\Python27\lib\site-packages\compose\cli\command.py", line 46, in dispatch raise errors.ConnectionErrorGeneric(self.get_client().base_url) AttributeError: 'TopLevelCommand' object has no attribute 'get_client'
AttributeError
def loop(self): self._init_readers() while self._num_running > 0: try: item, exception = self.queue.get(timeout=0.1) if exception: raise exception if item is STOP: self._num_running -= 1 else: yield item except Empty: pass # See https://github.com/docker/compose/issues/189 except thread.error: raise KeyboardInterrupt()
def loop(self): self._init_readers() while self._num_running > 0: try: item, exception = self.queue.get(timeout=0.1) if exception: raise exception if item is STOP: self._num_running -= 1 else: yield item except Empty: pass
https://github.com/docker/compose/issues/189
^CGracefully stopping... (press Ctrl+C again to force) Stopping dailylead_db_1... Stopping dailylead_queue_1... Traceback (most recent call last): File "<string>", line 3, in <module> File "/Users/ben/fig/build/fig/out00-PYZ.pyz/fig.cli.main", line 39, in main File "/Users/ben/fig/build/fig/out00-PYZ.pyz/fig.cli.docopt_command", line 21, in sys_dispatch File "/Users/ben/fig/build/fig/out00-PYZ.pyz/fig.cli.command", line 30, in dispatch File "/Users/ben/fig/build/fig/out00-PYZ.pyz/fig.cli.docopt_command", line 24, in dispatch File "/Users/ben/fig/build/fig/out00-PYZ.pyz/fig.cli.command", line 47, in perform_command File "/Users/ben/fig/build/fig/out00-PYZ.pyz/fig.cli.docopt_command", line 27, in perform_command File "/Users/ben/fig/build/fig/out00-PYZ.pyz/fig.cli.main", line 316, in up File "/Users/ben/fig/build/fig/out00-PYZ.pyz/fig.cli.log_printer", line 20, in run File "/Users/ben/fig/build/fig/out00-PYZ.pyz/fig.cli.multiplexer", line 20, in loop File "/Users/ben/fig/build/fig/out00-PYZ.pyz/Queue", line 182, in get thread.error: release unlocked lock
thread.error
def resolve_extends(self, service_dict): if "extends" not in service_dict: return service_dict extends_options = self.validate_extends_options( service_dict["name"], service_dict["extends"] ) if self.working_dir is None: raise Exception("No working_dir passed to ServiceLoader()") if "file" in extends_options: extends_from_filename = extends_options["file"] other_config_path = expand_path(self.working_dir, extends_from_filename) else: other_config_path = self.filename other_working_dir = os.path.dirname(other_config_path) other_already_seen = self.already_seen + [self.signature(service_dict["name"])] other_loader = ServiceLoader( working_dir=other_working_dir, filename=other_config_path, already_seen=other_already_seen, ) base_service = extends_options["service"] other_config = load_yaml(other_config_path) if base_service not in other_config: msg = ("Cannot extend service '%s' in %s: Service not found") % ( base_service, other_config_path, ) raise ConfigurationError(msg) other_service_dict = other_config[base_service] other_loader.detect_cycle(extends_options["service"]) other_service_dict = other_loader.make_service_dict( service_dict["name"], other_service_dict, ) validate_extended_service_dict( other_service_dict, filename=other_config_path, service=extends_options["service"], ) return merge_service_dicts(other_service_dict, service_dict)
def resolve_extends(self, service_dict): if "extends" not in service_dict: return service_dict extends_options = self.validate_extends_options( service_dict["name"], service_dict["extends"] ) if self.working_dir is None: raise Exception("No working_dir passed to ServiceLoader()") if "file" in extends_options: extends_from_filename = extends_options["file"] other_config_path = expand_path(self.working_dir, extends_from_filename) else: other_config_path = self.filename other_working_dir = os.path.dirname(other_config_path) other_already_seen = self.already_seen + [self.signature(service_dict["name"])] other_loader = ServiceLoader( working_dir=other_working_dir, filename=other_config_path, already_seen=other_already_seen, ) other_config = load_yaml(other_config_path) other_service_dict = other_config[extends_options["service"]] other_loader.detect_cycle(extends_options["service"]) other_service_dict = other_loader.make_service_dict( service_dict["name"], other_service_dict, ) validate_extended_service_dict( other_service_dict, filename=other_config_path, service=extends_options["service"], ) return merge_service_dicts(other_service_dict, service_dict)
https://github.com/docker/compose/issues/1826
$ docker-compose up -d Traceback (most recent call last): File "/Users/aanand/.virtualenvs/docker-compose/bin/docker-compose", line 9, in <module> load_entry_point('docker-compose==1.4.0.dev0', 'console_scripts', 'docker-compose')() File "/Users/aanand/work/docker/compose/compose/cli/main.py", line 39, in main command.sys_dispatch() File "/Users/aanand/work/docker/compose/compose/cli/docopt_command.py", line 21, in sys_dispatch self.dispatch(sys.argv[1:], None) File "/Users/aanand/work/docker/compose/compose/cli/command.py", line 27, in dispatch super(Command, self).dispatch(*args, **kwargs) File "/Users/aanand/work/docker/compose/compose/cli/docopt_command.py", line 24, in dispatch self.perform_command(*self.parse(argv, global_options)) File "/Users/aanand/work/docker/compose/compose/cli/command.py", line 57, in perform_command verbose=options.get('--verbose')) File "/Users/aanand/work/docker/compose/compose/cli/command.py", line 78, in get_project config.load(config_details), File "/Users/aanand/work/docker/compose/compose/config/config.py", line 132, in load service_dict = loader.make_service_dict(service_name, service_dict) File "/Users/aanand/work/docker/compose/compose/config/config.py", line 156, in make_service_dict service_dict = self.resolve_extends(service_dict) File "/Users/aanand/work/docker/compose/compose/config/config.py", line 183, in resolve_extends other_service_dict = other_config[extends_options['service']] KeyError: 'foo'
KeyError
def create_container( self, one_off=False, insecure_registry=False, do_build=True, intermediate_container=None, **override_options, ): """ Create a container for this service. If the image doesn't exist, attempt to pull it. """ container_options = self._get_container_create_options( override_options, one_off=one_off, intermediate_container=intermediate_container, ) if do_build and self.can_be_built() and not self.client.images(name=self.full_name): self.build() try: return Container.create(self.client, **container_options) except APIError as e: if ( e.response.status_code == 404 and e.explanation and "No such image" in str(e.explanation) ): self.pull(insecure_registry=insecure_registry) return Container.create(self.client, **container_options) raise
def create_container( self, one_off=False, insecure_registry=False, do_build=True, intermediate_container=None, **override_options, ): """ Create a container for this service. If the image doesn't exist, attempt to pull it. """ container_options = self._get_container_create_options( override_options, one_off=one_off, intermediate_container=intermediate_container, ) if do_build and self.can_be_built() and not self.client.images(name=self.full_name): self.build() try: return Container.create(self.client, **container_options) except APIError as e: if ( e.response.status_code == 404 and e.explanation and "No such image" in str(e.explanation) ): log.info("Pulling image %s..." % container_options["image"]) output = self.client.pull( container_options["image"], stream=True, insecure_registry=insecure_registry, ) stream_output(output, sys.stdout) return Container.create(self.client, **container_options) raise
https://github.com/docker/compose/issues/923
Pulling image 50ff1e85c429:latest... Pulling repository 50ff1e85c429 Traceback (most recent call last): File "<string>", line 3, in <module> File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 31, in main File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 21, in sys_dispatch File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 27, in dispatch File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 24, in dispatch File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 59, in perform_command File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 445, in up File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.project", line 183, in up File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.service", line 258, in recreate_containers File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.service", line 243, in create_container File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.progress_stream", line 37, in stream_output File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.progress_stream", line 50, in print_output_event compose.progress_stream.StreamOutputError: Error: image library/50ff1e85c429:latest not found
compose.progress_stream.StreamOutputError
def _get_container_create_options( self, override_options, one_off=False, intermediate_container=None ): container_options = dict( (k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options ) container_options.update(override_options) container_options["name"] = self._next_container_name( self.containers(stopped=True, one_off=one_off), one_off ) # If a qualified hostname was given, split it into an # unqualified hostname and a domainname unless domainname # was also given explicitly. This matches the behavior of # the official Docker CLI in that scenario. if ( "hostname" in container_options and "domainname" not in container_options and "." in container_options["hostname"] ): parts = container_options["hostname"].partition(".") container_options["hostname"] = parts[0] container_options["domainname"] = parts[2] if "ports" in container_options or "expose" in self.options: ports = [] all_ports = container_options.get("ports", []) + self.options.get("expose", []) for port in all_ports: port = str(port) if ":" in port: port = port.split(":")[-1] if "/" in port: port = tuple(port.split("/")) ports.append(port) container_options["ports"] = ports if "volumes" in container_options: container_options["volumes"] = dict( (parse_volume_spec(v).internal, {}) for v in container_options["volumes"] ) if self.can_be_built(): container_options["image"] = self.full_name # Delete options which are only used when starting for key in DOCKER_START_KEYS: container_options.pop(key, None) container_options["host_config"] = self._get_container_host_config( override_options, one_off=one_off, intermediate_container=intermediate_container ) return container_options
def _get_container_create_options( self, override_options, one_off=False, intermediate_container=None ): container_options = dict( (k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options ) container_options.update(override_options) container_options["name"] = self._next_container_name( self.containers(stopped=True, one_off=one_off), one_off ) # If a qualified hostname was given, split it into an # unqualified hostname and a domainname unless domainname # was also given explicitly. This matches the behavior of # the official Docker CLI in that scenario. if ( "hostname" in container_options and "domainname" not in container_options and "." in container_options["hostname"] ): parts = container_options["hostname"].partition(".") container_options["hostname"] = parts[0] container_options["domainname"] = parts[2] if "ports" in container_options or "expose" in self.options: ports = [] all_ports = container_options.get("ports", []) + self.options.get("expose", []) for port in all_ports: port = str(port) if ":" in port: port = port.split(":")[-1] if "/" in port: port = tuple(port.split("/")) ports.append(port) container_options["ports"] = ports if "volumes" in container_options: container_options["volumes"] = dict( (parse_volume_spec(v).internal, {}) for v in container_options["volumes"] ) if self.can_be_built(): container_options["image"] = self.full_name else: container_options["image"] = self._get_image_name(container_options["image"]) # Delete options which are only used when starting for key in DOCKER_START_KEYS: container_options.pop(key, None) container_options["host_config"] = self._get_container_host_config( override_options, one_off=one_off, intermediate_container=intermediate_container ) return container_options
https://github.com/docker/compose/issues/923
Pulling image 50ff1e85c429:latest... Pulling repository 50ff1e85c429 Traceback (most recent call last): File "<string>", line 3, in <module> File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 31, in main File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 21, in sys_dispatch File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 27, in dispatch File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 24, in dispatch File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 59, in perform_command File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 445, in up File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.project", line 183, in up File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.service", line 258, in recreate_containers File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.service", line 243, in create_container File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.progress_stream", line 37, in stream_output File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.progress_stream", line 50, in print_output_event compose.progress_stream.StreamOutputError: Error: image library/50ff1e85c429:latest not found
compose.progress_stream.StreamOutputError
def pull(self, insecure_registry=False): if "image" not in self.options: return repo, tag = parse_repository_tag(self.options["image"]) tag = tag or "latest" log.info("Pulling %s (%s:%s)..." % (self.name, repo, tag)) output = self.client.pull( repo, tag=tag, stream=True, insecure_registry=insecure_registry ) stream_output(output, sys.stdout)
def pull(self, insecure_registry=False): if "image" in self.options: image_name = self._get_image_name(self.options["image"]) log.info("Pulling %s (%s)..." % (self.name, image_name)) self.client.pull(image_name, insecure_registry=insecure_registry)
https://github.com/docker/compose/issues/923
Pulling image 50ff1e85c429:latest... Pulling repository 50ff1e85c429 Traceback (most recent call last): File "<string>", line 3, in <module> File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 31, in main File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 21, in sys_dispatch File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 27, in dispatch File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.docopt_command", line 24, in dispatch File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.command", line 59, in perform_command File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.cli.main", line 445, in up File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.project", line 183, in up File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.service", line 258, in recreate_containers File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.service", line 243, in create_container File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.progress_stream", line 37, in stream_output File "/Users/ben/fig/build/docker-compose/out00-PYZ.pyz/compose.progress_stream", line 50, in print_output_event compose.progress_stream.StreamOutputError: Error: image library/50ff1e85c429:latest not found
compose.progress_stream.StreamOutputError
def run(self, project, options): """ Run a one-off command on a service. For example: $ docker-compose run web python manage.py shell By default, linked services will be started, unless they are already running. If you do not want to start linked services, use `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`. Usage: run [options] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...] Options: --allow-insecure-ssl Allow insecure connections to the docker registry -d Detached mode: Run container in the background, print new container name. --entrypoint CMD Override the entrypoint of the image. -e KEY=VAL Set an environment variable (can be used multiple times) --no-deps Don't start linked services. --rm Remove container after run. Ignored in detached mode. --service-ports Run command with the service's ports enabled and mapped to the host. -T Disable pseudo-tty allocation. By default `docker-compose run` allocates a TTY. """ service = project.get_service(options["SERVICE"]) insecure_registry = options["--allow-insecure-ssl"] if not options["--no-deps"]: deps = service.get_linked_names() if len(deps) > 0: project.up( service_names=deps, start_links=True, recreate=False, insecure_registry=insecure_registry, detach=options["-d"], ) tty = True if options["-d"] or options["-T"] or not sys.stdin.isatty(): tty = False if options["COMMAND"]: command = [options["COMMAND"]] + options["ARGS"] else: command = service.options.get("command") container_options = { "command": command, "tty": tty, "stdin_open": not options["-d"], "detach": options["-d"], } if options["-e"]: # Merge environment from config with -e command line container_options["environment"] = dict( parse_environment(service.options.get("environment")), **parse_environment(options["-e"]), ) if options["--entrypoint"]: container_options["entrypoint"] = options.get("--entrypoint") container = service.create_container( one_off=True, insecure_registry=insecure_registry, **container_options ) service_ports = None if options["--service-ports"]: service_ports = service.options["ports"] if options["-d"]: service.start_container(container, ports=service_ports, one_off=True) print(container.name) else: service.start_container(container, ports=service_ports, one_off=True) dockerpty.start(project.client, container.id, interactive=not options["-T"]) exit_code = container.wait() if options["--rm"]: log.info("Removing %s..." % container.name) project.client.remove_container(container.id) sys.exit(exit_code)
def run(self, project, options): """ Run a one-off command on a service. For example: $ docker-compose run web python manage.py shell By default, linked services will be started, unless they are already running. If you do not want to start linked services, use `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`. Usage: run [options] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...] Options: --allow-insecure-ssl Allow insecure connections to the docker registry -d Detached mode: Run container in the background, print new container name. --entrypoint CMD Override the entrypoint of the image. -e KEY=VAL Set an environment variable (can be used multiple times) --no-deps Don't start linked services. --rm Remove container after run. Ignored in detached mode. --service-ports Run command with the service's ports enabled and mapped to the host. -T Disable pseudo-tty allocation. By default `docker-compose run` allocates a TTY. """ service = project.get_service(options["SERVICE"]) insecure_registry = options["--allow-insecure-ssl"] if not options["--no-deps"]: deps = service.get_linked_names() if len(deps) > 0: project.up( service_names=deps, start_links=True, recreate=False, insecure_registry=insecure_registry, detach=options["-d"], ) tty = True if options["-d"] or options["-T"] or not sys.stdin.isatty(): tty = False if options["COMMAND"]: command = [options["COMMAND"]] + options["ARGS"] else: command = service.options.get("command") container_options = { "command": command, "tty": tty, "stdin_open": not options["-d"], "detach": options["-d"], } if options["-e"]: for option in options["-e"]: if "environment" not in service.options: service.options["environment"] = {} k, v = option.split("=", 1) service.options["environment"][k] = v if options["--entrypoint"]: container_options["entrypoint"] = options.get("--entrypoint") container = service.create_container( one_off=True, insecure_registry=insecure_registry, **container_options ) service_ports = None if options["--service-ports"]: service_ports = service.options["ports"] if options["-d"]: service.start_container(container, ports=service_ports, one_off=True) print(container.name) else: service.start_container(container, ports=service_ports, one_off=True) dockerpty.start(project.client, container.id, interactive=not options["-T"]) exit_code = container.wait() if options["--rm"]: log.info("Removing %s..." % container.name) project.client.remove_container(container.id) sys.exit(exit_code)
https://github.com/docker/compose/issues/927
$ fig run -e BLA=bla bliep Traceback (most recent call last): File "/usr/local/bin/fig", line 9, in <module> load_entry_point('fig==1.0.1', 'console_scripts', 'fig')() File "/usr/local/lib/python2.7/site-packages/fig/cli/main.py", line 31, in main command.sys_dispatch() File "/usr/local/lib/python2.7/site-packages/fig/cli/docopt_command.py", line 21, in sys_dispatch self.dispatch(sys.argv[1:], None) File "/usr/local/lib/python2.7/site-packages/fig/cli/command.py", line 28, in dispatch super(Command, self).dispatch(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/fig/cli/docopt_command.py", line 24, in dispatch self.perform_command(*self.parse(argv, global_options)) File "/usr/local/lib/python2.7/site-packages/fig/cli/command.py", line 56, in perform_command handler(project, command_options) File "/usr/local/lib/python2.7/site-packages/fig/cli/main.py", line 312, in run service.options['environment'][k] = v TypeError: list indices must be integers, not unicode
TypeError
def _get_container_create_options(self, override_options, one_off=False): container_options = dict( (k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options ) container_options.update(override_options) container_options["name"] = self._next_container_name( self.containers(stopped=True, one_off=one_off), one_off ) # If a qualified hostname was given, split it into an # unqualified hostname and a domainname unless domainname # was also given explicitly. This matches the behavior of # the official Docker CLI in that scenario. if ( "hostname" in container_options and "domainname" not in container_options and "." in container_options["hostname"] ): parts = container_options["hostname"].partition(".") container_options["hostname"] = parts[0] container_options["domainname"] = parts[2] if "ports" in container_options or "expose" in self.options: ports = [] all_ports = container_options.get("ports", []) + self.options.get("expose", []) for port in all_ports: port = str(port) if ":" in port: port = port.split(":")[-1] if "/" in port: port = tuple(port.split("/")) ports.append(port) container_options["ports"] = ports if "volumes" in container_options: container_options["volumes"] = dict( (parse_volume_spec(v).internal, {}) for v in container_options["volumes"] ) container_options["environment"] = build_environment(container_options) if self.can_be_built(): container_options["image"] = self.full_name else: container_options["image"] = self._get_image_name(container_options["image"]) # Delete options which are only used when starting for key in DOCKER_START_KEYS: container_options.pop(key, None) return container_options
def _get_container_create_options(self, override_options, one_off=False): container_options = dict( (k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options ) container_options.update(override_options) container_options["name"] = self._next_container_name( self.containers(stopped=True, one_off=one_off), one_off ) # If a qualified hostname was given, split it into an # unqualified hostname and a domainname unless domainname # was also given explicitly. This matches the behavior of # the official Docker CLI in that scenario. if ( "hostname" in container_options and "domainname" not in container_options and "." in container_options["hostname"] ): parts = container_options["hostname"].partition(".") container_options["hostname"] = parts[0] container_options["domainname"] = parts[2] if "ports" in container_options or "expose" in self.options: ports = [] all_ports = container_options.get("ports", []) + self.options.get("expose", []) for port in all_ports: port = str(port) if ":" in port: port = port.split(":")[-1] if "/" in port: port = tuple(port.split("/")) ports.append(port) container_options["ports"] = ports if "volumes" in container_options: container_options["volumes"] = dict( (parse_volume_spec(v).internal, {}) for v in container_options["volumes"] ) container_options["environment"] = merge_environment(container_options) if self.can_be_built(): container_options["image"] = self.full_name else: container_options["image"] = self._get_image_name(container_options["image"]) # Delete options which are only used when starting for key in DOCKER_START_KEYS: container_options.pop(key, None) return container_options
https://github.com/docker/compose/issues/927
$ fig run -e BLA=bla bliep Traceback (most recent call last): File "/usr/local/bin/fig", line 9, in <module> load_entry_point('fig==1.0.1', 'console_scripts', 'fig')() File "/usr/local/lib/python2.7/site-packages/fig/cli/main.py", line 31, in main command.sys_dispatch() File "/usr/local/lib/python2.7/site-packages/fig/cli/docopt_command.py", line 21, in sys_dispatch self.dispatch(sys.argv[1:], None) File "/usr/local/lib/python2.7/site-packages/fig/cli/command.py", line 28, in dispatch super(Command, self).dispatch(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/fig/cli/docopt_command.py", line 24, in dispatch self.perform_command(*self.parse(argv, global_options)) File "/usr/local/lib/python2.7/site-packages/fig/cli/command.py", line 56, in perform_command handler(project, command_options) File "/usr/local/lib/python2.7/site-packages/fig/cli/main.py", line 312, in run service.options['environment'][k] = v TypeError: list indices must be integers, not unicode
TypeError
def from_n3(s, default=None, backend=None, nsm=None): r''' Creates the Identifier corresponding to the given n3 string. >>> from_n3('<http://ex.com/foo>') == URIRef('http://ex.com/foo') True >>> from_n3('"foo"@de') == Literal('foo', lang='de') True >>> from_n3('"""multi\nline\nstring"""@en') == Literal( ... 'multi\nline\nstring', lang='en') True >>> from_n3('42') == Literal(42) True >>> from_n3(Literal(42).n3()) == Literal(42) True >>> from_n3('"42"^^xsd:integer') == Literal(42) True >>> from rdflib import RDFS >>> from_n3('rdfs:label') == RDFS['label'] True >>> nsm = NamespaceManager(Graph()) >>> nsm.bind('dbpedia', 'http://dbpedia.org/resource/') >>> berlin = URIRef('http://dbpedia.org/resource/Berlin') >>> from_n3('dbpedia:Berlin', nsm=nsm) == berlin True ''' if not s: return default if s.startswith("<"): return URIRef(s[1:-1]) elif s.startswith('"'): if s.startswith('"""'): quotes = '"""' else: quotes = '"' value, rest = s.rsplit(quotes, 1) value = value[len(quotes) :] # strip leading quotes datatype = None language = None # as a given datatype overrules lang-tag check for it first dtoffset = rest.rfind("^^") if dtoffset >= 0: # found a datatype # datatype has to come after lang-tag so ignore everything before # see: http://www.w3.org/TR/2011/WD-turtle-20110809/ # #prod-turtle2-RDFLiteral datatype = from_n3(rest[dtoffset + 2 :], default, backend, nsm) else: if rest.startswith("@"): language = rest[1:] # strip leading at sign value = value.replace(r"\"", '"') # Hack: this should correctly handle strings with either native unicode # characters, or \u1234 unicode escapes. value = value.encode("raw-unicode-escape").decode("unicode-escape") return Literal(value, language, datatype) elif s == "true" or s == "false": return Literal(s == "true") elif s.isdigit(): return Literal(int(s)) elif s.startswith("{"): identifier = from_n3(s[1:-1]) return QuotedGraph(backend, identifier) elif s.startswith("["): identifier = from_n3(s[1:-1]) return Graph(backend, identifier) elif s.startswith("_:"): return BNode(s[2:]) elif ":" in s: if nsm is None: # instantiate default NamespaceManager and rely on its defaults nsm = NamespaceManager(Graph()) prefix, last_part = s.split(":", 1) ns = dict(nsm.namespaces())[prefix] return Namespace(ns)[last_part] else: return BNode(s)
def from_n3(s, default=None, backend=None, nsm=None): r''' Creates the Identifier corresponding to the given n3 string. >>> from_n3('<http://ex.com/foo>') == URIRef('http://ex.com/foo') True >>> from_n3('"foo"@de') == Literal('foo', lang='de') True >>> from_n3('"""multi\nline\nstring"""@en') == Literal( ... 'multi\nline\nstring', lang='en') True >>> from_n3('42') == Literal(42) True >>> from_n3(Literal(42).n3()) == Literal(42) True >>> from_n3('"42"^^xsd:integer') == Literal(42) True >>> from rdflib import RDFS >>> from_n3('rdfs:label') == RDFS['label'] True >>> nsm = NamespaceManager(Graph()) >>> nsm.bind('dbpedia', 'http://dbpedia.org/resource/') >>> berlin = URIRef('http://dbpedia.org/resource/Berlin') >>> from_n3('dbpedia:Berlin', nsm=nsm) == berlin True ''' if not s: return default if s.startswith("<"): return URIRef(s[1:-1]) elif s.startswith('"'): if s.startswith('"""'): quotes = '"""' else: quotes = '"' value, rest = s.rsplit(quotes, 1) value = value[len(quotes) :] # strip leading quotes datatype = None language = None # as a given datatype overrules lang-tag check for it first dtoffset = rest.rfind("^^") if dtoffset >= 0: # found a datatype # datatype has to come after lang-tag so ignore everything before # see: http://www.w3.org/TR/2011/WD-turtle-20110809/ # #prod-turtle2-RDFLiteral datatype = from_n3(rest[dtoffset + 2 :], default, backend, nsm) else: if rest.startswith("@"): language = rest[1:] # strip leading at sign value = value.replace(r"\"", '"').replace("\\\\", "\\") # Hack: this should correctly handle strings with either native unicode # characters, or \u1234 unicode escapes. value = value.encode("raw-unicode-escape").decode("unicode-escape") return Literal(value, language, datatype) elif s == "true" or s == "false": return Literal(s == "true") elif s.isdigit(): return Literal(int(s)) elif s.startswith("{"): identifier = from_n3(s[1:-1]) return QuotedGraph(backend, identifier) elif s.startswith("["): identifier = from_n3(s[1:-1]) return Graph(backend, identifier) elif s.startswith("_:"): return BNode(s[2:]) elif ":" in s: if nsm is None: # instantiate default NamespaceManager and rely on its defaults nsm = NamespaceManager(Graph()) prefix, last_part = s.split(":", 1) ns = dict(nsm.namespaces())[prefix] return Namespace(ns)[last_part] else: return BNode(s)
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def ComponentTerms(cls): """ Takes a Class instance and returns a generator over the classes that are involved in its definition, ignoring unnamed classes """ if OWL_NS.Restriction in cls.type: try: cls = CastClass(cls, Individual.factoryGraph) for s, p, innerClsId in cls.factoryGraph.triples_choices( (cls.identifier, [OWL_NS.allValuesFrom, OWL_NS.someValuesFrom], None) ): innerCls = Class(innerClsId, skipOWLClassMembership=True) if isinstance(innerClsId, BNode): for _c in ComponentTerms(innerCls): yield _c else: yield innerCls except: pass else: cls = CastClass(cls, Individual.factoryGraph) if isinstance(cls, BooleanClass): for _cls in cls: _cls = Class(_cls, skipOWLClassMembership=True) if isinstance(_cls.identifier, BNode): for _c in ComponentTerms(_cls): yield _c else: yield _cls else: for innerCls in cls.subClassOf: if isinstance(innerCls.identifier, BNode): for _c in ComponentTerms(innerCls): yield _c else: yield innerCls for s, p, o in cls.factoryGraph.triples_choices( (classOrIdentifier(cls), CLASS_RELATIONS, None) ): if isinstance(o, BNode): for _c in ComponentTerms(CastClass(o, Individual.factoryGraph)): yield _c else: yield innerCls
def ComponentTerms(cls): """ Takes a Class instance and returns a generator over the classes that are involved in its definition, ignoring unamed classes """ if OWL_NS.Restriction in cls.type: try: cls = CastClass(cls, Individual.factoryGraph) for s, p, innerClsId in cls.factoryGraph.triples_choices( (cls.identifier, [OWL_NS.allValuesFrom, OWL_NS.someValuesFrom], None) ): innerCls = Class(innerClsId, skipOWLClassMembership=True) if isinstance(innerClsId, BNode): for _c in ComponentTerms(innerCls): yield _c else: yield innerCls except: pass else: cls = CastClass(cls, Individual.factoryGraph) if isinstance(cls, BooleanClass): for _cls in cls: _cls = Class(_cls, skipOWLClassMembership=True) if isinstance(_cls.identifier, BNode): for _c in ComponentTerms(_cls): yield _c else: yield _cls else: for innerCls in cls.subClassOf: if isinstance(innerCls.identifier, BNode): for _c in ComponentTerms(innerCls): yield _c else: yield innerCls for s, p, o in cls.factoryGraph.triples_choices( (classOrIdentifier(cls), CLASS_RELATIONS, None) ): if isinstance(o, BNode): for _c in ComponentTerms(CastClass(o, Individual.factoryGraph)): yield _c else: yield innerCls
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def title(self): # overrides unicode.title to allow DCTERMS.title for example return URIRef(self + "title")
def title(self): return URIRef(self + "title")
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def term(self, name): uri = self.__uris.get(name) if uri is None: raise Exception("term '%s' not in namespace '%s'" % (name, self)) else: return uri
def term(self, name): uri = self.__uris.get(name) if uri is None: raise Exception("term '%s' not in namespace '%s'" % (name, self.uri)) else: return uri
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def __repr__(self): return """rdf.namespace.ClosedNamespace('%s')""" % self
def __repr__(self): return """rdf.namespace.ClosedNamespace('%s')""" % str(self.uri)
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def term(self, name): try: i = int(name) return URIRef("%s_%s" % (self, i)) except ValueError: return super(_RDFNamespace, self).term(name)
def term(self, name): try: i = int(name) return URIRef("%s_%s" % (self.uri, i)) except ValueError: return super(_RDFNamespace, self).term(name)
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def __new__(cls): return ClosedNamespace.__new__( cls, "http://www.w3.org/1999/02/22-rdf-syntax-ns#", terms=[ # Syntax Names "RDF", "Description", "ID", "about", "parseType", "resource", "li", "nodeID", "datatype", # RDF Classes "Seq", "Bag", "Alt", "Statement", "Property", "List", "PlainLiteral", # RDF Properties "subject", "predicate", "object", "type", "value", "first", "rest", # and _n where n is a non-negative integer # RDF Resources "nil", # Added in RDF 1.1 "XMLLiteral", "HTML", "langString", ], )
def __new__(cls, value): try: rt = unicode.__new__(cls, value) except UnicodeDecodeError: rt = unicode.__new__(cls, value, "utf-8") return rt
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def __init__(self, system_id=None): xmlreader.InputSource.__init__(self, system_id=system_id) self.content_type = None self.auto_close = False # see Graph.parse(), true if opened by us
def __init__(self, system_id=None): xmlreader.InputSource.__init__(self, system_id=system_id) self.content_type = None
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def create_input_source( source=None, publicID=None, location=None, file=None, data=None, format=None ): """ Return an appropriate InputSource instance for the given parameters. """ # test that exactly one of source, location, file, and data is not None. if ( sum( ( source is not None, location is not None, file is not None, data is not None, ) ) != 1 ): raise ValueError("exactly one of source, location, file or data must be given") input_source = None if source is not None: if isinstance(source, InputSource): input_source = source else: if isinstance(source, basestring): location = source elif hasattr(source, "read") and not isinstance(source, Namespace): f = source input_source = InputSource() input_source.setByteStream(f) if f is sys.stdin: input_source.setSystemId("file:///dev/stdin") elif hasattr(f, "name"): input_source.setSystemId(f.name) else: raise Exception( "Unexpected type '%s' for source '%s'" % (type(source), source) ) absolute_location = None # Further to fix for issue 130 auto_close = False # make sure we close all file handles we open if location is not None: # Fix for Windows problem https://github.com/RDFLib/rdflib/issues/145 if os.path.exists(location): location = pathname2url(location) base = urljoin("file:", "%s/" % pathname2url(os.getcwd())) absolute_location = URIRef(location, base=base).defrag() if absolute_location.startswith("file:///"): filename = url2pathname(absolute_location.replace("file:///", "/")) file = open(filename, "rb") else: input_source = URLInputSource(absolute_location, format) auto_close = True # publicID = publicID or absolute_location # Further to fix # for issue 130 if file is not None: input_source = FileInputSource(file) if data is not None: if isinstance(data, unicode): data = data.encode("utf-8") input_source = StringInputSource(data) auto_close = True if input_source is None: raise Exception("could not create InputSource") else: input_source.auto_close |= auto_close if publicID is not None: # Further to fix for issue 130 input_source.setPublicId(publicID) # Further to fix for issue 130 elif input_source.getPublicId() is None: input_source.setPublicId(absolute_location or "") return input_source
def create_input_source( source=None, publicID=None, location=None, file=None, data=None, format=None ): """ Return an appropriate InputSource instance for the given parameters. """ # TODO: test that exactly one of source, location, file, and data # is not None. input_source = None if source is not None: if isinstance(source, InputSource): input_source = source else: if isinstance(source, basestring): location = source elif hasattr(source, "read") and not isinstance(source, Namespace): f = source input_source = InputSource() input_source.setByteStream(f) if f is sys.stdin: input_source.setSystemId("file:///dev/stdin") elif hasattr(f, "name"): input_source.setSystemId(f.name) else: raise Exception( "Unexpected type '%s' for source '%s'" % (type(source), source) ) absolute_location = None # Further to fix for issue 130 if location is not None: # Fix for Windows problem https://github.com/RDFLib/rdflib/issues/145 if os.path.exists(location): location = pathname2url(location) base = urljoin("file:", "%s/" % pathname2url(os.getcwd())) absolute_location = URIRef(location, base=base).defrag() if absolute_location.startswith("file:///"): filename = url2pathname(absolute_location.replace("file:///", "/")) file = open(filename, "rb") else: input_source = URLInputSource(absolute_location, format) # publicID = publicID or absolute_location # Further to fix # for issue 130 if file is not None: input_source = FileInputSource(file) if data is not None: if isinstance(data, unicode): data = data.encode("utf-8") input_source = StringInputSource(data) if input_source is None: raise Exception("could not create InputSource") else: if publicID is not None: # Further to fix for issue 130 input_source.setPublicId(publicID) # Further to fix for issue 130 elif input_source.getPublicId() is None: input_source.setPublicId(absolute_location or "") return input_source
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def __init__(self, name): """ @param name: URL to be opened @keyword additional_headers: additional HTTP request headers to be added to the call """ try: # Note the removal of the fragment ID. This is necessary, per the HTTP spec req = Request(url=name.split("#")[0]) req.add_header("Accept", "text/html, application/xhtml+xml") self.data = urlopen(req) self.headers = self.data.info() if URIOpener.CONTENT_LOCATION in self.headers: self.location = urljoin( self.data.geturl(), self.headers[URIOpener.CONTENT_LOCATION] ) else: self.location = name except urllib_HTTPError: e = sys.exc_info()[1] from pyMicrodata import HTTPError msg = BaseHTTPRequestHandler.responses[e.code] raise HTTPError("%s" % msg[1], e.code) except Exception: e = sys.exc_info()[1] from pyMicrodata import MicrodataError raise MicrodataError("%s" % e)
def __init__(self, name): """ @param name: URL to be opened @keyword additional_headers: additional HTTP request headers to be added to the call """ try: # Note the removal of the fragment ID. This is necessary, per the HTTP spec req = Request(url=name.split("#")[0]) req.add_header("Accept", "text/html, application/xhtml+xml") self.data = urlopen(req) self.headers = self.data.info() if URIOpener.CONTENT_LOCATION in self.headers: self.location = urlparse.urljoin( self.data.geturl(), self.headers[URIOpener.CONTENT_LOCATION] ) else: self.location = name except urllib_HTTPError: e = sys.exc_info()[1] from pyMicrodata import HTTPError msg = BaseHTTPRequestHandler.responses[e.code] raise HTTPError("%s" % msg[1], e.code) except Exception: e = sys.exc_info()[1] from pyMicrodata import MicrodataError raise MicrodataError("%s" % e)
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def html5_extra_attributes(node, state): """ @param node: the current node that could be modified @param state: current state @type state: L{Execution context<pyRdfa.state.ExecutionContext>} """ def _get_literal(Pnode): """ Get (recursively) the full text from a DOM Node. @param Pnode: DOM Node @return: string """ rc = "" for node in Pnode.childNodes: if node.nodeType == node.TEXT_NODE: rc = rc + node.data elif node.nodeType == node.ELEMENT_NODE: rc = rc + _get_literal(node) if state.options.space_preserve: return rc else: return re.sub(r"(\r| |\n|\t)+", " ", rc).strip() # return re.sub(r'(\r| |\n|\t)+',"",rc).strip() # end _getLiteral def _set_time(value): if not node.hasAttribute("datatype"): # Check the datatype: dt = _format_test(value) if dt != plain: node.setAttribute("datatype", dt) # Finally, set the value itself node.setAttribute("content", value) # end _set_time if not node.hasAttribute("content"): # @content has top priority over the others... if node.hasAttribute("datetime"): _set_time(node.getAttribute("datetime")) elif node.hasAttribute("dateTime"): _set_time(node.getAttribute("dateTime")) elif node.tagName == "time": # Note that a possible @datetime value has already been taken care of _set_time(_get_literal(node))
def html5_extra_attributes(node, state): """ @param node: the current node that could be modified @param state: current state @type state: L{Execution context<pyRdfa.state.ExecutionContext>} """ def _get_literal(Pnode): """ Get (recursively) the full text from a DOM Node. @param Pnode: DOM Node @return: string """ rc = "" for node in Pnode.childNodes: if node.nodeType == node.TEXT_NODE: rc = rc + node.data elif node.nodeType == node.ELEMENT_NODE: rc = rc + self._get_literal(node) if state.options.space_preserve: return rc else: return re.sub(r"(\r| |\n|\t)+", " ", rc).strip() # return re.sub(r'(\r| |\n|\t)+',"",rc).strip() # end _getLiteral def _set_time(value): if not node.hasAttribute("datatype"): # Check the datatype: dt = _format_test(value) if dt != plain: node.setAttribute("datatype", dt) # Finally, set the value itself node.setAttribute("content", value) # end _set_time if not node.hasAttribute("content"): # @content has top priority over the others... if node.hasAttribute("datetime"): _set_time(node.getAttribute("datetime")) elif node.hasAttribute("dateTime"): _set_time(node.getAttribute("dateTime")) elif node.tagName == "time": # Note that a possible @datetime value has already been taken care of _set_time(_get_literal(node))
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def _get_literal(Pnode): """ Get (recursively) the full text from a DOM Node. @param Pnode: DOM Node @return: string """ rc = "" for node in Pnode.childNodes: if node.nodeType == node.TEXT_NODE: rc = rc + node.data elif node.nodeType == node.ELEMENT_NODE: rc = rc + _get_literal(node) if state.options.space_preserve: return rc else: return re.sub(r"(\r| |\n|\t)+", " ", rc).strip()
def _get_literal(Pnode): """ Get (recursively) the full text from a DOM Node. @param Pnode: DOM Node @return: string """ rc = "" for node in Pnode.childNodes: if node.nodeType == node.TEXT_NODE: rc = rc + node.data elif node.nodeType == node.ELEMENT_NODE: rc = rc + self._get_literal(node) if state.options.space_preserve: return rc else: return re.sub(r"(\r| |\n|\t)+", " ", rc).strip()
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def generate_1_1(self): """Generate the property object, 1.1 version""" ######################################################################### # See if the target is _not_ a literal irirefs = ("resource", "href", "src") noiri = ("content", "datatype", "rel", "rev") notypediri = ("content", "datatype", "rel", "rev", "about", "about_pruned") if has_one_of_attributes(self.node, irirefs) and not has_one_of_attributes( self.node, noiri ): # @href/@resource/@src takes the lead here... object = self.state.getResource(irirefs) elif ( self.node.hasAttribute("typeof") and not has_one_of_attributes(self.node, notypediri) and self.typed_resource != None ): # a @typeof creates a special branch in case the typed resource was set during parsing object = self.typed_resource else: # We have to generate a literal # Get, if exists, the value of @datatype datatype = "" dtset = False if self.node.hasAttribute("datatype"): dtset = True dt = self.node.getAttribute("datatype") if dt != "": datatype = self.state.getURI("datatype") # Supress lange is set in case some elements explicitly want to supress the effect of language # There were discussions, for example, that the <time> element should do so. Although, # after all, this was reversed, the functionality is kept in the code in case another # element might need it... if self.state.lang != None and self.state.supress_lang == False: lang = self.state.lang else: lang = "" # The simple case: separate @content attribute if self.node.hasAttribute("content"): val = self.node.getAttribute("content") # Handling the automatic uri conversion case if dtset == False: object = Literal(val, lang=lang) else: object = self._create_Literal(val, datatype=datatype, lang=lang) # The value of datatype has been set, and the keyword parameters take care of the rest else: # see if there *is* a datatype (even if it is empty!) if dtset: if datatype == XMLLiteral: litval = self._get_XML_literal(self.node) object = Literal(litval, datatype=XMLLiteral) elif datatype == HTMLLiteral: # I am not sure why this hack is necessary, but otherwise an encoding error occurs # In Python3 all this should become moot, due to the unicode everywhere approach... if sys.version_info[0] >= 3: object = Literal( self._get_HTML_literal(self.node), datatype=HTMLLiteral ) else: litval = self._get_HTML_literal(self.node) o = Literal(litval, datatype=XMLLiteral) object = Literal(o, datatype=HTMLLiteral) else: object = self._create_Literal( self._get_literal(self.node), datatype=datatype, lang=lang ) else: object = self._create_Literal(self._get_literal(self.node), lang=lang) if object != None: for prop in self.state.getURI("property"): if not isinstance(prop, BNode): if self.node.hasAttribute("inlist"): self.state.add_to_list_mapping(prop, object) else: self.graph.add((self.subject, prop, object)) else: self.state.options.add_warning( err_no_blank_node % "property", warning_type=IncorrectBlankNodeUsage, node=self.node.nodeName, )
def generate_1_1(self): """Generate the property object, 1.1 version""" ######################################################################### # See if the target is _not_ a literal irirefs = ("resource", "href", "src") noiri = ("content", "datatype", "rel", "rev") notypediri = ("content", "datatype", "rel", "rev", "about", "about_pruned") if has_one_of_attributes(self.node, irirefs) and not has_one_of_attributes( self.node, noiri ): # @href/@resource/@src takes the lead here... object = self.state.getResource(irirefs) elif ( self.node.hasAttribute("typeof") and not has_one_of_attributes(self.node, notypediri) and self.typed_resource != None ): # a @typeof creates a special branch in case the typed resource was set during parsing object = self.typed_resource else: # We have to generate a literal # Get, if exists, the value of @datatype datatype = "" dtset = False if self.node.hasAttribute("datatype"): dtset = True dt = self.node.getAttribute("datatype") if dt != "": datatype = self.state.getURI("datatype") # Supress lange is set in case some elements explicitly want to supress the effect of language # There were discussions, for example, that the <time> element should do so. Although, # after all, this was reversed, the functionality is kept in the code in case another # element might need it... if self.state.lang != None and self.state.supress_lang == False: lang = self.state.lang else: lang = "" # The simple case: separate @content attribute if self.node.hasAttribute("content"): val = self.node.getAttribute("content") # Handling the automatic uri conversion case if dtset == False: object = Literal(val, lang=lang) else: object = self._create_Literal(val, datatype=datatype, lang=lang) # The value of datatype has been set, and the keyword paramaters take care of the rest else: # see if there *is* a datatype (even if it is empty!) if dtset: if datatype == XMLLiteral: litval = self._get_XML_literal(self.node) object = Literal(litval, datatype=XMLLiteral) elif datatype == HTMLLiteral: # I am not sure why this hack is necessary, but otherwise an encoding error occurs # In Python3 all this should become moot, due to the unicode everywhere approach... if sys.version_info[0] >= 3: object = Literal( self._get_HTML_literal(self.node), datatype=HTMLLiteral ) else: litval = self._get_HTML_literal(self.node) o = Literal(litval, datatype=XMLLiteral) object = Literal(o, datatype=HTMLLiteral) else: object = self._create_Literal( self._get_literal(self.node), datatype=datatype, lang=lang ) else: object = self._create_Literal(self._get_literal(self.node), lang=lang) if object != None: for prop in self.state.getURI("property"): if not isinstance(prop, BNode): if self.node.hasAttribute("inlist"): self.state.add_to_list_mapping(prop, object) else: self.graph.add((self.subject, prop, object)) else: self.state.options.add_warning( err_no_blank_node % "property", warning_type=IncorrectBlankNodeUsage, node=self.node.nodeName, )
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def generate_1_0(self): """Generate the property object, 1.0 version""" ######################################################################### # We have to generate a literal indeed. # Get, if exists, the value of @datatype datatype = "" dtset = False if self.node.hasAttribute("datatype"): dtset = True dt = self.node.getAttribute("datatype") if dt != "": datatype = self.state.getURI("datatype") if self.state.lang != None: lang = self.state.lang else: lang = "" # The simple case: separate @content attribute if self.node.hasAttribute("content"): val = self.node.getAttribute("content") # Handling the automatic uri conversion case if dtset == False: object = Literal(val, lang=lang) else: object = self._create_Literal(val, datatype=datatype, lang=lang) # The value of datatype has been set, and the keyword parameters take care of the rest else: # see if there *is* a datatype (even if it is empty!) if dtset: # yep. The Literal content is the pure text part of the current element: # We have to check whether the specified datatype is, in fact, an # explicit XML Literal if datatype == XMLLiteral: litval = self._get_XML_literal(self.node) object = Literal(litval, datatype=XMLLiteral) elif datatype == HTMLLiteral: # I am not sure why this hack is necessary, but otherwise an encoding error occurs # In Python3 all this should become moot, due to the unicode everywhere approach... if sys.version_info[0] >= 3: object = Literal( self._get_HTML_literal(self.node), datatype=HTMLLiteral ) else: litval = self._get_HTML_literal(self.node) o = Literal(litval, datatype=XMLLiteral) object = Literal(o, datatype=HTMLLiteral) else: object = self._create_Literal( self._get_literal(self.node), datatype=datatype, lang=lang ) else: # no controlling @datatype. We have to see if there is markup in the contained # element if True in [ n.nodeType == self.node.ELEMENT_NODE for n in self.node.childNodes ]: # yep, and XML Literal should be generated object = self._create_Literal( self._get_XML_literal(self.node), datatype=XMLLiteral ) else: # At this point, there might be entities in the string that are returned as real characters by the dom # implementation. That should be turned back object = self._create_Literal(self._get_literal(self.node), lang=lang) for prop in self.state.getURI("property"): if not isinstance(prop, BNode): self.graph.add((self.subject, prop, object)) else: self.state.options.add_warning( err_no_blank_node % "property", warning_type=IncorrectBlankNodeUsage, node=self.node.nodeName, )
def generate_1_0(self): """Generate the property object, 1.0 version""" ######################################################################### # We have to generate a literal indeed. # Get, if exists, the value of @datatype datatype = "" dtset = False if self.node.hasAttribute("datatype"): dtset = True dt = self.node.getAttribute("datatype") if dt != "": datatype = self.state.getURI("datatype") if self.state.lang != None: lang = self.state.lang else: lang = "" # The simple case: separate @content attribute if self.node.hasAttribute("content"): val = self.node.getAttribute("content") # Handling the automatic uri conversion case if dtset == False: object = Literal(val, lang=lang) else: object = self._create_Literal(val, datatype=datatype, lang=lang) # The value of datatype has been set, and the keyword paramaters take care of the rest else: # see if there *is* a datatype (even if it is empty!) if dtset: # yep. The Literal content is the pure text part of the current element: # We have to check whether the specified datatype is, in fact, an # explicit XML Literal if datatype == XMLLiteral: litval = self._get_XML_literal(self.node) object = Literal(litval, datatype=XMLLiteral) elif datatype == HTMLLiteral: # I am not sure why this hack is necessary, but otherwise an encoding error occurs # In Python3 all this should become moot, due to the unicode everywhere approach... if sys.version_info[0] >= 3: object = Literal( self._get_HTML_literal(self.node), datatype=HTMLLiteral ) else: litval = self._get_HTML_literal(self.node) o = Literal(litval, datatype=XMLLiteral) object = Literal(o, datatype=HTMLLiteral) else: object = self._create_Literal( self._get_literal(self.node), datatype=datatype, lang=lang ) else: # no controlling @datatype. We have to see if there is markup in the contained # element if True in [ n.nodeType == self.node.ELEMENT_NODE for n in self.node.childNodes ]: # yep, and XML Literal should be generated object = self._create_Literal( self._get_XML_literal(self.node), datatype=XMLLiteral ) else: # At this point, there might be entities in the string that are returned as real characters by the dom # implementation. That should be turned back object = self._create_Literal(self._get_literal(self.node), lang=lang) for prop in self.state.getURI("property"): if not isinstance(prop, BNode): self.graph.add((self.subject, prop, object)) else: self.state.options.add_warning( err_no_blank_node % "property", warning_type=IncorrectBlankNodeUsage, node=self.node.nodeName, )
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def evalPart(ctx, part): # try custom evaluation functions for name, c in CUSTOM_EVALS.items(): try: return c(ctx, part) except NotImplementedError: pass # the given custome-function did not handle this part if part.name == "BGP": # Reorder triples patterns by number of bound nodes in the current ctx # Do patterns with more bound nodes first triples = sorted( part.triples, key=lambda t: len([n for n in t if ctx[n] is None]) ) return evalBGP(ctx, triples) elif part.name == "Filter": return evalFilter(ctx, part) elif part.name == "Join": return evalJoin(ctx, part) elif part.name == "LeftJoin": return evalLeftJoin(ctx, part) elif part.name == "Graph": return evalGraph(ctx, part) elif part.name == "Union": return evalUnion(ctx, part) elif part.name == "ToMultiSet": return evalMultiset(ctx, part) elif part.name == "Extend": return evalExtend(ctx, part) elif part.name == "Minus": return evalMinus(ctx, part) elif part.name == "Project": return evalProject(ctx, part) elif part.name == "Slice": return evalSlice(ctx, part) elif part.name == "Distinct": return evalDistinct(ctx, part) elif part.name == "Reduced": return evalReduced(ctx, part) elif part.name == "OrderBy": return evalOrderBy(ctx, part) elif part.name == "Group": return evalGroup(ctx, part) elif part.name == "AggregateJoin": return evalAggregateJoin(ctx, part) elif part.name == "SelectQuery": return evalSelectQuery(ctx, part) elif part.name == "AskQuery": return evalAskQuery(ctx, part) elif part.name == "ConstructQuery": return evalConstructQuery(ctx, part) elif part.name == "ServiceGraphPattern": raise Exception("ServiceGraphPattern not implemented") elif part.name == "DescribeQuery": raise Exception("DESCRIBE not implemented") else: # import pdb ; pdb.set_trace() raise Exception("I dont know: %s" % part.name)
def evalPart(ctx, part): # try custom evaluation functions for name, c in CUSTOM_EVALS.items(): try: return c(ctx, part) except NotImplementedError: pass # the given custome-function did not handle this part if part.name == "BGP": return evalBGP(ctx, part.triples) # NOTE pass part.triples, not part! elif part.name == "Filter": return evalFilter(ctx, part) elif part.name == "Join": return evalJoin(ctx, part) elif part.name == "LeftJoin": return evalLeftJoin(ctx, part) elif part.name == "Graph": return evalGraph(ctx, part) elif part.name == "Union": return evalUnion(ctx, part) elif part.name == "ToMultiSet": return evalMultiset(ctx, part) elif part.name == "Extend": return evalExtend(ctx, part) elif part.name == "Minus": return evalMinus(ctx, part) elif part.name == "Project": return evalProject(ctx, part) elif part.name == "Slice": return evalSlice(ctx, part) elif part.name == "Distinct": return evalDistinct(ctx, part) elif part.name == "Reduced": return evalReduced(ctx, part) elif part.name == "OrderBy": return evalOrderBy(ctx, part) elif part.name == "Group": return evalGroup(ctx, part) elif part.name == "AggregateJoin": return evalAggregateJoin(ctx, part) elif part.name == "SelectQuery": return evalSelectQuery(ctx, part) elif part.name == "AskQuery": return evalAskQuery(ctx, part) elif part.name == "ConstructQuery": return evalConstructQuery(ctx, part) elif part.name == "ServiceGraphPattern": raise Exception("ServiceGraphPattern not implemented") elif part.name == "DescribeQuery": raise Exception("DESCRIBE not implemented") else: # import pdb ; pdb.set_trace() raise Exception("I dont know: %s" % part.name)
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def evalQuery(graph, query, initBindings, base=None): ctx = QueryContext(graph) ctx.prologue = query.prologue main = query.algebra if initBindings: # add initBindings as a values clause values = {} # no dict comprehension in 2.6 :( for k, v in initBindings.iteritems(): if not isinstance(k, Variable): k = Variable(k) values[k] = v main = main.clone() # clone to not change prepared q main["p"] = main.p.clone() # Find the right place to insert MultiSet join repl = main.p if repl.name == "Slice": repl["p"] = repl.p.clone() repl = repl.p if repl.name == "Distinct": repl["p"] = repl.p.clone() repl = repl.p if repl.p.name == "OrderBy": repl["p"] = repl.p.clone() repl = repl.p if repl.p.name == "Extend": repl["p"] = repl.p.clone() repl = repl.p repl["p"] = Join(repl.p, ToMultiSet(Values([values]))) # TODO: Vars? if main.datasetClause: if ctx.dataset is None: raise Exception( "Non-conjunctive-graph doesn't know about " + "graphs! Try a query without FROM (NAMED)." ) ctx = ctx.clone() # or push/pop? firstDefault = False for d in main.datasetClause: if d.default: if firstDefault: # replace current default graph dg = ctx.dataset.get_context(BNode()) ctx = ctx.pushGraph(dg) firstDefault = True ctx.load(d.default, default=True) elif d.named: g = d.named ctx.load(g, default=False) return evalPart(ctx, main)
def evalQuery(graph, query, initBindings, base=None): ctx = QueryContext(graph) ctx.prologue = query.prologue if initBindings: for k, v in initBindings.iteritems(): if not isinstance(k, Variable): k = Variable(k) ctx[k] = v # ctx.push() # nescessary? main = query.algebra # import pdb; pdb.set_trace() if main.datasetClause: if ctx.dataset is None: raise Exception( "Non-conjunctive-graph doesn't know about " + "graphs! Try a query without FROM (NAMED)." ) ctx = ctx.clone() # or push/pop? firstDefault = False for d in main.datasetClause: if d.default: if firstDefault: # replace current default graph dg = ctx.dataset.get_context(BNode()) ctx = ctx.pushGraph(dg) firstDefault = True ctx.load(d.default, default=True) elif d.named: g = d.named ctx.load(g, default=False) return evalPart(ctx, main)
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def absolutize(self, iri): """ Apply BASE / PREFIXes to URIs (and to datatypes in Literals) TODO: Move resolving URIs to pre-processing """ if isinstance(iri, CompValue): if iri.name == "pname": return self.resolvePName(iri.prefix, iri.localname) if iri.name == "literal": return Literal( iri.string, lang=iri.lang, datatype=self.absolutize(iri.datatype) ) elif isinstance(iri, URIRef) and not ":" in iri: return URIRef(iri, base=self.base) return iri
def absolutize(self, iri): """ Apply BASE / PREFIXes to URIs (and to datatypes in Literals) TODO: Move resolving URIs to pre-processing """ if isinstance(iri, CompValue): if iri.name == "pname": return self.resolvePName(iri.prefix, iri.localname) if iri.name == "literal": return Literal( iri.string, lang=iri.lang, datatype=self.absolutize(iri.datatype) ) elif isinstance(iri, URIRef) and not ":" in iri: # TODO: Check for relative URI? return URIRef(self.base + iri) return iri
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def __getitem__(self, item): if isinstance(item, slice): if item.step: raise TypeError( "Resources fix the subject for slicing, and can only be sliced by predicate/object. " ) p, o = item.start, item.stop if isinstance(p, Resource): p = p._identifier if isinstance(o, Resource): o = o._identifier if p is None and o is None: return self.predicate_objects() elif p is None: return self.predicates(o) elif o is None: return self.objects(p) else: return (self.identifier, p, o) in self._graph elif isinstance(item, (Node, Path)): return self.objects(item) else: raise TypeError( "You can only index a resource by a single rdflib term, a slice of rdflib terms, not %s (%s)" % (item, type(item)) )
def __getitem__(self, item): if isinstance(item, slice): if item.step: raise TypeError( "Resources fix the subject for slicing, and can only be sliced by predicate/object. " ) p, o = item.start, item.stop if p is None and o is None: return self.predicate_objects() elif p is None: return self.predicates(o) elif o is None: return self.objects(p) else: return (self.identifier, p, o) in self._graph elif isinstance(item, (Node, Path)): return self.objects(item) else: raise TypeError( "You can only index a resource by a single rdflib term, a slice of rdflib terms, not %s (%s)" % (item, type(item)) )
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def setup_python3(): # Taken from "distribute" setup.py from distutils.filelist import FileList from distutils import dir_util, file_util, util, log from os.path import join, exists tmp_src = join("build", "src") # Not covered by "setup.py clean --all", so explicit deletion required. if exists(tmp_src): dir_util.remove_tree(tmp_src) # log.set_verbosity(1) fl = FileList() for line in open("MANIFEST.in"): if not line.strip(): continue fl.process_template_line(line) dir_util.create_tree(tmp_src, fl.files) outfiles_2to3 = [] for f in fl.files: outf, copied = file_util.copy_file(f, join(tmp_src, f), update=1) if copied and outf.endswith(".py"): outfiles_2to3.append(outf) util.run_2to3(outfiles_2to3) # arrange setup to use the copy sys.path.insert(0, tmp_src) return tmp_src
def setup_python3(): # Taken from "distribute" setup.py from distutils.filelist import FileList from distutils import dir_util, file_util, util, log from os.path import join, exists tmp_src = join("build", "src") # Not covered by "setup.py clean --all", so explicit deletion required. if exists(tmp_src): dir_util.remove_tree(tmp_src) log.set_verbosity(1) fl = FileList() for line in open("MANIFEST.in"): if not line.strip(): continue fl.process_template_line(line) dir_util.create_tree(tmp_src, fl.files) outfiles_2to3 = [] for f in fl.files: outf, copied = file_util.copy_file(f, join(tmp_src, f), update=1) if copied and outf.endswith(".py"): outfiles_2to3.append(outf) util.run_2to3(outfiles_2to3) # arrange setup to use the copy sys.path.insert(0, tmp_src) return tmp_src
https://github.com/RDFLib/rdflib/issues/546
from rdflib.util import from_n3 sample = "\"Sample string with trailing backslash\\\"^^xsd:string" from_n3(sample) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/site-packages/rdflib/util.py", line 183, in from_n3 value = value.encode("raw-unicode-escape").decode("unicode-escape") UnicodeDecodeError: 'unicodeescape' codec can't decode byte 0x5c in position 37: \ at end of string
UnicodeDecodeError
def create_input_source( source=None, publicID=None, location=None, file=None, data=None, format=None ): """ Return an appropriate InputSource instance for the given parameters. """ # TODO: test that exactly one of source, location, file, and data # is not None. input_source = None if source is not None: if isinstance(source, InputSource): input_source = source else: if isinstance(source, basestring): location = source elif hasattr(source, "read") and not isinstance(source, Namespace): f = source input_source = InputSource() input_source.setByteStream(f) if f is sys.stdin: input_source.setSystemId("file:///dev/stdin") elif hasattr(f, "name"): input_source.setSystemId(f.name) else: raise Exception( "Unexpected type '%s' for source '%s'" % (type(source), source) ) absolute_location = None # Further to fix for issue 130 if location is not None: # Fix for Windows problem https://github.com/RDFLib/rdflib/issues/145 if os.path.exists(location): location = pathname2url(location) base = urljoin("file:", "%s/" % pathname2url(os.getcwd())) absolute_location = URIRef(location, base=base).defrag() if absolute_location.startswith("file:///"): filename = url2pathname(absolute_location.replace("file:///", "/")) file = open(filename, "rb") else: input_source = URLInputSource(absolute_location, format) # publicID = publicID or absolute_location # Further to fix # for issue 130 if file is not None: input_source = FileInputSource(file) if data is not None: if isinstance(data, unicode): data = data.encode("utf-8") input_source = StringInputSource(data) if input_source is None: raise Exception("could not create InputSource") else: if publicID is not None: # Further to fix for issue 130 input_source.setPublicId(publicID) # Further to fix for issue 130 elif input_source.getPublicId() is None: input_source.setPublicId(absolute_location or "") return input_source
def create_input_source( source=None, publicID=None, location=None, file=None, data=None, format=None ): """ Return an appropriate InputSource instance for the given parameters. """ # TODO: test that exactly one of source, location, file, and data # is not None. input_source = None if source is not None: if isinstance(source, InputSource): input_source = source else: if isinstance(source, basestring): location = source elif hasattr(source, "read") and not isinstance(source, Namespace): f = source input_source = InputSource() input_source.setByteStream(f) if hasattr(f, "name"): input_source.setSystemId(f.name) else: raise Exception( "Unexpected type '%s' for source '%s'" % (type(source), source) ) absolute_location = None # Further to fix for issue 130 if location is not None: # Fix for Windows problem https://github.com/RDFLib/rdflib/issues/145 if os.path.exists(location): location = pathname2url(location) base = urljoin("file:", "%s/" % pathname2url(os.getcwd())) absolute_location = URIRef(location, base=base).defrag() if absolute_location.startswith("file:///"): filename = url2pathname(absolute_location.replace("file:///", "/")) file = open(filename, "rb") else: input_source = URLInputSource(absolute_location, format) # publicID = publicID or absolute_location # Further to fix # for issue 130 if file is not None: input_source = FileInputSource(file) if data is not None: if isinstance(data, unicode): data = data.encode("utf-8") input_source = StringInputSource(data) if input_source is None: raise Exception("could not create InputSource") else: if publicID is not None: # Further to fix for issue 130 input_source.setPublicId(publicID) # Further to fix for issue 130 elif input_source.getPublicId() is None: input_source.setPublicId(absolute_location or "") return input_source
https://github.com/RDFLib/rdflib/issues/285
Traceback (most recent call last): File "<string>", line 4, in <module> ... File ".../rdflib/term.py", line 208, in __new__ raise Exception('%s does not look like a valid URI, perhaps you want to urlencode it?'%value) Exception: file:///private/tmp/<stdin> does not look like a valid URI, perhaps you want to urlencode it?
Exception
def compute_qname(self, uri, generate=True): if not _is_valid_uri(uri): raise Exception( '"%s" does not look like a valid URI, I cannot serialize this. Perhaps you wanted to urlencode it?' % uri ) if not uri in self.__cache: namespace, name = split_uri(uri) namespace = URIRef(namespace) prefix = self.store.prefix(namespace) if prefix is None: if not generate: raise Exception("No known prefix for %s and generate=False") num = 1 while 1: prefix = "ns%s" % num if not self.store.namespace(prefix): break num += 1 self.bind(prefix, namespace) self.__cache[uri] = (prefix, namespace, name) return self.__cache[uri]
def compute_qname(self, uri, generate=True): if not uri in self.__cache: namespace, name = split_uri(uri) namespace = URIRef(namespace) prefix = self.store.prefix(namespace) if prefix is None: if not generate: raise Exception("No known prefix for %s and generate=False") num = 1 while 1: prefix = "ns%s" % num if not self.store.namespace(prefix): break num += 1 self.bind(prefix, namespace) self.__cache[uri] = (prefix, namespace, name) return self.__cache[uri]
https://github.com/RDFLib/rdflib/issues/285
Traceback (most recent call last): File "<string>", line 4, in <module> ... File ".../rdflib/term.py", line 208, in __new__ raise Exception('%s does not look like a valid URI, perhaps you want to urlencode it?'%value) Exception: file:///private/tmp/<stdin> does not look like a valid URI, perhaps you want to urlencode it?
Exception
async def checkData(tweet, location, config, conn): usernames = [] copyright = tweet.find("div", "StreamItemContent--withheld") if copyright is None and is_tweet(tweet): tweet = Tweet(tweet, location, config) if not tweet.datestamp: print("[x] Hidden tweet found, account suspended due to violation of TOS") return if datecheck(tweet.datestamp, config): output = format.Tweet(config, tweet) if config.Database: db.tweets(conn, tweet, config) if config.Pandas: panda.update(tweet, config) if config.Store_object: tweets_object.append(tweet) if config.Elasticsearch: elasticsearch.Tweet(tweet, config) _output(tweet, output, config)
async def checkData(tweet, location, config, conn): usernames = [] user_ids = set() global _duplicate_dict copyright = tweet.find("div", "StreamItemContent--withheld") if copyright is None and is_tweet(tweet): tweet = Tweet(tweet, location, config) if datecheck(tweet.datestamp, config): output = format.Tweet(config, tweet) if config.Database: db.tweets(conn, tweet, config) if config.Pandas: panda.update(tweet, config) if config.Store_object: tweets_object.append(tweet) if config.Elasticsearch: elasticsearch.Tweet(tweet, config) _output(tweet, output, config)
https://github.com/twintproject/twint/issues/321
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.6/dist-packages/twint-1.2.1-py3.6.egg/twint/run.py", line 215, in Search File "/usr/local/lib/python3.6/dist-packages/twint-1.2.1-py3.6.egg/twint/run.py", line 167, in run File "/usr/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete return future.result() File "/usr/local/lib/python3.6/dist-packages/twint-1.2.1-py3.6.egg/twint/run.py", line 154, in main File "/usr/local/lib/python3.6/dist-packages/twint-1.2.1-py3.6.egg/twint/run.py", line 117, in tweets File "/usr/local/lib/python3.6/dist-packages/twint-1.2.1-py3.6.egg/twint/output.py", line 118, in Tweets File "/usr/local/lib/python3.6/dist-packages/twint-1.2.1-py3.6.egg/twint/output.py", line 96, in checkData File "/usr/local/lib/python3.6/dist-packages/twint-1.2.1-py3.6.egg/twint/storage/db.py", line 241, in tweets TypeError: can only join an iterable
TypeError
def _output(obj, output, config, **extra): # logging.info("[<] " + str(datetime.now()) + ':: output+_output') if config.Lowercase: if isinstance(obj, str): obj = obj.lower() elif str(type(obj)) == "<class 'twint.user.user'>": pass else: obj.username = obj.username.lower() for i in range(len(obj.mentions)): obj.mentions[i] = obj.mentions[i]["screen_name"].lower() for i in range(len(obj.hashtags)): obj.hashtags[i] = obj.hashtags[i].lower() if config.Output != None: if config.Store_csv: try: write.Csv(obj, config) except Exception as e: print(str(e) + " [x] output._output") elif config.Store_json: write.Json(obj, config) else: write.Text(output, config.Output) if config.Pandas and obj.type == "user": panda.update(obj, config) if extra.get("follow_list"): follow_object.username = config.Username follow_object.action = ( config.Following * "following" + config.Followers * "followers" ) follow_object.users = _follow_list panda.update(follow_object, config.Essid) if config.Elasticsearch: print("", end=".", flush=True) else: if config.Store_object: tweets_object.append(obj) else: if not config.Hide_output: try: print(output) except UnicodeEncodeError: print("unicode error [x] output._output")
def _output(obj, output, config, **extra): # logging.info("[<] " + str(datetime.now()) + ':: output+_output') if config.Lowercase: if isinstance(obj, str): obj = obj.lower() elif str(type(obj)) == "<class 'twint.user.user'>": pass else: obj.username = obj.username.lower() for i in range(len(obj.mentions)): obj.mentions[i] = obj.mentions[i]["screen_name"].lower() for i in range(len(obj.hashtags)): obj.hashtags[i] = obj.hashtags[i].lower() if config.Output != None: if config.Store_csv: try: write.Csv(obj, config) except Exception as e: print(str(e) + " [x] output._output") elif config.Store_json: write.Json(obj, config) else: write.Text(output, config.Output) if config.Pandas and config.User_full: panda.update(obj, config) if extra.get("follow_list"): follow_object.username = config.Username follow_object.action = ( config.Following * "following" + config.Followers * "followers" ) follow_object.users = _follow_list panda.update(follow_object, config.Essid) if config.Elasticsearch: print("", end=".", flush=True) else: if config.Store_object: tweets_object.append(obj) else: if not config.Hide_output: try: print(output) except UnicodeEncodeError: print("unicode error [x] output._output")
https://github.com/twintproject/twint/issues/283
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. import twint c = twint.Config() query= 'bar' c.Search = query c.Pandas = True twint.run.Search(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> File ".../lib/python3.6/site-packages/twint/run.py", line 201, in Search run(config) File ".../lib/python3.6/site-packages/twint/run.py", line 153, in run get_event_loop().run_until_complete(Twint(config).main()) File ".../lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete return future.result() File ".../lib/python3.6/site-packages/twint/run.py", line 140, in main await self.tweets() File ".../lib/python3.6/site-packages/twint/run.py", line 103, in tweets await output.Tweets(tweet, "", self.config, self.conn) File ".../lib/python3.6/site-packages/twint/output.py", line 161, in Tweets await checkData(tweets, location, config, conn) File ".../lib/python3.6/site-packages/twint/output.py", line 142, in checkData panda.update(tweet, config) File ".../lib/python3.6/site-packages/twint/storage/panda.py", line 61, in update "user_rt": object.user_rt, AttributeError: 'tweet' object has no attribute 'user_rt'
AttributeError
def update(object, config): global _type try: _type = (object.type == "tweet") * "tweet" + (object.type == "user") * "user" except AttributeError: _type = config.Following * "following" + config.Followers * "followers" if _type == "tweet": Tweet = object day = weekdays[strftime("%A", localtime(Tweet.datetime))] dt = f"{object.datestamp} {object.timestamp}" _data = { "id": str(Tweet.id), "conversation_id": Tweet.conversation_id, "created_at": Tweet.datetime, "date": dt, "timezone": Tweet.timezone, "place": Tweet.place, "location": Tweet.location, "tweet": Tweet.tweet, "hashtags": Tweet.hashtags, "user_id": Tweet.user_id, "user_id_str": Tweet.user_id_str, "username": Tweet.username, "name": Tweet.name, "profile_image_url": Tweet.profile_image_url, "day": day, "hour": hour(Tweet.datetime), "link": Tweet.link, "gif_url": Tweet.gif_url, "gif_thumb": Tweet.gif_thumb, "video_url": Tweet.video_url, "video_thumb": Tweet.video_thumb, "is_reply_to": Tweet.is_reply_to, "has_parent_tweet": Tweet.has_parent_tweet, "retweet": Tweet.retweet, "nlikes": int(Tweet.likes_count), "nreplies": int(Tweet.replies_count), "nretweets": int(Tweet.retweets_count), "is_quote_status": Tweet.is_quote_status, "quote_id": Tweet.quote_id, "quote_id_str": Tweet.quote_id_str, "quote_url": Tweet.quote_url, "search": str(config.Search), "near": config.Near, } _object_blocks[_type].append(_data) elif _type == "user": user = object _data = { "id": user.id, "name": user.name, "username": user.username, "bio": user.bio, "location": user.location, "url": user.url, "join_datetime": user.join_date + " " + user.join_time, "join_date": user.join_date, "join_time": user.join_time, "tweets": user.tweets, "following": user.following, "followers": user.followers, "likes": user.likes, "media": user.media_count, "private": user.is_private, "verified": user.is_verified, "avatar": user.avatar, "background_image": user.background_image, } _object_blocks[_type].append(_data) elif _type == "followers" or _type == "following": _data = { config.Following * "following" + config.Followers * "followers": { config.Username: object[_type] } } _object_blocks[_type] = _data else: print("Wrong type of object passed!")
def update(object, config): global _type try: _type = (object.type == "tweet") * "tweet" + (object.type == "user") * "user" except AttributeError: _type = config.Following * "following" + config.Followers * "followers" if _type == "tweet": dt = f"{object.datestamp} {object.timestamp}" _data = { "id": object.id, "date": dt, "timezone": object.timezone, "location": object.location, "tweet": object.tweet, "hashtags": object.hashtags, "user_id": object.user_id, "username": object.username, "link": object.link, "retweet": object.retweet, "user_rt": object.user_rt, "essid": config.Essid, "mentions": object.mentions, } _object_blocks[_type].append(_data) elif _type == "user": _data = { "id": object.id, "name": object.name, "username": object.username, "bio": object.bio, "location": object.location, "url": object.url, "join_datetime": object.join_date + " " + object.join_time, "join_date": object.join_date, "join_time": object.join_time, "tweets": object.tweets, "following": object.following, "followers": object.followers, "likes": object.likes, "media": object.media_count, "private": object.is_private, "verified": object.is_verified, "avatar": object.avatar, "session": str(config.Essid), } _object_blocks[_type].append(_data) elif _type == "followers" or _type == "following": _data = { config.Following * "following" + config.Followers * "followers": { config.Username: object[_type] } } _object_blocks[_type] = _data else: print("Wrong type of object passed!")
https://github.com/twintproject/twint/issues/283
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. import twint c = twint.Config() query= 'bar' c.Search = query c.Pandas = True twint.run.Search(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> File ".../lib/python3.6/site-packages/twint/run.py", line 201, in Search run(config) File ".../lib/python3.6/site-packages/twint/run.py", line 153, in run get_event_loop().run_until_complete(Twint(config).main()) File ".../lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete return future.result() File ".../lib/python3.6/site-packages/twint/run.py", line 140, in main await self.tweets() File ".../lib/python3.6/site-packages/twint/run.py", line 103, in tweets await output.Tweets(tweet, "", self.config, self.conn) File ".../lib/python3.6/site-packages/twint/output.py", line 161, in Tweets await checkData(tweets, location, config, conn) File ".../lib/python3.6/site-packages/twint/output.py", line 142, in checkData panda.update(tweet, config) File ".../lib/python3.6/site-packages/twint/storage/panda.py", line 61, in update "user_rt": object.user_rt, AttributeError: 'tweet' object has no attribute 'user_rt'
AttributeError
def update(Tweet, session): day = weekday(strftime("%A", localtime(Tweet.datetime))) dt = "{} {}".format(Tweet.datestamp, Tweet.timestamp) _data = { "id": Tweet.id, "date": dt, "timezone": Tweet.timezone, "location": Tweet.location, "tweet": Tweet.tweet, "hashtags": Tweet.hashtags, "user_id": Tweet.user_id, "username": Tweet.username, "day": day, "hour": hour(Tweet.datetime), "link": Tweet.link, "retweet": Tweet.retweet, "user_rt": Tweet.user_rt, "essid": str(session), "mentions": Tweet.mentions, } _blocks.append(_data)
def update(Tweet, session): day = weekday(strftime("%A", localtime(Tweet.datetime))) dt = "{} {}".format(Tweet.datestamp, Tweet.timestamp) _data = { "id": Tweet.id, "date": dt, "timezone": Tweet.timezone, "location": Tweet.location, "tweet": Tweet.tweet, "hashtags": Tweet.hashtags, "user_id": Tweet.user_id, "username": Tweet.username, "day": day, "hour": hour(Tweet.datetime), "link": Tweet.link, "retweet": Tweet.retweet, "user_rt": Tweet.user_rt, "essid": str(session), } _blocks.append(_data)
https://github.com/twintproject/twint/issues/152
Traceback (most recent call last): File "/path/to/my/script.py", line 21, in <module> twint.run.Search(c) File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/run.py", line 25, in Search run(search.Search(config).main()) File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/run.py", line 5, in run get_event_loop().run_until_complete(x) File "/anaconda3/envs/twitter_scrape/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete return future.result() File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/search.py", line 49, in main await self.tweets() File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/search.py", line 37, in tweets await output.Tweets(tweet, "", self.config, self.conn) File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/output.py", line 59, in Tweets _output(tweet, output, config) File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/output.py", line 45, in _output print(output) UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 389-389: Non-BMP character not supported in Tk
UnicodeEncodeError
def _output(obj, output, config): if config.Output != None: if config.Store_csv: write.Csv(obj, config) elif config.Store_json: write.Json(obj, config) else: write.Text(output, config.Output) if config.Pandas: Pandas.update(obj, config.Essid) if config.Elasticsearch: if config.Store_object: tweets_object.append(obj) else: print(output, end=".", flush=True) else: if config.Store_object: tweets_object.append(obj) else: try: print(output) except UnicodeEncodeError: pass
def _output(obj, output, config): if config.Output != None: if config.Store_csv: write.Csv(obj, config) elif config.Store_json: write.Json(obj, config) else: write.Text(output, config.Output) if config.Pandas: Pandas.update(obj, config.Essid) if config.Elasticsearch: if config.Store_object: tweets_object.append(obj) else: print(output, end=".", flush=True) else: if config.Store_object: tweets_object.append(obj) else: print(output)
https://github.com/twintproject/twint/issues/152
Traceback (most recent call last): File "/path/to/my/script.py", line 21, in <module> twint.run.Search(c) File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/run.py", line 25, in Search run(search.Search(config).main()) File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/run.py", line 5, in run get_event_loop().run_until_complete(x) File "/anaconda3/envs/twitter_scrape/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete return future.result() File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/search.py", line 49, in main await self.tweets() File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/search.py", line 37, in tweets await output.Tweets(tweet, "", self.config, self.conn) File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/output.py", line 59, in Tweets _output(tweet, output, config) File "/anaconda3/envs/twitter_scrape/lib/python3.6/site-packages/twint/output.py", line 45, in _output print(output) UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 389-389: Non-BMP character not supported in Tk
UnicodeEncodeError
def __str__(self): cls = self.obj.__class__ schema_path = ["{}.{}".format(cls.__module__, cls.__name__)] schema_path.extend(self.schema_path) schema_path = "->".join( str(val) for val in schema_path[:-1] if val not in ("properties", "additionalProperties", "patternProperties") ) return """Invalid specification {}, validating {!r} {} """.format(schema_path, self.validator, self.message)
def __str__(self): cls = self.obj.__class__ schema_path = ["{}.{}".format(cls.__module__, cls.__name__)] schema_path.extend(self.schema_path) schema_path = "->".join( val for val in schema_path[:-1] if val not in ("properties", "additionalProperties", "patternProperties") ) return """Invalid specification {}, validating {!r} {} """.format(schema_path, self.validator, self.message)
https://github.com/altair-viz/altair/issues/1935
$ cat test.py import pandas, altair d = [{'WijkenEnBuurten': 'Nederland', 'Codering_3': 'NL00', 'Mannen_6': 8475102, 'Vrouwen_7': 8606405, 'SoortRegio_2': 'Land ', 'GeboorteRelatief_25': 9}, {'WijkenEnBuurten': 'Aa en Hunze', 'Codering_3': 'GM1680', 'Mannen_6': 12603, 'Vrouwen_7': 12683, 'SoortRegio_2': 'Gemeente ', 'GeboorteRelatief_25': 6}] df = pandas.DataFrame(d) a = altair.Data(df) $ python ./test.py Traceback (most recent call last): File "./t_altair_schema.py", line 5, in <module> a = altair.Data(df) File "/home/paulm/.local/lib/python3.8/site-packages/altair/vegalite/v3/schema/core.py", line 3741, in __init__ super(Data, self).__init__(*args, **kwds) File "/home/paulm/.local/lib/python3.8/site-packages/altair/utils/schemapi.py", line 154, in __init__ self.to_dict(validate=True) File "/home/paulm/.local/lib/python3.8/site-packages/altair/utils/schemapi.py", line 302, in to_dict raise SchemaValidationError(self, err) altair.utils.schemapi.SchemaValidationError: <exception str() failed>
altair.utils.schemapi.SchemaValidationError
def __getattr__(self, attr): # reminder: getattr is called after the normal lookups if attr == "_kwds": raise AttributeError() if attr in self._kwds: return self._kwds[attr] else: try: _getattr = super(SchemaBase, self).__getattr__ except AttributeError: _getattr = super(SchemaBase, self).__getattribute__ return _getattr(attr)
def __getattr__(self, attr): # reminder: getattr is called after the normal lookups if attr in self._kwds: return self._kwds[attr] else: try: _getattr = super(SchemaBase, self).__getattr__ except AttributeError: _getattr = super(SchemaBase, self).__getattribute__ return _getattr(attr)
https://github.com/altair-viz/altair/issues/1681
(py36) C:\Develop\plab>python sandbox\test_altair_pickle.py Traceback (most recent call last): File "sandbox\test_altair_pickle.py", line 15, in <module> pch = pickle.load(fid) File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__ if attr in self._kwds: File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__ if attr in self._kwds: File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__ if attr in self._kwds: [Previous line repeated 330 more times] RecursionError: maximum recursion depth exceeded while calling a Python object ```
RecursionError
def _subclasses(cls): """Breadth-first sequence of all classes which inherit from cls.""" seen = set() current_set = {cls} while current_set: seen |= current_set current_set = set.union(*(set(cls.__subclasses__()) for cls in current_set)) for cls in current_set - seen: yield cls
def _subclasses(cls): """Breadth-first sequence of classes which inherit from cls.""" seen = set() current_set = {cls} while current_set: seen |= current_set current_set = set.union(*(set(cls.__subclasses__()) for cls in current_set)) for cls in current_set - seen: yield cls
https://github.com/altair-viz/altair/issues/1681
(py36) C:\Develop\plab>python sandbox\test_altair_pickle.py Traceback (most recent call last): File "sandbox\test_altair_pickle.py", line 15, in <module> pch = pickle.load(fid) File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__ if attr in self._kwds: File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__ if attr in self._kwds: File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__ if attr in self._kwds: [Previous line repeated 330 more times] RecursionError: maximum recursion depth exceeded while calling a Python object ```
RecursionError
def from_dict(self, dct, cls=None, schema=None, rootschema=None): """Construct an object from a dict representation""" if (schema is None) == (cls is None): raise ValueError("Must provide either cls or schema, but not both.") if schema is None: schema = schema or cls._schema rootschema = rootschema or cls._rootschema rootschema = rootschema or schema def _passthrough(*args, **kwds): return args[0] if args else kwds if cls is None: # If there are multiple matches, we use the last one in the dict. # Our class dict is constructed breadth-first from top to bottom, # so the last class that matches is the most specific. matches = self.class_dict[self.hash_schema(schema)] cls = matches[-1] if matches else _passthrough schema = _resolve_references(schema, rootschema) if "anyOf" in schema or "oneOf" in schema: schemas = schema.get("anyOf", []) + schema.get("oneOf", []) for possible_schema in schemas: resolver = jsonschema.RefResolver.from_schema(rootschema) try: jsonschema.validate(dct, possible_schema, resolver=resolver) except jsonschema.ValidationError: continue else: return self.from_dict( dct, schema=possible_schema, rootschema=rootschema, ) if isinstance(dct, dict): # TODO: handle schemas for additionalProperties/patternProperties props = schema.get("properties", {}) kwds = {} for key, val in dct.items(): if key in props: val = self.from_dict(val, schema=props[key], rootschema=rootschema) kwds[key] = val return cls(**kwds) elif isinstance(dct, list): item_schema = schema.get("items", {}) dct = [ self.from_dict(val, schema=item_schema, rootschema=rootschema) for val in dct ] return cls(dct) else: return cls(dct)
def from_dict(self, dct, cls=None, schema=None, rootschema=None): """Construct an object from a dict representation""" if (schema is None) == (cls is None): raise ValueError("Must provide either cls or schema, but not both.") if schema is None: schema = schema or cls._schema rootschema = rootschema or cls._rootschema rootschema = rootschema or schema def _passthrough(*args, **kwds): return args[0] if args else kwds if cls is None: # TODO: do something more than simply selecting the last match? matches = self.class_dict[self.hash_schema(schema)] cls = matches[-1] if matches else _passthrough schema = _resolve_references(schema, rootschema) if "anyOf" in schema or "oneOf" in schema: schemas = schema.get("anyOf", []) + schema.get("oneOf", []) for possible_schema in schemas: resolver = jsonschema.RefResolver.from_schema(rootschema) try: jsonschema.validate(dct, possible_schema, resolver=resolver) except jsonschema.ValidationError: continue else: return self.from_dict( dct, schema=possible_schema, rootschema=rootschema, ) if isinstance(dct, dict): # TODO: handle schemas for additionalProperties/patternProperties props = schema.get("properties", {}) kwds = {} for key, val in dct.items(): if key in props: val = self.from_dict(val, schema=props[key], rootschema=rootschema) kwds[key] = val return cls(**kwds) elif isinstance(dct, list): item_schema = schema.get("items", {}) dct = [ self.from_dict(val, schema=item_schema, rootschema=rootschema) for val in dct ] return cls(dct) else: return cls(dct)
https://github.com/altair-viz/altair/issues/1681
(py36) C:\Develop\plab>python sandbox\test_altair_pickle.py Traceback (most recent call last): File "sandbox\test_altair_pickle.py", line 15, in <module> pch = pickle.load(fid) File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__ if attr in self._kwds: File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__ if attr in self._kwds: File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__ if attr in self._kwds: [Previous line repeated 330 more times] RecursionError: maximum recursion depth exceeded while calling a Python object ```
RecursionError
def transform_joinaggregate(self, joinaggregate=Undefined, groupby=Undefined, **kwargs): """ Add a JoinAggregateTransform to the schema. Parameters ---------- joinaggregate : List(:class:`JoinAggregateFieldDef`) The definition of the fields in the join aggregate, and what calculations to use. groupby : List(string) The data fields for partitioning the data objects into separate groups. If unspecified, all data points will be in a single group. **kwargs joinaggregates can also be passed by keyword argument; see Examples. Returns ------- self : Chart object returns chart to allow for chaining Examples -------- >>> import altair as alt >>> chart = alt.Chart().transform_joinaggregate(x='sum(y)') >>> chart.transform[0] JoinAggregateTransform({ joinaggregate: [JoinAggregateFieldDef({ as: 'x', field: 'y', op: 'sum' })] }) See Also -------- alt.JoinAggregateTransform : underlying transform object """ if joinaggregate is Undefined: joinaggregate = [] for key, val in kwargs.items(): parsed = utils.parse_shorthand(val) dct = { "as": key, "field": parsed.get("field", Undefined), "op": parsed.get("aggregate", Undefined), } joinaggregate.append(core.JoinAggregateFieldDef(**dct)) return self._add_transform( core.JoinAggregateTransform(joinaggregate=joinaggregate, groupby=groupby) )
def transform_joinaggregate(self, joinaggregate=Undefined, groupby=Undefined, **kwargs): """ Add a JoinAggregateTransform to the schema. Parameters ---------- joinaggregate : List(:class:`JoinAggregateFieldDef`) The definition of the fields in the join aggregate, and what calculations to use. groupby : List(string) The data fields for partitioning the data objects into separate groups. If unspecified, all data points will be in a single group. **kwargs joinaggregates can also be passed by keyword argument; see Examples. Returns ------- self : Chart object returns chart to allow for chaining Examples -------- >>> import altair as alt >>> chart = alt.Chart().transform_joinaggregate(x='sum(y)') >>> chart.transform[0] JoinAggregateTransform({ joinaggregate: [JoinAggregateFieldDef({ as: FieldName('x'), field: FieldName('y'), op: AggregateOp('sum') })] }) See Also -------- alt.JoinAggregateTransform : underlying transform object """ if joinaggregate is Undefined: joinaggregate = [] for key, val in kwargs.items(): parsed = utils.parse_shorthand(val) dct = { "as": key, "field": parsed.get("field", Undefined), "op": parsed.get("aggregate", Undefined), } joinaggregate.append(core.JoinAggregateFieldDef.from_dict(dct)) return self._add_transform( core.JoinAggregateTransform(joinaggregate=joinaggregate, groupby=groupby) )
https://github.com/altair-viz/altair/issues/1750
--------------------------------------------------------------------------- ValidationError Traceback (most recent call last) <ipython-input-142-2bf583dd0be9> in <module>() 5 ).transform_joinaggregate( 6 group_count='count()', ----> 7 groupby=['group'] 8 ).transform_calculate( 9 normalized_a="datum.a / datum.group_count", ~/.virtualenvs/simulate/lib/python3.6/site-packages/altair/vegalite/v3/api.py in transform_joinaggregate(self, joinaggregate, groupby, **kwargs) 929 'field': parsed.get('field', Undefined), 930 'op': parsed.get('aggregate', Undefined)} --> 931 joinaggregate.append(core.JoinAggregateFieldDef.from_dict(dct)) 932 return self._add_transform(core.JoinAggregateTransform( 933 joinaggregate=joinaggregate, groupby=groupby ~/.virtualenvs/simulate/lib/python3.6/site-packages/altair/utils/schemapi.py in from_dict(cls, dct, validate, _wrapper_classes) 366 """ 367 if validate: --> 368 cls.validate(dct) 369 if _wrapper_classes is None: 370 _wrapper_classes = cls._default_wrapper_classes() ~/.virtualenvs/simulate/lib/python3.6/site-packages/altair/utils/schemapi.py in validate(cls, instance, schema) 402 schema = cls._schema 403 resolver = jsonschema.RefResolver.from_schema(cls._rootschema or cls._schema) --> 404 return jsonschema.validate(instance, schema, resolver=resolver) 405 406 @classmethod ~/.virtualenvs/simulate/lib/python3.6/site-packages/jsonschema/validators.py in validate(instance, schema, cls, *args, **kwargs) 897 error = exceptions.best_match(validator.iter_errors(instance)) 898 if error is not None: --> 899 raise error 900 901 ValidationError: Undefined is not of type 'string' Failed validating 'type' in schema['properties']['field']: {'type': 'string'} On instance['field']: Undefined
ValidationError
def spec_to_image_mimebundle( spec, format, mode, vega_version, vegaembed_version, vegalite_version=None, driver_timeout=10, ): """Conver a vega/vega-lite specification to a PNG/SVG image Parameters ---------- spec : dict a dictionary representing a vega-lite plot spec format : string {'png' | 'svg'} the file format to be saved. mode : string {'vega' | 'vega-lite'} The rendering mode. vega_version : string For html output, the version of vega.js to use vegalite_version : string For html output, the version of vegalite.js to use vegaembed_version : string For html output, the version of vegaembed.js to use driver_timeout : int (optional) the number of seconds to wait for page load before raising an error (default: 10) Returns ------- output : dict a mime-bundle representing the image Note ---- This requires the pillow, selenium, and chrome headless packages to be installed. """ # TODO: allow package versions to be specified # TODO: detect & use local Jupyter caches of JS packages? if format not in ["png", "svg"]: raise NotImplementedError("format must be 'svg' and 'png'") if mode not in ["vega", "vega-lite"]: raise ValueError("mode must be 'vega' or 'vega-lite'") if mode == "vega-lite" and vegalite_version is None: raise ValueError("must specify vega-lite version") if webdriver is None: raise ImportError( "selenium package is required for saving chart as {0}".format(format) ) if ChromeOptions is None: raise ImportError( "chromedriver is required for saving chart as {0}".format(format) ) html = HTML_TEMPLATE.format( vega_version=vega_version, vegalite_version=vegalite_version, vegaembed_version=vegaembed_version, ) try: chrome_options = ChromeOptions() chrome_options.add_argument("--headless") if os.geteuid() == 0: chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(chrome_options=chrome_options) driver.set_page_load_timeout(driver_timeout) with temporary_filename(suffix=".html") as htmlfile: with open(htmlfile, "w") as f: f.write(html) driver.get("file://" + htmlfile) online = driver.execute_script("return navigator.onLine") if not online: raise ValueError( "Internet connection required for saving chart as {0}".format( format ) ) render = driver.execute_async_script(EXTRACT_CODE[format], spec, mode) finally: driver.close() if format == "png": return {"image/png": base64.decodebytes(render.split(",", 1)[1].encode())} elif format == "svg": return {"image/svg+xml": render}
def spec_to_image_mimebundle( spec, format, mode, vega_version, vegaembed_version, vegalite_version=None, driver_timeout=10, ): """Conver a vega/vega-lite specification to a PNG/SVG image Parameters ---------- spec : dict a dictionary representing a vega-lite plot spec format : string {'png' | 'svg'} the file format to be saved. mode : string {'vega' | 'vega-lite'} The rendering mode. vega_version : string For html output, the version of vega.js to use vegalite_version : string For html output, the version of vegalite.js to use vegaembed_version : string For html output, the version of vegaembed.js to use driver_timeout : int (optional) the number of seconds to wait for page load before raising an error (default: 10) Returns ------- output : dict a mime-bundle representing the image Note ---- This requires the pillow, selenium, and chrome headless packages to be installed. """ # TODO: allow package versions to be specified # TODO: detect & use local Jupyter caches of JS packages? if format not in ["png", "svg"]: raise NotImplementedError("format must be 'svg' and 'png'") if mode not in ["vega", "vega-lite"]: raise ValueError("mode must be 'vega' or 'vega-lite'") if mode == "vega-lite" and vegalite_version is None: raise ValueError("must specify vega-lite version") if webdriver is None: raise ImportError( "selenium package is required for saving chart as {0}".format(format) ) if ChromeOptions is None: raise ImportError( "chromedriver is required for saving chart as {0}".format(format) ) html = HTML_TEMPLATE.format( vega_version=vega_version, vegalite_version=vegalite_version, vegaembed_version=vegaembed_version, ) try: chrome_options = ChromeOptions() chrome_options.add_argument("--headless") if os.geteuid() == 0: chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(chrome_options=chrome_options) driver.set_page_load_timeout(driver_timeout) try: fd, htmlfile = tempfile.mkstemp(suffix=".html", text=True) with open(htmlfile, "w") as f: f.write(html) driver.get("file://" + htmlfile) online = driver.execute_script("return navigator.onLine") if not online: raise ValueError( "Internet connection required for saving chart as {0}".format( format ) ) render = driver.execute_async_script(EXTRACT_CODE[format], spec, mode) finally: os.remove(htmlfile) finally: driver.close() if format == "png": return {"image/png": base64.decodebytes(render.split(",", 1)[1].encode())} elif format == "svg": return {"image/svg+xml": render}
https://github.com/altair-viz/altair/issues/649
--------------------------------------------------------------------------- PermissionError Traceback (most recent call last) <ipython-input-16-c16ecf6573c1> in <module>() ----> 1 chart.savechart('test.png') G:\Software\Anaconda2\envs\py36\lib\site-packages\altair\vegalite\v2\api.py in savechart(self, fp, format, **kwargs) 331 utils.write_file_or_filename(fp, spec_html, mode='w') 332 elif format in ['png', 'svg']: --> 333 utils.save_spec(self.to_dict(), fp, format=format, **kwargs) 334 else: 335 raise ValueError("unrecognized format: '{0}'".format(format)) G:\Software\Anaconda2\envs\py36\lib\site-packages\altair\utils\headless.py in save_spec(spec, fp, mode, format, driver_timeout) 136 spec, mode) 137 finally: --> 138 os.remove(htmlfile) 139 finally: 140 driver.close() PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\PAGPI_~1\\AppData\\Local\\Temp\\tmpbyp9uhvp.html'
PermissionError
def spec_to_image_mimebundle( spec, format, mode, vega_version, vegaembed_version, vegalite_version=None, driver_timeout=10, ): """Conver a vega/vega-lite specification to a PNG/SVG image Parameters ---------- spec : dict a dictionary representing a vega-lite plot spec format : string {'png' | 'svg'} the file format to be saved. mode : string {'vega' | 'vega-lite'} The rendering mode. vega_version : string For html output, the version of vega.js to use vegalite_version : string For html output, the version of vegalite.js to use vegaembed_version : string For html output, the version of vegaembed.js to use driver_timeout : int (optional) the number of seconds to wait for page load before raising an error (default: 10) Returns ------- output : dict a mime-bundle representing the image Note ---- This requires the pillow, selenium, and chrome headless packages to be installed. """ # TODO: allow package versions to be specified # TODO: detect & use local Jupyter caches of JS packages? if format not in ["png", "svg"]: raise NotImplementedError("format must be 'svg' and 'png'") if mode not in ["vega", "vega-lite"]: raise ValueError("mode must be 'vega' or 'vega-lite'") if mode == "vega-lite" and vegalite_version is None: raise ValueError("must specify vega-lite version") if webdriver is None: raise ImportError( "selenium package is required for saving chart as {0}".format(format) ) if ChromeOptions is None: raise ImportError( "chromedriver is required for saving chart as {0}".format(format) ) html = HTML_TEMPLATE.format( vega_version=vega_version, vegalite_version=vegalite_version, vegaembed_version=vegaembed_version, ) chrome_options = ChromeOptions() chrome_options.add_argument("--headless") # for linux/osx root user, need to add --no-sandbox option. # since geteuid doesn't exist on windows, we don't check it if hasattr(os, "geteuid") and (os.geteuid() == 0): chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(chrome_options=chrome_options) try: driver.set_page_load_timeout(driver_timeout) with temporary_filename(suffix=".html") as htmlfile: with open(htmlfile, "w") as f: f.write(html) driver.get("file://" + htmlfile) online = driver.execute_script("return navigator.onLine") if not online: raise ValueError( "Internet connection required for saving chart as {0}".format( format ) ) render = driver.execute_async_script(EXTRACT_CODE[format], spec, mode) finally: driver.close() if format == "png": return {"image/png": base64.decodebytes(render.split(",", 1)[1].encode())} elif format == "svg": return {"image/svg+xml": render}
def spec_to_image_mimebundle( spec, format, mode, vega_version, vegaembed_version, vegalite_version=None, driver_timeout=10, ): """Conver a vega/vega-lite specification to a PNG/SVG image Parameters ---------- spec : dict a dictionary representing a vega-lite plot spec format : string {'png' | 'svg'} the file format to be saved. mode : string {'vega' | 'vega-lite'} The rendering mode. vega_version : string For html output, the version of vega.js to use vegalite_version : string For html output, the version of vegalite.js to use vegaembed_version : string For html output, the version of vegaembed.js to use driver_timeout : int (optional) the number of seconds to wait for page load before raising an error (default: 10) Returns ------- output : dict a mime-bundle representing the image Note ---- This requires the pillow, selenium, and chrome headless packages to be installed. """ # TODO: allow package versions to be specified # TODO: detect & use local Jupyter caches of JS packages? if format not in ["png", "svg"]: raise NotImplementedError("format must be 'svg' and 'png'") if mode not in ["vega", "vega-lite"]: raise ValueError("mode must be 'vega' or 'vega-lite'") if mode == "vega-lite" and vegalite_version is None: raise ValueError("must specify vega-lite version") if webdriver is None: raise ImportError( "selenium package is required for saving chart as {0}".format(format) ) if ChromeOptions is None: raise ImportError( "chromedriver is required for saving chart as {0}".format(format) ) html = HTML_TEMPLATE.format( vega_version=vega_version, vegalite_version=vegalite_version, vegaembed_version=vegaembed_version, ) try: chrome_options = ChromeOptions() chrome_options.add_argument("--headless") if os.geteuid() == 0: chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(chrome_options=chrome_options) driver.set_page_load_timeout(driver_timeout) with temporary_filename(suffix=".html") as htmlfile: with open(htmlfile, "w") as f: f.write(html) driver.get("file://" + htmlfile) online = driver.execute_script("return navigator.onLine") if not online: raise ValueError( "Internet connection required for saving chart as {0}".format( format ) ) render = driver.execute_async_script(EXTRACT_CODE[format], spec, mode) finally: driver.close() if format == "png": return {"image/png": base64.decodebytes(render.split(",", 1)[1].encode())} elif format == "svg": return {"image/svg+xml": render}
https://github.com/altair-viz/altair/issues/649
--------------------------------------------------------------------------- PermissionError Traceback (most recent call last) <ipython-input-16-c16ecf6573c1> in <module>() ----> 1 chart.savechart('test.png') G:\Software\Anaconda2\envs\py36\lib\site-packages\altair\vegalite\v2\api.py in savechart(self, fp, format, **kwargs) 331 utils.write_file_or_filename(fp, spec_html, mode='w') 332 elif format in ['png', 'svg']: --> 333 utils.save_spec(self.to_dict(), fp, format=format, **kwargs) 334 else: 335 raise ValueError("unrecognized format: '{0}'".format(format)) G:\Software\Anaconda2\envs\py36\lib\site-packages\altair\utils\headless.py in save_spec(spec, fp, mode, format, driver_timeout) 136 spec, mode) 137 finally: --> 138 os.remove(htmlfile) 139 finally: 140 driver.close() PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\PAGPI_~1\\AppData\\Local\\Temp\\tmpbyp9uhvp.html'
PermissionError
async def async_setup_frontend(): """Configure the HACS frontend elements.""" hacs = get_hacs() hacs.log.info("Setup task %s", HacsSetupTask.FRONTEND) # Custom view hacs.hass.http.register_view(HacsFrontend()) # Custom iconset if "frontend_extra_module_url" not in hacs.hass.data: hacs.hass.data["frontend_extra_module_url"] = set() hacs.hass.data["frontend_extra_module_url"].add("/hacsfiles/iconset.js") hacs.frontend.version_running = FE_VERSION hacs.frontend.version_expected = await hacs.hass.async_add_executor_job( get_frontend_version ) # Add to sidepanel if "hacs" not in hacs.hass.data.get("frontend_panels", {}): custom_panel_config = { "name": "hacs-frontend", "embed_iframe": True, "trust_external": False, "js_url": "/hacsfiles/frontend/entrypoint.js", } config = {} config["_panel_custom"] = custom_panel_config hacs.hass.components.frontend.async_register_built_in_panel( component_name="custom", sidebar_title=hacs.configuration.sidepanel_title, sidebar_icon=hacs.configuration.sidepanel_icon, frontend_url_path="hacs", config=config, require_admin=True, )
async def async_setup_frontend(): """Configure the HACS frontend elements.""" hacs = get_hacs() hacs.log.info("Setup task %s", HacsSetupTask.FRONTEND) # Custom view hacs.hass.http.register_view(HacsFrontend()) # Custom iconset if "frontend_extra_module_url" not in hacs.hass.data: hacs.hass.data["frontend_extra_module_url"] = set() hacs.hass.data["frontend_extra_module_url"].add("/hacsfiles/iconset.js") hacs.frontend.version_running = FE_VERSION hacs.frontend.version_expected = await hacs.hass.async_add_executor_job( get_frontend_version ) # Add to sidepanel custom_panel_config = { "name": "hacs-frontend", "embed_iframe": True, "trust_external": False, "js_url": "/hacsfiles/frontend/entrypoint.js", } config = {} config["_panel_custom"] = custom_panel_config hacs.hass.components.frontend.async_register_built_in_panel( component_name="custom", sidebar_title=hacs.configuration.sidepanel_title, sidebar_icon=hacs.configuration.sidepanel_icon, frontend_url_path="hacs", config=config, require_admin=True, )
https://github.com/hacs/integration/issues/1605
2020-10-27 16:42:22 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry for hacs Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/config_entries.py", line 234, in async_setup result = await component.async_setup_entry(hass, self) # type: ignore File "/config/custom_components/hacs/__init__.py", line 30, in async_setup_entry return await hacs_ui_setup(hass, config_entry) File "/config/custom_components/hacs/operational/setup.py", line 63, in async_setup_entry return await async_startup_wrapper_for_config_entry() File "/config/custom_components/hacs/operational/setup.py", line 88, in async_startup_wrapper_for_config_entry startup_result = await async_hacs_startup() File "/config/custom_components/hacs/operational/setup.py", line 133, in async_hacs_startup await async_setup_frontend() File "/config/custom_components/hacs/operational/setup_actions/frontend.py", line 38, in async_setup_frontend hacs.hass.components.frontend.async_register_built_in_panel( File "/usr/src/homeassistant/homeassistant/components/frontend/__init__.py", line 196, in async_register_built_in_panel raise ValueError(f"Overwriting panel {panel.frontend_url_path}") ValueError: Overwriting panel hacs
ValueError
def create_window( title, url=None, js_api=None, width=800, height=600, resizable=True, fullscreen=False, min_size=(200, 100), strings={}, confirm_quit=False, background_color="#FFFFFF", text_select=False, debug=False, ): """ Create a web view window using a native GUI. The execution blocks after this function is invoked, so other program logic must be executed in a separate thread. :param title: Window title :param url: URL to load :param width: window width. Default is 800px :param height:window height. Default is 600px :param resizable True if window can be resized, False otherwise. Default is True :param fullscreen: True if start in fullscreen mode. Default is False :param min_size: a (width, height) tuple that specifies a minimum window size. Default is 200x100 :param strings: a dictionary with localized strings :param confirm_quit: Display a quit confirmation dialog. Default is False :param background_color: Background color as a hex string that is displayed before the content of webview is loaded. Default is white. :param text_select: Allow text selection on page. Default is False. :return: The uid of the created window. """ valid_color = r"^#(?:[0-9a-fA-F]{3}){1,2}$" if not re.match(valid_color, background_color): raise ValueError( "{0} is not a valid hex triplet color".format(background_color) ) # Check if starting up from main thread; if not, wait; finally raise exception if current_thread().name == "MainThread": uid = "master" if not _initialized: _initialize_imports() localization.update(strings) else: uid = "child_" + uuid4().hex[:8] if not _webview_ready.wait(5): raise Exception( "Call create_window from the main thread first, and then from subthreads" ) _webview_ready.clear() # Make API calls wait while the new window is created gui.create_window( uid, make_unicode(title), transform_url(url), width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, _webview_ready, ) return uid
def create_window( title, url=None, js_api=None, width=800, height=600, resizable=True, fullscreen=False, min_size=(200, 100), strings={}, confirm_quit=False, background_color="#FFFFFF", text_select=False, debug=False, ): """ Create a web view window using a native GUI. The execution blocks after this function is invoked, so other program logic must be executed in a separate thread. :param title: Window title :param url: URL to load :param width: window width. Default is 800px :param height:window height. Default is 600px :param resizable True if window can be resized, False otherwise. Default is True :param fullscreen: True if start in fullscreen mode. Default is False :param min_size: a (width, height) tuple that specifies a minimum window size. Default is 200x100 :param strings: a dictionary with localized strings :param confirm_quit: Display a quit confirmation dialog. Default is False :param background_color: Background color as a hex string that is displayed before the content of webview is loaded. Default is white. :param text_select: Allow text selection on page. Default is False. :return: The uid of the created window. """ uid = "child_" + uuid4().hex[:8] valid_color = r"^#(?:[0-9a-fA-F]{3}){1,2}$" if not re.match(valid_color, background_color): raise ValueError( "{0} is not a valid hex triplet color".format(background_color) ) if not _initialized: # Check if starting up from main thread; if not, wait; finally raise exception if current_thread().name != "MainThread": if not _webview_ready.wait(5): raise Exception( "Call create_window from the main thread first, and then from subthreads" ) else: _initialize_imports() localization.update(strings) uid = "master" _webview_ready.clear() # Make API calls wait while the new window is created gui.create_window( uid, make_unicode(title), transform_url(url), width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, _webview_ready, ) return uid
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def windowWillClose_(self, notification): # Delete the closed instance from the dict i = BrowserView.get_instance("window", notification.object()) del BrowserView.instances[i.uid] if BrowserView.instances == {}: AppHelper.callAfter(BrowserView.app.stop_, self)
def windowWillClose_(self, notification): # Delete the closed instance from the dict i = BrowserView.get_instance("window", notification.object()) del BrowserView.instances[i.uid]
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def webView_didFinishLoadForFrame_(self, webview, frame): # Add the webview to the window if it's not yet the contentView i = BrowserView.get_instance("webkit", webview) if i and not webview.window(): i.window.setContentView_(webview) i.window.makeFirstResponder_(webview) if i.js_bridge: i._set_js_api() if not i.text_select: i.webkit.windowScriptObject().evaluateWebScript_(disable_text_select) i.loaded.set()
def webView_didFinishLoadForFrame_(self, webview, frame): # Add the webview to the window if it's not yet the contentView i = BrowserView.get_instance("webkit", webview) if not webview.window(): i.window.setContentView_(webview) i.window.makeFirstResponder_(webview) if i.js_bridge: i._set_js_api() if not i.text_select: i.webkit.windowScriptObject().evaluateWebScript_(disable_text_select) i.loaded.set()
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def performKeyEquivalent_(self, theEvent): """ Handle common hotkey shortcuts as copy/cut/paste/undo/select all/quit :param theEvent: :return: """ if ( theEvent.type() == AppKit.NSKeyDown and theEvent.modifierFlags() & AppKit.NSCommandKeyMask ): responder = self.window().firstResponder() keyCode = theEvent.keyCode() if responder != None: handled = False range_ = responder.selectedRange() hasSelectedText = len(range_) > 0 if keyCode == 7 and hasSelectedText: # cut responder.cut_(self) handled = True elif keyCode == 8 and hasSelectedText: # copy responder.copy_(self) handled = True elif keyCode == 9: # paste responder.paste_(self) handled = True elif keyCode == 0: # select all responder.selectAll_(self) handled = True elif keyCode == 6: # undo if responder.undoManager().canUndo(): responder.undoManager().undo() handled = True elif keyCode == 12: # quit BrowserView.app.stop_(self) return handled
def performKeyEquivalent_(self, theEvent): """ Handle common hotkey shortcuts as copy/cut/paste/undo/select all/quit :param theEvent: :return: """ if ( theEvent.type() == AppKit.NSKeyDown and theEvent.modifierFlags() & AppKit.NSCommandKeyMask ): responder = self.window().firstResponder() keyCode = theEvent.keyCode() if responder != None: handled = False range_ = responder.selectedRange() hasSelectedText = len(range_) > 0 if keyCode == 7 and hasSelectedText: # cut responder.cut_(self) handled = True elif keyCode == 8 and hasSelectedText: # copy responder.copy_(self) handled = True elif keyCode == 9: # paste responder.paste_(self) handled = True elif keyCode == 0: # select all responder.selectAll_(self) handled = True elif keyCode == 6: # undo if responder.undoManager().canUndo(): responder.undoManager().undo() handled = True elif keyCode == 12: # quit BrowserView.app.terminate_(self) return handled
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def __init__( self, uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready, ): BrowserView.instances[uid] = self self.uid = uid if debug: BrowserView.debug = debug BrowserView._set_debugging() self.js_bridge = None self._file_name = None self._file_name_semaphore = Semaphore(0) self._current_url_semaphore = Semaphore(0) self.webview_ready = webview_ready self.loaded = Event() self.confirm_quit = confirm_quit self.title = title self.text_select = text_select self.is_fullscreen = False rect = AppKit.NSMakeRect(0.0, 0.0, width, height) window_mask = ( AppKit.NSTitledWindowMask | AppKit.NSClosableWindowMask | AppKit.NSMiniaturizableWindowMask ) if resizable: window_mask = window_mask | AppKit.NSResizableWindowMask # The allocated resources are retained because we would explicitly delete # this instance when its window is closed self.window = ( AppKit.NSWindow.alloc() .initWithContentRect_styleMask_backing_defer_( rect, window_mask, AppKit.NSBackingStoreBuffered, False ) .retain() ) self.window.setTitle_(title) self.window.setBackgroundColor_(BrowserView.nscolor_from_hex(background_color)) self.window.setMinSize_(AppKit.NSSize(min_size[0], min_size[1])) self.window.setAnimationBehavior_(AppKit.NSWindowAnimationBehaviorDocumentWindow) BrowserView.cascade_loc = self.window.cascadeTopLeftFromPoint_( BrowserView.cascade_loc ) # Set the titlebar color (so that it does not change with the window color) self.window.contentView().superview().subviews().lastObject().setBackgroundColor_( AppKit.NSColor.windowBackgroundColor() ) self.webkit = BrowserView.WebKitHost.alloc().initWithFrame_(rect).retain() self._browserDelegate = BrowserView.BrowserDelegate.alloc().init().retain() self._windowDelegate = BrowserView.WindowDelegate.alloc().init().retain() self._appDelegate = BrowserView.AppDelegate.alloc().init().retain() self.webkit.setUIDelegate_(self._browserDelegate) self.webkit.setFrameLoadDelegate_(self._browserDelegate) self.webkit.setPolicyDelegate_(self._browserDelegate) self.window.setDelegate_(self._windowDelegate) BrowserView.app.setDelegate_(self._appDelegate) if url: self.url = url self.load_url(url) else: self.loaded.set() if js_api: self.js_bridge = BrowserView.JSBridge.alloc().initWithObject_(js_api) if fullscreen: self.toggle_fullscreen()
def __init__( self, uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready, ): BrowserView.instances[uid] = self self.uid = uid if debug: BrowserView.debug = debug BrowserView._set_debugging() self.js_bridge = None self._file_name = None self._file_name_semaphore = Semaphore(0) self._current_url_semaphore = Semaphore(0) self.webview_ready = webview_ready self.loaded = Event() self.confirm_quit = confirm_quit self.title = title self.text_select = text_select self.is_fullscreen = False rect = AppKit.NSMakeRect(0.0, 0.0, width, height) window_mask = ( AppKit.NSTitledWindowMask | AppKit.NSClosableWindowMask | AppKit.NSMiniaturizableWindowMask ) if resizable: window_mask = window_mask | AppKit.NSResizableWindowMask # The allocated resources are retained because we would explicitly delete # this instance when its window is closed self.window = ( AppKit.NSWindow.alloc() .initWithContentRect_styleMask_backing_defer_( rect, window_mask, AppKit.NSBackingStoreBuffered, False ) .retain() ) self.window.setTitle_(title) self.window.setBackgroundColor_(BrowserView.nscolor_from_hex(background_color)) self.window.setMinSize_(AppKit.NSSize(min_size[0], min_size[1])) BrowserView.cascade_loc = self.window.cascadeTopLeftFromPoint_( BrowserView.cascade_loc ) # Set the titlebar color (so that it does not change with the window color) self.window.contentView().superview().subviews().lastObject().setBackgroundColor_( AppKit.NSColor.windowBackgroundColor() ) self.webkit = BrowserView.WebKitHost.alloc().initWithFrame_(rect).retain() self._browserDelegate = BrowserView.BrowserDelegate.alloc().init().retain() self._windowDelegate = BrowserView.WindowDelegate.alloc().init().retain() self._appDelegate = BrowserView.AppDelegate.alloc().init().retain() self.webkit.setUIDelegate_(self._browserDelegate) self.webkit.setFrameLoadDelegate_(self._browserDelegate) self.webkit.setPolicyDelegate_(self._browserDelegate) self.window.setDelegate_(self._windowDelegate) BrowserView.app.setDelegate_(self._appDelegate) if url: self.url = url self.load_url(url) else: self.loaded.set() if js_api: self.js_bridge = BrowserView.JSBridge.alloc().initWithObject_(js_api) if fullscreen: self.toggle_fullscreen()
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def on_inspect_webview(self, inspector, webview): title = "Web Inspector - {}".format(self.window.get_title()) uid = self.uid + "-inspector" inspector = BrowserView( uid, title, "", 700, 500, True, False, (300, 200), False, "#fff", False, None, True, self.webview_ready, ) inspector.show() return inspector.webview
def on_inspect_webview(self, inspector, webview): title = "Web Inspector - {}".format(self.window.get_title()) uid = self.uid + "-inspector" inspector = BrowserView( uid, title, "", 700, 500, True, False, (300, 200), False, "#fff", False, None, self.webview_ready, ) inspector.show() return inspector.webview
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def evaluate_js(self, script): def _evaluate_js(): self.webview.execute_script(code) result_semaphore.release() self.eval_js_lock.acquire() result_semaphore = Semaphore(0) self.js_result_semaphores.append(result_semaphore) # Backup the doc title and store the result in it with a custom prefix unique_id = uuid1().hex code = "window.oldTitle{0} = document.title; document.title = {1};".format( unique_id, script ) self.load_event.wait() glib.idle_add(_evaluate_js) result_semaphore.acquire() if not gtk.main_level(): # Webview has been closed, don't proceed return None result = self.webview.get_title() result = ( None if result == "undefined" or result == "null" or result is None else result if result == "" else json.loads(result) ) # Restore document title and return code = "document.title = window.oldTitle{0}".format(unique_id) glib.idle_add(_evaluate_js) self.js_result_semaphores.remove(result_semaphore) self.eval_js_lock.release() return result
def evaluate_js(self, script): def _evaluate_js(): self.webview.execute_script(code) result_semaphore.release() self.eval_js_lock.acquire() result_semaphore = Semaphore(0) self.js_result_semaphores.append(result_semaphore) # Backup the doc title and store the result in it with a custom prefix unique_id = uuid1().hex code = "window.oldTitle{0} = document.title; document.title = {1};".format( unique_id, script ) self.load_event.wait() glib.idle_add(_evaluate_js) result_semaphore.acquire() if not gtk.main_level(): # Webview has been closed, don't proceed return None result = self.webview.get_title() result = ( None if result == "undefined" or result == "null" else result if result == "" else json.loads(result) ) # Restore document title and return code = "document.title = window.oldTitle{0}".format(unique_id) glib.idle_add(_evaluate_js) self.js_result_semaphores.remove(result_semaphore) self.eval_js_lock.release() return result
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def show_inspector(self): uid = self.parent().uid + "-inspector" try: # If inspector already exists, bring it to the front BrowserView.instances[uid].raise_() BrowserView.instances[uid].activateWindow() except KeyError: title = "Web Inspector - {}".format(self.parent().title) url = "http://localhost:{}".format(BrowserView.inspector_port) inspector = BrowserView( uid, title, url, 700, 500, True, False, (300, 200), False, "#fff", False, None, True, self.parent().webview_ready, ) inspector.show()
def show_inspector(self): uid = self.parent().uid + "-inspector" try: # If inspector already exists, bring it to the front BrowserView.instances[uid].raise_() BrowserView.instances[uid].activateWindow() except KeyError: title = "Web Inspector - {}".format(self.parent().title) url = "http://localhost:{}".format(BrowserView.inspector_port) inspector = BrowserView( uid, title, url, 700, 500, True, False, (300, 200), False, "#fff", False, None, self.parent().webview_ready, ) inspector.show()
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def closeEvent(self, event): if self.confirm_quit: reply = QMessageBox.question( self, self.title, localization["global.quitConfirmation"], QMessageBox.Yes, QMessageBox.No, ) if reply == QMessageBox.No: event.ignore() return event.accept() del BrowserView.instances[self.uid] try: # Close inspector if open BrowserView.instances[self.uid + "-inspector"].close() del BrowserView.instances[self.uid + "-inspector"] except KeyError: pass if len(BrowserView.instances) == 0: _app.exit()
def closeEvent(self, event): if self.confirm_quit: reply = QMessageBox.question( self, self.title, localization["global.quitConfirmation"], QMessageBox.Yes, QMessageBox.No, ) if reply == QMessageBox.No: event.ignore() return event.accept() del BrowserView.instances[self.uid] try: # Close inpsector if open BrowserView.instances[self.uid + "-inspector"].close() del BrowserView.instances[self.uid + "-inspector"] except KeyError: pass
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def create_window( uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready, ): global _app _app = QApplication.instance() or QApplication([]) def _create(): browser = BrowserView( uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready, ) browser.show() if uid == "master": _create() _app.exec_() else: i = list(BrowserView.instances.values())[0] # arbitrary instance i.create_window_trigger.emit(_create)
def create_window( uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready, ): app = QApplication.instance() or QApplication([]) def _create(): browser = BrowserView( uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready, ) browser.show() if uid == "master": _create() app.exec_() else: i = list(BrowserView.instances.values())[0] # arbitrary instance i.create_window_trigger.emit(_create)
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def create_window( uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready, ): def create(): window = BrowserView.BrowserForm( uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready, ) BrowserView.instances[uid] = window window.Show() if uid == "master": app.Run() webview_ready.clear() app = WinForms.Application if uid == "master": set_ie_mode() if sys.getwindowsversion().major >= 6: windll.user32.SetProcessDPIAware() app.EnableVisualStyles() app.SetCompatibleTextRenderingDefault(False) thread = Thread(ThreadStart(create)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join() else: i = list(BrowserView.instances.values())[0] # arbitrary instance i.Invoke(Func[Type](create))
def create_window( uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready, ): def create(): window = BrowserView.BrowserForm( uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, text_select, webview_ready, ) BrowserView.instances[uid] = window window.Show() if uid == "master": app.Run() webview_ready.clear() app = WinForms.Application if uid == "master": set_ie_mode() if sys.getwindowsversion().major >= 6: windll.user32.SetProcessDPIAware() app.EnableVisualStyles() app.SetCompatibleTextRenderingDefault(False) thread = Thread(ThreadStart(create)) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join() else: BrowserView.instances["master"].Invoke(Func[Type](create))
https://github.com/r0x0r/pywebview/issues/229
Exception in thread Thread-3: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "ui_pywebview.py", line 23, in create_second_window second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi) File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window background_color, debug, js_api, text_select, _webview_ready) File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window BrowserView.instances['master'].Invoke(Func[Type](create)) KeyError: 'master'
KeyError
def _switch(self, chara, charb): if self._isdigit(chara): return 0, not self._isdigit(charb) if self._isletter(chara): return 1, not self._isletter(charb) return 2, self._isdigit(charb) or self._isletter(charb)
def _switch(self, chara, charb): if self._isdigit(chara): return 0, not self._isdigit(charb) if self._isletter(chara): return 1, not self._isletter(charb) if self._isnonword(chara): return 2, not self._isnonword(charb) return "", True
https://github.com/scrapinghub/dateparser/issues/621
dateparser.parse('Oct 1 2018 4:40 PM EST —') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "dateparser/conf.py", line 82, in wrapper return f(*args, **kwargs) File "dateparser/__init__.py", line 53, in parse data = parser.get_date_data(date_string, date_formats) File "dateparser/date.py", line 417, in get_date_data locale, date_string, date_formats, settings=self._settings) File "dateparser/date.py", line 189, in parse return instance._parse() File "dateparser/date.py", line 199, in _parse date_obj = parser() File "dateparser/date.py", line 222, in _try_parser self._get_translated_date(), settings=self._settings) File "dateparser/conf.py", line 82, in wrapper return f(*args, **kwargs) File "dateparser/date_parser.py", line 26, in parse date_obj, period = parse(date_string, settings=settings) File "dateparser/parser.py", line 70, in parse raise exceptions.pop(-1) File "dateparser/parser.py", line 64, in parse res = parser(datestring, settings) File "dateparser/parser.py", line 446, in parse po = cls(tokens.tokenize(), settings) File "dateparser/parser.py", line 192, in __init__ self.filtered_tokens = [t for t in self.tokens if t[1] <= 1] File "dateparser/parser.py", line 192, in <listcomp> self.filtered_tokens = [t for t in self.tokens if t[1] <= 1] TypeError: '<=' not supported between instances of 'str' and 'int'
TypeError
def __init__(self, tokens, settings): self.settings = settings self.tokens = list(tokens) self.filtered_tokens = [t for t in self.tokens if t[1] <= 1] self.unset_tokens = [] self.day = None self.month = None self.year = None self.time = None self.auto_order = [] self._token_day = None self._token_month = None self._token_year = None self._token_time = None self.ordered_num_directives = OrderedDict( (k, self.num_directives[k]) for k in (resolve_date_order(settings.DATE_ORDER, lst=True)) ) skip_index = [] skip_component = None for index, token_type in enumerate(self.filtered_tokens): if index in skip_index: continue token, type = token_type if token in settings.SKIP_TOKENS_PARSER: continue if self.time is None: try: microsecond = MICROSECOND.search( self.filtered_tokens[index + 1][0] ).group() _is_after_time_token = token.index(":") _is_after_period = self.tokens[self.tokens.index((token, 0)) + 1][ 0 ].index(".") except: microsecond = None if microsecond: mindex = index + 2 else: mindex = index + 1 try: meridian = MERIDIAN.search(self.filtered_tokens[mindex][0]).group() except: meridian = None if any([":" in token, meridian, microsecond]): if meridian and not microsecond: self._token_time = "%s %s" % (token, meridian) skip_index.append(mindex) elif microsecond and not meridian: self._token_time = "%s.%s" % (token, microsecond) skip_index.append(index + 1) elif meridian and microsecond: self._token_time = "%s.%s %s" % (token, microsecond, meridian) skip_index.append(index + 1) skip_index.append(mindex) else: self._token_time = token self.time = lambda: time_parser(self._token_time) continue results = self._parse( type, token, settings.FUZZY, skip_component=skip_component ) for res in results: if len(token) == 4 and res[0] == "year": skip_component = "year" setattr(self, *res) known, unknown = get_unresolved_attrs(self) params = {} for attr in known: params.update({attr: getattr(self, attr)}) for attr in unknown: for token, type, _ in self.unset_tokens: if type == 0: params.update({attr: int(token)}) setattr(self, "_token_%s" % attr, token) setattr(self, attr, int(token))
def __init__(self, tokens, settings): self.settings = settings self.tokens = list(tokens) self.filtered_tokens = [t for t in self.tokens if t[1] <= 1] self.unset_tokens = [] self.day = None self.month = None self.year = None self.time = None self.auto_order = [] self._token_day = None self._token_month = None self._token_year = None self._token_time = None self.ordered_num_directives = OrderedDict( (k, self.num_directives[k]) for k in (resolve_date_order(settings.DATE_ORDER, lst=True)) ) skip_index = [] skip_component = None for index, token_type in enumerate(self.filtered_tokens): if index in skip_index: continue token, type = token_type if token in settings.SKIP_TOKENS_PARSER: continue if self.time is None: try: microsecond = MICROSECOND.search( self.filtered_tokens[index + 1][0] ).group() _is_after_time_token = token.index(":") _is_after_period = self.tokens[self.tokens.index((token, 0)) + 1][ 0 ].index(".") except: microsecond = None if microsecond: mindex = index + 2 else: mindex = index + 1 try: meridian = MERIDIAN.search(self.filtered_tokens[mindex][0]).group() except: meridian = None if any([":" in token, meridian, microsecond]): if meridian and not microsecond: self._token_time = "%s %s" % (token, meridian) skip_index.append(mindex) elif microsecond and not meridian: self._token_time = "%s.%s" % (token, microsecond) skip_index.append(index + 1) elif meridian and microsecond: self._token_time = "%s.%s %s" % (token, microsecond, meridian) skip_index.append(index + 1) skip_index.append(mindex) else: self._token_time = token self.time = lambda: time_parser(self._token_time) continue results = self._parse( type, token, settings.FUZZY, skip_component=skip_component ) for res in results: if len(token) == 4 and res[0] == "year": skip_component = "year" setattr(self, *res) known, unknown = get_unresolved_attrs(self) params = {} for attr in known: params.update({attr: getattr(self, attr)}) for attr in unknown: for token, type, _ in self.unset_tokens: if type == 0: params.update({attr: int(token)}) datetime(**params) setattr(self, "_token_%s" % attr, token) setattr(self, attr, int(token))
https://github.com/scrapinghub/dateparser/issues/336
Python 3.6.2 (default, Jul 17 2017, 23:14:31) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. import dateparser dateparser.__version__ '0.6.0' dateparser.parse('+38 (0352)') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/conf.py", line 84, in wrapper return f(*args, **kwargs) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/__init__.py", line 40, in parse data = parser.get_date_data(date_string, date_formats) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/date.py", line 371, in get_date_data language, date_string, date_formats, settings=self._settings) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/date.py", line 168, in parse return instance._parse() File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/date.py", line 178, in _parse date_obj = parser() File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/date.py", line 199, in _try_parser self._get_translated_date(), settings=self._settings) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/conf.py", line 84, in wrapper return f(*args, **kwargs) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/date_parser.py", line 26, in parse date_obj, period = parse(date_string, settings=settings) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/parser.py", line 84, in parse raise exceptions.pop(-1) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/parser.py", line 78, in parse res = parser(datestring, settings) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/parser.py", line 454, in parse po = cls(tokens.tokenize(), settings) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/parser.py", line 288, in __init__ datetime(**params) TypeError: Required argument 'day' (pos 3) not found dateparser.parse('+38 0352') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/conf.py", line 84, in wrapper return f(*args, **kwargs) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/__init__.py", line 40, in parse data = parser.get_date_data(date_string, date_formats) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/date.py", line 371, in get_date_data language, date_string, date_formats, settings=self._settings) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/date.py", line 168, in parse return instance._parse() File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/date.py", line 178, in _parse date_obj = parser() File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/date.py", line 199, in _try_parser self._get_translated_date(), settings=self._settings) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/conf.py", line 84, in wrapper return f(*args, **kwargs) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/date_parser.py", line 26, in parse date_obj, period = parse(date_string, settings=settings) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/parser.py", line 84, in parse raise exceptions.pop(-1) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/parser.py", line 78, in parse res = parser(datestring, settings) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/parser.py", line 454, in parse po = cls(tokens.tokenize(), settings) File "/home/amorgun/env3.6/lib/python3.6/site-packages/dateparser/parser.py", line 288, in __init__ datetime(**params) TypeError: Required argument 'day' (pos 3) not found
TypeError
def read_my_cnf_files(self, files, keys): """ Reads a list of config files and merges them. The last one will win. :param files: list of files to read :param keys: list of keys to retrieve :returns: tuple, with None for missing keys. """ cnf = read_config_files(files) sections = ["client"] if self.login_path and self.login_path != "client": sections.append(self.login_path) if self.defaults_suffix: sections.extend([sect + self.defaults_suffix for sect in sections]) def get(key): result = None for sect in cnf: if sect in sections and key in cnf[sect]: result = cnf[sect][key] # HACK: if result is a list, then ConfigObj() probably decoded from # string by splitting on comma, so reconstruct string by joining on # comma. if isinstance(result, list): result = ",".join(result) return result return {x: get(x) for x in keys}
def read_my_cnf_files(self, files, keys): """ Reads a list of config files and merges them. The last one will win. :param files: list of files to read :param keys: list of keys to retrieve :returns: tuple, with None for missing keys. """ cnf = read_config_files(files) sections = ["client"] if self.login_path and self.login_path != "client": sections.append(self.login_path) if self.defaults_suffix: sections.extend([sect + self.defaults_suffix for sect in sections]) def get(key): result = None for sect in cnf: if sect in sections and key in cnf[sect]: result = cnf[sect][key] return result return {x: get(x) for x in keys}
https://github.com/dbcli/mycli/issues/624
2018-07-22 01:30:33,368 (48024/MainThread) mycli.main ERROR - traceback: 'Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/mycli/main.py", line 445, in connect _connect() File "/usr/local/lib/python3.7/site-packages/mycli/main.py", line 398, in _connect socket, charset, local_infile, ssl) File "/usr/local/lib/python3.7/site-packages/mycli/sqlexecute.py", line 52, in __init__ self.connect() File "/usr/local/lib/python3.7/site-packages/mycli/sqlexecute.py", line 88, in connect conv=conv, ssl=ssl) File "/usr/local/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 327, in __init__ self.connect() File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 598, in connect self._request_authentication() File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 808, in _request_authentication authresp = _auth.scramble_native_password(self.password, self.salt) File "/usr/local/lib/python3.7/site-packages/pymysql/_auth.py", line 31, in scramble_native_password stage1 = sha1_new(password).digest() File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/hashlib.py", line 149, in __hash_new return _hashlib.new(name, data) TypeError: object supporting the buffer API required '
TypeError
def get(key): result = None for sect in cnf: if sect in sections and key in cnf[sect]: result = cnf[sect][key] # HACK: if result is a list, then ConfigObj() probably decoded from # string by splitting on comma, so reconstruct string by joining on # comma. if isinstance(result, list): result = ",".join(result) return result
def get(key): result = None for sect in cnf: if sect in sections and key in cnf[sect]: result = cnf[sect][key] return result
https://github.com/dbcli/mycli/issues/624
2018-07-22 01:30:33,368 (48024/MainThread) mycli.main ERROR - traceback: 'Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/mycli/main.py", line 445, in connect _connect() File "/usr/local/lib/python3.7/site-packages/mycli/main.py", line 398, in _connect socket, charset, local_infile, ssl) File "/usr/local/lib/python3.7/site-packages/mycli/sqlexecute.py", line 52, in __init__ self.connect() File "/usr/local/lib/python3.7/site-packages/mycli/sqlexecute.py", line 88, in connect conv=conv, ssl=ssl) File "/usr/local/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 327, in __init__ self.connect() File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 598, in connect self._request_authentication() File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 808, in _request_authentication authresp = _auth.scramble_native_password(self.password, self.salt) File "/usr/local/lib/python3.7/site-packages/pymysql/_auth.py", line 31, in scramble_native_password stage1 = sha1_new(password).digest() File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/hashlib.py", line 149, in __hash_new return _hashlib.new(name, data) TypeError: object supporting the buffer API required '
TypeError
def extract_from_part(parsed, stop_at_punctuation=True): tbl_prefix_seen = False for item in parsed.tokens: if tbl_prefix_seen: if is_subselect(item): for x in extract_from_part(item, stop_at_punctuation): yield x elif stop_at_punctuation and item.ttype is Punctuation: return # An incomplete nested select won't be recognized correctly as a # sub-select. eg: 'SELECT * FROM (SELECT id FROM user'. This causes # the second FROM to trigger this elif condition resulting in a # StopIteration. So we need to ignore the keyword if the keyword # FROM. # Also 'SELECT * FROM abc JOIN def' will trigger this elif # condition. So we need to ignore the keyword JOIN and its variants # INNER JOIN, FULL OUTER JOIN, etc. elif ( item.ttype is Keyword and (not item.value.upper() == "FROM") and (not item.value.upper().endswith("JOIN")) ): return else: yield item elif ( item.ttype is Keyword or item.ttype is Keyword.DML ) and item.value.upper() in ( "COPY", "FROM", "INTO", "UPDATE", "TABLE", "JOIN", ): tbl_prefix_seen = True # 'SELECT a, FROM abc' will detect FROM as part of the column list. # So this check here is necessary. elif isinstance(item, IdentifierList): for identifier in item.get_identifiers(): if identifier.ttype is Keyword and identifier.value.upper() == "FROM": tbl_prefix_seen = True break
def extract_from_part(parsed, stop_at_punctuation=True): tbl_prefix_seen = False for item in parsed.tokens: if tbl_prefix_seen: if is_subselect(item): for x in extract_from_part(item, stop_at_punctuation): yield x elif stop_at_punctuation and item.ttype is Punctuation: raise StopIteration # An incomplete nested select won't be recognized correctly as a # sub-select. eg: 'SELECT * FROM (SELECT id FROM user'. This causes # the second FROM to trigger this elif condition resulting in a # StopIteration. So we need to ignore the keyword if the keyword # FROM. # Also 'SELECT * FROM abc JOIN def' will trigger this elif # condition. So we need to ignore the keyword JOIN and its variants # INNER JOIN, FULL OUTER JOIN, etc. elif ( item.ttype is Keyword and (not item.value.upper() == "FROM") and (not item.value.upper().endswith("JOIN")) ): raise StopIteration else: yield item elif ( item.ttype is Keyword or item.ttype is Keyword.DML ) and item.value.upper() in ( "COPY", "FROM", "INTO", "UPDATE", "TABLE", "JOIN", ): tbl_prefix_seen = True # 'SELECT a, FROM abc' will detect FROM as part of the column list. # So this check here is necessary. elif isinstance(item, IdentifierList): for identifier in item.get_identifiers(): if identifier.ttype is Keyword and identifier.value.upper() == "FROM": tbl_prefix_seen = True break
https://github.com/dbcli/mycli/issues/619
Traceback (most recent call last): File "c:\python37\lib\site-packages\mycli\packages\parseutils.py", line 95, in extract_from_part raise StopIteration StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last):w to complete suggestion File "c:\python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "c:\python37\lib\site-packages\prompt_toolkit\interface.py", line 865, in run completions = list(buffer.completer.get_completions(document, complete_event)) File "c:\python37\lib\site-packages\mycli\sqlcompleter.py", line 258, in get_completions suggestions = suggest_type(document.text, document.text_before_cursor) File "c:\python37\lib\site-packages\mycli\packages\completion_engine.py", line 93, in suggest_type full_text, identifier) File "c:\python37\lib\site-packages\mycli\packages\completion_engine.py", line 203, in suggest_based_on_last_token return [{'type': 'column', 'tables': extract_tables(full_text)}] File "c:\python37\lib\site-packages\mycli\packages\parseutils.py", line 154, in extract_tables return list(extract_table_identifiers(stream)) File "c:\python37\lib\site-packages\mycli\packages\parseutils.py", line 113, in extract_table_identifiers for item in token_stream: RuntimeError: generator raised StopIteration
RuntimeError
def watch_query(arg, **kwargs): usage = """Syntax: watch [seconds] [-c] query. * seconds: The interval at the query will be repeated, in seconds. By default 5. * -c: Clears the screen between every iteration. """ if not arg: yield (None, None, None, usage) return seconds = 5 clear_screen = False statement = None while statement is None: arg = arg.strip() if not arg: # Oops, we parsed all the arguments without finding a statement yield (None, None, None, usage) return (current_arg, _, arg) = arg.partition(" ") try: seconds = float(current_arg) continue except ValueError: pass if current_arg == "-c": clear_screen = True continue statement = "{0!s} {1!s}".format(current_arg, arg) destructive_prompt = confirm_destructive_query(statement) if destructive_prompt is False: click.secho("Wise choice!") return elif destructive_prompt is True: click.secho("Your call!") cur = kwargs["cur"] sql_list = [ (sql.rstrip(";"), "> {0!s}".format(sql)) for sql in sqlparse.split(statement) ] old_pager_enabled = is_pager_enabled() while True: if clear_screen: click.clear() try: # Somewhere in the code the pager its activated after every yield, # so we disable it in every iteration set_pager_enabled(False) for sql, title in sql_list: cur.execute(sql) if cur.description: headers = [x[0] for x in cur.description] yield (title, cur, headers, None) else: yield (title, None, None, None) sleep(seconds) except KeyboardInterrupt: # This prints the Ctrl-C character in its own line, which prevents # to print a line with the cursor positioned behind the prompt click.secho("", nl=True) return finally: set_pager_enabled(old_pager_enabled)
def watch_query(arg, **kwargs): usage = """Syntax: watch [seconds] [-c] query. * seconds: The interval at the query will be repeated, in seconds. By default 5. * -c: Clears the screen between every iteration. """ if not arg: yield (None, None, None, usage) raise StopIteration seconds = 5 clear_screen = False statement = None while statement is None: arg = arg.strip() if not arg: # Oops, we parsed all the arguments without finding a statement yield (None, None, None, usage) raise StopIteration (current_arg, _, arg) = arg.partition(" ") try: seconds = float(current_arg) continue except ValueError: pass if current_arg == "-c": clear_screen = True continue statement = "{0!s} {1!s}".format(current_arg, arg) destructive_prompt = confirm_destructive_query(statement) if destructive_prompt is False: click.secho("Wise choice!") raise StopIteration elif destructive_prompt is True: click.secho("Your call!") cur = kwargs["cur"] sql_list = [ (sql.rstrip(";"), "> {0!s}".format(sql)) for sql in sqlparse.split(statement) ] old_pager_enabled = is_pager_enabled() while True: if clear_screen: click.clear() try: # Somewhere in the code the pager its activated after every yield, # so we disable it in every iteration set_pager_enabled(False) for sql, title in sql_list: cur.execute(sql) if cur.description: headers = [x[0] for x in cur.description] yield (title, cur, headers, None) else: yield (title, None, None, None) sleep(seconds) except KeyboardInterrupt: # This prints the Ctrl-C character in its own line, which prevents # to print a line with the cursor positioned behind the prompt click.secho("", nl=True) raise StopIteration finally: set_pager_enabled(old_pager_enabled)
https://github.com/dbcli/mycli/issues/619
Traceback (most recent call last): File "c:\python37\lib\site-packages\mycli\packages\parseutils.py", line 95, in extract_from_part raise StopIteration StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last):w to complete suggestion File "c:\python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "c:\python37\lib\site-packages\prompt_toolkit\interface.py", line 865, in run completions = list(buffer.completer.get_completions(document, complete_event)) File "c:\python37\lib\site-packages\mycli\sqlcompleter.py", line 258, in get_completions suggestions = suggest_type(document.text, document.text_before_cursor) File "c:\python37\lib\site-packages\mycli\packages\completion_engine.py", line 93, in suggest_type full_text, identifier) File "c:\python37\lib\site-packages\mycli\packages\completion_engine.py", line 203, in suggest_based_on_last_token return [{'type': 'column', 'tables': extract_tables(full_text)}] File "c:\python37\lib\site-packages\mycli\packages\parseutils.py", line 154, in extract_tables return list(extract_table_identifiers(stream)) File "c:\python37\lib\site-packages\mycli\packages\parseutils.py", line 113, in extract_table_identifiers for item in token_stream: RuntimeError: generator raised StopIteration
RuntimeError
def initialize_logging(self): log_file = os.path.expanduser(self.config["main"]["log_file"]) log_level = self.config["main"]["log_level"] level_map = { "CRITICAL": logging.CRITICAL, "ERROR": logging.ERROR, "WARNING": logging.WARNING, "INFO": logging.INFO, "DEBUG": logging.DEBUG, } # Disable logging if value is NONE by switching to a no-op handler # Set log level to a high value so it doesn't even waste cycles getting called. if log_level.upper() == "NONE": handler = logging.NullHandler() log_level = "CRITICAL" elif dir_path_exists(log_file): handler = logging.FileHandler(log_file) else: self.echo( 'Error: Unable to open the log file "{}".'.format(log_file), err=True, fg="red", ) return formatter = logging.Formatter( "%(asctime)s (%(process)d/%(threadName)s) %(name)s %(levelname)s - %(message)s" ) handler.setFormatter(formatter) root_logger = logging.getLogger("mycli") root_logger.addHandler(handler) root_logger.setLevel(level_map[log_level.upper()]) logging.captureWarnings(True) root_logger.debug("Initializing mycli logging.") root_logger.debug("Log file %r.", log_file)
def initialize_logging(self): log_file = self.config["main"]["log_file"] log_level = self.config["main"]["log_level"] level_map = { "CRITICAL": logging.CRITICAL, "ERROR": logging.ERROR, "WARNING": logging.WARNING, "INFO": logging.INFO, "DEBUG": logging.DEBUG, } # Disable logging if value is NONE by switching to a no-op handler # Set log level to a high value so it doesn't even waste cycles getting called. if log_level.upper() == "NONE": handler = logging.NullHandler() log_level = "CRITICAL" else: handler = logging.FileHandler(os.path.expanduser(log_file)) formatter = logging.Formatter( "%(asctime)s (%(process)d/%(threadName)s) %(name)s %(levelname)s - %(message)s" ) handler.setFormatter(formatter) root_logger = logging.getLogger("mycli") root_logger.addHandler(handler) root_logger.setLevel(level_map[log_level.upper()]) logging.captureWarnings(True) root_logger.debug("Initializing mycli logging.") root_logger.debug("Log file %r.", log_file)
https://github.com/dbcli/mycli/issues/569
$ mycli Password: localhost:(none)> use test Traceback (most recent call last): File "/home/linuxbrew/.linuxbrew/bin/mycli", line 11, in <module> load_entry_point('mycli==1.16.0', 'console_scripts', 'mycli')() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/click/core.py", line 722, in __call__ return self.main(*args, **kwargs) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/click/core.py", line 697, in main rv = self.invoke(ctx) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/click/core.py", line 895, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/click/core.py", line 535, in invoke return callback(*args, **kwargs) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/mycli/main.py", line 1053, in cli mycli.run_cli() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/mycli/main.py", line 696, in run_cli one_iteration() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/mycli/main.py", line 512, in one_iteration document = self.cli.run() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/interface.py", line 415, in run self.eventloop.run(self.input, self.create_eventloop_callbacks()) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/eventloop/posix.py", line 159, in run t() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/eventloop/posix.py", line 82, in read_from_stdin inputstream.feed(data) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/terminal/vt100_input.py", line 398, in feed self._input_parser.send(c) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/terminal/vt100_input.py", line 307, in _input_parser_generator self._call_handler(match, prefix) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/terminal/vt100_input.py", line 340, in _call_handler self.feed_key_callback(KeyPress(key, insert_text)) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/interface.py", line 1048, in feed_key cli.input_processor.process_keys() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/key_binding/input_processor.py", line 219, in process_keys self._process_coroutine.send(key_press) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/key_binding/input_processor.py", line 176, in _process self._call_handler(matches[-1], key_sequence=buffer[:]) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/key_binding/input_processor.py", line 247, in _call_handler handler.call(event) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/key_binding/registry.py", line 61, in call return self.handler(event) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/key_binding/bindings/basic.py", line 167, in _ buff.accept_action.validate_and_handle(event.cli, buff) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/buffer.py", line 86, in validate_and_handle buffer.append_to_history() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/buffer.py", line 1130, in append_to_history self.history.append(self.text) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/history.py", line 105, in append with open(self.filename, 'ab') as f: IOError: [Errno 2] No such file or directory: '/home/tsr/.cache/mycli/history'
IOError
def run_cli(self): iterations = 0 sqlexecute = self.sqlexecute logger = self.logger self.configure_pager() if self.smart_completion: self.refresh_completions() author_file = os.path.join(PACKAGE_ROOT, "AUTHORS") sponsor_file = os.path.join(PACKAGE_ROOT, "SPONSORS") history_file = os.path.expanduser( os.environ.get("MYCLI_HISTFILE", "~/.mycli-history") ) if dir_path_exists(history_file): history = FileHistory(history_file) else: history = None self.echo( 'Error: Unable to open the history file "{}". ' "Your query history will not be saved.".format(history_file), err=True, fg="red", ) key_binding_manager = mycli_bindings() if not self.less_chatty: print("Version:", __version__) print("Chat: https://gitter.im/dbcli/mycli") print("Mail: https://groups.google.com/forum/#!forum/mycli-users") print("Home: http://mycli.net") print("Thanks to the contributor -", thanks_picker([author_file, sponsor_file])) def prompt_tokens(cli): prompt = self.get_prompt(self.prompt_format) if ( self.prompt_format == self.default_prompt and len(prompt) > self.max_len_prompt ): prompt = self.get_prompt("\\d> ") return [(Token.Prompt, prompt)] def get_continuation_tokens(cli, width): continuation_prompt = self.get_prompt(self.prompt_continuation_format) return [ ( Token.Continuation, " " * (width - len(continuation_prompt)) + continuation_prompt, ) ] def show_suggestion_tip(): return iterations < 2 def one_iteration(document=None): if document is None: document = self.cli.run() special.set_expanded_output(False) try: document = self.handle_editor_command(self.cli, document) except RuntimeError as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg="red") return if not document.text.strip(): return if self.destructive_warning: destroy = confirm_destructive_query(document.text) if destroy is None: pass # Query was not destructive. Nothing to do here. elif destroy is True: self.echo("Your call!") else: self.echo("Wise choice!") return # Keep track of whether or not the query is mutating. In case # of a multi-statement query, the overall query is considered # mutating if any one of the component statements is mutating mutating = False try: logger.debug("sql: %r", document.text) special.write_tee(self.get_prompt(self.prompt_format) + document.text) if self.logfile: self.logfile.write("\n# %s\n" % datetime.now()) self.logfile.write(document.text) self.logfile.write("\n") successful = False start = time() res = sqlexecute.run(document.text) self.formatter.query = document.text successful = True result_count = 0 for title, cur, headers, status in res: logger.debug("headers: %r", headers) logger.debug("rows: %r", cur) logger.debug("status: %r", status) threshold = 1000 if is_select(status) and cur and cur.rowcount > threshold: self.echo( "The result set has more than {} rows.".format(threshold), fg="red", ) if not click.confirm("Do you want to continue?"): self.echo("Aborted!", err=True, fg="red") break if self.auto_vertical_output: max_width = self.cli.output.get_size().columns else: max_width = None formatted = self.format_output( title, cur, headers, special.is_expanded_output(), max_width ) t = time() - start try: if result_count > 0: self.echo("") try: self.output(formatted, status) except KeyboardInterrupt: pass if special.is_timing_enabled(): self.echo("Time: %0.03fs" % t) except KeyboardInterrupt: pass start = time() result_count += 1 mutating = mutating or is_mutating(status) special.unset_once_if_written() except EOFError as e: raise e except KeyboardInterrupt: # get last connection id connection_id_to_kill = sqlexecute.connection_id logger.debug("connection id to kill: %r", connection_id_to_kill) # Restart connection to the database sqlexecute.connect() try: for title, cur, headers, status in sqlexecute.run( "kill %s" % connection_id_to_kill ): status_str = str(status).lower() if status_str.find("ok") > -1: logger.debug( "cancelled query, connection id: %r, sql: %r", connection_id_to_kill, document.text, ) self.echo("cancelled query", err=True, fg="red") except Exception as e: self.echo( "Encountered error while cancelling query: {}".format(e), err=True, fg="red", ) except NotImplementedError: self.echo("Not Yet Implemented.", fg="yellow") except OperationalError as e: logger.debug("Exception: %r", e) if e.args[0] in (2003, 2006, 2013): logger.debug("Attempting to reconnect.") self.echo("Reconnecting...", fg="yellow") try: sqlexecute.connect() logger.debug("Reconnected successfully.") one_iteration(document) return # OK to just return, cuz the recursion call runs to the end. except OperationalError as e: logger.debug("Reconnect failed. e: %r", e) self.echo(str(e), err=True, fg="red") # If reconnection failed, don't proceed further. return else: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg="red") except Exception as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg="red") else: if is_dropping_database(document.text, self.sqlexecute.dbname): self.sqlexecute.dbname = None self.sqlexecute.connect() # Refresh the table names and column names if necessary. if need_completion_refresh(document.text): self.refresh_completions(reset=need_completion_reset(document.text)) finally: if self.logfile is False: self.echo("Warning: This query was not logged.", err=True, fg="red") query = Query(document.text, successful, mutating) self.query_history.append(query) get_toolbar_tokens = create_toolbar_tokens_func( self.completion_refresher.is_refreshing, show_suggestion_tip ) layout = create_prompt_layout( lexer=MyCliLexer, multiline=True, get_prompt_tokens=prompt_tokens, get_continuation_tokens=get_continuation_tokens, get_bottom_toolbar_tokens=get_toolbar_tokens, display_completions_in_columns=self.wider_completion_menu, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars="[](){}"), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(), ) ], reserve_space_for_menu=self.get_reserved_space(), ) with self._completer_lock: buf = CLIBuffer( always_multiline=self.multi_line, completer=self.completer, history=history, auto_suggest=AutoSuggestFromHistory(), complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT, ) if self.key_bindings == "vi": editing_mode = EditingMode.VI else: editing_mode = EditingMode.EMACS application = Application( style=style_from_pygments(style_cls=self.output_style), layout=layout, buffer=buf, key_bindings_registry=key_binding_manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, editing_mode=editing_mode, ignore_case=True, ) self.cli = CommandLineInterface( application=application, eventloop=create_eventloop() ) try: while True: one_iteration() iterations += 1 except EOFError: special.close_tee() if not self.less_chatty: self.echo("Goodbye!")
def run_cli(self): iterations = 0 sqlexecute = self.sqlexecute logger = self.logger self.configure_pager() if self.smart_completion: self.refresh_completions() author_file = os.path.join(PACKAGE_ROOT, "AUTHORS") sponsor_file = os.path.join(PACKAGE_ROOT, "SPONSORS") key_binding_manager = mycli_bindings() if not self.less_chatty: print("Version:", __version__) print("Chat: https://gitter.im/dbcli/mycli") print("Mail: https://groups.google.com/forum/#!forum/mycli-users") print("Home: http://mycli.net") print("Thanks to the contributor -", thanks_picker([author_file, sponsor_file])) def prompt_tokens(cli): prompt = self.get_prompt(self.prompt_format) if ( self.prompt_format == self.default_prompt and len(prompt) > self.max_len_prompt ): prompt = self.get_prompt("\\d> ") return [(Token.Prompt, prompt)] def get_continuation_tokens(cli, width): continuation_prompt = self.get_prompt(self.prompt_continuation_format) return [ ( Token.Continuation, " " * (width - len(continuation_prompt)) + continuation_prompt, ) ] def show_suggestion_tip(): return iterations < 2 def one_iteration(document=None): if document is None: document = self.cli.run() special.set_expanded_output(False) try: document = self.handle_editor_command(self.cli, document) except RuntimeError as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg="red") return if not document.text.strip(): return if self.destructive_warning: destroy = confirm_destructive_query(document.text) if destroy is None: pass # Query was not destructive. Nothing to do here. elif destroy is True: self.echo("Your call!") else: self.echo("Wise choice!") return # Keep track of whether or not the query is mutating. In case # of a multi-statement query, the overall query is considered # mutating if any one of the component statements is mutating mutating = False try: logger.debug("sql: %r", document.text) special.write_tee(self.get_prompt(self.prompt_format) + document.text) if self.logfile: self.logfile.write("\n# %s\n" % datetime.now()) self.logfile.write(document.text) self.logfile.write("\n") successful = False start = time() res = sqlexecute.run(document.text) self.formatter.query = document.text successful = True result_count = 0 for title, cur, headers, status in res: logger.debug("headers: %r", headers) logger.debug("rows: %r", cur) logger.debug("status: %r", status) threshold = 1000 if is_select(status) and cur and cur.rowcount > threshold: self.echo( "The result set has more than {} rows.".format(threshold), fg="red", ) if not click.confirm("Do you want to continue?"): self.echo("Aborted!", err=True, fg="red") break if self.auto_vertical_output: max_width = self.cli.output.get_size().columns else: max_width = None formatted = self.format_output( title, cur, headers, special.is_expanded_output(), max_width ) t = time() - start try: if result_count > 0: self.echo("") try: self.output(formatted, status) except KeyboardInterrupt: pass if special.is_timing_enabled(): self.echo("Time: %0.03fs" % t) except KeyboardInterrupt: pass start = time() result_count += 1 mutating = mutating or is_mutating(status) special.unset_once_if_written() except EOFError as e: raise e except KeyboardInterrupt: # get last connection id connection_id_to_kill = sqlexecute.connection_id logger.debug("connection id to kill: %r", connection_id_to_kill) # Restart connection to the database sqlexecute.connect() try: for title, cur, headers, status in sqlexecute.run( "kill %s" % connection_id_to_kill ): status_str = str(status).lower() if status_str.find("ok") > -1: logger.debug( "cancelled query, connection id: %r, sql: %r", connection_id_to_kill, document.text, ) self.echo("cancelled query", err=True, fg="red") except Exception as e: self.echo( "Encountered error while cancelling query: {}".format(e), err=True, fg="red", ) except NotImplementedError: self.echo("Not Yet Implemented.", fg="yellow") except OperationalError as e: logger.debug("Exception: %r", e) if e.args[0] in (2003, 2006, 2013): logger.debug("Attempting to reconnect.") self.echo("Reconnecting...", fg="yellow") try: sqlexecute.connect() logger.debug("Reconnected successfully.") one_iteration(document) return # OK to just return, cuz the recursion call runs to the end. except OperationalError as e: logger.debug("Reconnect failed. e: %r", e) self.echo(str(e), err=True, fg="red") # If reconnection failed, don't proceed further. return else: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg="red") except Exception as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg="red") else: if is_dropping_database(document.text, self.sqlexecute.dbname): self.sqlexecute.dbname = None self.sqlexecute.connect() # Refresh the table names and column names if necessary. if need_completion_refresh(document.text): self.refresh_completions(reset=need_completion_reset(document.text)) finally: if self.logfile is False: self.echo("Warning: This query was not logged.", err=True, fg="red") query = Query(document.text, successful, mutating) self.query_history.append(query) get_toolbar_tokens = create_toolbar_tokens_func( self.completion_refresher.is_refreshing, show_suggestion_tip ) layout = create_prompt_layout( lexer=MyCliLexer, multiline=True, get_prompt_tokens=prompt_tokens, get_continuation_tokens=get_continuation_tokens, get_bottom_toolbar_tokens=get_toolbar_tokens, display_completions_in_columns=self.wider_completion_menu, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars="[](){}"), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(), ) ], reserve_space_for_menu=self.get_reserved_space(), ) with self._completer_lock: buf = CLIBuffer( always_multiline=self.multi_line, completer=self.completer, history=FileHistory( os.path.expanduser(os.environ.get("MYCLI_HISTFILE", "~/.mycli-history")) ), auto_suggest=AutoSuggestFromHistory(), complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT, ) if self.key_bindings == "vi": editing_mode = EditingMode.VI else: editing_mode = EditingMode.EMACS application = Application( style=style_from_pygments(style_cls=self.output_style), layout=layout, buffer=buf, key_bindings_registry=key_binding_manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, editing_mode=editing_mode, ignore_case=True, ) self.cli = CommandLineInterface( application=application, eventloop=create_eventloop() ) try: while True: one_iteration() iterations += 1 except EOFError: special.close_tee() if not self.less_chatty: self.echo("Goodbye!")
https://github.com/dbcli/mycli/issues/569
$ mycli Password: localhost:(none)> use test Traceback (most recent call last): File "/home/linuxbrew/.linuxbrew/bin/mycli", line 11, in <module> load_entry_point('mycli==1.16.0', 'console_scripts', 'mycli')() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/click/core.py", line 722, in __call__ return self.main(*args, **kwargs) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/click/core.py", line 697, in main rv = self.invoke(ctx) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/click/core.py", line 895, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/click/core.py", line 535, in invoke return callback(*args, **kwargs) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/mycli/main.py", line 1053, in cli mycli.run_cli() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/mycli/main.py", line 696, in run_cli one_iteration() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/mycli/main.py", line 512, in one_iteration document = self.cli.run() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/interface.py", line 415, in run self.eventloop.run(self.input, self.create_eventloop_callbacks()) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/eventloop/posix.py", line 159, in run t() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/eventloop/posix.py", line 82, in read_from_stdin inputstream.feed(data) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/terminal/vt100_input.py", line 398, in feed self._input_parser.send(c) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/terminal/vt100_input.py", line 307, in _input_parser_generator self._call_handler(match, prefix) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/terminal/vt100_input.py", line 340, in _call_handler self.feed_key_callback(KeyPress(key, insert_text)) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/interface.py", line 1048, in feed_key cli.input_processor.process_keys() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/key_binding/input_processor.py", line 219, in process_keys self._process_coroutine.send(key_press) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/key_binding/input_processor.py", line 176, in _process self._call_handler(matches[-1], key_sequence=buffer[:]) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/key_binding/input_processor.py", line 247, in _call_handler handler.call(event) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/key_binding/registry.py", line 61, in call return self.handler(event) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/key_binding/bindings/basic.py", line 167, in _ buff.accept_action.validate_and_handle(event.cli, buff) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/buffer.py", line 86, in validate_and_handle buffer.append_to_history() File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/buffer.py", line 1130, in append_to_history self.history.append(self.text) File "/home/linuxbrew/.linuxbrew/Cellar/mycli/1.16.0/libexec/lib/python2.7/site-packages/prompt_toolkit/history.py", line 105, in append with open(self.filename, 'ab') as f: IOError: [Errno 2] No such file or directory: '/home/tsr/.cache/mycli/history'
IOError
def _mount_references(self): """ Find the references that is defined in self.configuration :return: """ self.resources_raw = deepcopy(self.resources) invalid_references = ("var.", "each.") # This section will link resources found in configuration part of the plan output. # The reference should be on both ways (A->B, B->A) since terraform sometimes report these references # in opposite ways, depending on the provider structure. for resource in self.configuration["resources"]: if "expressions" in self.configuration["resources"][resource]: ref_list = {} for key, value in self.configuration["resources"][resource][ "expressions" ].items(): references = ( seek_key_in_dict(value, "references") if isinstance(value, (dict, list)) else [] ) valid_references = [] for ref in references: if isinstance(ref, dict) and ref.get("references"): valid_references = [ r for r in ref["references"] if not r.startswith(invalid_references) ] for ref in valid_references: if key not in ref_list: ref_list[key] = self._find_resource_from_name(ref) else: ref_list[key].extend(self._find_resource_from_name(ref)) # This is where we synchronise constant_value in the configuration section with the resource # for filling up the missing elements that hasn't been defined in the resource due to provider # implementation. target_resource = [ t for t in [self.resources.get(resource, {}).get("address")] if t is not None ] if not target_resource: target_resource = [ k for k in self.resources.keys() if k.startswith(resource) ] for t_r in target_resource: if ( type(value) is type(self.resources[t_r]["values"].get(key)) and self.resources[t_r]["values"].get(key) != value ): if isinstance(value, (list, dict)): merge_dicts(self.resources[t_r]["values"][key], value) if ref_list: ref_type = self.configuration["resources"][resource]["expressions"].get( "type", {} ) if "references" in ref_type: ref_type = resource.split(".")[0] if not ref_type and not self.is_type(resource, "data"): resource_type, resource_id = resource.split(".") ref_type = resource_type for k, v in ref_list.items(): v = flatten_list(v) # Mounting A->B source_resources = self._find_resource_from_name( self.configuration["resources"][resource]["address"] ) self._mount_resources( source=source_resources, target=ref_list, ref_type=ref_type ) # Mounting B->A for parameter, target_resources in ref_list.items(): for target_resource in target_resources: if ( not self.is_type(resource, "data") and not self.is_type(resource, "var") and not self.is_type(resource, "provider") ): ref_type = target_resource.split(".", maxsplit=1)[0] self._mount_resources( source=[target_resource], target={parameter: source_resources}, ref_type=ref_type, )
def _mount_references(self): """ Find the references that is defined in self.configuration :return: """ self.resources_raw = deepcopy(self.resources) invalid_references = ("var.", "each.") # This section will link resources found in configuration part of the plan output. # The reference should be on both ways (A->B, B->A) since terraform sometimes report these references # in opposite ways, depending on the provider structure. for resource in self.configuration["resources"]: if "expressions" in self.configuration["resources"][resource]: ref_list = {} for key, value in self.configuration["resources"][resource][ "expressions" ].items(): references = ( seek_key_in_dict(value, "references") if isinstance(value, (dict, list)) else [] ) valid_references = [] for ref in references: if isinstance(ref, dict) and ref.get("references"): valid_references = [ r for r in ref["references"] if not r.startswith(invalid_references) ] for ref in valid_references: if key not in ref_list: ref_list[key] = self._find_resource_from_name(ref) else: ref_list[key].extend(self._find_resource_from_name(ref)) # This is where we synchronise constant_value in the configuration section with the resource # for filling up the missing elements that hasn't been defined in the resource due to provider # implementation. target_resource = [ t for t in [self.resources.get(resource, {}).get("address")] if t is not None ] if not target_resource: target_resource = [ k for k in self.resources.keys() if k.startswith(resource) ] if not target_resource: target_resource = [ k for k in self.resources.keys() if k.endswith(resource) ] for t_r in target_resource: if ( type(value) is type(self.resources[t_r]["values"].get(key)) and self.resources[t_r]["values"].get(key) != value ): if isinstance(value, (list, dict)): merge_dicts(self.resources[t_r]["values"][key], value) if ref_list: ref_type = self.configuration["resources"][resource]["expressions"].get( "type", {} ) if not ref_type and not self.is_type(resource, "data"): resource_type, resource_id = resource.split(".") ref_type = resource_type for k, v in ref_list.items(): v = flatten_list(v) # Mounting A->B source_resources = self._find_resource_from_name( self.configuration["resources"][resource]["address"] ) self._mount_resources( source=source_resources, target=ref_list, ref_type=ref_type ) # Mounting B->A for parameter, target_resources in ref_list.items(): for target_resource in target_resources: if ( not self.is_type(resource, "data") and not self.is_type(resource, "var") and not self.is_type(resource, "provider") ): ref_type = target_resource.split(".", maxsplit=1)[0] self._mount_resources( source=[target_resource], target={parameter: source_resources}, ref_type=ref_type, )
https://github.com/terraform-compliance/cli/issues/427
❗ ERROR: Hook 'load_terraform_data' from /usr/local/lib/python3.7/site-packages/terraform_compliance/steps/terrain.py:8 raised: 'TypeError: unhashable type: 'dict'' Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/radish/hookregistry.py", line 132, in call func(model, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/terraform_compliance/steps/terrain.py", line 10, in load_terraform_data world.config.terraform = TerraformParser(world.config.user_data['plan_file']) File "/usr/local/lib/python3.7/site-packages/terraform_compliance/extensions/terraform.py", line 44, in __init__ self.parse() File "/usr/local/lib/python3.7/site-packages/terraform_compliance/extensions/terraform.py", line 403, in parse self._mount_references() File "/usr/local/lib/python3.7/site-packages/terraform_compliance/extensions/terraform.py", line 359, in _mount_references ref_type=ref_type) File "/usr/local/lib/python3.7/site-packages/terraform_compliance/extensions/terraform.py", line 257, in _mount_resources if ref_type not in self.resources[target_resource]['values']: TypeError: unhashable type: 'dict'
TypeError
def _mount_resources(self, source, target, ref_type): """ Mounts values of the source resource to the target resource's values with ref_type key :param source: source resource :param target: target resource :param ref_type: reference type (e.g. ingress ) :return: none """ for source_resource in source: if "values" not in self.resources[source_resource]: continue for target_resource in target: if "values" not in self.resources[target_resource]: continue if ref_type not in self.resources[target_resource]["values"]: self.resources[target_resource]["values"][ref_type] = list() self.resources[target_resource]["values"][ref_type].append( self.resources[source_resource]["values"] ) else: self.resources[target_resource]["values"][ref_type].append( self.resources[source_resource]["values"] )
def _mount_resources(self, source, target, ref_type): """ Mounts values of the source resource to the target resource's values with ref_type key :param source: source resource :param target: target resource :param ref_type: reference type (e.g. ingress ) :return: none """ for source_resource in source: for target_resource in target: if ref_type not in self.resources[target_resource]["values"]: self.resources[target_resource]["values"][ref_type] = list() self.resources[target_resource]["values"][ref_type].append( self.resources[source_resource]["values"] ) else: self.resources[target_resource]["values"][ref_type].append( self.resources[source_resource]["values"] )
https://github.com/terraform-compliance/cli/issues/124
$ terraform-compliance -p /target/tc-test2/tf-template/jenkins.plan.out.json -f /target/tc-test2/features terraform-compliance v1.0.13 initiated * Features : /target/tc-test2/features * Plan File : /target/tc-test2/tf-template/jenkins.plan.out.json . Running tests. Feature: Resources should be properly tagged # /target/tc-test2/features/tags.feature In order to keep track of resource ownership As engineers We'll enforce tagging on all resources 2 features (0 passed) 30 scenarios (0 passed) 109 steps (0 passed) Run 1562934682 finished within a moment Error: Hook 'load_terraform_data' from /usr/local/lib/python3.7/site-packages/terraform_compliance/steps/terrain.py:5 raised: 'KeyError: 'values'' Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/radish/hookregistry.py", line 132, in call func(model, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/terraform_compliance/steps/terrain.py", line 7, in load_terraform_data world.config.terraform = TerraformParser(world.config.user_data['plan_file']) File "/usr/local/lib/python3.7/site-packages/terraform_compliance/extensions/terraform.py", line 34, in __init__ self.parse() File "/usr/local/lib/python3.7/site-packages/terraform_compliance/extensions/terraform.py", line 225, in parse self._mount_references() File "/usr/local/lib/python3.7/site-packages/terraform_compliance/extensions/terraform.py", line 200, in _mount_references self._mount_resources(source_resources, flatten_list(ref_list), ref_type) File "/usr/local/lib/python3.7/site-packages/terraform_compliance/extensions/terraform.py", line 153, in _mount_resources self.resources[target_resource]['values'][ref_type].append(self.resources[source_resource]['values']) KeyError: 'values'
KeyError
def change_value_in_dict(target_dictionary, path_to_change, value_to_change): if type(path_to_change) is str: path_to_change = path_to_change.split(".") if type(path_to_change) is not list: return False for x in xrange(0, len(path_to_change)): for condition in hcl_conditions: if condition in path_to_change[x]: return False path_to_adjust = '["{}"]'.format('"]["'.join(path_to_change)) try: target = eval("target_dictionary{}".format(path_to_adjust)) for key, value in value_to_change.items(): if "type" in value: type_key = value["type"] source = value source["referenced_name"] = key if type_key not in target: target[type_key] = list() elif type_key in target and type(target[type_key]) is not list: target[type_key] = [target[type_key]] target[type_key].append(source) target.update(value_to_change) try: exec("target_dictionary{}.update({})".format(path_to_adjust, target)) except: # Yes I know, this is against PEP8. pass except KeyError: pass
def change_value_in_dict(target_dictionary, path_to_change, value_to_change): if type(path_to_change) is str: path_to_change = path_to_change.split(".") if type(path_to_change) is not list: return False path_to_adjust = '["{}"]'.format('"]["'.join(path_to_change)) try: target = eval("target_dictionary{}".format(path_to_adjust)) for key, value in value_to_change.items(): if "type" in value: type_key = value["type"] source = value source["referenced_name"] = key if type_key not in target: target[type_key] = list() elif type_key in target and type(target[type_key]) is not list: target[type_key] = [target[type_key]] target[type_key].append(source) target.update(value_to_change) try: exec("target_dictionary{}.update({})".format(path_to_adjust, target)) except: # Yes I know, this is against PEP8. pass except KeyError: pass
https://github.com/terraform-compliance/cli/issues/53
terraform-compliance v0.4.11 initiated Steps : /usr/local/lib/python2.7/site-packages/terraform_compliance/steps Features : /Users/demianginther/git/tf-modules/compliance TF Files : /var/folders/zf/f1h382nn35z3gd1kv92bw6r80000gn/T/tmpxTN1V9 (.) Reading terraform files. All HCL files look good. Running tests. Feature: Resources should be properly tagged # /Users/demianginther/git/tf-modules/compliance/tags.feature In order to keep track of resource ownership As engineers We'll enforce tagging on all resources 1 features (0 passed) 1 scenarios (0 passed) 3 steps (0 passed) Run 1547251063 finished within a moment Error: Hook 'load_terraform_data' from /usr/local/lib/python2.7/site-packages/terraform_compliance/steps/terrain.py:6 raised: 'SyntaxError: invalid syntax (<string>, line 1)' Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/radish/hookregistry.py", line 121, in call func(model, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/terraform_compliance/steps/terrain.py", line 12, in load_terraform_data enable_resource_mounting(tf_conf.terraform_config) File "/usr/local/lib/python2.7/site-packages/terraform_compliance/extensions/terraform_validate.py", line 29, in enable_resource_mounting enable_resource_mounting(tf_conf, sub_value, sub_resource) File "/usr/local/lib/python2.7/site-packages/terraform_compliance/extensions/terraform_validate.py", line 29, in enable_resource_mounting enable_resource_mounting(tf_conf, sub_value, sub_resource) File "/usr/local/lib/python2.7/site-packages/terraform_compliance/extensions/terraform_validate.py", line 37, in enable_resource_mounting change_value_in_dict(tf_conf, target, {source: processing_resource}) File "/usr/local/lib/python2.7/site-packages/terraform_compliance/common/helper.py", line 119, in change_value_in_dict target = eval('target_dictionary{}'.format(path_to_adjust)) File "<string>", line 1 target_dictionary["resource"]["!var"]["alb_enabled &amp;&amp; !var"]["double_elb_listener_enabled &amp;&amp; var"]["env == "prod" ? 1 : 0"] ^ SyntaxError: invalid syntax
SyntaxError
def make_statements(code, variables, dtype, optimise=True, blockname=""): """ make_statements(code, variables, dtype, optimise=True, blockname='') Turn a series of abstract code statements into Statement objects, inferring whether each line is a set/declare operation, whether the variables are constant or not, and handling the cacheing of subexpressions. Parameters ---------- code : str A (multi-line) string of statements. variables : dict-like A dictionary of with `Variable` and `Function` objects for every identifier used in the `code`. dtype : `dtype` The data type to use for temporary variables optimise : bool, optional Whether to optimise expressions, including pulling out loop invariant expressions and putting them in new scalar constants. Defaults to ``False``, since this function is also used just to in contexts where we are not interested by this kind of optimisation. For the main code generation stage, its value is set by the `codegen.loop_invariant_optimisations` preference. blockname : str, optional A name for the block (used to name intermediate variables to avoid name clashes when multiple blocks are used together) Returns ------- scalar_statements, vector_statements : (list of `Statement`, list of `Statement`) Lists with statements that are to be executed once and statements that are to be executed once for every neuron/synapse/... (or in a vectorised way) Notes ----- If ``optimise`` is ``True``, then the ``scalar_statements`` may include newly introduced scalar constants that have been identified as loop-invariant and have therefore been pulled out of the vector statements. The resulting statements will also use augmented assignments where possible, i.e. a statement such as ``w = w + 1`` will be replaced by ``w += 1``. Also, statements involving booleans will have additional information added to them (see `Statement` for details) describing how the statement can be reformulated as a sequence of if/then statements. Calls `~brian2.codegen.optimisation.optimise_statements`. """ code = strip_empty_lines(deindent(code)) lines = re.split(r"[;\n]", code) lines = [LineInfo(code=line) for line in lines if len(line)] # Do a copy so we can add stuff without altering the original dict variables = dict(variables) # we will do inference to work out which lines are := and which are = defined = set( k for k, v in variables.items() if not isinstance(v, AuxiliaryVariable) ) for line in lines: statement = None # parse statement into "var op expr" var, op, expr, comment = parse_statement(line.code) if var in variables and isinstance(variables[var], Subexpression): raise SyntaxError( "Illegal line '{line}' in abstract code. " "Cannot write to subexpression " "'{var}'.".format(line=line.code, var=var) ) if op == "=": if var not in defined: op = ":=" defined.add(var) if var not in variables: annotated_ast = brian_ast(expr, variables) is_scalar = annotated_ast.scalar if annotated_ast.dtype == "boolean": use_dtype = bool elif annotated_ast.dtype == "integer": use_dtype = int else: use_dtype = dtype new_var = AuxiliaryVariable(var, dtype=use_dtype, scalar=is_scalar) variables[var] = new_var elif not variables[var].is_boolean: sympy_expr = str_to_sympy(expr, variables) if variables[var].is_integer: sympy_var = sympy.Symbol(var, integer=True) else: sympy_var = sympy.Symbol(var, real=True) try: collected = sympy.collect( sympy_expr, sympy_var, exact=True, evaluate=False ) except AttributeError: # If something goes wrong during collection, e.g. collect # does not work for logical expressions collected = {1: sympy_expr} if ( len(collected) == 2 and set(collected.keys()) == {1, sympy_var} and collected[sympy_var] == 1 ): # We can replace this statement by a += assignment statement = Statement( var, "+=", sympy_to_str(collected[1]), comment, dtype=variables[var].dtype, scalar=variables[var].scalar, ) elif len(collected) == 1 and sympy_var in collected: # We can replace this statement by a *= assignment statement = Statement( var, "*=", sympy_to_str(collected[sympy_var]), comment, dtype=variables[var].dtype, scalar=variables[var].scalar, ) if statement is None: statement = Statement( var, op, expr, comment, dtype=variables[var].dtype, scalar=variables[var].scalar, ) line.statement = statement # for each line will give the variable being written to line.write = var # each line will give a set of variables which are read line.read = get_identifiers_recursively([expr], variables) # All writes to scalar variables must happen before writes to vector # variables scalar_write_done = False for line in lines: stmt = line.statement if stmt.op != ":=" and variables[stmt.var].scalar and scalar_write_done: raise SyntaxError( ( "All writes to scalar variables in a code block " "have to be made before writes to vector " "variables. Illegal write to %s." ) % line.write ) elif not variables[stmt.var].scalar: scalar_write_done = True # all variables which are written to at some point in the code block # used to determine whether they should be const or not all_write = set(line.write for line in lines) # backwards compute whether or not variables will be read again # note that will_read for a line gives the set of variables it will read # on the current line or subsequent ones. will_write gives the set of # variables that will be written after the current line will_read = set() will_write = set() for line in lines[::-1]: will_read = will_read.union(line.read) line.will_read = will_read.copy() line.will_write = will_write.copy() will_write.add(line.write) subexpressions = dict( (name, val) for name, val in variables.items() if isinstance(val, Subexpression) ) # Check that no scalar subexpression refers to a vectorised function # (e.g. rand()) -- otherwise it would be differently interpreted depending # on whether it is used in a scalar or a vector context (i.e., even though # the subexpression is supposed to be scalar, it would be vectorised when # used as part of non-scalar expressions) for name, subexpr in subexpressions.items(): if subexpr.scalar: identifiers = get_identifiers(subexpr.expr) for identifier in identifiers: if identifier in variables and getattr( variables[identifier], "auto_vectorise", False ): raise SyntaxError( ( "The scalar subexpression {} refers to " "the implicitly vectorised function {} " "-- this is not allowed since it leads " "to different interpretations of this " "subexpression depending on whether it " "is used in a scalar or vector " "context." ).format(name, identifier) ) # sort subexpressions into an order so that subexpressions that don't depend # on other subexpressions are first subexpr_deps = dict( (name, [dep for dep in subexpr.identifiers if dep in subexpressions]) for name, subexpr in subexpressions.items() ) sorted_subexpr_vars = topsort(subexpr_deps) statements = [] # none are yet defined (or declared) subdefined = dict((name, None) for name in subexpressions) for line in lines: stmt = line.statement read = line.read write = line.write will_read = line.will_read will_write = line.will_write # update/define all subexpressions needed by this statement for var in sorted_subexpr_vars: if var not in read: continue subexpression = subexpressions[var] # if already defined/declared if subdefined[var] == "constant": continue elif subdefined[var] == "variable": op = "=" constant = False else: op = ":=" # check if the referred variables ever change ids = subexpression.identifiers constant = all(v not in will_write for v in ids) subdefined[var] = "constant" if constant else "variable" statement = Statement( var, op, subexpression.expr, comment="", dtype=variables[var].dtype, constant=constant, subexpression=True, scalar=variables[var].scalar, ) statements.append(statement) var, op, expr, comment = stmt.var, stmt.op, stmt.expr, stmt.comment # constant only if we are declaring a new variable and we will not # write to it again constant = op == ":=" and var not in will_write statement = Statement( var, op, expr, comment, dtype=variables[var].dtype, constant=constant, scalar=variables[var].scalar, ) statements.append(statement) scalar_statements = [s for s in statements if s.scalar] vector_statements = [s for s in statements if not s.scalar] if optimise and prefs.codegen.loop_invariant_optimisations: scalar_statements, vector_statements = optimise_statements( scalar_statements, vector_statements, variables, blockname=blockname ) return scalar_statements, vector_statements
def make_statements(code, variables, dtype, optimise=True, blockname=""): """ make_statements(code, variables, dtype, optimise=True, blockname='') Turn a series of abstract code statements into Statement objects, inferring whether each line is a set/declare operation, whether the variables are constant or not, and handling the cacheing of subexpressions. Parameters ---------- code : str A (multi-line) string of statements. variables : dict-like A dictionary of with `Variable` and `Function` objects for every identifier used in the `code`. dtype : `dtype` The data type to use for temporary variables optimise : bool, optional Whether to optimise expressions, including pulling out loop invariant expressions and putting them in new scalar constants. Defaults to ``False``, since this function is also used just to in contexts where we are not interested by this kind of optimisation. For the main code generation stage, its value is set by the `codegen.loop_invariant_optimisations` preference. blockname : str, optional A name for the block (used to name intermediate variables to avoid name clashes when multiple blocks are used together) Returns ------- scalar_statements, vector_statements : (list of `Statement`, list of `Statement`) Lists with statements that are to be executed once and statements that are to be executed once for every neuron/synapse/... (or in a vectorised way) Notes ----- If ``optimise`` is ``True``, then the ``scalar_statements`` may include newly introduced scalar constants that have been identified as loop-invariant and have therefore been pulled out of the vector statements. The resulting statements will also use augmented assignments where possible, i.e. a statement such as ``w = w + 1`` will be replaced by ``w += 1``. Also, statements involving booleans will have additional information added to them (see `Statement` for details) describing how the statement can be reformulated as a sequence of if/then statements. Calls `~brian2.codegen.optimisation.optimise_statements`. """ code = strip_empty_lines(deindent(code)) lines = re.split(r"[;\n]", code) lines = [LineInfo(code=line) for line in lines if len(line)] # Do a copy so we can add stuff without altering the original dict variables = dict(variables) # we will do inference to work out which lines are := and which are = defined = set( k for k, v in variables.items() if not isinstance(v, AuxiliaryVariable) ) for line in lines: statement = None # parse statement into "var op expr" var, op, expr, comment = parse_statement(line.code) if var in variables and isinstance(variables[var], Subexpression): raise SyntaxError( "Illegal line '{line}' in abstract code. " "Cannot write to subexpression " "'{var}'.".format(line=line.code, var=var) ) if op == "=": if var not in defined: op = ":=" defined.add(var) if var not in variables: annotated_ast = brian_ast(expr, variables) is_scalar = annotated_ast.scalar if annotated_ast.dtype == "boolean": use_dtype = bool elif annotated_ast.dtype == "integer": use_dtype = int else: use_dtype = dtype new_var = AuxiliaryVariable(var, dtype=use_dtype, scalar=is_scalar) variables[var] = new_var elif not variables[var].is_boolean: sympy_expr = str_to_sympy(expr, variables) sympy_var = sympy.Symbol(var, real=True) try: collected = sympy.collect( sympy_expr, sympy_var, exact=True, evaluate=False ) except AttributeError: # If something goes wrong during collection, e.g. collect # does not work for logical expressions collected = {1: sympy_expr} if ( len(collected) == 2 and set(collected.keys()) == {1, sympy_var} and collected[sympy_var] == 1 ): # We can replace this statement by a += assignment statement = Statement( var, "+=", sympy_to_str(collected[1]), comment, dtype=variables[var].dtype, scalar=variables[var].scalar, ) elif len(collected) == 1 and sympy_var in collected: # We can replace this statement by a *= assignment statement = Statement( var, "*=", sympy_to_str(collected[sympy_var]), comment, dtype=variables[var].dtype, scalar=variables[var].scalar, ) if statement is None: statement = Statement( var, op, expr, comment, dtype=variables[var].dtype, scalar=variables[var].scalar, ) line.statement = statement # for each line will give the variable being written to line.write = var # each line will give a set of variables which are read line.read = get_identifiers_recursively([expr], variables) # All writes to scalar variables must happen before writes to vector # variables scalar_write_done = False for line in lines: stmt = line.statement if stmt.op != ":=" and variables[stmt.var].scalar and scalar_write_done: raise SyntaxError( ( "All writes to scalar variables in a code block " "have to be made before writes to vector " "variables. Illegal write to %s." ) % line.write ) elif not variables[stmt.var].scalar: scalar_write_done = True # all variables which are written to at some point in the code block # used to determine whether they should be const or not all_write = set(line.write for line in lines) # backwards compute whether or not variables will be read again # note that will_read for a line gives the set of variables it will read # on the current line or subsequent ones. will_write gives the set of # variables that will be written after the current line will_read = set() will_write = set() for line in lines[::-1]: will_read = will_read.union(line.read) line.will_read = will_read.copy() line.will_write = will_write.copy() will_write.add(line.write) subexpressions = dict( (name, val) for name, val in variables.items() if isinstance(val, Subexpression) ) # Check that no scalar subexpression refers to a vectorised function # (e.g. rand()) -- otherwise it would be differently interpreted depending # on whether it is used in a scalar or a vector context (i.e., even though # the subexpression is supposed to be scalar, it would be vectorised when # used as part of non-scalar expressions) for name, subexpr in subexpressions.items(): if subexpr.scalar: identifiers = get_identifiers(subexpr.expr) for identifier in identifiers: if identifier in variables and getattr( variables[identifier], "auto_vectorise", False ): raise SyntaxError( ( "The scalar subexpression {} refers to " "the implicitly vectorised function {} " "-- this is not allowed since it leads " "to different interpretations of this " "subexpression depending on whether it " "is used in a scalar or vector " "context." ).format(name, identifier) ) # sort subexpressions into an order so that subexpressions that don't depend # on other subexpressions are first subexpr_deps = dict( (name, [dep for dep in subexpr.identifiers if dep in subexpressions]) for name, subexpr in subexpressions.items() ) sorted_subexpr_vars = topsort(subexpr_deps) statements = [] # none are yet defined (or declared) subdefined = dict((name, None) for name in subexpressions) for line in lines: stmt = line.statement read = line.read write = line.write will_read = line.will_read will_write = line.will_write # update/define all subexpressions needed by this statement for var in sorted_subexpr_vars: if var not in read: continue subexpression = subexpressions[var] # if already defined/declared if subdefined[var] == "constant": continue elif subdefined[var] == "variable": op = "=" constant = False else: op = ":=" # check if the referred variables ever change ids = subexpression.identifiers constant = all(v not in will_write for v in ids) subdefined[var] = "constant" if constant else "variable" statement = Statement( var, op, subexpression.expr, comment="", dtype=variables[var].dtype, constant=constant, subexpression=True, scalar=variables[var].scalar, ) statements.append(statement) var, op, expr, comment = stmt.var, stmt.op, stmt.expr, stmt.comment # constant only if we are declaring a new variable and we will not # write to it again constant = op == ":=" and var not in will_write statement = Statement( var, op, expr, comment, dtype=variables[var].dtype, constant=constant, scalar=variables[var].scalar, ) statements.append(statement) scalar_statements = [s for s in statements if s.scalar] vector_statements = [s for s in statements if not s.scalar] if optimise and prefs.codegen.loop_invariant_optimisations: scalar_statements, vector_statements = optimise_statements( scalar_statements, vector_statements, variables, blockname=blockname ) return scalar_statements, vector_statements
https://github.com/brian-team/brian2/issues/1199
BrianObjectException: Original error and traceback: Traceback (most recent call last): File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/codegen/runtime/numpy_rt/numpy_rt.py", line 246, in run exec(self.compiled_code, self.namespace) File "(string)", line 19, in <module> File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/input/timedarray.py", line 230, in unitless_timed_array_func return values[timestep, i] IndexError: arrays used as indices must be of integer (or boolean) type Error encountered with object named "neurongroup". Object was created here (most recent call only, full details in debug log): File "<ipython-input-6-321ca0774a4a>", line 18, in <module> method='euler') An exception occured during the execution of code object neurongroup_stateupdater_codeobject. The error was raised in the following line: _v = (_lio_1 * I(t, 2.0 + i)) + v IndexError: arrays used as indices must be of integer (or boolean) type (See above for original error message and traceback.)
IndexError
def get_substituted_expressions(self, variables=None, include_subexpressions=False): """ Return a list of ``(varname, expr)`` tuples, containing all differential equations (and optionally subexpressions) with all the subexpression variables substituted with the respective expressions. Parameters ---------- variables : dict, optional A mapping of variable names to `Variable`/`Function` objects. include_subexpressions : bool Whether also to return substituted subexpressions. Defaults to ``False``. Returns ------- expr_tuples : list of (str, `CodeString`) A list of ``(varname, expr)`` tuples, where ``expr`` is a `CodeString` object with all subexpression variables substituted with the respective expression. """ if self._substituted_expressions is None: self._substituted_expressions = [] substitutions = {} for eq in self.ordered: # Skip parameters if eq.expr is None: continue new_sympy_expr = str_to_sympy(eq.expr.code, variables).xreplace( substitutions ) new_str_expr = sympy_to_str(new_sympy_expr) expr = Expression(new_str_expr) if eq.type == SUBEXPRESSION: if eq.var_type == INTEGER: sympy_var = sympy.Symbol(eq.varname, integer=True) else: sympy_var = sympy.Symbol(eq.varname, real=True) substitutions.update({sympy_var: str_to_sympy(expr.code, variables)}) self._substituted_expressions.append((eq.varname, expr)) elif eq.type == DIFFERENTIAL_EQUATION: # a differential equation that we have to check self._substituted_expressions.append((eq.varname, expr)) else: raise AssertionError("Unknown equation type %s" % eq.type) if include_subexpressions: return self._substituted_expressions else: return [ (name, expr) for name, expr in self._substituted_expressions if self[name].type == DIFFERENTIAL_EQUATION ]
def get_substituted_expressions(self, variables=None, include_subexpressions=False): """ Return a list of ``(varname, expr)`` tuples, containing all differential equations (and optionally subexpressions) with all the subexpression variables substituted with the respective expressions. Parameters ---------- variables : dict, optional A mapping of variable names to `Variable`/`Function` objects. include_subexpressions : bool Whether also to return substituted subexpressions. Defaults to ``False``. Returns ------- expr_tuples : list of (str, `CodeString`) A list of ``(varname, expr)`` tuples, where ``expr`` is a `CodeString` object with all subexpression variables substituted with the respective expression. """ if self._substituted_expressions is None: self._substituted_expressions = [] substitutions = {} for eq in self.ordered: # Skip parameters if eq.expr is None: continue new_sympy_expr = str_to_sympy(eq.expr.code, variables).xreplace( substitutions ) new_str_expr = sympy_to_str(new_sympy_expr) expr = Expression(new_str_expr) if eq.type == SUBEXPRESSION: substitutions.update( { sympy.Symbol(eq.varname, real=True): str_to_sympy( expr.code, variables ) } ) self._substituted_expressions.append((eq.varname, expr)) elif eq.type == DIFFERENTIAL_EQUATION: # a differential equation that we have to check self._substituted_expressions.append((eq.varname, expr)) else: raise AssertionError("Unknown equation type %s" % eq.type) if include_subexpressions: return self._substituted_expressions else: return [ (name, expr) for name, expr in self._substituted_expressions if self[name].type == DIFFERENTIAL_EQUATION ]
https://github.com/brian-team/brian2/issues/1199
BrianObjectException: Original error and traceback: Traceback (most recent call last): File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/codegen/runtime/numpy_rt/numpy_rt.py", line 246, in run exec(self.compiled_code, self.namespace) File "(string)", line 19, in <module> File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/input/timedarray.py", line 230, in unitless_timed_array_func return values[timestep, i] IndexError: arrays used as indices must be of integer (or boolean) type Error encountered with object named "neurongroup". Object was created here (most recent call only, full details in debug log): File "<ipython-input-6-321ca0774a4a>", line 18, in <module> method='euler') An exception occured during the execution of code object neurongroup_stateupdater_codeobject. The error was raised in the following line: _v = (_lio_1 * I(t, 2.0 + i)) + v IndexError: arrays used as indices must be of integer (or boolean) type (See above for original error message and traceback.)
IndexError
def render_node(self, node): nodename = node.__class__.__name__ methname = "render_" + nodename try: return getattr(self, methname)(node) except AttributeError: raise SyntaxError("Unknown syntax: " + nodename)
def render_node(self, node): nodename = node.__class__.__name__ methname = "render_" + nodename try: return getattr(self, methname)(node) except AttributeError: raise raise SyntaxError("Unknown syntax: " + nodename)
https://github.com/brian-team/brian2/issues/1199
BrianObjectException: Original error and traceback: Traceback (most recent call last): File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/codegen/runtime/numpy_rt/numpy_rt.py", line 246, in run exec(self.compiled_code, self.namespace) File "(string)", line 19, in <module> File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/input/timedarray.py", line 230, in unitless_timed_array_func return values[timestep, i] IndexError: arrays used as indices must be of integer (or boolean) type Error encountered with object named "neurongroup". Object was created here (most recent call only, full details in debug log): File "<ipython-input-6-321ca0774a4a>", line 18, in <module> method='euler') An exception occured during the execution of code object neurongroup_stateupdater_codeobject. The error was raised in the following line: _v = (_lio_1 * I(t, 2.0 + i)) + v IndexError: arrays used as indices must be of integer (or boolean) type (See above for original error message and traceback.)
IndexError
def render_Num(self, node): if isinstance(node.n, numbers.Integral): return sympy.Integer(node.n) else: return sympy.Float(node.n)
def render_Num(self, node): return sympy.Float(node.n)
https://github.com/brian-team/brian2/issues/1199
BrianObjectException: Original error and traceback: Traceback (most recent call last): File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/codegen/runtime/numpy_rt/numpy_rt.py", line 246, in run exec(self.compiled_code, self.namespace) File "(string)", line 19, in <module> File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/input/timedarray.py", line 230, in unitless_timed_array_func return values[timestep, i] IndexError: arrays used as indices must be of integer (or boolean) type Error encountered with object named "neurongroup". Object was created here (most recent call only, full details in debug log): File "<ipython-input-6-321ca0774a4a>", line 18, in <module> method='euler') An exception occured during the execution of code object neurongroup_stateupdater_codeobject. The error was raised in the following line: _v = (_lio_1 * I(t, 2.0 + i)) + v IndexError: arrays used as indices must be of integer (or boolean) type (See above for original error message and traceback.)
IndexError
def __call__(self, eqs, variables=None, method_options=None): """ Apply a state updater description to model equations. Parameters ---------- eqs : `Equations` The equations describing the model variables: dict-like, optional The `Variable` objects for the model. Ignored by the explicit state updater. method_options : dict, optional Additional options to the state updater (not used at the moment for the explicit state updaters). Examples -------- >>> from brian2 import * >>> eqs = Equations('dv/dt = -v / tau : volt') >>> print(euler(eqs)) _v = -dt*v/tau + v v = _v >>> print(rk4(eqs)) __k_1_v = -dt*v/tau __k_2_v = -dt*(__k_1_v/2 + v)/tau __k_3_v = -dt*(__k_2_v/2 + v)/tau __k_4_v = -dt*(__k_3_v + v)/tau _v = __k_1_v/6 + __k_2_v/3 + __k_3_v/3 + __k_4_v/6 + v v = _v """ method_options = extract_method_options(method_options, {}) # Non-stochastic numerical integrators should work for all equations, # except for stochastic equations if eqs.is_stochastic and self.stochastic is None: raise UnsupportedEquationsException( "Cannot integrate stochastic equations with this state updater." ) if self.custom_check: self.custom_check(eqs, variables) # The final list of statements statements = [] stochastic_variables = eqs.stochastic_variables # The variables for the intermediate results in the state updater # description, e.g. the variable k in rk2 intermediate_vars = [var for var, expr in self.statements] # A dictionary mapping all the variables in the equations to their # sympy representations eq_variables = dict(((var, _symbol(var)) for var in eqs.eq_names)) # Generate the random numbers for the stochastic variables for stochastic_variable in stochastic_variables: statements.append(stochastic_variable + " = " + "dt**.5 * randn()") substituted_expressions = eqs.get_substituted_expressions(variables) # Process the intermediate statements in the stateupdater description for intermediate_var, intermediate_expr in self.statements: # Split the expression into a non-stochastic and a stochastic part non_stochastic_expr, stochastic_expr = split_expression(intermediate_expr) # Execute the statement by appropriately replacing the functions f # and g and the variable x for every equation in the model. # We use the model equations where the subexpressions have # already been substituted into the model equations. for var, expr in substituted_expressions: for xi in stochastic_variables: RHS = self._generate_RHS( eqs, var, eq_variables, intermediate_vars, expr, non_stochastic_expr, stochastic_expr, xi, ) statements.append(intermediate_var + "_" + var + "_" + xi + " = " + RHS) if not stochastic_variables: # no stochastic variables RHS = self._generate_RHS( eqs, var, eq_variables, intermediate_vars, expr, non_stochastic_expr, stochastic_expr, ) statements.append(intermediate_var + "_" + var + " = " + RHS) # Process the "return" line of the stateupdater description non_stochastic_expr, stochastic_expr = split_expression(self.output) if eqs.is_stochastic and ( self.stochastic != "multiplicative" and eqs.stochastic_type == "multiplicative" ): # The equations are marked as having multiplicative noise and the # current state updater does not support such equations. However, # it is possible that the equations do not use multiplicative noise # at all. They could depend on time via a function that is constant # over a single time step (most likely, a TimedArray). In that case # we can integrate the equations dt_value = variables["dt"].get_value()[0] if "dt" in variables else None for _, expr in substituted_expressions: _, stoch = expr.split_stochastic() if stoch is None: continue # There could be more than one stochastic variable (e.g. xi_1, xi_2) for _, stoch_expr in stoch.items(): sympy_expr = str_to_sympy(stoch_expr.code) # The equation really has multiplicative noise, if it depends # on time (and not only via a function that is constant # over dt), or if it depends on another variable defined # via differential equations. if not is_constant_over_dt(sympy_expr, variables, dt_value) or len( stoch_expr.identifiers & eqs.diff_eq_names ): raise UnsupportedEquationsException( "Cannot integrate " "equations with " "multiplicative noise with " "this state updater." ) # Assign a value to all the model variables described by differential # equations for var, expr in substituted_expressions: RHS = self._generate_RHS( eqs, var, eq_variables, intermediate_vars, expr, non_stochastic_expr, stochastic_expr, stochastic_variables, ) statements.append("_" + var + " = " + RHS) # Assign everything to the final variables for var, expr in substituted_expressions: statements.append(var + " = " + "_" + var) return "\n".join(statements)
def __call__(self, eqs, variables=None, method_options=None): """ Apply a state updater description to model equations. Parameters ---------- eqs : `Equations` The equations describing the model variables: dict-like, optional The `Variable` objects for the model. Ignored by the explicit state updater. method_options : dict, optional Additional options to the state updater (not used at the moment for the explicit state updaters). Examples -------- >>> from brian2 import * >>> eqs = Equations('dv/dt = -v / tau : volt') >>> print(euler(eqs)) _v = -dt*v/tau + v v = _v >>> print(rk4(eqs)) __k_1_v = -dt*v/tau __k_2_v = -dt*(0.5*__k_1_v + v)/tau __k_3_v = -dt*(0.5*__k_2_v + v)/tau __k_4_v = -dt*(__k_3_v + v)/tau _v = 0.166666666666667*__k_1_v + 0.333333333333333*__k_2_v + 0.333333333333333*__k_3_v + 0.166666666666667*__k_4_v + v v = _v """ method_options = extract_method_options(method_options, {}) # Non-stochastic numerical integrators should work for all equations, # except for stochastic equations if eqs.is_stochastic and self.stochastic is None: raise UnsupportedEquationsException( "Cannot integrate stochastic equations with this state updater." ) if self.custom_check: self.custom_check(eqs, variables) # The final list of statements statements = [] stochastic_variables = eqs.stochastic_variables # The variables for the intermediate results in the state updater # description, e.g. the variable k in rk2 intermediate_vars = [var for var, expr in self.statements] # A dictionary mapping all the variables in the equations to their # sympy representations eq_variables = dict(((var, _symbol(var)) for var in eqs.eq_names)) # Generate the random numbers for the stochastic variables for stochastic_variable in stochastic_variables: statements.append(stochastic_variable + " = " + "dt**.5 * randn()") substituted_expressions = eqs.get_substituted_expressions(variables) # Process the intermediate statements in the stateupdater description for intermediate_var, intermediate_expr in self.statements: # Split the expression into a non-stochastic and a stochastic part non_stochastic_expr, stochastic_expr = split_expression(intermediate_expr) # Execute the statement by appropriately replacing the functions f # and g and the variable x for every equation in the model. # We use the model equations where the subexpressions have # already been substituted into the model equations. for var, expr in substituted_expressions: for xi in stochastic_variables: RHS = self._generate_RHS( eqs, var, eq_variables, intermediate_vars, expr, non_stochastic_expr, stochastic_expr, xi, ) statements.append(intermediate_var + "_" + var + "_" + xi + " = " + RHS) if not stochastic_variables: # no stochastic variables RHS = self._generate_RHS( eqs, var, eq_variables, intermediate_vars, expr, non_stochastic_expr, stochastic_expr, ) statements.append(intermediate_var + "_" + var + " = " + RHS) # Process the "return" line of the stateupdater description non_stochastic_expr, stochastic_expr = split_expression(self.output) if eqs.is_stochastic and ( self.stochastic != "multiplicative" and eqs.stochastic_type == "multiplicative" ): # The equations are marked as having multiplicative noise and the # current state updater does not support such equations. However, # it is possible that the equations do not use multiplicative noise # at all. They could depend on time via a function that is constant # over a single time step (most likely, a TimedArray). In that case # we can integrate the equations dt_value = variables["dt"].get_value()[0] if "dt" in variables else None for _, expr in substituted_expressions: _, stoch = expr.split_stochastic() if stoch is None: continue # There could be more than one stochastic variable (e.g. xi_1, xi_2) for _, stoch_expr in stoch.items(): sympy_expr = str_to_sympy(stoch_expr.code) # The equation really has multiplicative noise, if it depends # on time (and not only via a function that is constant # over dt), or if it depends on another variable defined # via differential equations. if not is_constant_over_dt(sympy_expr, variables, dt_value) or len( stoch_expr.identifiers & eqs.diff_eq_names ): raise UnsupportedEquationsException( "Cannot integrate " "equations with " "multiplicative noise with " "this state updater." ) # Assign a value to all the model variables described by differential # equations for var, expr in substituted_expressions: RHS = self._generate_RHS( eqs, var, eq_variables, intermediate_vars, expr, non_stochastic_expr, stochastic_expr, stochastic_variables, ) statements.append("_" + var + " = " + RHS) # Assign everything to the final variables for var, expr in substituted_expressions: statements.append(var + " = " + "_" + var) return "\n".join(statements)
https://github.com/brian-team/brian2/issues/1199
BrianObjectException: Original error and traceback: Traceback (most recent call last): File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/codegen/runtime/numpy_rt/numpy_rt.py", line 246, in run exec(self.compiled_code, self.namespace) File "(string)", line 19, in <module> File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/input/timedarray.py", line 230, in unitless_timed_array_func return values[timestep, i] IndexError: arrays used as indices must be of integer (or boolean) type Error encountered with object named "neurongroup". Object was created here (most recent call only, full details in debug log): File "<ipython-input-6-321ca0774a4a>", line 18, in <module> method='euler') An exception occured during the execution of code object neurongroup_stateupdater_codeobject. The error was raised in the following line: _v = (_lio_1 * I(t, 2.0 + i)) + v IndexError: arrays used as indices must be of integer (or boolean) type (See above for original error message and traceback.)
IndexError
def get_conditionally_linear_system(eqs, variables=None): ''' Convert equations into a linear system using sympy. Parameters ---------- eqs : `Equations` The model equations. Returns ------- coefficients : dict of (sympy expression, sympy expression) tuples For every variable x, a tuple (M, B) containing the coefficients M and B (as sympy expressions) for M * x + B Raises ------ ValueError If one of the equations cannot be converted into a M * x + B form. Examples -------- >>> from brian2 import Equations >>> eqs = Equations(""" ... dv/dt = (-v + w**2.0) / tau : 1 ... dw/dt = -w / tau : 1 ... """) >>> system = get_conditionally_linear_system(eqs) >>> print(system['v']) (-1/tau, w**2.0/tau) >>> print(system['w']) (-1/tau, 0) ''' diff_eqs = eqs.get_substituted_expressions(variables) coefficients = {} for name, expr in diff_eqs: var = sp.Symbol(name, real=True) s_expr = str_to_sympy(expr.code, variables).expand() if s_expr.has(var): # Factor out the variable s_expr = sp.collect(s_expr, var, evaluate=False) if len(s_expr) > 2 or var not in s_expr: raise ValueError( ( 'The expression "%s", defining the variable %s, ' "could not be separated into linear components" ) % (expr, name) ) coefficients[name] = (s_expr[var], s_expr.get(1, 0)) else: coefficients[name] = (0, s_expr) return coefficients
def get_conditionally_linear_system(eqs, variables=None): ''' Convert equations into a linear system using sympy. Parameters ---------- eqs : `Equations` The model equations. Returns ------- coefficients : dict of (sympy expression, sympy expression) tuples For every variable x, a tuple (M, B) containing the coefficients M and B (as sympy expressions) for M * x + B Raises ------ ValueError If one of the equations cannot be converted into a M * x + B form. Examples -------- >>> from brian2 import Equations >>> eqs = Equations(""" ... dv/dt = (-v + w**2) / tau : 1 ... dw/dt = -w / tau : 1 ... """) >>> system = get_conditionally_linear_system(eqs) >>> print(system['v']) (-1/tau, w**2.0/tau) >>> print(system['w']) (-1/tau, 0) ''' diff_eqs = eqs.get_substituted_expressions(variables) coefficients = {} for name, expr in diff_eqs: var = sp.Symbol(name, real=True) s_expr = str_to_sympy(expr.code, variables).expand() if s_expr.has(var): # Factor out the variable s_expr = sp.collect(s_expr, var, evaluate=False) if len(s_expr) > 2 or var not in s_expr: raise ValueError( ( 'The expression "%s", defining the variable %s, ' "could not be separated into linear components" ) % (expr, name) ) coefficients[name] = (s_expr[var], s_expr.get(1, 0)) else: coefficients[name] = (0, s_expr) return coefficients
https://github.com/brian-team/brian2/issues/1199
BrianObjectException: Original error and traceback: Traceback (most recent call last): File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/codegen/runtime/numpy_rt/numpy_rt.py", line 246, in run exec(self.compiled_code, self.namespace) File "(string)", line 19, in <module> File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/input/timedarray.py", line 230, in unitless_timed_array_func return values[timestep, i] IndexError: arrays used as indices must be of integer (or boolean) type Error encountered with object named "neurongroup". Object was created here (most recent call only, full details in debug log): File "<ipython-input-6-321ca0774a4a>", line 18, in <module> method='euler') An exception occured during the execution of code object neurongroup_stateupdater_codeobject. The error was raised in the following line: _v = (_lio_1 * I(t, 2.0 + i)) + v IndexError: arrays used as indices must be of integer (or boolean) type (See above for original error message and traceback.)
IndexError
def __init__(self): super(CPPStandaloneDevice, self).__init__() #: Dictionary mapping `ArrayVariable` objects to their globally #: unique name self.arrays = {} #: Dictionary mapping `ArrayVariable` objects to their value or to #: ``None`` if the value (potentially) depends on executed code. This #: mechanism allows to access state variables in standalone mode if #: their value is known at run time self.array_cache = {} #: List of all dynamic arrays #: Dictionary mapping `DynamicArrayVariable` objects with 1 dimension to #: their globally unique name self.dynamic_arrays = {} #: Dictionary mapping `DynamicArrayVariable` objects with 2 dimensions #: to their globally unique name self.dynamic_arrays_2d = {} #: List of all arrays to be filled with zeros (list of (var, varname) ) self.zero_arrays = [] #: List of all arrays to be filled with numbers (list of #: (var, varname, start) tuples self.arange_arrays = [] #: Whether the simulation has been run self.has_been_run = False #: Whether a run should trigger a build self.build_on_run = False #: build options self.build_options = None #: The directory which contains the generated code and results self.project_dir = None #: Whether to generate profiling information (stored in an instance #: variable to be accessible during CodeObject generation) self.enable_profiling = False #: CodeObjects that use profiling (users can potentially enable #: profiling only for a subset of runs) self.profiled_codeobjects = [] #: Dict of all static saved arrays self.static_arrays = {} self.code_objects = {} self.main_queue = [] self.runfuncs = {} self.networks = set() self.static_array_specs = [] self.report_func = "" self.synapses = [] #: Code lines that have been manually added with `device.insert_code` #: Dictionary mapping slot names to lists of lines. #: Note that the main slot is handled separately as part of `main_queue` self.code_lines = { "before_start": [], "after_start": [], "before_end": [], "after_end": [], } self.clocks = set([]) self.extra_compile_args = [] self.define_macros = [] self.headers = [] self.include_dirs = ["brianlib/randomkit"] if sys.platform == "win32": self.include_dirs += [os.path.join(sys.prefix, "Library", "include")] else: self.include_dirs += [os.path.join(sys.prefix, "include")] self.library_dirs = ["brianlib/randomkit"] if sys.platform == "win32": self.library_dirs += [os.path.join(sys.prefix, "Library", "Lib")] else: self.library_dirs += [os.path.join(sys.prefix, "lib")] self.runtime_library_dirs = [] if sys.platform.startswith("linux"): self.runtime_library_dirs += [os.path.join(sys.prefix, "lib")] self.run_environment_variables = {} if sys.platform.startswith("darwin"): if "DYLD_LIBRARY_PATH" in os.environ: dyld_library_path = ( os.environ["DYLD_LIBRARY_PATH"] + ":" + os.path.join(sys.prefix, "lib") ) else: dyld_library_path = os.path.join(sys.prefix, "lib") self.run_environment_variables["DYLD_LIBRARY_PATH"] = dyld_library_path self.libraries = [] if sys.platform == "win32": self.libraries += ["advapi32"] self.extra_link_args = [] self.writer = None
def __init__(self): super(CPPStandaloneDevice, self).__init__() #: Dictionary mapping `ArrayVariable` objects to their globally #: unique name self.arrays = {} #: Dictionary mapping `ArrayVariable` objects to their value or to #: ``None`` if the value (potentially) depends on executed code. This #: mechanism allows to access state variables in standalone mode if #: their value is known at run time self.array_cache = {} #: List of all dynamic arrays #: Dictionary mapping `DynamicArrayVariable` objects with 1 dimension to #: their globally unique name self.dynamic_arrays = {} #: Dictionary mapping `DynamicArrayVariable` objects with 2 dimensions #: to their globally unique name self.dynamic_arrays_2d = {} #: List of all arrays to be filled with zeros (list of (var, varname) ) self.zero_arrays = [] #: List of all arrays to be filled with numbers (list of #: (var, varname, start) tuples self.arange_arrays = [] #: Whether the simulation has been run self.has_been_run = False #: Whether a run should trigger a build self.build_on_run = False #: build options self.build_options = None #: The directory which contains the generated code and results self.project_dir = None #: Whether to generate profiling information (stored in an instance #: variable to be accessible during CodeObject generation) self.enable_profiling = False #: CodeObjects that use profiling (users can potentially enable #: profiling only for a subset of runs) self.profiled_codeobjects = [] #: Dict of all static saved arrays self.static_arrays = {} self.code_objects = {} self.main_queue = [] self.runfuncs = {} self.networks = [] self.net_synapses = [] self.static_array_specs = [] self.report_func = "" self.synapses = [] #: Code lines that have been manually added with `device.insert_code` #: Dictionary mapping slot names to lists of lines. #: Note that the main slot is handled separately as part of `main_queue` self.code_lines = { "before_start": [], "after_start": [], "before_end": [], "after_end": [], } self.clocks = set([]) self.extra_compile_args = [] self.define_macros = [] self.headers = [] self.include_dirs = ["brianlib/randomkit"] if sys.platform == "win32": self.include_dirs += [os.path.join(sys.prefix, "Library", "include")] else: self.include_dirs += [os.path.join(sys.prefix, "include")] self.library_dirs = ["brianlib/randomkit"] if sys.platform == "win32": self.library_dirs += [os.path.join(sys.prefix, "Library", "Lib")] else: self.library_dirs += [os.path.join(sys.prefix, "lib")] self.runtime_library_dirs = [] if sys.platform.startswith("linux"): self.runtime_library_dirs += [os.path.join(sys.prefix, "lib")] self.run_environment_variables = {} if sys.platform.startswith("darwin"): if "DYLD_LIBRARY_PATH" in os.environ: dyld_library_path = ( os.environ["DYLD_LIBRARY_PATH"] + ":" + os.path.join(sys.prefix, "lib") ) else: dyld_library_path = os.path.join(sys.prefix, "lib") self.run_environment_variables["DYLD_LIBRARY_PATH"] = dyld_library_path self.libraries = [] if sys.platform == "win32": self.libraries += ["advapi32"] self.extra_link_args = [] self.writer = None
https://github.com/brian-team/brian2/issues/1189
ERROR Brian 2 encountered an unexpected error. If you think this is bug in Brian 2, please report this issue either to the mailing list at <http://groups.google.com/group/brian-development/>, or to the issue tracker at <https://github.com/brian-team/brian2/issues>. Please include this file with debug information in your report: /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_debug_1uynejn5.log Additionally, you can also include a copy of the script that was run, available at: /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_script_m_84dmg4.py You can also include a copy of the redirected std stream outputs, available at /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_stdout_d2yd1ugv.log and /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_stderr_xkxqltw0.log Thanks! [brian2] Traceback (most recent call last): File "/Users/fpbatta/src/assembly_sequences/scripts/run_simulation_simple.py", line 69, in <module> nn1 = network_sim() File "/Users/fpbatta/src/assembly_sequences/scripts/run_simulation_simple.py", line 59, in network_sim bb.get_device().build(directory='PETH_standalone', compile=True, run=True, debug=False) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/device.py", line 1265, in build self.generate_objects_source(self.writer, self.arange_arrays, File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/device.py", line 633, in generate_objects_source arr_tmp = self.code_object_class().templater.objects( File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/codegen/templates.py", line 210, in __call__ return MultiTemplate(module) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/codegen/templates.py", line 226, in __init__ s = autoindent_postfilter(str(f())) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 675, in __call__ return self._invoke(arguments, autoescape) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 679, in _invoke rv = self._func(*arguments) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/templates/objects.cpp", line 122, in macro if(f{{name}}.is_open()) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 747, in _fail_with_undefined_error raise self._undefined_exception(self._undefined_message) jinja2.exceptions.UndefinedError: dict object has no element <DynamicArrayVariable(dimensions=Dimension(), dtype=int32, scalar=False, constant=True, read_only=True)>
jinja2.exceptions.UndefinedError
def build( self, directory="output", compile=True, run=True, debug=False, clean=False, with_output=True, additional_source_files=None, run_args=None, direct_call=True, **kwds, ): """ Build the project TODO: more details Parameters ---------- directory : str, optional The output directory to write the project to, any existing files will be overwritten. If the given directory name is ``None``, then a temporary directory will be used (used in the test suite to avoid problems when running several tests in parallel). Defaults to ``'output'``. compile : bool, optional Whether or not to attempt to compile the project. Defaults to ``True``. run : bool, optional Whether or not to attempt to run the built project if it successfully builds. Defaults to ``True``. debug : bool, optional Whether to compile in debug mode. Defaults to ``False``. with_output : bool, optional Whether or not to show the ``stdout`` of the built program when run. Output will be shown in case of compilation or runtime error. Defaults to ``True``. clean : bool, optional Whether or not to clean the project before building. Defaults to ``False``. additional_source_files : list of str, optional A list of additional ``.cpp`` files to include in the build. direct_call : bool, optional Whether this function was called directly. Is used internally to distinguish an automatic build due to the ``build_on_run`` option from a manual ``device.build`` call. """ if self.build_on_run and direct_call: raise RuntimeError( "You used set_device with build_on_run=True " "(the default option), which will automatically " "build the simulation at the first encountered " "run call - do not call device.build manually " "in this case. If you want to call it manually, " "e.g. because you have multiple run calls, use " "set_device with build_on_run=False." ) if self.has_been_run: raise RuntimeError( "The network has already been built and run " "before. To build several simulations in " 'the same script, call "device.reinit()" ' 'and "device.activate()". Note that you ' "will have to set build options (e.g. the " "directory) and defaultclock.dt again." ) renames = { "project_dir": "directory", "compile_project": "compile", "run_project": "run", } if len(kwds): msg = "" for kwd in kwds: if kwd in renames: msg += ("Keyword argument '%s' has been renamed to '%s'. ") % ( kwd, renames[kwd], ) else: msg += "Unknown keyword argument '%s'. " % kwd raise TypeError(msg) if additional_source_files is None: additional_source_files = [] if run_args is None: run_args = [] if directory is None: directory = tempfile.mkdtemp(prefix="brian_standalone_") self.project_dir = directory ensure_directory(directory) # Determine compiler flags and directories compiler, default_extra_compile_args = get_compiler_and_args() extra_compile_args = self.extra_compile_args + default_extra_compile_args extra_link_args = self.extra_link_args + prefs["codegen.cpp.extra_link_args"] codeobj_define_macros = [ macro for codeobj in self.code_objects.values() for macro in codeobj.compiler_kwds.get("define_macros", []) ] define_macros = ( self.define_macros + prefs["codegen.cpp.define_macros"] + codeobj_define_macros ) codeobj_include_dirs = [ include_dir for codeobj in self.code_objects.values() for include_dir in codeobj.compiler_kwds.get("include_dirs", []) ] include_dirs = ( self.include_dirs + prefs["codegen.cpp.include_dirs"] + codeobj_include_dirs ) codeobj_library_dirs = [ library_dir for codeobj in self.code_objects.values() for library_dir in codeobj.compiler_kwds.get("library_dirs", []) ] library_dirs = ( self.library_dirs + prefs["codegen.cpp.library_dirs"] + codeobj_library_dirs ) codeobj_runtime_dirs = [ runtime_dir for codeobj in self.code_objects.values() for runtime_dir in codeobj.compiler_kwds.get("runtime_library_dirs", []) ] runtime_library_dirs = ( self.runtime_library_dirs + prefs["codegen.cpp.runtime_library_dirs"] + codeobj_runtime_dirs ) codeobj_libraries = [ library for codeobj in self.code_objects.values() for library in codeobj.compiler_kwds.get("libraries", []) ] libraries = self.libraries + prefs["codegen.cpp.libraries"] + codeobj_libraries compiler_obj = ccompiler.new_compiler(compiler=compiler) compiler_flags = ( ccompiler.gen_preprocess_options(define_macros, include_dirs) + extra_compile_args ) linker_flags = ( ccompiler.gen_lib_options( compiler_obj, library_dirs=library_dirs, runtime_library_dirs=runtime_library_dirs, libraries=libraries, ) + extra_link_args ) codeobj_source_files = [ source_file for codeobj in self.code_objects.values() for source_file in codeobj.compiler_kwds.get("sources", []) ] additional_source_files += codeobj_source_files + ["brianlib/randomkit/randomkit.c"] for d in ["code_objects", "results", "static_arrays"]: ensure_directory(os.path.join(directory, d)) self.writer = CPPWriter(directory) # Get the number of threads if specified in an openmp context nb_threads = prefs.devices.cpp_standalone.openmp_threads # If the number is negative, we need to throw an error if nb_threads < 0: raise ValueError("The number of OpenMP threads can not be negative !") logger.diagnostic( "Writing C++ standalone project to directory " + os.path.normpath(directory) ) self.check_openmp_compatible(nb_threads) self.write_static_arrays(directory) # Check that all names are globally unique names = [obj.name for net in self.networks for obj in net.objects] non_unique_names = [name for name, count in Counter(names).items() if count > 1] if len(non_unique_names): formatted_names = ", ".join("'%s'" % name for name in non_unique_names) raise ValueError( "All objects need to have unique names in " "standalone mode, the following name(s) were used " "more than once: %s" % formatted_names ) net_synapses = [ s for net in self.networks for s in net.objects if isinstance(s, Synapses) ] self.generate_objects_source( self.writer, self.arange_arrays, net_synapses, self.static_array_specs, self.networks, ) self.generate_main_source(self.writer) self.generate_codeobj_source(self.writer) self.generate_network_source(self.writer, compiler) self.generate_synapses_classes_source(self.writer) self.generate_run_source(self.writer) self.copy_source_files(self.writer, directory) self.writer.source_files.extend(additional_source_files) self.generate_makefile( self.writer, compiler, compiler_flags=" ".join(compiler_flags), linker_flags=" ".join(linker_flags), nb_threads=nb_threads, debug=debug, ) # Not sure what the best place is to call Network.after_run -- at the # moment the only important thing it does is to clear the objects stored # in magic_network. If this is not done, this might lead to problems # for repeated runs of standalone (e.g. in the test suite). for net in self.networks: net.after_run() if compile: self.compile_source(directory, compiler, debug, clean) if run: self.run(directory, with_output, run_args)
def build( self, directory="output", compile=True, run=True, debug=False, clean=False, with_output=True, additional_source_files=None, run_args=None, direct_call=True, **kwds, ): """ Build the project TODO: more details Parameters ---------- directory : str, optional The output directory to write the project to, any existing files will be overwritten. If the given directory name is ``None``, then a temporary directory will be used (used in the test suite to avoid problems when running several tests in parallel). Defaults to ``'output'``. compile : bool, optional Whether or not to attempt to compile the project. Defaults to ``True``. run : bool, optional Whether or not to attempt to run the built project if it successfully builds. Defaults to ``True``. debug : bool, optional Whether to compile in debug mode. Defaults to ``False``. with_output : bool, optional Whether or not to show the ``stdout`` of the built program when run. Output will be shown in case of compilation or runtime error. Defaults to ``True``. clean : bool, optional Whether or not to clean the project before building. Defaults to ``False``. additional_source_files : list of str, optional A list of additional ``.cpp`` files to include in the build. direct_call : bool, optional Whether this function was called directly. Is used internally to distinguish an automatic build due to the ``build_on_run`` option from a manual ``device.build`` call. """ if self.build_on_run and direct_call: raise RuntimeError( "You used set_device with build_on_run=True " "(the default option), which will automatically " "build the simulation at the first encountered " "run call - do not call device.build manually " "in this case. If you want to call it manually, " "e.g. because you have multiple run calls, use " "set_device with build_on_run=False." ) if self.has_been_run: raise RuntimeError( "The network has already been built and run " "before. To build several simulations in " 'the same script, call "device.reinit()" ' 'and "device.activate()". Note that you ' "will have to set build options (e.g. the " "directory) and defaultclock.dt again." ) renames = { "project_dir": "directory", "compile_project": "compile", "run_project": "run", } if len(kwds): msg = "" for kwd in kwds: if kwd in renames: msg += ("Keyword argument '%s' has been renamed to '%s'. ") % ( kwd, renames[kwd], ) else: msg += "Unknown keyword argument '%s'. " % kwd raise TypeError(msg) if additional_source_files is None: additional_source_files = [] if run_args is None: run_args = [] if directory is None: directory = tempfile.mkdtemp(prefix="brian_standalone_") self.project_dir = directory ensure_directory(directory) # Determine compiler flags and directories compiler, default_extra_compile_args = get_compiler_and_args() extra_compile_args = self.extra_compile_args + default_extra_compile_args extra_link_args = self.extra_link_args + prefs["codegen.cpp.extra_link_args"] codeobj_define_macros = [ macro for codeobj in self.code_objects.values() for macro in codeobj.compiler_kwds.get("define_macros", []) ] define_macros = ( self.define_macros + prefs["codegen.cpp.define_macros"] + codeobj_define_macros ) codeobj_include_dirs = [ include_dir for codeobj in self.code_objects.values() for include_dir in codeobj.compiler_kwds.get("include_dirs", []) ] include_dirs = ( self.include_dirs + prefs["codegen.cpp.include_dirs"] + codeobj_include_dirs ) codeobj_library_dirs = [ library_dir for codeobj in self.code_objects.values() for library_dir in codeobj.compiler_kwds.get("library_dirs", []) ] library_dirs = ( self.library_dirs + prefs["codegen.cpp.library_dirs"] + codeobj_library_dirs ) codeobj_runtime_dirs = [ runtime_dir for codeobj in self.code_objects.values() for runtime_dir in codeobj.compiler_kwds.get("runtime_library_dirs", []) ] runtime_library_dirs = ( self.runtime_library_dirs + prefs["codegen.cpp.runtime_library_dirs"] + codeobj_runtime_dirs ) codeobj_libraries = [ library for codeobj in self.code_objects.values() for library in codeobj.compiler_kwds.get("libraries", []) ] libraries = self.libraries + prefs["codegen.cpp.libraries"] + codeobj_libraries compiler_obj = ccompiler.new_compiler(compiler=compiler) compiler_flags = ( ccompiler.gen_preprocess_options(define_macros, include_dirs) + extra_compile_args ) linker_flags = ( ccompiler.gen_lib_options( compiler_obj, library_dirs=library_dirs, runtime_library_dirs=runtime_library_dirs, libraries=libraries, ) + extra_link_args ) codeobj_source_files = [ source_file for codeobj in self.code_objects.values() for source_file in codeobj.compiler_kwds.get("sources", []) ] additional_source_files += codeobj_source_files + ["brianlib/randomkit/randomkit.c"] for d in ["code_objects", "results", "static_arrays"]: ensure_directory(os.path.join(directory, d)) self.writer = CPPWriter(directory) # Get the number of threads if specified in an openmp context nb_threads = prefs.devices.cpp_standalone.openmp_threads # If the number is negative, we need to throw an error if nb_threads < 0: raise ValueError("The number of OpenMP threads can not be negative !") logger.diagnostic( "Writing C++ standalone project to directory " + os.path.normpath(directory) ) self.check_openmp_compatible(nb_threads) self.write_static_arrays(directory) self.find_synapses() # Not sure what the best place is to call Network.after_run -- at the # moment the only important thing it does is to clear the objects stored # in magic_network. If this is not done, this might lead to problems # for repeated runs of standalone (e.g. in the test suite). for net in self.networks: net.after_run() # Check that all names are globally unique names = [obj.name for net in self.networks for obj in net.objects] non_unique_names = [name for name, count in Counter(names).items() if count > 1] if len(non_unique_names): formatted_names = ", ".join("'%s'" % name for name in non_unique_names) raise ValueError( "All objects need to have unique names in " "standalone mode, the following name(s) were used " "more than once: %s" % formatted_names ) self.generate_objects_source( self.writer, self.arange_arrays, self.net_synapses, self.static_array_specs, self.networks, ) self.generate_main_source(self.writer) self.generate_codeobj_source(self.writer) self.generate_network_source(self.writer, compiler) self.generate_synapses_classes_source(self.writer) self.generate_run_source(self.writer) self.copy_source_files(self.writer, directory) self.writer.source_files.extend(additional_source_files) self.generate_makefile( self.writer, compiler, compiler_flags=" ".join(compiler_flags), linker_flags=" ".join(linker_flags), nb_threads=nb_threads, debug=debug, ) if compile: self.compile_source(directory, compiler, debug, clean) if run: self.run(directory, with_output, run_args)
https://github.com/brian-team/brian2/issues/1189
ERROR Brian 2 encountered an unexpected error. If you think this is bug in Brian 2, please report this issue either to the mailing list at <http://groups.google.com/group/brian-development/>, or to the issue tracker at <https://github.com/brian-team/brian2/issues>. Please include this file with debug information in your report: /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_debug_1uynejn5.log Additionally, you can also include a copy of the script that was run, available at: /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_script_m_84dmg4.py You can also include a copy of the redirected std stream outputs, available at /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_stdout_d2yd1ugv.log and /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_stderr_xkxqltw0.log Thanks! [brian2] Traceback (most recent call last): File "/Users/fpbatta/src/assembly_sequences/scripts/run_simulation_simple.py", line 69, in <module> nn1 = network_sim() File "/Users/fpbatta/src/assembly_sequences/scripts/run_simulation_simple.py", line 59, in network_sim bb.get_device().build(directory='PETH_standalone', compile=True, run=True, debug=False) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/device.py", line 1265, in build self.generate_objects_source(self.writer, self.arange_arrays, File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/device.py", line 633, in generate_objects_source arr_tmp = self.code_object_class().templater.objects( File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/codegen/templates.py", line 210, in __call__ return MultiTemplate(module) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/codegen/templates.py", line 226, in __init__ s = autoindent_postfilter(str(f())) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 675, in __call__ return self._invoke(arguments, autoescape) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 679, in _invoke rv = self._func(*arguments) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/templates/objects.cpp", line 122, in macro if(f{{name}}.is_open()) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 747, in _fail_with_undefined_error raise self._undefined_exception(self._undefined_message) jinja2.exceptions.UndefinedError: dict object has no element <DynamicArrayVariable(dimensions=Dimension(), dtype=int32, scalar=False, constant=True, read_only=True)>
jinja2.exceptions.UndefinedError
def network_run( self, net, duration, report=None, report_period=10 * second, namespace=None, profile=False, level=0, **kwds, ): self.networks.add(net) if kwds: logger.warn( ("Unsupported keyword argument(s) provided for run: %s") % ", ".join(kwds.keys()) ) # We store this as an instance variable for later access by the # `code_object` method self.enable_profiling = profile all_objects = net.sorted_objects net._clocks = {obj.clock for obj in all_objects} t_end = net.t + duration for clock in net._clocks: clock.set_interval(net.t, t_end) # Get the local namespace if namespace is None: namespace = get_local_namespace(level=level + 2) net.before_run(namespace) self.clocks.update(net._clocks) net.t_ = float(t_end) # TODO: remove this horrible hack for clock in self.clocks: if clock.name == "clock": clock._name = "_clock" # Extract all the CodeObjects # Note that since we ran the Network object, these CodeObjects will be sorted into the right # running order, assuming that there is only one clock code_objects = [] for obj in all_objects: if obj.active: for codeobj in obj._code_objects: code_objects.append((obj.clock, codeobj)) # Code for a progress reporting function standard_code = """ std::string _format_time(float time_in_s) { float divisors[] = {24*60*60, 60*60, 60, 1}; char letters[] = {'d', 'h', 'm', 's'}; float remaining = time_in_s; std::string text = ""; int time_to_represent; for (int i =0; i < sizeof(divisors)/sizeof(float); i++) { time_to_represent = int(remaining / divisors[i]); remaining -= time_to_represent * divisors[i]; if (time_to_represent > 0 || text.length()) { if(text.length() > 0) { text += " "; } text += (std::to_string(time_to_represent)+letters[i]); } } //less than one second if(text.length() == 0) { text = "< 1s"; } return text; } void report_progress(const double elapsed, const double completed, const double start, const double duration) { if (completed == 0.0) { %STREAMNAME% << "Starting simulation at t=" << start << " s for duration " << duration << " s"; } else { %STREAMNAME% << completed*duration << " s (" << (int)(completed*100.) << "%) simulated in " << _format_time(elapsed); if (completed < 1.0) { const int remaining = (int)((1-completed)/completed*elapsed+0.5); %STREAMNAME% << ", estimated " << _format_time(remaining) << " remaining."; } } %STREAMNAME% << std::endl << std::flush; } """ if report is None: report_func = "" elif report == "text" or report == "stdout": report_func = standard_code.replace("%STREAMNAME%", "std::cout") elif report == "stderr": report_func = standard_code.replace("%STREAMNAME%", "std::cerr") elif isinstance(report, str): report_func = """ void report_progress(const double elapsed, const double completed, const double start, const double duration) { %REPORT% } """.replace("%REPORT%", report) else: raise TypeError( ( 'report argument has to be either "text", ' '"stdout", "stderr", or the code for a report ' "function" ) ) if report_func != "": if self.report_func != "" and report_func != self.report_func: raise NotImplementedError( "The C++ standalone device does not " "support multiple report functions, " "each run has to use the same (or " "none)." ) self.report_func = report_func if report is not None: report_call = "report_progress" else: report_call = "NULL" # Generate the updaters run_lines = ["{net.name}.clear();".format(net=net)] all_clocks = set() for clock, codeobj in code_objects: run_lines.append( "{net.name}.add(&{clock.name}, _run_{codeobj.name});".format( clock=clock, net=net, codeobj=codeobj ) ) all_clocks.add(clock) # Under some rare circumstances (e.g. a NeuronGroup only defining a # subexpression that is used by other groups (via linking, or recorded # by a StateMonitor) *and* not calculating anything itself *and* using a # different clock than all other objects) a clock that is not used by # any code object should nevertheless advance during the run. We include # such clocks without a code function in the network. for clock in net._clocks: if clock not in all_clocks: run_lines.append( "{net.name}.add(&{clock.name}, NULL);".format(clock=clock, net=net) ) run_lines.append( "{net.name}.run({duration!r}, {report_call}, {report_period!r});".format( net=net, duration=float(duration), report_call=report_call, report_period=float(report_period), ) ) self.main_queue.append(("run_network", (net, run_lines))) # Manually set the cache for the clocks, simulation scripts might # want to access the time (which has been set in code and is therefore # not accessible by the normal means until the code has been built and # run) for clock in net._clocks: self.array_cache[clock.variables["timestep"]] = np.array([clock._i_end]) self.array_cache[clock.variables["t"]] = np.array([clock._i_end * clock.dt_]) if self.build_on_run: if self.has_been_run: raise RuntimeError( "The network has already been built and run " "before. Use set_device with " "build_on_run=False and an explicit " "device.build call to use multiple run " "statements with this device." ) self.build(direct_call=False, **self.build_options)
def network_run( self, net, duration, report=None, report_period=10 * second, namespace=None, profile=False, level=0, **kwds, ): if kwds: logger.warn( ("Unsupported keyword argument(s) provided for run: %s") % ", ".join(kwds.keys()) ) # We store this as an instance variable for later access by the # `code_object` method self.enable_profiling = profile all_objects = net.sorted_objects net._clocks = {obj.clock for obj in all_objects} t_end = net.t + duration for clock in net._clocks: clock.set_interval(net.t, t_end) # Get the local namespace if namespace is None: namespace = get_local_namespace(level=level + 2) net.before_run(namespace) self.clocks.update(net._clocks) net.t_ = float(t_end) # TODO: remove this horrible hack for clock in self.clocks: if clock.name == "clock": clock._name = "_clock" # Extract all the CodeObjects # Note that since we ran the Network object, these CodeObjects will be sorted into the right # running order, assuming that there is only one clock code_objects = [] for obj in all_objects: if obj.active: for codeobj in obj._code_objects: code_objects.append((obj.clock, codeobj)) # Code for a progress reporting function standard_code = """ std::string _format_time(float time_in_s) { float divisors[] = {24*60*60, 60*60, 60, 1}; char letters[] = {'d', 'h', 'm', 's'}; float remaining = time_in_s; std::string text = ""; int time_to_represent; for (int i =0; i < sizeof(divisors)/sizeof(float); i++) { time_to_represent = int(remaining / divisors[i]); remaining -= time_to_represent * divisors[i]; if (time_to_represent > 0 || text.length()) { if(text.length() > 0) { text += " "; } text += (std::to_string(time_to_represent)+letters[i]); } } //less than one second if(text.length() == 0) { text = "< 1s"; } return text; } void report_progress(const double elapsed, const double completed, const double start, const double duration) { if (completed == 0.0) { %STREAMNAME% << "Starting simulation at t=" << start << " s for duration " << duration << " s"; } else { %STREAMNAME% << completed*duration << " s (" << (int)(completed*100.) << "%) simulated in " << _format_time(elapsed); if (completed < 1.0) { const int remaining = (int)((1-completed)/completed*elapsed+0.5); %STREAMNAME% << ", estimated " << _format_time(remaining) << " remaining."; } } %STREAMNAME% << std::endl << std::flush; } """ if report is None: report_func = "" elif report == "text" or report == "stdout": report_func = standard_code.replace("%STREAMNAME%", "std::cout") elif report == "stderr": report_func = standard_code.replace("%STREAMNAME%", "std::cerr") elif isinstance(report, str): report_func = """ void report_progress(const double elapsed, const double completed, const double start, const double duration) { %REPORT% } """.replace("%REPORT%", report) else: raise TypeError( ( 'report argument has to be either "text", ' '"stdout", "stderr", or the code for a report ' "function" ) ) if report_func != "": if self.report_func != "" and report_func != self.report_func: raise NotImplementedError( "The C++ standalone device does not " "support multiple report functions, " "each run has to use the same (or " "none)." ) self.report_func = report_func if report is not None: report_call = "report_progress" else: report_call = "NULL" # Generate the updaters run_lines = ["{net.name}.clear();".format(net=net)] all_clocks = set() for clock, codeobj in code_objects: run_lines.append( "{net.name}.add(&{clock.name}, _run_{codeobj.name});".format( clock=clock, net=net, codeobj=codeobj ) ) all_clocks.add(clock) # Under some rare circumstances (e.g. a NeuronGroup only defining a # subexpression that is used by other groups (via linking, or recorded # by a StateMonitor) *and* not calculating anything itself *and* using a # different clock than all other objects) a clock that is not used by # any code object should nevertheless advance during the run. We include # such clocks without a code function in the network. for clock in net._clocks: if clock not in all_clocks: run_lines.append( "{net.name}.add(&{clock.name}, NULL);".format(clock=clock, net=net) ) run_lines.append( "{net.name}.run({duration!r}, {report_call}, {report_period!r});".format( net=net, duration=float(duration), report_call=report_call, report_period=float(report_period), ) ) self.main_queue.append(("run_network", (net, run_lines))) # Manually set the cache for the clocks, simulation scripts might # want to access the time (which has been set in code and is therefore # not accessible by the normal means until the code has been built and # run) for clock in net._clocks: self.array_cache[clock.variables["timestep"]] = np.array([clock._i_end]) self.array_cache[clock.variables["t"]] = np.array([clock._i_end * clock.dt_]) if self.build_on_run: if self.has_been_run: raise RuntimeError( "The network has already been built and run " "before. Use set_device with " "build_on_run=False and an explicit " "device.build call to use multiple run " "statements with this device." ) self.build(direct_call=False, **self.build_options)
https://github.com/brian-team/brian2/issues/1189
ERROR Brian 2 encountered an unexpected error. If you think this is bug in Brian 2, please report this issue either to the mailing list at <http://groups.google.com/group/brian-development/>, or to the issue tracker at <https://github.com/brian-team/brian2/issues>. Please include this file with debug information in your report: /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_debug_1uynejn5.log Additionally, you can also include a copy of the script that was run, available at: /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_script_m_84dmg4.py You can also include a copy of the redirected std stream outputs, available at /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_stdout_d2yd1ugv.log and /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_stderr_xkxqltw0.log Thanks! [brian2] Traceback (most recent call last): File "/Users/fpbatta/src/assembly_sequences/scripts/run_simulation_simple.py", line 69, in <module> nn1 = network_sim() File "/Users/fpbatta/src/assembly_sequences/scripts/run_simulation_simple.py", line 59, in network_sim bb.get_device().build(directory='PETH_standalone', compile=True, run=True, debug=False) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/device.py", line 1265, in build self.generate_objects_source(self.writer, self.arange_arrays, File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/device.py", line 633, in generate_objects_source arr_tmp = self.code_object_class().templater.objects( File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/codegen/templates.py", line 210, in __call__ return MultiTemplate(module) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/codegen/templates.py", line 226, in __init__ s = autoindent_postfilter(str(f())) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 675, in __call__ return self._invoke(arguments, autoescape) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 679, in _invoke rv = self._func(*arguments) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/templates/objects.cpp", line 122, in macro if(f{{name}}.is_open()) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 747, in _fail_with_undefined_error raise self._undefined_exception(self._undefined_message) jinja2.exceptions.UndefinedError: dict object has no element <DynamicArrayVariable(dimensions=Dimension(), dtype=int32, scalar=False, constant=True, read_only=True)>
jinja2.exceptions.UndefinedError
def network_run( self, net, duration, report=None, report_period=10 * second, namespace=None, profile=False, level=0, **kwds, ): self.networks.add(net) if kwds: logger.warn( ("Unsupported keyword argument(s) provided for run: %s") % ", ".join(kwds.keys()) ) # We store this as an instance variable for later access by the # `code_object` method self.enable_profiling = profile all_objects = net.sorted_objects net._clocks = {obj.clock for obj in all_objects} t_end = net.t + duration for clock in net._clocks: clock.set_interval(net.t, t_end) # Get the local namespace if namespace is None: namespace = get_local_namespace(level=level + 2) net.before_run(namespace) self.clocks.update(net._clocks) net.t_ = float(t_end) # TODO: remove this horrible hack for clock in self.clocks: if clock.name == "clock": clock._name = "_clock" # Extract all the CodeObjects # Note that since we ran the Network object, these CodeObjects will be sorted into the right # running order, assuming that there is only one clock code_objects = [] for obj in all_objects: if obj.active: for codeobj in obj._code_objects: code_objects.append((obj.clock, codeobj)) # Code for a progress reporting function standard_code = """ void report_progress(const double elapsed, const double completed, const double start, const double duration) { if (completed == 0.0) { %STREAMNAME% << "Starting simulation at t=" << start << " s for duration " << duration << " s"; } else { %STREAMNAME% << completed*duration << " s (" << (int)(completed*100.) << "%) simulated in " << elapsed << " s"; if (completed < 1.0) { const int remaining = (int)((1-completed)/completed*elapsed+0.5); %STREAMNAME% << ", estimated " << remaining << " s remaining."; } } %STREAMNAME% << std::endl << std::flush; } """ if report is None: report_func = "" elif report == "text" or report == "stdout": report_func = standard_code.replace("%STREAMNAME%", "std::cout") elif report == "stderr": report_func = standard_code.replace("%STREAMNAME%", "std::cerr") elif isinstance(report, str): report_func = """ void report_progress(const double elapsed, const double completed, const double start, const double duration) { %REPORT% } """.replace("%REPORT%", report) else: raise TypeError( ( 'report argument has to be either "text", ' '"stdout", "stderr", or the code for a report ' "function" ) ) if report_func != "": if self.report_func != "" and report_func != self.report_func: raise NotImplementedError( "The C++ standalone device does not " "support multiple report functions, " "each run has to use the same (or " "none)." ) self.report_func = report_func if report is not None: report_call = "report_progress" else: report_call = "NULL" # Generate the updaters run_lines = ["{net.name}.clear();".format(net=net)] all_clocks = set() for clock, codeobj in code_objects: run_lines.append( "{net.name}.add(&{clock.name}, _run_{codeobj.name});".format( clock=clock, net=net, codeobj=codeobj ) ) all_clocks.add(clock) # Under some rare circumstances (e.g. a NeuronGroup only defining a # subexpression that is used by other groups (via linking, or recorded # by a StateMonitor) *and* not calculating anything itself *and* using a # different clock than all other objects) a clock that is not used by # any code object should nevertheless advance during the run. We include # such clocks without a code function in the network. for clock in net._clocks: if clock not in all_clocks: run_lines.append( "{net.name}.add(&{clock.name}, NULL);".format(clock=clock, net=net) ) run_lines.append( "{net.name}.run({duration!r}, {report_call}, {report_period!r});".format( net=net, duration=float(duration), report_call=report_call, report_period=float(report_period), ) ) self.main_queue.append(("run_network", (net, run_lines))) # Manually set the cache for the clocks, simulation scripts might # want to access the time (which has been set in code and is therefore # not accessible by the normal means until the code has been built and # run) for clock in net._clocks: self.array_cache[clock.variables["timestep"]] = np.array([clock._i_end]) self.array_cache[clock.variables["t"]] = np.array([clock._i_end * clock.dt_]) if self.build_on_run: if self.has_been_run: raise RuntimeError( "The network has already been built and run " "before. Use set_device with " "build_on_run=False and an explicit " "device.build call to use multiple run " "statements with this device." ) self.build(direct_call=False, **self.build_options)
def network_run( self, net, duration, report=None, report_period=10 * second, namespace=None, profile=False, level=0, **kwds, ): if kwds: logger.warn( ("Unsupported keyword argument(s) provided for run: %s") % ", ".join(kwds.keys()) ) # We store this as an instance variable for later access by the # `code_object` method self.enable_profiling = profile all_objects = net.sorted_objects net._clocks = {obj.clock for obj in all_objects} t_end = net.t + duration for clock in net._clocks: clock.set_interval(net.t, t_end) # Get the local namespace if namespace is None: namespace = get_local_namespace(level=level + 2) net.before_run(namespace) self.clocks.update(net._clocks) net.t_ = float(t_end) # TODO: remove this horrible hack for clock in self.clocks: if clock.name == "clock": clock._name = "_clock" # Extract all the CodeObjects # Note that since we ran the Network object, these CodeObjects will be sorted into the right # running order, assuming that there is only one clock code_objects = [] for obj in all_objects: if obj.active: for codeobj in obj._code_objects: code_objects.append((obj.clock, codeobj)) # Code for a progress reporting function standard_code = """ void report_progress(const double elapsed, const double completed, const double start, const double duration) { if (completed == 0.0) { %STREAMNAME% << "Starting simulation at t=" << start << " s for duration " << duration << " s"; } else { %STREAMNAME% << completed*duration << " s (" << (int)(completed*100.) << "%) simulated in " << elapsed << " s"; if (completed < 1.0) { const int remaining = (int)((1-completed)/completed*elapsed+0.5); %STREAMNAME% << ", estimated " << remaining << " s remaining."; } } %STREAMNAME% << std::endl << std::flush; } """ if report is None: report_func = "" elif report == "text" or report == "stdout": report_func = standard_code.replace("%STREAMNAME%", "std::cout") elif report == "stderr": report_func = standard_code.replace("%STREAMNAME%", "std::cerr") elif isinstance(report, str): report_func = """ void report_progress(const double elapsed, const double completed, const double start, const double duration) { %REPORT% } """.replace("%REPORT%", report) else: raise TypeError( ( 'report argument has to be either "text", ' '"stdout", "stderr", or the code for a report ' "function" ) ) if report_func != "": if self.report_func != "" and report_func != self.report_func: raise NotImplementedError( "The C++ standalone device does not " "support multiple report functions, " "each run has to use the same (or " "none)." ) self.report_func = report_func if report is not None: report_call = "report_progress" else: report_call = "NULL" # Generate the updaters run_lines = ["{net.name}.clear();".format(net=net)] all_clocks = set() for clock, codeobj in code_objects: run_lines.append( "{net.name}.add(&{clock.name}, _run_{codeobj.name});".format( clock=clock, net=net, codeobj=codeobj ) ) all_clocks.add(clock) # Under some rare circumstances (e.g. a NeuronGroup only defining a # subexpression that is used by other groups (via linking, or recorded # by a StateMonitor) *and* not calculating anything itself *and* using a # different clock than all other objects) a clock that is not used by # any code object should nevertheless advance during the run. We include # such clocks without a code function in the network. for clock in net._clocks: if clock not in all_clocks: run_lines.append( "{net.name}.add(&{clock.name}, NULL);".format(clock=clock, net=net) ) run_lines.append( "{net.name}.run({duration!r}, {report_call}, {report_period!r});".format( net=net, duration=float(duration), report_call=report_call, report_period=float(report_period), ) ) self.main_queue.append(("run_network", (net, run_lines))) # Manually set the cache for the clocks, simulation scripts might # want to access the time (which has been set in code and is therefore # not accessible by the normal means until the code has been built and # run) for clock in net._clocks: self.array_cache[clock.variables["timestep"]] = np.array([clock._i_end]) self.array_cache[clock.variables["t"]] = np.array([clock._i_end * clock.dt_]) if self.build_on_run: if self.has_been_run: raise RuntimeError( "The network has already been built and run " "before. Use set_device with " "build_on_run=False and an explicit " "device.build call to use multiple run " "statements with this device." ) self.build(direct_call=False, **self.build_options)
https://github.com/brian-team/brian2/issues/1189
ERROR Brian 2 encountered an unexpected error. If you think this is bug in Brian 2, please report this issue either to the mailing list at <http://groups.google.com/group/brian-development/>, or to the issue tracker at <https://github.com/brian-team/brian2/issues>. Please include this file with debug information in your report: /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_debug_1uynejn5.log Additionally, you can also include a copy of the script that was run, available at: /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_script_m_84dmg4.py You can also include a copy of the redirected std stream outputs, available at /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_stdout_d2yd1ugv.log and /var/folders/_n/ml20bf7n0_g3sz165pd3nrjm0000gn/T/brian_stderr_xkxqltw0.log Thanks! [brian2] Traceback (most recent call last): File "/Users/fpbatta/src/assembly_sequences/scripts/run_simulation_simple.py", line 69, in <module> nn1 = network_sim() File "/Users/fpbatta/src/assembly_sequences/scripts/run_simulation_simple.py", line 59, in network_sim bb.get_device().build(directory='PETH_standalone', compile=True, run=True, debug=False) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/device.py", line 1265, in build self.generate_objects_source(self.writer, self.arange_arrays, File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/device.py", line 633, in generate_objects_source arr_tmp = self.code_object_class().templater.objects( File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/codegen/templates.py", line 210, in __call__ return MultiTemplate(module) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/codegen/templates.py", line 226, in __init__ s = autoindent_postfilter(str(f())) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 675, in __call__ return self._invoke(arguments, autoescape) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 679, in _invoke rv = self._func(*arguments) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/brian2/devices/cpp_standalone/templates/objects.cpp", line 122, in macro if(f{{name}}.is_open()) File "/Users/fpbatta/.conda/envs/brian23/lib/python3.8/site-packages/jinja2/runtime.py", line 747, in _fail_with_undefined_error raise self._undefined_exception(self._undefined_message) jinja2.exceptions.UndefinedError: dict object has no element <DynamicArrayVariable(dimensions=Dimension(), dtype=int32, scalar=False, constant=True, read_only=True)>
jinja2.exceptions.UndefinedError
def brian_object_exception(message, brianobj, original_exception): """ Returns a `BrianObjectException` derived from the original exception. Creates a new class derived from the class of the original exception and `BrianObjectException`. This allows exception handling code to respond both to the original exception class and `BrianObjectException`. See `BrianObjectException` for arguments and notes. """ DerivedBrianObjectException = type( "BrianObjectException", (BrianObjectException, original_exception.__class__), {} ) new_exception = DerivedBrianObjectException(message, brianobj, original_exception) # Copy over all exception attributes for attribute in dir(original_exception): if attribute.startswith("_"): continue setattr(new_exception, attribute, getattr(original_exception, attribute)) return new_exception
def brian_object_exception(message, brianobj, original_exception): """ Returns a `BrianObjectException` derived from the original exception. Creates a new class derived from the class of the original exception and `BrianObjectException`. This allows exception handling code to respond both to the original exception class and `BrianObjectException`. See `BrianObjectException` for arguments and notes. """ DerivedBrianObjectException = type( "BrianObjectException", (BrianObjectException, original_exception.__class__), {} ) return DerivedBrianObjectException(message, brianobj, original_exception)
https://github.com/brian-team/brian2/issues/964
Traceback (most recent call last): File "err_test.py", line 5, in <module> run(0*ms) File "/home/marcel/programming/brian2/brian2/units/fundamentalunits.py", line 2360, in new_f result = f(*args, **kwds) File "/home/marcel/programming/brian2/brian2/core/magic.py", line 371, in run namespace=namespace, profile=profile, level=2+level) File "/home/marcel/programming/brian2/brian2/core/magic.py", line 231, in run namespace=namespace, profile=profile, level=level+1) File "/home/marcel/programming/brian2/brian2/core/base.py", line 278, in device_override_decorated_function return func(*args, **kwds) File "/home/marcel/programming/brian2/brian2/units/fundamentalunits.py", line 2360, in new_f result = f(*args, **kwds) File "/home/marcel/programming/brian2/brian2/core/network.py", line 951, in run self.before_run(namespace) File "/home/marcel/programming/brian2/brian2/core/base.py", line 278, in device_override_decorated_function return func(*args, **kwds) File "/home/marcel/programming/brian2/brian2/core/network.py", line 843, in before_run raise brian_object_exception("An error occurred when preparing an object.", obj, ex) BrianObjectException: Original error and traceback: Traceback (most recent call last): File "/home/marcel/programming/brian2/brian2/core/network.py", line 841, in before_run obj.before_run(run_namespace) File "/home/marcel/programming/brian2/brian2/groups/group.py", line 1093, in before_run self.update_abstract_code(run_namespace=run_namespace) File "/home/marcel/programming/brian2/brian2/groups/neurongroup.py", line 267, in update_abstract_code if not is_boolean_expression(code, variables): File "/home/marcel/programming/brian2/brian2/parsing/expressions.py", line 64, in is_boolean_expression mod = ast.parse(expr, mode='eval') File "/home/marcel/anaconda2/envs/brian2/lib/python2.7/ast.py", line 37, in parse return compile(source, filename, mode, PyCF_ONLY_AST) File "<unknown>", line 1 `False ^ SyntaxError: unexpected EOF while parsing Error encountered with object named "neurongroup_thresholder". Object was created here (most recent call only, full details in debug log): File "err_test.py", line 3, in <module> g = NeuronGroup(1, '', threshold='`False') An error occurred when preparing an object. File "<unknown>", line 1 `False ^ SyntaxError: unexpected EOF while parsing (See above for original error message and traceback.)
SyntaxError
def conditional_write( self, line, stmt, variables, conditional_write_vars, created_vars ): if stmt.var in conditional_write_vars: subs = {} index = conditional_write_vars[stmt.var] # we replace all var with var[index], but actually we use this repl_string first because # we don't want to end up with lines like x[not_refractory[not_refractory]] when # multiple substitution passes are invoked repl_string = ( "#$(@#&$@$*U#@)$@(#" # this string shouldn't occur anywhere I hope! :) ) for varname, var in variables.items(): if isinstance(var, ArrayVariable) and not var.scalar: subs[varname] = varname + "[" + repl_string + "]" # all newly created vars are arrays and will need indexing for varname in created_vars: subs[varname] = varname + "[" + repl_string + "]" # Also index _vectorisation_idx so that e.g. rand() works correctly subs["_vectorisation_idx"] = "_vectorisation_idx" + "[" + repl_string + "]" line = word_substitute(line, subs) line = line.replace(repl_string, index) return line
def conditional_write( self, line, stmt, variables, conditional_write_vars, created_vars ): if stmt.var in conditional_write_vars: subs = {} index = conditional_write_vars[stmt.var] # we replace all var with var[index], but actually we use this repl_string first because # we don't want to end up with lines like x[not_refractory[not_refractory]] when # multiple substitution passes are invoked repl_string = ( "#$(@#&$@$*U#@)$@(#" # this string shouldn't occur anywhere I hope! :) ) for varname, var in variables.items(): if isinstance(var, ArrayVariable) and not var.scalar: subs[varname] = varname + "[" + repl_string + "]" # all newly created vars are arrays and will need indexing for varname in created_vars: subs[varname] = varname + "[" + repl_string + "]" line = word_substitute(line, subs) line = line.replace(repl_string, index) return line
https://github.com/brian-team/brian2/issues/761
BrianObjectException: Original error and traceback: Traceback (most recent call last): File "E:\Dan\programming\brian2\brian2\codegen\runtime\numpy_rt\numpy_rt.py", line 122, in run exec self.compiled_code in self.namespace File "(string)", line 13, in <module> ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,) Error encountered with object named "neurongroup_1". Object was created here (most recent call only, full details in debug log): File "<ipython-input-2-ff5506ac93b4>", line 9, in <module> G = NeuronGroup(100, eqs, reset='v=0', threshold='v>1', refractory=1*ms) An exception occured during the execution of code object poissoninput_1_codeobject. The error was raised in the following line: v[not_refractory] += 0.1 * poissoninput_binomial_1(_vectorisation_idx) ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,) (See above for original error message and traceback.)
ValueError
def randn_func(vectorisation_idx): try: N = len(vectorisation_idx) return np.random.randn(N) except TypeError: # scalar value return np.random.randn()
def randn_func(vectorisation_idx): try: N = len(vectorisation_idx) except TypeError: N = int(vectorisation_idx) numbers = np.random.randn(N) if N == 1: return numbers[0] else: return numbers
https://github.com/brian-team/brian2/issues/761
BrianObjectException: Original error and traceback: Traceback (most recent call last): File "E:\Dan\programming\brian2\brian2\codegen\runtime\numpy_rt\numpy_rt.py", line 122, in run exec self.compiled_code in self.namespace File "(string)", line 13, in <module> ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,) Error encountered with object named "neurongroup_1". Object was created here (most recent call only, full details in debug log): File "<ipython-input-2-ff5506ac93b4>", line 9, in <module> G = NeuronGroup(100, eqs, reset='v=0', threshold='v>1', refractory=1*ms) An exception occured during the execution of code object poissoninput_1_codeobject. The error was raised in the following line: v[not_refractory] += 0.1 * poissoninput_binomial_1(_vectorisation_idx) ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,) (See above for original error message and traceback.)
ValueError
def rand_func(vectorisation_idx): try: N = len(vectorisation_idx) return np.random.rand(N) except TypeError: # scalar value return np.random.rand()
def rand_func(vectorisation_idx): try: N = len(vectorisation_idx) except TypeError: N = int(vectorisation_idx) numbers = np.random.rand(N) if N == 1: return numbers[0] else: return numbers
https://github.com/brian-team/brian2/issues/761
BrianObjectException: Original error and traceback: Traceback (most recent call last): File "E:\Dan\programming\brian2\brian2\codegen\runtime\numpy_rt\numpy_rt.py", line 122, in run exec self.compiled_code in self.namespace File "(string)", line 13, in <module> ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,) Error encountered with object named "neurongroup_1". Object was created here (most recent call only, full details in debug log): File "<ipython-input-2-ff5506ac93b4>", line 9, in <module> G = NeuronGroup(100, eqs, reset='v=0', threshold='v>1', refractory=1*ms) An exception occured during the execution of code object poissoninput_1_codeobject. The error was raised in the following line: v[not_refractory] += 0.1 * poissoninput_binomial_1(_vectorisation_idx) ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,) (See above for original error message and traceback.)
ValueError
def restore(self, name="default", filename=None): """ restore(name='default', filename=None) Retore the state of the network and all included objects. Parameters ---------- name : str, optional The name of the snapshot to restore, if not specified uses ``'default'``. filename : str, optional The name of the file from where the state should be restored. If not specified, it is expected that the state exist in memory (i.e. `Network.store` was previously called without the ``filename`` argument). """ if filename is None: state = self._stored_state[name] else: with open(filename, "rb") as f: state = pickle.load(f)[name] self.t_ = state["0_t"] clocks = set([obj.clock for obj in self.objects]) restored_objects = set() for obj in self.objects: if obj.name in state: obj._restore_from_full_state(state[obj.name]) restored_objects.add(obj.name) elif hasattr(obj, "_restore_from_full_state"): raise KeyError( ( "Stored state does not have a stored state for " '"%s". Note that the names of all objects have ' "to be identical to the names when they were " "stored." ) % obj.name ) for clock in clocks: clock._restore_from_full_state(state[clock.name]) clock_names = {c.name for c in clocks} unnused = set(state.keys()) - restored_objects - clock_names - {"0_t"} if len(unnused): raise KeyError( "The stored state contains the state of the " "following objects which were not present in the " "network: %s. Note that the names of all objects " "have to be identical to the names when they were " "stored." % (", ".join(unnused)) )
def restore(self, name="default", filename=None): """ restore(name='default', filename=None) Retore the state of the network and all included objects. Parameters ---------- name : str, optional The name of the snapshot to restore, if not specified uses ``'default'``. filename : str, optional The name of the file from where the state should be restored. If not specified, it is expected that the state exist in memory (i.e. `Network.store` was previously called without the ``filename`` argument). """ if filename is None: state = self._stored_state[name] else: with open(filename, "rb") as f: state = pickle.load(f)[name] self.t_ = state.pop("0_t") clocks = set([obj.clock for obj in self.objects]) restored_objects = set() for obj in self.objects: if obj.name in state: obj._restore_from_full_state(state[obj.name]) restored_objects.add(obj.name) elif hasattr(obj, "_restore_from_full_state"): raise KeyError( ( "Stored state does not have a stored state for " '"%s". Note that the names of all objects have ' "to be identical to the names when they were " "stored." ) % obj.name ) for clock in clocks: clock._restore_from_full_state(state[clock.name]) clock_names = {c.name for c in clocks} unnused = set(state.keys()) - restored_objects - clock_names if len(unnused): raise KeyError( "The stored state contains the state of the " "following objects which were not present in the " "network: %s. Note that the names of all objects " "have to be identical to the names when they were " "stored." % (", ".join(unnused)) )
https://github.com/brian-team/brian2/issues/681
In [1]: from brian2 import * In [2]: G = NeuronGroup(1, 'v: 1') In [3]: store() In [4]: restore() In [5]: restore() --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-5-ad7bb0bcaaad> in <module>() ----> 1 restore() /home/marcel/programming/brian2/brian2/core/magic.pyc in restore(name, filename) 411 Network.restore 412 ''' --> 413 magic_network.restore(name=name, filename=filename, level=1) 414 415 /home/marcel/programming/brian2/brian2/core/magic.pyc in restore(self, name, filename, level) 244 ''' 245 self._update_magic_objects(level=level+1) --> 246 super(MagicNetwork, self).restore(name=name, filename=filename) 247 self.objects[:] = [] 248 /home/marcel/programming/brian2/brian2/core/base.pyc in device_override_decorated_function(*args, **kwds) 276 return getattr(curdev, name)(*args, **kwds) 277 else: --> 278 return func(*args, **kwds) 279 280 device_override_decorated_function.__doc__ = func.__doc__ /home/marcel/programming/brian2/brian2/core/network.pyc in restore(self, name, filename) 431 with open(filename, 'rb') as f: 432 state = pickle.load(f)[name] --> 433 self.t_ = state.pop('0_t') 434 clocks = set([obj.clock for obj in self.objects]) 435 restored_objects = set() KeyError: '0_t'
KeyError
def push(self, sources): """ Push spikes to the queue. Parameters ---------- sources : ndarray of int The indices of the neurons that spiked. """ if len(sources) and len(self._delays): start = self._source_start stop = self._source_end if start > 0: start_idx = bisect.bisect_left(sources, start) else: start_idx = 0 if stop <= sources[-1]: stop_idx = bisect.bisect_left(sources, stop, lo=start_idx) else: stop_idx = len(self._neurons_to_synapses) sources = sources[start_idx:stop_idx] if len(sources) == 0: return synapse_indices = self._neurons_to_synapses indices = np.concatenate( [synapse_indices[source - start] for source in sources] ).astype(np.int32) if self._homogeneous: # homogeneous delays self._insert_homogeneous(self._delays[0], indices) elif self._offsets is None: # vectorise over synaptic events # there are no precomputed offsets, this is the case # (in particular) when there are dynamic delays self._insert(self._delays[indices], indices) else: # offsets are precomputed self._insert(self._delays[indices], indices, self._offsets[indices])
def push(self, sources): """ Push spikes to the queue. Parameters ---------- sources : ndarray of int The indices of the neurons that spiked. """ if len(sources): start = self._source_start stop = self._source_end if start > 0: start_idx = bisect.bisect_left(sources, start) else: start_idx = 0 if stop <= sources[-1]: stop_idx = bisect.bisect_left(sources, stop, lo=start_idx) else: stop_idx = len(self._neurons_to_synapses) sources = sources[start_idx:stop_idx] if len(sources) == 0: return synapse_indices = self._neurons_to_synapses indices = np.concatenate( [synapse_indices[source - start] for source in sources] ).astype(np.int32) if self._homogeneous: # homogeneous delays self._insert_homogeneous(self._delays[0], indices) elif self._offsets is None: # vectorise over synaptic events # there are no precomputed offsets, this is the case # (in particular) when there are dynamic delays self._insert(self._delays[indices], indices) else: # offsets are precomputed self._insert(self._delays[indices], indices, self._offsets[indices])
https://github.com/brian-team/brian2/issues/371
SG = SpikeGeneratorGroup(1, [0], [0*ms]) G = NeuronGroup(1, 'v:1') S = Synapses(SG, G, pre='v+=1') run(0.1*ms) Traceback (most recent call last): ... File "/home/marcel/programming/brian2/brian2/synapses/spikequeue.py", line 254, in push self._insert_homogeneous(self._delays[0], indices) IndexError: index 0 is out of bounds for axis 0 with size 0
IndexError
def initialise_queue(self): if self.synapse_sources.get_len() == 0: logger.warn( ( "Synapses object '%s' does not have any synapses. Did " "you forget a 'connect'?" ) % self.synapses.name, "no_synapses", once=True, ) if self.queue is None: self.queue = get_device().spike_queue(self.source.start, self.source.stop) # Update the dt (might have changed between runs) self.queue.prepare( self._delays.get_value(), self.source.clock.dt_, self.synapse_sources.get_value(), ) if ( len( set([self.source.clock.dt_, self.synapses.clock.dt_, self.target.clock.dt_]) ) > 1 ): logger.warn( ( "Note that the synaptic pathway '{pathway}' will run on the " "clock of the group '{source}' using a dt of {dt}. Either " "the Synapses object '{synapses}' or the target '{target}' " "(or both) are using a different dt. This might lead to " "unexpected results. In particular, all delays will be rounded to " "multiples of {dt}. If in doubt, try to ensure that " "'{source}', '{synapses}', and '{target}' use the " "same dt." ).format( pathway=self.name, source=self.source.name, target=self.target.name, dt=self.source.clock.dt, synapses=self.synapses.name, ), "synapses_dt_mismatch", once=True, )
def initialise_queue(self): if self.queue is None: self.queue = get_device().spike_queue(self.source.start, self.source.stop) # Update the dt (might have changed between runs) self.queue.prepare( self._delays.get_value(), self.source.clock.dt_, self.synapse_sources.get_value(), ) if ( len( set([self.source.clock.dt_, self.synapses.clock.dt_, self.target.clock.dt_]) ) > 1 ): logger.warn( ( "Note that the synaptic pathway '{pathway}' will run on the " "clock of the group '{source}' using a dt of {dt}. Either " "the Synapses object '{synapses}' or the target '{target}' " "(or both) are using a different dt. This might lead to " "unexpected results. In particular, all delays will be rounded to " "multiples of {dt}. If in doubt, try to ensure that " "'{source}', '{synapses}', and '{target}' use the " "same dt." ).format( pathway=self.name, source=self.source.name, target=self.target.name, dt=self.source.clock.dt, synapses=self.synapses.name, ), "synapses_dt_mismatch", once=True, )
https://github.com/brian-team/brian2/issues/371
SG = SpikeGeneratorGroup(1, [0], [0*ms]) G = NeuronGroup(1, 'v:1') S = Synapses(SG, G, pre='v+=1') run(0.1*ms) Traceback (most recent call last): ... File "/home/marcel/programming/brian2/brian2/synapses/spikequeue.py", line 254, in push self._insert_homogeneous(self._delays[0], indices) IndexError: index 0 is out of bounds for axis 0 with size 0
IndexError
def __call__(self, engine: Engine) -> None: """ This method assumes self.batch_transform will extract metadata from the input batch. Args: engine: Ignite Engine, it can be a trainer, validator or evaluator. """ _meta_data = self.batch_transform(engine.state.batch) if Key.FILENAME_OR_OBJ in _meta_data: # all gather filenames across ranks, only filenames are necessary _meta_data = { Key.FILENAME_OR_OBJ: string_list_all_gather(_meta_data[Key.FILENAME_OR_OBJ]) } # all gather predictions across ranks _engine_output = evenly_divisible_all_gather( self.output_transform(engine.state.output) ) if self._expected_rank: self.saver.save_batch(_engine_output, _meta_data)
def __call__(self, engine: Engine) -> None: """ This method assumes self.batch_transform will extract metadata from the input batch. Args: engine: Ignite Engine, it can be a trainer, validator or evaluator. """ _meta_data = self.batch_transform(engine.state.batch) if Key.FILENAME_OR_OBJ in _meta_data: # all gather filenames across ranks _meta_data[Key.FILENAME_OR_OBJ] = string_list_all_gather( _meta_data[Key.FILENAME_OR_OBJ] ) # all gather predictions across ranks _engine_output = evenly_divisible_all_gather( self.output_transform(engine.state.output) ) if self._expected_rank: self.saver.save_batch(_engine_output, _meta_data)
https://github.com/Project-MONAI/MONAI/issues/1570
2021-02-09 02:12:24,253 - ignite.engine.engine.SupervisedEvaluator - INFO - Engine run resuming from iteration 0, epoch 0 until 1 epochs 2021-02-09 02:12:24,436 - ignite.engine.engine.SupervisedEvaluator - INFO - Restored all variables from /home/madil/dlmed/problems/pt_mmars/classification_chestxray_ea2/commands/../models/model.pt 2021-02-09 02:12:29,927 - ignite.engine.engine.SupervisedEvaluator - ERROR - Current run is terminating due to exception: list index out of range. 2021-02-09 02:12:29,928 - ignite.engine.engine.SupervisedEvaluator - ERROR - Exception: list index out of range Traceback (most recent call last): File "/opt/conda/lib/python3.6/site-packages/ignite/engine/engine.py", line 812, in _run_once_on_dataset self._fire_event(Events.ITERATION_COMPLETED) File "/opt/conda/lib/python3.6/site-packages/ignite/engine/engine.py", line 423, in _fire_event func(*first, *(event_args + others), **kwargs) File "/opt/monai/monai/handlers/classification_saver.py", line 97, in __call__ self.saver.save_batch(_engine_output, _meta_data) File "/opt/monai/monai/data/csv_saver.py", line 95, in save_batch self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None) File "/opt/monai/monai/data/csv_saver.py", line 95, in <dictcomp> self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None) IndexError: list index out of range
IndexError
def string_list_all_gather(strings: List[str], delimiter: str = "\t") -> List[str]: """ Utility function for distributed data parallel to all gather a list of strings. Args: strings: a list of strings to all gather. delimiter: use the delimiter to join the string list to be a long string, then all gather across ranks and split to a list. default to "\t". """ if idist.get_world_size() <= 1: return strings _joined = delimiter.join(strings) if get_torch_version_tuple() > (1, 6, 0): # all gather across all ranks _joined = delimiter.join(idist.all_gather(_joined)) else: raise RuntimeError("string all_gather can not be supported in PyTorch < 1.7.0.") return _joined.split(delimiter)
def string_list_all_gather(strings: List[str], delimiter: str = "\t") -> List[str]: """ Utility function for distributed data parallel to all gather a list of strings. Args: strings: a list of strings to all gather. delimiter: use the delimiter to join the string list to be a long string, then all gather across ranks and split to a list. default to "\t". """ if idist.get_world_size() <= 1: return strings _joined = delimiter.join(strings) if get_torch_version_tuple() > (1, 6, 0): # all gather across all ranks _joined = delimiter.join(idist.all_gather(_joined)) else: raise RuntimeError( "MetricsSaver can not save metric details in distributed mode with PyTorch < 1.7.0." ) return _joined.split(delimiter)
https://github.com/Project-MONAI/MONAI/issues/1570
2021-02-09 02:12:24,253 - ignite.engine.engine.SupervisedEvaluator - INFO - Engine run resuming from iteration 0, epoch 0 until 1 epochs 2021-02-09 02:12:24,436 - ignite.engine.engine.SupervisedEvaluator - INFO - Restored all variables from /home/madil/dlmed/problems/pt_mmars/classification_chestxray_ea2/commands/../models/model.pt 2021-02-09 02:12:29,927 - ignite.engine.engine.SupervisedEvaluator - ERROR - Current run is terminating due to exception: list index out of range. 2021-02-09 02:12:29,928 - ignite.engine.engine.SupervisedEvaluator - ERROR - Exception: list index out of range Traceback (most recent call last): File "/opt/conda/lib/python3.6/site-packages/ignite/engine/engine.py", line 812, in _run_once_on_dataset self._fire_event(Events.ITERATION_COMPLETED) File "/opt/conda/lib/python3.6/site-packages/ignite/engine/engine.py", line 423, in _fire_event func(*first, *(event_args + others), **kwargs) File "/opt/monai/monai/handlers/classification_saver.py", line 97, in __call__ self.saver.save_batch(_engine_output, _meta_data) File "/opt/monai/monai/data/csv_saver.py", line 95, in save_batch self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None) File "/opt/monai/monai/data/csv_saver.py", line 95, in <dictcomp> self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None) IndexError: list index out of range
IndexError
def __call__(self, data): """ Raises: KeyError: When a key in ``self.names`` already exists in ``data``. """ d = dict(data) for key, new_key in zip(self.keys * self.times, self.names): if new_key in d: raise KeyError(f"Key {new_key} already exists in data.") if type(d[key]) == torch.Tensor: d[new_key] = d[key].detach().clone() else: d[new_key] = copy.deepcopy(d[key]) return d
def __call__(self, data): """ Raises: KeyError: When a key in ``self.names`` already exists in ``data``. """ d = dict(data) for key, new_key in zip(self.keys * self.times, self.names): if new_key in d: raise KeyError(f"Key {new_key} already exists in data.") d[new_key] = copy.deepcopy(d[key]) return d
https://github.com/Project-MONAI/MONAI/issues/1178
ERROR - Exception: Applying transform <monai.transforms.compose.Compose object at 0x7f0700e9deb8>. Traceback (most recent call last): File "/home/madil/dlmed/code/MONAI/monai/transforms/utils.py", line 309, in apply_transform return transform(data) File "/home/madil/dlmed/code/MONAI/monai/transforms/utility/dictionary.py", line 406, in __call__ d[new_key] = copy.deepcopy(d[key]) File "/opt/conda/lib/python3.6/copy.py", line 161, in deepcopy y = copier(memo) File "/opt/conda/lib/python3.6/site-packages/torch/tensor.py", line 38, in __deepcopy__ raise RuntimeError("Only Tensors created explicitly by the user " RuntimeError: Only Tensors created explicitly by the user (graph leaves) support the deepcopy protocol at the moment
RuntimeError
def __init__( self, output_dir: str = "./", output_postfix: str = "seg", output_ext: str = ".nii.gz", resample: bool = True, mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, align_corners: bool = False, dtype: Optional[np.dtype] = np.float64, ) -> None: """ Args: output_dir: output image directory. output_postfix: a string appended to all output file names. output_ext: output file extension name. resample: whether to resample before saving the data array. mode: {``"bilinear"``, ``"nearest"``} This option is used when ``resample = True``. Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} This option is used when ``resample = True``. Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample align_corners: Geometrically, we consider the pixels of the input as squares rather than points. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample dtype: data type for resampling computation. Defaults to ``np.float64`` for best precision. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``np.float32``. """ self.output_dir = output_dir self.output_postfix = output_postfix self.output_ext = output_ext self.resample = resample self.mode: GridSampleMode = GridSampleMode(mode) self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode) self.align_corners = align_corners self.dtype = dtype self._data_index = 0
def __init__( self, output_dir: str = "./", output_postfix: str = "seg", output_ext: str = ".nii.gz", resample: bool = True, mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, dtype: Optional[np.dtype] = None, ) -> None: """ Args: output_dir: output image directory. output_postfix: a string appended to all output file names. output_ext: output file extension name. resample: whether to resample before saving the data array. mode: {``"bilinear"``, ``"nearest"``} This option is used when ``resample = True``. Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} This option is used when ``resample = True``. Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample dtype: convert the image data to save to this data type. If None, keep the original type of data. """ self.output_dir = output_dir self.output_postfix = output_postfix self.output_ext = output_ext self.resample = resample self.mode: GridSampleMode = GridSampleMode(mode) self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode) self.dtype = dtype self._data_index = 0
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError
def save( self, data: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None ) -> None: """ Save data into a Nifti file. The meta_data could optionally have the following keys: - ``'filename_or_obj'`` -- for output file name creation, corresponding to filename or object. - ``'original_affine'`` -- for data orientation handling, defaulting to an identity matrix. - ``'affine'`` -- for data output affine, defaulting to an identity matrix. - ``'spatial_shape'`` -- for data output shape. When meta_data is specified, the saver will try to resample batch data from the space defined by "affine" to the space defined by "original_affine". If meta_data is None, use the default index (starting from 0) as the filename. Args: data: target data content that to be saved as a NIfTI format file. Assuming the data shape starts with a channel dimension and followed by spatial dimensions. meta_data: the meta data information corresponding to the data. See Also :py:meth:`monai.data.nifti_writer.write_nifti` """ filename = meta_data["filename_or_obj"] if meta_data else str(self._data_index) self._data_index += 1 original_affine = meta_data.get("original_affine", None) if meta_data else None affine = meta_data.get("affine", None) if meta_data else None spatial_shape = meta_data.get("spatial_shape", None) if meta_data else None if torch.is_tensor(data): data = data.detach().cpu().numpy() filename = create_file_basename(self.output_postfix, filename, self.output_dir) filename = f"{filename}{self.output_ext}" # change data shape to be (channel, h, w, d) while len(data.shape) < 4: data = np.expand_dims(data, -1) # change data to "channel last" format and write to nifti format file data = np.moveaxis(data, 0, -1) write_nifti( data, file_name=filename, affine=affine, target_affine=original_affine, resample=self.resample, output_spatial_shape=spatial_shape, mode=self.mode, padding_mode=self.padding_mode, align_corners=self.align_corners, dtype=self.dtype, )
def save( self, data: Union[torch.Tensor, np.ndarray], meta_data: Optional[Dict] = None ) -> None: """ Save data into a Nifti file. The meta_data could optionally have the following keys: - ``'filename_or_obj'`` -- for output file name creation, corresponding to filename or object. - ``'original_affine'`` -- for data orientation handling, defaulting to an identity matrix. - ``'affine'`` -- for data output affine, defaulting to an identity matrix. - ``'spatial_shape'`` -- for data output shape. When meta_data is specified, the saver will try to resample batch data from the space defined by "affine" to the space defined by "original_affine". If meta_data is None, use the default index (starting from 0) as the filename. Args: data: target data content that to be saved as a NIfTI format file. Assuming the data shape starts with a channel dimension and followed by spatial dimensions. meta_data: the meta data information corresponding to the data. See Also :py:meth:`monai.data.nifti_writer.write_nifti` """ filename = meta_data["filename_or_obj"] if meta_data else str(self._data_index) self._data_index += 1 original_affine = meta_data.get("original_affine", None) if meta_data else None affine = meta_data.get("affine", None) if meta_data else None spatial_shape = meta_data.get("spatial_shape", None) if meta_data else None if torch.is_tensor(data): data = data.detach().cpu().numpy() filename = create_file_basename(self.output_postfix, filename, self.output_dir) filename = f"{filename}{self.output_ext}" # change data shape to be (channel, h, w, d) while len(data.shape) < 4: data = np.expand_dims(data, -1) # change data to "channel last" format and write to nifti format file data = np.moveaxis(data, 0, -1) write_nifti( data, file_name=filename, affine=affine, target_affine=original_affine, resample=self.resample, output_spatial_shape=spatial_shape, mode=self.mode, padding_mode=self.padding_mode, dtype=self.dtype or data.dtype, )
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError
def write_nifti( data: np.ndarray, file_name: str, affine: Optional[np.ndarray] = None, target_affine: Optional[np.ndarray] = None, resample: bool = True, output_spatial_shape: Optional[Sequence[int]] = None, mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, align_corners: bool = False, dtype: Optional[np.dtype] = np.float64, ) -> None: """ Write numpy data into NIfTI files to disk. This function converts data into the coordinate system defined by `target_affine` when `target_affine` is specified. If the coordinate transform between `affine` and `target_affine` could be achieved by simply transposing and flipping `data`, no resampling will happen. otherwise this function will resample `data` using the coordinate transform computed from `affine` and `target_affine`. Note that the shape of the resampled `data` may subject to some rounding errors. For example, resampling a 20x20 pixel image from pixel size (1.5, 1.5)-mm to (3.0, 3.0)-mm space will return a 10x10-pixel image. However, resampling a 20x20-pixel image from pixel size (2.0, 2.0)-mm to (3.0, 3.0)-mma space will output a 14x14-pixel image, where the image shape is rounded from 13.333x13.333 pixels. In this case `output_spatial_shape` could be specified so that this function writes image data to a designated shape. When `affine` and `target_affine` are None, the data will be saved with an identity matrix as the image affine. This function assumes the NIfTI dimension notations. Spatially it supports up to three dimensions, that is, H, HW, HWD for 1D, 2D, 3D respectively. When saving multiple time steps or multiple channels `data`, time and/or modality axes should be appended after the first three dimensions. For example, shape of 2D eight-class segmentation probabilities to be saved could be `(64, 64, 1, 8)`. Also, data in shape (64, 64, 8), (64, 64, 8, 1) will be considered as a single-channel 3D image. Args: data: input data to write to file. file_name: expected file name that saved on disk. affine: the current affine of `data`. Defaults to `np.eye(4)` target_affine: before saving the (`data`, `affine`) as a Nifti1Image, transform the data into the coordinates defined by `target_affine`. resample: whether to run resampling when the target affine could not be achieved by swapping/flipping data axes. output_spatial_shape: spatial shape of the output image. This option is used when resample = True. mode: {``"bilinear"``, ``"nearest"``} This option is used when ``resample = True``. Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} This option is used when ``resample = True``. Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample align_corners: Geometrically, we consider the pixels of the input as squares rather than points. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample dtype: data type for resampling computation. Defaults to ``np.float64`` for best precision. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``np.float32``. """ assert isinstance(data, np.ndarray), "input data must be numpy array." dtype = dtype or data.dtype sr = min(data.ndim, 3) if affine is None: affine = np.eye(4, dtype=np.float64) affine = to_affine_nd(sr, affine) if target_affine is None: target_affine = affine target_affine = to_affine_nd(sr, target_affine) if np.allclose(affine, target_affine, atol=1e-3): # no affine changes, save (data, affine) results_img = nib.Nifti1Image( data.astype(np.float32), to_affine_nd(3, target_affine) ) nib.save(results_img, file_name) return # resolve orientation start_ornt = nib.orientations.io_orientation(affine) target_ornt = nib.orientations.io_orientation(target_affine) ornt_transform = nib.orientations.ornt_transform(start_ornt, target_ornt) data_shape = data.shape data = nib.orientations.apply_orientation(data, ornt_transform) _affine = affine @ nib.orientations.inv_ornt_aff(ornt_transform, data_shape) if np.allclose(_affine, target_affine, atol=1e-3) or not resample: results_img = nib.Nifti1Image( data.astype(np.float32), to_affine_nd(3, target_affine) ) nib.save(results_img, file_name) return # need resampling affine_xform = AffineTransform( normalized=False, mode=mode, padding_mode=padding_mode, align_corners=align_corners, reverse_indexing=True, ) transform = np.linalg.inv(_affine) @ target_affine if output_spatial_shape is None: output_spatial_shape, _ = compute_shape_offset( data.shape, _affine, target_affine ) output_spatial_shape_ = list(output_spatial_shape) if data.ndim > 3: # multi channel, resampling each channel while len(output_spatial_shape_) < 3: output_spatial_shape_ = output_spatial_shape_ + [1] spatial_shape, channel_shape = data.shape[:3], data.shape[3:] data_ = data.reshape(list(spatial_shape) + [-1]) data_ = np.moveaxis(data_, -1, 0) # channel first for pytorch data_ = affine_xform( torch.as_tensor(np.ascontiguousarray(data_).astype(dtype)).unsqueeze(0), torch.as_tensor(np.ascontiguousarray(transform).astype(dtype)), spatial_size=output_spatial_shape_[:3], ) data_ = data_.squeeze(0).detach().cpu().numpy() data_ = np.moveaxis(data_, 0, -1) # channel last for nifti data_ = data_.reshape(list(data_.shape[:3]) + list(channel_shape)) else: # single channel image, need to expand to have batch and channel while len(output_spatial_shape_) < len(data.shape): output_spatial_shape_ = output_spatial_shape_ + [1] data_ = affine_xform( torch.as_tensor(np.ascontiguousarray(data).astype(dtype)[None, None]), torch.as_tensor(np.ascontiguousarray(transform).astype(dtype)), spatial_size=output_spatial_shape_[: len(data.shape)], ) data_ = data_.squeeze(0).squeeze(0).detach().cpu().numpy() results_img = nib.Nifti1Image( data_.astype(np.float32), to_affine_nd(3, target_affine) ) nib.save(results_img, file_name) return
def write_nifti( data: np.ndarray, file_name: str, affine: Optional[np.ndarray] = None, target_affine: Optional[np.ndarray] = None, resample: bool = True, output_spatial_shape: Optional[Sequence[int]] = None, mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, dtype: Optional[np.dtype] = None, ) -> None: """ Write numpy data into NIfTI files to disk. This function converts data into the coordinate system defined by `target_affine` when `target_affine` is specified. If the coordinate transform between `affine` and `target_affine` could be achieved by simply transposing and flipping `data`, no resampling will happen. otherwise this function will resample `data` using the coordinate transform computed from `affine` and `target_affine`. Note that the shape of the resampled `data` may subject to some rounding errors. For example, resampling a 20x20 pixel image from pixel size (1.5, 1.5)-mm to (3.0, 3.0)-mm space will return a 10x10-pixel image. However, resampling a 20x20-pixel image from pixel size (2.0, 2.0)-mm to (3.0, 3.0)-mma space will output a 14x14-pixel image, where the image shape is rounded from 13.333x13.333 pixels. In this case `output_spatial_shape` could be specified so that this function writes image data to a designated shape. When `affine` and `target_affine` are None, the data will be saved with an identity matrix as the image affine. This function assumes the NIfTI dimension notations. Spatially it supports up to three dimensions, that is, H, HW, HWD for 1D, 2D, 3D respectively. When saving multiple time steps or multiple channels `data`, time and/or modality axes should be appended after the first three dimensions. For example, shape of 2D eight-class segmentation probabilities to be saved could be `(64, 64, 1, 8)`. Also, data in shape (64, 64, 8), (64, 64, 8, 1) will be considered as a single-channel 3D image. Args: data: input data to write to file. file_name: expected file name that saved on disk. affine: the current affine of `data`. Defaults to `np.eye(4)` target_affine: before saving the (`data`, `affine`) as a Nifti1Image, transform the data into the coordinates defined by `target_affine`. resample: whether to run resampling when the target affine could not be achieved by swapping/flipping data axes. output_spatial_shape: spatial shape of the output image. This option is used when resample = True. mode: {``"bilinear"``, ``"nearest"``} This option is used when ``resample = True``. Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} This option is used when ``resample = True``. Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample dtype: convert the image to save to this data type. """ assert isinstance(data, np.ndarray), "input data must be numpy array." sr = min(data.ndim, 3) if affine is None: affine = np.eye(4, dtype=np.float64) affine = to_affine_nd(sr, affine) if target_affine is None: target_affine = affine target_affine = to_affine_nd(sr, target_affine) if np.allclose(affine, target_affine, atol=1e-3): # no affine changes, save (data, affine) results_img = nib.Nifti1Image( data.astype(dtype), to_affine_nd(3, target_affine) ) nib.save(results_img, file_name) return # resolve orientation start_ornt = nib.orientations.io_orientation(affine) target_ornt = nib.orientations.io_orientation(target_affine) ornt_transform = nib.orientations.ornt_transform(start_ornt, target_ornt) data_shape = data.shape data = nib.orientations.apply_orientation(data, ornt_transform) _affine = affine @ nib.orientations.inv_ornt_aff(ornt_transform, data_shape) if np.allclose(_affine, target_affine, atol=1e-3) or not resample: results_img = nib.Nifti1Image( data.astype(dtype), to_affine_nd(3, target_affine) ) nib.save(results_img, file_name) return # need resampling affine_xform = AffineTransform( normalized=False, mode=mode, padding_mode=padding_mode, align_corners=True, reverse_indexing=True, ) transform = np.linalg.inv(_affine) @ target_affine if output_spatial_shape is None: output_spatial_shape, _ = compute_shape_offset( data.shape, _affine, target_affine ) output_spatial_shape_ = list(output_spatial_shape) if data.ndim > 3: # multi channel, resampling each channel while len(output_spatial_shape_) < 3: output_spatial_shape_ = output_spatial_shape_ + [1] spatial_shape, channel_shape = data.shape[:3], data.shape[3:] data_ = data.reshape(list(spatial_shape) + [-1]) data_ = np.moveaxis(data_, -1, 0) # channel first for pytorch data_ = affine_xform( torch.from_numpy(data_.astype(np.float64)).unsqueeze(0), torch.from_numpy(transform.astype(np.float64)), spatial_size=output_spatial_shape_[:3], ) data_ = data_.squeeze(0).detach().cpu().numpy() data_ = np.moveaxis(data_, 0, -1) # channel last for nifti data_ = data_.reshape(list(data_.shape[:3]) + list(channel_shape)) else: # single channel image, need to expand to have batch and channel while len(output_spatial_shape_) < len(data.shape): output_spatial_shape_ = output_spatial_shape_ + [1] data_ = affine_xform( torch.from_numpy((data.astype(np.float64))[None, None]), torch.from_numpy(transform.astype(np.float64)), spatial_size=output_spatial_shape_[: len(data.shape)], ) data_ = data_.squeeze(0).squeeze(0).detach().cpu().numpy() dtype = dtype or data.dtype results_img = nib.Nifti1Image(data_.astype(dtype), to_affine_nd(3, target_affine)) nib.save(results_img, file_name) return
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError
def __init__( self, pixdim: Union[Sequence[float], float], diagonal: bool = False, mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, align_corners: bool = False, dtype: Optional[np.dtype] = np.float64, ) -> None: """ Args: pixdim: output voxel spacing. diagonal: whether to resample the input to have a diagonal affine matrix. If True, the input data is resampled to the following affine:: np.diag((pixdim_0, pixdim_1, ..., pixdim_n, 1)) This effectively resets the volume to the world coordinate system (RAS+ in nibabel). The original orientation, rotation, shearing are not preserved. If False, this transform preserves the axes orientation, orthogonal rotation and translation components from the original affine. This option will not flip/swap axes of the original data. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample align_corners: Geometrically, we consider the pixels of the input as squares rather than points. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample dtype: data type for resampling computation. Defaults to ``np.float64`` for best precision. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``np.float32``. """ self.pixdim = np.array(ensure_tuple(pixdim), dtype=np.float64) self.diagonal = diagonal self.mode: GridSampleMode = GridSampleMode(mode) self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode) self.align_corners = align_corners self.dtype = dtype
def __init__( self, pixdim: Union[Sequence[float], float], diagonal: bool = False, mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, dtype: Optional[np.dtype] = None, ) -> None: """ Args: pixdim: output voxel spacing. diagonal: whether to resample the input to have a diagonal affine matrix. If True, the input data is resampled to the following affine:: np.diag((pixdim_0, pixdim_1, ..., pixdim_n, 1)) This effectively resets the volume to the world coordinate system (RAS+ in nibabel). The original orientation, rotation, shearing are not preserved. If False, this transform preserves the axes orientation, orthogonal rotation and translation components from the original affine. This option will not flip/swap axes of the original data. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample dtype: output array data type. Defaults to ``np.float32``. """ self.pixdim = np.array(ensure_tuple(pixdim), dtype=np.float64) self.diagonal = diagonal self.mode: GridSampleMode = GridSampleMode(mode) self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode) self.dtype = dtype
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError
def __call__( self, data_array: np.ndarray, affine=None, mode: Optional[Union[GridSampleMode, str]] = None, padding_mode: Optional[Union[GridSamplePadMode, str]] = None, align_corners: Optional[bool] = None, dtype: Optional[np.dtype] = None, ): """ Args: data_array: in shape (num_channels, H[, W, ...]). affine (matrix): (N+1)x(N+1) original affine matrix for spatially ND `data_array`. Defaults to identity. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``self.mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``self.padding_mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample align_corners: Geometrically, we consider the pixels of the input as squares rather than points. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample dtype: data type for resampling computation. Defaults to ``self.dtype``. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``np.float32``. Raises: ValueError: When ``data_array`` has no spatial dimensions. ValueError: When ``pixdim`` is nonpositive. Returns: data_array (resampled into `self.pixdim`), original pixdim, current pixdim. """ _dtype = dtype or self.dtype or data_array.dtype sr = data_array.ndim - 1 if sr <= 0: raise ValueError("data_array must have at least one spatial dimension.") if affine is None: # default to identity affine = np.eye(sr + 1, dtype=np.float64) affine_ = np.eye(sr + 1, dtype=np.float64) else: affine_ = to_affine_nd(sr, affine) out_d = self.pixdim[:sr] if out_d.size < sr: out_d = np.append(out_d, [1.0] * (out_d.size - sr)) if np.any(out_d <= 0): raise ValueError(f"pixdim must be positive, got {out_d}.") # compute output affine, shape and offset new_affine = zoom_affine(affine_, out_d, diagonal=self.diagonal) output_shape, offset = compute_shape_offset( data_array.shape[1:], affine_, new_affine ) new_affine[:sr, -1] = offset[:sr] transform = np.linalg.inv(affine_) @ new_affine # adapt to the actual rank transform_ = to_affine_nd(sr, transform) # no resampling if it's identity transform if np.allclose(transform_, np.diag(np.ones(len(transform_))), atol=1e-3): output_data = data_array.copy().astype(np.float32) new_affine = to_affine_nd(affine, new_affine) return output_data, affine, new_affine # resample affine_xform = AffineTransform( normalized=False, mode=mode or self.mode, padding_mode=padding_mode or self.padding_mode, align_corners=self.align_corners if align_corners is None else align_corners, reverse_indexing=True, ) output_data = affine_xform( # AffineTransform requires a batch dim torch.as_tensor(np.ascontiguousarray(data_array).astype(_dtype)).unsqueeze(0), torch.as_tensor(np.ascontiguousarray(transform_).astype(_dtype)), spatial_size=output_shape, ) output_data = output_data.squeeze(0).detach().cpu().numpy().astype(np.float32) new_affine = to_affine_nd(affine, new_affine) return output_data, affine, new_affine
def __call__( self, data_array: np.ndarray, affine=None, mode: Optional[Union[GridSampleMode, str]] = None, padding_mode: Optional[Union[GridSamplePadMode, str]] = None, dtype: Optional[np.dtype] = None, ): """ Args: data_array: in shape (num_channels, H[, W, ...]). affine (matrix): (N+1)x(N+1) original affine matrix for spatially ND `data_array`. Defaults to identity. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``self.mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``self.padding_mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample dtype: output array data type. Defaults to ``self.dtype``. Raises: ValueError: When ``data_array`` has no spatial dimensions. ValueError: When ``pixdim`` is nonpositive. Returns: data_array (resampled into `self.pixdim`), original pixdim, current pixdim. """ sr = data_array.ndim - 1 if sr <= 0: raise ValueError("data_array must have at least one spatial dimension.") if affine is None: # default to identity affine = np.eye(sr + 1, dtype=np.float64) affine_ = np.eye(sr + 1, dtype=np.float64) else: affine_ = to_affine_nd(sr, affine) out_d = self.pixdim[:sr] if out_d.size < sr: out_d = np.append(out_d, [1.0] * (out_d.size - sr)) if np.any(out_d <= 0): raise ValueError(f"pixdim must be positive, got {out_d}.") # compute output affine, shape and offset new_affine = zoom_affine(affine_, out_d, diagonal=self.diagonal) output_shape, offset = compute_shape_offset( data_array.shape[1:], affine_, new_affine ) new_affine[:sr, -1] = offset[:sr] transform = np.linalg.inv(affine_) @ new_affine # adapt to the actual rank transform_ = to_affine_nd(sr, transform) _dtype = dtype or self.dtype or np.float32 # no resampling if it's identity transform if np.allclose(transform_, np.diag(np.ones(len(transform_))), atol=1e-3): output_data = data_array.copy().astype(_dtype) new_affine = to_affine_nd(affine, new_affine) return output_data, affine, new_affine # resample affine_xform = AffineTransform( normalized=False, mode=mode or self.mode, padding_mode=padding_mode or self.padding_mode, align_corners=True, reverse_indexing=True, ) output_data = affine_xform( torch.from_numpy((data_array.astype(np.float64))).unsqueeze( 0 ), # AffineTransform requires a batch dim torch.from_numpy(transform_.astype(np.float64)), spatial_size=output_shape, ) output_data = output_data.squeeze(0).detach().cpu().numpy().astype(_dtype) new_affine = to_affine_nd(affine, new_affine) return output_data, affine, new_affine
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError
def __init__( self, angle: Union[Sequence[float], float], keep_size: bool = True, mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, align_corners: bool = False, dtype: Optional[np.dtype] = np.float64, ) -> None: self.angle = angle self.keep_size = keep_size self.mode: GridSampleMode = GridSampleMode(mode) self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode) self.align_corners = align_corners self.dtype = dtype
def __init__( self, angle: Union[Sequence[float], float], keep_size: bool = True, mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, align_corners: bool = False, ) -> None: self.angle = angle self.keep_size = keep_size self.mode: GridSampleMode = GridSampleMode(mode) self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode) self.align_corners = align_corners
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError
def __call__( self, img: np.ndarray, mode: Optional[Union[GridSampleMode, str]] = None, padding_mode: Optional[Union[GridSamplePadMode, str]] = None, align_corners: Optional[bool] = None, dtype: Optional[np.dtype] = None, ) -> np.ndarray: """ Args: img: channel first array, must have shape: [chns, H, W] or [chns, H, W, D]. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``self.mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``self.padding_mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample align_corners: Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample align_corners: Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample dtype: data type for resampling computation. Defaults to ``self.dtype``. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``np.float32``. Raises: ValueError: When ``img`` spatially is not one of [2D, 3D]. """ _dtype = dtype or self.dtype or img.dtype im_shape = np.asarray(img.shape[1:]) # spatial dimensions input_ndim = len(im_shape) if input_ndim not in (2, 3): raise ValueError( f"Unsupported img dimension: {input_ndim}, available options are [2, 3]." ) _angle = ensure_tuple_rep(self.angle, 1 if input_ndim == 2 else 3) _rad = np.deg2rad(_angle) transform = create_rotate(input_ndim, _rad) shift = create_translate(input_ndim, (im_shape - 1) / 2) if self.keep_size: output_shape = im_shape else: corners = np.asarray( np.meshgrid(*[(0, dim) for dim in im_shape], indexing="ij") ).reshape((len(im_shape), -1)) corners = transform[:-1, :-1] @ corners output_shape = (corners.ptp(axis=1) + 0.5).astype(int) shift_1 = create_translate(input_ndim, -(output_shape - 1) / 2) transform = shift @ transform @ shift_1 xform = AffineTransform( normalized=False, mode=mode or self.mode, padding_mode=padding_mode or self.padding_mode, align_corners=self.align_corners if align_corners is None else align_corners, reverse_indexing=True, ) output = xform( torch.as_tensor(np.ascontiguousarray(img).astype(_dtype)).unsqueeze(0), torch.as_tensor(np.ascontiguousarray(transform).astype(_dtype)), spatial_size=output_shape, ) output = output.squeeze(0).detach().cpu().numpy().astype(np.float32) return output
def __call__( self, img: np.ndarray, mode: Optional[Union[GridSampleMode, str]] = None, padding_mode: Optional[Union[GridSamplePadMode, str]] = None, align_corners: Optional[bool] = None, ) -> np.ndarray: """ Args: img: channel first array, must have shape: [chns, H, W] or [chns, H, W, D]. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``self.mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``self.padding_mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample align_corners: Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample align_corners: Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample Raises: ValueError: When ``img`` spatially is not one of [2D, 3D]. """ im_shape = np.asarray(img.shape[1:]) # spatial dimensions input_ndim = len(im_shape) if input_ndim not in (2, 3): raise ValueError( f"Unsupported img dimension: {input_ndim}, available options are [2, 3]." ) _angle = ensure_tuple_rep(self.angle, 1 if input_ndim == 2 else 3) _rad = np.deg2rad(_angle) transform = create_rotate(input_ndim, _rad) shift = create_translate(input_ndim, (im_shape - 1) / 2) if self.keep_size: output_shape = im_shape else: corners = np.asarray( np.meshgrid(*[(0, dim) for dim in im_shape], indexing="ij") ).reshape((len(im_shape), -1)) corners = transform[:-1, :-1] @ corners output_shape = (corners.ptp(axis=1) + 0.5).astype(int) shift_1 = create_translate(input_ndim, -(output_shape - 1) / 2) transform = shift @ transform @ shift_1 _dtype = img.dtype xform = AffineTransform( normalized=False, mode=mode or self.mode, padding_mode=padding_mode or self.padding_mode, align_corners=self.align_corners if align_corners is None else align_corners, reverse_indexing=True, ) output = xform( torch.from_numpy(img.astype(np.float64)).unsqueeze(0), torch.from_numpy(transform.astype(np.float64)), spatial_size=output_shape, ) output = output.squeeze(0).detach().cpu().numpy().astype(_dtype) return output
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError
def __init__( self, range_x: Union[Tuple[float, float], float] = 0.0, range_y: Union[Tuple[float, float], float] = 0.0, range_z: Union[Tuple[float, float], float] = 0.0, prob: float = 0.1, keep_size: bool = True, mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, align_corners: bool = False, dtype: Optional[np.dtype] = np.float64, ) -> None: self.range_x = ensure_tuple(range_x) if len(self.range_x) == 1: self.range_x = tuple(sorted([-self.range_x[0], self.range_x[0]])) self.range_y = ensure_tuple(range_y) if len(self.range_y) == 1: self.range_y = tuple(sorted([-self.range_y[0], self.range_y[0]])) self.range_z = ensure_tuple(range_z) if len(self.range_z) == 1: self.range_z = tuple(sorted([-self.range_z[0], self.range_z[0]])) self.prob = prob self.keep_size = keep_size self.mode: GridSampleMode = GridSampleMode(mode) self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode) self.align_corners = align_corners self.dtype = dtype self._do_transform = False self.x = 0.0 self.y = 0.0 self.z = 0.0
def __init__( self, range_x: Union[Tuple[float, float], float] = 0.0, range_y: Union[Tuple[float, float], float] = 0.0, range_z: Union[Tuple[float, float], float] = 0.0, prob: float = 0.1, keep_size: bool = True, mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR, padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER, align_corners: bool = False, ) -> None: self.range_x = ensure_tuple(range_x) if len(self.range_x) == 1: self.range_x = tuple(sorted([-self.range_x[0], self.range_x[0]])) self.range_y = ensure_tuple(range_y) if len(self.range_y) == 1: self.range_y = tuple(sorted([-self.range_y[0], self.range_y[0]])) self.range_z = ensure_tuple(range_z) if len(self.range_z) == 1: self.range_z = tuple(sorted([-self.range_z[0], self.range_z[0]])) self.prob = prob self.keep_size = keep_size self.mode: GridSampleMode = GridSampleMode(mode) self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode) self.align_corners = align_corners self._do_transform = False self.x = 0.0 self.y = 0.0 self.z = 0.0
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError
def __call__( self, img: np.ndarray, mode: Optional[Union[GridSampleMode, str]] = None, padding_mode: Optional[Union[GridSamplePadMode, str]] = None, align_corners: Optional[bool] = None, dtype: Optional[np.dtype] = None, ) -> np.ndarray: """ Args: img: channel first array, must have shape 2D: (nchannels, H, W), or 3D: (nchannels, H, W, D). mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``self.mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``self.padding_mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample align_corners: Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample dtype: data type for resampling computation. Defaults to ``self.dtype``. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``np.float32``. """ self.randomize() if not self._do_transform: return img rotator = Rotate( angle=self.x if img.ndim == 3 else (self.x, self.y, self.z), keep_size=self.keep_size, mode=mode or self.mode, padding_mode=padding_mode or self.padding_mode, align_corners=self.align_corners if align_corners is None else align_corners, dtype=dtype or self.dtype or img.dtype, ) return rotator(img)
def __call__( self, img: np.ndarray, mode: Optional[Union[GridSampleMode, str]] = None, padding_mode: Optional[Union[GridSamplePadMode, str]] = None, align_corners: Optional[bool] = None, ) -> np.ndarray: """ Args: img: channel first array, must have shape 2D: (nchannels, H, W), or 3D: (nchannels, H, W, D). mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``self.mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``self.padding_mode``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample align_corners: Defaults to ``self.align_corners``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample """ self.randomize() if not self._do_transform: return img rotator = Rotate( angle=self.x if img.ndim == 3 else (self.x, self.y, self.z), keep_size=self.keep_size, mode=mode or self.mode, padding_mode=padding_mode or self.padding_mode, align_corners=self.align_corners if align_corners is None else align_corners, ) return rotator(img)
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError
def __init__( self, keys: KeysCollection, pixdim: Sequence[float], diagonal: bool = False, mode: GridSampleModeSequence = GridSampleMode.BILINEAR, padding_mode: GridSamplePadModeSequence = GridSamplePadMode.BORDER, align_corners: Union[Sequence[bool], bool] = False, dtype: Optional[Union[Sequence[np.dtype], np.dtype]] = np.float64, meta_key_postfix: str = "meta_dict", ) -> None: """ Args: pixdim: output voxel spacing. diagonal: whether to resample the input to have a diagonal affine matrix. If True, the input data is resampled to the following affine:: np.diag((pixdim_0, pixdim_1, pixdim_2, 1)) This effectively resets the volume to the world coordinate system (RAS+ in nibabel). The original orientation, rotation, shearing are not preserved. If False, the axes orientation, orthogonal rotation and translations components from the original affine will be preserved in the target affine. This option will not flip/swap axes against the original ones. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample It also can be a sequence of string, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample It also can be a sequence of string, each element corresponds to a key in ``keys``. align_corners: Geometrically, we consider the pixels of the input as squares rather than points. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample It also can be a sequence of bool, each element corresponds to a key in ``keys``. dtype: data type for resampling computation. Defaults to ``np.float64`` for best precision. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``np.float32``. It also can be a sequence of np.dtype, each element corresponds to a key in ``keys``. meta_key_postfix: use `key_{postfix}` to to fetch the meta data according to the key data, default is `meta_dict`, the meta data is a dictionary object. For example, to handle key `image`, read/write affine matrices from the metadata `image_meta_dict` dictionary's `affine` field. Raises: TypeError: When ``meta_key_postfix`` is not a ``str``. """ super().__init__(keys) self.spacing_transform = Spacing(pixdim, diagonal=diagonal) self.mode = ensure_tuple_rep(mode, len(self.keys)) self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys)) self.align_corners = ensure_tuple_rep(align_corners, len(self.keys)) self.dtype = ensure_tuple_rep(dtype, len(self.keys)) if not isinstance(meta_key_postfix, str): raise TypeError( f"meta_key_postfix must be a str but is {type(meta_key_postfix).__name__}." ) self.meta_key_postfix = meta_key_postfix
def __init__( self, keys: KeysCollection, pixdim: Sequence[float], diagonal: bool = False, mode: GridSampleModeSequence = GridSampleMode.BILINEAR, padding_mode: GridSamplePadModeSequence = GridSamplePadMode.BORDER, dtype: Optional[Union[Sequence[np.dtype], np.dtype]] = None, meta_key_postfix: str = "meta_dict", ) -> None: """ Args: pixdim: output voxel spacing. diagonal: whether to resample the input to have a diagonal affine matrix. If True, the input data is resampled to the following affine:: np.diag((pixdim_0, pixdim_1, pixdim_2, 1)) This effectively resets the volume to the world coordinate system (RAS+ in nibabel). The original orientation, rotation, shearing are not preserved. If False, the axes orientation, orthogonal rotation and translations components from the original affine will be preserved in the target affine. This option will not flip/swap axes against the original ones. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample It also can be a sequence of string, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample It also can be a sequence of string, each element corresponds to a key in ``keys``. dtype: output array data type. Defaults to None to use input data's dtype. It also can be a sequence of np.dtype, each element corresponds to a key in ``keys``. meta_key_postfix: use `key_{postfix}` to to fetch the meta data according to the key data, default is `meta_dict`, the meta data is a dictionary object. For example, to handle key `image`, read/write affine matrices from the metadata `image_meta_dict` dictionary's `affine` field. Raises: TypeError: When ``meta_key_postfix`` is not a ``str``. """ super().__init__(keys) self.spacing_transform = Spacing(pixdim, diagonal=diagonal) self.mode = ensure_tuple_rep(mode, len(self.keys)) self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys)) self.dtype = ensure_tuple_rep(dtype, len(self.keys)) if not isinstance(meta_key_postfix, str): raise TypeError( f"meta_key_postfix must be a str but is {type(meta_key_postfix).__name__}." ) self.meta_key_postfix = meta_key_postfix
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError
def __call__(self, data): d = dict(data) for idx, key in enumerate(self.keys): meta_data = d[f"{key}_{self.meta_key_postfix}"] # resample array of each corresponding key # using affine fetched from d[affine_key] d[key], _, new_affine = self.spacing_transform( data_array=d[key], affine=meta_data["affine"], mode=self.mode[idx], padding_mode=self.padding_mode[idx], align_corners=self.align_corners[idx], dtype=self.dtype[idx], ) # set the 'affine' key meta_data["affine"] = new_affine return d
def __call__(self, data): d = dict(data) for idx, key in enumerate(self.keys): meta_data = d[f"{key}_{self.meta_key_postfix}"] # resample array of each corresponding key # using affine fetched from d[affine_key] d[key], _, new_affine = self.spacing_transform( data_array=d[key], affine=meta_data["affine"], mode=self.mode[idx], padding_mode=self.padding_mode[idx], dtype=self.dtype[idx], ) # set the 'affine' key meta_data["affine"] = new_affine return d
https://github.com/Project-MONAI/MONAI/issues/832
====================================================================== FAIL: test_training (__main__.IntegrationSegmentation3D) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_integration_segmentation_3d.py", line 257, in test_training rtol=1e-3, File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose verbose=verbose, header=header, equal_nan=equal_nan) File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare raise AssertionError(msg) AssertionError: Not equal to tolerance rtol=0.001, atol=0 Mismatched elements: 6 / 6 (100%) Max absolute difference: 0.01720129 Max relative difference: 0.04047175 x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818]) y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ]) ---------------------------------------------------------------------- Ran 1 test in 92.377s FAILED (failures=1)
AssertionError