Reads the HAIR.pgn file and creates
    the hair layer.
198713
def create_hair_layer(aspect, ip):
    ''''''
    layer = []
    if 'HAIR' in aspect:
        layer = pgnreader.parse_pagan_file(FILE_HAIR, ip, invert=False, sym=True)
    return layer
1006209
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
        
        # Set file extension property
        self.fileExtension = extension

        # Open file and parse into a data structure
        with open(path, 'r') as f:
            for line in f:
                sline = line.strip().split()
                if len(sline) == 1:
                    self.numParameters = sline[0]
                else:
                    # Create GSSHAPY TargetParameter object
                    target = TargetParameter(targetVariable=sline[0],
                                             varFormat=sline[1])

                    # Associate TargetParameter with ReplaceParamFile
                    target.replaceParamFile = self
221254
def _generate_neuron_files_from_neuroml(network, verbose=False, dir_for_mod_files = None):
    

    print_v("-------------   Generating NEURON files from NeuroML for %s (default dir: %s)..." % (network.id, dir_for_mod_files))
    nml_src_files = []

    from neuroml import NeuroMLDocument
    import neuroml.writers as writers
    temp_nml_doc = NeuroMLDocument(id="temp")
    
    dirs_for_mod_files = []
    if dir_for_mod_files!=None:
        dirs_for_mod_files.append(os.path.abspath(dir_for_mod_files))

    for c in network.cells:
        if c.neuroml2_source_file:
            nml_src_files.append(c.neuroml2_source_file)
            dir_for_mod = os.path.dirname(os.path.abspath(c.neuroml2_source_file))
            if not dir_for_mod in dirs_for_mod_files: dirs_for_mod_files.append(dir_for_mod)
                
    for s in network.synapses:
        if s.neuroml2_source_file:
            nml_src_files.append(s.neuroml2_source_file)
            dir_for_mod = os.path.dirname(os.path.abspath(s.neuroml2_source_file))
            if not dir_for_mod in dirs_for_mod_files: dirs_for_mod_files.append(dir_for_mod)

    for i in network.input_sources:
        if i.neuroml2_source_file:
            nml_src_files.append(i.neuroml2_source_file)
            dir_for_mod = os.path.dirname(os.path.abspath(i.neuroml2_source_file))
            if not dir_for_mod in dirs_for_mod_files: dirs_for_mod_files.append(dir_for_mod)
                
    temp_nml_doc = _extract_pynn_components_to_neuroml(network)
      
    summary = temp_nml_doc.summary()
    
    if 'IF_' in summary: 
        import tempfile
        temp_nml_file = tempfile.NamedTemporaryFile(delete=False, suffix='.nml', dir=dir_for_mod_files)
        print_v("Writing temporary NML file to: %s, summary: "%temp_nml_file.name)
        print_v(summary)

        writers.NeuroMLWriter.write(temp_nml_doc, temp_nml_file.name)
        nml_src_files.append(temp_nml_file.name)

    for f in nml_src_files:
        from pyneuroml import pynml
        print_v("Generating/compiling hoc/mod files for: %s"%f)
        pynml.run_lems_with_jneuroml_neuron(f, 
                                            nogui=True, 
                                            only_generate_scripts=True,
                                            compile_mods=True,
                                            verbose=False)

    for dir_for_mod_files in dirs_for_mod_files:
        if not dir_for_mod_files in locations_mods_loaded_from:
            print_v("Generated NEURON code; loading mechanisms from %s (cwd: %s; already loaded: %s)" % (dir_for_mod_files,os.getcwd(),locations_mods_loaded_from))
            try:

                from neuron import load_mechanisms
                if os.getcwd()==dir_for_mod_files:
                    print_v("That's current dir => importing neuron module loads mods here...")
                else:
                    load_mechanisms(dir_for_mod_files)
                locations_mods_loaded_from.append(dir_for_mod_files)
            except:
                print_v("Failed to load mod file mechanisms...")
        else:
            print_v("Already loaded mechanisms from %s (all loaded: %s)" % (dir_for_mod_files,locations_mods_loaded_from))
