Convert a LocalOperator instance to qutip
499504
def _convert_local_operator_to_qutip(expr, full_space, mapping):
    """"""
    n = full_space.dimension
    if full_space != expr.space:
        all_spaces = full_space.local_factors
        own_space_index = all_spaces.index(expr.space)
        return qutip.tensor(
            *([qutip.qeye(s.dimension)
               for s in all_spaces[:own_space_index]] +
              [convert_to_qutip(expr, expr.space, mapping=mapping), ] +
              [qutip.qeye(s.dimension)
               for s in all_spaces[own_space_index + 1:]])
        )
    if isinstance(expr, Create):
        return qutip.create(n)
    elif isinstance(expr, Jz):
        return qutip.jmat((expr.space.dimension-1)/2., "z")
    elif isinstance(expr, Jplus):
        return qutip.jmat((expr.space.dimension-1)/2., "+")
    elif isinstance(expr, Jminus):
        return qutip.jmat((expr.space.dimension-1)/2., "-")
    elif isinstance(expr, Destroy):
        return qutip.destroy(n)
    elif isinstance(expr, Phase):
        arg = complex(expr.operands[1]) * arange(n)
        d = np_cos(arg) + 1j * np_sin(arg)
        return qutip.Qobj(np_diag(d))
    elif isinstance(expr, Displace):
        alpha = expr.operands[1]
        return qutip.displace(n, alpha)
    elif isinstance(expr, Squeeze):
        eta = expr.operands[1]
        return qutip.displace(n, eta)
    elif isinstance(expr, LocalSigma):
        j = expr.j
        k = expr.k
        if isinstance(j, str):
            j = expr.space.basis_labels.index(j)
        if isinstance(k, str):
            k = expr.space.basis_labels.index(k)
        ket = qutip.basis(n, j)
        bra = qutip.basis(n, k).dag()
        return ket * bra
    else:
        raise ValueError("Cannot convert '%s' of type %s"
                         % (str(expr), type(expr)))
927018
def query( self ):
        
        widget = self.uiWidgetAREA.widget()
        if ( widget and type(widget) != QWidget ):
            value = nativestring(widget.text())
        else:
            value = ''
        
        op = nativestring(self.uiOperatorDDL.currentText())
        if ( self.currentRule() ):
            op = self.currentRule().labelOperator(op)
        
        return (nativestring(self.uiTermDDL.currentText()), op, value)
1118066
def from_dict(d):
        
        return Specs(
            qubits_specs=sorted([QubitSpecs(id=int(q),
                                            fRO=qspecs.get('fRO'),
                                            f1QRB=qspecs.get('f1QRB'),
                                            T1=qspecs.get('T1'),
                                            T2=qspecs.get('T2'),
                                            fActiveReset=qspecs.get('fActiveReset'))
                                 for q, qspecs in d["1Q"].items()],
                                key=lambda qubit_specs: qubit_specs.id),
            edges_specs=sorted([EdgeSpecs(targets=[int(q) for q in e.split('-')],
                                          fBellState=especs.get('fBellState'),
                                          fCZ=especs.get('fCZ'),
                                          fCZ_std_err=especs.get('fCZ_std_err'),
                                          fCPHASE=especs.get('fCPHASE'))
                                for e, especs in d["2Q"].items()],
                               key=lambda edge_specs: edge_specs.targets)
        )
