Extract the number of ruptures and set it
332394
def get_set_num_ruptures(src):
    
    if not src.num_ruptures:
        t0 = time.time()
        src.num_ruptures = src.count_ruptures()
        dt = time.time() - t0
        clsname = src.__class__.__name__
        if dt > 10:
            if 'Area' in clsname:
                logging.warning(
                    '%s.count_ruptures took %d seconds, perhaps the '
                    'area discretization is too small', src, dt)
            elif 'ComplexFault' in clsname:
                logging.warning(
                    '%s.count_ruptures took %d seconds, perhaps the '
                    'complex_fault_mesh_spacing is too small', src, dt)
            elif 'SimpleFault' in clsname:
                logging.warning(
                    '%s.count_ruptures took %d seconds, perhaps the '
                    'rupture_mesh_spacing is too small', src, dt)
            else:
                # multiPointSource
                logging.warning('count_ruptures %s took %d seconds', src, dt)
    return src.num_ruptures
326212
def numberofsamples(self):
        """"""
        # Initialise variables to store line data
        idline = 0
        linenumber = 0
        # Parse the sample sheet to find the number of samples
        with open(self.samplesheet, "rb") as ssheet:
            # Use enumerate to iterate through the lines in the sample sheet to retrieve the line number and the data
            for linenumber, entry in enumerate(ssheet):
                # Once Sample_ID is encountered
                if "Sample_ID" in entry:
                    # Set the id line as the current line number
                    idline = linenumber
        # :samplecount is the last line number in the file minus the line number of Sample_ID
        self.samplecount = linenumber - idline
        printtime('There are {} samples in this run. '
                  'Running off-hours module with the following parameters:\n'
                  'MiSeqPath: {},\n'
                  'MiSeqFolder: {},\n'
                  'SampleSheet: {}'.format(self.samplecount, self.miseqpath, self.miseqfolder, self.samplesheet),
                  self.start)
        # Run the fastqmover module now that the number of sequences is known
        self.fastqlinker()
438636
def num_failures(self):
        
        min_time = time.time() - self.window

        while self.failures and self.failures[0] < min_time:
            self.failures.popleft()

        return len(self.failures)
900690
def each
      if block_given?
        length.times do |n|
          yield build_coordinate(n)
        end
        self
      else
        length.times.collect { |n|
          build_coordinate(n)
        }.to_enum
      end
    end
1212565
def sizes(count, offset=0, max_chunk=500):
    
    if count is None:
        chunk = max_chunk
        while True:
            yield chunk, offset
            offset += chunk
    else:
        while count:
            chunk = min(count, max_chunk)
            count = max(0, count - max_chunk)
            yield chunk, offset
            offset += chunk
192344
def init(self):
        
        if hasattr(self, 'computers'):  # init already called
            return
        with hdf5.File(self.rupgetter.filename, 'r') as parent:
            self.weights = parent['weights'].value
        self.computers = []
        for ebr in self.rupgetter.get_ruptures(self.srcfilter):
            sitecol = self.sitecol.filtered(ebr.sids)
            try:
                computer = calc.gmf.GmfComputer(
                    ebr, sitecol, self.oqparam.imtls, self.cmaker,
                    self.oqparam.truncation_level, self.correl_model)
            except FarAwayRupture:
                # due to numeric errors, ruptures within the maximum_distance
                # when written, can be outside when read; I found a case with
                # a distance of 99.9996936 km over a maximum distance of 100 km
                continue
            self.computers.append(computer)
1006516
function(err, r) {
      if (err) {
        numberOfValidConnections = numberOfValidConnections - 1;
        errorObject = err;
        return false;
      } else if (r.result['$err']) {
        errorObject = r.result;
        return false;
      } else if (r.result['errmsg']) {
        errorObject = r.result;
        return false;
      } else {
        numberOfValidConnections = numberOfValidConnections + 1;
      }

      return true;
    }
915825
def _initialize(self, funs_to_tally, length):
        """"""

        chain = self.nchains
        self._chains[chain] = self._h5file.create_group(
            '/', 'chain%d' % chain, 'chain #%d' % chain)

        for name, fun in six.iteritems(funs_to_tally):

            arr = np.asarray(fun())

            assert arr.dtype != np.dtype('object')

            array = self._h5file.createEArray(
                self._chains[chain], name,
                tables.Atom.from_dtype(arr.dtype), (0,) + arr.shape,
                filters=self.filter)

            self._arrays[chain, name] = array
            self._traces[name] = Trace(name, getfunc=fun, db=self)
            self._traces[name]._initialize(self.chains, length)

        self.trace_names.append(list(funs_to_tally.keys()))
1358116
def _get_var_array(self, k, use_raw=False, layer='X'):
        """"""
        in_raw_obs_names = k in self.raw.obs_names if self.raw is not None else False

        if use_raw and self.raw is None:
            raise ValueError('.raw doesn\'t exist')

        if k in self.var.keys():
            x = self._var[k]
        elif in_raw_obs_names and use_raw and layer == 'X':
            x = self.raw[k].X
        elif k in self.obs_names and not use_raw and (layer == 'X' or layer in self.layers.keys()):
            x = self[k].X if layer=='X' else self[k].layers[layer]
        elif use_raw and layer != 'X':
            raise ValueError('No layers in .raw')
        elif layer != 'X' and layer not in self.layers.keys():
            raise ValueError('Did not find {} in layers.keys.'
                             .format(layer))
        else:
            raise ValueError('Did not find {} in var.keys or obs_names.'
                             .format(k))
        return x
