main processing loop, display graphs and maps
492935
def main_loop():
    ''''''
    global grui, last_xlim
    while True:
        if mestate is None or mestate.exit:
            return
        while not mestate.input_queue.empty():
            line = mestate.input_queue.get()
            cmds = line.split(';')
            for c in cmds:
                process_stdin(c)

        for i in range(0, len(grui)):
            xlim = grui[i].check_xlim_change()
            if xlim is not None and mestate.settings.sync_xzoom:
                remlist = []
                for j in range(0, len(grui)):
                    #print("set_xlim: ", j, xlim)
                    if not grui[j].set_xlim(xlim):
                        remlist.append(j)
                last_xlim = xlim
                if len(remlist) > 0:
                    # remove stale graphs
                    new_grui = []
                    for j in range(0, len(grui)):
                        if j not in remlist:
                            new_grui.append(grui[j])
                    grui = new_grui
                break

        time.sleep(0.1)
1274040
def generate_graphs(data_frames, hardware_info, steps, outdir,
                    verbose=False):
    """"""
    _setup_matplotlib()
    # Hash of hosts containing (data, hardware, steps) tuple
    collectl_info = collections.defaultdict(dict)

    for host, data_frame in data_frames.items():
        if verbose:
            print('Generating CPU graph for {}...'.format(host))
        graph, data_cpu = graph_cpu(data_frame, steps, hardware_info[host]['num_cpus'])

        graph.get_figure().savefig(
            os.path.join(outdir, '{}_cpu.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        ifaces = set([series.split('_')[0]
                      for series in data_frame.keys()
                      if series.startswith(('eth', 'ib'))])

        if verbose:
            print('Generating network graphs for {}...'.format(host))
        graph, data_net_bytes = graph_net_bytes(data_frame, steps, ifaces)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_net_bytes.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        graph, data_net_pkts = graph_net_pkts(data_frame, steps, ifaces)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_net_pkts.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        if verbose:
            print('Generating memory graph for {}...'.format(host))
        graph, data_mem = graph_memory(data_frame, steps, hardware_info[host]["memory"])
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_memory.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        if verbose:
            print('Generating storage I/O graph for {}...'.format(host))
        drives = set([
            series.split('_')[0]
            for series in data_frame.keys()
            if series.startswith(('sd', 'vd', 'hd', 'xvd'))
        ])
        graph, data_disk = graph_disk_io(data_frame, steps, drives)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_disk_io.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        print('Serializing output to pickle object for node {}...'.format(host))
        # "Clean" dataframes ready to be plotted
        collectl_info[host] = { "hardware": hardware_info,
                                "steps": steps, "cpu": data_cpu, "mem": data_mem,
                                "disk": data_disk, "net_bytes": data_net_bytes,
                                "net_pkts": data_net_pkts
                              }
    return collectl_info
319162
def main(**kwargs):
    
    draw_lines()
    draw_histogram()
    draw_bar_chart()
    destination = "-r /report"
    if use_html:
        generate_html()
        command = "dx-build-report-html {h} {d}".format(h=html_filename, d=destination)
    else:
        command = "dx-build-report-html {l} {b} {h} {d}".format(l=lines_filename, b=bars_filename, h=histogram_filename, d=destination)
    sub_output = json.loads(subprocess.check_output(command, shell=True))
    output = {}
    output["report"] = dxpy.dxlink(sub_output["recordId"])
    return output
84139
public static void main(final String[] args) {
		BenchmarkOutputParser parser = new BenchmarkOutputParser(FRAMEWORKS.keySet());
		HtmlDiagramRenderer renderer = new HtmlDiagramRenderer(FRAMEWORKS);
		renderer.output(parser.parse(OUTPUT_FILE));
	}
321403
public static void main(String[] args) throws Exception {
		
		if(!parseParameters(args)) {
			return;
		}
		
		// set up execution environment
		final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
	
		// read input data
		DataSet<Edge> edges = getEdgeDataSet(env);
		
		// project edges by vertex id
		DataSet<Edge> edgesById = edges
				.map(new EdgeByIdProjector());
		
		DataSet<Triad> triangles = edgesById
				// build triads
				.groupBy(Edge.V1).sortGroup(Edge.V2, Order.ASCENDING).reduceGroup(new TriadBuilder())
				// filter triads
				.join(edgesById).where(Triad.V2, Triad.V3).equalTo(Edge.V1, Edge.V2).with(new TriadFilter());

		// emit result
		if(fileOutput) {
			triangles.writeAsCsv(outputPath, "\n", ",");
		} else {
			triangles.print();
		}

		// execute program
		env.execute("Basic Triangle Enumeration Example");

	}
