Identify the convention used to write this file
493959
def identify_HPX_convention(header):
        
        # Hopefully the file contains the HPX_CONV keyword specifying
        # the convention used
        try:
            return header['HPX_CONV']
        except KeyError:
            pass

        indxschm = header.get('INDXSCHM', None)

        # Try based on the EXTNAME keyword
        extname = header.get('EXTNAME', None)
        if extname == 'HPXEXPOSURES':
            return 'FGST_BEXPCUBE'
        elif extname == 'SKYMAP2':
            if 'COORDTYPE' in header.keys():
                return 'GALPROP'
            else:
                return 'GALPROP2'

        # Check for the INDXSCHM keyword
        if indxschm == 'SPARSE':
            return 'FGST_SRCMAP_SPARSE'

        # Check the name of the first column
        colname = header['TTYPE1']
        if colname == 'PIX':
            colname = header['TTYPE2']

        if colname == 'KEY':
            return 'FGST_SRCMAP_SPARSE'
        elif colname == 'ENERGY1':
            return 'FGST_TEMPLATE'
        elif colname == 'COSBINS':
            return 'FGST_LTCUBE'
        elif colname == 'Bin0':
            return 'GALPROP'
        elif colname in ['CHANNEL1', 'Bin 0']:
            if extname == 'SKYMAP':
                return 'FGST_CCUBE'
            else:
                return 'FGST_SRCMAP'
        else:
            raise ValueError("Could not identify HEALPix convention")
989045
def _write(self, to_write):
        
        self._file.write(to_write.encode(self._encoding or
                                         self._default_encoding))
728649
int writeMethodParametersAttr(MethodSymbol m) {
        MethodType ty = m.externalType(types).asMethodType();
        final int allparams = ty.argtypes.size();
        if (m.params != null && allparams != 0) {
            final int attrIndex = writeAttr(names.MethodParameters);
            databuf.appendByte(allparams);
            // Write extra parameters first
            for (VarSymbol s : m.extraParams) {
                final int flags =
                    ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
                    ((int) m.flags() & SYNTHETIC);
                databuf.appendChar(pool.put(s.name));
                databuf.appendChar(flags);
            }
            // Now write the real parameters
            for (VarSymbol s : m.params) {
                final int flags =
                    ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
                    ((int) m.flags() & SYNTHETIC);
                databuf.appendChar(pool.put(s.name));
                databuf.appendChar(flags);
            }
            // Now write the captured locals
            for (VarSymbol s : m.capturedLocals) {
                final int flags =
                    ((int) s.flags() & (FINAL | SYNTHETIC | MANDATED)) |
                    ((int) m.flags() & SYNTHETIC);
                databuf.appendChar(pool.put(s.name));
                databuf.appendChar(flags);
            }
            endAttr(attrIndex);
            return 1;
        } else
            return 0;
    }
