Write first two lines of gct file.

    Args:
        version (string): 1.3 by default
        dims (list of strings): length = 4
        f (file handle): handle of output file
    Returns:
        nothing
498741
def write_version_and_dims(version, dims, f):
    
    f.write(("#" + version + "\n"))
    f.write((dims[0] + "\t" + dims[1] + "\t" + dims[2] + "\t" + dims[3] + "\n"))
776811
def write(self,
        fout=None,
        fmt=SPARSE,
        schema_only=False,
        data_only=False):
        
        assert not (schema_only and data_only), 'Make up your mind.'
        assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s' % (fmt, ', '.join(FORMATS))
        close = False
        if fout is None:
            close = True
            fout = StringIO()
        if not data_only:
            print('% ' + re.sub("\n", "\n% ", '\n'.join(self.comment)), file=fout)
            print("@relation " + self.relation, file=fout)
            self.write_attributes(fout=fout)
        if not schema_only:
            print("@data", file=fout)
            for d in self.data:
                line_str = self.write_line(d, fmt=fmt)
                if line_str:
                    print(line_str, file=fout)
        if isinstance(fout, StringIO) and close:
            return fout.getvalue()
874131
def gen_version(do_write=True, txt=None):
    

    if txt is None:
        txt = get_git_describe()

    try:
        info = VersionInfo(txt)
        vstr = info.package_version
    except MalformedGitTag:
        warnings.warn("Malformed input '{0}'".format(txt))
        vstr = '0.0.0'+txt

    if not do_write:
        print(vstr)
        return

    lines = (
        '# This file automatically generated by',
        '#    {0}'.format(__file__),
        '# at',
        '#    {0}'.format(datetime.datetime.now().isoformat(' ')),
        "__version__ = '{0}'".format(vstr)
    )
    with open(VERSION_FILE, "w") as fp:
        fp.write("\n".join(lines))
996880
def version_to_write(self, found):  # type: (str) -> Version
        
        first = False
        if self.version is None:
            first = True
            try:
                self.current_version, self.version, self.schema = version_object_and_next(
                    found.strip(" ")
                )
            except:
                raise JiggleVersionException("Shouldn't throw here.")

        if first:
            logger.info(
                "Updating from version {0} to {1}".format(
                    unicode(self.version), unicode(self.version)
                )
            )
        return self.version
848988
def _write_ini(source_dict, namespace_name=None, level=0, indent_size=4,
                   output_stream=sys.stdout):
        """"""
        options = [
            value
            for value in source_dict.values()
            if isinstance(value, Option)
        ]
        options.sort(key=lambda x: x.name)
        indent_spacer = " " * (level * indent_size)
        for an_option in options:
            print("%s# %s" % (indent_spacer, an_option.doc),
                  file=output_stream)
            option_value = to_str(an_option)

            if an_option.reference_value_from:
                print(
                    '%s# see "%s.%s" for the default or override it here' % (
                        indent_spacer,
                        an_option.reference_value_from,
                        an_option.name
                    ),
                    file=output_stream
                )

            if an_option.likely_to_be_changed or an_option.has_changed:
                option_format = '%s%s=%s\n'
            else:
                option_format = '%s#%s=%s\n'

            if isinstance(option_value, six.string_types) and \
                    ',' in option_value:
                # quote lists unless they're already quoted
                if option_value[0] not in '\'"':
                    option_value = '"%s"' % option_value

            print(option_format % (indent_spacer, an_option.name,
                                   option_value),
                  file=output_stream)
        next_level = level + 1
        namespaces = [
            (key, value)
            for key, value in source_dict.items()
            if isinstance(value, Namespace)
        ]
        namespaces.sort(key=ValueSource._namespace_reference_value_from_sort)
        for key, namespace in namespaces:
            next_level_spacer = " " * next_level * indent_size
            print("%s%s%s%s\n" % (indent_spacer, "[" * next_level, key,
                                  "]" * next_level),
                  file=output_stream)
            if namespace._doc:
                print("%s%s" % (next_level_spacer, namespace._doc),
                      file=output_stream)
            if namespace._reference_value_from:
                print("%s#+include ./common_%s.ini\n"
                      % (next_level_spacer, key), file=output_stream)

            if namespace_name:
                ValueSource._write_ini(
                    source_dict=namespace,
                    namespace_name="%s.%s" % (namespace_name, key),
                    level=level+1,
                    indent_size=indent_size,
                    output_stream=output_stream
                )
            else:
                ValueSource._write_ini(
                    source_dict=namespace,
                    namespace_name=key,
                    level=level+1,
                    indent_size=indent_size,
                    output_stream=output_stream
                )
