r"""
    base_fmtstr must have a %d in it
497286
def get_nonconflicting_path_old(base_fmtstr, dpath, offset=0):
    
    """
    import utool as ut
    from os.path import basename

    pattern = '*'
    dname_list = ut.glob(dpath, pattern, recursive=False,
                               with_files=True, with_dirs=True)
    conflict_set = set([basename(dname) for dname in dname_list])

    newname = ut.get_nonconflicting_string(base_fmtstr, conflict_set,
                                           offset=offset)
    newpath = join(dpath, newname)
    return newpath
885427
def parse(fmt, stri):
    """"""
    convdef = get_convert_dict(fmt)
    keyvals = regex_formatter.extract_values(fmt, stri)
    for key in convdef.keys():
        keyvals[key] = _convert(convdef[key], keyvals[key])

    return keyvals
347213
def deg2fmt(ra_deg, dec_deg, format):
    """"""

    rhr, rmn, rsec = degToHms(ra_deg)
    dsgn, ddeg, dmn, dsec = degToDms(dec_deg)

    if format == 'hms':
        return rhr, rmn, rsec, dsgn, ddeg, dmn, dsec

    elif format == 'str':
        #ra_txt = '%02d:%02d:%06.3f' % (rhr, rmn, rsec)
        ra_txt = '%d:%02d:%06.3f' % (rhr, rmn, rsec)
        if dsgn < 0:
            dsgn = '-'
        else:
            dsgn = '+'
        #dec_txt = '%s%02d:%02d:%05.2f' % (dsgn, ddeg, dmn, dsec)
        dec_txt = '%s%d:%02d:%05.2f' % (dsgn, ddeg, dmn, dsec)
        return ra_txt, dec_txt
180565
function rtrim(str, targetStr) {
    var retStr = "";
    var regStr;

    if (typeof str != "string") {
        return retStr;
    }

    if (typeof targetStr != "string" || !targetStr) {
        targetStr = "\\s";
    }

    regStr = "(.*?)" + targetStr + "*$";
    regStr = new RegExp(regStr);

    str = str.replace(regStr, "$1");
    return str;
}
163215
def dt2str(dt, flagSeconds=True):
    """"""
    if isinstance(dt, str):
        return dt
    return dt.strftime(_FMTS if flagSeconds else _FMT)
576189
def unpack(fmt, arg):
    """"""

    if isinstance(arg, bytearray) and not (sys.version_info >= (2, 7, 5)):
        return struct.unpack(fmt, str(arg))

    return struct.unpack(fmt, arg)
240252
def _no_ntplt(self, ntplt):
        """"""
        sys.stdout.write("  {GO_USR:>6,} usr {GO_ALL:>6,} GOs  DID NOT WRITE: {B} {D}\n".format(
            B=self.grprobj.get_fout_base(ntplt.hdrgo),
            D=ntplt.desc,
            GO_USR=len(ntplt.gosubdag.go_sources),
            GO_ALL=len(ntplt.gosubdag.go2obj)))
204035
def fmtstr(text='', colorstr=None, align='>', trunc=True, width=0, end=' '):
    ''' 
    '''
    colwidth = width or opts.colwidth

    if trunc:
        if len(text) > colwidth:
            text = truncstr(text, colwidth, align=trunc)  # truncate w/ellipsis

    value = f'{text:{align}{colwidth}}'
    if opts.incolor and colorstr:
        return colorstr % value + end
    else:
        return value + end
762898
def clean_add_strdec(*args, prec=28):
    """"""

    # load modules
    import pandas as pd
    import numpy as np
    import re
    from decimal import Decimal, getcontext
    getcontext().prec = prec

    # initialize result as 0.0
    def proc_elem(*args):
        t = Decimal('0.0')
        for a in args:
            if isinstance(a, str):
                a = re.sub('[^0-9\.\-]+', '', a)

            if a and pd.notnull(a):
                t += Decimal(a)

        return str(t)

    def proc_list(arr):
        return [proc_elem(*row) for row in arr]

    def proc_ndarray(arr):
        return np.array(proc_list(arr))

    # transform depending on provided datatypes
    if isinstance(args[0], (list, tuple)):
        return proc_list(args[0])
    elif isinstance(args[0], np.ndarray):
        return proc_ndarray(args[0])
    elif isinstance(args[0], pd.DataFrame):
        return pd.DataFrame(proc_ndarray(args[0].values),
                            index=args[0].index)
    else:
        return proc_elem(*args)
