Error from the model mapped back to the CSV header if we can
327929
def errors
      Hash[
        model.errors.map do |attribute, errors|
          if column_name = header.column_name_for_model_attribute(attribute)
            [column_name, errors]
          else
            [attribute, errors]
          end
        end
      ]
    end
1210256
function _formatErrorsWarnings(level, list, projectRoot){
    return list.map(x => {
        let file, line, col, endLine, endCol, message
        try{
            // resolve  the relative path 
            let fullFilePath = data_get(x, 'module.resource')
            file = fullFilePath && projectRoot ? path.relative(projectRoot, fullFilePath) : ''
            // file = file.replace(/[\\//]/g, '/')

            line = data_get(x, 'error.error.loc.line') || 0
            col = data_get(x, 'error.error.loc.column') || 0

            // only need first line of message
            let fullMessage = (x.message + '').trim()
            let crPos = fullMessage.indexOf("\n")
            if (crPos >= 0){
                message = fullMessage.substring(0, crPos)
            } else {
                message = fullMessage
            }

            if (!line){
                let linesColsInfo
                let m
                if (x.name === 'ModuleNotFoundError'
                    && (m = fullMessage.match(MODULE_NOT_FOUND_ERR_MSG_PATTERN))){
                    linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1])
                } else if (fullMessage.indexOf('component lists rendered with v-for should have explicit keys') > 0
                    && (m = fullMessage.match(/([a-zA-Z-_]+)\s+(v-for=['"].*?['"])/))){
                    linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[2], {after: m[1]})
                } else if (m = fullMessage.match(/export ['"](\S+?)['"] was not found/)){
                    linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1], {after: 'import'})
                } else if (m = fullMessage.match(/Error compiling template:((?:.|[\r\n])*)- Component template/m)){
                    linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1].trim())
                    message = fullMessage.replace(/\n/g, ' ')
                }

                if (linesColsInfo){
                    line = linesColsInfo.line || 0
                    col = linesColsInfo.col || 0
                    endLine = linesColsInfo.endLine
                    endCol = linesColsInfo.endCol
                }
            }

            let endLinesCols = (endLine || endCol) ? ('~' + (endLine || '') + (endLine ? ',' : '') + (endCol || '0')) : ''

            return `!>${level}: ${file}:${line},${col}${endLinesCols}: ${message || '@see output window'}`            
        } catch (e){
            console.warn(e)
            return ''
        }
    }).join("\n")
}
696049
def _get_csv_from_model(models, crumbs, csvs):
    
    logger_csvs.info("enter get_csv_from_model: {}".format(crumbs))
    _idx = 0
    try:
        for _name, _model in models.items():
            if "distributionTable" in _model:
                models[_name]["distributionTable"], csvs = _get_csv_from_table(_model["distributionTable"], "{}{}{}".format(crumbs, _idx, "distribution"), csvs)

            if "summaryTable" in _model:
                models[_name]["summaryTable"], csvs = _get_csv_from_table(_model["summaryTable"], "{}{}{}".format(crumbs, _idx, "summary"), csvs)

            if "ensembleTable" in _model:
                models[_name]["ensembleTable"], csvs = _get_csv_from_table(_model["ensembleTable"], "{}{}{}".format(crumbs, _idx, "ensemble"), csvs)
            _idx += 1
    except Exception as e:
        print("Error: get_csv_from_model: {}, {}".format(crumbs, e))
        logger_csvs.error("Error: get_csv_from_model: {}, {}".format(crumbs, e))
    return models, csvs
1062210
def parse_errors(csv_file):
    
    with csv_file.open(newline='') as f:
        f = csv.reader(f)
        next(f, None)  # header
        for line, tup in enumerate(f, start=2):
            try:
                name, codes, description = tup
            except ValueError:
                raise ValueError('Columns count mismatch, unquoted comma in '
                                 'desc? (line {})'.format(line)) from None

            try:
                codes = [int(x) for x in codes.split()] or [400]
            except ValueError:
                raise ValueError('Not all codes are integers '
                                 '(line {})'.format(line)) from None

            yield Error([int(x) for x in codes], name, description)
1023058
def _dump_model(model, attrs=None):
    

    fields = []

    for field in model._meta.fields:
        fields.append((field.name, str(getattr(model, field.name))))

    if attrs is not None:
        for attr in attrs:
            fields.append((attr, str(getattr(model, attr))))

    for field in model._meta.many_to_many:
        vals = getattr(model, field.name)
        fields.append((field.name, '{val} ({count})'.format(
            val=', '.join(map(str, vals.all())),
            count=vals.count(),
        )))

    print(', '.join(
        '{0}={1}'.format(field, value)
        for field, value in fields
    ))
566704
function error (message, error) {
    // get model name
    var modelName = defined(this) && defined(this.name) ? this.name : 'ImmutableCoreModel'
    // build custom error message
    message = `${modelName} error` + (
        typeof message === 'string'
            ? `: ${message}`
            : ''
    )
    // use error object passed in
    if (defined(error)) {
        // create data object with original message
        error.data = {
            error: {
                code: error.code,
                message: error.message,
            },
        }
    }
    // create new error message
    else {
        error = new Error(message)
        error.data = {}
    }

    return error
}
144892
def getCsv(L=None):
    
    _c = {}
    try:
        if not L:
            print("Error: LiPD data not provided. Pass LiPD data into the function.")
        else:
            _j, _c = get_csv_from_metadata(L["dataSetName"], L)
    except KeyError as ke:
        print("Error: Unable to get data. Please check that input is one LiPD dataset: {}".format(ke))
    except Exception as e:
        print("Error: Unable to get data. Something went wrong: {}".format(e))
        logger_start.warn("getCsv: Exception: Unable to process lipd data: {}".format(e))
    return _c
