we intercept the strategy in order to capture the final layout and compute statistics
545747
function strategyInterceptor(strategy) {
    var interceptor = function(layout) {
        var start = new Date().getMilliseconds();
        var finalLayout = strategy(data);
        var time = new Date().getMilliseconds() - start;

        // record some statistics on this strategy
        if (!interceptor.time) {
            Object.defineProperty(interceptor, 'time', { enumerable: false, writable: true });
        }
        interceptor.time = time;
        return finalLayout;
    };

    interceptor.bucketSize = function() {
        return strategy.bucketSize.apply(this, arguments);
    };

    return interceptor;
}
928082
function() {
        if (this.strategies) {
            var strategy, i, len;
            for(i=0, len=this.strategies.length; i<len; i++) {
                strategy = this.strategies[i];
                if(strategy.autoDestroy) {
                    strategy.destroy();
                }
            }
            this.strategies = null;
        }
        if (this.protocol) {
            if(this.protocol.autoDestroy) {
                this.protocol.destroy();
            }
            this.protocol = null;
        }
        this.destroyFeatures();
        this.features = null;
        this.selectedFeatures = null;
        this.unrenderedFeatures = null;
        if (this.renderer) {
            this.renderer.destroy();
        }
        this.renderer = null;
        this.geometryType = null;
        this.drawn = null;
        OpenLayers.Layer.prototype.destroy.apply(this, arguments);  
    }
975739
protected function makeRanking () : void
    {
        $result = [];

        // Calculate ranking
        $challenge = array ();
        $rank = 1;
        $done = 0;

        foreach ($this->_Comparison as $candidate_key => $candidate_data) :
            $challenge[$candidate_key] = $candidate_data[$this->_countType];
        endforeach;

        while ($done < $this->_selfElection->countCandidates()) :
            $looking = $this->looking($challenge);

            foreach ($challenge as $candidate => $value) :
                if ($value === $looking) :
                    $result[$rank][] = $candidate;

                    $done++;
                    unset($challenge[$candidate]);
                endif;
            endforeach;

            $rank++;
        endwhile;

        $this->_Result = $this->createResult($result);
    }
1205500
function() {

            var self = this;
            var $element = $(this.element);
            self.attrId = $element.attr('id');
            //$element.html("Here I am...");
            // This is associated with dataAnalyzer.
            self.analyzeData();
            // TODO: process data:
            //  - rule to group! generate the tree map data.
            //  - set up the sunburst data structure.
            //  - calculate sub total, total
            //  - sorting the data, group

            // build dashboard, which will refresh the page's HTML DOM object
            // This is associated with dashboardBuilder.
            self.buildDashboard();
            // once we have the dashboard we will build the summary for data
            // This is associated with summaryBuilder.
            self.buildSummary();
            // and feed the insights
            self.feedInsights();
            // draw chart at the end, so we could calculate
            // the correct position (top and left offset).
            // This is associated with chartPainter
            self.drawChart();
        }
435127
static void constructAvgHitsGraph(Map.Entry<String, LrProjectScenarioResults> scenarioResults,
                                      JSONObject scenarioGraphData) {
        Map<Integer, WholeRunResult> avgHitsPerSec = scenarioResults.getValue().getAverageHitsPerSecondResults();
        JSONObject avgHitsPerSecGraphSet = extractWholeRunSlaResult(avgHitsPerSec, "Hits/Sec");
        if (!avgHitsPerSecGraphSet.getJSONArray(LABELS).isEmpty()) {
            avgHitsPerSecGraphSet.put(TITLE, "Average Hits per Second");
            avgHitsPerSecGraphSet.put(X_AXIS_TITLE, "Build number");
            avgHitsPerSecGraphSet.put(Y_AXIS_TITLE, "Hits");
            avgHitsPerSecGraphSet.put(DESCRIPTION,
                    "Displays the number of hits made on the Web server by Vusers " +
                            "during each second of the load test. This graph helps you evaluate the amount of load " +
                            "Vusers" +
                            " " +
                            "generate, in terms of the number of hits.");
            scenarioGraphData.put("avgHitsPerSec", avgHitsPerSecGraphSet);
        }
    }
948593
def setup_gui_analysis_done(self):
        """"""
        self.progress_bar.hide()
        self.lblAnalysisStatus.setText(tr('Analysis done.'))
        self.pbnReportWeb.show()
        self.pbnReportPDF.show()
        # self.pbnReportComposer.show()  # Hide until it works again.
        self.pbnReportPDF.clicked.connect(self.print_map)
