Run CGI var to gVCF conversion from the command line.
341093
def from_command_line():
    
    # Parse options
    parser = argparse.ArgumentParser(
        description='Convert Complete Genomics var files to gVCF format.')
    parser.add_argument(
        '-d', '--refseqdir', metavar='REFSEQDIR', required=True,
        dest='refseqdir',
        help='Directory twobit reference genomes files are stored.')
    parser.add_argument(
        '-i', '--input', metavar='INPUTVARFILE',
        dest='cgivarfile',
        help='Path to Complete Genomics var file to convert. If omitted, data '
        ' also be piped in as standard input.')
    parser.add_argument(
        '-o', '--output', metavar='OUTPUTVCFFILE',
        dest='vcfoutfile',
        help='Path to where to save output VCF file.')
    parser.add_argument(
        '-D', '--download', action='store_true', dest='downloadrefseq',
        help='Download the 2bit file from UCSC to REFSEQDIR, if needed.')
    parser.add_argument(
        '-v', '--var-only', action='store_true', dest='varonly',
        help='Only report variant lines (i.e. VCF, but not gVCF)')
    args = parser.parse_args()

    # Get local twobit file from its directory. Download and store if needed.
    twobit_path, twobit_name = get_reference_genome_file(
        args.refseqdir, build='b37')
    # Handle input
    if sys.stdin.isatty():  # false if data is piped in
        var_input = args.cgivarfile
    else:
        var_input = sys.stdin
    # Handle output
    if args.vcfoutfile:
        convert_to_file(var_input,
                        args.vcfoutfile,
                        twobit_path,
                        twobit_name,
                        args.varonly)
    else:
        for line in convert(
                cgi_input=var_input,
                twobit_ref=twobit_path,
                twobit_name=twobit_name,
                var_only=args.varonly):
            print(line)
