Run flake8 against all py files
13478
def lint():
    """"""
    py_files = subprocess.check_output("git ls-files")
    if PY3:
        py_files = py_files.decode()
    py_files = [x for x in py_files.split() if x.endswith('.py')]
    py_files = ' '.join(py_files)
    sh("%s -m flake8 %s" % (PYTHON, py_files), nolog=True)
695610
def clean():
    ''''''

    basedir = dirname(__file__)

    print(cyan('delete temp files and dirs for packaging'))
    local(flo(
        'rm -rf  '
        '{basedir}/.eggs/  '
        '{basedir}/fabsetup.egg-info/  '
        '{basedir}/dist  '
        '{basedir}/README  '
        '{basedir}/build/  '
    ))

    print(cyan('\ndelete temp files and dirs for editing'))
    local(flo(
        'rm -rf  '
        '{basedir}/.cache  '
        '{basedir}/.ropeproject  '
    ))

    print(cyan('\ndelete bytecode compiled versions of the python src'))
    # cf. http://stackoverflow.com/a/30659970
    local(flo('find  {basedir}/fabsetup  '
              'fabfile*  ') +
          '\( -name \*pyc -o -name \*.pyo -o -name __pycache__ '
          '-o -name \*.so -o -name \*.o -o -name \*.c \) '
          '-prune '
          '-exec rm -rf {} + || true')
1039385
def clean_python(ctx, dry_run=False):
    """"""
    # MAYBE NOT: "**/__pycache__"
    cleanup_dirs(["build", "dist", "*.egg-info", "**/__pycache__"],
                 dry_run=dry_run)
    if not dry_run:
        ctx.run("py.cleanup")
    cleanup_files(["**/*.pyc", "**/*.pyo", "**/*$py.class"], dry_run=dry_run)
