Python implementation of ``calcbinflux``.

    This is only used if ``synphot.synphot_utils`` C-extension
    import fails.

    See docstrings.py
169905
def _slow_calcbinflux(len_binwave, i_beg, i_end, avflux, deltaw):
    
    binflux = np.empty(shape=(len_binwave, ), dtype=np.float64)
    intwave = np.empty(shape=(len_binwave, ), dtype=np.float64)

    # Note that, like all Python striding, the range over which
    # we integrate is [first:last).
    for i in range(len(i_beg)):
        first = i_beg[i]
        last = i_end[i]
        cur_dw = deltaw[first:last]
        intwave[i] = cur_dw.sum()
        binflux[i] = np.sum(avflux[first:last] * cur_dw) / intwave[i]

    return binflux, intwave
967410
function calcBBox(node, toBBox) {
    distBBox(node, 0, node.children.length, toBBox, node);
}
597926
def _addf(ins):
    ''' 
    '''
    op1, op2 = tuple(ins.quad[2:])

    if _f_ops(op1, op2) is not None:
        opa, opb = _f_ops(op1, op2)
        if opb == 0:  # A + 0 => A
            output = _float_oper(opa)
            output.extend(_fpush())
            return output

    output = _float_oper(op1, op2)
    output.append('call __ADDF')
    output.extend(_fpush())
    REQUIRES.add('addf.asm')
    return output
791755
def _paramf(ins):
    
    output = _float_oper(ins.quad[1])
    output.extend(_fpush())
    return output
1091839
def resolve(self):
        
        module = __import__(self.module_name, fromlist=['__name__'], level=0)
        try:
            return functools.reduce(getattr, self.attrs, module)
        except AttributeError as exc:
            raise ImportError(str(exc))
673652
def GenericPump(filenames, use_jppy=False, name="GenericPump", **kwargs):
    """"""
    if isinstance(filenames, str):
        filenames = [filenames]

    try:
        iter(filenames)
    except TypeError:
        log.critical("Don't know how to iterate through filenames.")
        raise TypeError("Invalid filenames.")

    extensions = set(os.path.splitext(fn)[1] for fn in filenames)

    if len(extensions) > 1:
        log.critical("Mixed filetypes, please use only files of the same type")
        raise IOError("Mixed filetypes.")

    extension = list(extensions)[0]

    io = {
        '.evt': EvtPump,
        '.h5': HDF5Pump,
        '.root': EventPump if use_jppy else AanetPump,
        '.dat': DAQPump,
        '.dqd': CLBPump,
    }

    if extension not in io:
        log.critical(
            "No pump found for file extension '{0}'".format(extension)
        )
        raise ValueError("Unknown filetype")

    missing_files = [fn for fn in filenames if not os.path.exists(fn)]
    if missing_files:
        if len(missing_files) == len(filenames):
            message = "None of the given files could be found."
            log.critical(message)
            raise SystemExit(message)
        else:
            log.warning(
                "The following files are missing and ignored: {}".format(
                    ', '.join(missing_files)
                )
            )

    input_files = set(filenames) - set(missing_files)

    if len(input_files) == 1:
        return io[extension](filename=filenames[0], name=name, **kwargs)
    else:
        return io[extension](filenames=filenames, name=name, **kwargs)
150437
def set_window_pos_callback(window, cbfun):
    
    window_addr = ctypes.cast(ctypes.pointer(window),
                              ctypes.POINTER(ctypes.c_long)).contents.value
    if window_addr in _window_pos_callback_repository:
        previous_callback = _window_pos_callback_repository[window_addr]
    else:
        previous_callback = None
    if cbfun is None:
        cbfun = 0
    c_cbfun = _GLFWwindowposfun(cbfun)
    _window_pos_callback_repository[window_addr] = (cbfun, c_cbfun)
    cbfun = c_cbfun
    _glfw.glfwSetWindowPosCallback(window, cbfun)
    if previous_callback is not None and previous_callback[0] != 0:
        return previous_callback[0]
