Write ``system.Varout.vars`` to a ``.dat`` file
        :return:
491775
def write_dat(self):
        
        logger.warn('This function is deprecated and replaced by `write_np_dat`.')

        ret = False
        system = self.system

        # compute the total number of columns, excluding time
        if not system.Recorder.n:
            n_vars = system.dae.m + system.dae.n
            # post-computed power flows include:
            #   bus   - (Pi, Qi)
            #   line  - (Pij, Pji, Qij, Qji, Iij_Real, Iij_Imag, Iji_real, Iji_Imag)
            if system.tds.config.compute_flows:
                n_vars += 2 * system.Bus.n + 8 * system.Line.n + 2 * system.Area.n_combination
            idx = list(range(n_vars))

        else:
            n_vars = len(system.Recorder.varout_idx)
            idx = system.Recorder.varout_idx

        template = ['{:<8g}'] + ['{:0.10f}'] * n_vars
        template = ' '.join(template)

        # format the output in a string
        out = ''
        for t, line in zip(self.t, self.vars):
            values = [t] + list(line[idx])
            out += template.format(*values) + '\n'

        try:
            os.makedirs(os.path.abspath(os.path.dirname(system.files.dat)), exist_ok=True)
            with open(system.files.dat, self._mode) as f:
                f.write(out)
            ret = True

        except IOError:
            logger.error('I/O Error while writing the dat file.')

        return ret
904005
def _EnvOpen(var, mode):
  """"""
  value = os.getenv(var)
  if value is None:
    raise ValueError("%s is not set" % var)

  fd = int(value)

  # If running on Windows, convert the file handle to a C file descriptor; see:
  # https://groups.google.com/forum/#!topic/dev-python/GeN5bFJWfJ4
  if _WINDOWS:
    fd = msvcrt.open_osfhandle(fd, 0)

  return os.fdopen(fd, mode)
1090605
def write_lst(self):
        

        ret = False
        out = ''
        system = self.system
        dae = self.system.dae
        varname = self.system.varname
        template = '{:>6g}, {:>25s}, {:>35s}\n'

        # header line
        out += template.format(0, 'Time [s]', '$Time\\ [s]$')

        # include line flow variables in algebraic variables
        nflows = 0
        if self.system.tds.config.compute_flows:
            nflows = 2 * self.system.Bus.n + \
                     8 * self.system.Line.n + \
                     2 * self.system.Area.n_combination

        # output variable indices
        if system.Recorder.n == 0:
            state_idx = list(range(dae.n))
            algeb_idx = list(range(dae.n, dae.n + dae.m + nflows))
            idx = state_idx + algeb_idx
        else:
            idx = system.Recorder.varout_idx

        # variable names concatenated
        uname = varname.unamex + varname.unamey
        fname = varname.fnamex + varname.fnamey

        for e, i in enumerate(idx):
            out += template.format(e + 1, uname[i], fname[i])

        try:
            with open(self.system.files.lst, 'w') as f:
                f.write(out)
            ret = True
        except IOError:
            logger.error('I/O Error while writing the lst file.')

        return ret
895663
function envReplace(str, vars) {
  return str.replace(/\$?\$\{([A-Za-z0-9_]+)(:-(.*?))?\}/g, function (varStr, varName, _, defValue) {
    // Handle escaping:
    if (varStr.indexOf('$$') === 0) {
      return varStr;
    }
    // Handle simple variable replacement:
    if (vars.hasOwnProperty(varName)) {
      log.debug(`${varName} replaced in configuration file`);
      return vars[varName];
    }
    // Handle default values:
    if (defValue) {
      log.debug(`${varName} replaced with default value in configuration file`);
      return defValue;
    }
    log.warn(`Unknown variable: ${varName}. Returning null.`);
    return null;
  });
}
215565
def _do_write(fname, variable, version, date, table):
        """"""
        # pylint: disable=R0914
        #         Too many local variables (19/15) (col 4)
        print("writing {} ..".format(fname))
        import unicodedata
        import datetime
        import string
        utc_now = datetime.datetime.utcnow()
        indent = 4
        with open(fname, 'w') as fout:
            fout.write(
                '"""{variable_proper} table. Created by setup.py."""\n'
                "# Generated: {iso_utc}\n"
                "# Source: {version}\n"
                "# Date: {date}\n"
                "{variable} = (".format(iso_utc=utc_now.isoformat(),
                                        version=version,
                                        date=date,
                                        variable=variable,
                                        variable_proper=variable.title()))
            for start, end in table:
                ucs_start, ucs_end = unichr(start), unichr(end)
                hex_start, hex_end = ('0x{0:04x}'.format(start),
                                      '0x{0:04x}'.format(end))
                try:
                    name_start = string.capwords(unicodedata.name(ucs_start))
                except ValueError:
                    name_start = u''
                try:
                    name_end = string.capwords(unicodedata.name(ucs_end))
                except ValueError:
                    name_end = u''
                fout.write('\n' + (' ' * indent))
                fout.write('({0}, {1},),'.format(hex_start, hex_end))
                fout.write('  # {0:24s}..{1}'.format(
                    name_start[:24].rstrip() or '(nil)',
                    name_end[:24].rstrip()))
            fout.write('\n)\n')
        print("complete.")
