targetSize options: width, height, cover, aspectRatio
973811
public static function calculateScaleDimensions($source, $targetSize)
    {

        // Get size of image (handle different param-possibilities)
        if (is_string($source)) {
            $sourceSize = @getimagesize($source);
            $sourceSize['rotation'] = self::getExifRotation($source);
        } else if ($source instanceof Imagick) {
            $sourceSize = $source->getImageGeometry();
            $source = null;
        } else if ($source instanceof Kwf_Uploads_Row) {
            $sourceSize = $source->getImageDimensions();
            $source = null;
        } else {
            $sourceSize = $source;
            $source = null;
        }

        if (!$sourceSize) return false;
        if (!isset($sourceSize['rotation'])) $sourceSize['rotation'] = 0;

        $w = null;
        if (isset($sourceSize[0])) $w = $sourceSize[0];
        if (isset($sourceSize['width'])) $w = $sourceSize['width'];

        $h = null;
        if (isset($sourceSize[1])) $h = $sourceSize[1];
        if (isset($sourceSize['height'])) $h = $sourceSize['height'];

        if (!$w || !$h) return false;

        $originalSize = array($w, $h);

        // get output-width
        $outputWidth = 0;
        if (isset($targetSize[0])) $outputWidth = $targetSize[0];
        if (isset($targetSize['width'])) $outputWidth = $targetSize['width'];

        // get output-height
        $outputHeight = 0;
        if (isset($targetSize[1])) $outputHeight = $targetSize[1];
        if (isset($targetSize['height'])) $outputHeight = $targetSize['height'];

        // get crop-data
        $crop = isset($targetSize['crop']) ? $targetSize['crop'] : null;

        // get cover
        $cover = isset($targetSize['cover']) ? $targetSize['cover'] : true;

        // Check if image has to be rotated
        if ($sourceSize['rotation'] == 90) {
            $originalSize = array($originalSize[1], $originalSize[0]);
        }

        if ($outputWidth == 0 && $outputHeight == 0) {
            if ($crop) {
                $ret = array(
                    'width' => $crop['width'],
                    'height' => $crop['height'],
                    'rotate' => 0,
                    'crop' => array(
                        'x' => $crop['x'],
                        'y' => $crop['y'],
                        'width' => $crop['width'],
                        'height' => $crop['height']
                    )
                );
                if (isset($targetSize['imageCompressionQuality'])) {
                    $ret['imageCompressionQuality'] = $targetSize['imageCompressionQuality'];
                }

                return $ret;
            } else {
                // Handle keep original
                return array(
                    'width' => $originalSize[0],
                    'height' => $originalSize[1],
                    'rotate' => 0,
                    'crop' => array(
                        'x' => 0,
                        'y' => 0,
                        'width' => $originalSize[0],
                        'height' => $originalSize[1]
                    ),
                    'keepOriginal' => true,
                );
            }
        }


        // Calculate missing dimension
        $calculateWidth = $originalSize[0];
        $calculateHeight = $originalSize[1];
        if ($crop) {
            $calculateWidth = $crop['width'];
            $calculateHeight = $crop['height'];
        }

        if ($cover) { // image will always have defined size

            if ($outputWidth == 0) {
                if (isset($targetSize['aspectRatio'])) {
                    $outputWidth = round($outputHeight * $targetSize['aspectRatio']);
                } else {
                    $outputWidth = round($outputHeight * ($calculateWidth / $calculateHeight));
                }
                if ($outputWidth <= 0) $outputWidth = 1;
            }
            if ($outputHeight == 0) {
                if (isset($targetSize['aspectRatio']) && $targetSize['aspectRatio']) {
                    $outputHeight = round($outputWidth * $targetSize['aspectRatio']);
                } else {
                    $outputHeight = round($outputWidth * ($calculateHeight / $calculateWidth));
                }
                if ($outputHeight <= 0) $outputHeight = 1;
            }
            if (!$crop) { // crop from complete image
                $crop = array();
                // calculate crop depending on target-size
                if (($outputWidth / $outputHeight) >= ($originalSize[0] / $originalSize[1])) {
                    $crop['width'] = $originalSize[0];
                    $crop['height'] = $originalSize[0] * ($outputHeight / $outputWidth);
                } else {
                    $crop['height'] = $originalSize[1];
                    $crop['width'] = $originalSize[1] * ($outputWidth / $outputHeight);
                }
                // calculate x and y of crop
                $xDiff = $originalSize[0] - $crop['width'];
                $crop['x'] = $xDiff > 0 ? $xDiff / 2 : 0;
                $yDiff = $originalSize[1] - $crop['height'];
                $crop['y'] = $yDiff > 0 ? $yDiff / 2 : 0;
            } else {
                $oldCrop['width'] = $crop['width'];
                $oldCrop['height'] = $crop['height'];
                if (($outputWidth / $outputHeight) >= ($crop['width'] / $crop['height'])) {
                    $crop['width'] = $crop['width'];
                    $crop['height'] = $crop['width'] * ($outputHeight / $outputWidth);
                } else {
                    $crop['height'] = $crop['height'];
                    $crop['width'] = $crop['height'] * ($outputWidth / $outputHeight);
                }
                $xDiff = $oldCrop['width'] - $crop['width'];
                $crop['x'] += $xDiff > 0 ? $xDiff / 2 : 0;
                $yDiff = $oldCrop['height'] - $crop['height'];
                $crop['y'] += $yDiff > 0 ? $yDiff / 2 : 0;
            }

        } elseif (!$cover) { // image keeps aspectratio and will not be scaled up

            // calculateWidth is cropWidth if existing else originalWidth.
            // prevent image scale up
            if (!$crop) {
                $crop = array(
                    'x' => 0,
                    'y' => 0,
                    'width' => $originalSize[0],
                    'height' => $originalSize[1]
                );
            }
            if ($calculateWidth <= $outputWidth && $calculateHeight <= $outputHeight) {
                $outputWidth = $calculateWidth;
                $outputHeight = $calculateHeight;
            } else {
                if ($calculateWidth < $outputWidth) {
                    $outputWidth = $calculateWidth;
                }
                if ($calculateHeight < $outputHeight) {
                    $outputHeight = $calculateHeight;
                }
            }
            $widthRatio = $outputWidth ? $calculateWidth / $outputWidth : null;
            $heightRatio = $outputHeight ? $calculateHeight / $outputHeight : null;
            if ($widthRatio > $heightRatio) {
                $outputWidth = $calculateWidth / $widthRatio;
                $outputHeight = $calculateHeight / $widthRatio;
            } else if ($heightRatio > $widthRatio) {
                $outputWidth = $calculateWidth / $heightRatio;
                $outputHeight = $calculateHeight / $heightRatio;
            }

        }

        $outputWidth = round($outputWidth);
        if ($outputWidth <= 0) $outputWidth = 1;
        $outputHeight = round($outputHeight);
        if ($outputHeight <= 0) $outputHeight = 1;

        $ret = array(
            'width' => round($outputWidth),
            'height' => round($outputHeight),
            'rotate' => $sourceSize['rotation'],
            'crop' => $crop
        );
        if (isset($targetSize['imageCompressionQuality'])) {
            $ret['imageCompressionQuality'] = $targetSize['imageCompressionQuality'];
        }

        //Set values to match original-parameters when original won't change
        if ($ret['crop']['x'] == 0
            && $ret['crop']['y'] == 0
            && $ret['crop']['width'] == $originalSize[0]
            && $ret['crop']['height'] == $originalSize[1]
            && $ret['width'] == $originalSize[0]
            && $ret['height'] == $originalSize[1]
            && !$ret['rotate']
        ) {
            $ret['keepOriginal'] = true;
        }

        return $ret;
    }