120746
def run():
    """"""

    # Use print() instead of logging when running in CLI mode:
    set_pyftpsync_logger(None)

    parser = argparse.ArgumentParser(
        description="Synchronize folders over FTP.",
        epilog="See also https://github.com/mar10/pyftpsync",
        parents=[verbose_parser],
    )

    # Note: we want to allow --version to be combined with --verbose. However
    # on Py2, argparse makes sub-commands mandatory, unless `action="version"` is used.
    if check_cli_verbose(3) > 3:
        version_info = "pyftpsync/{} Python/{} {}".format(
            __version__, PYTHON_VERSION, platform.platform()
        )
    else:
        version_info = "{}".format(__version__)

    parser.add_argument("-V", "--version", action="version", version=version_info)

    subparsers = parser.add_subparsers(help="sub-command help")

    # --- Create the parser for the "upload" command ---------------------------

    sp = subparsers.add_parser(
        "upload",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="copy new and modified files to remote folder",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--force",
        action="store_true",
        help="overwrite remote files, even if the target is newer "
        "(but no conflict was detected)",
    )
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["local", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )
    sp.add_argument(
        "--delete",
        action="store_true",
        help="remove remote files if they don't exist locally",
    )
    sp.add_argument(
        "--delete-unmatched",
        action="store_true",
        help="remove remote files if they don't exist locally "
        "or don't match the current filter (implies '--delete' option)",
    )

    sp.set_defaults(command="upload")

    # --- Create the parser for the "download" command -------------------------

    sp = subparsers.add_parser(
        "download",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="copy new and modified files from remote folder to local target",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--force",
        action="store_true",
        help="overwrite local files, even if the target is newer "
        "(but no conflict was detected)",
    )
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["remote", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )
    sp.add_argument(
        "--delete",
        action="store_true",
        help="remove local files if they don't exist on remote target",
    )
    sp.add_argument(
        "--delete-unmatched",
        action="store_true",
        help="remove local files if they don't exist on remote target "
        "or don't match the current filter (implies '--delete' option)",
    )

    sp.set_defaults(command="download")

    # --- Create the parser for the "sync" command -----------------------------

    sp = subparsers.add_parser(
        "sync",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="synchronize new and modified files between remote folder and local target",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["old", "new", "local", "remote", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )

    sp.set_defaults(command="sync")

    # --- Create the parser for the "run" command -----------------------------

    add_run_parser(subparsers)

    # --- Create the parser for the "scan" command -----------------------------

    add_scan_parser(subparsers)

    # --- Parse command line ---------------------------------------------------

    args = parser.parse_args()

    args.verbose -= args.quiet
    del args.quiet

    # print("verbose", args.verbose)

    ftp_debug = 0
    if args.verbose >= 6:
        ftp_debug = 1

    # Modify the `args` from the `pyftpsync.yaml` config:
    if getattr(args, "command", None) == "run":
        handle_run_command(parser, args)

    if callable(getattr(args, "command", None)):
        # scan_handler
        try:
            return args.command(parser, args)
        except KeyboardInterrupt:
            print("\nAborted by user.", file=sys.stderr)
            sys.exit(3)

    elif not hasattr(args, "command"):
        parser.error(
            "missing command (choose from 'upload', 'download', 'run', 'sync', 'scan')"
        )

    # Post-process and check arguments
    if hasattr(args, "delete_unmatched") and args.delete_unmatched:
        args.delete = True

    args.local_target = make_target(args.local, {"ftp_debug": ftp_debug})

    if args.remote == ".":
        parser.error("'.' is expected to be the local target (not remote)")
    args.remote_target = make_target(args.remote, {"ftp_debug": ftp_debug})
    if not isinstance(args.local_target, FsTarget) and isinstance(
        args.remote_target, FsTarget
    ):
        parser.error("a file system target is expected to be local")

    # Let the command handler do its thing
    opts = namespace_to_dict(args)
    if args.command == "upload":
        s = UploadSynchronizer(args.local_target, args.remote_target, opts)
    elif args.command == "download":
        s = DownloadSynchronizer(args.local_target, args.remote_target, opts)
    elif args.command == "sync":
        s = BiDirSynchronizer(args.local_target, args.remote_target, opts)
    else:
        parser.error("unknown command '{}'".format(args.command))

    s.is_script = True

    try:
        s.run()
    except KeyboardInterrupt:
        print("\nAborted by user.", file=sys.stderr)
        sys.exit(3)
    finally:
        # Prevent sporadic exceptions in ftplib, when closing in __del__
        s.local.close()
        s.remote.close()

    stats = s.get_stats()
    if args.verbose >= 5:
        pprint(stats)
    elif args.verbose >= 1:
        if args.dry_run:
            print("(DRY-RUN) ", end="")
        print(
            "Wrote {}/{} files in {} directories, skipped: {}.".format(
                stats["files_written"],
                stats["local_files"],
                stats["local_dirs"],
                stats["conflict_files_skipped"],
            ),
            end="",
        )
        if stats["interactive_ask"]:
            print()
        else:
            print(" Elap: {}.".format(stats["elap_str"]))

    return
407285
def _register_pyflakes_check():
    """"""
    from flake8_isort import Flake8Isort
    from flake8_blind_except import check_blind_except

    # Resolving conflicts between pep8 and pyflakes.
    codes = {
        "UnusedImport": "F401",
        "ImportShadowedByLoopVar": "F402",
        "ImportStarUsed": "F403",
        "LateFutureImport": "F404",
        "Redefined": "F801",
        "RedefinedInListComp": "F812",
        "UndefinedName": "F821",
        "UndefinedExport": "F822",
        "UndefinedLocal": "F823",
        "DuplicateArgument": "F831",
        "UnusedVariable": "F841",
    }

    for name, obj in vars(pyflakes.messages).items():
        if name[0].isupper() and obj.message:
            obj.tpl = "{0} {1}".format(codes.get(name, "F999"), obj.message)

    pep8.register_check(_PyFlakesChecker, codes=['F'])
    # FIXME parser hack
    parser = pep8.get_parser('', '')
    Flake8Isort.add_options(parser)
    options, args = parser.parse_args([])
    # end of hack
    pep8.register_check(Flake8Isort, codes=['I'])
    pep8.register_check(check_blind_except, codes=['B90'])
1329864
def run(self):
        
        with open('src/gvar/__init__.py', 'a') as gvfile:
            gvfile.write("\n__version__ = '%s'\n" % GVAR_VERSION)
        _build_py.run(self)
1044436
def to_flake8(self, checker_cls: type) -> Flake8Error:
        
        return Flake8Error(
            line_number=self.line_number,
            offset=self.offset,
            text=self.text,
            checker_cls=checker_cls,
        )
820639
def run
      command = ['flay', '--mass', @config['mass_threshold'].to_s, '--fuzzy', @config['fuzzy'].to_s]
      # Use a more liberal detection method
      command += ['--liberal'] if @config['liberal']
      messages = []
      # Run the command for each file
      applicable_files.each do |file|
        result = execute(command, args: [file])
        results = result.stdout.split("\n\n")
        results.shift
        unless results.empty?
          error_message = results.join("\n").gsub(/^\d+\)\s*/, '')
          message = Overcommit::Hook::Message.new(:error, nil, nil, error_message)
          messages << message
        end
      end
      messages
    end
672050
def _setup_py_run_from_dir(root_dir, py_interpreter):
    """"""
    data = {}
    with _enter_single_subdir(root_dir) as single_subdir:
        if not os.path.exists("setup.py"):
            raise Exception("'setup.py' does not exist in '%s'" % (
                single_subdir))
        # generate a temporary json file which contains the metadata
        output_json = tempfile.NamedTemporaryFile()
        cmd = "%s setup.py -q --command-packages metaextract " \
              "metaextract -o %s " % (py_interpreter, output_json.name)
        try:
            subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
        except subprocess.CalledProcessError:
            # try again with a encoding in setup.py
            _set_file_encoding_utf8("setup.py")
            subprocess.check_output(cmd, shell=True)

        # read json file and return data
        with open(output_json.name, "r") as f:
            data = json.loads(f.read())

        # sort some of the keys if the dict values are lists
        for key in ['data_files', 'entry_points', 'extras_require',
                    'install_requires', 'setup_requires', 'scripts',
                    'tests_require', 'tests_suite']:
            if key in data['data'] and isinstance(data['data'][key], list):
                data['data'][key] = sorted(data['data'][key])
    return data