1271091
private void doLog(long lastRun, long finalMoment)
    {
        double[] percentilenames = m_percentiles;

        //
        //  Do logging, if requested.
        //
        if( m_mode == Mode.LOG_ONLY || m_mode == Mode.ALL )
        {
            if( m_log != null && m_log.isInfoEnabled() )
            {
                StringBuilder percString = new StringBuilder();
                for( int i = 0; i < percentilenames.length; i++ )
                {
                    percString.append( String.format( " %6sth", saneDoubleToString(percentilenames[i]) ) );
                }
                
                printf("Statistics from %tc to %tc", new Date(lastRun), new Date(finalMoment));

                printf("%-"+m_tagWidth+"s %8s %8s %8s %8s%s%8s","Tag","Avg(ms)","Min","Max","Std Dev",percString,"Count");

                for( Map.Entry<String,CollectedStatistics> e : m_stats.entrySet() )
                {
                    CollectedStatistics cs = e.getValue();
                    StringBuilder sb = new StringBuilder();
                    
                    sb.append(String.format("%-"+m_tagWidth+"s %8.2f %8.2f %8.2f %8.2f", e.getKey(),cs.getAverageMS(), cs.getMin(), cs.getMax(), cs.getStdDev()));
                    for( int i = 0; i < percentilenames.length; i++ )
                        sb.append( String.format(" %8.2f", cs.getPercentile( percentilenames[i] )) );
                    
                    sb.append( String.format("%8d", cs.getInvocations()) );
                    m_log.info( sb.toString() );
                    
                    //
                    //  Only collect threshold information when the slow logging
                    //  is on.  Otherwise the array grows without bounds.
                    //
                    if( m_slowLogOn && m_slowLog != null )
                    {
                        long threshold = (long)(cs.getPercentile(m_slowLogPercentile)*1000);
                        m_slowThresholdMicros.put( e.getKey(), threshold );
                    }
                }
                
                m_log.info( "" );
            }
        }

        //
        //  Store these to the JMX attribute list
        //

        if( m_mode == Mode.JMX_ONLY || m_mode == Mode.ALL )
        {
            if( m_jmxAttributes != null )
            {
                m_jmxStatistics = new ConcurrentHashMap<String, PeriodicalLog.JmxStatistics>();

                for( String name : m_jmxAttributes )
                {
                    String n = name.trim();
                    CollectedStatistics cs = m_stats.get(n);

                    if ( cs == null )
                        continue;

                    JmxStatistics js = new JmxStatistics();
                    js.count = cs.getInvocations();
                    js.max = cs.getMax();
                    js.min = cs.getMin();
                    js.mean = cs.getAverageMS();
                    js.percentiles = new double[percentilenames.length];
                    
                    for( int i = 0; i < percentilenames.length; i++ )
                        js.percentiles[i] = cs.getPercentile( percentilenames[i] );
                    
                    js.stddev = cs.getStdDev();
                    m_jmxStatistics.put(n, js);
                }
            }
        }

        resetForNextPeriod();
    }
25971
def gather_parsing_stats(self):
        """"""
        if self.verbose:
            start_time = time.clock()
            try:
                yield
            finally:
                elapsed_time = time.clock() - start_time
                printerr("Time while parsing:", elapsed_time, "seconds")
                if packrat_cache:
                    hits, misses = ParserElement.packrat_cache_stats
                    printerr("Packrat parsing stats:", hits, "hits;", misses, "misses")
        else:
            yield
843768
public void process() {

		// compute match intensities
		if( mask == null )
			match.process(template);
		else
			match.process(template,mask);

		GrayF32 intensity = match.getIntensity();
		int offsetX = 0;
		int offsetY = 0;

		// adjust intensity image size depending on if there is a border or not
		if (!match.isBorderProcessed()) {
			int x0 = match.getBorderX0();
			int x1 = imageWidth - (template.width - x0);
			int y0 = match.getBorderY0();
			int y1 = imageHeight - (template.height - y0);
			intensity = intensity.subimage(x0, y0, x1, y1, null);
		} else {
			offsetX = match.getBorderX0();
			offsetY = match.getBorderY0();
		}

		// find local peaks in intensity image
		candidates.reset();
		extractor.process(intensity, null,null,null, candidates);

		// select the best matches
		if (scores.length < candidates.size) {
			scores = new float[candidates.size];
			indexes = new int[candidates.size];
		}

		for (int i = 0; i < candidates.size; i++) {
			Point2D_I16 p = candidates.get(i);

			scores[i] = -intensity.get(p.x, p.y);
		}

		int N = Math.min(maxMatches, candidates.size);

		QuickSelect.selectIndex(scores, N, candidates.size, indexes);

		// save the results
		results.reset();
		for (int i = 0; i < N; i++) {
			Point2D_I16 p = candidates.get(indexes[i]);

			Match m = results.grow();
			m.score = -scores[indexes[i]];
			m.set(p.x - offsetX, p.y - offsetY);
		}
	}
