Parse the output from Invoke-BloodHound
334357
def parse_ouput(self, data, context, response):
        '''
        
        '''

        parsedData = data.split("!-!")
        nameList = ['user_sessions', 'group_membership.csv', 'acls.csv', 'local_admins.csv', 'trusts.csv']
        for x in range(0, len(parsedData)):
            if "ComputerName" in parsedData[x] and "UserName" in parsedData[x] :
                log_name = '{}-{}-{}.csv'.format(nameList[0], response.client_address[0], datetime.now().strftime("%Y-%m-%d_%H%M%S"))
                write_log(parsedData[x].replace('" "', '"\n"').replace(' "', '"'), log_name)
                context.log.info("Saved csv output to {}".format(log_name))
            elif "GroupName" in parsedData[x] and "AccountName" in parsedData[x] :
                log_name = '{}-{}-{}.csv'.format(nameList[1], response.client_address[0], datetime.now().strftime("%Y-%m-%d_%H%M%S"))
                write_log(parsedData[x].replace('" "', '"\n"').replace(' "', '"'), log_name)
                context.log.info("Saved csv output to {}".format(log_name))
            elif "ComputerName" in parsedData[x] and "AccountName" in parsedData[x] :
                log_name = '{}-{}-{}.csv'.format(nameList[3], response.client_address[0], datetime.now().strftime("%Y-%m-%d_%H%M%S"))
                write_log(parsedData[x].replace('" "', '"\n"').replace(' "', '"'), log_name)
                context.log.info("Saved csv output to {}".format(log_name))
            elif "SourceDomain" in parsedData[x] and "TrustType" in parsedData[x] :
                log_name = '{}-{}-{}.csv'.format(nameList[4], response.client_address[0], datetime.now().strftime("%Y-%m-%d_%H%M%S"))
                write_log(parsedData[x].replace('" "', '"\n"').replace(' "', '"'), log_name)
                context.log.info("Saved csv output to {}".format(log_name))
            elif "ObjectName" in parsedData[x] and "ObjectType" in parsedData[x] :
                log_name = '{}-{}-{}.csv'.format(nameList[2], response.client_address[0], datetime.now().strftime("%Y-%m-%d_%H%M%S"))
                write_log(parsedData[x].replace('" "', '"\n"').replace(' "', '"'), log_name)
                context.log.info("Saved csv output to {}".format(log_name))
1087813
function parseOutput(output) {
  if (!output) {
    throw new Error('Expected JSON output');
  }

  let info;
  try {
    info = JSON.parse(String(output));
  } catch (err) {
    throw new Error('Failed to parse output as JSON: ' + output);
  }
  if (!Array.isArray(info.symbols)) {
    throw new Error('Expected symbols array: ' + output);
  }
  if (!Array.isArray(info.defines)) {
    throw new Error('Expected defines array: ' + output);
  }

  return info;
}
1112725
function(mapping, i)
	{
		if ( i == undefined ) i = 0;
		var output = {};
		var len = mapping.length;
		i += 1;
		var done = false;
		var doContinue = false;

		// {foo: bar, bar:foo, ...}
		while ( i < len )
		{
			doContinue = false;
			
			switch ( mapping.charAt(i) )
			{
				case ' ':
				case ',':
					i++;
					doContinue = true;
					break;
				case '}':
					this.i = i;
					return output;
			}
			
			if ( doContinue ) continue;

			// key
			var key = this.parseScalar(mapping, [':', ' '], ['"', "'"], i, false);
			i = this.i;

			// value
			done = false;
			while ( i < len )
			{
				switch ( mapping.charAt(i) )
				{
					case '[':
						// nested sequence
						output[key] = this.parseSequence(mapping, i);
						i = this.i;
						done = true;
						break;
					case '{':
						// nested mapping
						output[key] = this.parseMapping(mapping, i);
						i = this.i;
						done = true;
						break;
					case ':':
					case ' ':
						break;
					default:
						output[key] = this.parseScalar(mapping, [',', '}'], ['"', "'"], i);
						i = this.i;
						done = true;
						i--;
				}

				++i;

				if ( done )
				{
					doContinue = true;
					break;
				}
			}
			
			if ( doContinue ) continue;
		}

		throw new YamlParseException('Malformed inline YAML string "'+mapping+'"');
	}
160892
def parse_query_output(cls, out):
        
        query_data = {}

        for line in out.strip().split("\n"):
            parts = line.split()
            if len(parts) < 6:
                continue

            job_id = parts[0]
            status_flag = parts[2]

            # map the status
            status = cls.map_status(status_flag)

            # save the result
            query_data[job_id] = cls.job_status_dict(job_id=job_id, status=status)

        return query_data