42462
def output(self, _filename):
        

        for c in self.contracts:
            (name, inheritance, var, func_summaries, modif_summaries) = c.get_summary()
            txt = "\nContract %s"%name
            txt += '\nContract vars: '+str(var)
            txt += '\nInheritance:: '+str(inheritance)
            table = PrettyTable(["Function",
                                 "Visibility",
                                 "Modifiers",
                                 "Read",
                                 "Write",
                                 "Internal Calls",
                                 "External Calls"])
            for (_c_name, f_name, visi, modifiers, read, write, internal_calls, external_calls) in func_summaries:
                read = self._convert(read)
                write = self._convert(write)
                internal_calls = self._convert(internal_calls)
                external_calls = self._convert(external_calls)
                table.add_row([f_name, visi, modifiers, read, write, internal_calls, external_calls])
            txt += "\n \n"+str(table)
            table = PrettyTable(["Modifiers",
                                 "Visibility",
                                 "Read",
                                 "Write",
                                 "Internal Calls",
                                 "External Calls"])
            for (_c_name, f_name, visi, _, read, write, internal_calls, external_calls) in modif_summaries:
                read = self._convert(read)
                write = self._convert(write)
                internal_calls = self._convert(internal_calls)
                external_calls = self._convert(external_calls)
                table.add_row([f_name, visi, read, write, internal_calls, external_calls])
            txt += "\n\n"+str(table)
            txt += "\n"
            self.info(txt)
306467
def print_versions(file: typing.TextIO = None) -> None:
    

    print('** QuantumFlow dependencies (> python -m quantumflow.meta) **')
    print('quantumflow \t', qf.__version__, file=file)
    print('python      \t', sys.version[0:5], file=file)
    print('numpy       \t', np.__version__, file=file)
    print('networkx    \t', nx.__version__, file=file)
    print('cvxpy      \t', cvx.__version__, file=file)
    print('pyquil      \t', pyquil.__version__, file=file)

    print(bk.name, '   \t', bk.version, '(BACKEND)', file=file)
362392
def write(notebook, file_or_stream, fmt, version=nbformat.NO_CONVERT, **kwargs):
    """"""
    # Python 2 compatibility
    text = u'' + writes(notebook, fmt, version, **kwargs)
    file_or_stream.write(text)
    # Add final newline #165
    if not text.endswith(u'\n'):
        file_or_stream.write(u'\n')
285428
def _write_header(f, version, flags, stream_id, opcode, length):
        
        pack = v3_header_pack if version >= 3 else header_pack
        f.write(pack(version, flags, stream_id, opcode))
        write_int(f, length)
345473
def write(self, __text: str) -> None:
        
        if __text == os.linesep:
            self.handle.write(__text)
        else:
            frame = inspect.currentframe()
            if frame is None:
                filename = 'unknown'
                lineno = 0
            else:
                outer = frame.f_back
                filename = outer.f_code.co_filename.split(os.sep)[-1]
                lineno = outer.f_lineno
            self.handle.write('[{:>15s}:{:03d}] {}'.format(filename[-15:],
                                                           lineno, __text))