980764
def scalars_to_op(cls, ops, kwargs):
    '''
    from qnet.algebra.core.scalar_algebra import is_scalar
    op_ops = []
    for op in ops:
        if is_scalar(op):
            op_ops.append(op * cls._one)
        else:
            op_ops.append(op)
    return op_ops, kwargs
720088
def wrap(ptr, base=None):
    
    if ptr is None:
        return None
    ptr = long(ptr) # Ensure type
    if base is None:
        qObj = shiboken.wrapInstance(long(ptr), QtCore.QObject)
        metaObj = qObj.metaObject()
        cls = metaObj.className()
        superCls = metaObj.superClass().className()
        if hasattr(QtGui, cls):
            base = getattr(QtGui, cls)
        elif hasattr(QtGui, superCls):
            base = getattr(QtGui, superCls)
        else:
            base = QtGui.QWidget
    return shiboken.wrapInstance(long(ptr), base)
456197
def Compile(self, filter_implemention):
    """"""
    return self.operator_method(self.attribute_obj, filter_implemention,
                                *self.args)
1233655
function dotOperatorFunc (attributeName, obj) {
      var func

      if (obj) func = obj[attributeName]

      if (typeof func === 'function') {
        return func.apply(obj, Array.prototype.slice.call(arguments, 2))
      }
    }
1347487
function $$(instance, Clazz, ctor, args) {
                args = ria.__API.clone(args);
                var clazz = args[0],
                    specs = args[1];

                if (clazz instanceof ria.__API.ClassDescriptor)
                    clazz = clazz.ctor;

                if (clazz instanceof ria.__API.Class) {
                    var instance = clazz;
                    clazz = instance.getClass();
                    // TODO; fetch specs from instance
                }

                if (ria.__API.isSpecification(clazz)) {
                    var specify = clazz;
                    clazz = specify.type;
                    specs = specify.specs;
                }

                if (!ria.__API.isClassConstructor(clazz))
                    throw new ria.reflection.Exception('ReflectionFactory works only on CLASS');

                args.splice(0, 1, clazz, specs);

                var name = ria.__API.getIdentifierOfType(ria.__API.specify(clazz, specs)) + '@' + clazz.__REF_ID;
                if (cache.hasOwnProperty(name))
                    return cache[name];

                return cache[name] = new ria.__API.init(instance, Clazz, ctor, args);
            }
1032023
def from_dict(d):
        
        return ISA(
            qubits=sorted([Qubit(id=int(qid),
                                 type=q.get("type", DEFAULT_QUBIT_TYPE),
                                 dead=q.get("dead", False))
                           for qid, q in d["1Q"].items()],
                          key=lambda qubit: qubit.id),
            edges=sorted([Edge(targets=[int(q) for q in eid.split('-')],
                               type=e.get("type", DEFAULT_EDGE_TYPE),
                               dead=e.get("dead", False))
                          for eid, e in d["2Q"].items()],
                         key=lambda edge: edge.targets),
        )
30251
private static <T, K> org.apache.flink.api.common.operators.SingleInputOperator<?, T, ?> translateSelectorFunctionReducer(
		SelectorFunctionKeys<T, ?> rawKeys,
		ReduceFunction<T> function,
		TypeInformation<T> inputType,
		String name,
		Operator<T> input,
		int parallelism,
		CombineHint hint) {
		@SuppressWarnings("unchecked")
		final SelectorFunctionKeys<T, K> keys = (SelectorFunctionKeys<T, K>) rawKeys;

		TypeInformation<Tuple2<K, T>> typeInfoWithKey = KeyFunctions.createTypeWithKey(keys);
		Operator<Tuple2<K, T>> keyedInput = KeyFunctions.appendKeyExtractor(input, keys);

		PlanUnwrappingReduceOperator<T, K> reducer = new PlanUnwrappingReduceOperator<>(function, keys, name, inputType, typeInfoWithKey);
		reducer.setInput(keyedInput);
		reducer.setParallelism(parallelism);
		reducer.setCombineHint(hint);

		return KeyFunctions.appendKeyRemover(reducer, keys);
	}
903892
def widget_from_tuple(o):
        """"""
        if _matches(o, (Real, Real)):
            min, max, value = _get_min_max_value(o[0], o[1])
            if all(isinstance(_, Integral) for _ in o):
                cls = IntSlider
            else:
                cls = FloatSlider
            return cls(value=value, min=min, max=max)
        elif _matches(o, (Real, Real, Real)):
            step = o[2]
            if step <= 0:
                raise ValueError("step must be >= 0, not %r" % step)
            min, max, value = _get_min_max_value(o[0], o[1], step=step)
            if all(isinstance(_, Integral) for _ in o):
                cls = IntSlider
            else:
                cls = FloatSlider
            return cls(value=value, min=min, max=max, step=step)
1276022
def from_raw(self, rval: RawObject, jptr: JSONPointer = "") -> ObjectValue:
        """"""
        if not isinstance(rval, dict):
            raise RawTypeError(jptr, "object")
        res = ObjectValue()
        for qn in rval:
            if qn.startswith("@"):
                if qn != "@":
                    tgt = qn[1:]
                    if tgt not in rval:
                        raise MissingAnnotationTarget(jptr, tgt)
                    jptr += '/' + tgt
                res[qn] = self._process_metadata(rval[qn], jptr)
            else:
                cn = self._iname2qname(qn)
                ch = self.get_data_child(*cn)
                npath = jptr + "/" + qn
                if ch is None:
                    raise RawMemberError(npath)
                res[ch.iname()] = ch.from_raw(rval[qn], npath)
        return res
892754
def apply_cast(scope, input_name, output_name, container, operator_name=None, to=None):
    '''
    
    '''
    name = _create_name_or_use_existing_one(scope, 'Cast', operator_name)
    attrs = {'name': name}

    d = onnx_proto.TensorProto.DataType.DESCRIPTOR
    allowed_type_name_and_type_enum_pairs = {v.number: k for k, v in d.values_by_name.items()}
    if to not in allowed_type_name_and_type_enum_pairs:
        raise ValueError('Attribute "to" must be one of %s' % allowed_type_name_and_type_enum_pairs.keys())

    if container.target_opset < 9:
        if to in [onnx_proto.TensorProto.STRING, onnx_proto.TensorProto.COMPLEX64, onnx_proto.TensorProto.COMPLEX128]:
            raise ValueError('Attribute "to" cannot correspond to a String or Complex TensorProto type.')

        if container.target_opset < 6:
            # Convert enum to string, for example, TensorProto.INT64 to 'INT64'
            attrs['to'] = allowed_type_name_and_type_enum_pairs[to]
            op_version = 1
        else:
            # Enum, for example, TensorProto.INT64
            attrs['to'] = to
            op_version = 6
    else:
        # Enum value, for example, TensorProto.INT64
        # String casting is supported in opset 9
        if to in [onnx_proto.TensorProto.COMPLEX64, onnx_proto.TensorProto.COMPLEX128]:
            raise ValueError('Attribute "to" cannot correspond to a Complex TensorProto type.')
        attrs['to'] = to
        op_version = 9

    container.add_node('Cast', input_name, output_name, op_version=op_version, **attrs)
265053
def properties_operator(cls, name):
    """"""

    def wrapper(self, *args, **kwargs):
        """Perform operation and cast to container class"""
        output = getattr(super(cls, self), name)(*args, **kwargs)
        return cls(output)

    wrapped = getattr(cls, name)
    wrapper.__name__ = wrapped.__name__
    wrapper.__doc__ = wrapped.__doc__
    return wrapper
243802
function localExport(opt) {
    var ind = _.reGet(/\d/)(opt.chart.renderTo);
    _.assign(opt, {
      'exporting': {
        'buttons': {
          'contextButton': {
            'y': -10,
            'menuItems': [{
              'text': 'Save as PNG',
              onclick: function() {
                this.createCanvas(opt.title, 'png', ind);
              },
              'separator': false
            }, {
              'text': 'Save as JPEG',
              onclick: function() {
                this.createCanvas(opt.title, 'jpeg', ind);
              },
              'separator': false
            }]
          }
        }
      }
    })
    return opt;
  }
574972
function Tooltip(el, options) {
      _classCallCheck(this, Tooltip);

      var _this26 = _possibleConstructorReturn(this, (Tooltip.__proto__ || Object.getPrototypeOf(Tooltip)).call(this, Tooltip, el, options));

      _this26.el.M_Tooltip = _this26;
      _this26.options = $.extend({}, Tooltip.defaults, options);

      _this26.isOpen = false;
      _this26.isHovered = false;
      _this26.isFocused = false;
      _this26._appendTooltipEl();
      _this26._setupEventHandlers();
      return _this26;
    }
213977
function injectDotOperators (funcs, task) {
  /**
   * Inject dot operator.
   */

  function inject (taskKey) {
    var taskName = task[taskKey]

    /**
     * Dot operator function.
     *
     * @param {String} attributeName
     * @param {Object} obj
     * @param {...} rest of arguments
     *
     * @returns {*} result
     */

    function dotOperatorFunc (attributeName, obj) {
      var func

      if (obj) func = obj[attributeName]

      if (typeof func === 'function') {
        return func.apply(obj, Array.prototype.slice.call(arguments, 2))
      }
    }

    if (regexDotOperator.func.test(taskName)) {
      // .foo() -> foo
      funcs[taskName] = dotOperatorFunc.bind(null, taskName.substring(1, taskName.length - 2))
    }

    /**
     * Dot operator attribute write.
     *
     * @param {String} attributeName
     * @param {Object} obj
     * @param {*} attributeValue
     *
     * @returns {Object} obj modified
     */

    function dotOperatorAttributeWrite (attributeName, obj, attributeValue) {
      obj[attributeName] = attributeValue

      return obj
    }

    if (regexDotOperator.attrWrite.test(taskName)) {
      // .foo= -> foo
      funcs[taskName] = dotOperatorAttributeWrite.bind(null, taskName.substring(1, taskName.length - 1))
    }

    /**
     * Dot operator attribute read.
     *
     * @param {String} attributeName
     * @param {Object} obj
     *
     * @returns {*} attribute
     */

    function dotOperatorAttributeRead (attributeName, obj) {
      var attr

      if (obj) attr = obj[attributeName]

      if (typeof attr === 'function') return attr.bind(obj)

      return attr
    }

    if (regexDotOperator.attrRead.test(taskName)) {
      // .foo -> foo
      funcs[taskName] = dotOperatorAttributeRead.bind(null, taskName.substring(1))
    }
  }

  Object.keys(task).forEach(inject)
}