Extract error message for queries
326422
def extract_error_message(cls, e):
        """"""
        message = str(e)
        try:
            if isinstance(e.args, tuple) and len(e.args) > 1:
                message = e.args[1]
        except Exception:
            pass
        return message
87383
def x_parse_error(err, content, source):
    
    lineno, column = err.position
    if "<doc>" in content:
        #Adjust the position since we are taking the <doc> part out of the tags
        #since we may have put that in ourselves.
        column -= 5
    start = lineno - (1 if lineno == 1 else 2)
    lines = []
    tcontent = content.replace("<doc>", "").replace("</doc>", "").split('\n')
    for context in IT.islice(tcontent, start, lineno):
        lines.append(context.strip())
    last = wrap_line(lines.pop(), column)
    lines.extend(last)
    
    caret = '{:=>{}}'.format('^', len(last[-1]))
    if source is not None:
        err.msg = '\nIn: {}\n{}\n{}\n{}'.format(source, err, '\n'.join(lines), caret)
    else:
        err.msg = '{}\n{}\n{}'.format(err, '\n'.join(lines), caret)

    raise err
1103270
def make_syntax_err(self, err, original):
        """"""
        msg, loc = err.args
        return self.make_err(CoconutSyntaxError, msg, original, loc)
1336563
function ErrorMsg()
	{
		if (!$this->_connectionID) return "No connection established";
		$errmsg = '';

		try {
			$errc = $this->_connectionID->Errors;
			if (!$errc) return "No Errors object found";
			if ($errc->Count == 0) return '';
			$err = $errc->Item($errc->Count-1);
			$errmsg = $err->Description;
		}catch(exception $e) {
		}
		return $errmsg;
	}
509777
private function parseConnectionError(): array
    {
        $return = ['sql_state' => null, 'code' => null, 'message' => 'Unknown error.'];
        if ($error = error_get_last()) {
            $return['sql_state'] = SqlState::OPPA_CONNECTION_ERROR;

            $errorMessage = strstr($error['message'], "\n", true);
            if ($errorMessage === false) {
                $errorMessage = $error['message'];
            }
            $errorMessage = preg_replace('~(pg_connect\(\)|fatal):\s+~i', '', $errorMessage);
            $errorMessage = explode(':', $errorMessage);
            if (count($errorMessage) > 2) {
                $errorMessage = array_slice($errorMessage, 0, 2);
            }
            $errorMessage = implode(',', $errorMessage);

            $return['message'] = $errorMessage .'.';

            if (strpos($errorMessage, 'to address')) {
                $return['message'] = sprintf('Unable to connect to PostgreSQL server at "%s", '.
                    'could not translate host name "%s" to address.', $this->config['host'], $this->config['host']);
                $return['sql_state'] = SqlState::OPPA_HOST_ERROR;
            } elseif (strpos($errorMessage, 'not exist')) {
                $return['message'] = sprintf('Unable to connect to PostgreSQL server at "%s", '.
                    'database "%s" does not exist.', $this->config['host'], $this->config['name']);
                $return['sql_state'] = SqlState::OPPA_DATABASE_ERROR;
            } elseif (strpos($errorMessage, 'password authentication')) {
                $return['message'] = sprintf('Unable to connect to PostgreSQL server at "%s", '.
                    'password authentication failed for user "%s".', $this->config['host'], $this->config['username']);
                $return['sql_state'] = SqlState::OPPA_AUTHENTICATION_ERROR;
            } elseif (strpos($errorMessage, 'client_encoding')) {
                $return['message'] = sprintf('Unable to connect to PostgreSQL server at "%s", '.
                    'invalid or not-supported character set "%s" given.', $this->config['host'], $this->config['charset']);
                $return['sql_state'] = SqlState::OPPA_CHARSET_ERROR;
            } elseif (strpos($errorMessage, 'TimeZone')) {
                $return['message'] = sprintf('Unable to connect to PostgreSQL server at "%s", '.
                    'invalid or not-supported timezone "%s" given.', $this->config['host'], $this->config['timezone']);
                $return['sql_state'] = SqlState::OPPA_TIMEZONE_ERROR;
            }
        }

        return $return;
    }