605521
def handle_import(self, name, compilation, rule):
        
        from .sprites import sprite_map

        # TODO check that the found file is actually under the root
        if callable(config.STATIC_ROOT):
            files = sorted(config.STATIC_ROOT(name))
        else:
            glob_path = os.path.join(config.STATIC_ROOT, name)
            files = glob.glob(glob_path)
            files = sorted((fn[len(config.STATIC_ROOT):], None) for fn in files)

        if not files:
            return

        # Build magic context
        calculator = compilation._make_calculator(rule.namespace)
        map_name = os.path.normpath(os.path.dirname(name)).replace('\\', '_').replace('/', '_')
        kwargs = {}

        # TODO this is all kinds of busted.  rule.context hasn't existed for
        # ages.
        def setdefault(var, val):
            _var = '$' + map_name + '-' + var
            if _var in rule.context:
                kwargs[var] = calculator.interpolate(rule.context[_var], rule, self._library)
            else:
                rule.context[_var] = val
                kwargs[var] = calculator.interpolate(val, rule, self._library)
            return rule.context[_var]

        setdefault('sprite-base-class', String('.' + map_name + '-sprite', quotes=None))
        setdefault('sprite-dimensions', Boolean(False))
        position = setdefault('position', Number(0, '%'))
        spacing = setdefault('spacing', Number(0))
        repeat = setdefault('repeat', String('no-repeat', quotes=None))
        names = tuple(os.path.splitext(os.path.basename(file))[0] for file, storage in files)
        for n in names:
            setdefault(n + '-position', position)
            setdefault(n + '-spacing', spacing)
            setdefault(n + '-repeat', repeat)
        rule.context['$' + map_name + '-' + 'sprites'] = sprite_map(name, **kwargs)
        generated_code = '''
            @import "compass/utilities/sprites/base";

            // All sprites should extend this class
            // The %(map_name)s-sprite mixin will do so for you.
            #{$%(map_name)s-sprite-base-class} {
                background: $%(map_name)s-sprites;
            }

            // Use this to set the dimensions of an element
            // based on the size of the original image.
            @mixin %(map_name)s-sprite-dimensions($name) {
                @include sprite-dimensions($%(map_name)s-sprites, $name);
            }

            // Move the background position to display the sprite.
            @mixin %(map_name)s-sprite-position($name, $offset-x: 0, $offset-y: 0) {
                @include sprite-position($%(map_name)s-sprites, $name, $offset-x, $offset-y);
            }

            // Extends the sprite base class and set the background position for the desired sprite.
            // It will also apply the image dimensions if $dimensions is true.
            @mixin %(map_name)s-sprite($name, $dimensions: $%(map_name)s-sprite-dimensions, $offset-x: 0, $offset-y: 0) {
                @extend #{$%(map_name)s-sprite-base-class};
                @include sprite($%(map_name)s-sprites, $name, $dimensions, $offset-x, $offset-y);
            }

            @mixin %(map_name)s-sprites($sprite-names, $dimensions: $%(map_name)s-sprite-dimensions) {
                @include sprites($%(map_name)s-sprites, $sprite-names, $%(map_name)s-sprite-base-class, $dimensions);
            }

            // Generates a class for each sprited image.
            @mixin all-%(map_name)s-sprites($dimensions: $%(map_name)s-sprite-dimensions) {
                @include %(map_name)s-sprites(%(sprites)s, $dimensions);
            }
        ''' % {'map_name': map_name, 'sprites': ' '.join(names)}

        return SourceFile.from_string(generated_code)
810534
def _load_cdll(name):
    
    # our custom defined part of the extension file name
    libname = _get_lib_name(name)
    libdir = os.path.join(os.path.dirname(__file__), 'lib')
    libpath = os.path.join(libdir, libname)
    static_fftw = os.path.join(libdir, 'libfftw3-3.dll')
    static_fftwf = os.path.join(libdir, 'libfftw3f-3.dll')
    try:
        fftw_lib = ctypes.CDLL(str(static_fftw))  # noqa: F841
        fftwf_lib = ctypes.CDLL(str(static_fftwf))  # noqa: F841
    except:
        pass
    try:
        cdll = ctypes.CDLL(str(libpath))
    except Exception as e:
        msg = 'Could not load shared library "%s".\n\n %s' % (libname, str(e))
        raise ImportError(msg)
    return cdll