333661
def main(argv=None):
    ''''''

    program_name = os.path.basename(sys.argv[0])
    program_version = version
    program_build_date = "%s" % __updated__

    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
    #program_usage = '''usage: spam two eggs''' # optional - will be autogenerated by optparse
    program_longdesc = '''''' # optional - give further explanation about what the program does
    program_license = "Copyright 2015-2018 Mohamed El Amine SEHILI                                            \
                Licensed under the General Public License (GPL) Version 3 \nhttp://www.gnu.org/licenses/"

    if argv is None:
        argv = sys.argv[1:]
    try:
        # setup option parser
        parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
        
        group = OptionGroup(parser, "[Input-Output options]")
        group.add_option("-i", "--input", dest="input", help="Input audio or video file. Use - for stdin [default: read from microphone using pyaudio]", metavar="FILE")
        group.add_option("-t", "--input-type", dest="input_type", help="Input audio file type. Mandatory if file name has no extension [default: %default]", type=str, default=None, metavar="String")
        group.add_option("-M", "--max_time", dest="max_time", help="Max data (in seconds) to read from microphone/file [default: read until the end of file/stream]", type=float, default=None, metavar="FLOAT")
        group.add_option("-O", "--output-main", dest="output_main", help="Save main stream as. If omitted main stream will not be saved [default: omitted]", type=str, default=None, metavar="FILE")
        group.add_option("-o", "--output-tokens", dest="output_tokens", help="Output file name format for detections. Use {N} and {start} and {end} to build file names, example: 'Det_{N}_{start}-{end}.wav'", type=str, default=None, metavar="STRING")
        group.add_option("-T", "--output-type", dest="output_type", help="Audio type used to save detections and/or main stream. If not supplied will: (1). guess from extension or (2). use wav format", type=str, default=None, metavar="STRING")
        group.add_option("-u", "--use-channel", dest="use_channel", help="Choose channel to use from a multi-channel audio file (requires pydub). 'left', 'right' and 'mix' are accepted values. [Default: 1 (i.e. 1st or left channel)]", type=str, default="1", metavar="STRING")
        parser.add_option_group(group)
        
        
        group = OptionGroup(parser, "[Tokenization options]", "Set tokenizer options and energy threshold.")
        group.add_option("-a", "--analysis-window", dest="analysis_window", help="Size of analysis window in seconds [default: %default (10ms)]", type=float, default=0.01, metavar="FLOAT")
        group.add_option("-n", "--min-duration", dest="min_duration", help="Min duration of a valid audio event in seconds [default: %default]", type=float, default=0.2, metavar="FLOAT")
        group.add_option("-m", "--max-duration", dest="max_duration", help="Max duration of a valid audio event in seconds [default: %default]", type=float, default=5, metavar="FLOAT")
        group.add_option("-s", "--max-silence", dest="max_silence", help="Max duration of a consecutive silence within a valid audio event in seconds [default: %default]", type=float, default=0.3, metavar="FLOAT")
        group.add_option("-d", "--drop-trailing-silence", dest="drop_trailing_silence", help="Drop trailing silence from a detection [default: keep trailing silence]",  action="store_true", default=False)
        group.add_option("-e", "--energy-threshold", dest="energy_threshold", help="Log energy threshold for detection [default: %default]", type=float, default=50, metavar="FLOAT")
        parser.add_option_group(group)
        
        
        group = OptionGroup(parser, "[Audio parameters]", "Define audio parameters if data is read from a headerless file (raw or stdin) or you want to use different microphone parameters.")        
        group.add_option("-r", "--rate", dest="sampling_rate", help="Sampling rate of audio data [default: %default]", type=int, default=16000, metavar="INT")
        group.add_option("-c", "--channels", dest="channels", help="Number of channels of audio data [default: %default]", type=int, default=1, metavar="INT")
        group.add_option("-w", "--width", dest="sample_width", help="Number of bytes per audio sample [default: %default]", type=int, default=2, metavar="INT")
        group.add_option("-I", "--input-device-index", dest="input_device_index", help="Audio device index [default: %default] - only when using PyAudio", type=int, default=None, metavar="INT")
        group.add_option("-F", "--audio-frame-per-buffer", dest="frame_per_buffer", help="Audio frame per buffer [default: %default] - only when using PyAudio", type=int, default=1024, metavar="INT")
        parser.add_option_group(group)
        
        group = OptionGroup(parser, "[Do something with detections]", "Use these options to print, play or plot detections.") 
        group.add_option("-C", "--command", dest="command", help="Command to call when an audio detection occurs. Use $ to represent the file name to use with the command (e.g. -C 'du -h $')", default=None, type=str, metavar="STRING")
        group.add_option("-E", "--echo", dest="echo", help="Play back each detection immediately using pyaudio [default: do not play]",  action="store_true", default=False)
        group.add_option("-p", "--plot", dest="plot", help="Plot and show audio signal and detections (requires matplotlib)",  action="store_true", default=False)
        group.add_option("", "--save-image", dest="save_image", help="Save plotted audio signal and detections as a picture or a PDF file (requires matplotlib)",  type=str, default=None, metavar="FILE")
        group.add_option("", "--printf", dest="printf", help="print detections, one per line, using a user supplied format (e.g. '[{id}]: {start} -- {end}'). Available keywords {id}, {start}, {end} and {duration}",  type=str, default="{id} {start} {end}", metavar="STRING")
        group.add_option("", "--time-format", dest="time_format", help="format used to print {start} and {end}. [Default= %default]. %S: absolute time in sec. %I: absolute time in ms. If at least one of (%h, %m, %s, %i) is used, convert time into hours, minutes, seconds and millis (e.g. %h:%m:%s.%i). Only required fields are printed",  type=str, default="%S", metavar="STRING")
        parser.add_option_group(group)
        
        parser.add_option("-q", "--quiet", dest="quiet", help="Do not print any information about detections [default: print 'id', 'start' and 'end' of each detection]",  action="store_true", default=False)
        parser.add_option("-D", "--debug", dest="debug", help="Print processing operations to STDOUT",  action="store_true", default=False)
        parser.add_option("", "--debug-file", dest="debug_file", help="Print processing operations to FILE",  type=str, default=None, metavar="FILE")
        
        

        # process options
        (opts, args) = parser.parse_args(argv)
        
        if opts.input == "-":
            asource = StdinAudioSource(sampling_rate = opts.sampling_rate,
                                       sample_width = opts.sample_width,
                                       channels = opts.channels)
        #read data from a file
        elif opts.input is not None:
            asource = file_to_audio_source(filename=opts.input, filetype=opts.input_type, uc=opts.use_channel)
        
        # read data from microphone via pyaudio
        else:
            try:
                asource = PyAudioSource(sampling_rate = opts.sampling_rate,
                                        sample_width = opts.sample_width,
                                        channels = opts.channels,
                                        frames_per_buffer = opts.frame_per_buffer,
                                        input_device_index = opts.input_device_index)
            except Exception:
                sys.stderr.write("Cannot read data from audio device!\n")
                sys.stderr.write("You should either install pyaudio or read data from STDIN\n")
                sys.exit(2)
               
        logger = logging.getLogger(LOGGER_NAME)
        logger.setLevel(logging.DEBUG)
        
        handler = logging.StreamHandler(sys.stdout)
        if opts.quiet or not opts.debug:
            # only critical messages will be printed
            handler.setLevel(logging.CRITICAL)
        else:
            handler.setLevel(logging.DEBUG)
        
        logger.addHandler(handler)
        
        if opts.debug_file is not None:
            logger.setLevel(logging.DEBUG)
            opts.debug = True
            handler = logging.FileHandler(opts.debug_file, "w")
            fmt = logging.Formatter('[%(asctime)s] | %(message)s')
            handler.setFormatter(fmt)
            handler.setLevel(logging.DEBUG)
            logger.addHandler(handler)
        
        record = opts.output_main is not None or opts.plot or opts.save_image is not None
                        
        ads = ADSFactory.ads(audio_source = asource, block_dur = opts.analysis_window, max_time = opts.max_time, record = record)
        validator = AudioEnergyValidator(sample_width=asource.get_sample_width(), energy_threshold=opts.energy_threshold)
        
        
        if opts.drop_trailing_silence:
            mode = StreamTokenizer.DROP_TRAILING_SILENCE
        else:
            mode = 0
        
        analysis_window_per_second = 1. / opts.analysis_window
        tokenizer = StreamTokenizer(validator=validator, min_length=opts.min_duration * analysis_window_per_second,
                                    max_length=int(opts.max_duration * analysis_window_per_second),
                                    max_continuous_silence=opts.max_silence * analysis_window_per_second,
                                    mode = mode)
        
        
        observers = []
        tokenizer_worker = None
        
        if opts.output_tokens is not None:
            
            try:
                # check user format is correct
                fname  = opts.output_tokens.format(N=0, start=0, end=0)
                
                # find file type for detections
                tok_type =  opts.output_type
                if tok_type is None:
                    tok_type = os.path.splitext(opts.output_tokens)[1][1:]
                if tok_type == "": 
                    tok_type = "wav"
                
                token_saver = TokenSaverWorker(name_format=opts.output_tokens, filetype=tok_type,
                                               debug=opts.debug, logger=logger, sr=asource.get_sampling_rate(),
                                               sw=asource.get_sample_width(),
                                               ch=asource.get_channels())
                observers.append(token_saver)
            
            except Exception:
                sys.stderr.write("Wrong format for detections file name: '{0}'\n".format(opts.output_tokens))
                sys.exit(2)
            
        if opts.echo:
            try:
                player = player_for(asource)
                player_worker = PlayerWorker(player=player, debug=opts.debug, logger=logger)
                observers.append(player_worker)
            except Exception:
                sys.stderr.write("Cannot get an audio player!\n")
                sys.stderr.write("You should either install pyaudio or supply a command (-C option) to play audio\n")
                sys.exit(2)
                
        if opts.command is not None and len(opts.command) > 0:
            cmd_worker = CommandLineWorker(command=opts.command, debug=opts.debug, logger=logger)
            observers.append(cmd_worker)
        
        if not opts.quiet or opts.plot is not None or opts.save_image is not None:    
            oformat = opts.printf.replace("\\n", "\n").replace("\\t", "\t").replace("\\r", "\r")
            converter = seconds_to_str_fromatter(opts.time_format)
            log_worker = LogWorker(print_detections = not opts.quiet, output_format=oformat,
                                   time_formatter=converter, logger=logger, debug=opts.debug)
            observers.append(log_worker)
        
        tokenizer_worker = TokenizerWorker(ads, tokenizer, opts.analysis_window, observers)
        
        def _save_main_stream():
            # find file type
            main_type =  opts.output_type
            if main_type is None:
                main_type = os.path.splitext(opts.output_main)[1][1:]
            if main_type == "": 
                main_type = "wav"
            ads.close()
            ads.rewind()
            data = ads.get_audio_source().get_data_buffer()
            if len(data) > 0:
                save_audio_data(data=data, filename=opts.output_main, filetype=main_type, sr=asource.get_sampling_rate(),
                                sw = asource.get_sample_width(),
                                ch = asource.get_channels())
        
        def _plot():
            import numpy as np
            ads.close()
            ads.rewind()
            data = ads.get_audio_source().get_data_buffer()
            signal = AudioEnergyValidator._convert(data, asource.get_sample_width())
            detections = [(det[3] , det[4]) for det in log_worker.detections]
            max_amplitude = 2**(asource.get_sample_width() * 8 - 1) - 1
            energy_as_amp = np.sqrt(np.exp(opts.energy_threshold * np.log(10) / 10)) / max_amplitude
            plot_all(signal / max_amplitude, asource.get_sampling_rate(), energy_as_amp, detections, show = opts.plot, save_as = opts.save_image)
        
        
        # start observer threads
        for obs in observers:
            obs.start()
        # start tokenization thread
        tokenizer_worker.start()
        
        while True:
            time.sleep(1)
            if len(threading.enumerate()) == 1:
                break
            
        tokenizer_worker = None
            
        if opts.output_main is not None:
            _save_main_stream()
        if opts.plot or opts.save_image is not None:
            _plot()
            
        return 0
            
    except KeyboardInterrupt:
        
        if tokenizer_worker is not None:
            tokenizer_worker.stop()
        for obs in observers:
            obs.stop()
            
        if opts.output_main is not None:
            _save_main_stream()
        if opts.plot or opts.save_image is not None:
            _plot()
        
        return 0

    except Exception as e:
        sys.stderr.write(program_name + ": " + str(e) + "\n")
        sys.stderr.write("for help use -h\n")
        
        return 2
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)
1018312
def main(argv=None):
    
    if argv is None:
        argv = sys.argv

    parser = argparse.ArgumentParser(
        fromfile_prefix_chars='@',
        description=
        """Check whether cgroups are available and can be used for BenchExec.
           Part of BenchExec: https://github.com/sosy-lab/benchexec/""")
    parser.add_argument("--wait", type=int, default=1, metavar="SECONDS",
                        help='wait some time to ensure no process interferes with cgroups in the meantime (default: 1s)')
    parser.add_argument("--no-thread", action="store_true",
                        help='run check on the main thread instead of a separate thread'
                            + '(behavior of cgrulesengd differs depending on this)')

    options = parser.parse_args(argv[1:])

    if options.no_thread:
        check_cgroup_availability(options.wait)
    else:
        check_cgroup_availability_in_thread(options)