445132
def read_skel(self, fid):
        """"""
        lin = self.read_line(fid)
        while lin:
            if lin[0]==':':
                if lin[1:]== 'name':
                    lin = self.read_line(fid)
                    self.name = lin
                elif lin[1:]=='units':
                    lin = self.read_units(fid)
                elif lin[1:]=='documentation':
                    lin = self.read_documentation(fid)
                elif lin[1:]=='root':
                    lin = self.read_root(fid)
                elif lin[1:]=='bonedata':
                    lin = self.read_bonedata(fid)
                elif lin[1:]=='hierarchy':
                    lin = self.read_hierarchy(fid)
                elif lin[1:8]=='version':
                    lin = self.read_line(fid)
                    continue
                else: 
                    if not lin:
                        self.finalize()
                        return
                    lin = self.read_line(fid)
            else:
                raise ValueError('Unrecognised file format')
            self.finalize()
531866
def src(globs, **options):
	""""""

	# Create an array of globs if only one string is given
	if isinstance(globs, str):
		globs = [ globs ]

	# Find files
	files = find_files(globs)

	# Create a stream
	stream = Stream()

	# Options
	options["cwd"] = config.cwd

	if "base" in options:
		options["base"] = os.path.abspath(options["base"])

	# Create a File object for each file to include
	for infile in files:
		file = File(infile[2], **options)
		file.relpath = file.path
		file.order = infile[0]
		file.base = options.get("base", infile[1])
		stream.append_file(file)

	# No more files to add
	stream.end_of_stream()

	# Pipe a file reader and return the stream
	if options.get("read", True):
		return stream.pipe(FileReader())
	return stream
521059
def _initialize(self):
        
        meta = getattr(self, ModelBase._meta_attr)
        # read modelfile, convert JSON and load/update model
        if self.param_file is not None:
            self._load()
        LOGGER.debug('model:\n%r', self.model)
        # initialize layers
        # FIXME: move import inside loop for custom layers in different modules
        mod = importlib.import_module(meta.layers_mod, meta.layers_pkg)
        src_model = {}
        for layer, value in self.model.iteritems():
            # from layers module get the layer's class definition
            layer_cls = getattr(mod, meta.layer_cls_names[layer])  # class def
            self.layers[layer] = layer_cls  # add layer class def to model
            # check if model layers are classes
            src_value = {}  # layer value generated from source classes
            for src in value['sources']:
                # check if source has keyword arguments
                try:
                    src, kwargs = src
                except (TypeError, ValueError):
                    kwargs = {}  # no key work arguments
                # skip if not a source class
                if isinstance(src, basestring):
                    continue
                # generate layer value from source class
                src_value[src.__name__] = {'module': src.__module__,
                                           'package': None}
                # update layer keyword arguments
                src_value[src.__name__].update(kwargs)
            # use layer values generated from source class
            if src_value:
                value = src_model[layer] = src_value
            else:
                srcmod, srcpkg = value.get('module'), value.get('package')
                try:
                    value = dict(value['sources'])
                except ValueError:
                    value = dict.fromkeys(value['sources'], {})
                for src in value.viewkeys():
                    if srcmod is not None:
                        value[src]['module'] = srcmod
                    if srcpkg is not None:
                        value[src]['package'] = srcpkg
            # set layer attribute with model data
            setattr(self, layer, layer_cls(value))
        # update model with layer values generated from source classes
        if src_model:
            self.model.update(src_model)
        self._update()
        self._state = 'initialized'
