Print the detector serial number for a given run of ARCA/ORCA
182731
def rundetsn(run_id, detector="ARCA", temporary=False):
    """"""
    db = DBManager(temporary=temporary)
    dts = db.detectors
    for det_id in dts[dts.OID.str.contains(detector)].SERIALNUMBER:
        if run_id in db.run_table(det_id).RUN.values:
            print(det_id)
            return
497797
def check_ns_run_members(run):
    
    run_keys = list(run.keys())
    # Mandatory keys
    for key in ['logl', 'nlive_array', 'theta', 'thread_labels',
                'thread_min_max']:
        assert key in run_keys
        run_keys.remove(key)
    # Optional keys
    for key in ['output']:
        try:
            run_keys.remove(key)
        except ValueError:
            pass
    # Check for unexpected keys
    assert not run_keys, 'Unexpected keys in ns_run: ' + str(run_keys)
    # Check type of mandatory members
    for key in ['logl', 'nlive_array', 'theta', 'thread_labels',
                'thread_min_max']:
        assert isinstance(run[key], np.ndarray), (
            key + ' is type ' + type(run[key]).__name__)
    # check shapes of keys
    assert run['logl'].ndim == 1
    assert run['logl'].shape == run['nlive_array'].shape
    assert run['logl'].shape == run['thread_labels'].shape
    assert run['theta'].ndim == 2
    assert run['logl'].shape[0] == run['theta'].shape[0]
176943
def _print_throbber(self):
        ''''''
        self._print('[')

        for position in range(self._bar_width):
            self._print('O' if position == self._throbber_index else ' ')

        self._print(']')

        self._throbber_index = next(self._throbber_iter)
764276
def _print_result_info(traces, events):
    
    print_v('Returning %i traces:'%len(traces))
    for r in sorted(traces.keys()):
        x = traces[r]
        print_v('  %s (%s): %s -> %s (min: %s, max: %s, len: %i)'%(r, type(x), x[0],x[-1],min(x),max(x),len(x)))
    print_v('Returning %i events:'%len(events))
    for r in sorted(events.keys()):
        x = events[r]
        print_v('  %s: %s -> %s (len: %i)'%(r, x[0] if len(x)>0 else '-',x[-1] if len(x)>0 else '-',len(x)))
570630
function debugPrintFlatScannedData(data, printer) {
        var pInfo = [
            'numConnectionTypes',
            'connectionTypeNames',
            'verifiedConnectionTypeNames',
            'connectionTypes',
            'unverifiedConnectionTypeNames',
        ];

        if(DEBUG_MARKING_ACTIVE_CONNECTION_TYPES) {
            pInfo.push('handle');
            pInfo.push('dt');
            pInfo.push('deviceType');
            pInfo.push('deviceTypeStr');
            pInfo.push('deviceTypeString');
            pInfo.push('deviceTypeName');
            pInfo.push('handleConnectionType');
            pInfo.push('handleConnectionTypeStr');
            pInfo.push('handleConnectionTypeName');
            pInfo.push('ct');
            pInfo.push('connectionType');
            pInfo.push('connectionTypeStr');
            pInfo.push('connectionTypeName');
            pInfo.push('serialNumber');
            pInfo.push('ip');
            pInfo.push('port');
            pInfo.push('maxBytesPerMB');
            pInfo.push('maxBytesPerMB');
            pInfo.push('isActive');
        }
        var pData = {};
        var keys = Object.keys(data);
        keys.forEach(function(key) {
            var dData = data[key];
            var dKeys = Object.keys(dData);
            pData[key] = {};
            var otherKeys = [];
            // loop through each available device.
            dKeys.forEach(function(dKey) {
                // Save the requested key's info.
                if(pInfo.indexOf(dKey) >= 0) {
                    pData[key][dKey] = dData[dKey];
                } else {
                    otherKeys.push(dKey);
                }
            });
            // pData[key].keys = otherKeys;
        });
        if(printer) {
            printer('Scanned Data', pData);
        } else {
            console.log('Scanned Data', pData);
        }
    }