381566
def write_file(self, file_name, vasp4_compatible=False):
        

        def _print_fortran_float(f):
            """
            Fortran codes print floats with a leading zero in scientific
            notation. When writing CHGCAR files, we adopt this convention
            to ensure written CHGCAR files are byte-to-byte identical to
            their input files as far as possible.
            :param f: float
            :return: str
            """
            s = "{:.10E}".format(f)
            if f >= 0:
                return "0." + s[0] + s[2:12] + 'E' + "{:+03}".format(int(s[13:]) + 1)
            else:
                return "-." + s[1] + s[3:13] + 'E' + "{:+03}".format(int(s[14:]) + 1)

        with zopen(file_name, "wt") as f:
            p = Poscar(self.structure)

            # use original name if it's been set (e.g. from Chgcar)
            comment = getattr(self, 'name', p.comment)

            lines = comment + "\n"
            lines += "   1.00000000000000\n"
            latt = self.structure.lattice.matrix
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[0, :])
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[1, :])
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[2, :])
            if not vasp4_compatible:
                lines += "".join(["%5s" % s for s in p.site_symbols]) + "\n"
            lines += "".join(["%6d" % x for x in p.natoms]) + "\n"
            lines += "Direct\n"
            for site in self.structure:
                lines += "%10.6f%10.6f%10.6f\n" % tuple(site.frac_coords)
            lines += " \n"
            f.write(lines)
            a = self.dim

            def write_spin(data_type):
                lines = []
                count = 0
                f.write("   {}   {}   {}\n".format(a[0], a[1], a[2]))
                for (k, j, i) in itertools.product(list(range(a[2])),
                                                   list(range(a[1])),
                                                   list(range(a[0]))):
                    lines.append(_print_fortran_float(self.data[data_type][i, j, k]))
                    count += 1
                    if count % 5 == 0:
                        f.write(" " + "".join(lines) + "\n")
                        lines = []
                    else:
                        lines.append(" ")
                f.write(" " + "".join(lines) + " \n")
                f.write("".join(self.data_aug.get(data_type, [])))

            write_spin("total")
            if self.is_spin_polarized and self.is_soc:
                write_spin("diff_x")
                write_spin("diff_y")
                write_spin("diff_z")
            elif self.is_spin_polarized:
                write_spin("diff")
267087
def write_lines_to_file(cls_name, filename, lines, metadata_dict):
  """"""
  metadata_dict = metadata_dict or {}
  header_line = "%s%s" % (_HEADER_PREFIX, cls_name)
  metadata_line = "%s%s" % (_METADATA_PREFIX,
                            json.dumps(metadata_dict, sort_keys=True))
  with tf.io.gfile.GFile(filename, "wb") as f:
    for line in [header_line, metadata_line]:
      f.write(tf.compat.as_bytes(line))
      f.write(tf.compat.as_bytes("\n"))
    if lines:
      f.write(tf.compat.as_bytes("\n".join(lines)))
      f.write(tf.compat.as_bytes("\n"))
971243
def format(self, indent_level, indent_size=4):
        

        name = self.format_name('Bytes', indent_size)
        return self.wrap_lines(name, indent_level, indent_size)
342129
def _output_from_file(self, entry='git_describe'):
        
        try:
            vfile = os.path.join(os.path.dirname(self.fpath), '.version')
            with open(vfile, 'r') as f:
                return json.loads(f.read()).get(entry, None)
        except: # File may be missing if using pip + git archive
            return None
293069
def format(self, indent_level, indent_size=4):
        

        desc = self.format_name('String')
        return self.wrap_lines(desc, indent_level, indent_size=indent_size)
628689
def write_versions(dirs, config=None, is_wrapper=False):
    
    out_file = _get_program_file(dirs)
    if is_wrapper:
        assert utils.file_exists(out_file), "Failed to create program versions from VM"
    elif out_file is None:
        for p in _get_versions(config):
            print("{program},{version}".format(**p))
    else:
        with open(out_file, "w") as out_handle:
            for p in _get_versions(config):
                out_handle.write("{program},{version}\n".format(**p))
    return out_file
143115
def write_how_many(self, file):
        
        report = CaseReport(self.case)

        # Map component labels to attribute names
        components = [("Bus", "n_buses"), ("Generator", "n_generators"),
            ("Committed Generator", "n_online_generators"),
            ("Load", "n_loads"), ("Fixed Load", "n_fixed_loads"),
            ("Despatchable Load", "n_online_vloads"), ("Shunt", "n_shunts"),
            ("Branch", "n_branches"), ("Transformer", "n_transformers"),
            ("Inter-tie", "n_interties"), ("Area", "n_areas")
        ]

        # Column 1 width
        longest = max([len(c[0]) for c in components])

        col1_header = "Object"
        col1_width = longest
        col2_header = "Quantity"
        col2_width = len(col2_header)

        # Row separator
        sep = "="*col1_width + " " + "="*col2_width + "\n"

        # Row headers
        file.write(sep)

        file.write(col1_header.center(col1_width))
        file.write(" ")
        file.write("%s\n" % col2_header.center(col2_width))

        file.write(sep)

        # Rows
        for label, attr in components:
            col2_value = str(getattr(report, attr))
            file.write("%s %s\n" %
                (label.ljust(col1_width), col2_value.rjust(col2_width)))
        else:
            file.write(sep)
            file.write("\n")

        del report