Setup flake8 for code linting
Fix all flake8 warnings

This also fixes a bunch of missing imports in rare code paths.