1242017
private void writeInfo(Definition def, Writer out, int indent) throws IOException
   {
      writeWithIndent(out, indent, "/**\n");
      writeWithIndent(out, indent, " * Gets the version of the resource adapter.\n");
      writeWithIndent(out, indent, " *\n");
      writeWithIndent(out, indent, " * @return String representing version of the resource adapter\n");
      writeWithIndent(out, indent, " */\n");

      writeWithIndent(out, indent, "@Override\n");
      writeWithIndent(out, indent, "public String getAdapterVersion()");
      writeLeftCurlyBracket(out, indent);
      writeWithIndent(out, indent + 1, "return null; //TODO");
      writeRightCurlyBracket(out, indent);
      writeEol(out);

      writeWithIndent(out, indent, "/**\n");
      writeWithIndent(out, indent, " * Gets the name of the vendor that has provided the resource adapter.\n");
      writeWithIndent(out, indent, " *\n");
      writeWithIndent(out, indent, " * @return String representing name of the vendor \n");
      writeWithIndent(out, indent, " */\n");

      writeWithIndent(out, indent, "@Override\n");
      writeWithIndent(out, indent, "public String getAdapterVendorName()");
      writeLeftCurlyBracket(out, indent);
      writeWithIndent(out, indent + 1, "return null; //TODO");
      writeRightCurlyBracket(out, indent);
      writeEol(out);

      writeWithIndent(out, indent, "/**\n");
      writeWithIndent(out, indent, " * Gets a tool displayable name of the resource adapter.\n");
      writeWithIndent(out, indent, " *\n");
      writeWithIndent(out, indent, " * @return String representing the name of the resource adapter\n");
      writeWithIndent(out, indent, " */\n");

      writeWithIndent(out, indent, "@Override\n");
      writeWithIndent(out, indent, "public String getAdapterName()");
      writeLeftCurlyBracket(out, indent);
      writeWithIndent(out, indent + 1, "return null; //TODO");
      writeRightCurlyBracket(out, indent);
      writeEol(out);

      writeWithIndent(out, indent, "/**\n");
      writeWithIndent(out, indent, " * Gets a tool displayable short desription of the resource adapter.\n");
      writeWithIndent(out, indent, " *\n");
      writeWithIndent(out, indent, " * @return String describing the resource adapter\n");
      writeWithIndent(out, indent, " */\n");

      writeWithIndent(out, indent, "@Override\n");
      writeWithIndent(out, indent, "public String getAdapterShortDescription()");
      writeLeftCurlyBracket(out, indent);
      writeWithIndent(out, indent + 1, "return null; //TODO");
      writeRightCurlyBracket(out, indent);
      writeEol(out);

      writeWithIndent(out, indent, "/**\n");
      writeWithIndent(out, indent, " * Returns a string representation of the version\n");
      writeWithIndent(out, indent, " *\n");
      writeWithIndent(out, indent,
            " * @return String representing the supported version of the connector architecture\n");
      writeWithIndent(out, indent, " */\n");

      writeWithIndent(out, indent, "@Override\n");
      writeWithIndent(out, indent, "public String getSpecVersion()");
      writeLeftCurlyBracket(out, indent);
      writeWithIndent(out, indent + 1, "return null; //TODO");
      writeRightCurlyBracket(out, indent);
      writeEol(out);
   }
44367
def _writeRec(self, fh, rec):
        
        fh.write(str(rec) + "\n")
        for child in sorted(rec.children, key=self._recSortKey):
            self._writeRec(fh, child)
30537
def write(self, path, data, offset, fh):  # pragma: no cover
        
        # print("write {}".format(path))
        with self.attr_lock:
            base = self.attr[path][BASE_KEY]
            staged = self.attr[path][STAGED_KEY]
            if not staged.closed:
                base.st_size += len(data)
                staged.write(data)
        return len(data)
249920
def write_file(self, fileobject, skip_unknown=False):
        """"""
        self.set_metadata_version()

        for field in _version2fieldlist(self['Metadata-Version']):
            values = self.get(field)
            if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']):
                continue
            if field in _ELEMENTSFIELD:
                self._write_field(fileobject, field, ','.join(values))
                continue
            if field not in _LISTFIELDS:
                if field == 'Description':
                    if self.metadata_version in ('1.0', '1.1'):
                        values = values.replace('\n', '\n        ')
                    else:
                        values = values.replace('\n', '\n       |')
                values = [values]

            if field in _LISTTUPLEFIELDS:
                values = [','.join(value) for value in values]

            for value in values:
                self._write_field(fileobject, field, value)
311195
def write_sig(self):
        ''''''
        if not self._md5:
            self._md5 = fileMD5(self)
        with open(self.sig_file(), 'w') as sig:
            sig.write(
                f'{os.path.getmtime(self)}\t{os.path.getsize(self)}\t{self._md5}'
            )
1119150
def write_to(self, f):
        
        f.write(self.version + "\r\n")
        for name, value in self.items():
            name = name.title()
            # Use standard forms for commonly used patterns
            name = name.replace("Warc-", "WARC-").replace("-Ip-", "-IP-").replace("-Id", "-ID").replace("-Uri", "-URI")
            f.write(name)
            f.write(": ")
            f.write(value)
            f.write("\r\n")
        
        # Header ends with an extra CRLF
        f.write("\r\n")
93250
def write(self):
        
        if not os.path.isdir(self._dirs['source_dir']):
            os.mkdir(self._dirs['source_dir'])

        fout = codecs.open(self._dirs['source_filename'], 'w', encoding="utf-8", errors="xmlcharrefreplace")
        fout.write(self._config_to_text())
        if self._content:
            fout.write('\n')
            fout.write(self._content)
            fout.write('\n')
        fout.close()
