Create a NIfTI file filled with ``value``, matching properties of ``in_file``
774175
def nii_ones_like(in_file, value, dtype, newpath=None):
    """"""
    import os
    import numpy as np
    import nibabel as nb

    nii = nb.load(in_file)
    data = np.ones(nii.shape, dtype=float) * value

    out_file = os.path.join(newpath or os.getcwd(), "filled.nii.gz")
    nii = nb.Nifti1Image(data, nii.affine, nii.header)
    nii.set_data_dtype(dtype)
    nii.to_filename(out_file)

    return out_file
1040292
def _append_dict(self, value, _file):
        
        _tabs = '\t' * self._tctr
        _labs = '{tabs}<dict>\n'.format(tabs=_tabs)
        _file.write(_labs)
        self._tctr += 1

        for (_item, _text) in value.items():
            if _text is None:
                continue

            _tabs = '\t' * self._tctr
            _keys = '{tabs}<key>{item}</key>\n'.format(tabs=_tabs, item=_item)
            _file.write(_keys)

            _text = self.object_hook(_text)
            _type = type(_text).__name__
            _MAGIC_TYPES[_type](self, _text, _file)

        self._tctr -= 1
        _tabs = '\t' * self._tctr
        _labs = '{tabs}</dict>\n'.format(tabs=_tabs)
        _file.write(_labs)
513385
function(filename, template, outputInInput) {
    var basename;
    var glob;

    template = Array.isArray(template) ? filename : template;
    glob = isGlob(template);
    if (outputInInput) {
      basename = _toArray(filename.split('.').pop()) ;
    } else if (glob) {
      basename = filename.slice(glob.length, filename.length).split('.');
      basename.pop();
    } else {
      basename = filename.split('/').pop().split('.');
      basename.pop();
    }
    return basename.join('.');
  }
386965
def create_from_user_input(raw_properties, jamfile_module, location):
    """'"""
    assert is_iterable_typed(raw_properties, basestring)
    assert isinstance(jamfile_module, basestring)
    assert isinstance(location, basestring)
    properties = property.create_from_strings(raw_properties, True)
    properties = property.translate_paths(properties, location)
    properties = property.translate_indirect(properties, jamfile_module)

    project_id = get_manager().projects().attributeDefault(jamfile_module, 'id', None)
    if not project_id:
        project_id = os.path.abspath(location)
    properties = property.translate_dependencies(properties, project_id, location)
    properties = property.expand_subfeatures_in_conditions(properties)
    return create(properties)
424640
def buildFileList(input, output=None, ivmlist=None,
                wcskey=None, updatewcs=True, **workinplace):
    
    newfilelist, ivmlist, output, oldasndict, filelist = \
        buildFileListOrig(input=input, output=output, ivmlist=ivmlist,
                    wcskey=wcskey, updatewcs=updatewcs, **workinplace)
    return newfilelist, ivmlist, output, oldasndict
683898
def _combine_files(orig_files, base_out_file, data, fill_paths=True):
    
    orig_files = [x for x in orig_files if x and utils.file_exists(x)]
    if not orig_files:
        return None
    out_file = "%s-combine%s" % (utils.splitext_plus(base_out_file)[0],
                                    utils.splitext_plus(orig_files[0])[-1])
    with open(out_file, "w") as out_handle:
        for orig_file in orig_files:
            with open(orig_file) as in_handle:
                for line in in_handle:
                    if fill_paths and line.startswith("file"):
                        line = _fill_file_path(line, data)
                    out_handle.write(line)
            out_handle.write("\n\n")
    return out_file
1251455
def _append_integer(self, value, _file):
        
        _tabs = '\t' * self._tctr
        _text = value
        _labs = '{tabs}<integer>{text}</integer>\n'.format(tabs=_tabs, text=_text)
        _file.write(_labs)
22583
def _generate_file_set(self, var=None, start_date=None, end_date=None,
                           domain=None, intvl_in=None, dtype_in_vert=None,
                           dtype_in_time=None, intvl_out=None):
        """"""
        try:
            return self.file_map[intvl_in]
        except KeyError:
            raise KeyError('File set does not exist for the specified'
                           ' intvl_in {0}'.format(intvl_in))
291937
def _input_as_multifile(self, data):
        
        if data:
            try:
                filename1, filename2 = data
            except:
                raise ValueError, "Expected two filenames"

            self.Parameters['-in'].off()
            self.Parameters['-in1'].on(filename1)
            self.Parameters['-in2'].on(filename2)
        return ''
793446
def template(colors, input_file, output_file=None):
    """"""
    template_data = util.read_file_raw(input_file)

    try:
        template_data = "".join(template_data).format(**colors)
    except ValueError:
        logging.error("Syntax error in template file '%s'.", input_file)
        return

    util.save_file(template_data, output_file)
199266
function createFileUsingSpec (src, spec, dest) {
  const base = spec.base
  const destForObj = spec.dest ? path.join(dest, spec.dest) : dest
  const resolved = path.relative(base, src)
  const destForFile = path.join(destForObj, resolved)
  const watch = spec.watch === undefined ? true : spec.watch
  return new FileInfo({
    src: src,
    resolved: resolved,
    base: base,
    dest: destForFile,
    destBase: dest,
    watch: watch
  })
}
122139
def default_filter_in(self, value):
        

        if value is not None:
            assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
                "default_filter_in", value)
            assert os.path.exists(value), "'{0}' attribute: '{1}' file doesn't exists!".format(
                "default_filter_in", value)
        self.__default_filter_in = value
