Run tshark to decode and display the packet. If no args defined uses -V
182460
def tdecode(pkt, *args):
    """"""
    if not args:
      args = [ "-V" ]
    fname = get_temp_file()
    wrpcap(fname,[pkt])
    subprocess.call(["tshark", "-r", fname] + list(args))
829415
async def packets_from_tshark(self, packet_callback, packet_count=None, close_tshark=True):
        
        tshark_process = await self._get_tshark_process(packet_count=packet_count)
        try:
            await self._go_through_packets_from_fd(tshark_process.stdout, packet_callback, packet_count=packet_count)
        except StopCapture:
            pass
        finally:
            if close_tshark:
                await self._close_async()
483845
def run(port, like, use_json, server):
    """"""
    if not port and not server[0]:
        raise click.UsageError("Please specify a port")

    if server[0]:
        app.run(host=server[0], port=server[1])
        return

    ports = get_ports(port, like)
    if not ports:
        sys.stderr.write("No ports found for '{0}'\n".format(port))
        return

    if use_json:
        print(json.dumps(ports, indent=4))
    else:
        table = get_table(ports)
        print(table)
680004
def read_raw(self, length, *, error=None):
        """"""
        if length is None:
            length = len(self)

        raw = dict(
            packet=self._read_fileng(length),
            error=error or None,
        )

        return raw
1170933
def main(args=None):
    
    parser = ArgumentParser()
    parser.add_argument('-v', '--version',
                        action='version', version=CLI_VERSION)

    parsers = parser.add_subparsers(dest='dtype')

    text.create_arg_parser(parsers.add_parser('text'))
    if image is not None:
        image.create_arg_parser(parsers.add_parser('image'))

    if len(sys.argv if args is None else args) <= 1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args(args)
    dtype = globals()[args.dtype]
    try:
        set_args(args)
        cmd = getattr(dtype, 'cmd_' + args.command)
        cmd(args)
    except ValueError as err:
        print(str(err), file=sys.stderr)
        sys.exit(1)
1311525
def call(args, stdout=PIPE, stderr=PIPE):
    
    p = Popen(args, stdout=stdout, stderr=stderr)
    out, err = p.communicate()

    try:
        return out.decode(sys.stdout.encoding), err.decode(sys.stdout.encoding)
    except Exception:
        return out, err
1090557
def main():
    ''''''

    import sys
    import argparse

    stdout = buffer(sys.stdout)

    parser = argparse.ArgumentParser(description=main.__doc__)
    parser.add_argument(
        'file',
        metavar='FILE',
        nargs='?',
        type=argparse.FileType('r'),
        default='-')
    parser.add_argument(
        '-d', '--decode', action='store_true', help='decode data')
    parser.add_argument(
        '-c',
        '--check',
        action='store_true',
        help='append a checksum before encoding')

    args = parser.parse_args()
    fun = {
        (False, False): b58encode,
        (False, True): b58encode_check,
        (True, False): b58decode,
        (True, True): b58decode_check
    }[(args.decode, args.check)]

    data = buffer(args.file).read().rstrip(b'\n')

    try:
        result = fun(data)
    except Exception as e:
        sys.exit(e)

    if not isinstance(result, bytes):
        result = result.encode('ascii')

    stdout.write(result)