643070
def pypi():
    ''''''
    if not query_yes_no('version updated in '
                        '`fabsetup/_version.py`?'):
        print('abort')
    else:
        print(cyan('\n## clean-up\n'))
        execute(clean)

        basedir = dirname(__file__)

        # latest_pythons = _determine_latest_pythons()
        # # e.g. highest_minor: '3.6'
        # highest_minor = _highest_minor(latest_pythons)
        # python = flo('python{highest_minor}')
        python = 'python'

        print(cyan('\n## build package'))
        local(flo('cd {basedir}  &&  {python}  setup.py  sdist'))

        print(cyan('\n## upload package'))
        local(flo('cd {basedir}  &&  {python} -m twine upload  dist/*'))
551510
def lint(args):
    """"""
    application = get_current_application()
    if not args:
        args = [application.name, 'tests']
    args = ['flake8'] + list(args)
    run.main(args, standalone_mode=False)
261298
def run(self):
        """"""
        flag = True
        if self._exeng == 'dpkt':
            flag, engine = self.import_test('dpkt', name='DPKT')
            if flag:
                return self._run_dpkt(engine)
        elif self._exeng == 'scapy':
            flag, engine = self.import_test('scapy.all', name='Scapy')
            if flag:
                return self._run_scapy(engine)
        elif self._exeng == 'pyshark':
            flag, engine = self.import_test('pyshark', name='PyShark')
            if flag:
                return self._run_pyshark(engine)
        elif self._exeng == 'pipeline':
            flag, engine = self.import_test('multiprocessing', name='Pipeline Multiprocessing')
            self._flag_m = flag = bool(flag and (self._flag_a and CPU_CNT > 1))
            if self._flag_m:
                return self._run_pipeline(engine)
            warnings.warn(f'extraction engine Pipeline Multiprocessing is not available; '
                          'using default engine instead', EngineWarning, stacklevel=stacklevel())
        elif self._exeng == 'server':
            flag, engine = self.import_test('multiprocessing', name='Server Multiprocessing')
            self._flag_m = flag = bool(flag and (self._flag_a and CPU_CNT > 2))
            if self._flag_m:
                return self._run_server(engine)
            warnings.warn(f'extraction engine Server Multiprocessing is not available; '
                          'using default engine instead', EngineWarning, stacklevel=stacklevel())
        elif self._exeng not in ('default', 'pcapkit'):
            flag = False
            warnings.warn(f'unsupported extraction engine: {self._exeng}; '
                          'using default engine instead', EngineWarning, stacklevel=stacklevel())

        # using default/pcapkit engine
        self._exeng = self._exeng if flag else 'default'
        self.record_header()            # read PCAP global header
        self.record_frames()
913780
def _run_with_different_python(executable):
    
    args = [arg for arg in sys.argv if arg != VIRTUALENV_OPTION]
    args.insert(0, executable)
    print("Running bootstrap.py with {0}".format(executable))
    exit(subprocess.call(args))
248203
def run_all():
    '''
    
    '''
    plugins = list_plugins()
    ret = {}
    for plugin in plugins:
        ret.update(run(plugin))
    return ret
305586
def recompile_all(path):
    """"""
    import os
    if os.path.isdir(path):
        for root, dirs, files in os.walk(path):
            for name in files:
                if name.endswith('.py'):
                    filename = os.path.abspath(os.path.join(root, name))
                    print >> sys.stderr, filename
                    recompile(filename)
    else:
        filename = os.path.abspath(path)
        recompile(filename)
139183
def run(files, temp_folder, arg=None):
    ""
    try:
        import pylint
    except ImportError:
        return NO_PYLINT_MSG

    # set default level of threshold
    arg = arg or SCORE

    py_files = filter_python_files(files)
    if not py_files:
        return False

    str_py_files = " ".join(py_files)
    cmd = "{0} {1}".format(PYLINT_CMD, str_py_files)
    output = bash(cmd).value()

    if 'rated' not in output:
        return False
    score = float(re.search("(\d.\d\d)/10", output).group(1))
    if score >= float(arg):
        return False
    return ("Pylint appreciated your {0} as {1},"
        "required threshold is {2}".format(PYLINT_TARGET, score, arg)
        )
823737
def run(self, *args, **kwargs):
        
        if self.gw and shiboken.isValid(self.gw):
            self.gw.deleteLater()
        mayawin = maya_main_window()
        self.gw = self.GenesisWin(parent=mayawin)
        self.gw.last_file.connect(self.save_lastfile)
        if not self.gw.get_current_file():
            c = self.get_config()
            try:
                f = models.TaskFile.objects.get(pk=c['lastfile'])
            except models.TaskFile.DoesNotExist:
                pass
            else:
                self.gw.browser.set_selection(f)
        self.gw.show()