505577
def opt(self, x_init, f_fp=None, f=None, fp=None):
        

        statuses = ['Converged', 'Maximum number of function evaluations made', 'Maximum number of iterations reached']

        opt_dict = {}
        if self.xtol is not None:
            opt_dict['xtol'] = self.xtol
        if self.ftol is not None:
            opt_dict['ftol'] = self.ftol
        if self.gtol is not None:
            print("WARNING: simplex doesn't have an gtol arg, so I'm going to ignore it")

        opt_result = optimize.fmin(f, x_init, (), disp=self.messages,
                   maxfun=self.max_f_eval, full_output=True, **opt_dict)

        self.x_opt = opt_result[0]
        self.f_opt = opt_result[1]
        self.funct_eval = opt_result[3]
        self.status = statuses[opt_result[4]]
        self.trace = None
288505
def fix_ipython_startup(fn):
    
    BADSTR = 'TPython::Exec( "" )'
    GOODSTR = 'TPython::Exec( "" );'
    if sys.version_info[0] < 3:
        consts = fn.im_func.func_code.co_consts
    else:
        consts = fn.__code__.co_consts
    if BADSTR not in consts:
        return
    idx = consts.index(BADSTR)
    orig_refcount = sys.getrefcount(consts)
    del consts

    PyTuple_SetItem = ctypes.pythonapi.PyTuple_SetItem
    PyTuple_SetItem.argtypes = (ctypes.py_object,
                                ctypes.c_size_t,
                                ctypes.py_object)

    if sys.version_info[0] < 3:
        consts = ctypes.py_object(fn.im_func.func_code.co_consts)
    else:
        consts = ctypes.py_object(fn.im_func.__code__.co_consts)

    for _ in range(orig_refcount - 2):
        ctypes.pythonapi.Py_DecRef(consts)
    try:
        ctypes.pythonapi.Py_IncRef(GOODSTR)
        PyTuple_SetItem(consts, idx, GOODSTR)
    finally:
        for _ in range(orig_refcount - 2):
            ctypes.pythonapi.Py_IncRef(consts)
304815
def depends(func):
    
    from jcvi.apps.base import need_update, listify

    infile = "infile"
    outfile = "outfile"

    def wrapper(*args, **kwargs):
        assert outfile in kwargs, \
            "You need to specify `outfile=` on function call"
        if infile in kwargs:
            infilename = listify(kwargs[infile])
            for x in infilename:
                assert op.exists(x), \
                    "The specified infile `{0}` does not exist".format(x)

        outfilename = kwargs[outfile]
        if need_update(infilename, outfilename):
            return func(*args, **kwargs)
        else:
            msg = "File `{0}` exists. Computation skipped." \
                .format(outfilename)
            logging.debug(msg)

        outfilename = listify(outfilename)

        for x in outfilename:
            assert op.exists(x), \
                "Something went wrong, `{0}` not found".format(x)

        return outfilename

    return wrapper