315117
private Dimension layoutSize(Container target, boolean preferred)
	{
	synchronized (target.getTreeLock())
	{
		//  Each row must fit with the width allocated to the containter.
		//  When the container width = 0, the preferred width of the container
		//  has not yet been calculated so lets ask for the maximum.

		int targetWidth = target.getSize().width;
		Container container = target;

		while (container.getSize().width == 0 && container.getParent() != null)
		{
			container = container.getParent();
		}

		targetWidth = container.getSize().width;

		if (targetWidth == 0)
			targetWidth = Integer.MAX_VALUE;

		int hgap = getHgap();
		int vgap = getVgap();
		Insets insets = target.getInsets();
		int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
		int maxWidth = targetWidth - horizontalInsetsAndGap;

		//  Fit components into the allowed width

		Dimension dim = new Dimension(0, 0);
		int rowWidth = 0;
		int rowHeight = 0;

		int nmembers = target.getComponentCount();

		for (int i = 0; i < nmembers; i++)
		{
			Component m = target.getComponent(i);

			if (m.isVisible())
			{
				Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();

				//  Can't add the component to current row. Start a new row.

				if (rowWidth + d.width > maxWidth)
				{
					addRow(dim, rowWidth, rowHeight);
					rowWidth = 0;
					rowHeight = 0;
				}

				//  Add a horizontal gap for all components after the first

				if (rowWidth != 0)
				{
					rowWidth += hgap;
				}

				rowWidth += d.width;
				rowHeight = Math.max(rowHeight, d.height);
			}
		}

		addRow(dim, rowWidth, rowHeight);

		dim.width += horizontalInsetsAndGap;
		dim.height += insets.top + insets.bottom + vgap * 2;

		//	When using a scroll pane or the DecoratedLookAndFeel we need to
		//  make sure the preferred size is less than the size of the
		//  target containter so shrinking the container size works
		//  correctly. Removing the horizontal gap is an easy way to do this.

		Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);

		if (scrollPane != null && target.isValid())
		{
			dim.width -= (hgap + 1);
		}

		return dim;
	}
	}
