Display loudness scan results.
968309
def show_scan_report(audio_filepaths, album_dir, r128_data):
  
  # track loudness/peak
  for audio_filepath in audio_filepaths:
    try:
      loudness, peak = r128_data[audio_filepath]
    except KeyError:
      loudness, peak = "SKIPPED", "SKIPPED"
    else:
      loudness = "%.1f LUFS" % (loudness)
      if peak is None:
        peak = "-"
      else:
        peak = "%.1f dBFS" % (scale_to_gain(peak))
    logger().info("File '%s': loudness = %s, sample peak = %s" % (audio_filepath, loudness, peak))

  # album loudness/peak
  if album_dir:
    try:
      album_loudness, album_peak = r128_data[ALBUM_GAIN_KEY]
    except KeyError:
      album_loudness, album_peak = "SKIPPED", "SKIPPED"
    else:
      album_loudness = "%.1f LUFS" % (album_loudness)
      if album_peak is None:
        album_peak = "-"
      else:
        album_peak = "%.1f dBFS" % (scale_to_gain(album_peak))
    logger().info("Album '%s': loudness = %s, sample peak = %s" % (album_dir, album_loudness, album_peak))
321060
def _check_freqs(parts, indexes):
    
    thresh_ratio = 2.7
    try:  # FreeBayes
        ao_index = parts[8].split(":").index("AO")
        ro_index = parts[8].split(":").index("RO")
    except ValueError:
        ao_index, ro_index = None, None
    try:  # VarDict
        af_index = parts[8].split(":").index("AF")
    except ValueError:
        af_index = None
    if af_index is None and ao_index is None:
        # okay to skip if a gVCF record
        if parts[4].find("<*>") == -1:
            raise NotImplementedError("Unexpected format annotations: %s" % parts[8])
    def _calc_freq(item):
        try:
            if ao_index is not None and ro_index is not None:
                ao = sum([int(x) for x in item.split(":")[ao_index].split(",")])
                ro = int(item.split(":")[ro_index])
                freq = ao / float(ao + ro)
            elif af_index is not None:
                freq = float(item.split(":")[af_index])
            else:
                freq = 0.0
        except (IndexError, ValueError, ZeroDivisionError):
            freq = 0.0
        return freq
    tumor_freq, normal_freq = _calc_freq(parts[indexes["tumor"]]), _calc_freq(parts[indexes["normal"]])
    return normal_freq <= 0.001 or normal_freq <= tumor_freq / thresh_ratio
1258491
def sound_pressure_low(self):
        
        self._ensure_mode(self.MODE_DBA)
        return self.value(0) * self._scale('DBA')
534223
private void outputSamples() {
        int samples;
        while ((samples = vorbisDspState.synthesis_pcmout(_pcmf, _index)) > 0) {
            float[][] pcmf = _pcmf[0];
            bout = (samples < convsize ? samples : convsize);
            // convert doubles to 16 bit signed ints (host order) and
            // interleave
            for (i = 0; i < vorbisInfo.channels; i++) {
                int pointer = i * 2;
                //int ptr=i;
                int mono = _index[i];
                for (int j = 0; j < bout; j++) {
                    double fVal = pcmf[i][mono + j] * 32767.;
                    int val = (int) (fVal);
                    if (val > 32767) {
                        val = 32767;
                    }
                    if (val < -32768) {
                        val = -32768;
                    }
                    if (val < 0) {
                        val = val | 0x8000;
                    }
                    convbuffer[pointer] = (byte) (val);
                    convbuffer[pointer + 1] = (byte) (val >>> 8);
                    pointer += 2 * (vorbisInfo.channels);
                }
            }
            LOG.log(Level.FINE, "about to write: {0}", 2 * vorbisInfo.channels * bout);
            if (getCircularBuffer().availableWrite() < 2 * vorbisInfo.channels * bout) {
                LOG.log(Level.FINE, "Too much data in this data packet, better return, let the channel drain, and try again...");
                playState = playState_BufferFull;
                return;
            }
            getCircularBuffer().write(convbuffer, 0, 2 * vorbisInfo.channels * bout);
            if (bytes < bufferSize_) {
                LOG.log(Level.FINE, "Finished with final buffer of music?");
            }
            if (vorbisDspState.synthesis_read(bout) != 0) {
                LOG.log(Level.FINE, "VorbisDspState.synthesis_read returned -1.");
            }
        } // while(samples...)
        playState = playState_ReadData;
    }