735610
function(file) {
        var self = this;

        var ext;

        if (!self._options.keepExtension) {
            ext = self._options.extension || path.extname(file);
        }

        var fileName = path.basename(file, ext);

        if (self._options.format) {
            var formatRegex = self._options.format[0].split('/');
            formatRegex = new RegExp(formatRegex[1], formatRegex[2]);

            var replaceValue = self._options.format[1];

            fileName = fileName.replace(formatRegex, replaceValue);
        }

        var moduleConfig = {
            name: '',
            version: '1.0.0'
        };

        if (self._options.moduleConfig) {
            if (typeof self._options.moduleConfig === 'string') {
                var fileModuleConfig = path.resolve(self._options.moduleConfig);

                if (fs.existsSync(fileModuleConfig)) {
                    moduleConfig = require(fileModuleConfig);
                }
            } else {
                moduleConfig = self._options.moduleConfig;
            }
        }

        fileName = path.join(path.dirname(file), fileName);

        var moduleName = '';

        if (moduleConfig.name) {
            moduleName = moduleConfig.name + '@' + moduleConfig.version;
        }

        moduleName = path.join(moduleName, fileName.substring(self._options.moduleRoot.length));

        if (self._options.lowerCase) {
            moduleName = moduleName.toLowerCase();
        }

        return upath.toUnix(moduleName);
    }
1043987
private static int createWriteDFSPaths()
  {

  	if (createDFSPaths() != 0) {
  		return -1;
  	}
  	
	  try {
		  // write to all the files!
	  	for (Map.Entry<String, OutputStream> file : files_.entrySet()) {
	  		OutputStream os = file.getValue();

	  		long startTime = System.nanoTime();
	  		os.write(data_.getBytes());
        timingWrite_.add(new Double((System.nanoTime() - startTime)/(1E9)));
	  		os.close();
	  	}
	  	
	  } catch (IOException e) {
	  	e.printStackTrace();
	  	return -1;
	  }
  	  	
  	return 0;
  }
270242
def write(file, system):
    

    # TODO: Check for bugs!!!

    out = list()
    out.append('# DOME format version 1.0')
    ppl = 7  # parameter per line
    retval = True
    dev_list = sorted(system.devman.devices)
    for dev in dev_list:
        model = system.__dict__[dev]
        if not model.n:
            continue

        out.append('')
        header = dev + ', '
        space = ' ' * (len(dev) + 2)
        keys = list(model._data.keys())
        keys.extend(['name', 'idx'])
        keys = sorted(keys)

        # remove non-existent keys
        for key in keys:
            if key not in model.__dict__.keys():
                keys.pop(key)

        nline = int(ceil(len(keys) / ppl))
        nelement = model.n
        vals = [''] * len(keys)

        # for each element, read values
        for elem in range(nelement):
            for idx, key in enumerate(keys):
                if model._flags['sysbase'] and key in model._store.keys():
                    val = model._store[key][elem]
                else:
                    val = model.__dict__[key][elem]

                if isinstance(val, float):
                    val = round(val, 5)
                elif isinstance(val, str):
                    val = '"{}"'.format(val)
                elif isinstance(val, list):
                    val = list(val)
                    val = '; '.join(str(i) for i in val)
                    val = '[{}]'.format(val)
                elif val is None:
                    val = 0
                vals[idx] = val

            pair = []
            for key, val in zip(keys, vals):
                pair.append('{} = {}'.format(key, val))

            for line in range(nline):
                string = ', '.join(pair[ppl * line:ppl * (line + 1)])
                if line == 0:  # append header or space
                    string = header + string
                else:
                    string = space + string
                if not line == nline - 1:  # add comma except for last line
                    string += ','

                out.append(string)

    fid = open(file, 'w')
    for line in out:
        fid.write(line + '\n')

    fid.close()
    return retval
468100
def write_file(fname, info):
    """"""
    with open(fname, 'w') as outfile:
        # File header
        outfile.write('# Copyright (c) 2018 MetPy Developers.\n')
        outfile.write('# Distributed under the terms of the BSD 3-Clause License.\n')
        outfile.write('# SPDX-License-Identifier: BSD-3-Clause\n\n')
        outfile.write('# flake8: noqa\n')
        outfile.write('# Generated file -- do not modify\n')

        # Variable descriptions
        outfile.write('descriptions = {')
        outdata = ',\n                '.join('"{name}": "{desc}"'.format(
            **i) for i in info if need_desc(i))
        outfile.write(outdata)
        outfile.write('}\n\n')

        # Now the struct format
        outfile.write('fields = [')
        outdata = ',\n          '.join('({fname}, "{fmt}")'.format(
            fname=field_name(i), **i) for i in info)
        outfile.write(outdata)
        outfile.write(']\n')
