Generates the required Sz operators, given the system parameter setup
       and the operator dictionary
439727
def spin_z_op(param, oper):
    """"""
    slaves = param['slaves']
    oper['Sz'] = np.array([spin_z(slaves, spin) for spin in range(slaves)])
    oper['Sz+1/2'] = oper['Sz'] + 0.5*np.eye(2**slaves)
    oper['sumSz2'] = oper['Sz'].sum(axis=0)**2  # because Sz is diagonal
    Sz_mat_shape = oper['Sz'].reshape(param['orbitals'], 2, 2**slaves, 2**slaves)
    oper['sumSz-sp2'] = (Sz_mat_shape.sum(axis=1)**2).sum(axis=0)
    oper['sumSz-or2'] = (Sz_mat_shape.sum(axis=0)**2).sum(axis=0)
1341745
def generate_devices(lxd_params, options)
      logger.info("Calling <#{__method__.to_s}>")
      lxd_params[:devices] = {}

      if options[:'no-maas']
        lxd_params[:devices] = YAML.load_file(options[:file])['devices']

        # Now, LXD API can handle integer as a value of a map
        lxd_params[:devices].each do |k, v|
          v.each do |kk, vv|
            if vv.is_a? Integer
              v[kk] = vv.to_s
            end
          end
        end

        lxd_params[:devices] = (Hashie.symbolize_keys lxd_params[:devices])

      elsif options[:ipaddresses]
        config[:ifaces].each_with_index do |iface,index|
          if index == 0
            if iface['vlan']['name'] == 'untagged' # or vid == 0
              lxd_params[:devices][:"eth#{index}"] = {
                mtu: iface['vlan']['mtu'].to_s,   #This must be string
                name: "eth#{index}",
                nictype: 'bridged',
                parent: config[:default][:root_bridge],
                type: 'nic'
              }
            elsif iface['vlan']['name'] != 'untagged' # or vid != 0
              lxd_params[:devices][:"eth#{index}"] = {
                mtu: iface['vlan']['mtu'].to_s,   #This must be string
                name: "eth#{index}",
                nictype: 'bridged',
                parent: config[:default][:root_bridge] + "-" + iface['vlan']['vid'].to_s,
                type: 'nic'
              }
            end
          # When config[:ifaces][0]['vlan']['name'] == 'untagged' and index > 0,
          # it does not need to generate more devices 
          # since it will configure the IPs with tagged VLANs.
          elsif config[:ifaces][0]['vlan']['name'] != 'untagged'
            lxd_params[:devices][:"eth#{index}"] = {
              mtu: iface['vlan']['mtu'].to_s,   #This must be string
              name: "eth#{index}",
              nictype: 'bridged',
              parent: config[:default][:root_bridge] + "-" + iface['vlan']['vid'].to_s,
              type: 'nic'
            }
          end
        end
      else
        abort("root_bridge #{config[:default][:root_bridge]} does not exist.") \
           unless conn.networks.include? config[:default][:root_bridge]

        root_bridge_mtu = nil
        # It assumes you only use one fabric as of now,
        # since there might be more fabrics with each untagged vlans on them,
        # which might make finding exact mtu fail as following process.
        default_fabric = 'fabric-0'

        maas.get_subnets.each do |subnet|
          if subnet['vlan']['name'] == 'untagged' and \
              subnet['vlan']['fabric'] == default_fabric
            root_bridge_mtu = subnet['vlan']['mtu']
            break
          end
        end

        lxd_params[:devices] = {}
        lxd_params[:devices][:"eth0"] = {
          mtu: root_bridge_mtu.to_s,   #This must be string
          name: 'eth0',
          nictype: 'bridged',
          parent: config[:default][:root_bridge],
          type: 'nic'
        }
      end

      if options[:'maas-on-lxc']
        # https://docs.maas.io/2.4/en/installconfig-lxd-install
        for i in 0..7
          i = i.to_s
          lxd_params[:devices]["loop" + i] = {}
          lxd_params[:devices]["loop" + i]["path"] = "/dev/loop" + i
          lxd_params[:devices]["loop" + i]["type"] = "unix-block"
        end
      end

      return lxd_params
    end
980955
def _gen_code(self):
        """"""
        # This is the dictionary that stores all the generated code.

        self.code = {}
        def match_key(expr):
            if type(expr) is dict:
                code = {}
                for key in expr.keys():
                    code[key] = match_key(expr[key])
            else:
                arg_list = [e for e in expr.atoms() if e.is_Symbol]
                code = self._expr2code(arg_list, expr)
            return code

        self.code = match_key(self.expressions)