1131243
def asizeof(self, *objs, **opts):
        '''
        '''
        if opts:
            self.set(**opts)
        s, _ = self._sizes(objs, None)
        return s
259750
void setPixelSize(final int wide, final int high)
    {
        m_wide = wide;

        m_high = high;

        if (LienzoCore.IS_CANVAS_SUPPORTED)
        {
            if (false == isSelection())
            {
                getElement().getStyle().setWidth(wide, Unit.PX);

                getElement().getStyle().setHeight(high, Unit.PX);
            }

            final CanvasElement element = getCanvasElement();

            element.setWidth(wide);

            element.setHeight(high);

            if (false == isSelection())
            {
                getContext().getNativeContext().initDeviceRatio();
            }

            if ((false == isSelection()) && (null != m_select))
            {
                m_select.setPixelSize(wide, high);
            }
        }
    }
759152
@Override protected void resize() {
        width  = clock.getWidth() - clock.getInsets().getLeft() - clock.getInsets().getRight();
        height = clock.getHeight() - clock.getInsets().getTop() - clock.getInsets().getBottom();

        if (aspectRatio * width > height) {
            width = 1 / (aspectRatio / height);
        } else if (1 / (aspectRatio / height) > width) {
            height = aspectRatio * width;
        }

        if (width > 0 && height > 0) {
            pane.setMaxSize(width, height);
            pane.relocate((clock.getWidth() - height) * 0.5, (clock.getHeight() - height) * 0.5);

            if (clock.isTextVisible()) {
                if (null == customFont) {
                    timeText.setFont(Locale.US == clock.getLocale() ? Fonts.robotoLight(0.5 * height) : Fonts.robotoLight(0.6 * height));
                } else {
                    timeText.setFont(Locale.US == clock.getLocale() ? new Font(customFont.getName(), 0.5 * height) : new Font(customFont.getName(), 0.6 * height));
                }
                timeText.setX((width - timeText.getLayoutBounds().getWidth()) * 0.5);
                if (clock.isDateVisible()) {
                    timeText.setY(height * 0.3);
                } else {
                    timeText.setY(height * 0.5);
                }
            }
            if (clock.isDateVisible()) {
                if (null == customFont) {
                    dateText.setFont(Fonts.robotoLight(0.3 * height));
                } else {
                    dateText.setFont(new Font(customFont.getName(), 0.3 * height));
                }
                dateText.setX((width - dateText.getLayoutBounds().getWidth()) * 0.5);
                dateText.setY(height * 0.8);
            }
        }
    }
242484
def do_size(self, w, h):
        """"""
        if (w is None):
            self.logger.debug("size: no scaling (nop)")
        else:
            self.logger.debug("size: scaling to (%d,%d)" % (w, h))
            self.image = self.image.resize((w, h))
            self.width = w
            self.height = h