2352
def extract_multiple(record, field, tag)
     a = Array.new
     record.fields(field).each do |field|
       a.push field[tag]
     end
     return a
   end
323165
def _get_top_of_rupture_depth_term(self, C, imt, rup):
        
        if rup.ztor >= 20.0:
            return C['a15']
        else:
            return C['a15'] * rup.ztor / 20.0
1136189
function(){
        while(this.numPairs>0){
            var pair=this.pairs[--this.numPairs];
            pair.shape1=null;
            pair.shape2=null;
        }
        this.numPairChecks=0;
        this.collectPairs();
    }
562426
async def _setops(self, name, valu, editatom, init=False):
        '''
        
        '''
        prop = self.form.prop(name)
        if prop is None:

            if self.snap.strict:
                raise s_exc.NoSuchProp(name=name)

            await self.snap.warn(f'NoSuchProp: name={name}')
            return False

        if self.isrunt:
            if prop.info.get('ro'):
                raise s_exc.IsRuntForm(mesg='Cannot set read-only props on runt nodes',
                                       form=self.form.full, prop=name, valu=valu)
            return await self.snap.core.runRuntPropSet(self, prop, valu)

        curv = self.props.get(name)

        # normalize the property value...
        try:
            norm, info = prop.type.norm(valu)

        except Exception as e:
            mesg = f'Bad property value: {prop.full}={valu!r}'
            return await self.snap._raiseOnStrict(s_exc.BadPropValu, mesg, name=prop.name, valu=valu, emesg=str(e))

        # do we already have the value?
        if curv == norm:
            return False

        if curv is not None and not init:

            if prop.info.get('ro'):

                if self.snap.strict:
                    raise s_exc.ReadOnlyProp(name=prop.full)

                # not setting a set-once prop unless we are init...
                await self.snap.warn(f'ReadOnlyProp: name={prop.full}')
                return False

            # check for type specific merging...
            norm = prop.type.merge(curv, norm)
            if curv == norm:
                return False

        sops = prop.getSetOps(self.buid, norm)

        editatom.sops.extend(sops)

        # self.props[prop.name] = norm
        editatom.npvs.append((self, prop, curv, norm))

        # do we have any auto nodes to add?
        auto = self.snap.model.form(prop.type.name)
        if auto is not None:
            buid = s_common.buid((auto.name, norm))
            await self.snap._addNodeFnibOps((auto, norm, info, buid), editatom)

        # does the type think we have special auto nodes to add?
        # ( used only for adds which do not meet the above block )
        for autoname, autovalu in info.get('adds', ()):
            auto = self.snap.model.form(autoname)
            autonorm, autoinfo = auto.type.norm(autovalu)
            buid = s_common.buid((auto.name, autonorm))
            await self.snap._addNodeFnibOps((auto, autovalu, autoinfo, buid), editatom)

        # do we need to set any sub props?
        subs = info.get('subs')
        if subs is not None:

            for subname, subvalu in subs.items():

                full = prop.name + ':' + subname

                subprop = self.form.prop(full)
                if subprop is None:
                    continue

                await self._setops(full, subvalu, editatom, init=init)

        return True
823969
def get_recurrence(self, config):
        '''
        
        '''
        model = MFD_MAP[config['Model_Name']]()
        model.setUp(config)
        model.get_mmax(config, self.msr, self.rake, self.area)
        model.mmax = model.mmax + (self.msr_sigma * model.mmax_sigma)
        # As the Anderson & Luco arbitrary model requires the input of the
        # displacement to length ratio

        if 'AndersonLucoAreaMmax' in config['Model_Name']:
            if not self.disp_length_ratio:
                # If not defined then default to 1.25E-5
                self.disp_length_ratio = 1.25E-5
            min_mag, bin_width, occur_rates = model.get_mfd(
                self.slip,
                self.area, self.shear_modulus, self.disp_length_ratio)

        else:
            min_mag, bin_width, occur_rates = model.get_mfd(self.slip,
                                                            self.area,
                                                            self.shear_modulus)

        self.recurrence = IncrementalMFD(min_mag, bin_width, occur_rates)
        self.magnitudes = min_mag + np.cumsum(
            bin_width *
            np.ones(len(occur_rates), dtype=float)) - bin_width
        self.max_mag = np.max(self.magnitudes)
369852
def varange(starts, count):
    
    try:
        return stack(arange(s, s + count) for s in starts)
    except TypeError:
        return arange(starts, starts + count)
1089284
def extract_rupture(dstore, serial):
    
    ridx = list(dstore['ruptures']['serial']).index(int(serial))
    [getter] = getters.gen_rupture_getters(dstore, slice(ridx, ridx + 1))
    yield from getter.get_rupdict().items()
998916
def select_catalogue(self, selector, distance, distance_metric="rupture",
                         upper_eq_depth=None, lower_eq_depth=None):
        
        if selector.catalogue.get_number_events() < 1:
            raise ValueError('No events found in catalogue!')

        # rupture metric is selected
        if ('rupture' in distance_metric):
            # Use rupture distance
            self.catalogue = selector.within_rupture_distance(
                self.geometry.surface,
                distance,
                upper_depth=upper_eq_depth,
                lower_depth=lower_eq_depth)
        else:
            # Use Joyner-Boore distance
            self.catalogue = selector.within_joyner_boore_distance(
                self.geometry.surface,
                distance,
                upper_depth=upper_eq_depth,
                lower_depth=lower_eq_depth)