328063
def main(unused_argv):
    """"""
    if FLAGS.use_tpu:
        dual_net.freeze_graph_tpu(FLAGS.model_path)
    else:
        dual_net.freeze_graph(FLAGS.model_path)
1068823
def main():
    
    parser = make_parser()
    args = parser.parse_args()
    data_dir = Path(args.data_dir).expand()
    if not data_dir.isdir():  # pylint: disable=no-value-for-parameter
        msg = u"Data directory {dir} does not exist".format(dir=args.data_dir)
        raise ValueError(msg)
    data_filenames = [name for name in data_dir.files()  # pylint: disable=no-value-for-parameter
                      if name.endswith(".json")]
    if not data_filenames:
        msg = u"Data directory {dir} contains no JSON files".format(dir=args.data_dir)
        raise ValueError(msg)
    output_dir = Path(args.output_dir).expand()
    output_dir.makedirs_p()  # pylint: disable=no-value-for-parameter

    return render_html(data_dir, output_dir)
907405
def Main():
  """"""
  multiprocessing.freeze_support()

  tool = psteal_tool.PstealTool()
  if not tool.ParseArguments():
    return False

  have_list_option = False

  if tool.list_timezones:
    tool.ListTimeZones()
    have_list_option = True

  if tool.list_output_modules:
    tool.ListOutputModules()
    have_list_option = True

  if tool.list_timezones:
    tool.ListTimeZones()
    have_list_option = True

  if tool.list_parsers_and_plugins:
    tool.ListParsersAndPlugins()
    have_list_option = True

  if tool.list_hashers:
    tool.ListHashers()
    have_list_option = True

  if tool.list_language_identifiers:
    tool.ListLanguageIdentifiers()
    have_list_option = True

  if have_list_option:
    return True

  try:
    tool.ExtractEventsFromSources()
    tool.AnalyzeEvents()

  except (KeyboardInterrupt, errors.UserAbort):
    logging.warning('Aborted by user.')
    return False

  except errors.SourceScannerError as exception:
    logging.warning(exception)
    return False

  return True
196751
def main():
    
    usage = "usage: %(prog)s [options] "
    description = "Merge a set of Fermi-LAT files."
    parser = argparse.ArgumentParser(usage=usage, description=description)

    parser.add_argument('-o', '--output', default=None, type=str,
                        help='Output file.')
    parser.add_argument('--clobber', default=False, action='store_true',
                        help='Overwrite output file.')
    parser.add_argument('files', nargs='+', default=None,
                        help='List of input files.')

    args = parser.parse_args()

    proj, f, hdu = fits_utils.read_projection_from_fits(args.files[0])
    if isinstance(proj, WCS):
        hdulist = merge_utils.merge_wcs_counts_cubes(args.files)
    elif isinstance(proj, HPX):
        hdulist = merge_utils.merge_hpx_counts_cubes(args.files)
    else:
        raise TypeError("Could not read projection from file %s" %
                        args.files[0])

    if args.output:
        hdulist.writeto(args.output, clobber=args.clobber, output_verify='silentfix')
1003154
def main():
    '''
        
    '''

    print('GLWindow:', GLWindow.__version__)
    print('Python:', sys.version)
    print('Platform:', sys.platform)

    wnd = GLWindow.create_window((480, 480), title='GLWindow Sample')
    wnd.vsync = False

    ctx = ModernGL.create_context()

    prog = ctx.program([
        ctx.vertex_shader('''
            #version 330
            in vec2 vert;
            in vec4 vert_color;
            out vec4 frag_color;
            uniform vec2 scale;
            uniform float rotation;
            void main() {
                frag_color = vert_color;
                float r = rotation * (0.5 + gl_InstanceID * 0.05);
                mat2 rot = mat2(cos(r), sin(r), -sin(r), cos(r));
                gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
            }
        '''),
        ctx.fragment_shader('''
            #version 330
            in vec4 frag_color;
            out vec4 color;
            void main() {
                color = vec4(frag_color);
            }
        '''),
    ])

    scale = prog.uniforms['scale']
    rotation = prog.uniforms['rotation']

    vbo = ctx.buffer(struct.pack(
        '18f',
        1.0, 0.0, 1.0, 0.0, 0.0, 0.5,
        -0.5, 0.86, 0.0, 1.0, 0.0, 0.5,
        -0.5, -0.86, 0.0, 0.0, 1.0, 0.5,
    ))

    vao = ctx.simple_vertex_array(prog, vbo, ['vert', 'vert_color'])

    while wnd.update():
        wnd.clear(0.95, 0.95, 0.95)

        width, height = wnd.size
        scale.value = (height / width * 0.75, 0.75)
        ctx.viewport = wnd.viewport
        ctx.enable(ModernGL.BLEND)
        rotation.value = wnd.time
        vao.render(instances=10)