477717
def parse_loudnorm_stats(self):
        
        logger.info(
            "Running first pass loudnorm filter for stream {}".format(self.stream_id)
        )

        opts = {
            'i': self.media_file.ffmpeg_normalize.target_level,
            'lra': self.media_file.ffmpeg_normalize.loudness_range_target,
            'tp': self.media_file.ffmpeg_normalize.true_peak,
            'offset': self.media_file.ffmpeg_normalize.offset,
            'print_format': 'json'
        }

        if self.media_file.ffmpeg_normalize.dual_mono:
            opts['dual_mono'] = 'true'

        filter_str = '[0:{}]'.format(self.stream_id) + \
            'loudnorm=' + dict_to_filter_opts(opts)

        cmd = [
            self.media_file.ffmpeg_normalize.ffmpeg_exe, '-nostdin', '-y',
            '-i', self.media_file.input_file,
            '-filter_complex', filter_str,
            '-vn', '-sn', '-f', 'null', NUL
        ]

        cmd_runner = CommandRunner(cmd)
        for progress in cmd_runner.run_ffmpeg_command():
            yield progress
        output = cmd_runner.get_output()

        logger.debug("Loudnorm first pass command output:")
        logger.debug(output)

        output_lines = [line.strip() for line in output.split('\n')]
        loudnorm_start = False
        loudnorm_end = False
        for index, line in enumerate(output_lines):
            if line.startswith('[Parsed_loudnorm'):
                loudnorm_start = index + 1
                continue
            if loudnorm_start and line.startswith('}'):
                loudnorm_end = index + 1
                break

        if not (loudnorm_start and loudnorm_end):
            raise FFmpegNormalizeError("Could not parse loudnorm stats; no loudnorm-related output found")

        try:
            loudnorm_stats = json.loads('\n'.join(output_lines[loudnorm_start:loudnorm_end]))
        except Exception as e:
            raise FFmpegNormalizeError("Could not parse loudnorm stats; wrong JSON format in string: {}".format(e))

        logger.debug("Loudnorm stats parsed: {}".format(json.dumps(loudnorm_stats)))

        self.loudness_statistics['ebu'] = loudnorm_stats
        for key, val in self.loudness_statistics['ebu'].items():
            if key == 'normalization_type':
                continue
            # FIXME: drop Python 2 support and just use math.inf
            if float(val) == -float("inf"):
                self.loudness_statistics['ebu'][key] = -99
            elif float(val) == float("inf"):
                self.loudness_statistics['ebu'][key] = 0
886075
def showMonitors(cls):
        
        Debug.info("*** monitor configuration [ {} Screen(s)] ***".format(cls.getNumberScreens()))
        Debug.info("*** Primary is Screen {}".format(cls.primaryScreen))
        for index, screen in enumerate(PlatformManager.getScreenDetails()):
            Debug.info("Screen {}: ({}, {}, {}, {})".format(index, *screen["rect"]))
        Debug.info("*** end monitor configuration ***")
160695
def busy_display():
    """"""
    sys.stdout.write("\033[?25l")  # cursor off
    sys.stdout.flush()
    for x in range(1800):
        symb = ['\\', '|', '/', '-']
        sys.stdout.write("\033[D{}".format(symb[x % 4]))
        sys.stdout.flush()
        gevent.sleep(0.1)