370485
def main(argv=None):
    """"""
    global Verbose
    global EncodeUtf8
    global csvOutput
    if argv is None:
        argv = sys.argv

    if (len(argv) < 3 and not (('-h' in argv) or ('--help' in argv))):
        log.exception('Bad args')
        raise TikaException('Bad args')
    try:
        opts, argv = getopt.getopt(argv[1:], 'hi:s:o:p:v:e:c',
          ['help', 'install=', 'server=', 'output=', 'port=', 'verbose', 'encode', 'csv'])
    except getopt.GetoptError as opt_error:
        msg, bad_opt = opt_error
        log.exception("%s error: Bad option: %s, %s" % (argv[0], bad_opt, msg))
        raise TikaException("%s error: Bad option: %s, %s" % (argv[0], bad_opt, msg))

    tikaServerJar = TikaServerJar
    serverHost = ServerHost
    outDir = '.'
    port = Port
    for opt, val in opts:
        if opt   in ('-h', '--help'):    echo2(USAGE); sys.exit()
        elif opt in ('--install'):       tikaServerJar = val
        elif opt in ('--server'):        serverHost = val
        elif opt in ('-o', '--output'):  outDir = val
        elif opt in ('--port'):          port = val
        elif opt in ('-v', '--verbose'): Verbose = 1
        elif opt in ('-e', '--encode'): EncodeUtf8 = 1
        elif opt in ('-c', '--csv'): csvOutput = 1
        else:
            raise TikaException(USAGE)

    cmd = argv[0]
    option = argv[1]
    try:
        paths = argv[2:]
    except:
        paths = None
    return runCommand(cmd, option, paths, port, outDir, serverHost=serverHost, tikaServerJar=tikaServerJar, verbose=Verbose, encode=EncodeUtf8)
700427
function parse(args, optsSpec) {
  if (args[0] == "?") return printHelp()

  optsSpec = optsSpec || {}
  optsSpec.port    = [ "p", Number  ]
  optsSpec.verbose = [ "v", Boolean ]
  optsSpec.help    = [ "h", Boolean ]

  var longOpts   = {}
  var shortOpts  = {}
  var defValues  = {}

  for (var name in optsSpec) {
    var fixedName = name.replace(/_/g, "-")

    var opt = optsSpec[name]

    var shortName = opt[0]
    var type      = opt[1]
    var defValue  = opt[2]

    if (type == Boolean) defValue = false

    shortOpts[shortName] = "--" + fixedName
    longOpts[fixedName]  = type

    if (defValue != null) {
      defValues[fixedName] = defValue
    }
  }

  var parsed = nopt(longOpts, shortOpts, args, 0)

  if (parsed.help) return printHelp()

  var opts

  args = parsed.argv.remain
  opts = _.pick(parsed, _.keys(longOpts))
  opts = _.defaults(opts, defValues)

  if (opts.port == null) {
    if (process.env.PORT != null) opts.port = process.env.PORT
  }

  if (opts.port == null) {
    opts.port = ports.getPort(utils.COMMAND)
  }

  utils.verbose(opts.verbose)

  return {args:args, opts:opts}
}
51146
def main(argv=None):
  """"""

  if argv is None:
    argv = sys.argv

  try:
    opts, args = getopt.getopt(argv[1:], 'h', ['help'])
  except getopt.error as msg:
    raise Usage(msg)

  for opt, _ in opts:
    if opt in ('-h', '--help'):
      print(__doc__)
      print(help_msg)
      return 0

  if not args or len(args) > 4:
    raise Usage('Invalid arguments.')

  # If we have an argument, parse content of file and display as a template.
  # Template displayed will match input template, minus any comment lines.
  with open(args[0], 'r') as template:
    fsm = TextFSM(template)
    print('FSM Template:\n%s\n' % fsm)

    if len(args) > 1:
      # Second argument is file with example cli input.
      # Prints parsed tabular result.
      with open(args[1], 'r') as f:
        cli_input = f.read()

      table = fsm.ParseText(cli_input)
      print('FSM Table:')
      result = str(fsm.header) + '\n'
      for line in table:
        result += str(line) + '\n'
      print(result, end='')

  if len(args) > 2:
    # Compare tabular result with data in third file argument.
    # Exit value indicates if processed data matched expected result.
    with open(args[2], 'r') as f:
      ref_table = f.read()

    if ref_table != result:
      print('Data mis-match!')
      return 1
    else:
      print('Data match!')
1370764
def iterstd(cmd, std="out", **kwargs):
    """"""
    def _readline():
        while True:
            line = getattr(proc, "std"+std).readline()
            if line != b"":
                yield line.rstrip().decode("UTF-8", "replace")
            else:
                break
    kwargs['shell'] = True
    kwargs['stdout'] = subprocess.PIPE
    kwargs['stderr'] = subprocess.PIPE
    if sys.version_info >= (3,0):
        with subprocess.Popen(cmd, **kwargs) as proc:
            for line in _readline(): yield line
    else:
        proc = subprocess.Popen(cmd, **kwargs)
        for line in _readline(): yield line
        proc.kill()
