Handle EPIPE errors when user doesn't put quotes around output file name with parameters
779802
function epipeError(err) {
  if (err.code === 'EPIPE' || err.errno === 32) return process.exit;

  if (process.stdout.listeners('error').length <= 1) {
    process.stdout.removeAllListeners();
    process.stdout.emit('error', err);
    process.stdout.on('error', epipeError);
  }
}
424126
function onDelete( error ) {
			if ( error ) {
				debug( 'Error encountered while attempting to delete a temporary output file %s: %s', outFile, error.message );
				return done( error );
			}
			debug( 'Successfully deleted temporary output file: %s', outFile );
			done( null, file );
		}
170263
def err(*output, **kwargs):
    
    output = 'Error: ' + ' '.join([str(o) for o in output])
    if kwargs.get('wrap') is not False:
        output = '\n'.join(wrap(output, kwargs.get('indent', '')))
    elif kwargs.get('indent'):
        indent = kwargs['indent']
        output = indent + ('\n' + indent).join(output.splitlines())
    sys.stderr.write(output + '\n')
1356569
def _report_lint_error(error, file_path):
    """"""
    line = error[1].line
    code = error[0]
    description = error[1].description
    sys.stdout.write("{0}:{1} [{2}] {3}\n".format(file_path,
                                                  line,
                                                  code,
                                                  description))
476619
def _adorn_eof_error(self, e):
        
        if self.eof_error_hint:
            e.args = ('%s\n\n%s' % (e.args[0], self.eof_error_hint),)
989665
def FormatException(self, e, output):
    """"""
    d = e.GetDictToFormat()
    for k in ('file_name', 'feedname', 'column_name'):
      if k in d.keys():
        d[k] = '<code>%s</code>' % d[k]
    if 'url' in d.keys():
      d['url'] = '<a href="%(url)s">%(url)s</a>' % d

    problem_text = e.FormatProblem(d).replace('\n', '<br>')
    problem_class = 'problem'
    if e.IsNotice():
      problem_class += ' notice'
    output.append('<li>')
    output.append('<div class="%s">%s</div>' %
                  (problem_class, transitfeed.EncodeUnicode(problem_text)))
    try:
      if hasattr(e, 'row_num'):
        line_str = 'line %d of ' % e.row_num
      else:
        line_str = ''
      output.append('in %s<code>%s</code><br>\n' %
                    (line_str, transitfeed.EncodeUnicode(e.file_name)))
      row = e.row
      headers = e.headers
      column_name = e.column_name
      table_header = ''  # HTML
      table_data = ''  # HTML
      for header, value in zip(headers, row):
        attributes = ''
        if header == column_name:
          attributes = ' class="problem"'
        table_header += '<th%s>%s</th>' % (attributes, header)
        table_data += '<td%s>%s</td>' % (attributes, value)
      # Make sure output is encoded into UTF-8
      output.append('<table class="dump"><tr>%s</tr>\n' %
                    transitfeed.EncodeUnicode(table_header))
      output.append('<tr>%s</tr></table>\n' %
                    transitfeed.EncodeUnicode(table_data))
    except AttributeError as e:
      pass  # Hope this was getting an attribute from e ;-)
    output.append('<br></li>\n')
703928
def quote(self, identifier, errors="strict"):
        
        if identifier is None:
            return None

        encodable = identifier.encode("utf-8", errors).decode("utf-8")

        nul_index = encodable.find("\x00")

        if nul_index >= 0:
            error = UnicodeEncodeError(
                "NUL-terminated utf-8",
                encodable,
                nul_index,
                nul_index + 1,
                "NUL not allowed"
            )
            error_handler = codecs.lookup_error(errors)
            replacement, _ = error_handler(error)
            encodable = encodable.replace("\x00", replacement)

        return "\"" + encodable.replace("\"", "\"\"") + "\""
16106
def on_error(e):  # pragma: no cover
    
    exname = {'RuntimeError': 'Runtime error', 'Value Error': 'Value error'}
    sys.stderr.write('{}: {}\n'.format(exname[e.__class__.__name__], str(e)))
    sys.stderr.write('See file slam_error.log for additional details.\n')
    sys.exit(1)