574527
function parseArgv() {
  const args = {}
  for (const arg of process.argv) {
    const elems = arg.split('=')
    const key = elems[0]
    const val = elems.length > 1 ? elems[1] : true
    args[key] = val
  }
  return args
}
1232661
def parse_debug_object(response):
    ""
    # The 'type' of the object is the first item in the response, but isn't
    # prefixed with a name
    response = nativestr(response)
    response = 'type:' + response
    response = dict([kv.split(':') for kv in response.split()])

    # parse some expected int values from the string response
    # note: this cmd isn't spec'd so these may not appear in all redis versions
    int_fields = ('refcount', 'serializedlength', 'lru', 'lru_seconds_idle')
    for field in int_fields:
        if field in response:
            response[field] = int(response[field])

    return response
229670
function parseJshintResults(fileName, showDetails) {
            var result = {};
            if (grunt.file.exists(fileName)) {
                var content = grunt.file.read(fileName);
                xml2js.parseString(content, {}, function (err, res) {
                    var consoleStatements = content.match(/(console.*)/g);
                    result = {
                        tests: Number(res.testsuite.$.tests),
                        failures: Number(res.testsuite.$.failures),
                        errors: Number(res.testsuite.$.errors),
                        consoleStatements: consoleStatements != null ? consoleStatements.length : 0
                    };

                    if (showDetails) {
                        var details = {};
                        res.testsuite.testcase.forEach(function (key) {
                            if(typeof key.failure !== 'undefined') {
                                var filename = key.$.name.substring(key.$.name.search(/[^\/]+$/g));
                                var failures = key.failure[0]._.replace(/\n/g, "###").split("###");
                                failures.shift();
                                failures.pop();
                                details[filename] = failures;
                            }
                        });
                        result.failureDetails = details;
                    }
                });
            }
            return result;
        }
767121
function parseChunk(expected, cursor) {
    var type, length;

    type = cursor.toString('ascii', 4);
    length = cursor.readUInt32BE();

    if (type !== expected) {
        throw new error.MIDIParserError(
            type,
            expected,
            cursor.tell()
        );
    }

    return cursor.slice(length);
}
171216
def parse_volumedetect_stats(self):
        
        logger.info(
            "Running first pass volumedetect filter for stream {}".format(self.stream_id)
        )

        filter_str = '[0:{}]volumedetect'.format(self.stream_id)

        cmd = [
            self.media_file.ffmpeg_normalize.ffmpeg_exe, '-nostdin', '-y',
            '-i', self.media_file.input_file,
            '-filter_complex', filter_str,
            '-vn', '-sn', '-f', 'null', NUL
        ]

        cmd_runner = CommandRunner(cmd)
        for progress in cmd_runner.run_ffmpeg_command():
            yield progress
        output = cmd_runner.get_output()

        logger.debug("Volumedetect command output:")
        logger.debug(output)

        mean_volume_matches = re.findall(r"mean_volume: ([\-\d\.]+) dB", output)
        if mean_volume_matches:
            self.loudness_statistics['mean'] = float(mean_volume_matches[0])
        else:
            raise FFmpegNormalizeError(
                "Could not get mean volume for {}".format(self.media_file.input_file)
            )

        max_volume_matches = re.findall(r"max_volume: ([\-\d\.]+) dB", output)
        if max_volume_matches:
            self.loudness_statistics['max'] = float(max_volume_matches[0])
        else:
            raise FFmpegNormalizeError(
                "Could not get max volume for {}".format(self.media_file.input_file)
            )
133659
def _parse_status(self, output):
        '''
        
        '''
        parsed = self._parse_machine_readable_output(output)
        statuses = []
        # group tuples by target name
        # assuming tuples are sorted by target name, this should group all
        # the tuples with info for each target.
        for target, tuples in itertools.groupby(parsed, lambda tup: tup[1]):
            # transform tuples into a dict mapping "type" to "data"
            info = {kind: data for timestamp, _, kind, data in tuples}
            status = Status(name=target, state=info.get('state'),
                            provider=info.get('provider-name'))
            statuses.append(status)

        return statuses
90391
def _parse_openssh_output(lines, fingerprint_hash_type=None):
    '''
    
    '''
    for line in lines:
        # We don't need any whitespace-only containing lines or arbitrary doubled newlines
        line = line.strip()
        if line == '':
            continue
        line += '\n'

        if line.startswith('#'):
            continue
        try:
            hostname, enc, key = line.split()
        except ValueError:  # incorrect format
            continue
        fingerprint = _fingerprint(key,
                                   fingerprint_hash_type=fingerprint_hash_type)
        if not fingerprint:
            continue
        yield {'hostname': hostname, 'key': key, 'enc': enc,
               'fingerprint': fingerprint}