502715
def _build_parameters(
    server_no_context_takeover: bool,
    client_no_context_takeover: bool,
    server_max_window_bits: Optional[int],
    client_max_window_bits: Optional[Union[int, bool]],
) -> List[ExtensionParameter]:
    
    params: List[ExtensionParameter] = []
    if server_no_context_takeover:
        params.append(("server_no_context_takeover", None))
    if client_no_context_takeover:
        params.append(("client_no_context_takeover", None))
    if server_max_window_bits:
        params.append(("server_max_window_bits", str(server_max_window_bits)))
    if client_max_window_bits is True:  # only in handshake requests
        params.append(("client_max_window_bits", None))
    elif client_max_window_bits:
        params.append(("client_max_window_bits", str(client_max_window_bits)))
    return params
1354319
private void populateOperators() {
		operators = new HashMap();

		registerContentOperator("q", new PushGraphicsState());
		registerContentOperator("Q", new PopGraphicsState());
		registerContentOperator("cm", new ModifyCurrentTransformationMatrix());
		registerContentOperator("gs", new ProcessGraphicsStateResource());

		registerContentOperator("Tc", new SetTextCharacterSpacing());
		registerContentOperator("Tw", new SetTextWordSpacing());
		registerContentOperator("Tz", new SetTextHorizontalScaling());
		registerContentOperator("TL", new SetTextLeading());
		registerContentOperator("Tf", new SetTextFont());
		registerContentOperator("Tr", new SetTextRenderMode());
		registerContentOperator("Ts", new SetTextRise());

		registerContentOperator("BT", new BeginText());
		registerContentOperator("ET", new EndText());

		registerContentOperator("Td", new TextMoveStartNextLine());
		registerContentOperator("TD", new TextMoveStartNextLineWithLeading());
		registerContentOperator("Tm", new TextSetTextMatrix());
		registerContentOperator("T*", new TextMoveNextLine());

		registerContentOperator("Tj", new ShowText());
		registerContentOperator("'", new MoveNextLineAndShowText());
		registerContentOperator("\"", new MoveNextLineAndShowTextWithSpacing());
		registerContentOperator("TJ", new ShowTextArray());

		registerContentOperator("Do", new Do());
	}
99780
def prepare_system_options(cfg, defaults=None):
    
    d = {} if defaults is None else defaults.copy()
    if 'nonbondedMethod' in cfg:
        d['nonbondedMethod'] = warned_getattr(openmm_app, cfg.pop('nonbondedMethod'), None)
    if 'nonbondedCutoff' in cfg:
        d['nonbondedCutoff'] = cfg.pop('nonbondedCutoff') * u.nanometers
    if 'constraints' in cfg:
        d['constraints'] = warned_getattr(openmm_app, cfg.pop('constraints'), None)
    for key in ['rigidWater', 'ewaldErrorTolerance']:
        if key in cfg:
            d[key] = cfg.pop(key)
    if 'extra_system_options' in cfg:
        if 'implicitSolvent' in cfg['extra_system_options']:
            implicit_solvent = warned_getattr(
                openmm_app, cfg['extra_system_options']['implicitSolvent'], None)
            cfg['extra_system_options']['implicitSolvent'] = implicit_solvent
        d.update(cfg.pop('extra_system_options'))
    return d