148954
def auto_qc(dset,inside_perc=60,atlas=None,p=0.001):
    ''''''
    with nl.notify('Running quality check on %s:' % dset):
        if not os.path.exists(dset):
            nl.notify('Error: cannot find the file!',level=nl.level.error)
            return False
        
        info = nl.dset_info(dset)
        if not info:
            nl.notify('Error: could not read the dataset!',level=nl.level.error)
        
        if any(['stat' in x for x in info.subbricks]):
            with nl.notify('Statistical results detected...'):
                inside = inside_brain(dset,atlas=atlas,p=p)
                nl.notify('%.1f significant voxels inside brain')
                if inside<inside_perc:
                    nl.notify('Warning: below quality threshold!',level=nl.level.warning)
#                    return False
                nl.notify('Looks ok')
                return inside
        
        if len(info.subbricks)>1:
            with nl.notify('Time-series detected...'):
                return_val = True
                (cost,overlap) = atlas_overlap(dset)
                if cost>0.15 or overlap<80:
                    nl.notify('Warning: does not appear to conform to brain dimensions',level=nl.level.warning)
                    return_val = False
                if len(info.subbricks)>5:
                    (oc,perc_outliers) = outcount(dset)
                    if perc_outliers>0.1:
                        nl.notify('Warning: large amount of outlier time points',level=nl.level.warning)
                        return_val = False
            if return_val:
                nl.notify('Looks ok')
                return min(100*(1-cost),overlap,100*perc_outliers)
            return False
        
        with nl.notify('Single brain image detected...'):
            (cost,overlap) = atlas_overlap(dset)
            # Be more lenient if it's not an EPI, cuz who knows what else is in this image
            if cost>0.45 or overlap<70:
                nl.notify('Warning: does not appear to conform to brain dimensions',level=nl.level.warning)
                return False
            nl.notify('Looks ok')
            return min(100*(1-cost),overlap)
1276704
async def sound(dev: Device, target, value):
    """"""
    if target and value:
        click.echo("Setting %s to %s" % (target, value))
        click.echo(await dev.set_sound_settings(target, value))

    print_settings(await dev.get_sound_settings())
