Private function to parse world. Return infomation about particles
    (name, coordinates and particle size) for each species.
168225
def __parse_world(
        world, radius=None, species_list=None, max_count=None,
        predicator=None):
    
    from ecell4_base.core import Species

    if species_list is None:
        species_list = [
            p.species().serial() for pid, p in world.list_particles()]
        species_list = sorted(
            set(species_list), key=species_list.index)  # XXX: pick unique ones

    species = []
    for name in species_list:
        particles = [
            {'pos': p.position(), 'r': p.radius()}
            for pid, p in world.list_particles(Species(name))
            if predicator is None or predicator(pid, p)]
        # particles = [
        #     {'pos': p.position(), 'r': p.radius()}
        #     for pid, p in world.list_particles()
        #     if (p.species().serial() == name and
        #         (predicator is None or predicator(pid, p)))]

        if len(particles) == 0:
            continue

        if max_count is not None and len(particles) > max_count:
            particles = random.sample(particles, max_count)

        data = {
            'x': [p['pos'][0] for p in particles],
            'y': [p['pos'][1] for p in particles],
            'z': [p['pos'][2] for p in particles]
        }

        # assume that all particles belong to one species have the same radius
        r = max([p['r'] for p in particles]) if radius is None else radius
        r = r if r > 0 else min(world.edge_lengths()) * 0.005
        size = 30.0 / max(world.edge_lengths()) * r

        species.append({
            'name': name,
            'data': data,
            'size': size
        })

    return species
210669
def parse(self):
        """"""
        result = nodes.Template(self.subparse(), lineno=1)
        result.set_environment(self.environment)
        return result
399730
def _parse_coords(self,opts):
        
        # The coordinates are mutually exclusive, so
        # shouldn't have to worry about over-writing them.
        if 'coords' in vars(opts): return
        radius = vars(opts).get('radius',0)
        gal = None
        if vars(opts).get('gal') is not None: 
            gal = opts.gal
        elif vars(opts).get('cel') is not None: 
            gal = cel2gal(*opts.cel)
        elif vars(opts).get('hpx') is not None: 
            gal = pix2ang(*opts.hpx)

        if gal is not None:
            opts.coords = [(gal[0],gal[1],radius)]
            opts.names = [vars(opts).get('name','')]
        else:
            opts.coords = None
            opts.names = None

        if vars(opts).get('targets') is not None:
            opts.names,opts.coords = self.parse_targets(opts.targets)
            if vars(opts).get('radius') is not None:
                opts.coords['radius'] = vars(opts).get('radius')
799410
def get_explanation(logical_form: str,
                    world_extractions: JsonDict,
                    answer_index: int,
                    world: QuarelWorld) -> List[JsonDict]:
    
    output = []
    nl_world = {}
    if world_extractions['world1'] != "N/A" and world_extractions['world1'] != ["N/A"]:
        nl_world['world1'] = nl_world_string(world_extractions['world1'])
        nl_world['world2'] = nl_world_string(world_extractions['world2'])
        output.append({
                "header": "Identified two worlds",
                "content": [f'''world1 = {nl_world['world1']}''',
                            f'''world2 = {nl_world['world2']}''']
        })
    else:
        nl_world['world1'] = 'world1'
        nl_world['world2'] = 'world2'
    parse = semparse_util.lisp_to_nested_expression(logical_form)
    if parse[0] != "infer":
        return None
    setup = parse[1]
    output.append({
            "header": "The question is stating",
            "content": nl_arg(setup, nl_world)
    })
    answers = parse[2:]
    output.append({
            "header": "The answer options are stating",
            "content": ["A: " + " and ".join(nl_arg(answers[0], nl_world)),
                        "B: " + " and ".join(nl_arg(answers[1], nl_world))]
    })
    setup_core = setup
    if setup[0] == 'and':
        setup_core = setup[1]
    s_attr = setup_core[0]
    s_dir = world.qr_size[setup_core[1]]
    s_world = nl_world[setup_core[2]]
    a_attr = answers[answer_index][0]
    qr_dir = world._get_qr_coeff(strip_entity_type(s_attr), strip_entity_type(a_attr))  # pylint: disable=protected-access
    a_dir = s_dir * qr_dir
    a_world = nl_world[answers[answer_index][2]]

    content = [f'When {nl_attr(s_attr)} is {nl_dir(s_dir)} ' +
               f'then {nl_attr(a_attr)} is {nl_dir(a_dir)} (for {s_world})']
    if a_world != s_world:
        content.append(f'''Therefore {nl_attr(a_attr)} is {nl_dir(-a_dir)} for {a_world}''')
    content.append(f"Therefore {chr(65+answer_index)} is the correct answer")

    output.append({
            "header": "Theory used",
            "content": content
    })

    return output