491719
protected void layoutBlocks()
    {
        int wlimit = getAvailableContentWidth();
        BlockLayoutStatus stat = new BlockLayoutStatus();
        int mtop = 0; //current accumulated top margin
        int mbottom = 0; //current accumulated bottom marin

        for (int i = 0; i < getSubBoxNumber(); i++)
        {
            int nexty = stat.y; //y coordinate after positioning the subbox 
            BlockBox subbox = (BlockBox) getSubBox(i);
            
            if (subbox.isDisplayed())
            {
            	boolean clearance = false; //clearance applied?
            	
                //clear set - try to find the first possible Y value
                if (subbox.getClearing() != CLEAR_NONE)
                {
                    int ny = stat.y;
                    if (subbox.getClearing() == CLEAR_LEFT)
                        ny = fleft.getMaxY() - floatY;
                    else if (subbox.getClearing() == CLEAR_RIGHT)
                        ny = fright.getMaxY() - floatY;
                    else if (subbox.getClearing() == CLEAR_BOTH)
                        ny = Math.max(fleft.getMaxY(), fright.getMaxY()) - floatY;
                    if (stat.y < ny) 
                    {
                    	stat.y = ny;
                    	clearance = true;
                    }
                }
                
                if (subbox.isInFlow()) //normal flow
                {
                    boolean boxempty = subbox.marginsAdjoin(); 
                    
                	//the border edge of the parent or the last placed box
                	int borderY = stat.y;
                	if (stat.lastinflow != null)
                	    borderY -= stat.lastinflow.emargin.bottom; //do not consider the margin applied by the layout
                	
                	//update expected top margin
                	if (subbox.emargin.top > mtop)
                	    mtop = subbox.emargin.top;
                	
                    //top margins are separated?
			        if (stat.firstseparated == null && separatedFromTop(this))
			        {
			        	//separated - cannot collapse, use the largest margin
			            borderY += mtop;
			        }
			        
			        //subsequent block margins
			        if (stat.firstseparated != null)
			        {
    		        	if (clearance) //some clearance, cannot collapse
    		        		borderY += mtop + mbottom;
    		        	else //do collapse
    		        		borderY += collapsedMarginHeight(mtop, mbottom);
			        }
			        
			        stat.lastinflow = subbox;
                    if (!boxempty && stat.firstseparated == null)
                        stat.firstseparated = subbox;
                    if (!boxempty)
                    {
                        stat.lastseparated = subbox;
                        mtop = 0;
                        mbottom = subbox.emargin.bottom;
                    }
			        
                    //update expected bottom margin
                    if (stat.lastseparated != null) //compute maximum of bottom margins after some separation
                    {
                        if (subbox.emargin.bottom > mbottom)
                            mbottom = subbox.emargin.bottom;
                    }
                    
                    if (subbox.emargin.top > 0) //place the border edge appropriately: overlap positive margins
                        stat.y = borderY - subbox.emargin.top;
                    
                    if (subbox.mayOverlapFloats())
                        layoutBlockInFlow(subbox, wlimit, stat);
                    else
                        layoutBlockInFlowAvoidFloats(subbox, wlimit, stat);
                        
                    if (subbox.getRest() != null) //not everything placed -- insert the rest to the queue
                        insertSubBox(i+1, subbox.getRest());
                    nexty = stat.y; //the flow influences current y
                }
                else if (subbox.getFloating() == FLOAT_LEFT || subbox.getFloating() == FLOAT_RIGHT) //floating boxes
                {
                    layoutBlockFloating(subbox, wlimit, stat);
                }
                else //absolute or fixed positioning
                {
                    layoutBlockPositioned(subbox, stat);
                }
                //accept the resulting Y coordinate
                stat.y = nexty;
            }
        }

        //collapse bottom margins
        if (!separatedFromBottom(this))
        {
  			stat.y -= mbottom;
        }
        
        //update the height when not set or set to "auto"
        if (!hasFixedHeight())
        {
            if (encloseFloats())
            {
                //enclose all floating boxes we own
                // http://www.w3.org/TR/CSS21/visudet.html#root-height
                int mfy = getFloatHeight() - floatY;
                if (mfy > stat.y) stat.y = mfy;
            }
            //the total height is the last Y coordinate
            setContentHeight(stat.y);
            updateSizes();
            updateChildSizes();
        }
        setSize(totalWidth(), totalHeight());
    }