733431
function assemble(fpath, opts, cb) {
  if (!cb && typeof opts == 'function') {
    cb = opts;
    opts = undefined;
  }
  opts = opts || {};
  if (!opts.importHook) {
    opts.importHook = files.createImportHook();
  }

  // Types found in imports. We store them separately to be able to insert them
  // in the correct order in the final attributes.
  var importedTypes = [];
  var attrs, imports;
  opts.importHook(fpath, 'idl', function (err, str) {
    if (err) {
      cb(err);
      return;
    }
    if (!str) {
      // Skipped import (likely already imported).
      cb(null, {});
      return;
    }
    try {
      var protocol = parse(str, opts);
    } catch (err) {
      err.path = fpath; // To help debug which file caused the error.
      cb(err);
      return;
    }
    attrs = protocol.attrs;
    imports = protocol.imports;
    fetchImports();
  });

  function fetchImports() {
    var info = imports.shift();
    if (!info) {
      // We are done with this file. We prepend all imported types to this
      // file's and we can return the final result. We also perform a JSON
      // serialization rountrip to remove non-numerical attributes from unions
      // and transform Javadocs into strings.
      if (importedTypes.length) {
        attrs.types = attrs.types ?
          importedTypes.concat(attrs.types) :
          importedTypes;
      }
      cb(null, JSON.parse(JSON.stringify(attrs)));
    } else {
      var importPath = path.join(path.dirname(fpath), info.name);
      if (info.kind === 'idl') {
        assemble(importPath, opts, mergeImportedAttrs);
      } else {
        // We are importing a protocol or schema file.
        opts.importHook(importPath, info.kind, function (err, str) {
          if (err) {
            cb(err);
            return;
          }
          switch (info.kind) {
            case 'protocol':
            case 'schema':
              try {
                var obj = JSON.parse(str);
              } catch (err) {
                err.path = importPath;
                cb(err);
                return;
              }
              var attrs = info.kind === 'schema' ? {types: [obj]} : obj;
              mergeImportedAttrs(null, attrs);
              break;
            default:
              cb(new Error(f('invalid import kind: %s', info.kind)));
          }
        });
      }
    }
  }

  function mergeImportedAttrs(err, importedAttrs) {
    if (err) {
      cb(err);
      return;
    }
    // Merge  first the types (where we don't need to check for duplicates
    // since `parse` will take care of it), then the messages (where we need
    // to, as duplicates will overwrite each other).
    (importedAttrs.types || []).forEach(function (typeAttrs) {
      // Ensure the imported protocol's namespace is inherited correctly (it
      // might be different from the current one).
      if (typeAttrs.namespace === undefined) {
        var namespace = importedAttrs.namespace;
        if (!namespace) {
          var match = /^(.*)\.[^.]+$/.exec(importedAttrs.protocol);
          if (match) {
            namespace = match[1];
          }
        }
        typeAttrs.namespace = namespace || '';
      }
      importedTypes.push(typeAttrs);
    });
    try {
      Object.keys(importedAttrs.messages || {}).forEach(function (name) {
        if (!attrs.messages) {
          attrs.messages = {};
        }
        if (attrs.messages[name]) {
          throw new Error(f('duplicate message: %s', name));
        }
        attrs.messages[name] = importedAttrs.messages[name];
      });
    } catch (err) {
      cb(err);
      return;
    }
    fetchImports(); // Continue importing any remaining imports.
  }
}
1223545
def _retf(ins):
    
    output = _float_oper(ins.quad[1])
    output.append('#pragma opt require a,bc,de')
    output.append('jp %s' % str(ins.quad[2]))
    return output
1324621
def __import_file(self, f):
        
        directory, module_name = os.path.split(f)
        module_name = os.path.splitext(module_name)[0]

        path = list(sys.path)
        sys.path.insert(0, directory)
        module = __import__(module_name)
        return module
1011939
def _calcOffAxisFactor(self, aLocation, deltaLocation, limits):
        
        relative = []
        for dim in limits.keys():
            f = aLocation[dim]
            v = deltaLocation[dim]
            mB, M, mA = limits[dim]
            r = 0
            if mA is not None and v > mA:
                relative.append(0)
                continue
            elif mB is not None and v < mB:
                relative.append(0)
                continue
            if f < v-_EPSILON:
                if mB is None:
                    if M is not None and mA is not None:
                        if v == M:
                            r = (float(max(f,mA)-min(f, mA))/float(max(M,mA)-min(M, mA)))
                        else:
                            r = -(float(max(f,mA)-min(f, mA))/float(max(M,mA)-min(M, mA)) -1)
                    else: r = 0
                elif mA is None: r = 0
                else: r = float(f-mB)/(mA-mB)
            elif f > v+_EPSILON:
                if mB is None: r = 0
                elif mA is None:
                    if M is not None and mB is not None:
                        if v == M:
                            r = (float(max(f,mB)-min(f, mB))/(max(mB, M)-min(mB, M)))
                        else:
                            r = -(float(max(f,mB)-min(f, mB))/(max(mB, M)-min(mB, M)) - 1)
                    else: r = 0
                else: r = float(mA-f)/(mA-mB)
            else: r = 1
            relative.append(r)
        f = 1
        for i in relative:
            f *= i
        return f
420336
def pickle(self, f, protocol=-1):
        
        try: #Py2
            import cPickle as pickle
            if isinstance(f, basestring):
                with open(f, 'wb') as f:
                    pickle.dump(self, f, protocol)
            else:
                pickle.dump(self, f, protocol)
        except ImportError: #python3
            import pickle
            if isinstance(f, str):
                with open(f, 'wb') as f:
                    pickle.dump(self, f, protocol)
            else:
                pickle.dump(self, f, protocol)