Lay out nested block boxes in this box
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());
    }
798002
def nest(label, nested)
      indented = indent
      indented.puts("#{label}:")
      nested.pretty_dump(indented.indent)
      self
    end
948805
def layout
      # This assumes that the container overlaps all the children.

      # Move all children if we have moved.
      @children.each.with_index do |child, index|
        child.x = padding_left + x
        child.y = padding_top + y
      end

      # Make us as wrap around the largest child.
      rect.width = (@children.map {|c| c.width }.max || 0) + padding_left + padding_right
      rect.height = (@children.map {|c| c.height }.max || 0) + padding_top + padding_bottom

      super
    end
420776
def _tabulate(rows, headers, spacing=5):
    """"""
    if len(rows) == 0:
        return "None\n"
    assert len(rows[0]) == len(headers)
    count = len(rows[0])
    widths = [0 for _ in range(count)]
    rows = [headers] + rows

    for row in rows:
        for index, field in enumerate(row):
            if len(str(field)) > widths[index]:
                widths[index] = len(str(field))

    output = ""
    for row in rows:
        for index, field in enumerate(row):
            field = str(field)
            output += field + (widths[index] - len(field) + spacing) * " "
        output += "\n"
    return output
592320
protected void layoutBlockInFlowAvoidFloats(BlockBox subbox, int wlimit, BlockLayoutStatus stat)
    {
        final int minw = subbox.getMinimalDecorationWidth(); //minimal subbox width for computing the space -- content is not considered (based on other browser observations) 
        int yoffset = stat.y + floatY; //starting offset
        int availw = 0;
        do
        {
            int fy = yoffset;
            int flx = fleft.getWidth(fy) - floatXl;
            if (flx < 0) flx = 0;
            int frx = fright.getWidth(fy) - floatXr;
            if (frx < 0) frx = 0;
            int avail = wlimit - flx - frx;
            
            //if it does not fit the width, try to move down
            //TODO the available space must be tested for the whole height of the subbox
            final int startfy = fy;
            //System.out.println("minw=" + minw + " avail=" + avail + " availw=" + availw);
            while ((flx > floatXl || frx > floatXr) //if the space can be narrower at least at one side
                   && (minw > avail)) //the subbox doesn't fit in this Y coordinate
            {
                int nexty = FloatList.getNextY(fleft, fright, fy);
                if (nexty == -1)
                    fy += Math.max(stat.maxh, getLineHeight()); //if we don't know try increasing by a line
                else
                    fy = nexty;
                //recompute the limits for the new fy
                flx = fleft.getWidth(fy) - floatXl;
                if (flx < 0) flx = 0;
                frx = fright.getWidth(fy) - floatXr;
                if (frx < 0) frx = 0;
                avail = wlimit - flx - frx;
            }
            //do not consider the top margin when moving down
            if (fy > startfy && subbox.margin.top != 0)
            {
                fy -= subbox.margin.top;
                if (fy < startfy) fy = startfy;
            }
            stat.y = fy - floatY;
            
            //position the box
            subbox.setFloats(new FloatList(subbox), new FloatList(subbox), 0, 0, 0);
            subbox.setPosition(flx,  stat.y);
            subbox.setWidthAdjust(-flx - frx);
            //if (availw != 0)
            //    System.out.println("jo!");
            subbox.doLayout(avail, true, true);
            //System.out.println("H=" + subbox.getHeight());
            
            //check the colisions after the layout
            int xlimit[] = computeFloatLimits(fy, fy + subbox.getBounds().height, new int[]{flx, frx});
            availw = wlimit - xlimit[0] - xlimit[1];
            if (minw > availw) //the whole box still does not fit
                yoffset = FloatList.getNextY(fleft, fright, fy); //new starting Y 
        } while (minw > availw && yoffset != -1);
        
        stat.y += subbox.getHeight();
        //maximal width
        if (subbox.getWidth() > stat.maxw)
            stat.maxw = subbox.getWidth();
    }