687992
private void resize() {
        width  = getWidth() - getInsets().getLeft() - getInsets().getRight();
        height = getHeight() - getInsets().getTop() - getInsets().getBottom();
        size   = width < height ? width : height;

        double center = size * 0.5;

        if (width > 0 && height > 0) {
            pane.setMaxSize(size, size);
            pane.setPrefSize(size, size);
            pane.relocate((getWidth() - size) * 0.5, (getHeight() - size) * 0.5);

            ring.setStrokeWidth(size * 0.078125);
            ring.setRadius(center);
            ring.setCenterX(center);
            ring.setCenterY(center);

            dot.setRadius(size * 0.3125);
            dot.setCenterX(center);
            dot.setCenterY(center);

            redraw();
        }
    }
448231
@Override protected void resize() {
        width  = clock.getWidth() - clock.getInsets().getLeft() - clock.getInsets().getRight();
        height = clock.getHeight() - clock.getInsets().getTop() - clock.getInsets().getBottom();

        if (aspectRatio * width > height) {
            width = 1 / (aspectRatio / height);
        } else if (1 / (aspectRatio / height) > width) {
            height = aspectRatio * width;
        }

        if (width > 0 && height > 0) {
            pane.setMaxSize(width, height);
            pane.relocate((clock.getWidth() - height) * 0.5, (clock.getHeight() - height) * 0.5);

            canvas.setWidth(width);
            canvas.setHeight(height);

            dotSize     = height * 0.045455;
            spacer      = height * 0.022727;
            digitWidth  = 8 * dotSize + 7 * spacer;
            digitHeight = 15 * dotSize + 14 * spacer;
            digitSpacer = height * 0.09090909;
        }
    }
790296
function screenSize() {
        // remove earlier sizes
        html.className = html.className.replace(/ (w-|eq-|gt-|gte-|lt-|lte-|portrait|no-portrait|landscape|no-landscape)\d+/g, "");

        // Viewport width
        var iw = win.innerWidth || html.clientWidth,
            ow = win.outerWidth || win.screen.width;

        api.screen.innerWidth = iw;
        api.screen.outerWidth = ow;

        // for debugging purposes, not really useful for anything else
        pushClass("w-" + iw);

        each(conf.screens, function(width) {
            if (iw > width) {
                if (conf.screensCss.gt) {
                    pushClass("gt-" + width);
                }

                if (conf.screensCss.gte) {
                    pushClass("gte-" + width);
                }
            } else if (iw < width) {
                if (conf.screensCss.lt) {
                    pushClass("lt-" + width);
                }

                if (conf.screensCss.lte) {
                    pushClass("lte-" + width);
                }
            } else if (iw === width) {
                if (conf.screensCss.lte) {
                    pushClass("lte-" + width);
                }

                if (conf.screensCss.eq) {
                    pushClass("e-q" + width);
                }

                if (conf.screensCss.gte) {
                    pushClass("gte-" + width);
                }
            }
        });

        // Viewport height
        var ih = win.innerHeight || html.clientHeight,
            oh = win.outerHeight || win.screen.height;

        api.screen.innerHeight = ih;
        api.screen.outerHeight = oh;

        // no need for onChange event to detect this
        api.feature("portrait" , (ih > iw));
        api.feature("landscape", (ih < iw));
    }
75274
function parseAspectRatio(aspectRatio) {
  if (typeof aspectRatio !== 'string') {
    return false;
  }
  const isValidFormat = str => /^\d+(\.\d+)?:\d+(\.\d+)?$/.test(str);
  if (!isValidFormat(aspectRatio)) {
    return false;
  }

  const [width, height] = aspectRatio.split(':');

  return parseFloat(width) / parseFloat(height);
}
358304
def fitToSize(rect, targetWidth, targetHeight, bounds):
	
	
	# Determine the difference between the current size and target size
	x,y,w,h = rect
	diffX = w - targetWidth
	diffY = h - targetHeight
	
	# Determine if we are cropping or padding the width
	if diffX > 0:
		cropLeft  = math.floor(diffX / 2)
		cropRight = diffX - cropLeft
		x,y,w,h   = cropRect((x,y,w,h), 0, 0, cropLeft, cropRight)
	elif diffX < 0:
		padLeft  = math.floor(abs(diffX) / 2)
		padRight = abs(diffX) - padLeft
		x,y,w,h  = padRect((x,y,w,h), 0, 0, padLeft, padRight, bounds, False)
	
	# Determine if we are cropping or padding the height
	if diffY > 0:
		cropTop    = math.floor(diffY / 2)
		cropBottom = diffY - cropTop
		x,y,w,h    = cropRect((x,y,w,h), cropTop, cropBottom, 0, 0)
	elif diffY < 0:
		padTop    = math.floor(abs(diffY) / 2)
		padBottom = abs(diffY) - padTop
		x,y,w,h   = padRect((x,y,w,h), padTop, padBottom, 0, 0, bounds, False)
	
	return (x,y,w,h)