104453
def _parse_absorption(line, lines):
    """"""

    split_line = line.split()

    energy = float(split_line[0])
    re_sigma_xx = float(split_line[1])
    re_sigma_zz = float(split_line[2])
    absorp_xx = float(split_line[3])
    absorp_zz = float(split_line[4])

    return {"energy": energy, "re_sigma_xx": re_sigma_xx, "re_sigma_zz": re_sigma_zz,
            "absorp_xx": absorp_xx, "absorp_zz": absorp_zz}
1176308
def list_species(model, seeds=None):
    """"""
    seeds = None or []

    from ecell4_base.core import Species

    if not isinstance(seeds, list):
        seeds = list(seeds)

    expanded = model.expand([Species(serial) for serial in seeds])
    species_list = [sp.serial() for sp in expanded.list_species()]
    species_list = sorted(set(seeds + species_list))
    return species_list
260075
def xyz(self):
        
        if not self.children:
            pos = np.expand_dims(self._pos, axis=0)
        else:
            arr = np.fromiter(itertools.chain.from_iterable(
                particle.pos for particle in self.particles()), dtype=float)
            pos = arr.reshape((-1, 3))
        return pos
1109913
def _parse_params(self, params=None):
        
        prm = self.default_params.copy()
        if params is not None: 
            prm.update(params)
 
        if prm["background_model"]:
            # Absolute path, just to be sure
            prm["background_model"] = os.path.abspath(prm["background_model"])
        else:
            if prm.get("organism", None):
                prm["background_model"] = os.path.join(
                        self.config.get_bg_dir(), 
                        "{}.{}.bg".format(
                            prm["organism"], 
                            "MotifSampler"))
            else:            
                raise Exception("No background specified for {}".format(self.name))
        
        prm["strand"] = 1
        if prm["single"]:
            prm["strand"] = 0
        
        tmp = NamedTemporaryFile(dir=self.tmpdir)
        prm["pwmfile"] = tmp.name

        tmp2  = NamedTemporaryFile(dir=self.tmpdir)
        prm["outfile"] = tmp2.name
 
        return prm
880309
function computeSpecifierMap(specifiers) {
  const specifierCount = specifiers.length;
  const specifierMap = Object.create(null);

  for (let i = 0; i < specifierCount; ++i) {
    const s = specifiers[i];

    const local =
      s.type === "ExportDefaultSpecifier" ? "default" :
      s.type === "ExportNamespaceSpecifier" ? "*" :
      s.local.name;

    const __ported = // The IMported or EXported name.
      s.type === "ImportSpecifier" ? s.imported.name :
      s.type === "ImportDefaultSpecifier" ? "default" :
      s.type === "ImportNamespaceSpecifier" ? "*" :
      (s.type === "ExportSpecifier" ||
       s.type === "ExportDefaultSpecifier" ||
       s.type === "ExportNamespaceSpecifier") ? s.exported.name :
      null;

    if (typeof local === "string" && typeof __ported === "string") {
      addToSpecifierMap(specifierMap, __ported, local);
    }
  }

  return specifierMap;
}
517458
def num_species(self):
        
        all_headers = reduce(lambda x, y: set(x) | set(y),
                             (rec.get_names() for rec in self.records))
        return len(all_headers)
252397
def info(self):
        
        result = dict()
        for name, namespace in self._namespaces.items():
            result[name] = namespace.info_all()
        return result