1210129
def group_items_html(grouped_items, options = {})
      default_opts  = {
          :group_nr_cols =>3,
          :item_nr_cols  => 1,
          :css_begin     => 'span-24 last',
          :render        => proc { |item| "<b>#{item.to_s}</b>" }
      }
      options       = default_opts.merge(options)
      title         = options[:title]
      group_nr_cols = options[:group_nr_cols]
      item_nr_cols  = options[:item_nr_cols]
      css_begin     = options[:css_begin]
      render        = options[:render]

      html          = ""
      html << "<h2>#{title}</h2>" if title
      grouped_items.each_with_index do |items_with_headers, items_box_index|
        headers = items_with_headers[0]
        items   = items_with_headers[1]
        html << "<div class='#{css_begin}'>" if (items_box_index % group_nr_cols) == 0
        if (items_box_index % group_nr_cols) == (group_nr_cols - 1)
          html << "<div class='span-8 last'>"
        else
          html << "<div class='span-8'>"
        end

        html << "<h2>"
        html << headers.first.to_s
        html << "- #{headers.last}" if headers.length > 1
        html << "</h2>"

        items.each_with_index do |item, index|
          if (index % (items.length / item_nr_cols + 1)) == 0
            html << "<div class='span-6#{index == ((items.length / item_nr_cols + 1) * (item_nr_cols-1)) ? "last" : ""}'/><ul>"
          end

          html << "<li>"
          html << render.call(item)
          html << "</li>"

          if (index % (items.length / item_nr_cols + 1)) == ((items.length / item_nr_cols + 1) -1)
            html << "</ul></div>"
          end
        end
        html << "</ul></div>" if ((items.length-1) % (items.length / item_nr_cols + 1)) != ((items.length / item_nr_cols + 1) -1)
        html << "</div>"
        html << "</div>" if (items_box_index % group_nr_cols) == (group_nr_cols - 1)
      end

      html
    end
749243
private void setup(DMatrixRBlock orig) {
        blockLength = orig.blockLength;
        dataW.blockLength = blockLength;
        dataWTA.blockLength = blockLength;

        this.dataA = orig;
        A.original = dataA;

        int l = Math.min(blockLength,orig.numCols);
        dataW.reshape(orig.numRows,l,false);
        dataWTA.reshape(l,orig.numRows,false);
        Y.original = orig;
        Y.row1 = W.row1 = orig.numRows;
        if( temp.length < blockLength )
            temp = new double[blockLength];
        if( gammas.length < orig.numCols )
            gammas = new double[ orig.numCols ];

        if( saveW ) {
            dataW.reshape(orig.numRows,orig.numCols,false);
        }
    }