814074
def run_graphviz(program, code, options=[], format='png'):
    
    import os
    from subprocess import Popen, PIPE

    dot_args = [program] + options + ['-T', format]

    if os.name == 'nt':
        # Avoid opening shell window.
        # * https://github.com/tkf/ipython-hierarchymagic/issues/1
        # * http://stackoverflow.com/a/2935727/727827
        p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE, creationflags=0x08000000)
    else:
        p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE)
        wentwrong = False

    try:
        # Graphviz may close standard input when an error occurs,
        # resulting in a broken pipe on communicate()
        stdout, stderr = p.communicate(code.encode('utf-8'))
    except (OSError, IOError) as err:
        if err.errno != EPIPE:
            raise
        wentwrong = True
    except IOError as err:
        if err.errno != EINVAL:
            raise
        wentwrong = True

    if wentwrong:
    # in this case, read the standard output and standard error streams
    # directly, to get the error message(s)
        stdout, stderr = p.stdout.read(), p.stderr.read()
        p.wait()

    if p.returncode != 0:
        raise RuntimeError('dot exited with error:\n[stderr]\n{0}'.format(stderr.decode('utf-8')))

    return stdout
537166
function loadGraphSON(graph, filename, callback) {
        var FileInputStream = Tinkerpop.autoImport('FileInputStream');
        var stream = new FileInputStream(filename);
        return Tinkerpop.GraphSONReader.buildP()
            .then(function (builder) {
            return _newGraphSONMapper()
                .then(function (mapper) { return builder.mapperP(mapper); });
        })
            .then(function (builder) { return builder.createP(); })
            .then(function (reader) { return reader.readGraphP(stream, graph); })
            .then(function () { return graph; })
            .nodeify(callback);
    }
723844
public static void main(String... args) throws Exception {

		// Checking input parameters
		final ParameterTool params = ParameterTool.fromArgs(args);

		// set up execution environment
		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		final int maxIterations = params.getInt("iterations", 10);

		// make parameters available in the web interface
		env.getConfig().setGlobalJobParameters(params);

		// read vertex and edge data
		DataSet<Long> vertices = getVertexDataSet(env, params);
		DataSet<Tuple2<Long, Long>> edges = getEdgeDataSet(env, params).flatMap(new UndirectEdge());

		// assign the initial components (equal to the vertex id)
		DataSet<Tuple2<Long, Long>> verticesWithInitialId =
			vertices.map(new DuplicateValue<Long>());

		// open a delta iteration
		DeltaIteration<Tuple2<Long, Long>, Tuple2<Long, Long>> iteration =
				verticesWithInitialId.iterateDelta(verticesWithInitialId, maxIterations, 0);

		// apply the step logic: join with the edges, select the minimum neighbor, update if the component of the candidate is smaller
		DataSet<Tuple2<Long, Long>> changes = iteration.getWorkset().join(edges).where(0).equalTo(0).with(new NeighborWithComponentIDJoin())
				.groupBy(0).aggregate(Aggregations.MIN, 1)
				.join(iteration.getSolutionSet()).where(0).equalTo(0)
				.with(new ComponentIdFilter());

		// close the delta iteration (delta and new workset are identical)
		DataSet<Tuple2<Long, Long>> result = iteration.closeWith(changes, changes);

		// emit result
		if (params.has("output")) {
			result.writeAsCsv(params.get("output"), "\n", " ");
			// execute program
			env.execute("Connected Components Example");
		} else {
			System.out.println("Printing result to stdout. Use --output to specify output path.");
			result.print();
		}
	}
92752
public static void main( String args[] ) {
		BenchmarkNearestNeighborCorrect app = new BenchmarkNearestNeighborCorrect();

//		app.evaluateDataSet(3,30);
//		app.evaluateDataSet(3,300);
//		app.evaluateDataSet(3,600);
//		app.evaluateDataSet(5,10000);
		app.evaluateDataSet(10,100000,1000);
		app.evaluateDataSet(20,100000,1000);
		app.evaluateDataSet(60,100000,1000);
		app.evaluateDataSet(120,100000,1000);

		try {
			synchronized ( app ) {
				Thread.sleep(100);
			}
		} catch (InterruptedException e) {}
	}