1316998
function() {
      if (options.fit) {
        options.cy.fit(options.eles.nodes(), options.padding);
      }

      if (!ready) {
        ready = true;
        self.cy.one('layoutready', options.ready);
        self.cy.trigger({type: 'layoutready', layout: self});
      }
    }
431921
def strategy(data, params):
        
        width = params['width']
        with suppress(TypeError):
            iter(width)
            width = np.asarray(width)
            width = width[data.index]

        udata_group = data['group'].drop_duplicates()

        n = params.get('n', None)
        if n is None:
            n = len(udata_group)
        if n == 1:
            return data

        if not all([col in data.columns for col in ['xmin', 'xmax']]):
            data['xmin'] = data['x']
            data['xmax'] = data['x']

        d_width = np.max(data['xmax'] - data['xmin'])

        # Have a new group index from 1 to number of groups.
        # This might be needed if the group numbers in this set don't
        # include all of 1:n
        udata_group = udata_group.sort_values()
        groupidx = match(data['group'], udata_group)
        groupidx = np.asarray(groupidx) + 1

        # Find the center for each group, then use that to
        # calculate xmin and xmax
        data['x'] = data['x'] + width * ((groupidx - 0.5) / n - 0.5)
        data['xmin'] = data['x'] - (d_width / n) / 2
        data['xmax'] = data['x'] + (d_width / n) / 2

        return data
209296
def layout(args):
    
    from jcvi.algorithms.ec import GA_setup, GA_run

    p = OptionParser(layout.__doc__)
    p.set_beds()
    p.set_cpus(cpus=32)
    opts, args = p.parse_args(args)

    if len(args) != 3:
        sys.exit(not p.print_help())

    simplefile, qseqids, sseqids = args
    qbed, sbed, qorder, sorder, is_self = check_beds(simplefile, p, opts)

    qseqids = qseqids.strip().split(",")
    sseqids = sseqids.strip().split(",")
    qseqids_ii = dict((s, i) for i, s in enumerate(qseqids))
    sseqids_ii = dict((s, i) for i, s in enumerate(sseqids))

    blocks = SimpleFile(simplefile).blocks
    scores = defaultdict(int)
    for a, b, c, d, score, orientation, hl in blocks:
        qi, q = qorder[a]
        si, s = sorder[c]
        qseqid, sseqid = q.seqid, s.seqid
        if sseqid not in sseqids:
            continue
        scores[sseqids_ii[sseqid], qseqid] += score

    data = []
    for (a, b), score in sorted(scores.items()):
        if b not in qseqids_ii:
            continue
        data.append((qseqids_ii[b], score))

    tour = range(len(qseqids))
    toolbox = GA_setup(tour)
    toolbox.register("evaluate", colinear_evaluate_weights, data=data)
    tour, fitness = GA_run(toolbox, ngen=100, npop=100, cpus=opts.cpus)
    tour = [qseqids[x] for x in tour]

    print(",".join(tour))
19666
def run(self):
        
        logger.info(
            "The {} strategy will be applied on each duplicate set.".format(
                self.conf.strategy))

        self.stats['set_total'] = len(self.mails)

        for hash_key, mail_path_set in self.mails.items():
            # Print visual clue to separate duplicate sets.
            logger.info('---')

            duplicates = DuplicateSet(hash_key, mail_path_set, self.conf)

            # Perfom the deduplication.
            duplicates.dedupe()

            # Merge stats resulting of actions on duplicate sets.
            self.stats += duplicates.stats