107379
function extractMessage(error) {
	var {message} = error
	if (error.plugin === 'babel') {
		// Hey Babel, you're not helping!
		var filepath = error.id
		var message = error.message
		function stripFilePath() {
			var index = message.indexOf(filepath)
			console.log(index, filepath.length)
			message = message.slice(0, index) + message.slice(filepath.length + 1)
			message = message.trim()
		}
		if (message.includes(filepath)) {
			stripFilePath()
		} else {
			filepath = filepath.replace(/\\/g, '/')
			if (message.includes(filepath))
				stripFilePath()
		}
	}
	return message
}
526118
def get_context_query_errors(self):
    
    if self._context_query_errors:  return self._context_query_errors
    if len(self._query_errors) < 3: return {}
    nts = ['A','C','G','T']
    poss = ['A','C','G','T','-']
    r = {}
    for i in nts:
      if i not in r:  r[i] = {}
      for j in nts:
        if j not in r[i]: r[i][j] = {}
        for k in poss:
          if k not in r[i][j]: 
            r[i][j][k] = {}
            r[i][j][k]['types'] = {}
            r[i][j][k]['total'] = 0
          for l in poss:
            if l not in r[i][j][k]['types']: r[i][j][k]['types'][l] = 0
    # now r is initialized
    for i in range(1,len(self._query_errors)-1):

      tobs = self._query_errors[i].get_observable()
      tunobs = self._query_errors[i].get_unobservable()
      otype = tobs.get_type()
      op = tobs.get_error_probability()
      before = tunobs.get_before_type()
      bp = tunobs.get_before_probability()
      after = tunobs.get_after_type()
      ap = tunobs.get_after_probability()
      if otype[2][0][0] == 'N': continue
      if otype[2][1][0] == 'N': continue
      if before:
        if before[2][0][0] == 'N': continue
        if before[2][1][0] == 'N': continue
      if after:
        if after[2][0][0] == 'N': continue
        if after[2][1][0] == 'N': continue

      tbefore = self._query_errors[i-1].get_base()
      t = self._query_errors[i].get_base()
      tafter = self._query_errors[i+1].get_base()

      if tbefore == 'N' or tafter == 'N' or t == 'N': continue
      r[tbefore][t]['-']['total'] += 0.5
      r[t][tafter]['-']['total'] += 0.5
      r[tbefore][tafter][t]['total'] += 1

      # We know we made an observation
      if otype[0] == 'mismatch':
        tb = otype[2][0][0]
        qb = otype[2][1][0]
        r[tbefore][tafter][t]['types'][tb] += op
      elif otype[0] == 'match':
        tb = otype[2][0][0]
        qb = otype[2][1][0]
        r[tbefore][tafter][t]['types'][tb] += float(1)
      elif otype[0] == 'insertion':
        tb = otype[2][0][0]
        qb = otype[2][1][0]
        r[tbefore][tafter][t]['types']['-'] += op
        r[tbefore][tafter][t]['types'][tb] += (1-op)
      # make sure our deletion can't be bigger than 1
      hp_deletion_before = 0
      hp_deletion_after = 0
      if otype[0] == 'deletion':
        tb = otype[2][0][0]
        qb = otype[2][1][0]
        r[tbefore][tb]['-']['types'][tb] += op/2
        r[tb][tafter]['-']['types'][tb] += op/2
        #homopolymer ... so we do have the correct base
        r[tbefore][tafter][t]['types'][tb] += 1

      # now take care of total deletions
      if before:
        tb = before[2][0][0]
        r[tbefore][t]['-']['types'][tb] += bp
      if after:
        tb = after[2][0][0]
        r[t][tafter]['-']['types'][tb] += ap

      ##type = self._target_errors[i].get_type()
      #p = self._target_errors[i].get_error_probability()
      #if p > 0:
      #  if type[0] not in r[tbefore][t][tafter]['types']:
      #    r[tbefore][t][tafter]['types'][type[0]] = 0
      #  r[tbefore][t][tafter]['types'][type[0]] += p
      #r[tbefore][t][tafter]['total']+=1
    for b in r:
      for a in r:
        val = sum([r[b][a]['-']['types'][q] for q in nts])
        r[b][a]['-']['types']['-'] = r[b][a]['-']['total'] - val
    return r
35198
def get_error(self):
        """"""
        exc_info = sys.exc_info()
        if exc_info[0] is None:
            return None
        else:
            err_type, err_value, err_trace = exc_info[0], exc_info[1], None
            if self.verbose and len(exc_info) > 2:
                err_trace = exc_info[2]
            return format_error(err_type, err_value, err_trace)
