Highest Side Lobe Level (dB).

  Parameters
  ----------
  res :
    Zero-padding factor. 1 for no zero-padding, 2 for twice the length, etc..
  neighbors :
    Number of neighbors needed by ``get_peaks`` to define a peak.
427086
def hsll(wnd, res=20, neighbors=2):
  
  spectrum = dB20(rfft(wnd, res * len(wnd)))
  first_peak = next(get_peaks(spectrum, neighbors=neighbors))
  return max(spectrum[first_peak:]) - spectrum[0]
1134048
def calculateOverlapCurve(sp, inputVectors):
  
  columnNumber = np.prod(sp.getColumnDimensions())
  numInputVector, inputSize = inputVectors.shape

  outputColumns = np.zeros((numInputVector, columnNumber), dtype=uintType)
  outputColumnsCorrupted = np.zeros((numInputVector, columnNumber),
                                    dtype=uintType)

  noiseLevelList = np.linspace(0, 1.0, 21)
  inputOverlapScore = np.zeros((numInputVector, len(noiseLevelList)))
  outputOverlapScore = np.zeros((numInputVector, len(noiseLevelList)))
  for i in range(numInputVector):
    for j in range(len(noiseLevelList)):
      inputVectorCorrupted = copy.deepcopy(inputVectors[i][:])
      corruptSparseVector(inputVectorCorrupted, noiseLevelList[j])

      sp.compute(inputVectors[i][:], False, outputColumns[i][:])
      sp.compute(inputVectorCorrupted, False,
                 outputColumnsCorrupted[i][:])

      inputOverlapScore[i][j] = percentOverlap(inputVectors[i][:],
                                               inputVectorCorrupted)
      outputOverlapScore[i][j] = percentOverlap(outputColumns[i][:],
                                                outputColumnsCorrupted[i][:])

  return noiseLevelList, inputOverlapScore, outputOverlapScore
139244
def extract_source_hypocentral_depths(src):
    
    if "pointSource" not in src.tag and "areaSource" not in src.tag:
        hds = dict([(key, None) for key, _ in HDEPTH_PARAMS])
        hdsw = dict([(key, None) for key, _ in HDW_PARAMS])
        return hds, hdsw

    tags = get_taglist(src)
    hdd_nodeset = src.nodes[tags.index("hypoDepthDist")]
    if len(hdd_nodeset) > MAX_HYPO_DEPTHS:
        raise ValueError("Number of hypocentral depths %s exceeds stated "
                         "maximum of %s" % (str(len(hdd_nodeset)),
                                            str(MAX_HYPO_DEPTHS)))
    if len(hdd_nodeset):
        hds = []
        hdws = []
        for hdd_node in hdd_nodeset:
            hds.append(float(hdd_node.attrib["depth"]))
            hdws.append(float(hdd_node.attrib["probability"]))

        hds = expand_src_param(hds, HDEPTH_PARAMS)
        hdsw = expand_src_param(hdws, HDW_PARAMS)
    else:
        hds = dict([(key, None) for key, _ in HDEPTH_PARAMS])
        hdsw = dict([(key, None) for key, _ in HDW_PARAMS])

    return hds, hdsw
883695
def _extract_peaks(specgram, neighborhood, threshold):
    
    kernel = np.ones(shape=neighborhood)
    local_averages = convolve(specgram, kernel / kernel.sum(), mode="constant", cval=0)

    # suppress all points below the floor value
    floor = (1 + threshold) * local_averages
    candidates = np.where(specgram > floor, specgram, 0)

    # grayscale dilation is equivalent to non-maximal suppression
    local_maximums = grey_dilation(candidates, footprint=kernel)
    peak_coords = np.argwhere(specgram == local_maximums)
    peaks = zip(peak_coords[:, 0], peak_coords[:, 1])

    return peaks
1192102
def highPassFilter(self, threshold):
        '''
        
        '''
        if not threshold:
            return
        rows, cols = self.img.shape
        tx = int(cols * threshold)
        ty = int(rows * threshold)
        # middle:
        crow, ccol = rows // 2, cols // 2
        # square in the middle to zero
        self.fshift[crow - tx:crow + tx, ccol - ty:ccol + ty] = 0