576582
def runner(self):
        
        printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime)
        if not self.pipeline:
            # If the metadata has been passed from the method script, self.pipeline must still be false in order to
            # get Sippr() to function correctly, but the metadata shouldn't be recreated
            try:
                _ = vars(self.runmetadata)['samples']
            except KeyError:
                # Create the objects to be used in the analyses
                objects = Objectprep(self)
                objects.objectprep()
                self.runmetadata = objects.samples
            # Run the analyses
            Sippr(self, self.cutoff)
            #
            self.attributer()
            # Create the reports
            self.reporter()
            # Print the metadata
            printer = MetadataPrinter(self)
            printer.printmetadata()
186821
def print(self):
        """"""
        cond_var = None
        if self.supported:
            cond_var = conditional_var('{}{}'.format(self.func, self.fn_num))
            print_conditional_if(cond_var)
            print('  AF',  end='')
        else:
            print('  //', end='')
        fn_num = self.fn_num
        if fn_num is None:
            fn_num = 0
        print('({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}'.format(self.idx,
              self.func, fn_num, self.pin_type, self.ptr(), self.af_str))
        print_conditional_endif(cond_var)
979894
def serial_number(self, serial_number):
        
        if serial_number is not None and len(serial_number) > 64:
            raise ValueError("Invalid value for `serial_number`, length must be less than or equal to `64`")

        self._serial_number = serial_number
980532
def var_spool_cwl_detector(obj,           # type: Union[MutableMapping, List, Text]
                           item=None,     # type: Optional[Any]
                           obj_key=None,  # type: Optional[Any]
                          ):              # type: (...)->bool
    
    r = False
    if isinstance(obj, string_types):
        if "var/spool/cwl" in obj and obj_key != "dockerOutputDirectory":
            _logger.warning(
                SourceLine(item=item, key=obj_key, raise_type=Text).makeError(
                    _VAR_SPOOL_ERROR.format(obj)))
            r = True
    elif isinstance(obj, MutableMapping):
        for key, value in iteritems(obj):
            r = var_spool_cwl_detector(value, obj, key) or r
    elif isinstance(obj, MutableSequence):
        for key, value in enumerate(obj):
            r = var_spool_cwl_detector(value, obj, key) or r
    return r
367946
def run_analysis(self, argv):
        """"""
        args = self._parser.parse_args(argv)

        if not HAVE_ST:
            raise RuntimeError(
                "Trying to run fermipy analysis, but don't have ST")

        workdir = os.path.dirname(args.config)
        _config_file = self._clone_config_and_srcmaps(args.config, args.seed)

        gta = GTAnalysis(_config_file, logging={'verbosity': 3},
                         fileio={'workdir_regex': '\.xml$|\.npy$'})
        gta.load_roi(args.roi_baseline)

        simfile = os.path.join(workdir, 'sim_%s_%s.yaml' %
                               (args.sim, args.sim_profile))

        mcube_file = "%s_%s_%06i" % (args.sim, args.sim_profile, args.seed)
        sim_config = utils.load_yaml(simfile)

        injected_source = sim_config.get('injected_source', None)
        if injected_source is not None:
            src_dict =  injected_source['source_model']
            src_dict['ra'] = gta.config['selection']['ra']
            src_dict['dec'] = gta.config['selection']['dec']
            injected_name = injected_source['name']
            gta.add_source(injected_name, src_dict)
            gta.write_model_map(mcube_file)
            mc_spec_dict = dict(true_counts=gta.model_counts_spectrum(injected_name),
                                energies=gta.energies,
                                model=src_dict)
            mcspec_file = os.path.join(workdir,
                                       "mcspec_%s_%06i.yaml" % (mcube_file, args.seed))
            utils.write_yaml(mc_spec_dict, mcspec_file)
        else:
            injected_name = None

        gta.write_roi('sim_baseline_%06i' % args.seed)

        test_sources = []
        for profile in args.profiles:
            profile_path = os.path.join(workdir, 'profile_%s.yaml' % profile)
            test_source = load_yaml(profile_path)
            test_sources.append(test_source)
            first = args.seed
            last = first + args.nsims
            for seed in range(first, last):
                self._run_simulation(gta, args.roi_baseline,
                                     injected_name, test_sources, first, seed,
                                     non_null_src=args.non_null_src)