476123
function readData(datapath, layer, callback) {
  var features = [];

  var options = {
    delimiter: ',',
    columns: true
  };

  fs.createReadStream(path.join(datapath, 'meta', `wof-${layer}-latest.csv`))
    .pipe(parse(options))
    .pipe(loadJSON.create(datapath))
    .pipe(isActiveRecord.create())
    .pipe(filterOutNamelessRecords.create())
    .pipe(filterOutUnimportantRecords.create())
    .pipe(extractFields.create())
    .pipe(simplifyGeometry.create())
    .pipe(sink.obj(function(feature) {
      features.push(feature);
    }))
    .on('finish', function() {
      callback(features);
    });

}
509187
function layersPBFReader(tag, layers, pbf) {
  if (tag === 3) {
    const layer = {
      keys: [],
      values: [],
      features: []
    };
    const end = pbf.readVarint() + pbf.pos;
    pbf.readFields(layerPBFReader, layer, end);
    layer.length = layer.features.length;
    if (layer.length) {
      layers[layer.name] = layer;
    }
  }
}
1337822
function createLayers(sources) {
  const len = sources.length;
  const layers = new Array(len);
  for (let i = 0; i < len; ++i) {
    layers[i] = createLayer(sources[i]);
  }
  return layers;
}
677963
function layerPBFReader(tag, layer, pbf) {
  if (tag === 15) {
    layer.version = pbf.readVarint();
  } else if (tag === 1) {
    layer.name = pbf.readString();
  } else if (tag === 5) {
    layer.extent = pbf.readVarint();
  } else if (tag === 2) {
    layer.features.push(pbf.pos);
  } else if (tag === 3) {
    layer.keys.push(pbf.readString());
  } else if (tag === 4) {
    let value = null;
    const end = pbf.readVarint() + pbf.pos;
    while (pbf.pos < end) {
      tag = pbf.readVarint() >> 3;
      value = tag === 1 ? pbf.readString() :
        tag === 2 ? pbf.readFloat() :
          tag === 3 ? pbf.readDouble() :
            tag === 4 ? pbf.readVarint64() :
              tag === 5 ? pbf.readVarint() :
                tag === 6 ? pbf.readSVarint() :
                  tag === 7 ? pbf.readBoolean() : null;
    }
    layer.values.push(value);
  }
}
1285505
function processFile(autogenContext, commentInfo, callback) {
    fs.readFile(path.resolve(__dirname, "..", autogenContext.filePath), function (readError, sourceFileContentsBuffer) {
        if (readError) {
            callback(autogenContext.filePath, readError);
            return;
        }

        processNextAutogenBlock(autogenContext, sourceFileContentsBuffer.toString(), commentInfo, 0, function (result, autogenError) {
            //Write results if the content was changed (don't need to re-write the same content)
            if (sourceFileContentsBuffer.toString() != result)
                fs.writeFile(path.resolve(__dirname, "..", autogenContext.filePath), result, {}, function (writeError) {
                    callback(autogenContext.filePath, writeError);
                });
            else
                callback(autogenContext.filePath, autogenError);
        });
    });
}
856248
function createGLResources(gl, glConfig) {
  const resources = {
    gl,
    buffers: {},
    textures: {},
    framebuffers: {},
    programs: {},
  };
  const buffers = glConfig.resources.buffers || [];
  const textures = glConfig.resources.textures || [];
  const framebuffers = glConfig.resources.framebuffers || [];

  // Create Buffer
  buffers.forEach((buffer) => {
    const glBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, buffer.data, gl.STATIC_DRAW);
    resources.buffers[buffer.id] = glBuffer;
  });

  // Create Texture
  textures.forEach((texture) => {
    const glTexture = gl.createTexture();
    const pixelStore = texture.pixelStore || [];
    const texParameter = texture.texParameter || [];

    gl.bindTexture(gl.TEXTURE_2D, glTexture);

    pixelStore.forEach((option) => {
      gl.pixelStorei(gl[option[0]], option[1]);
    });

    texParameter.forEach((option) => {
      gl.texParameteri(gl.TEXTURE_2D, gl[option[0]], gl[option[1]]);
    });

    resources.textures[texture.id] = glTexture;
  });

  // Create Framebuffer
  framebuffers.forEach((framebuffer) => {
    const glFramebuffer = gl.createFramebuffer();
    glFramebuffer.width = framebuffer.width;
    glFramebuffer.height = framebuffer.height;

    resources.framebuffers[framebuffer.id] = glFramebuffer;
  });

  // Create programs
  Object.keys(glConfig.programs).forEach((programName) => {
    buildShaderProgram(gl, programName, glConfig, resources);
  });

  // Add destroy function
  resources.destroy = () => {
    freeGLResources(resources);
  };

  return resources;
}
934396
def _fromfile(self):
        """"""
        self._fd.seek(0)
        try:
            self.byte_order = {b'II': '<', b'MM': '>'}[self._fd.read(2)]
        except KeyError:
            raise ValueError("not a valid TIFF file")
        version = struct.unpack(self.byte_order+'H', self._fd.read(2))[0]
        if version == 43:  # BigTiff
            self.offset_size, zero = struct.unpack(self.byte_order+'HH',
                                                   self._fd.read(4))
            if zero or self.offset_size != 8:
                raise ValueError("not a valid BigTIFF file")
        elif version == 42:
            self.offset_size = 4
        else:
            raise ValueError("not a TIFF file")
        self.pages = []
        while True:
            try:
                page = TIFFpage(self)
                self.pages.append(page)
            except StopIteration:
                break
        if not self.pages:
            raise ValueError("empty TIFF file")