1008054
def write(self, outfile='../parameters/EQcorrscan_parameters.txt',
              overwrite=False):
        
        outpath = os.sep.join(outfile.split(os.sep)[0:-1])
        if len(outpath) > 0 and not os.path.isdir(outpath):
            msg = ' '.join([os.path.join(outfile.split(os.sep)[0:-1]),
                            'does not exist, check path.'])
            raise IOError(msg)
        # Make sure that the user wants to overwrite the old parameters
        if os.path.isfile(outfile) and not overwrite:
            responding = True
            while responding:
                print(' '.join([outfile, 'exists.  Overwrite? [y/N]']))
                option = raw_input()
                if option.upper() == 'N':
                    raise IOError('File exists, will not overwrite')
                elif option.upper() == 'Y':
                    responding = False
                else:
                    print('Must respond with y or n')
        f = open(outfile, 'w')
        # Write creation info.
        header = ' '.join(['# User:', getpass.getuser(),
                           '\n# Creation date:', str(UTCDateTime()),
                           '\n# EQcorrscan version:',
                           str(eqcorrscan.__version__),
                           '\n\n\n'])
        f.write(header)
        # Write parameter info in a user readable, and parsable format.
        parameters = self.__str__().split('\n')[1:]
        f.write('[eqcorrscan_pars]\n')
        for parameter in parameters:
            f.write(parameter.lstrip() + '\n')
        f.close()
        print('Written parameter file: ' + outfile)
118799
protected void handleNonDoubleQuoteString(int ch, boolean isName) throws IOException {
    if (ch == '\'') {
      stringTerm = ch;
      if ((flags & ALLOW_SINGLE_QUOTES) == 0) {
        throw err("Single quoted strings not allowed");
      }
    } else {
      if (isName && (flags & ALLOW_UNQUOTED_KEYS) == 0
        || !isName && (flags & ALLOW_UNQUOTED_STRING_VALUES) == 0
        || eof)
      {
        if (isName) {
          throw err("Expected quoted string");
        } else {
          throw err(null);
        }
      }

      if (!isUnquotedStringStart(ch)) {
        throw err(null);
      }

      stringTerm = 0;  // signal for unquoted string
      out.reset();
      out.unsafeWrite(ch);
    }
  }
1311571
function _displayCreationError(e, errorInfo) {
        window.setTimeout(function () {
            var error = errorInfo.type,
                isFolder = errorInfo.isFolder,
                name = errorInfo.name;

            if (error === FileSystemError.ALREADY_EXISTS) {
                _showErrorDialog(ERR_TYPE_CREATE_EXISTS, isFolder, null, name);
            } else if (error === ProjectModel.ERROR_INVALID_FILENAME) {
                _showErrorDialog(ERR_TYPE_INVALID_FILENAME, isFolder, ProjectModel._invalidChars);
            } else {
                var errString = error === FileSystemError.NOT_WRITABLE ?
                        Strings.NO_MODIFICATION_ALLOWED_ERR :
                        StringUtils.format(Strings.GENERIC_ERROR, error);

                _showErrorDialog(ERR_TYPE_CREATE, isFolder, errString, name).getPromise();
            }
        }, 10);
    }
822445
def showsyntaxerror(self, filename=None):
        """"""
        # Override for avoid using sys.excepthook PY-12600
        type, value, tb = sys.exc_info()
        sys.last_type = type
        sys.last_value = value
        sys.last_traceback = tb
        if filename and type is SyntaxError:
            # Work hard to stuff the correct filename in the exception
            try:
                msg, (dummy_filename, lineno, offset, line) = value.args
            except ValueError:
                # Not the format we expect; leave it alone
                pass
            else:
                # Stuff in the right filename
                value = SyntaxError(msg, (filename, lineno, offset, line))
                sys.last_value = value
        list = traceback.format_exception_only(type, value)
        sys.stderr.write(''.join(list))
212399
def handle_namespace_invalid(self, line: str, position: int, tokens: ParseResults) -> None:
        """"""
        name = tokens[NAME]
        raise NakedNameWarning(self.get_line_number(), line, position, name)
291966
def error(sample, message):
        
        # Set the .fastqfiles attribute to an empty list
        sample.general.fastqfiles = list()
        # Ensure that the run attribute exists
        if GenObject.isattr(sample, 'run'):
            # If the Description attribute exists, overwrite it, otherwise create and populate it
            if GenObject.isattr(sample.run, 'status'):
                sample.run.status = message
            else:
                setattr(sample.run, 'status', message)
        # Otherwise create and populate the attribute
        else:
            setattr(sample, 'run', GenObject())
            sample.run.Description = message
1059872
def pout(*args, **kwargs):
    """"""
    if should_msg(kwargs.get("groups", ["normal"])):
        args = indent_text(*args, **kwargs)

        # write to stdout
        sys.stderr.write("".join(args))
        sys.stderr.write("\n")
390245
def safeprint(message, write_to_stderr=False, newline=True):
    
    try:
        click.echo(message, nl=newline, err=write_to_stderr)
    except IOError as err:
        if err.errno is errno.EPIPE:
            pass
        else:
            raise
719109
def _export_work_errors(self, work, output_file):
    
    errors = set()
    for v in itervalues(work.work):
      if v['is_completed'] and v['error'] is not None:
        errors.add(v['error'])
    with open(output_file, 'w') as f:
      for e in sorted(errors):
        f.write(e)
        f.write('\n')