758685
def show(self):
        
        off = 0
        for n, i in enumerate(self.get_instructions()):
            print("{:8d} (0x{:08x}) {:04x} {:30} {}".format(n, off, i.get_op_value(), i.get_name(), i.get_output(self.idx)))
            off += i.get_length()
288587
def _PrintWarningCounters(self, storage_counters):
    
    warnings_by_pathspec = storage_counters.get('warnings_by_path_spec', {})
    warnings_by_parser_chain = storage_counters.get(
        'warnings_by_parser_chain', {})
    if not warnings_by_parser_chain:
      self._output_writer.Write('No warnings stored.\n\n')
      return

    table_view = views.ViewsFactory.GetTableView(
        self._views_format_type, title='Warnings generated per parser',
        column_names=['Parser (plugin) name', 'Number of warnings'])
    for parser_chain, count in warnings_by_parser_chain.items():
      parser_chain = parser_chain or '<No parser>'
      table_view.AddRow([parser_chain, '{0:d}'.format(count)])
    table_view.Write(self._output_writer)

    table_view = views.ViewsFactory.GetTableView(
        self._views_format_type, title='Pathspecs with most warnings',
        column_names=['Number of warnings', 'Pathspec'])

    top_pathspecs = warnings_by_pathspec.most_common(10)
    for pathspec, count in top_pathspecs:
      for path_index, line in enumerate(pathspec.split('\n')):
        if not line:
          continue

        if path_index == 0:
          table_view.AddRow(['{0:d}'.format(count), line])
        else:
          table_view.AddRow(['', line])

    table_view.Write(self._output_writer)