1236484
def dimension_range(lower, upper, hard_range, soft_range, padding=None, log=False):
    
    lower, upper = range_pad(lower, upper, padding, log)
    lower = max_range([(lower, None), (soft_range[0], None)])[0]
    upper = max_range([(None, upper), (None, soft_range[1])])[1]
    dmin, dmax = hard_range
    lower = lower if dmin is None or not isfinite(dmin) else dmin
    upper = upper if dmax is None or not isfinite(dmax) else dmax
    return lower, upper
933648
int[][] findNeighborIndices() {

		// looking at a typical protein case, number of neighbours are from ~10 to ~50, with an average of ~30
		int initialCapacity = 60;

		int[][] nbsIndices = new int[atomCoords.length][];

		for (int k=0; k<atomCoords.length; k++) {
			double radius = radii[k] + probe + probe;

			List<Integer> thisNbIndices = new ArrayList<>(initialCapacity);

			for (int i = 0; i < atomCoords.length; i++) {
				if (i == k) continue;

				double dist = atomCoords[i].distance(atomCoords[k]);

				if (dist < radius + radii[i]) {
					thisNbIndices.add(i);
				}
			}

			int[] indicesArray = new int[thisNbIndices.size()];
			for (int i=0;i<thisNbIndices.size();i++) indicesArray[i] = thisNbIndices.get(i);
			nbsIndices[k] = indicesArray;
		}
		return nbsIndices;
	}
271262
def _fuzzdb_get_strings(max_len=0):
    ''

    ignored = ['integer-overflow']

    for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH):
        if subdir in ignored:
            continue

        path = '{}/{}'.format(BASE_PATH, subdir)
        listing = pkg_resources.resource_listdir('protofuzz', path)
        for filename in listing:
            if not filename.endswith('.txt'):
                continue

            path = '{}/{}/{}'.format(BASE_PATH, subdir, filename)
            source = _open_fuzzdb_file(path)
            for line in source:
                string = line.decode('utf-8').strip()
                if not string or string.startswith('#'):
                    continue
                if max_len != 0 and len(line) > max_len:
                    continue

                yield string
143643
private int rightmostIndexBelowMax() {
		for (int i = r-1; i>=0; i--)
			if (index[i] < n - r + i) return i;
		return -1;
	}
837928
def find_max_rad_npnp(self):
        
        max_rad = 0
        max_npnp = 0
        for res, atoms in self.items():
            if res != 'KEY':
                for atom, ff_params in self[res].items():
                    if max_rad < ff_params[1]:
                        max_rad = ff_params[1]
                    if max_npnp < ff_params[4]:
                        max_npnp = ff_params[4]
        return max_rad, max_npnp
671951
private static void softmax(double[] prob) {
        double max = Double.NEGATIVE_INFINITY;
        for (int i = 0; i < prob.length; i++) {
            if (prob[i] > max) {
                max = prob[i];
            }
        }

        double Z = 0.0;
        for (int i = 0; i < prob.length; i++) {
            double p = Math.exp(prob[i] - max);
            prob[i] = p;
            Z += p;
        }

        for (int i = 0; i < prob.length; i++) {
            prob[i] /= Z;
        }
    }
162832
def neighbors2(self, distance, chain_residue, atom = None, resid_list = None):

        #atom = " CA "
        ''''''

        if atom == None:     # consider all atoms
            lines = [line for line in self.atomlines(resid_list) if line[17:20] in allowed_PDB_residues_types]
        else:                # consider only given atoms
            lines = [line for line in self.atomlines(resid_list) if line[17:20] in allowed_PDB_residues_types and line[12:16] == atom]

        shash = spatialhash.SpatialHash(distance)

        for line in lines:
            pos = (float(line[30:38]), float(line[38:46]), float(line[46:54]))
            shash.insert(pos, line[21:26])

        neighbor_list = []
        for line in lines:
            resid = line[21:26]
            if resid == chain_residue:
                pos = (float(line[30:38]), float(line[38:46]), float(line[46:54]))

                for data in shash.nearby(pos, distance):
                    if data[1] not in neighbor_list:
                        neighbor_list.append(data[1])
                neighbor_list.sort()
        return neighbor_list