793029
def main(argv=None):
    ''''''
    
    program_name = os.path.basename(sys.argv[0])
    program_version = "v0.1"
    program_build_date = "%s" % __updated__
 
    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
    #program_usage = '''usage: spam two eggs''' # optional - will be autogenerated by optparse
    program_longdesc = '''''' # optional - give further explanation about what the program does
    program_license = "Copyright 2013 Renaud Dussurget"
 
    if argv is None:
        argv = sys.argv[1:]
    try:
        # setup option parser
        parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
        parser.add_option("-v", "--verbose", dest="verbose", action="store", type="int", help="set verbosity level [default: %default]",default=0)
        parser.add_option("-l", "--use_local_dims", dest="use_local_dims", action="store_true", help="Use local netcdf dimensions [default: %default]",default=True)
        parser.add_option("-O", "--overwrite", dest="overwrite", action="store_true", help="Overwrite output file [default: %default]",default=False)
        parser.add_option("-f", "--format", dest="format", action="store", help="Output NetCDF format [default: %default]",default="NETCDF4")

        
        #Add kwargs!
        kwargs_keys=[]
        for a in argv :
            if a.startswith('--'):
                parser.add_option(a,dest=a.replace('--',''),action="store", help="Additional keyword to use with nctools [default: %default]")