225535
function parseTopLevelNodes() {
      var acorn = require('acorn');
      var output = acorn.parse(source, {
        locations: true,
        sourceFile: filePath,
        onComment: onComment
      });

      namespaceBoundary();

      output.body.forEach(function(node) {
        processTopLevelNode(node);
      });
    }
1130575
def get_structure_from_dict(d):
    

    species = []
    frac_coords = []
    masses = []
    if 'points' in d:
        for p in d['points']:
            species.append(p['symbol'])
            frac_coords.append(p['coordinates'])
            masses.append(p['mass'])
    elif 'atoms' in d:
        for p in d['atoms']:
            species.append(p['symbol'])
            frac_coords.append(p['position'])
            masses.append(p['mass'])
    else:
        raise ValueError('The dict does not contain structural information')

    return Structure(d['lattice'], species, frac_coords,
                     site_properties={"phonopy_masses": masses})
9951
function() {
        var name_parts = [],
            proto_ref  = this.reflector.getProto()[this.name],
            name       = '',
            body       = '';

        if (this.meta.is_abstract) { name_parts.push('abstract'); }
        if (this.meta.is_final) { name_parts.push('final'); }

        name_parts.push(this.meta.visibility);
        
        if (this.meta.is_static) { name_parts.push('static'); }

        if (this.meta.is_nullable) { name_parts.push('nullable'); }
        if (this.meta.is_read_only) { name_parts.push('read'); }

        // If type === null, attempt to detect it by the predefined value.
        if (this.meta.type === null) {
            if (proto_ref === null) {
                name_parts.push('mixed');
            } else {
                name_parts.push(typeof (proto_ref));
            }
        } else {
            name_parts.push(this.meta.type);
        }

        name_parts.push('"' + this.meta.name + '"');
        name = name_parts.join(' ');

        if (typeof (proto_ref) === 'function') {
            body = '[Function]';
        } else if (typeof (proto_ref) === 'object' && proto_ref !== null) {
            body = '[Object (' + proto_ref.length + ')]';
        } else if (typeof (proto_ref) === 'string') {
            body = '"' + proto_ref + '"';
        } else {
            body = proto_ref;
        }
        return name + ': ' + body;
    }
1036166
def get_world_size():
    
    if torch.distributed.is_available() and torch.distributed.is_initialized():
        world_size = torch.distributed.get_world_size()
    else:
        world_size = 1
    return world_size
62277
def parse_names(cls, names: List[str]) -> T:
        """"""
        value = 0
        iterable = cls  # type: Iterable
        for name in names:
            name = name.lower()
            flag = next((item for item in iterable if name == item.name.lower()), None)
            if not flag:
                raise ValueError("{} is not a member of {}".format(
                    name, cls.__name__))
            value = value | int(flag)
        return cls(value)
310690
def _parse_caps_cell(cell):
    '''
    
    '''
    result = {
        'id': int(cell.get('id'))
    }

    mem_node = cell.find('memory')
    if mem_node is not None:
        unit = mem_node.get('unit', 'KiB')
        memory = mem_node.text
        result['memory'] = "{} {}".format(memory, unit)

    pages = [{'size': "{} {}".format(page.get('size'), page.get('unit', 'KiB')),
              'available': int(page.text)}
             for page in cell.findall('pages')]
    if pages:
        result['pages'] = pages

    distances = {int(distance.get('id')): int(distance.get('value'))
                 for distance in cell.findall('distances/sibling')}
    if distances:
        result['distances'] = distances

    cpus = []
    for cpu_node in cell.findall('cpus/cpu'):
        cpu = {
            'id': int(cpu_node.get('id'))
        }
        socket_id = cpu_node.get('socket_id')
        if socket_id:
            cpu['socket_id'] = int(socket_id)

        core_id = cpu_node.get('core_id')
        if core_id:
            cpu['core_id'] = int(core_id)
        siblings = cpu_node.get('siblings')
        if siblings:
            cpu['siblings'] = siblings
        cpus.append(cpu)
    if cpus:
        result['cpus'] = cpus

    return result