753112
def main(argv=None):
    """"""
    if argv is None:
        argv = sys.argv

    log.setLevel(logging.INFO)

    import optparse  # TODO: use argparse

    parser = optparse.OptionParser(
        usage='usage: %prog [options] path',
        description='Display image data in TIFF files.',
        version='%%prog %s' % __version__, prog='tifffile')
    opt = parser.add_option
    opt('-p', '--page', dest='page', type='int', default=-1,
        help='display single page')
    opt('-s', '--series', dest='series', type='int', default=-1,
        help='display series of pages of same shape')
    opt('--nomultifile', dest='nomultifile', action='store_true',
        default=False, help='do not read OME series from multiple files')
    opt('--noplots', dest='noplots', type='int', default=10,
        help='maximum number of plots')
    opt('--interpol', dest='interpol', metavar='INTERPOL', default=None,
        help='image interpolation method')
    opt('--dpi', dest='dpi', type='int', default=96,
        help='plot resolution')
    opt('--vmin', dest='vmin', type='int', default=None,
        help='minimum value for colormapping')
    opt('--vmax', dest='vmax', type='int', default=None,
        help='maximum value for colormapping')
    opt('--debug', dest='debug', action='store_true', default=False,
        help='raise exception on failures')
    opt('--doctest', dest='doctest', action='store_true', default=False,
        help='runs the docstring examples')
    opt('-v', '--detail', dest='detail', type='int', default=2)
    opt('-q', '--quiet', dest='quiet', action='store_true')

    settings, path = parser.parse_args()
    path = ' '.join(path)

    if settings.doctest:
        import doctest
        if sys.version_info < (3, 6):
            print('Doctests work with Python >=3.6 only')
            return 0
        doctest.testmod(optionflags=doctest.ELLIPSIS)
        return 0
    if not path:
        path = askopenfilename(title='Select a TIFF file',
                               filetypes=TIFF.FILEOPEN_FILTER)
        if not path:
            parser.error('No file specified')

    if any(i in path for i in '?*'):
        path = glob.glob(path)
        if not path:
            print('No files match the pattern')
            return 0
        # TODO: handle image sequences
        path = path[0]

    if not settings.quiet:
        print_('\nReading TIFF header:', end=' ', flush=True)
    start = time.time()
    try:
        tif = TiffFile(path, multifile=not settings.nomultifile)
    except Exception as exc:
        if settings.debug:
            raise
        print('\n\n%s: %s' % (exc.__class__.__name__, exc))
        sys.exit(0)

    if not settings.quiet:
        print('%.3f ms' % ((time.time()-start) * 1e3))

    if tif.is_ome:
        settings.norgb = True

    images = []
    if settings.noplots > 0:
        if not settings.quiet:
            print_('Reading image data: ', end=' ', flush=True)

        def notnone(x):
            return next(i for i in x if i is not None)

        start = time.time()
        try:
            if settings.page >= 0:
                images = [(tif.asarray(key=settings.page),
                           tif[settings.page], None)]
            elif settings.series >= 0:
                images = [(tif.asarray(series=settings.series),
                           notnone(tif.series[settings.series]._pages),
                           tif.series[settings.series])]
            else:
                for i, s in enumerate(tif.series[:settings.noplots]):
                    try:
                        images.append((tif.asarray(series=i),
                                       notnone(s._pages),
                                       tif.series[i]))
                    except Exception as exc:
                        images.append((None, notnone(s.pages), None))
                        if settings.debug:
                            raise
                        print('\nSeries %i failed with %s: %s... ' %
                              (i, exc.__class__.__name__, exc), end='')
        except Exception as exc:
            if settings.debug:
                raise
            print('%s: %s' % (exc.__class__.__name__, exc))

        if not settings.quiet:
            print('%.3f ms' % ((time.time()-start) * 1e3))

    if not settings.quiet:
        print_('Generating printout:', end=' ', flush=True)
        start = time.time()
        info = TiffFile.__str__(tif, detail=int(settings.detail))
        print('%.3f ms' % ((time.time()-start) * 1e3))
        print()
        print(info)
        print()
    tif.close()

    if images and settings.noplots > 0:
        try:
            import matplotlib
            matplotlib.use('TkAgg')
            from matplotlib import pyplot
        except ImportError as exc:
            log.warning('tifffile.main: %s: %s', exc.__class__.__name__, exc)
        else:
            for img, page, series in images:
                if img is None:
                    continue
                vmin, vmax = settings.vmin, settings.vmax
                if 'GDAL_NODATA' in page.tags:
                    try:
                        vmin = numpy.min(
                            img[img > float(page.tags['GDAL_NODATA'].value)])
                    except ValueError:
                        pass
                if tif.is_stk:
                    try:
                        vmin = tif.stk_metadata['MinScale']
                        vmax = tif.stk_metadata['MaxScale']
                    except KeyError:
                        pass
                    else:
                        if vmax <= vmin:
                            vmin, vmax = settings.vmin, settings.vmax
                if series:
                    title = '%s\n%s\n%s' % (str(tif), str(page), str(series))
                else:
                    title = '%s\n %s' % (str(tif), str(page))
                photometric = 'MINISBLACK'
                if page.photometric not in (3,):
                    photometric = TIFF.PHOTOMETRIC(page.photometric).name
                imshow(img, title=title, vmin=vmin, vmax=vmax,
                       bitspersample=page.bitspersample,
                       photometric=photometric,
                       interpolation=settings.interpol,
                       dpi=settings.dpi)
            pyplot.show()
    return 0