487171
def readTraining(self, training_file):
        '''
        
        '''

        logger.info('reading training from file')
        training_pairs = json.load(training_file,
                                   cls=serializer.dedupe_decoder)
        self.markPairs(training_pairs)
1218080
def create(
    name,

    create_file,
    open_file,
    remove_file,

    create_directory,
    list_directory,
    remove_empty_directory,
    temporary_directory,

    stat,

    lstat,
    link,
    readlink,

    realpath=_realpath,
    remove=_recursive_remove,
):
    

    methods = dict(
        create=create_file,
        open=lambda fs, path, mode="r": open_file(
            fs=fs, path=path, mode=mode,
        ),
        remove_file=remove_file,

        create_directory=create_directory,
        list_directory=list_directory,
        remove_empty_directory=remove_empty_directory,
        temporary_directory=temporary_directory,

        get_contents=_get_contents,
        set_contents=_set_contents,
        create_with_contents=_create_with_contents,

        remove=remove,
        removing=_removing,

        stat=stat,

        lstat=lstat,
        link=link,
        readlink=readlink,
        realpath=realpath,

        exists=_exists,
        is_dir=_is_dir,
        is_file=_is_file,
        is_link=_is_link,

        touch=_touch,

        children=_children,
        glob_children=_glob_children,
    )
    return attr.s(hash=True)(type(name, (object,), methods))
953377
def _read(self, filename):
        """"""
        data = {}
        parsers = [
            FirstDataParser(), CoordinateParser(), EnergyGradParser(),
            SkipApproxHessian(), HessianParser(), MassParser(),
        ]
        with open(filename) as f:
            while True:
                line = f.readline()
                if line == "":
                    break
                # at each line, a parsers checks if it has to process a piece of
                # file. If that happens, the parser gets control over the file
                # and reads as many lines as it needs to collect data for some
                # attributes.
                for parser in parsers:
                    if parser.test(line, data):
                        parser.read(line, f, data)
                        break
        self.__dict__.update(data)
1182682
def read_tgf(filename):
    """"""
    g = Graph()
    with open(filename) as file:
        states = {}

        # Nodes
        for line in file:
            line = line.strip()
            if line == "": 
                continue
            elif line == "#":
                break
            i, q = line.split(None, 1)
            q, attrs = syntax.string_to_state(q)
            states[i] = q
            g.add_node(q, attrs)

        # Edges
        for line in file:
            line = line.strip()
            if line == "": 
                continue
            i, j, t = line.split(None, 2)
            q, r = states[i], states[j]
            t = syntax.string_to_transition(t)
            g.add_edge(q, r, {'label':t})

    return from_graph(g)