Get intervals for source and target audio files
    
    Use this information to find out how much to stretch/shrink each source
    interval.
    
    The target values are based on the contents of toTGFN.
334612
def getMorphParameters(fromTGFN, toTGFN, tierName,
                       filterFunc=None, useBlanks=False):
    '''
    
    '''
    
    if filterFunc is None:
        filterFunc = lambda entry: True  # Everything is accepted
    
    fromEntryList = utils.getIntervals(fromTGFN, tierName,
                                       includeUnlabeledRegions=useBlanks)
    toEntryList = utils.getIntervals(toTGFN, tierName,
                                     includeUnlabeledRegions=useBlanks)

    fromEntryList = [entry for entry in fromEntryList if filterFunc(entry)]
    toEntryList = [entry for entry in toEntryList if filterFunc(entry)]

    assert(len(fromEntryList) == len(toEntryList))

    durationParameters = []
    for fromEntry, toEntry in zip(fromEntryList, toEntryList):
        fromStart, fromEnd = fromEntry[:2]
        toStart, toEnd = toEntry[:2]

        # Praat will ignore a second value appearing at the same time as
        # another so we give each start a tiny offset to distinguish intervals
        # that start and end at the same point
        toStart += PRAAT_TIME_DIFF
        fromStart += PRAAT_TIME_DIFF
        
        ratio = (toEnd - toStart) / float((fromEnd - fromStart))
        durationParameters.append((fromStart, fromEnd, ratio))
    
    return durationParameters
258646
def main(input_filename, format):
    

    # open the file & convert to wav
    song_data = AudioSegment.from_file(input_filename, format=format)
    song_data = song_data.set_channels(1)  # convert to mono
    wav_tmp = song_data.export(format="wav")  # write to a tmp file buffer
    wav_tmp.seek(0)
    rate, wav_data = wavfile.read(wav_tmp)

    rows_per_second = (1 + (rate - WIDTH)) // FRAME_STRIDE

    # Calculate a coarser window for matching
    window_size = (rows_per_second // TIME_STRIDE, (WIDTH // 2) // FREQ_STRIDE)
    peaks = resound.get_peaks(np.array(wav_data), window_size=window_size)

    # half width (nyquist freq) & half size (window is +/- around the middle)
    f_width = WIDTH // (2 * FREQ_STRIDE) * 2
    t_gap = 1 * rows_per_second
    t_width = 2 * rows_per_second
    fingerprints = resound.hashes(peaks, f_width=f_width, t_gap=t_gap, t_width=t_width)  # hash, offset pairs

    return fingerprints
334987
function(source, target) {
  const sourceLen = source.length;
  const targetLen = target.length;
  let sourceSegment,
    targetSegment;
  let temp = 0;
  if (sourceLen === 0 || targetLen === 0) {
    return null;
  }
  const dist = [];
  for (let i = 0; i <= sourceLen; i++) {
    dist[i] = [];
    dist[i][0] = { min: i };
  }
  for (let j = 0; j <= targetLen; j++) {
    dist[0][j] = { min: j };
  }

  for (let i = 1; i <= sourceLen; i++) {
    sourceSegment = source[i - 1];
    for (let j = 1; j <= targetLen; j++) {
      targetSegment = target[j - 1];
      if (isEqual(sourceSegment, targetSegment)) {
        temp = 0;
      } else {
        temp = 1;
      }
      const del = dist[i - 1][j].min + 1;
      const add = dist[i][j - 1].min + 1;
      const modify = dist[i - 1][j - 1].min + temp;
      dist[i][j] = getMinDiff(del, add, modify);
    }
  }
  return dist;
}
687379
function compareContents(stream, sourceFile, targetPath) {
	return readFile(targetPath)
		.then(targetData => {
			if (sourceFile.isNull() || !sourceFile.contents.equals(targetData)) {
				stream.push(sourceFile);
			}
		});
}
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
        };
    });
}
506029
private long getJitterFreePTS(long bufferPts, long bufferSamplesNum) {
        long correctedPts = 0;
        long bufferDuration = (1000000 * bufferSamplesNum) / (mEncoderCore.mSampleRate);
        bufferPts -= bufferDuration; // accounts for the delay of acquiring the audio buffer
        if (totalSamplesNum == 0) {
            // reset
            startPTS = bufferPts;
            totalSamplesNum = 0;
        }
        correctedPts = startPTS +  (1000000 * totalSamplesNum) / (mEncoderCore.mSampleRate);
        if(bufferPts - correctedPts >= 2*bufferDuration) {
            // reset
            startPTS = bufferPts;
            totalSamplesNum = 0;
            correctedPts = startPTS;
        }
        totalSamplesNum += bufferSamplesNum;
        return correctedPts;
    }
1255595
private SourceRefRange findSourceRefRange(List<Reference> refList,
      InputId inputId) {
    checkNotNull(inputId);

    // TODO(bashir): We can do binary search here, but since this is fast enough
    // right now, we just do a linear search for simplicity.
    int lastBefore = -1;
    int firstAfter = refList.size();
    int index = 0;

    checkState(inputOrder.containsKey(inputId), inputId.getIdName());
    int sourceInputOrder = inputOrder.get(inputId);
    for (Reference ref : refList) {
      checkNotNull(ref.getInputId());
      int order = inputOrder.get(ref.getInputId());
      if (order < sourceInputOrder) {
        lastBefore = index;
      } else if (order > sourceInputOrder) {
        firstAfter = index;
        break;
      }
      index++;
    }
    return new SourceRefRange(refList, lastBefore, firstAfter);
  }