1041924
function GENERATE_PARAMS(spec) {
  return _.map(spec, function(paramSpec, paramName) {
    return paramName + ': ' + paramSpec.type;
  }).join(', ');
}
1138612
def generate_stub(self):
        
        needed_types = self.required_types - BUILTIN_TYPES

        needed_types -= self.defined_types
        _logger.debug("defined types: %s", self.defined_types)

        module_vars = {v.name for v in self.root.variables}
        _logger.debug("module variables: %s", module_vars)

        qualified_types = {n for n in needed_types if "." in n}
        qualified_namespaces = {".".join(n.split(".")[:-1]) for n in qualified_types}

        needed_namespaces = qualified_namespaces - module_vars
        needed_types -= qualified_types
        _logger.debug("needed namespaces: %s", needed_namespaces)

        imported_names = {n.split("::")[0] for n in self.imported_names}
        imported_types = imported_names & (needed_types | needed_namespaces)
        needed_types -= imported_types
        needed_namespaces -= imported_names
        _logger.debug("used imported types: %s", imported_types)

        try:
            typing_mod = __import__("typing")
            typing_types = {n for n in needed_types if hasattr(typing_mod, n)}
            needed_types -= typing_types
            _logger.debug("types from typing module: %s", typing_types)
        except ImportError:
            typing_types = set()
            _logger.warn("typing module not installed")

        if len(needed_types) > 0:
            raise ValueError("Unknown types: " + ", ".join(needed_types))

        out = StringIO()
        started = False

        if len(typing_types) > 0:
            line = self.generate_import_from("typing", typing_types)
            out.write(line + "\n")
            started = True

        if len(imported_types) > 0:
            if started:
                out.write("\n")
            # preserve the import order in the source file
            for name in self.imported_names:
                if name.split("::")[0] in imported_types:
                    line = self.generate_import_from(self.imported_names[name], {name})
                    out.write(line + "\n")
            started = True

        if len(needed_namespaces) > 0:
            if started:
                out.write("\n")
            as_names = {n.split("::")[0]: n for n in self.imported_namespaces if "::" in n}
            for module_ in sorted(needed_namespaces):
                if module_ in as_names:
                    a, n = as_names[module_].split("::")
                    out.write("import " + n + " as " + a + "\n")
                else:
                    out.write("import " + module_ + "\n")
            started = True

        if len(self.aliases) > 0:
            if started:
                out.write("\n")
            for alias, signature in self.aliases.items():
                out.write("%s = %s\n" % (alias, signature))
            started = True

        if started:
            out.write("\n")
        stub_lines = self.root.get_code()
        n_lines = len(stub_lines)
        for line_no in range(n_lines):
            prev_line = stub_lines[line_no - 1] if line_no > 0 else None
            line = stub_lines[line_no]
            next_line = stub_lines[line_no + 1] if line_no < (n_lines - 1) else None
            if (
                line.startswith("class ")
                and (prev_line is not None)
                and (
                    (not prev_line.startswith("class "))
                    or (next_line and next_line.startswith(" "))
                )
            ):
                out.write("\n")
            if (
                line.startswith("def ")
                and (prev_line is not None)
                and (prev_line.startswith((" ", "class ")))
            ):
                out.write("\n")
            out.write(line + "\n")
            line_no += 1
        return out.getvalue()
1083904
def get_XYZ(self, mode, disp):
        

        # Imports
        from ..xyz import OpanXYZ as XYZ
        from ..const import EnumAnharmRepoParam, EnumAnharmRepoData

        # Generate XYZ and return
        out_XYZ = XYZ(atom_syms=self.get_param(EnumAnharmRepoParam.atoms), \
                        coords=self.get_data(EnumAnharmRepoData.geom, mode, disp))
        return out_XYZ
1351760
function process( $tpl, &$value, $nspace, $current_nspace )
    {
        $named_params = array();
        $param_list = $tpl->operatorParameterList( $this->Name );
        $i = 0;
        foreach ( $param_list as $param_name => $param_type )
        {
            if ( !isset( $this->Params[$i] ) or
                 $this->Params[$i]["type"] == "null" )
            {
                if ( $param_type["required"] )
                {
                    $tpl->warning( "eZTemplateOperatorElement", "Parameter '$param_name' ($i) missing" );
                    $named_params[$param_name] = $param_type["default"];
                }
                else
                {
                    $named_params[$param_name] = $param_type["default"];
                }
            }
            else
            {
                $param_data = $this->Params[$i];
                $named_params[$param_name] = $tpl->elementValue( $param_data, $nspace );
            }
            ++$i;
        }
        if ( $param_list !== null )
            $tpl->doOperator( $this, $nspace, $current_nspace, $value, $this->Name, $this->Params, $named_params );
        else
            $tpl->doOperator( $this, $nspace, $current_nspace, $value, $this->Name, $this->Params );
    }
1229951
def perform_set_operation(*args)
      options     = extract_options!(args)
      environment = extract_environment!(options)
      identifier  = normalize_set_identifier(environment)
      # Uses yaml when we have multiple identifiers.
      uses_yaml   = !environment.nil?
      options.merge!(:yaml => true) if uses_yaml
      args.unshift(identifier) unless identifier.nil?
      args << options
      result = rvm(*args)
      uses_yaml ? YAML.load(result.stdout) : result
    end
269244
protected void _generate(SarlClass clazz, PyAppendable it, IExtraLanguageGeneratorContext context) {
		generateTypeDeclaration(
				this.qualifiedNameProvider.getFullyQualifiedName(clazz).toString(),
				clazz.getName(), clazz.isAbstract(),
				getSuperTypes(clazz.getExtends(), clazz.getImplements()),
				getTypeBuilder().getDocumentation(clazz),
				true,
				clazz.getMembers(), it, context, null);
	}