#                parser.set_defaults(**{a.replace('--',''):False})
                kwargs_keys.append(a.replace('--',''))

        # set defaults
#        parser.set_defaults(verbose="4",use_local_dims="True")
        
        # process options
        (opts, args) = parser.parse_args(argv)
        
        if opts.verbose > 0:
            print("verbosity level = %d" % opts.verbose)
            
        if len(args) != 3 :
            raise Exception('Program needs 3 arguments') 
            
        # MAIN BODY #
        
    except Exception, e:
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help")
        return 2

    #Get program arguments
    f1=args[0]
    f2=args[1]
    fout=args[2]
    
    #Get keyword arguments for nc
    kwargs={}
    for k in kwargs_keys :
        kwargs.update({k:eval(opts.__dict__.get(k))})
    
    ncr=nc(verbose=opts.verbose,use_local_dims=opts.use_local_dims)
    
    d1=ncr.load(f1,**kwargs)
    d2=ncr.load(f2,**kwargs)
    
    dout=d1.copy()
    for k in d2.keys():
        dout.update({k:d2.get(k)})
    
    attrStr=dout.get('_attributes',{})
    
    cmd=[os.path.basename(sys.argv[0])]
    for a in argv : cmd.append(a)
    attrStr.update({'history':attrStr.pop('history','') +' '.join(cmd)})
    dout.update({'_attributes':attrStr})
    ncr.write(dout,fout,clobber=opts.overwrite,format=opts.format)