7866
def ptconcat(output_file, input_files, overwrite=False):
    """"""
    filt = tb.Filters(
        complevel=5, shuffle=True, fletcher32=True, complib='zlib'
    )
    out_tabs = {}
    dt_file = input_files[0]
    log.info("Reading data struct '%s'..." % dt_file)
    h5struc = tb.open_file(dt_file, 'r')
    log.info("Opening output file '%s'..." % output_file)
    if overwrite:
        outmode = 'w'
    else:
        outmode = 'a'
    h5out = tb.open_file(output_file, outmode)

    for node in h5struc.walk_nodes('/', classname='Table'):
        path = node._v_pathname
        log.debug(path)
        dtype = node.dtype
        p, n = os.path.split(path)
        out_tabs[path] = h5out.create_table(
            p, n, description=dtype, filters=filt, createparents=True
        )
    h5struc.close()
    for fname in input_files:
        log.info('Reading %s...' % fname)
        h5 = tb.open_file(fname)
        for path, out in out_tabs.items():
            tab = h5.get_node(path)
            out.append(tab[:])
        h5.close()
    h5out.close()
1223276
def make_path_properties(file_or_path, prefix=''):
    """"""
    is_std = file_or_path in (sys.stdin, sys.stdout, sys.stderr)

    if is_std:
        path = '-'
    elif is_filelike(file_or_path):
        try:
            path = str(file_or_path.name)
        except AttributeError:
            path = None
    else:
        path = str(file_or_path)

    if is_std or not path:
        abspath = dirname = basename = stem = ext = None
        realpath = realdrive = realdir = realbase = realstem = realext = None
        numbers = num = None
    else:
        abspath = os.path.abspath(path)

        dirname, basename = os.path.split(path)
        stem, ext = os.path.splitext(basename)

        if not dirname:
            dirname = os.curdir

        realpath = os.path.realpath(path)
        realdrive, tail = os.path.splitdrive(realpath)
        realdir, realbase = os.path.split(tail)
        realstem, realext = os.path.splitext(realbase)

        numbers = [int(s) for s in re.findall(r'\d+', basename)]
        num = numbers[-1] if numbers else None

    return {
            prefix + 'path':      path,
            prefix + 'abspath':   abspath,
            prefix + 'dirname':   dirname,
            prefix + 'basename':  basename,
            prefix + 'stem':      stem,
            prefix + 'ext':       ext,
            prefix + 'realpath':  realpath,
            prefix + 'realdrive': realdrive,
            prefix + 'realdir':   realdir,
            prefix + 'realbase':  realbase,
            prefix + 'realstem':  realstem,
            prefix + 'realext':   realext,
            prefix + 'numbers':   numbers,
            prefix + 'num':       num,
        }
1352768
def _create_list(value, allow_filename=False):
    
    if isinstance(value, list):
        return value
    elif isinstance(value, string_type):
        if allow_filename and os.path.isfile(value):
            with codecs.open(value, 'r', encoding="utf-8") as handle:
                return handle.read().splitlines()
        return value.split(',')
    else:
        raise ValueError("Can't create list for input {}".format(value))
522347
def buildIndex(ipFile, ndxFile, append='Y', silent='N', useShortFileName='Y'):
    
    if silent == 'N':
        pass
    if append == 'N':
        try:
            os.remove(ndxFile)
        except Exception as ex:
            print('file already deleted - ignore' + str(ex))
            
    delims = [',', chr(31), '', '$', '&', '"', '%', '/', '\\', '.', ';', ':', '!', '?', '-', '_', ' ', '\n', '*', '\'', '(', ')', '[', ']', '{', '}']
    # 1st pass - index the ontologies, including 2 depths up (later - TODO)
    #buildIndex(ipFile, ndxFile, ' ', 1, 'Y')

    # 2nd pass - use ALL delims to catch each word as part of hyphenated - eg AI Build py
    totWords, totLines, uniqueWords = getWordList(ipFile, delims)
    
    AppendIndexDictionaryToFile(uniqueWords, ndxFile, ipFile, useShortFileName)
    if silent == 'N':
        print(format_op_row(ipFile, totLines, totWords, uniqueWords))
   
        show('uniqueWords', uniqueWords, 5)
    DisplayIndexAsDictionary(uniqueWords)
1031596
def declare_string(self, value):
        # type: (Union[Text, str]) -> Tuple[ProvEntity,Text]
        """"""
        byte_s = BytesIO(str(value).encode(ENCODING))
        data_file = self.research_object.add_data_file(byte_s, content_type=TEXT_PLAIN)
        checksum = posixpath.basename(data_file)
        # FIXME: Don't naively assume add_data_file uses hash in filename!
        data_id = "data:%s" % posixpath.split(data_file)[1]
        entity = self.document.entity(
            data_id, {provM.PROV_TYPE: WFPROV["Artifact"],
                      provM.PROV_VALUE: str(value)})  # type: ProvEntity
        return entity, checksum