581020
def stripext (cmd, archive, verbosity, extension=""):
    """"""
    if verbosity >= 0:
        print(util.stripext(archive)+extension)
    return None
869966
def get_tshark_interfaces(tshark_path=None):
    
    parameters = [get_process_path(tshark_path), '-D']
    with open(os.devnull, 'w') as null:
        tshark_interfaces = subprocess.check_output(parameters, stderr=null).decode("utf-8")

    return [line.split('.')[0] for line in tshark_interfaces.splitlines()]
768074
def _read_packet(self):
        
        # Grab command, send it and decode response
        cmd = self._commands_to_read.popleft()
        try:
            raw_data = self._interface.read()
            raw_data = bytearray(raw_data)
            decoded_data = cmd.decode_data(raw_data)
        except Exception as exception:
            self._abort_all_transfers(exception)
            raise

        decoded_data = bytearray(decoded_data)
        self._command_response_buf.extend(decoded_data)

        # Attach data to transfers
        pos = 0
        while True:
            size_left = len(self._command_response_buf) - pos
            if size_left == 0:
                # If size left is 0 then the transfer list might
                # be empty, so don't try to access element 0
                break
            transfer = self._transfer_list[0]
            size = transfer.get_data_size()
            if size > size_left:
                break

            self._transfer_list.popleft()
            data = self._command_response_buf[pos:pos + size]
            pos += size
            transfer.add_response(data)

        # Remove used data from _command_response_buf
        if pos > 0:
            self._command_response_buf = self._command_response_buf[pos:]
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)
620788
def main():
    """"""
    stream_config = spead2.send.StreamConfig(
        max_packet_size=16356, rate=1000e6, burst_size=10, max_heaps=1)
    item_group = spead2.send.ItemGroup(flavour=spead2.Flavour(4, 64, 48, 0))

    # Add item descriptors to the heap.
    num_baselines = (512 * 513) // 2
    dtype = [('TCI', 'i1'), ('FD', 'u1'), ('VIS', '<c8', 4)]
    item_group.add_item(
        id=0x6000, name='visibility_timestamp_count', description='',
        shape=tuple(), format=None, dtype='<u4')
    item_group.add_item(
        id=0x6001, name='visibility_timestamp_fraction', description='',
        shape=tuple(), format=None, dtype='<u4')
    item_group.add_item(
        id=0x6005, name='visibility_baseline_count', description='',
        shape=tuple(), format=None, dtype='<u4')
    item_group.add_item(
        id=0x6008, name='scan_id', description='',
        shape=tuple(), format=None, dtype='<u8')
    item_group.add_item(
        id=0x600A, name='correlator_output_data', description='',
        shape=(num_baselines,), dtype=dtype)

    # Create streams and send start-of-stream message.
    streams = []
    num_streams = 2
    for i in range(num_streams):
        stream = spead2.send.UdpStream(
            thread_pool=spead2.ThreadPool(threads=1),
            hostname='127.0.0.1', port=41000 + i, config=stream_config)
        stream.send_heap(item_group.get_start())
        streams.append(stream)

    vis = numpy.zeros(shape=(num_baselines,), dtype=dtype)
    num_heaps = 200
    start_time = time.time()
    for stream in streams:
        # Update values in the heap.
        item_group['visibility_timestamp_count'].value = 1
        item_group['visibility_timestamp_fraction'].value = 0
        item_group['visibility_baseline_count'].value = num_baselines
        item_group['scan_id'].value = 100000000
        item_group['correlator_output_data'].value = vis
        # Iterate heaps.
        for i in range(num_heaps):
            # Send heap.
            stream.send_heap(item_group.get_heap(descriptors='all', data='all'))

    # Print time taken.
    duration = time.time() - start_time
    data_size = num_streams * num_heaps * (vis.nbytes / 1e6)
    print("Sent %.3f MB in %.3f sec (%.3f MB/sec)" % (
        data_size, duration, (data_size/duration)))

    # Send end-of-stream message.
    for stream in streams:
        stream.send_heap(item_group.get_end())
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