584372
def get_errors(error_string):
    '''
    

    '''

    lines = error_string.splitlines()
    error_lines = tuple(line for line in lines if line.find('Error') >= 0)
    if len(error_lines) > 0:
        return '\n'.join(error_lines)
    else:
        return error_string.strip()
794200
def _make_error(index, code, errmsg, operation):
    
    return {
        _UINDEX: index,
        _UCODE: code,
        _UERRMSG: errmsg,
        _UOP: operation
    }
876564
protected function get_error()
    {
        $query = $this->database->getQueryCollection()->findQuery($this->strQuery);

        if ($query) {
            return $query->error();
        }

        return '';
    }
30897
def get_error_search_term(error_line):
    
    if not error_line:
        return None

    # This is strongly inspired by
    # https://hg.mozilla.org/webtools/tbpl/file/tip/php/inc/AnnotatedSummaryGenerator.php#l73

    tokens = error_line.split(" | ")
    search_term = None

    if len(tokens) >= 3:
        # If this is process output then discard the token with the PID
        if len(tokens) > 3 and OUTPUT_RE.match(tokens[0]):
            tokens = tokens[1:]
        # it's in the "FAILURE-TYPE | testNameOrFilePath | message" type format.
        test_name_or_path = tokens[1]
        message = tokens[2]
        # Leak failure messages are of the form:
        # leakcheck | .*\d+ bytes leaked (Object-1, Object-2, Object-3, ...)
        match = LEAK_RE.search(message)
        if match:
            search_term = match.group(1) if match.group(1) is not None else match.group(2)
        else:
            # For reftests, remove the reference path from the tokens as this is
            # not very unique
            test_name_or_path = REFTEST_RE.sub("", test_name_or_path)
            for splitter in ("/", "\\"):
                # if this is a path, we are interested in the last part
                test_name_or_path = test_name_or_path.split(splitter)[-1]
            search_term = test_name_or_path

    # If the failure line was not in the pipe symbol delimited format or the search term
    # will likely return too many (or irrelevant) results (eg: too short or matches terms
    # on the blacklist), then we fall back to searching for the entire failure line if
    # it is suitable.
    if not (search_term and is_helpful_search_term(search_term)):
        if is_helpful_search_term(error_line):
            search_term = error_line
        else:
            search_term = None

    # Searching for extremely long search terms is undesirable, since:
    # a) Bugzilla's max summary length is 256 characters, and once "Intermittent "
    # and platform/suite information is prefixed, there are even fewer characters
    # left for us to use for the failure string against which we need to match.
    # b) For long search terms, the additional length does little to prevent against
    # false positives, but means we're more susceptible to false negatives due to
    # run-to-run variances in the error messages (eg paths, process IDs).
    if search_term:
        search_term = search_term[:100]

    return search_term
1080307
def get_query_error(self,i):
    
    x = self._query_hpas[i]
    h = x['hpa']
    pos = x['pos']
    prob = 0
    be = BaseError('query')
    be.set_observable(h.get_target(),h.get_query())
    if i != 0 and pos == 0: # check for a total deletion before
      prev = x['prev-hpa']
      if len(prev.get_query()) == 0: # total deletion
        be.set_unobserved_before(len(prev.get_target()),0,prev.get_target()[0],0.5)
    if i != len(self._query_hpas)-1 and pos == len(h.get_query())-1: # check for a total deletion before
      if x['next-hpa']:
        foll = x['next-hpa']
        if len(foll.get_query()) == 0: # total deletion
          be.set_unobserved_after(len(foll.get_target()),0,foll.get_target()[0],0.5)
    return be
70772
def get_requests_with_errors(self):
        
        data = self._es.search(body={
            "size": max_query_results,
            "query": {
                "filtered": {
                    "query": {
                        "match_all": {}
                    },
                    "filter": {
                        "exists": {
                            "field": "errmsg"
                        }
                    }
                }
            }
        })
        return GremlinTestResult(False, data)