454820
def _write_executable_py(self, execname, lines):
        
        executable = self.module.executables[execname]
            
        #The 5 in the formatting indent comes from 1 space, 3 from the 'def'
        #and 1 from '('.
        inparams = []
        for p in executable.ordered_parameters:
            if "in" in p.direction:
                inparams.append(p.lname)
        pyparams = present_params(inparams, len(execname) + 5, linecont=", ")
        lines.append("def {}({}):".format(execname.lower(), pyparams))
        tab = "    "

        #Next, we want to append the docstring information from the XML tags
        #that were parsed by fortpy.
        docs = ['"""']
        summary = self._format_docstring(executable.summary)
        if len(summary) > 0:
            docs[0] += summary[0]
            docs.extend(summary[1::])
            docs.append("")
        else:
            docs[0] += "No XML documentation summary."
        for p in executable.ordered_parameters:
            doc = ":arg {}: {}; {}".format(p.name, p.strtype, p.summary)
            docs.extend(self._format_docstring(doc))

        lines.extend([tab + l for l in docs])
        lines.append(tab + '"""')

        pathstr = '{}libpath = path.join(path.dirname(__file__), "{}")'
        lines.append(pathstr.format(tab, self.libname))
        methparams = '"{}_c", "{}_c", libpath, True'.format(self.module.name, execname)
        lines.append("{}method = static_symbol({})".format(tab, methparams))
        argtypes = _py_ex_argtype(executable)
        spacing = len(tab) + 6 + 8 + 3
        lines.append("{}method.argtypes = [{}]".format(tab, present_params(argtypes, spacing,
                                                                           linecont=", ")))
        lines.append("")
        lparams = []
        _py_code_variables(lines, executable, lparams, tab)
        #This is the line that calls the shared library executable.
        methparams = present_params(lparams, len(tab) + 5, linecont=", ")
        lines.append("{}method({})\n".format(tab, methparams))

        #Now we clean up the output variables to turn them into numpy arrays etc.
        constructor = '{}result = FtypesResult("{}", "{}", "{}")'
        lines.append(constructor.format(tab, self.module.name, execname, type(executable).__name__))
        count = _py_code_clean(lines, tab, executable)
        
        if count > 0:
            lines.append("")
            lines.append("{}return result\n".format(tab))
        else:
            lines.append("{}return None\n".format(tab))
998358
def calling_convention(self):
        """"""
        if self._calling_convention is None:
            self._calling_convention = \
                calldef_types.CALLING_CONVENTION_TYPES.extract(self.attributes)
            if not self._calling_convention:
                self._calling_convention = self.guess_calling_convention()
        return self._calling_convention
810502
def _write_executable_f90(self, execname, lines):
        
        executable = self.module.executables[execname]
            
        #The 14 in the formatting indent comes from 4 spaces, 2 from "_c", 1 from the spacing
        #between 'subroutine' and name of the executable, 10 from subroutine, 1 from the ("
        cparams = present_params(_ctypes_ex_parameters(executable), len(execname) + 14)
        lines.append("  subroutine {}_c({}) BIND(C)".format(execname, cparams))
        #Next, we add the variables declarations, the call to the original executable and then
        #the handling of the output variables.
        lines.append("    " + "\n    ".join(_ctypes_ex_variables(executable)))
        lines.append("    " + "\n    ".join(_ctypes_ex_compatvars(executable)))

        #Add assignment/allocate statements for the intent(in*) paramaters *local* variable
        #declarations so that we can match the signature exactly.
        lines.extend(_ctypes_ex_assign(executable))
                
        if type(executable).__name__  == "Subroutine":
            prefix = "call "
        else:
            prefix = "{}_f = ".format(execname)
            
        spacing = len(list(prefix)) + len(list(execname)) + 4
        lines.append("    {}{}({})".format(prefix, execname,
                                           present_params(executable.paramorder, spacing, 90)))
        lines.append("")
        lines.extend(_ctypes_ex_clean(executable))

        lines.append("  end subroutine {}_c\n".format(execname))