1242544
def create_from_dict(cls, src_dict, roi_skydir=None, rescale=False):
        
        src_dict = copy.deepcopy(src_dict)
        src_dict.setdefault('SpatialModel', 'PointSource')
        src_dict.setdefault('Spectrum_Filename', None)
        src_dict.setdefault('SpectrumType', 'PowerLaw')
        src_dict['SpatialType'] = get_spatial_type(src_dict['SpatialModel'])

        spectrum_type = src_dict['SpectrumType']
        spatial_type = src_dict['SpatialType']

        spectral_pars = src_dict.pop('spectral_pars', {})
        spatial_pars = src_dict.pop('spatial_pars', {})

        if not spectral_pars:
            spectral_pars = extract_pars_from_dict(spectrum_type, src_dict)
            norm_par_name = get_function_norm_par_name(spectrum_type)
            if norm_par_name is not None:
                spectral_pars[norm_par_name].setdefault('free', True)

        if not spatial_pars:
            spatial_pars = extract_pars_from_dict(spatial_type, src_dict)
            for k in ['RA', 'DEC', 'Prefactor']:
                if k in spatial_pars:
                    del spatial_pars[k]

        spectral_pars = create_pars_from_dict(spectrum_type, spectral_pars,
                                              rescale)
        spatial_pars = create_pars_from_dict(spatial_type, spatial_pars,
                                             False)

        if 'file' in src_dict:
            src_dict['Spectrum_Filename'] = src_dict.pop('file')

        if spectrum_type == 'DMFitFunction' and src_dict['Spectrum_Filename'] is None:
            src_dict['Spectrum_Filename'] = os.path.join('$FERMIPY_DATA_DIR',
                                                         'gammamc_dif.dat')

        src_dict['spectral_pars'] = cast_pars_dict(spectral_pars)
        src_dict['spatial_pars'] = cast_pars_dict(spatial_pars)

        if 'name' in src_dict:
            name = src_dict['name']
            src_dict['Source_Name'] = src_dict.pop('name')
        elif 'Source_Name' in src_dict:
            name = src_dict['Source_Name']
        else:
            raise Exception('Source name undefined.')

        skydir = wcs_utils.get_target_skydir(src_dict, roi_skydir)

        src_dict['RAJ2000'] = skydir.ra.deg
        src_dict['DEJ2000'] = skydir.dec.deg

        radec = np.array([skydir.ra.deg, skydir.dec.deg])

        return cls(name, src_dict, radec=radec)
822672
def _tool_to_dict(tool, records, remapped):
    
    requirements = _requirements_to_dict(tool.requirements + tool.hints)
    inputs = []
    outputs = []
    for inp in tool.tool["inputs"]:
        ready_inp, records = _input_to_dict(inp, records, remapped)
        inputs.append(ready_inp)
    for outp in tool.tool["outputs"]:
        ready_outp, records = _output_to_dict(outp, records)
        outputs.append(ready_outp)
    out = {"name": _id_to_name(tool.tool["id"]),
           "baseCommand": " ".join(tool.tool["baseCommand"]),
           "arguments": [_arg_to_dict(a, requirements) for a in tool.tool["arguments"]],
           "inputs": inputs,
           "outputs": outputs,
           "requirements": requirements,
           "stdin": None, "stdout": None}
    return out, records
237088
def Rz(rads: Union[float, sympy.Basic]) -> ZPowGate:
    """"""
    pi = sympy.pi if protocols.is_parameterized(rads) else np.pi
    return ZPowGate(exponent=rads / pi, global_shift=-0.5)
909753
private LinkedHashSet<Formula> gatherAppliedOperands(final NAryOperator operator) {
    final LinkedHashSet<Formula> applied = new LinkedHashSet<>();
    for (final Formula operand : operator) {
      applied.add(apply(operand, false));
    }
    return applied;
  }
1137815
def calculate_padding_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
    check_input_and_output_types(operator, good_input_types=[FloatTensorType])

    output_shape = copy.deepcopy(operator.inputs[0].type.shape)

    params = operator.raw_operator.padding
    if len(params.paddingAmounts.borderAmounts) > 0:
        output_shape[2] += params.paddingAmounts.borderAmounts[0].startEdgeSize
        output_shape[2] += params.paddingAmounts.borderAmounts[0].endEdgeSize
        output_shape[3] += params.paddingAmounts.borderAmounts[1].startEdgeSize
        output_shape[3] += params.paddingAmounts.borderAmounts[1].endEdgeSize

    operator.outputs[0].type.shape = output_shape