1215343
def compile(script, vars={}, library_paths=[]):
    

    return _pyjq.Script(script.encode('utf-8'), vars=vars,
                        library_paths=library_paths)
47943
def main(argv):
    """"""
    _, black_model, white_model = argv
    utils.ensure_dir_exists(FLAGS.eval_sgf_dir)
    play_match(black_model, white_model, FLAGS.num_evaluation_games, FLAGS.eval_sgf_dir)
129057
def run(self):
    """"""
    compiler = new_compiler(compiler=self.compiler)
    if compiler.compiler_type == "msvc":
      self.define = [
          ("UNICODE", ""),
      ]

    else:
      command = "sh configure --disable-shared-libs"
      output = self._RunCommand(command)

      print_line = False
      for line in output.split("\n"):
        line = line.rstrip()
        if line == "configure:":
          print_line = True

        if print_line:
          print(line)

      self.define = [
          ("HAVE_CONFIG_H", ""),
          ("LOCALEDIR", "\"/usr/share/locale\""),
      ]

    build_ext.run(self)
145663
def main(argv):
    
    init()

    if OPTIONS.StdErrFileName.value:
        OPTIONS.stderr.value = open('wt', OPTIONS.StdErrFileName.value)

    asmlex.FILENAME = OPTIONS.inputFileName.value = argv[0]
    input_ = open(OPTIONS.inputFileName.value, 'rt').read()
    assemble(input_)
    generate_binary(OPTIONS.outputFileName.value, OPTIONS.output_file_type)