181364
def pretty_error(error, verbose=False):
    
    error_loc = ''

    if error.path:
        while len(error.path) > 0:
            path_elem = error.path.popleft()
            if type(path_elem) is not int:
                if error_loc:
                    error_loc += '.'
                error_loc += path_elem
            # elif len(error.path) > 0:
            else:
                error_loc += '[' + text_type(path_elem) + ']'
        error_loc += ': '

    # Get error message and remove ugly u'' prefixes
    if verbose:
        msg = remove_u(text_type(error))
    else:
        msg = remove_u(error.message)

    # Don't reword error messages from our validators,
    # only the default error messages from the jsonschema library
    if repr(error.schema) == '<unset>':
        try:
            return error_loc + msg
        except UnicodeDecodeError:
            return error_loc + msg.decode('utf-8')

    # Reword error messages containing regexes
    if error.validator == 'pattern' and 'title' in error.schema:
        if error.schema['title'] == 'type':
            msg = re.sub(r"match '.+'$", 'match the \'type\' field format '
                         '(lowercase ASCII a-z, 0-9, and hypens only - and no '
                         'two hyphens in a row)', msg)
        elif error.schema['title'] == 'identifier':
            msg = re.sub(r"match '.+'$", 'match the id format '
                         '([object-type]--[UUIDv4])', msg)
        elif error.schema['title'] == 'id':
            msg = re.sub(r"match '.+'$", 'start with \'' +
                         error.validator_value[1:-2] + '--\'', msg)
        elif error.schema['title'] == 'timestamp':
            msg = re.sub(r"match '.+'$", 'match the timestamp format '
                         'YYYY-MM-DDTHH:mm:ss[.s+]Z', msg)
        elif error.schema['title'] == 'timestamp_millis':
            msg = re.sub(r"match '.+'$", 'match the timestamp format '
                         'YYYY-MM-DDTHH:mm:ss.sssZ (must be precise to the '
                         'millisecond)', msg)
        elif error.schema['title'] == 'relationship_type':
            msg = re.sub(r"does not match '.+'$", 'contains invalid '
                         'characters', msg)
        elif error.schema['title'] == 'url-regex':
            msg = re.sub(r'match ".+"$', 'match the format '
                         'of a URL', msg)
        elif error.schema['title'] == 'binary':
            msg = re.sub(r"does not.+'$", 'must be a base64-encoded string', msg)
    elif error.validator == 'pattern' and 'observed_data_refs' in error.schema_path:
        msg = "'observed_data_refs' must refer to Observed Data Objects"
    elif error.validator == 'pattern' and 'where_sighted_refs' in error.schema_path:
        msg = "'where_sighted_refs' must refer to Identity Objects"

    # Reword empty array errors
    elif type(error.instance) is list and len(error.instance) == 0:
        msg = re.sub(r"\[\] is not valid .+$", 'empty arrays are not allowed',
                     msg)

    # Reword custom property errors
    elif 'title' in error.schema and error.schema['title'] == 'core':
        if error.validator == 'additionalProperties':
            msg = re.sub(r"Additional .+$", 'Custom properties must match the '
                         'proper format (lowercase ASCII a-z, 0-9, and '
                         'underscores; 3-250 characters)', msg)
        elif error.validator == 'not' and 'anyOf' in error.validator_value:
            reserved_properties = [y for x in error.validator_value['anyOf'] for y in x['required']]
            msg = re.sub(r".+", "Contains a reserved property ('%s')"
                         % "', '".join(reserved_properties), msg)
    elif 'title' in error.schema and error.schema['title'] == 'cyber-observable-core':
        if error.validator == 'additionalProperties':
            msg = re.sub(r"Additional .+$", 'Custom observable properties must'
                         ' match the proper format (lowercase ASCII a-z, 0-9, '
                         'and underscores; 3-250 characters)', msg)

    elif error.validator == 'additionalProperties':
        if 'extensions' in error.schema_path:
            msg = re.sub(r"Additional .+$", 'Custom extension keys may only '
                         'contain alphanumeric characters, dashes, and '
                         'underscores; 3-256 characters', msg)

    # Reword 'is valid under each of' errors
    elif error.validator == 'oneOf':
        try:
            if 'external_references' in error.schema_path:
                msg = "If the external reference is a CVE, 'source_name' must be" \
                      " 'cve' and 'external_id' must be in the CVE format " \
                      "(CVE-YYYY-NNNN+). If the external reference is a CAPEC, " \
                      "'source_name' must be 'capec' and 'external_id' must be " \
                      "in the CAPEC format (CAPEC-N+). If the external reference "\
                      "is neither, it must contain the 'source_name' property and"\
                      " at least one of the 'external_id', 'url', or "\
                      "'description' properties."
            elif 'type' in error.instance and error.instance['type'] == 'email-message':
                if 'is_multipart' not in error.instance:
                    msg = "'is_multipart' is a required property"
                elif error.instance['is_multipart'] is True:
                    msg = "Since 'is_multipart' is true, 'body_multipart' must "\
                          "contain valid 'mime-part-type' objects and the 'body' "\
                          "property must not be present. "
                elif error.instance['is_multipart'] is False:
                    msg = "Since 'is_multipart' is false, 'body' must be a string"\
                          " and the 'body_multipart' property must not be present."
            elif 'type' in error.instance and error.instance['type'] == 'artifact':
                if 'payload_bin' in error.instance and 'url' in error.instance:
                    msg = "'artifact' object must contain either 'payload_bin' "\
                          "or 'url' but not both"
                elif 'payload_bin' in error.instance:
                    msg = "'payload_bin' must be base64 encoded and 'hashes', if "\
                          "present, must contain a valid dictionary of hashes"
                elif 'url' in error.instance:
                    msg = "'url' must be a valid url and 'hashes', which must be "\
                          "present, must contain a valid hash dictionary"
                else:
                    msg = "'artifact' object must contain either 'payload_bin' "\
                          "or 'url'"
            elif 'type' in error.instance and error.instance['type'] == 'marking-definition':
                msg = "'definition' must contain a valid statement, TLP, or "\
                      "custom marking definition"
            elif 'type' in error.instance and error.instance['type'] == 'file':
                if (('is_encrypted' not in error.instance or
                        error.instance['is_encrypted'] is False) and
                        ('encryption_algorithm' in error.instance or
                         'decryption_key' in error.instance)):
                    msg = "'file' objects may only contain 'encryption_algorithm'"\
                          " or 'decryption_key' when 'is_encrypted' is true"
            elif 'type' in error.instance and error.instance['type'] == 'network-traffic':
                if ('is_active' in error.instance and
                        error.instance['is_active'] is True and
                        'end' in error.instance):
                    msg = "If the 'is_active' property is true, then the "\
                          "'end' property must not be included."
            else:
                raise TypeError
        except TypeError:
            msg = msg + ':\n' + remove_u(text_type(error.schema))

    # reword forbidden property or value errors
    elif error.validator == 'not':
        if 'enum' in error.validator_value:
            msg = re.sub(r"\{.+\} is not allowed for '(.+)'$", r"'\g<1>' is "
                         "not an allowed value", msg)
        elif ('target_ref' in error.schema_path or
              'source_ref' in error.schema_path):
                msg = "Relationships cannot link bundles, marking definitions"\
                      ", sightings, or other relationships. This field must "\
                      "contain the id of an SDO."
        elif 'sighting_of_ref' in error.schema_path:
            msg = "'sighting_of_ref' must refer to a STIX Domain Object or "\
                  "Custom Object"

    # Reword 'is not valid under any of the given schemas' errors
    elif error.validator == 'anyOf':
        try:
            if error.instance == {}:
                msg = "must contain at least one property from this type."
            elif error.instance is None:
                msg = "null properties are not allowed in STIX."
            elif 'type' in error.instance and error.instance['type'] == 'network-traffic':
                if ('src_ref' not in error.instance and
                        'dst_ref' not in error.instance):
                    msg = "'network-traffic' objects must contain at least "\
                          "one of 'src_ref' or 'dst_ref'"
            elif 'type' in error.instance and error.instance['type'] in ['process', 'x509-certificate']:
                if error.instance.keys() == ['type']:
                    msg = "must contain at least one property (other than `type`) from this object."
            else:
                raise TypeError
        except TypeError:
            msg = msg + ':\n' + remove_u(text_type(error.schema))

    return error_loc + msg
272430
def _extractErrorString(request):
        
        errorStr = ""

        tag = None

        # noinspection PyBroadException
        try:
            # parse XML return
            root = ET.fromstring(request.text.encode('utf-8'))
            tag = root[0][0]
        except:
            # return an empty string as we can not parse the structure
            return errorStr

        for element in tag.getiterator():
            tagName = element.tag.lower()

            if tagName.endswith("string"):
                errorStr += element.text + " "
            elif tagName.endswith("description"):
                errorStr += element.text + " "

        return errorStr
1083317
def error(self, msg, indent=0, **kwargs):
        """"""
        return self.logger.error(self._indent(msg, indent), **kwargs)