133396
def _print_count(log):
    """
    log['cnt2'] += 1                   # Current number
    cp = log['cnt2']/log['totnr']*100  # Percentage

    if log['cnt2'] == 0:  # Not sure about this; brute seems to call the
        pass              # function with the first arguments twice...

    elif log['cnt2'] > log['totnr']:  # fmin-status
        print("   fmin  fct calls : %d" % (log['cnt2']-log['totnr']), end='\r')

    elif int(cp) > log['cnt1'] or cp < 1 or log['cnt2'] == log['totnr']:
        # Get seconds since start
        sec = int(default_timer() - log['time'])

        # Get estimate of remaining time, as string
        tleft = str(timedelta(seconds=int(100*sec/cp - sec)))

        # Print progress
        pstr = ("   brute fct calls : %d/%d"
                % (log['cnt2'], log['totnr']))
        if log['totnr'] > 100:
            pstr += (" (%d %%); est: %s        " % (cp, tleft))
        print(pstr, end='\r')

        if log['cnt2'] == log['totnr']:
            # Empty previous line
            print(" "*len(pstr), end='\r')

            # Print final brute-message
            print("   brute fct calls : %d" % log['totnr'])

        # Update percentage cnt1
        log['cnt1'] = cp

    return log
1244672
def roc(args):
    
    outputfile = args.outfile
    # Default extension for image
    if outputfile and not outputfile.endswith(".png"):
        outputfile += ".png"
    
    motifs = read_motifs(args.pwmfile, fmt="pwm")

    ids = []
    if args.ids:
        ids = args.ids.split(",")
    else:
        ids = [m.id for m in motifs]
    motifs = [m for m in motifs if (m.id in ids)]
    
    stats = [
            "phyper_at_fpr",
            "roc_auc", 
            "pr_auc", 
            "enr_at_fpr",
            "recall_at_fdr", 
            "roc_values",
            "matches_at_fpr",
            ]
    
    plot_x = []
    plot_y = []
    legend = []
    
    f_out = sys.stdout
    if args.outdir:
        if not os.path.exists(args.outdir):
            os.makedirs(args.outdir)
        f_out = open(args.outdir + "/gimme.roc.report.txt", "w")
    
    # Print the metrics
    f_out.write("Motif\t# matches\t# matches background\tP-value\tlog10 P-value\tROC AUC\tPR AUC\tEnr. at 1% FPR\tRecall at 10% FDR\n")
    
    
    for motif_stats in calc_stats_iterator(motifs, args.sample, args.background, 
            genome=args.genome, stats=stats, ncpus=args.ncpus):
    
        for motif in motifs:
            if str(motif) in motif_stats:
                if outputfile:
                    x, y = motif_stats[str(motif)]["roc_values"]
                    plot_x.append(x)
                    plot_y.append(y)
                    legend.append(motif.id)
                log_pvalue = np.inf
                if motif_stats[str(motif)]["phyper_at_fpr"] > 0:
                    log_pvalue = -np.log10(motif_stats[str(motif)]["phyper_at_fpr"])
                f_out.write("{}\t{:d}\t{:d}\t{:.2e}\t{:.3f}\t{:.3f}\t{:.3f}\t{:.2f}\t{:0.4f}\n".format(
                      motif.id, 
                      motif_stats[str(motif)]["matches_at_fpr"][0], 
                      motif_stats[str(motif)]["matches_at_fpr"][1], 
                      motif_stats[str(motif)]["phyper_at_fpr"], 
                      log_pvalue, 
                      motif_stats[str(motif)]["roc_auc"], 
                      motif_stats[str(motif)]["pr_auc"], 
                      motif_stats[str(motif)]["enr_at_fpr"], 
                      motif_stats[str(motif)]["recall_at_fdr"],
                      ))
    f_out.close() 
    
    if args.outdir:
        html_report(
            args.outdir,
            args.outdir + "/gimme.roc.report.txt",
            args.pwmfile,
            0.01,
            )

    # Plot the ROC curve
    if outputfile:
        roc_plot(outputfile, plot_x, plot_y, ids=legend)
1098237
def printDiagnostics(exp, sequences, objects, args, verbosity=0):
  """"""
  print "Experiment start time:", time.ctime()
  print "\nExperiment arguments:"
  pprint.pprint(args)

  r = sequences.objectConfusion()
  print "Average common pairs in sequences=", r[0],
  print ", features=",r[2]

  r = objects.objectConfusion()
  print "Average common pairs in objects=", r[0],
  print ", locations=",r[1],
  print ", features=",r[2]

  # For detailed debugging
  if verbosity > 0:
    print "\nObjects are:"
    for o in objects:
      pairs = objects[o]
      pairs.sort()
      print str(o) + ": " + str(pairs)
    print "\nSequences:"
    for i in sequences:
      print i,sequences[i]

  print "\nNetwork parameters:"
  pprint.pprint(exp.config)
618162
def tracker_print(msg):
    
    if not isinstance(msg, STRING_TYPES):
        msg = str(msg)
    is_dist = _LIB.RabitIsDistributed()
    if is_dist != 0:
        _LIB.RabitTrackerPrint(c_str(msg))
    else:
        sys.stdout.write(msg)
        sys.stdout.flush()
1091899
def _vispy_emit_match_andor_record(self, record):
        """"""
        test = record.getMessage()
        match = self._vispy_match
        if (match is None or re.search(match, test) or
                re.search(match, _get_vispy_caller())):
            if self._vispy_emit_record:
                fmt_rec = self._vispy_formatter.format(record)
                self._vispy_emit_list.append(fmt_rec)
            if self._vispy_print_msg:
                return logging.StreamHandler.emit(self, record)
            else:
                return