1002216
@Override
    public AudioInputStream getAudioInputStream(AudioFormat.Encoding targetEncoding, AudioInputStream audioInputStream) {
        AudioFormat sourceFormat = audioInputStream.getFormat();
        AudioFormat targetFormat = new AudioFormat(
                targetEncoding,
                AudioSystem.NOT_SPECIFIED, // sample rate
                AudioSystem.NOT_SPECIFIED, // sample size in bits
                AudioSystem.NOT_SPECIFIED, // channels
                AudioSystem.NOT_SPECIFIED, // frame size
                AudioSystem.NOT_SPECIFIED, // frame rate
                sourceFormat.isBigEndian());  // big endian
        LOG.log(Level.FINE, "TFormatConversionProvider.getAudioInputStream(AudioFormat.Encoding, AudioInputStream):");
        LOG.log(Level.FINE, "trying to convert to {0}", targetFormat);
        return getAudioInputStream(targetFormat, audioInputStream);
    }
86781
def _get_content_range(start: Optional[int], end: Optional[int], total: int) -> str:
    
    start = start or 0
    end = (end or total) - 1
    return "bytes %s-%s/%s" % (start, end, total)
327547
def relocate_audio_to_wav_files(self, target_path):
        

        if not os.path.isdir(target_path):
            os.makedirs(target_path)

        new_tracks = {}

        # First create a new container track for all existing tracks
        for track in self.tracks.values():
            track_path = os.path.join(target_path, '{}.wav'.format(track.idx))
            sr = track.sampling_rate
            samples = track.read_samples()

            audio.write_wav(track_path, samples, sr=sr)
            new_track = tracks.FileTrack(track.idx, track_path)

            new_tracks[track.idx] = new_track

        # Update track list of corpus
        self._tracks = new_tracks

        # Update utterances to point to new tracks
        for utterance in self.utterances.values():
            new_track = self.tracks[utterance.track.idx]
            utterance.track = new_track
1281770
def find_speech_regions(filename, frame_width=4096, min_region_size=0.5, max_region_size=6): # pylint: disable=too-many-locals
    
    reader = wave.open(filename)
    sample_width = reader.getsampwidth()
    rate = reader.getframerate()
    n_channels = reader.getnchannels()
    chunk_duration = float(frame_width) / rate

    n_chunks = int(math.ceil(reader.getnframes()*1.0 / frame_width))
    energies = []

    for _ in range(n_chunks):
        chunk = reader.readframes(frame_width)
        energies.append(audioop.rms(chunk, sample_width * n_channels))

    threshold = percentile(energies, 0.2)

    elapsed_time = 0

    regions = []
    region_start = None

    for energy in energies:
        is_silence = energy <= threshold
        max_exceeded = region_start and elapsed_time - region_start >= max_region_size

        if (max_exceeded or is_silence) and region_start:
            if elapsed_time - region_start >= min_region_size:
                regions.append((region_start, elapsed_time))
                region_start = None

        elif (not region_start) and (not is_silence):
            region_start = elapsed_time
        elapsed_time += chunk_duration
    return regions
1093060
def targets(tgt, tgt_type='glob', **kwargs):  # pylint: disable=W0613
    '''
    
    '''
    roster_file = os.path.abspath('terraform.tfstate')
    if __opts__.get('roster_file'):
        roster_file = os.path.abspath(__opts__['roster_file'])

    if not os.path.isfile(roster_file):
        log.error("Can't find terraform state file '%s'", roster_file)
        return {}

    log.debug('terraform roster: using %s state file', roster_file)

    if not roster_file.endswith('.tfstate'):
        log.error("Terraform roster can only be used with terraform state files")
        return {}

    raw = _parse_state_file(roster_file)
    log.debug('%s hosts in terraform state file', len(raw))
    return __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4')
58369
def _sc_encode(gain, peak):
    
    # SoundCheck stores the peak value as the actual value of the
    # sample, rather than the percentage of full scale that RG uses, so
    # we do a simple conversion assuming 16 bit samples.
    peak *= 32768.0

    # SoundCheck stores absolute RMS values in some unknown units rather
    # than the dB values RG uses. We can calculate these absolute values
    # from the gain ratio using a reference value of 1000 units. We also
    # enforce the maximum value here, which is equivalent to about
    # -18.2dB.
    g1 = int(min(round((10 ** (gain / -10)) * 1000), 65534))
    # Same as above, except our reference level is 2500 units.
    g2 = int(min(round((10 ** (gain / -10)) * 2500), 65534))

    # The purpose of these values are unknown, but they also seem to be
    # unused so we just use zero.
    uk = 0
    values = (g1, g1, g2, g2, uk, uk, int(peak), int(peak), uk, uk)
    return (u' %08X' * 10) % values
656048
public String getStatValueAsString(T metric, String interval) {
        if (metric.isRateMetric()) {
            return String.valueOf(getStatValueAsDouble(metric, interval));
        }
        return getMonitoredStatValue(metric).getValueAsString(interval);
    }
399701
def getSoundFileDuration(fn):
    '''
    
    '''
    audiofile = wave.open(fn, "r")
    
    params = audiofile.getparams()
    framerate = params[2]
    nframes = params[3]
    
    duration = float(nframes) / framerate
    return duration
936557
def download(self, target_relpath, download_in_toto_metadata=True):
        '''
        
        '''
        return self.__get_target(target_relpath, download_in_toto_metadata=download_in_toto_metadata)
654120
function checkThresholds(metrics, thresholds) {
  if (!elv(thresholds)) return;

  const target = metrics[thresholds.target];

  for (let i = 0; i < metrics.length; i++) {
    if (i === thresholds.target) continue;

    const other = metrics[i];
    assertThreshold(target.avg, other.avg, thresholds.avg);
    assertThreshold(target.max, other.max, thresholds.max);
    assertThreshold(target.min, other.min, thresholds.min);
  }
}