345199
def parse
      parsed_output = []

      File.open(@filename).each_line.with_index do |line, num|
        next if line.lstrip[0] != "#"

        if expr = line.match(EXPRESSION)
          parsed_output.push [num, expr["expression"]]
        elsif result = line.match(RESULT)
          parsed_output.last.push(result["result"])
        end
      end
      parsed_output
    end
1151192
def parse_output(output, keep=("INCLUDE", "LIB", "LIBPATH", "PATH")):
    

    # dkeep is a dict associating key: path_list, where key is one item from
    # keep, and pat_list the associated list of paths
    dkeep = dict([(i, []) for i in keep])

    # rdk will  keep the regex to match the .bat file output line starts
    rdk = {}
    for i in keep:
        rdk[i] = re.compile('%s=(.*)' % i, re.I)

    def add_env(rmatch, key, dkeep=dkeep):
        path_list = rmatch.group(1).split(os.pathsep)
        for path in path_list:
            # Do not add empty paths (when a var ends with ;)
            if path:
                # XXX: For some reason, VC98 .bat file adds "" around the PATH
                # values, and it screws up the environment later, so we strip
                # it.
                path = path.strip('"')
                dkeep[key].append(str(path))

    for line in output.splitlines():
        for k, value in rdk.items():
            match = value.match(line)
            if match:
                add_env(match, k)

    return dkeep
184472
def handle_raw_output(ctx, data):
    """"""
    if ctx.obj['format'] == 'json':
        print(json_dump(data))
        exit(0)
    if ctx.obj['format'] == 'yaml':
        print(yaml_dump(data), end='')
        exit(0)
1159378
def _invoke(self, *params):
		
		cmd = [self.exe, '-R', self.location] + list(params)
		with reentry.in_process_context(cmd) as result:
			sys.modules['mercurial.dispatch'].run()
		stdout = result.stdio.stdout.getvalue()
		stderr = result.stdio.stderr.getvalue()
		if not result.returncode == 0:
			raise RuntimeError(stderr.strip() or stdout.strip())
		return stdout.decode('utf-8')
610594
function parseResult(text, callback) {
  var errors = [], i = 0, l, errBlock, match, match2, lines;

  text = text.replace(/\r/g, '');
  lines = text.split('\n');

  match = skippingRegex.exec(lines[i]);
  if (match) {
    i++;
  }

  match = successRegex.exec(lines[i]);
  if (match) {
    callback(null, createParseSuccessObj(match));
    return;
  }

  for (l = lines.length; i < l; i++) {
    match = fileRegex.exec(lines[i]);
    if (match) {
      match2 = errorRegex.exec(lines[++i]);
      errBlock = createFailObj(match);
      for (var j = i; match2 && j < lines.length;) {
        errBlock.errors.push(createErrorObj(match2));
        match2 = errorRegex.exec(lines[++j]);
      }
      i = --j;
      errors.push(errBlock);
    } else {
      match = abstractRegex.exec(lines[i]);
      if (match) {
        callback(createErrorGJSLintFailed(match, errors));
        return;
      }
    }
  }
  callback(createParseErrorUnknown(lines));

}
1008657
def _parse_kraken_output(out_dir, db, data):
    
    in_file = os.path.join(out_dir, "kraken_out")
    stat_file = os.path.join(out_dir, "kraken_stats")
    out_file = os.path.join(out_dir, "kraken_summary")
    kraken_cmd = config_utils.get_program("kraken-report", data["config"])
    classify = unclassify = None
    with open(stat_file, 'r') as handle:
        for line in handle:
            if line.find(" classified") > -1:
                classify = line[line.find("(") + 1:line.find(")")]
            if line.find(" unclassified") > -1:
                unclassify = line[line.find("(") + 1:line.find(")")]
    if os.path.getsize(in_file) > 0 and not os.path.exists(out_file):
        with file_transaction(data, out_file) as tx_out_file:
            cl = ("{kraken_cmd} --db {db} {in_file} > {tx_out_file}").format(**locals())
            do.run(cl, "kraken report: %s" % dd.get_sample_name(data))
    kraken = {"kraken_clas": classify, "kraken_unclas": unclassify}
    kraken_sum = _summarize_kraken(out_file)
    kraken.update(kraken_sum)
    return kraken