915017
protected void layout ()
    {
        Graphics2D gfx = (Graphics2D)_host.getComponent().getGraphics();
        Font font = gfx.getFont();
        _bounds = new Rectangle();

        // figure out which items are included
        int icount = _items.size();
        ArrayList<RadialMenuItem> items = new ArrayList<RadialMenuItem>();
        for (int i = 0; i < icount; i++) {
            RadialMenuItem item = _items.get(i);
            if (item.isIncluded(this)) {
                items.add(item);
            }
        }

        // lay out all of our menu items
        int maxwid = 0, maxhei = 0;
        icount = items.size();
        for (int i = 0; i < icount; i++) {
            RadialMenuItem item = items.get(i);
            item.layout(gfx, font);

            // track maximum menu item size
            if (item.closedBounds.width > maxwid) {
                maxwid = item.closedBounds.width;
            }
            if (item.closedBounds.height > maxhei) {
                maxhei = item.closedBounds.height;
            }
        }
        gfx.dispose();

        // use the maximum of either width or height and make a circle around that
        double radius = Math.max(_tbounds.height, _tbounds.width) / 2;

        // be sure to add a gap and space for the menu item itself
        radius += (5 + maxwid/2);

        // compute the angle between menu items (we use the diameter of the menu items as an
        // approximate measure of the distance along the circumference)
        double theta = (maxwid + 10) / radius ;

        // now position each item accordingly
        double angle = -Math.PI/2;
        for (int i = 0; i < icount; i++) {
            RadialMenuItem item = items.get(i);
            int ix = (int)(radius * Math.cos(angle));
            int iy = (int)(radius * Math.sin(angle));
            item.openBounds.x = item.closedBounds.x = ix - maxwid/2;
            item.openBounds.y = item.closedBounds.y = iy - maxhei/2;

            // move along the circle
            angle += theta;
        }

        // create and position the centerpiece label
        if (_centerIcon != null) {
            _centerLabel = new RadialLabelSausage("", _centerIcon);
            _centerLabel.layout(gfx, font);
            _centerLabel.openBounds.x = _centerLabel.closedBounds.x =
                -(_centerLabel.closedBounds.width / 2);
            _centerLabel.openBounds.y = _centerLabel.closedBounds.y =
                -(_centerLabel.closedBounds.height / 2);
        }

        // now compute the rectangle that encloses the entire menu

        // include the bounds for the centerpiece label
        if (_centerLabel != null) {
            _bounds.add(_centerLabel.openBounds);
        }

        // include the bounds for all menu items
        for (int i = 0; i < icount; i++) {
            RadialMenuItem item = items.get(i);
            // we need the open bounds rather than the closed ones
            _bounds.add(item.openBounds);
        }

        // now translate everything from the center of the target bounds to the upper left of the
        // menu bounds
        if (_centerLabel != null) {
            _centerLabel.openBounds.translate(-_bounds.x, -_bounds.y);
            _centerLabel.closedBounds.translate(-_bounds.x, -_bounds.y);
        }
        for (int i = 0; i < icount; i++) {
            RadialMenuItem item = items.get(i);
            item.openBounds.translate(-_bounds.x, -_bounds.y);
            item.closedBounds.translate(-_bounds.x, -_bounds.y);
        }

        // the origin was at the center of the encircled rectangle; we need to translate it such
        // that the origin of our bounds are in screen coordinates and at the upper left rather
        // than the center
        _bounds.x += (_tbounds.x + _tbounds.width/2);
        _bounds.y += (_tbounds.y + _tbounds.height/2);

        // now make sure the whole shebang is fully visible within the host component
        Rectangle hbounds = _host.getViewBounds();
        Point pos = SwingUtil.fitRectInRect(_bounds, hbounds);
        _bounds.setLocation(pos);
    }
21455
private void setStrategy(final ClassRealm realm, final Strategy strategy) {
        assert realm != null;
        assert strategy != null;

        try {
            Field field = realm.getClass().getDeclaredField("strategy");

            try {
                field.set(realm, strategy);
            }
            catch (IllegalAccessException ignore) {
                // try again
                field.setAccessible(true);

                try {
                    field.set(realm, strategy);
                }
                catch (IllegalAccessException e) {
                    throw new IllegalAccessError(e.getMessage());
                }
            }
        }
        catch (NoSuchFieldException e) {
            throw new Error(e);
        }
    }
827912
@Override
    protected void doPerform() {
        if (isSourceDocumentRoot()) {
            getActions().doubleClick().perform();
        } else {
            getActions().doubleClick(getFirstElement()).perform();
        }
    }