599506
def compilevcf(args):
    
    from jcvi.variation.str import LobSTRvcf

    p = OptionParser(compilevcf.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    folder, = args
    vcf_files = iglob(folder, "*.vcf,*.vcf.gz")
    for vcf_file in vcf_files:
        try:
            p = LobSTRvcf(columnidsfile=None)
            p.parse(vcf_file, filtered=False)
            res = p.items()
            if res:
                k, v = res[0]
                res = v.replace(',', '/')
            else:
                res = "-1/-1"
            num = op.basename(vcf_file).split(".")[0]
            print(num, res)
        except (TypeError, AttributeError) as e:
            p = TREDPARSEvcf(vcf_file)
            continue
128071
def main(argv=None):
    
    args = None
    cmd = None

    try:
        args = parse_args(argv)

        if args.quiet:
            logger.setLevel(logging.CRITICAL)

        elif args.verbose:
            logger.setLevel(logging.DEBUG)

        cmd = args.func(args)
        ret = cmd.run_cmd()
    except KeyboardInterrupt:
        logger.exception("interrupted by the user")
        ret = 252
    except NotDvcRepoError:
        logger.exception("")
        ret = 253
    except DvcParserError:
        ret = 254
    except Exception:  # pylint: disable=broad-except
        logger.exception("unexpected error")
        ret = 255

    Analytics().send_cmd(cmd, args, ret)

    return ret
789464
def main(argv=None):
    
    parser = argparse.ArgumentParser(
        description='Event storage and event proxy.',
        usage='%(prog)s <configfile>'
    )
    parser.add_argument('--exit-codeword', metavar="MSG", dest="exit_message",
                        default=None, help="An incoming message that makes"
                                           " Rewind quit. Used for testing.")
    parser.add_argument('configfile')

    args = argv if argv is not None else sys.argv[1:]
    args = parser.parse_args(args)

    config = configparser.SafeConfigParser()
    with open(args.configfile) as f:
        config.readfp(f)

    exitcode = run(config, args.exit_message)
    return exitcode
904005
def _EnvOpen(var, mode):
  """"""
  value = os.getenv(var)
  if value is None:
    raise ValueError("%s is not set" % var)

  fd = int(value)

  # If running on Windows, convert the file handle to a C file descriptor; see:
  # https://groups.google.com/forum/#!topic/dev-python/GeN5bFJWfJ4
  if _WINDOWS:
    fd = msvcrt.open_osfhandle(fd, 0)

  return os.fdopen(fd, mode)
313304
def main(argv, stdout=sys.stdout, stderr=sys.stderr):
    """"""
    # Wrap sys stdout for python 2, so print can understand unicode.
    linesep = os.linesep
    if sys.version_info[0] < 3:
        if stdout == sys.stdout:
            stdout = codecs.getwriter("utf-8")(stdout)
        if stderr == sys.stderr:
            stderr = codecs.getwriter("utf-8")(stderr)
        linesep = unicode(os.linesep)  # pylint: disable=undefined-variable

    arguments = docopt.docopt(
        __doc__, argv=argv[1:], version='git-lint v%s' % __VERSION__)

    json_output = arguments['--json']

    vcs, repository_root = get_vcs_root()

    if vcs is None:
        stderr.write('fatal: Not a git repository' + linesep)
        return 128

    commit = None
    if arguments['--last-commit']:
        commit = vcs.last_commit()

    if arguments['FILENAME']:
        invalid_filenames = find_invalid_filenames(arguments['FILENAME'],
                                                   repository_root)
        if invalid_filenames:
            invalid_filenames.append(('', ''))
            stderr.write(
                linesep.join(invalid[1] for invalid in invalid_filenames))
            return 2

        changed_files = vcs.modified_files(
            repository_root,
            tracked_only=arguments['--tracked'],
            commit=commit)
        modified_files = {}
        for filename in arguments['FILENAME']:
            normalized_filename = os.path.abspath(filename)
            modified_files[normalized_filename] = changed_files.get(
                normalized_filename)
    else:
        modified_files = vcs.modified_files(
            repository_root,
            tracked_only=arguments['--tracked'],
            commit=commit)

    linter_not_found = False
    files_with_problems = 0
    gitlint_config = get_config(repository_root)
    json_result = {}

    with futures.ThreadPoolExecutor(max_workers=multiprocessing.cpu_count())\
            as executor:
        processfile = functools.partial(process_file, vcs, commit,
                                        arguments['--force'], gitlint_config)
        for filename, result in executor.map(
                processfile, [(filename, modified_files[filename])
                              for filename in sorted(modified_files.keys())]):

            rel_filename = os.path.relpath(filename)

            if not json_output:
                stdout.write('Linting file: %s%s' % (termcolor.colored(
                    rel_filename, attrs=('bold', )), linesep))

            output_lines = []
            if result.get('error'):
                output_lines.extend('%s: %s' % (ERROR, reason)
                                    for reason in result.get('error'))
                linter_not_found = True
            if result.get('skipped'):
                output_lines.extend('%s: %s' % (SKIPPED, reason)
                                    for reason in result.get('skipped'))
            if not result.get('comments', []):
                if not output_lines:
                    output_lines.append(OK)
            else:
                files_with_problems += 1
                for data in result['comments']:
                    formatted_message = format_comment(data)
                    output_lines.append(formatted_message)
                    data['formatted_message'] = formatted_message

            if json_output:
                json_result[filename] = result
            else:
                output = linesep.join(output_lines)
                stdout.write(output)
                stdout.write(linesep + linesep)

    if json_output:
        # Hack to convert to unicode, Python3 returns unicode, wheres Python2
        # returns str.
        stdout.write(
            json.dumps(json_result,
                       ensure_ascii=False).encode('utf-8').decode('utf-8'))

    if files_with_problems > 0:
        return 1
    if linter_not_found:
        return 4
    return 0
835372
def main():
    """"""
    parser = get_parser()
    args = parser.parse_args()

    if args.debug:
        logger.setLevel(logging.NOTSET)

    initialize_preferences()

    if args.version:
        print(__version__)
        return

    cmd = args.cmd or args.args

    if args.no_browser and args.browser:
        print("Cannot specify no-browser and browser. Must specify one or the other.")
        exit(1)

    app.config["initial_binary_and_args"] = cmd
    app.config["gdb_args"] = shlex.split(args.gdb_args)
    app.config["rr"] = args.rr
    app.config["gdb_path"] = args.gdb
    app.config["show_gdbgui_upgrades"] = not args.hide_gdbgui_upgrades
    app.config["gdbgui_auth_user_credentials"] = get_gdbgui_auth_user_credentials(
        args.auth_file, args.user, args.password
    )
    app.config["project_home"] = args.project
    if args.remap_sources:
        try:
            app.config["remap_sources"] = json.loads(args.remap_sources)
        except json.decoder.JSONDecodeError as e:
            print(
                "The '--remap-sources' argument must be valid JSON. See gdbgui --help."
            )
            print(e)
            exit(1)

    if args.license:
        print("saving license information")
        save_license(args.license)

    verify_gdb_exists(app.config["gdb_path"])
    if args.remote:
        args.host = "0.0.0.0"
        args.no_browser = True
        if app.config["gdbgui_auth_user_credentials"] is None:
            print(
                "Warning: authentication is recommended when serving on a publicly "
                "accessible IP address. See gdbgui --help."
            )

    if warn_startup_with_shell_off(platform.platform().lower(), args.gdb_args):
        logger.warning(
            "You may need to set startup-with-shell off when running on a mac. i.e.\n"
            "  gdbgui --gdb-args='--init-eval-command=\"set startup-with-shell off\"'\n"
            "see http://stackoverflow.com/questions/39702871/gdb-kind-of-doesnt-work-on-macos-sierra\n"
            "and https://sourceware.org/gdb/onlinedocs/gdb/Starting.html"
        )

    setup_backend(
        serve=True,
        host=args.host,
        port=int(args.port),
        debug=bool(args.debug),
        open_browser=(not args.no_browser),
        browsername=args.browser,
        private_key=args.key,
        certificate=args.cert,
    )
248849
def main():
    """"""

    # Squelch SSL warnings
    logging.captureWarnings(True)
    if six.PY3:
        # These ones get triggered even when capturing warnings is turned on
        warnings.simplefilter('ignore', ResourceWarning)  # pylint:disable=E0602

    # Set the terminal title
    if os.getenv('DISPLAY'):
        title = 'rtv {0}'.format(__version__)
        sys.stdout.write('\x1b]2;{0}\x07'.format(title))
        sys.stdout.flush()

    args = Config.get_args()
    fargs, bindings = Config.get_file(args.get('config'))

    # Apply the file config first, then overwrite with any command line args
    config = Config()
    config.update(**fargs)
    config.update(**args)

    # If key bindings are supplied in the config file, overwrite the defaults
    if bindings:
        config.keymap.set_bindings(bindings)

    if config['copy_config']:
        return copy_default_config()
    if config['copy_mailcap']:
        return copy_default_mailcap()
    if config['list_themes']:
        return Theme.print_themes()

    # Load the browsing history from previous sessions
    config.load_history()

    # Load any previously saved auth session token
    config.load_refresh_token()
    if config['clear_auth']:
        config.delete_refresh_token()

    if config['log']:
        # Log request headers to the file (print hack only works on python 3.x)
        # from http import client
        # _http_logger = logging.getLogger('http.client')
        # client.HTTPConnection.debuglevel = 2
        # def print_to_file(*args, **_):
        #     if args[0] != "header:":
        #         _http_logger.info(' '.join(args))
        # client.print = print_to_file
        logging.basicConfig(
            level=logging.DEBUG,
            filename=config['log'],
            format='%(asctime)s:%(levelname)s:%(filename)s:%(lineno)d:%(message)s')
    else:
        # Add an empty handler so the logger doesn't complain
        logging.root.addHandler(logging.NullHandler())

    # Make sure the locale is UTF-8 for unicode support
    default_locale = locale.setlocale(locale.LC_ALL, '')
    try:
        encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1]
    except ValueError:
        # http://stackoverflow.com/a/19961403
        # OS X on some terminals will set the LC_CTYPE to "UTF-8"
        # (as opposed to something like "en_US.UTF-8") and python
        # doesn't know how to handle it.
        _logger.warning('Error parsing system locale: `%s`,'
                        ' falling back to utf-8', default_locale)
        encoding = 'UTF-8'

    if not encoding or encoding.lower() != 'utf-8':
        text = ('System encoding was detected as (%s) instead of UTF-8'
                ', falling back to ascii only mode' % encoding)
        warnings.warn(text)
        config['ascii'] = True

    if packages.__praw_bundled__:
        praw_info = 'packaged, commit {}'.format(packages.__praw_hash__[:12])
    else:
        praw_info = 'system installed v{}'.format(praw.__version__)

    # Update the webbrowser module's default behavior
    patch_webbrowser()
    if webbrowser_import_warning:
        _logger.warning('webbrowser module was unexpectedly imported before'
                        '$BROWSER could be overwritten')

    # Construct the reddit user agent
    user_agent = docs.AGENT.format(version=__version__)

    debug_info = [
        'rtv version: rtv {}'.format(__version__),
        'rtv module path: {}'.format(os.path.abspath(__file__)),
        'python version: {}'.format(sys.version.replace('\n', ' ')),
        'python executable: {}'.format(sys.executable),
        'praw version: {}'.format(praw_info),
        'locale, encoding: {}, {}'.format(default_locale, encoding),
        'Environment Variables']
    for name, value in [
        ('BROWSER', BROWSER),
        ('DISPLAY', os.getenv('DISPLAY')),
        ('EDITOR', os.getenv('EDITOR')),
        ('LANG', os.getenv('LANG')),
        ('PAGER', os.getenv('PAGER')),
        ('RTV_BROWSER', RTV_BROWSER),
        ('RTV_EDITOR', os.getenv('RTV_EDITOR')),
        ('RTV_PAGER', os.getenv('RTV_PAGER')),
        ('RTV_URLVIEWER', os.getenv('RTV_URLVIEWER')),
        ('TERM', os.getenv('TERM')),
        ('VISUAL', os.getenv('VISUAL')),
        ('XDG_CONFIG_HOME', os.getenv('XDG_CONFIG_HOME')),
        ('XDG_DATA_HOME', os.getenv('XDG_DATA_HOME')),
    ]:
        debug_info.append('  {:<16}: {}'.format(name, value or ''))
    debug_info.append('')
    debug_text = '\n'.join(debug_info)

    _logger.info(debug_text)
    if config['debug_info']:
        print(debug_text)
        return

    try:
        with curses_session() as stdscr:

            term = Terminal(stdscr, config)

            if config['monochrome'] or config['theme'] == 'monochrome':
                _logger.info('Using monochrome theme')
                theme = Theme(use_color=False)
            elif config['theme'] and config['theme'] != 'default':
                _logger.info('Loading theme: %s', config['theme'])
                theme = Theme.from_name(config['theme'])
            else:
                # Set to None to let the terminal figure out which theme
                # to use depending on if colors are supported or not
                theme = None
            term.set_theme(theme)

            with term.loader('Initializing', catch_exception=False):
                reddit = praw.Reddit(user_agent=user_agent,
                                     decode_html_entities=False,
                                     disable_update_check=True,
                                     timeout=10,  # 10 second request timeout
                                     handler=RequestHeaderRateLimiter())

            # Dial the request cache up from 30 seconds to 5 minutes
            # I'm trying this out to make navigation back and forth
            # between pages quicker, it may still need to be fine tuned.
            reddit.config.api_request_delay = 300

            # Authorize on launch if the refresh token is present
            oauth = OAuthHelper(reddit, term, config)
            if config['autologin'] and config.refresh_token:
                oauth.authorize(autologin=True)

            # Open the supplied submission link before opening the subreddit
            if config['link']:
                # Expand shortened urls like https://redd.it/
                # Praw won't accept the shortened versions, add the reddit
                # headers to avoid a 429 response from reddit.com
                url = requests.head(
                    config['link'],
                    headers=reddit.http.headers,
                    allow_redirects=True
                ).url

                page = None
                with term.loader('Loading submission'):
                    try:
                        page = SubmissionPage(reddit, term, config, oauth, url)
                    except Exception as e:
                        _logger.exception(e)
                        raise SubmissionError('Unable to load {0}'.format(url))
                while page:
                    page = page.loop()

            page = None
            name = config['subreddit']
            with term.loader('Loading subreddit'):
                try:
                    page = SubredditPage(reddit, term, config, oauth, name)
                except Exception as e:
                    # If we can't load the subreddit that was requested, try
                    # to load the "popular" page instead so at least the
                    # application still launches. This used to use the user's
                    # front page, but some users have an empty front page.
                    _logger.exception(e)
                    page = SubredditPage(reddit, term, config, oauth, 'popular')
                    raise SubredditError('Unable to load {0}'.format(name))

            # Launch the subreddit page
            while page:
                page = page.loop()

    except ConfigError as e:
        _logger.exception(e)
        print(e)
    except Exception as e:
        _logger.exception(e)
        import traceback
        exit_message = '\n'.join([
            debug_text,
            traceback.format_exc(),
            'rtv has crashed. Please report this traceback at:',
            'https://github.com/michael-lazar/rtv/issues\n'])
        sys.stderr.write(exit_message)
        return 1  # General error exception code
    except KeyboardInterrupt:
        pass
    finally:
        # Try to save the browsing history
        config.save_history()
        # Ensure sockets are closed to prevent a ResourceWarning
        if 'reddit' in locals():
            reddit.handler.http.close()
949879
def main(argv):
    """"""
    del argv
    engine = make_gtp_instance(FLAGS.load_file,
                               cgos_mode=FLAGS.cgos_mode,
                               kgs_mode=FLAGS.kgs_mode,
                               minigui_mode=FLAGS.minigui_mode)
    dbg("GTP engine ready\n")
    for msg in sys.stdin:
        if not engine.handle_msg(msg.strip()):
            break