166162
def display(self, stats, cs_status=None):
        
        # Init the internal line/column for Glances Curses
        self.init_line_column()

        # Get the current screen size
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        stats_max = screen_y - 3
        stats_len = len(stats)

        self._page_max_lines = stats_max
        self._page_max = int(math.ceil(stats_len / stats_max))
        # Init position
        x = 0
        y = 0

        # Display top header
        if stats_len == 0:
            if self.first_scan and not self.args.disable_autodiscover:
                msg = 'Glances is scanning your network. Please wait...'
                self.first_scan = False
            else:
                msg = 'No Glances server available'
        elif len(stats) == 1:
            msg = 'One Glances server available'
        else:
            msg = '{} Glances servers available'.format(stats_len)
        if self.args.disable_autodiscover:
            msg += ' (auto discover is disabled)'
        if screen_y > 1:
            self.term_window.addnstr(y, x,
                                     msg,
                                     screen_x - x,
                                     self.colors_list['TITLE'])

            msg = '{}'.format(self._get_status_count(stats))
            self.term_window.addnstr(y + 1, x,
                                     msg,
                                     screen_x - x)

        if stats_len > stats_max and screen_y > 2:
            msg = '{} servers displayed.({}/{}) {}'.format(self.get_pagelines(stats),
                                                            self._current_page + 1, 
                                                            self._page_max, 
                                                            self._get_status_count(stats))
            self.term_window.addnstr(y + 1, x,
                                     msg,
                                     screen_x - x)
        
        if stats_len == 0:
            return False

        # Display the Glances server list
        # ================================

        # Table of table
        # Item description: [stats_id, column name, column size]
        column_def = [
            ['name', 'Name', 16],
            ['alias', None, None],
            ['load_min5', 'LOAD', 6],
            ['cpu_percent', 'CPU%', 5],
            ['mem_percent', 'MEM%', 5],
            ['status', 'STATUS', 9],
            ['ip', 'IP', 15],
            # ['port', 'PORT', 5],
            ['hr_name', 'OS', 16],
        ]
        y = 2

        # Display table header
        xc = x + 2
        for cpt, c in enumerate(column_def):
            if xc < screen_x and y < screen_y and c[1] is not None:
                self.term_window.addnstr(y, xc,
                                         c[1],
                                         screen_x - x,
                                         self.colors_list['BOLD'])
                xc += c[2] + self.space_between_column
        y += 1

        # If a servers has been deleted from the list...
        # ... and if the cursor is in the latest position
        if self.cursor > len(stats) - 1:
            # Set the cursor position to the latest item
            self.cursor = len(stats) - 1

        stats_list = self._get_stats(stats)
        start_line = self._page_max_lines * self._current_page 
        end_line = start_line + self.get_pagelines(stats_list)
        current_page = stats_list[start_line:end_line]
        
        # Display table
        line = 0
        for v in current_page:
            # Limit the number of displayed server (see issue #1256)
            if line >= stats_max:
                continue
            # Get server stats
            server_stat = {}
            for c in column_def:
                try:
                    server_stat[c[0]] = v[c[0]]
                except KeyError as e:
                    logger.debug(
                        "Cannot grab stats {} from server (KeyError: {})".format(c[0], e))
                    server_stat[c[0]] = '?'
                # Display alias instead of name
                try:
                    if c[0] == 'alias' and v[c[0]] is not None:
                        server_stat['name'] = v[c[0]]
                except KeyError:
                    pass

            # Display line for server stats
            cpt = 0
            xc = x

            # Is the line selected ?
            if line == self.cursor:
                # Display cursor
                self.term_window.addnstr(
                    y, xc, ">", screen_x - xc, self.colors_list['BOLD'])

            # Display the line
            xc += 2
            for c in column_def:
                if xc < screen_x and y < screen_y and c[1] is not None:
                    # Display server stats
                    self.term_window.addnstr(
                        y, xc, format(server_stat[c[0]]), c[2], self.colors_list[v['status']])
                    xc += c[2] + self.space_between_column
                cpt += 1
            # Next line, next server...
            y += 1
            line += 1

        return True
829342
def scan(self):
        """"""
        devices = []
        diff = 65
        rom = False
        count = 0
        for _ in range(0xff):
            rom, diff = self._search_rom(rom, diff)
            if rom:
                count += 1
                if count > self.maximum_devices:
                    raise RuntimeError(
                        "Maximum device count of {} exceeded."\
                        .format(self.maximum_devices))
                devices.append(OneWireAddress(rom))
            if diff == 0:
                break
        return devices
98886
def has_loudness_tag(filepath):
  
  track, album = False, False

  try:
    mf = mutagen.File(filepath)
  except mutagen.MutagenError as e:
    logger().warning("File '%s' %s: %s" % (filepath,
                                           e.__class__.__qualname__,
                                           e))
    return

  if (isinstance(mf.tags, mutagen.id3.ID3) or
          isinstance(mf, mutagen.id3.ID3FileType)):
    track = ("TXXX:REPLAYGAIN_TRACK_GAIN" in mf) and ("TXXX:REPLAYGAIN_TRACK_PEAK" in mf)
    album = ("TXXX:REPLAYGAIN_ALBUM_GAIN" in mf) and ("TXXX:REPLAYGAIN_ALBUM_PEAK" in mf)

  elif isinstance(mf, mutagen.oggopus.OggOpus):
    track = "R128_TRACK_GAIN" in mf
    album = "R128_ALBUM_GAIN" in mf

  elif (isinstance(mf.tags, (mutagen._vorbis.VComment, mutagen.apev2.APEv2)) or
        isinstance(mf, (mutagen.ogg.OggFileType, mutagen.apev2.APEv2File))):
    track = ("REPLAYGAIN_TRACK_GAIN" in mf) and ("REPLAYGAIN_TRACK_PEAK" in mf)
    album = ("REPLAYGAIN_ALBUM_GAIN" in mf) and ("REPLAYGAIN_ALBUM_PEAK" in mf)

  elif (isinstance(mf.tags, mutagen.mp4.MP4Tags) or
        isinstance(mf, mutagen.mp4.MP4)):
    track = ("----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN" in mf) and ("----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_PEAK" in mf)
    album = ("----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN" in mf) and ("----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_PEAK" in mf)

  else:
    logger().warning("Unhandled '%s' tag format for file '%s'" % (mf.__class__.__name__,
                                                                  filepath))
    return

  return track, album