930501
function extractRegions(peaks, duration) {
    // Silence params
    var minValue = 0.0015;
    var minSeconds = 0.25;

    var length = peaks.length;
    var coef = duration / length;
    var minLen = minSeconds / coef;

    // Gather silence indeces
    var silences = [];
    Array.prototype.forEach.call(peaks, function(val, index) {
        if (Math.abs(val) <= minValue) {
            silences.push(index);
        }
    });

    // Cluster silence values
    var clusters = [];
    silences.forEach(function(val, index) {
        if (clusters.length && val == silences[index - 1] + 1) {
            clusters[clusters.length - 1].push(val);
        } else {
            clusters.push([val]);
        }
    });

    // Filter silence clusters by minimum length
    var fClusters = clusters.filter(function(cluster) {
        return cluster.length >= minLen;
    });

    // Create regions on the edges of silences
    var regions = fClusters.map(function(cluster, index) {
        var next = fClusters[index + 1];
        return {
            start: cluster[cluster.length - 1],
            end: next ? next[0] : length - 1
        };
    });

    // Add an initial region if the audio doesn't start with silence
    var firstCluster = fClusters[0];
    if (firstCluster && firstCluster[0] != 0) {
        regions.unshift({
            start: 0,
            end: firstCluster[firstCluster.length - 1]
        });
    }

    // Filter regions by minimum length
    var fRegions = regions.filter(function(reg) {
        return reg.end - reg.start >= minLen;
    });

    // Return time-based regions
    return fRegions.map(function(reg) {
        return {
            start: Math.round(reg.start * coef * 10) / 10,
            end: Math.round(reg.end * coef * 10) / 10
        };
    });
}
1033089
def searchExpressionLevelsInDb(
            self, rnaQuantId, names=[], threshold=0.0, startIndex=0,
            maxResults=0):
        
        sql = ("SELECT * FROM Expression WHERE "
               "rna_quantification_id = ? "
               "AND expression > ? ")
        sql_args = (rnaQuantId, threshold)
        if len(names) > 0:
            sql += "AND name in ("
            sql += ",".join(['?' for name in names])
            sql += ") "
            for name in names:
                sql_args += (name,)
        sql += sqlite_backend.limitsSql(
            startIndex=startIndex, maxResults=maxResults)
        query = self._dbconn.execute(sql, sql_args)
        return sqlite_backend.iterativeFetch(query)
12058
def corruptSparseVector(sdr, noiseLevel):
  

  numNoiseBits = int(noiseLevel * np.sum(sdr))
  if numNoiseBits <= 0:
    return sdr
  activeBits = np.where(sdr > 0)[0]
  inActiveBits = np.where(sdr == 0)[0]

  turnOffBits = np.random.permutation(activeBits)
  turnOnBits = np.random.permutation(inActiveBits)
  turnOffBits = turnOffBits[:numNoiseBits]
  turnOnBits = turnOnBits[:numNoiseBits]

  sdr[turnOffBits] = 0
  sdr[turnOnBits] = 1
628829
def lowpass(var, key, factor):
    ''''''
    global lowpass_data
    if not key in lowpass_data:
        lowpass_data[key] = var
    else:
        lowpass_data[key] = factor*lowpass_data[key] + (1.0 - factor)*var
    return lowpass_data[key]
880611
private long[] determinePreferenceVectorByMaxIntersection(ModifiableDBIDs[] neighborIDs, StringBuilder msg) {
    int dimensionality = neighborIDs.length;
    long[] preferenceVector = BitsUtil.zero(dimensionality);

    Map<Integer, ModifiableDBIDs> candidates = new HashMap<>(dimensionality);
    for(int i = 0; i < dimensionality; i++) {
      ModifiableDBIDs s_i = neighborIDs[i];
      if(s_i.size() > minpts) {
        candidates.put(i, s_i);
      }
    }
    if(msg != null) {
      msg.append("\n candidates ").append(candidates.keySet());
    }

    if(!candidates.isEmpty()) {
      int i = max(candidates);
      ModifiableDBIDs intersection = candidates.remove(i);
      BitsUtil.setI(preferenceVector, i);
      while(!candidates.isEmpty()) {
        i = maxIntersection(candidates, intersection);
        candidates.remove(i);
        if(intersection.size() < minpts) {
          break;
        }
        BitsUtil.setI(preferenceVector, i);
      }
    }

    if(msg != null) {
      msg.append("\n preference ").append(BitsUtil.toStringLow(preferenceVector, dimensionality));
      LOG.debug(msg.toString());
    }

    return preferenceVector;
  }