41361
public void process( List<List<SquareNode>> clusters ) {

		valid.reset();
		for( int i = 0; i < clusters.size(); i++ ) {
			List<SquareNode> graph = clusters.get(i);

			if( graph.size() < minimumElements )
				continue;

			switch( checkNumberOfConnections(graph) ) {
				case 1:orderIntoLine(graph); break;
				case 2:orderIntoGrid(graph); break;
//				default: System.out.println("Failed number of connections. size = "+graph.size());
			}
		}
	}
334133
def main():
    
    # Detector positions in ENU relative to the station GPS
    x = [-6.34, -2.23, -3.6, 3.46]
    y = [6.34, 2.23, -3.6, 3.46]

    # Scale mips to fit the graph
    n = [35.0, 51.9, 35.8, 78.9]

    # Make times relative to first detection
    t = [15., 17.5, 20., 27.5]
    dt = [ti - min(t) for ti in t]

    plot = Plot()
    plot.scatter([0], [0], mark='triangle')
    plot.add_pin_at_xy(0, 0, 'Station 503', use_arrow=False, location='below')
    plot.scatter_table(x, y, dt, n)

    plot.set_scalebar(location="lower right")
    plot.set_colorbar('$\Delta$t [ns]')
    plot.set_axis_equal()
    plot.set_mlimits(max=16.)
    plot.set_slimits(min=10., max=100.)

    plot.set_xlabel('x [m]')
    plot.set_ylabel('y [m]')

    plot.save('event_display')


    # Add event by Station 508
    # Detector positions in ENU relative to the station GPS
    x508 = [6.12, 0.00, -3.54, 3.54]
    y508 = [-6.12, -13.23, -3.54, 3.54]

    # Event GPS timestamp: 1371498167.016412100
    # MIPS
    n508 = [5.6, 16.7, 36.6, 9.0]
    # Arrival Times
    t508 = [15., 22.5, 22.5, 30.]
    dt508 = [ti - min(t508) for ti in t508]

    plot = MultiPlot(1, 2, width=r'.33\linewidth')
    plot.set_xlimits_for_all(min=-10, max=15)
    plot.set_ylimits_for_all(min=-15, max=10)
    plot.set_mlimits_for_all(min=0., max=16.)
    plot.set_colorbar('$\Delta$t [ns]', False)
    plot.set_colormap('blackwhite')
    plot.set_scalebar_for_all(location="upper right")

    p = plot.get_subplot_at(0, 0)
    p.scatter([0], [0], mark='triangle')
    p.add_pin_at_xy(0, 0, 'Station 503', use_arrow=False, location='below')
    p.scatter_table(x, y, dt, n)
    p.set_axis_equal()

    p = plot.get_subplot_at(0, 1)
    p.scatter([0], [0], mark='triangle')
    p.add_pin_at_xy(0, 0, 'Station 508', use_arrow=False, location='below')
    p.scatter_table(x508, y508, dt508, n508)
    p.set_axis_equal()

    plot.show_yticklabels_for_all([(0, 0)])
    plot.show_xticklabels_for_all([(0, 0), (0, 1)])

    plot.set_xlabel('x [m]')
    plot.set_ylabel('y [m]')

    plot.save('multi_event_display')