1083699
def createNoiseExperimentArgs():
  """"""
  experimentArguments = []
  n = 6000
  for a in [128]:
    noisePct = 0.75
    while noisePct <= 0.85:
      noise = int(round(noisePct*a,0))
      # Some parameter combinations are just not worth running!
      experimentArguments.append(
        ("./sdr_calculations2",
         "results_noise_10m/temp_"+str(n)+"_"+str(a)+"_"+str(noise)+"_30.csv",
         "200000", str(n), str(a), str(noise))
      )
      noisePct += 0.05
  return experimentArguments
595821
def analyze_quality(self):
    """"""
    res = {}
    for h in self._hpas:
      if h.type() not in res: res[h.type()]={}
      for c in h.get_quality():
        if c not in res[h.type()]: res[h.type()][c] = 0
        res[h.type()][c]+=1
    self._quality_distro = res
771276
def cli(ctx, monitor, full, stage):
    """"""
    if not ctx.bubble:
        msg = 'There is no bubble present, will not search stats'
        if monitor:
            ctx.say_yellow('Unknown - ' + msg, 0)
            raise SystemExit(3)
        else:
            ctx.say_yellow(msg)
        raise click.Abort()

    stats = {}
    stats_found = False
    flowing_full = False
    flowing_decrease = False
    flowing_increase = False
    errors = False

    loader = bubble_lod_load(ctx, 'stats', stage)
    lod_gen = _find_lod_gen(ctx, loader)
    if lod_gen:
        last_stats = {}
        ctx.say('lod_gen', stuff=lod_gen)
        for stats_data in lod_gen:
            last_stats = stats_data
        if last_stats:
            ctx.say('found last_stats:', stuff=last_stats, verbosity=10)

    try:
        ctx.say('trying:last stats:', stuff=last_stats, verbosity=10)
        if last_stats:
            l = last_stats
            stats['pull_err'] = k0(l, 'pulled_stat_error_count')
            stats['pull_total'] = k0(l, 'pulled_stat_total_count')

            stats['trans_err'] = k0(l, 'transformed_stat_error_count')
            stats['trans_total'] = k0(l, 'transformed_stat_total_count')

            stats['push_err'] = k0(l, 'pushed_stat_error_count')
            stats['push_total'] = k0(l, 'pushed_stat_total_count')
            stats_found = True
        else:
            stats_found = False

        ctx.say('stats:', stuff=stats, verbosity=10)

        if stats_found and stats['pull_err'] > 0 or \
                stats['trans_err'] > 0 or \
                stats['push_err'] > 0:
            errors = True
        if stats_found and stats['pull_total'] == stats['trans_total'] and \
                stats['trans_total'] == stats['push_total']:
            flowing_full = True
        if stats_found and stats['pull_total'] >= stats['trans_total'] >= stats['push_total']:
            flowing_decrease = True
        if stats_found and stats['pull_total'] <= stats['trans_total'] <= stats['push_total']:
            flowing_increase = True
    except KeyError as stat_key_error:
        errors = True
        ctx.gbc.cry('cannot create status from last stats', stuff=stat_key_error)

    if full:
        ctx.say_yellow('Stats full')
        ctx.say_yellow('Full flow:' + str(flowing_full))
        ctx.say_yellow('Flowing decrease:' + str(flowing_decrease))
        ctx.say_yellow('Flowing increase:' + str(flowing_increase))
        ctx.say_yellow('Errors:' + str(errors))
        ctx.say_yellow('totals:')
        ctx.say_yellow(pf(stats, indent=8))

    if monitor == 'nagios' or full:

        """
        for Numeric Value Service Status Status Description, please see:
        https://nagios-plugins.org/doc/guidelines.html#AEN78
        0 OK The plugin was able to check the service and
          it appeared to be functioning properly
        1 Warning The plugin was able to check the service,
          but it appeared to be above some "warning" threshold or did not appear to be working properly
        2 Critical The plugin detected that either the service was not running or
          it was above some "critical" threshold
        3 Unknown Invalid command line arguments were supplied to the plugin or
          low-level failures internal to the plugin (such as unable to fork, or open a tcp socket)
          that prevent it from performing the specified operation. Higher-level errors (such as name resolution errors,
          socket timeouts, etc) are outside of the control of plugins and
          should generally NOT be reported as UNKNOWN states.

        http://nagios.sourceforge.net/docs/3_0/perfdata.html
        http://nagios.sourceforge.net/docs/3_0/pluginapi.html
        """
        if stats_found:
            templ_nagios = 'pull: %d %d transform: %d  %d push: %d %d '
            res_nagios = templ_nagios % (stats['pull_total'],
                                         stats['pull_err'],
                                         stats['trans_total'],
                                         stats['trans_err'],
                                         stats['push_total'],
                                         stats['push_err']
                                         )
        else:
            res_nagios = 'Cannot find or read stats'

        if not stats_found:
            print('Unknown - ' + res_nagios)
            raise SystemExit(3)
            # return

        if not errors and flowing_full:
            print('Ok - ' + res_nagios)
            return

        # magister and databyte with amount
        if not errors and flowing_decrease:
            print('Ok - ' + res_nagios)
            return

        if not errors and not flowing_full:
            print('Warning - ' + res_nagios)
            raise SystemExit(1)
            # return

        if errors:
            print('Critical - ' + res_nagios)
            raise SystemExit(2)
            # return
    return False