1072795
def wr_dat_files(self, expanded=False, write_dir=''):
        
        # Get the set of dat files to be written, and
        # the channels to be written to each file.
        file_names, dat_channels = describe_list_indices(self.file_name)

        # Get the fmt and byte offset corresponding to each dat file
        DAT_FMTS = {}
        dat_offsets = {}
        for fn in file_names:
            DAT_FMTS[fn] = self.fmt[dat_channels[fn][0]]

            # byte_offset may not be present
            if self.byte_offset is None:
                dat_offsets[fn] = 0
            else:
                dat_offsets[fn] = self.byte_offset[dat_channels[fn][0]]

        # Write the dat files
        if expanded:
            for fn in file_names:
                wr_dat_file(fn, DAT_FMTS[fn], None , dat_offsets[fn], True,
                            [self.e_d_signal[ch] for ch in dat_channels[fn]],
                            self.samps_per_frame, write_dir=write_dir)
        else:
            # Create a copy to prevent overwrite
            dsig = self.d_signal.copy()
            for fn in file_names:
                wr_dat_file(fn, DAT_FMTS[fn],
                            dsig[:, dat_channels[fn][0]:dat_channels[fn][-1]+1],
                            dat_offsets[fn], write_dir=write_dir)
265066
def _add_or_update_vars(self):
        
        # Create the hosts extra inventory source (only if not empty)
        hosts_file = os.path.join(self.inventory_directory, 'hosts')
        if self.hosts:
            util.write_file(hosts_file, util.safe_dump(self.hosts))
        # Create the host_vars and group_vars directories
        for target in ['host_vars', 'group_vars']:
            if target == 'host_vars':
                vars_target = copy.deepcopy(self.host_vars)
                for instance_name, _ in self.host_vars.items():
                    if instance_name == 'localhost':
                        instance_key = instance_name
                    else:
                        instance_key = instance_name

                    vars_target[instance_key] = vars_target.pop(instance_name)

            elif target == 'group_vars':
                vars_target = self.group_vars

            if vars_target:
                target_vars_directory = os.path.join(self.inventory_directory,
                                                     target)

                if not os.path.isdir(util.abs_path(target_vars_directory)):
                    os.mkdir(util.abs_path(target_vars_directory))

                for target in vars_target.keys():
                    target_var_content = vars_target[target]
                    path = os.path.join(
                        util.abs_path(target_vars_directory), target)
                    util.write_file(path, util.safe_dump(target_var_content))
45911
def write_var_str(self, value, encoding: str = 'utf-8'):
        
        if isinstance(value, str):
            value = value.encode(encoding)
        self.write_var_int(len(value))
        self.write_bytes(value)
812877
def write_toml(self, data, path=None):
        """"""
        if path is None:
            path = self.pipfile_location
        data = convert_toml_outline_tables(data)
        try:
            formatted_data = tomlkit.dumps(data).rstrip()
        except Exception:
            document = tomlkit.document()
            for section in ("packages", "dev-packages"):
                document[section] = tomlkit.container.Table()
                # Convert things to inline tables — fancy :)
                for package in data.get(section, {}):
                    if hasattr(data[section][package], "keys"):
                        table = tomlkit.inline_table()
                        table.update(data[section][package])
                        document[section][package] = table
                    else:
                        document[section][package] = tomlkit.string(data[section][package])
            formatted_data = tomlkit.dumps(document).rstrip()

        if (
            vistir.compat.Path(path).absolute()
            == vistir.compat.Path(self.pipfile_location).absolute()
        ):
            newlines = self._pipfile_newlines
        else:
            newlines = DEFAULT_NEWLINES
        formatted_data = cleanup_toml(formatted_data)
        with io.open(path, "w", newline=newlines) as f:
            f.write(formatted_data)
        # pipfile is mutated!
        self.clear_pipfile_cache()