77415
def fmtd_sub_expr_str(self):
        """"""
        result = u"{}({}".format(self.normalized_func,
                                 self._metric_name)

        if self._dimensions is not None:
            result += "{" + self.dimensions_str + "}"

        if self._period != _DEFAULT_PERIOD:
            result += ", {}".format(self._period)

        result += ")"

        result += " {} {}".format(self._operator,
                                  self._threshold)

        if self._periods != _DEFAULT_PERIODS:
            result += " times {}".format(self._periods)

        return result
460215
def unixtime2str(timestamp, fmt='%Y-%m-%d %H:%M:%S'):
    
    dt = None
    try:
        timestamp = time.localtime(timestamp)
        dt = time.strftime(fmt, timestamp)
    except Exception as err:
        print(err)
    return dt
1317626
def fmtval(value, colorstr=None, precision=None, spacing=True, trunc=True,
           end=' '):
    '''  '''
    colwidth = opts.colwidth
    # get precision
    if precision is None:
        precision = opts.precision
    fmt = '%%.%sf' % precision

    # format with decimal mark, separators
    result = locale.format(fmt, value, True)

    if spacing:
        result = '%%%ss' % colwidth % result

    if trunc:
        if len(result) > colwidth:   # truncate w/ellipsis
            result = truncstr(result, colwidth)

    # Add color if needed
    if opts.incolor and colorstr:
        return colorstr % result + end
    else:
        return result + end
803039
def _fmt_structured(d):
        
        timeEntry = datetime.datetime.utcnow().strftime(
            "time=%Y-%m-%dT%H:%M:%S.%f-00")
        pidEntry = "pid=" + str(os.getpid())

        rest = sorted('='.join([str(k), str(v)])
                      for (k, v) in list(d.items()))

        return ' '.join([timeEntry, pidEntry] + rest)
1293929
def _cli_check_format(fmt):
    ''''''

    if fmt is None:
        return None

    fmt = fmt.lower()
    if not fmt in api.get_formats():
        errstr = "Format '" + fmt + "' does not exist.\n"
        errstr += "For a complete list of formats, use the 'bse list-formats' command"
        raise RuntimeError(errstr)

    return fmt
403414
def _retstr(ins):
    
    tmp, output = _str_oper(ins.quad[1], no_exaf=True)

    if not tmp:
        output.append('call __LOADSTR')
        REQUIRES.add('loadstr.asm')

    output.append('#pragma opt require hl')
    output.append('jp %s' % str(ins.quad[2]))
    return output
571120
def rdtxt_gos(go_file, prt):
        """"""
        goids_all = set()
        if not os.path.exists(go_file):
            raise RuntimeError("CAN NOT READ GO FILE: {FILE}\n".format(FILE=go_file))
        re_go = re.compile(r'(GO:\d{7})+?')
        re_com = re.compile(r'^\s*#')  # Lines starting with a '#' are comment lines and ignored
        with open(go_file) as ifstrm:
            for line in ifstrm:
                # Skip lines that are comments
                if re_com.search(line):
                    continue
                # Search for GO IDs on the line
                goids_found = re_go.findall(line)
                if goids_found:
                    goids_all.update(goids_found)
            if prt:
                prt.write("  {N} GO IDs READ: {TXT}\n".format(N=len(goids_all), TXT=go_file))
        return goids_all
772578
def get_nts_strpval(self, fmt="{:8.2e}"):
        """"""
        objntmgr = MgrNts(self.goea_results)
        dcts = objntmgr.init_dicts()
        # pylint: disable=line-too-long
        pval_flds = set(k for k in self._get_fieldnames(next(iter(self.goea_results))) if k[:2] == 'p_')
        for fld_float in pval_flds:
            fld_str = "s_" + fld_float[2:]
            objntmgr.add_f2str(dcts, fld_float, fld_str, fmt)
        return objntmgr.mknts(dcts)