453126
def export_asset_risk_csv(ekey, dstore):
    
    writer = writers.CsvWriter(fmt=writers.FIVEDIGITS)
    path = '%s.%s' % (sanitize(ekey[0]), ekey[1])
    fname = dstore.export_path(path)
    md = extract(dstore, 'exposure_metadata')
    tostr = {'taxonomy': md.taxonomy}
    for tagname in md.tagnames:
        tostr[tagname] = getattr(md, tagname)
    arr = extract(dstore, 'asset_risk').array
    arefs = dstore['assetcol/asset_refs'].value
    rows = []
    lossnames = sorted(name for name in arr.dtype.names if 'loss' in name)
    perilnames = sorted(name for name in arr.dtype.names
                        if name.upper() == name)
    expnames = [name for name in arr.dtype.names if name not in md.tagnames
                and 'loss' not in name and name not in perilnames
                and name not in 'lon lat']
    colnames = (['asset_ref'] + sorted(md.tagnames) + ['lon', 'lat'] +
                expnames + perilnames + lossnames)
    # sanity check
    assert len(colnames) == len(arr.dtype.names) + 1
    for aref, rec in zip(arefs, arr):
        row = [aref]
        for name in colnames[1:]:
            value = rec[name]
            try:
                row.append('"%s"' % tostr[name][value])
            except KeyError:
                row.append(value)
        rows.append(row)
    writer.save(rows, fname, colnames)
    return [fname]
205176
def _get_example_csv(self):
        
        station_key = self.json["station"][0]["key"]
        period = "corrected-archive"
        url = self.url\
                  .replace(".json", "/station/{}/period/{}/data.csv"\
                  .format(station_key, period))

        r = requests.get(url)
        if r.status_code == 200:
            return DataCsv().from_string(r.content)
        else:
            raise Exception("Error connecting to api")
854740
def from_csv(cls, path:PathOrStr, csv_name:str, cols:IntsOrStrs=0, delimiter:str=None, header:str='infer',
                 processor:PreProcessors=None, **kwargs)->'ItemList':
        """"""
        df = pd.read_csv(Path(path)/csv_name, delimiter=delimiter, header=header)
        return cls.from_df(df, path=path, cols=cols, processor=processor, **kwargs)
961157
private static ModelAndView paramError(Map<String, String> paramErrors, Map<String, Object[]> paramArgusErrors,
                                           ErrorCode errorCode) {

        JsonObjectBase jsonObject = JsonObjectUtils.buildFieldError(paramErrors, paramArgusErrors, errorCode);
        return JsonObjectUtils.JsonObjectError2ModelView((JsonObjectError) jsonObject);
    }
1051462
def _generate_csv_header_line(*, header_names, header_prefix='', header=True, sep=',', newline='\n'):
    
    if isinstance(header, str):  # user-provided header line
        header_line = header + newline
    else:
        if not (header is None or isinstance(header, bool)):
            raise ValueError(f"Invalid value for argument `header`: {header}")
        else:
            if header:
                header_line = header_prefix + sep.join(header_names) + newline
            else:
                header_line = ""
    return header_line
119136
function throwErrorOnUndefinedColumnName(keys, extract) {
    var regexRefs = /([a-zA-Z$_][\w$]+)(\s*\.\s*[a-zA-Z$_][\w$]+)*/g, // identifier[.identifier]...
        parts, variable;

    keys = keys.concat(['true', 'false']);

    // search for variable references, excluding property references (with dot operator prefix)
    while ((parts = regexRefs.exec(extract))) {
        variable = parts[1];
        if (keys.indexOf(variable) < 0) {
            throw new ReferenceError(variable + ' not defined.');
        }
    }
}
140638
def to_internal_value(self, data):
        
        if not data:
            return None
        request = self._get_request()
        user = request.user
        try:
            obj = core_utils.instance_from_url(data, user=user)
            model = obj.__class__
        except ValueError:
            raise serializers.ValidationError(_('URL is invalid: %s.') % data)
        except (Resolver404, AttributeError, MultipleObjectsReturned, ObjectDoesNotExist):
            raise serializers.ValidationError(_("Can't restore object from url: %s") % data)
        if model not in self.related_models:
            raise serializers.ValidationError(_('%s object does not support such relationship.') % six.text_type(obj))
        return obj
596072
def error(self, **kwargs):
        '''
        
        '''
        exception_header_width = 100

        e = Error(**kwargs)
        e.module = self.__class__.__name__

        self.errors.append(e)

        if e.exception:
            sys.stderr.write("\n" + e.module + " Exception: " + str(e.exception) + "\n")
            sys.stderr.write("-" * exception_header_width + "\n")
            traceback.print_exc(file=sys.stderr)
            sys.stderr.write("-" * exception_header_width + "\n\n")
        elif e.description:
            sys.stderr.write("\n" + e.module + " Error: " + e.description + "\n\n")
181931
@SuppressWarnings("rawtypes")
    private ModelAndView buildError(ModelAndView mvc, ResultCode error) {
        mvc.addObject("data", new ArrayList(0));
        mvc.addObject("status", error.getCode());
        Map<String, Object> statusInfo = Maps.newHashMapWithExpectedSize(1);
        statusInfo.put(WebResponseConstant.MESSAGE_GLOBAL, error.getMessage().getMessage());
        mvc.addObject("statusInfo", statusInfo);
        mvc.addObject("msg", error.getMessage().getMessage());
        return mvc;
    }
276493
def load(self, model, value):
        
        try:
            return self._cattrs_converter.structure(value, model)
        except (ValueError, TypeError) as e:
            raise SerializationException(str(e))