1232339
def insert_rawblocks_factory(rawblocks):
    
    """

    # pylint: disable=unused-argument
    def insert_rawblocks(key, value, fmt, meta):
        """Inserts non-duplicate RawBlock elements."""

        if not rawblocks:
            return None

        # Put the RawBlock elements in front of the first block element that
        # isn't also a RawBlock.

        if not key in ['Plain', 'Para', 'CodeBlock', 'RawBlock',
                       'BlockQuote', 'OrderedList', 'BulletList',
                       'DefinitionList', 'Header', 'HorizontalRule',
                       'Table', 'Div', 'Null']:
            return None

        if key == 'RawBlock':  # Remove duplicates
            rawblock = RawBlock(*value)
            if rawblock in rawblocks:
                rawblocks.remove(rawblock)
                return None

        if rawblocks:  # Insert blocks
            el = _getel(key, value)
            return [rawblocks.pop(0) for i in range(len(rawblocks))] + [el]

        return None

    return insert_rawblocks
569965
function styleBoxes(selection, self) {
    selection
      .style('width', `${self.boxWidth}px`)
      .style('height', `${self.boxHeight}px`);
    // .style('margin', `${self.boxMargin / 2}px`)
  }
231872
def make_block(self, values, placement=None, ndim=None):
        
        if placement is None:
            placement = self.mgr_locs
        if ndim is None:
            ndim = self.ndim

        return make_block(values, placement=placement, ndim=ndim)
307819
function createRow(
    opts: Options,
    columns: number,
    getCellContent?: (column: number) => Node[]
): Block {
    const cellNodes = Range(0, columns)
        .map(i =>
            createCell(opts, getCellContent ? getCellContent(i) : undefined)
        )
        .toList();

    return Block.create({
        type: opts.typeRow,
        nodes: cellNodes
    });
}
749819
private void organizeContent()
    {
        cells = new Vector<TableCellBox>();
        TableCellBox anoncell = null;
        
        int size = nested.size();
        List<Box> toremove = new ArrayList<Box>();
        for (int i = 0; i < size; i++)
        {
            Box box = nested.get(i);
            
            if (box instanceof TableCellBox)
            {
                addCell((TableCellBox) box);
                //finish and add possible previous anonymous cell
                if (anoncell != null)
                {
                    anoncell.endChild = anoncell.nested.size();
                    addSubBox(anoncell);
                }
                anoncell = null;
            }
            else
            {
                if (anoncell == null)
                {
                    Element anonelem = viewport.getFactory().createAnonymousElement(getParent().getParent().getParent().getElement().getOwnerDocument(), "td", "table-cell");
                    anoncell = new TableCellBox(anonelem, g, ctx);
                    anoncell.adoptParent(this);
                    anoncell.setStyle(viewport.getFactory().createAnonymousStyle("table-cell"));
                    addCell(anoncell);
                }
                anoncell.addSubBox(box);
                anoncell.isempty = false;
                if (box.isBlock()) anoncell.contblock = true;
                box.setContainingBlockBox(anoncell);
                box.setParent(anoncell);
                toremove.add(box);
                endChild--;
            }
        }
        nested.removeAll(toremove);
        
        if (anoncell != null)
        {
            anoncell.endChild = anoncell.nested.size();
            addSubBox(anoncell);
        }
    }
1156894
def grid(box, draw)
      x, y, w, h = box.x, box.y, box.width, box.height
      use_cairo do |cc|
        (x..@width + w).step(w)  { |ix| line_xy(ix, y - @height, ix, @height + y, draw) }
        (y..@height + h).step(h) { |iy| line_xy(x - @width, iy, @width + x, iy, draw) }
      end
    end
90642
def flatten_blocks(lines, num_indents=-1):
    
    # The standard indent is four spaces
    INDENTATION = " " * 4

    if not lines:
        return ""

    # If this is a string, add the indentation and finish here
    if isinstance(lines, six.string_types):
        return INDENTATION * num_indents + lines

    # If this is not a string, join the lines and recurse
    return "\n".join([flatten_blocks(line, num_indents + 1) for line in lines])
674130
function createBoxes(count) {
    var boxes = [];
    for (var i = 0; i < N; i++) {
      boxes.push(
        V(
          elementFlag,
          "div",
          "box-view",
          V(elementFlag, "div", "box", count % 100, {
            style: {
              top: Math.sin(count / 10) * 10 + "px",
              left: Math.cos(count / 10) * 10 + "px",
              background: "rgb(0, 0," + count % 255 + ")"
            }
          })
        )
      );
    }
    return boxes;
  }
218248
function position() {
    
    // Bullets & friends are positioned an absolute distance to the left of
    // the content edge of their parent element
    $cb = $this->_frame->get_containing_block();
    
    // Note: this differs from most frames in that we must position
    // ourselves after determining our width
    $x = $cb["x"] - $this->_frame->get_width();

    $p = $this->_frame->find_block_parent();

    $y = $p->get_current_line_box()->y;

    // This is a bit of a hack...
    $n = $this->_frame->get_next_sibling();
    if ( $n ) {
      $style = $n->get_style();
      $line_height = $style->length_in_pt($style->line_height, $style->get_font_size());
      $offset = $style->length_in_pt($line_height, $n->get_containing_block("h")) - $this->_frame->get_height();             
      $y += $offset / 2;
    }

  // Now the position is the left top of the block which should be marked with the bullet.
  // We tried to find out the y of the start of the first text character within the block.
  // But the top margin/padding does not fit, neither from this nor from the next sibling
  // The "bit of a hack" above does not work also.
  
  // Instead let's position the bullet vertically centered to the block which should be marked.
  // But for get_next_sibling() the get_containing_block is all zero, and for find_block_parent()
  // the get_containing_block is paper width and the entire list as height.
  
    // if ($p) {
    //   //$cb = $n->get_containing_block();
    //   $cb = $p->get_containing_block();
    //   $y += $cb["h"]/2;
    // print 'cb:'.$cb["x"].':'.$cb["y"].':'.$cb["w"].':'.$cb["h"].':';
    // }   

  // Todo:
  // For now give up on the above. Use Guesswork with font y-pos in the middle of the line spacing

    /*$style = $p->get_style();
    $font_size = $style->get_font_size();
    $line_height = $style->length_in_pt($style->line_height, $font_size);
    $y += ($line_height - $font_size) / 2;    */
   
    //Position is x-end y-top of character position of the bullet.    
    $this->_frame->set_position($x, $y);
    
  }
1255916
function setup() {
		// ------------------------------
		// LIGHTBOX
		setupLigtbox();
		// ------------------------------
		
		
		
		// ------------------------------
		// CODE PRETTIFY
		if($('.prettyprint').length) {
			window.prettyPrint && prettyPrint();
		}
		// ------------------------------
		
		
		
		// ------------------------------
		// TABS
		$('.tabs').each(function() {
			if(!$(this).find('.tab-titles li a.active').length) {
				$(this).find('.tab-titles li:first-child a').addClass('active');
				$(this).find('.tab-content > div:first-child').show();
			} else {
				$(this).find('.tab-content > div').eq($(this).find('.tab-titles li a.active').parent().index()).show();	
			}
		});
		
		$('.tabs .tab-titles li a').click(function() {
			if($(this).hasClass('active')) { return; }
			$(this).parent().siblings().find('a').removeClass('active');
			$(this).addClass('active');
			$(this).parents('.tabs').find('.tab-content > div').hide().eq($(this).parent().index()).show();
			return false;
		});
		// ------------------------------
		
		
		// ------------------------------
		// TOGGLES
		var toggleSpeed = 300;
		$('.toggle h4.active + .toggle-content').show();
	
		$('.toggle h4').click(function() {
			if($(this).hasClass('active')) { 
				$(this).removeClass('active');
				$(this).next('.toggle-content').stop(true,true).slideUp(toggleSpeed);
			} else {
				
				$(this).addClass('active');
				$(this).next('.toggle-content').stop(true,true).slideDown(toggleSpeed);
				
				//accordion
				if($(this).parents('.toggle-group').hasClass('accordion')) {
					$(this).parent().siblings().find('h4').removeClass('active');
					$(this).parent().siblings().find('.toggle-content').stop(true,true).slideUp(toggleSpeed);
				}
				
			}
			return false;
		});
		// ------------------------------
		
		
		
		// ------------------------------
		// RESPONSIVE VIDEOS
		if($('.media-wrap, .portfolio-single').length) {
			$(".media-wrap, .portfolio-single").fitVids();
		}
		// ------------------------------
		
		
		
		// ------------------------------
		// UNIFORM
		$("select:not([multiple]), input:checkbox, input:radio, input:file").uniform();
		var ua = navigator.userAgent.toLowerCase();
		var isAndroid = ua.indexOf("android") > -1;
		if(isAndroid) {
			$('html').addClass('android');
		}
		// ------------------------------
		
		
		
		// ------------------------------
		/* FLEX SLIDER */
		// cache container
		var $flexslider = $('.flexslider');
		if($flexslider.length) {
			
			$flexslider.each(function() {
			
				//wait for images
				$(this).imagesLoaded(function() {
					
					//remove loading
					$(this).find('.loading').remove();
					
					//setup slider
					$(this).flexslider({ 
						smoothHeight: true,
						slideshow: $(this).attr('data-autoplay') != "false",
						slideshowSpeed: $(this).attr('data-interval'), 
						animationSpeed : $(this).attr('data-animationSpeed'),
						animation: $(this).attr('data-animation'), 
						direction : $(this).attr('data-direction'),
						directionNav : $(this).attr('data-directionNav') != "false",
						controlNav : $(this).attr('data-controlNav') != "false",
						randomize : $(this).attr('data-randomize') == "true",
						startAt : $(this).attr('data-startAt') != null ? parseInt($(this).attr('data-startAt')) : 0,
						animationLoop : $(this).attr('data-animationLoop') != "false",
						pauseOnHover : $(this).attr('data-pauseOnHover') != "false",
						reverse : $(this).attr('data-reverse') == "true",
						prevText: "",
						nextText: "",
						start: function(slider) {
								$('.slides li img').click(function(event){
									event.preventDefault();
									slider.flexAnimate(slider.getTarget("next"));
								});
							}
						});
					
				});
			
			});
		}
		// ------------------------------
		
		
		// ------------------------------
		/* MEDIAELEMENT.JS - self hosted html5 video and audio player */
		if($('video,audio').length) {
			$('video,audio').mediaelementplayer({ audioHeight: 50 });	
		}
		// ------------------------------
	}