506522
def dump(props, output):
    
    def escape(token):
      return re.sub(r'([=:\s])', r'\\\1', token)

    def write(out):
      for k, v in props.items():
        out.write('%s=%s\n' % (escape(str(k)), escape(str(v))))

    if hasattr(output, 'write') and callable(output.write):
      write(output)
    elif isinstance(output, six.string_types):
      with open(output, 'w+') as out:
        write(out)
    else:
      raise TypeError('Can only dump data to a path or a writable object, given: %s' % output)
795951
def dump_to_store(dataset, store, writer=None, encoder=None,
                  encoding=None, unlimited_dims=None):
    """"""
    if writer is None:
        writer = ArrayWriter()

    if encoding is None:
        encoding = {}

    variables, attrs = conventions.encode_dataset_coordinates(dataset)

    check_encoding = set()
    for k, enc in encoding.items():
        # no need to shallow copy the variable again; that already happened
        # in encode_dataset_coordinates
        variables[k].encoding = enc
        check_encoding.add(k)

    if encoder:
        variables, attrs = encoder(variables, attrs)

    store.store(variables, attrs, check_encoding, writer,
                unlimited_dims=unlimited_dims)
852169
def _var(ins):
    
    output = []
    output.append('%s:' % ins.quad[1])
    output.append('DEFB %s' % ((int(ins.quad[2]) - 1) * '00, ' + '00'))

    return output
308869
def write_properties_from_env(cls, path):
        '''
        
        '''
        with open(path, 'w') as f:
            f.write("# Autogenerated by kclboot v%s on %s\n\n" % (PACKAGE_VERSION, datetime.now()))
            for env_var, prop_var in ENV_TO_PROPERTY.items():
                env_value = os.environ.get(env_var)
                if env_value:
                    f.write("%s=%s\n" % (prop_var, env_value))
1087620
def write_varint(i, data: nil, stream: nil)
      buf = encode_varint(i)
      data << buf if data
      stream.write(buf) if stream
      buf
    end
1367721
def format_vars(args):
    """'"""
    variables = []
    for key, value in args.items():
        if value:
            variables += ['{0}={1}'.format(key, value)]
    return variables
721685
def __write_variables_2(self, col):
        
        col = self.__convert_keys_1("Variables", col)

        # Write one line for each column. One line has all metadata for one column.
        for entry in NOAA_KEYS_BY_SECTION["Variables"]:
            # May need a better way of handling this in the future. Need a strict list for this section.
            try:
                # First entry: Add extra hash and tab
                if entry == 'shortname':
                    # DEPRECATED: Fixed spacing for variable names.
                    # self.noaa_txt.write('{:<20}'.format('#' + str(col[entry])))
                    # Fluid spacing for variable names. Spacing dependent on length of variable names.
                    self.noaa_txt += '{}\t'.format('#' + str(col[entry]))
                # Last entry: No space or comma
                elif entry == "additional":
                    e = " "
                    for item in ["notes", "uncertainty"]:
                        try:
                            if col[item]:
                                e += str(col[item]).replace(",", ";") + "; "
                        except KeyError:
                            pass
                    self.noaa_txt += '{} '.format(e)

                # elif entry == 'notes':
                #     self.noaa_txt.write('{} '.format(str(col[entry])))
                else:
                    # This is for any entry that is not first or last in the line ordering
                    # Account for nested entries.
                    # if entry == "uncertainty":
                    #     try:
                    #         e = str(col["calibration"][entry])
                    #     except KeyError:
                    #         e = ""
                    if entry == "seasonality":
                        try:
                            e = str(col["climateInterpretation"][entry])
                        except KeyError:
                            e = ""
                    elif entry == "archive":
                        e = self.noaa_data_sorted["Top"]["Archive"]
                    elif entry == "dataType":
                        # Lipd uses real data types (floats, ints), NOAA wants C or N (character or numeric)
                        if col[entry] == "float":
                            e = "N"
                        else:
                            e = "C"
                    else:
                        e = str(col[entry])
                    try:
                        e = e.replace(",", ";")
                    except AttributeError as ee:
                        logger_lpd_noaa.warn("write_variables_2: AttributeError: {}, {}".format(e, ee))
                    self.noaa_txt += '{}, '.format(e)
            except KeyError as e:
                self.noaa_txt += '{:<0}'.format(',')
                logger_lpd_noaa.info("write_variables: KeyError: missing {}".format(e))
        self.noaa_txt += '\n#'
        return
835320
def write_script(script, tempdir):
    

    name = "script" + self.suffix
    path = os.path.join(tempdir, name)

    with open(path, "w") as f:
        f.write("\n".join(script))

    return path