720525
def scan_results(self):
        """"""
        
        bsses = self._wifi_ctrl.scan_results(self._raw_obj)

        if self._logger.isEnabledFor(logging.INFO):
            for bss in bsses:
                self._logger.info("Find bss:")
                self._logger.info("\tbssid: %s", bss.bssid)
                self._logger.info("\tssid: %s", bss.ssid)
                self._logger.info("\tfreq: %d", bss.freq)
                self._logger.info("\tauth: %s", bss.auth)
                self._logger.info("\takm: %s", bss.akm)
                self._logger.info("\tsignal: %d", bss.signal)

        return bsses
1205065
def detect(self, volume_system, vstype='detect'):
        """"""

        volume_group = volume_system.parent.info.get('volume_group')

        result = _util.check_output_(["lvm", "lvdisplay", volume_group])
        cur_v = None
        for l in result.splitlines():
            if "--- Logical volume ---" in l:
                cur_v = volume_system._make_subvolume(
                    index=self._format_index(volume_system, len(volume_system)),
                    flag='alloc'
                )
                cur_v.info['fsdescription'] = 'Logical Volume'
            if "LV Name" in l:
                cur_v.info['label'] = l.replace("LV Name", "").strip()
            if "LV Size" in l:
                size, unit = l.replace("LV Size", "").strip().split(" ", 1)
                cur_v.size = int(float(size.replace(',', '.')) * {'KiB': 1024, 'MiB': 1024 ** 2,
                                                                  'GiB': 1024 ** 3, 'TiB': 1024 ** 4}.get(unit, 1))
            if "LV Path" in l:
                cur_v._paths['lv'] = l.replace("LV Path", "").strip()
                cur_v.offset = 0

        logger.info("{0} volumes found".format(len(volume_system)))
        volume_system.volume_source = 'multi'
        return volume_system.volumes