Fixes for various DOM errors that MAL commits.
    Yes, I know this is a cardinal sin, but there's really no elegant way to fix this.
1843
def fix_bad_html(html):
  
  # on anime list pages, sometimes tds won't be properly opened.
  html = re.sub(r'[\s]td class=', "<td class=", html)
  # on anime list pages, if the user doesn't specify progress, MAL will try to close a span it didn't open.
  def anime_list_closing_span(match):
    return match.group(u'count') + '/' + match.group(u'total') + '</td>'
  html = re.sub(r'(?P<count>[0-9\-]+)</span>/(?P<total>[0-9\-]+)</a></span></td>', anime_list_closing_span, html)

  # on anime info pages, under rating, there's an extra </div> by the "licensing company" note.
  html = html.replace('<small>L</small></sup><small> represents licensing company</small></div>', '<small>L</small></sup><small> represents licensing company</small>')

  # on manga character pages, sometimes the character info column will have an extra </div>.
  def manga_character_double_closed_div_picture(match):
    return "<td " + match.group(u'td_tag') + ">\n\t\t\t<div " + match.group(u'div_tag') + "><a " + match.group(u'a_tag') + "><img " + match.group(u'img_tag') + "></a></div>\n\t\t\t</td>"
  html = re.sub(r"""<td (?P<td_tag>[^>]+)>\n\t\t\t<div (?P<div_tag>[^>]+)><a (?P<a_tag>[^>]+)><img (?P<img_tag>[^>]+)></a></div>\n\t\t\t</div>\n\t\t\t</td>""", manga_character_double_closed_div_picture, html)

  def manga_character_double_closed_div_character(match):
    return """<a href="/character/""" + match.group(u'char_link') + """">""" + match.group(u'char_name') + """</a>\n\t\t\t<div class="spaceit_pad"><small>""" + match.group(u'role') + """</small></div>"""
  html = re.sub(r"""<a href="/character/(?P<char_link>[^"]+)">(?P<char_name>[^<]+)</a>\n\t\t\t<div class="spaceit_pad"><small>(?P<role>[A-Za-z ]+)</small></div>\n\t\t\t</div>""", manga_character_double_closed_div_character, html)
  return html
258018
function errHandler(err) {
    process.stderr.write(chalk.red('Model generation failed!') + '\n');

    switch (err.code) {
      default:
        case 'PARSE_FAIL':
        if (!quiet) {
          process.stderr.write('\n' + err.stack + '\n');
        }
      break;

      case 'ENOENT':
          if (!quiet) {
            process.stderr.write('\n' + err.stack.replace('ENOENT, lstat ', 'unable to find ') + '\n');
          }
        break;
    }
    callback(err);
  }
75133
function error(err, req, res, next) {
  // log it
  if (!test) console.error(err.stack);

  // respond with 500 "Internal Server Error".
  res.status(500);
  res.send('Internal Server Error');
}
480761
function formatError(error) {
        function localize(key) {
            if (Strings[key]) {
                return Strings[key];
            }
            console.log("Unknown installation error", key);
            return Strings.UNKNOWN_ERROR;
        }

        if (Array.isArray(error)) {
            error[0] = localize(error[0]);
            return StringUtils.format.apply(window, error);
        } else {
            return localize(error);
        }
    }
1356162
function GeneralAjaxError(jqXHR, textStatus, errorThrown, options) {
    this.jqXHR = jqXHR;
    this.textStatus = textStatus;
    this.errorThrown = errorThrown;

    // ``captureStackTrace`` is not always available.
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor);
    }
    else {
      // This will work on many platforms.
      var fakeError = new Error();
      if (fakeError.stack) {
        this.stack = fakeError.stack;
      }
      // However, IE11 and some other platforms do not set the stack until
      // the error is thrown.
      else {
        try {
          throw fakeError;
        }
        catch (ex) {
          this.stack = ex.stack;
        }
      }
    }

    // We try to produce a message that says something useful.
    var message = "Ajax operation failed";
    if (errorThrown) {
      message += ": " + errorThrown + " (" + jqXHR.status + ")";
    }
    else if (textStatus) {
      message += ": " + textStatus;
    }
    message += ".";

    // The user wanted verbose errors to be thrown, so be verbose.
    if (options) {
      message += " Called with: " + JSON.stringify(options);
    }

    this.message = message;
  }