1115560
def resize(self, height, width, **kwargs):
        
        self.client.exec_resize(self.exec_id, height=height, width=width)
133881
def configure(options = {})
      dimentions = options.values_at(:height, :width).collect(&:to_i)
      begin
        @input.winsize = dimentions
      rescue TypeError
        @input.winsize = [*dimentions, 0, 0]
      end if dimentions.none?(&:zero?)
    end
925684
def SetSize(self, rect):
        

        grid = self.main_window.grid
        key = grid.actions.cursor

        drawn_rect = grid.grid_renderer._get_drawn_rect(grid, key, rect)

        self._tc.SetDimensions(drawn_rect.x, drawn_rect.y,
                               drawn_rect.width+2, drawn_rect.height+2,
                               wx.SIZE_ALLOW_MINUS_ONE)
        self._tc.Layout()
467806
private int setViewSize(int mode, int size, int drawableWidth) {
        int viewSize;
        switch (mode) {
            case MeasureSpec.EXACTLY:
                viewSize = size;
                break;

            case MeasureSpec.AT_MOST:
                viewSize = Math.min(drawableWidth, size);
                break;

            case MeasureSpec.UNSPECIFIED:
                viewSize = drawableWidth;
                break;

            default:
                viewSize = size;
                break;
        }
        return viewSize;
    }
290497
function(context, options) {
        options = OpenLayers.Util.applyDefaults({
            maxExtent:  context.maxExtent,
            projection: context.projection,
            units:      context.units
        }, options);

        if (options.maxExtent) {
            options.maxResolution = 
                options.maxExtent.getWidth() / OpenLayers.Map.TILE_WIDTH;
        }

        var metadata = {
            contactInformation: context.contactInformation,
            "abstract":         context["abstract"],
            keywords:           context.keywords,
            logo:               context.logo,
            descriptionURL:     context.descriptionURL
        };

        options.metadata = metadata;

        var map = new OpenLayers.Map(options);
        map.addLayers(this.getLayersFromContext(context.layersContext));
        map.setCenter(
            context.bounds.getCenterLonLat(),
            map.getZoomForExtent(context.bounds, true)
        );
        return map;
    }
61321
function selectDimensionsAndMaterials() {
  let reverbLength = document.getElementById('reverbLengthSelect').value;
  switch (reverbLength) {
    case 'none':
    default:
    {
      return {
        dimensions: {
          width: 0,
          height: 0,
          depth: 0,
        },
        materials: {
          left: 'transparent',
          right: 'transparent',
          front: 'transparent',
          back: 'transparent',
          up: 'transparent',
          down: 'transparent',
        },
      };
    }
    break;
    case 'short':
    {
      return {
        dimensions: {
          width: 1.5,
          height: 1.5,
          depth: 1.5,
        },
        materials: {
          left: 'uniform',
          right: 'uniform',
          front: 'uniform',
          back: 'uniform',
          up: 'uniform',
          down: 'uniform',
        },
      };
    }
    break;
    case 'medium':
    {
      return {
        dimensions: {
          width: 6,
          height: 6,
          depth: 6,
        },
        materials: {
          left: 'uniform',
          right: 'uniform',
          front: 'uniform',
          back: 'uniform',
          up: 'uniform',
          down: 'uniform',
        },
      };
    }
    break;
    case 'long':
    {
      return {
        dimensions: {
          width: 24,
          height: 24,
          depth: 24,
        },
        materials: {
          left: 'uniform',
          right: 'uniform',
          front: 'uniform',
          back: 'uniform',
          up: 'uniform',
          down: 'uniform',
        },
      };
    }
    break;
  }
}