168344
function fixDemoComponentHtml(component, folder) {
    var re = /<!-- ignore the following lines[\s\S]*<!-- start to learn the demo from here -->\r?\n/;
    component.code = component.code.replace(re, '');

    if (component.code.indexOf('jigsaw-demo-description') != -1) {
        console.error('ERROR: can not strip "jigsaw-demo-description" from html!');
        console.error(`       path=${folder}`);
        process.exit(1);
    }
}
366390
function apiError(err) {
	var f = testProbe ? testProbe : anomaly.anomaly
	f.apply(this, Array.prototype.slice.call(arguments))
}
959754
function fix(event) {
    if (!('defaultPrevented' in event)) {
      event.defaultPrevented = false
      var prevent = event.preventDefault
      event.preventDefault = function() {
        this.defaultPrevented = true
        prevent.call(this)
      }
    }
  }
954367
def error(bot, update, error):
    """"""
    logger.error('Update {} caused error {}'.format(update, error), extra={"tag": "err"})
602061
function getError (errors) {
    var data = errors[0].data
    var err = data.error
    err.message = err.message + ' [jsdom]'

    // clean up stack trace
    if (err.stack) {
      err.stack = err.stack
        .split('\n')
        .reduce(function (list, line) {
          if (line.match(/node_modules.+(jsdom|mocha)/)) {
            return list
          }

          line = line
            .replace(/file:\/\/.*<script>/g, '<script>')
            .replace(/:undefined:undefined/g, '')
          list.push(line)
          return list
        }, [])
        .join('\n')
    }

    return err
  }
648657
function LightAssertionError(options) {
  merge(this, options);

  if (!options.message) {
    Object.defineProperty(this, "message", {
      get: function() {
        if (!this._message) {
          this._message = this.generateMessage();
          this.generatedMessage = true;
        }
        return this._message;
      }
    });
  }
}
206333
function err(...messages) {
  console.error(...messages);
  const p = document.createElement('p');
  p.innerText = messages.join(' ');
  p.style = 'color: red';
  logElement.appendChild(p);
}
1103746
function formatSassError(err, data) {
  // Generate three-line preview around the error:
  var preview = data.split('\n');
  preview = preview.slice(Math.max(0, err.line-2), Math.min(err.line+1, preview.length-1));
  preview = preview.map(function(src) { return '>>> '+ src });
  preview.unshift(err.message);

  var error = new Error('Error rendering theme Sass:\n'+ preview.join('\n'));
  error.line = err.line || null;
  error.column = err.column || null;
  return error;
}
575069
function onerror(meta, err) {
    const { ok, sourceFrame, atLine } = options.utils.getCodeInfo({
      parsedArgv: options.parsedArgv,
      filename: meta.filename,
      err,
    });

    if (ok) {
      console.error(options.ansi.bold.bgRed('  CRITICAL  '), atLine);
      console.error(sourceFrame);
    } else {
      console.error(options.ansi.bold.bgRed('  CRITICAL  '));
      console.error(options.ansi.red(err.stack));
    }
    console.error('');
  }
912908
function WError(options)
{
	Error.call(this);

	var args, cause, ctor;
	if (typeof (options) === 'object') {
		args = Array.prototype.slice.call(arguments, 1);
	} else {
		args = Array.prototype.slice.call(arguments, 0);
		options = undefined;
	}

	if (args.length > 0) {
		this.message = mod_extsprintf.sprintf.apply(null, args);
	} else {
		this.message = '';
	}

	if (options) {
		if (options instanceof Error) {
			cause = options;
		} else {
			cause = options.cause;
			ctor = options.constructorOpt;
		}
	}

	Error.captureStackTrace(this, ctor || this.constructor);
	if (cause)
		this.cause(cause);

}
645606
function error () {
  if (mocking) {
    cli.stderr += stripAnsi(concatArguments(arguments) + '\n')
  } else {
    console.error.apply(null, arguments)
  }
}
218870
protected function fix_tables(){
    $xp = new DOMXPath($this->_dom);
    
    // Move table caption before the table
    // FIXME find a better way to deal with it...
    $captions = $xp->query("//table/caption");
    foreach($captions as $caption) {
      $table = $caption->parentNode;
      $table->parentNode->insertBefore($caption, $table);
    }
    
    $rows = $xp->query("//table/tr");
    foreach($rows as $row) {
      $tbody = $this->_dom->createElement("tbody");
      $tbody = $row->parentNode->insertBefore($tbody, $row);
      $tbody->appendChild($row);
    }
  }