Volume utilities intended for use with data augmentation crop is the size of output dx,dy are offset wrt incoming volume, of the shift fliplr is boolean on whether we also want to flip left<->right
498547
function(V, crop, dx, dy, fliplr) {
    // note assumes square outputs of size crop x crop
    if(typeof(fliplr)==='undefined') var fliplr = false;
    if(typeof(dx)==='undefined') var dx = global.randi(0, V.sx - crop);
    if(typeof(dy)==='undefined') var dy = global.randi(0, V.sy - crop);
    
    // randomly sample a crop in the input volume
    var W;
    if(crop !== V.sx || dx!==0 || dy!==0) {
      W = new Vol(crop, crop, V.depth, 0.0);
      for(var x=0;x<crop;x++) {
        for(var y=0;y<crop;y++) {
          if(x+dx<0 || x+dx>=V.sx || y+dy<0 || y+dy>=V.sy) continue; // oob
          for(var d=0;d<V.depth;d++) {
           W.set(x,y,d,V.get(x+dx,y+dy,d)); // copy data over
          }
        }
      }
    } else {
      W = V;
    }

    if(fliplr) {
      // flip volume horziontally
      var W2 = W.cloneAndZero();
      for(var x=0;x<W.sx;x++) {
        for(var y=0;y<W.sy;y++) {
          for(var d=0;d<W.depth;d++) {
           W2.set(x,y,d,W.get(W.sx - x - 1,y,d)); // copy data over
          }
        }
      }
      W = W2; //swap
    }
    return W;
  }
366282
def _get_resize_target(img, crop_target, do_crop=False)->TensorImageSize:
    ""
    if crop_target is None: return None
    ch,r,c = img.shape
    target_r,target_c = crop_target
    ratio = (min if do_crop else max)(r/target_r, c/target_c)
    return ch,int(round(r/ratio)),int(round(c/ratio))
47808
public static long addWithOverflow(Slice left, Slice right, Slice result)
    {
        boolean leftNegative = isNegative(left);
        boolean rightNegative = isNegative(right);
        long overflow = 0;
        if (leftNegative == rightNegative) {
            // either both negative or both positive
            overflow = addUnsignedReturnOverflow(left, right, result, leftNegative);
            if (leftNegative) {
                overflow = -overflow;
            }
        }
        else {
            int compare = compareAbsolute(left, right);
            if (compare > 0) {
                subtractUnsigned(left, right, result, leftNegative);
            }
            else if (compare < 0) {
                subtractUnsigned(right, left, result, !leftNegative);
            }
            else {
                setToZero(result);
            }
        }
        return overflow;
    }
336173
int getRowByYWithShift(int y, int shiftEveryStep) {
        checkForInit();
        int sum = 0;
        // header offset
        int tempY = y - mHeaderColumnHeight;
        if (tempY <= sum) {
            return 0;
        }
        for (int count = mRowHeights.length, i = 0; i < count; i++) {
            int nextSum = sum + mRowHeights[i] + shiftEveryStep;

            if (tempY > sum && tempY < nextSum) {
                return i;
            } else if (tempY < nextSum) {
                return i - 1;
            }
            sum = nextSum;
        }
        return mRowHeights.length - 1;
    }
523450
def switch_to_output(self, value=False, **kwargs):
        
        self.direction = digitalio.Direction.OUTPUT
        self.value = value
480690
private boolean
toWire(DNSOutput out, int maxLength) {
	if (maxLength < Header.LENGTH)
		return false;

	Header newheader = null;

	int tempMaxLength = maxLength;
	if (tsigkey != null)
		tempMaxLength -= tsigkey.recordLength();

	OPTRecord opt = getOPT();
	byte [] optBytes = null;
        if (opt != null) {
		optBytes = opt.toWire(Section.ADDITIONAL);
		tempMaxLength -= optBytes.length;
	}

	int startpos = out.current();
	header.toWire(out);
	Compression c = new Compression();
	int flags = header.getFlagsByte();
	int additionalCount = 0;
	for (int i = 0; i < 4; i++) {
		int skipped;
		if (sections[i] == null)
			continue;
		skipped = sectionToWire(out, i, c, tempMaxLength);
		if (skipped != 0 && i != Section.ADDITIONAL) {
			flags = Header.setFlag(flags, Flags.TC, true);
			out.writeU16At(header.getCount(i) - skipped,
				       startpos + 4 + 2 * i);
			for (int j = i + 1; j < Section.ADDITIONAL; j++)
				out.writeU16At(0, startpos + 4 + 2 * j);
			break;
		}
		if (i == Section.ADDITIONAL)
			additionalCount = header.getCount(i) - skipped;
	}

	if (optBytes != null) {
		out.writeByteArray(optBytes);
		additionalCount++;
	}

	if (flags != header.getFlagsByte())
		out.writeU16At(flags, startpos + 2);

	if (additionalCount != header.getCount(Section.ADDITIONAL))
		out.writeU16At(additionalCount, startpos + 10);

	if (tsigkey != null) {
		TSIGRecord tsigrec = tsigkey.generate(this, out.toByteArray(),
						      tsigerror, querytsig);

		tsigrec.toWire(out, Section.ADDITIONAL, c);
		out.writeU16At(additionalCount + 1, startpos + 10);
	}

	return true;
}
477536
def taper_shift(waveform, output):
    

    if len(waveform) == len(output):
        output.data += waveform.data
    else:
        output.data[len(output)-len(waveform):] += waveform.data

    return output
750196
public static int cudnnLRNCrossChannelBackward(
        cudnnHandle handle, 
        cudnnLRNDescriptor normDesc, 
        int lrnMode, 
        Pointer alpha, 
        cudnnTensorDescriptor yDesc, 
        Pointer y, 
        cudnnTensorDescriptor dyDesc, 
        Pointer dy, 
        cudnnTensorDescriptor xDesc, 
        Pointer x, 
        Pointer beta, 
        cudnnTensorDescriptor dxDesc, 
        Pointer dx)
    {
        return checkResult(cudnnLRNCrossChannelBackwardNative(handle, normDesc, lrnMode, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));
    }
1235268
def generateForSize(width, height, dimOrder, maxWindowSize, overlapPercent, transforms = []):
	
	
	# If the input data is smaller than the specified window size,
	# clip the window size to the input size on both dimensions
	windowSizeX = min(maxWindowSize, width)
	windowSizeY = min(maxWindowSize, height)
	
	# Compute the window overlap and step size
	windowOverlapX = int(math.floor(windowSizeX * overlapPercent))
	windowOverlapY = int(math.floor(windowSizeY * overlapPercent))
	stepSizeX = windowSizeX - windowOverlapX
	stepSizeY = windowSizeY - windowOverlapY
	
	# Determine how many windows we will need in order to cover the input data
	lastX = width - windowSizeX
	lastY = height - windowSizeY
	xOffsets = list(range(0, lastX+1, stepSizeX))
	yOffsets = list(range(0, lastY+1, stepSizeY))
	
	# Unless the input data dimensions are exact multiples of the step size,
	# we will need one additional row and column of windows to get 100% coverage
	if len(xOffsets) == 0 or xOffsets[-1] != lastX:
		xOffsets.append(lastX)
	if len(yOffsets) == 0 or yOffsets[-1] != lastY:
		yOffsets.append(lastY)
	
	# Generate the list of windows
	windows = []
	for xOffset in xOffsets:
		for yOffset in yOffsets:
			for transform in [None] + transforms:
				windows.append(SlidingWindow(
					x=xOffset,
					y=yOffset,
					w=windowSizeX,
					h=windowSizeY,
					dimOrder=dimOrder,
					transform=transform
				))
	
	return windows
619853
def _crop_box(self, size):
        
        (left, top) = self.offset
        right = left + min(size[0], self.width)
        bottom = top + min(size[1], self.height)

        return (left, top, right, bottom)
634109
def _fused_batch_norm_op(self, input_batch, mean, variance, use_batch_stats):
    """"""
    # Store the original shape of the mean and variance.
    mean_shape = mean.get_shape()
    variance_shape = variance.get_shape()
    # The fused batch norm expects the mean, variance, gamma and beta
    # tensors to have dimension 1, so we flatten them to remove the
    # extra dimensions. In addition, it expects the input_batch to have
    # dimension 4, so we reshape it accordingly.
    gamma_flatten = tf.reshape(self._gamma, shape=(self._num_channels,))
    beta_flatten = tf.reshape(self._beta, shape=(self._num_channels,))
    flatten_mean = tf.reshape(mean, shape=(self._num_channels,))
    flatten_variance = tf.reshape(variance, shape=(self._num_channels,))
    use_batch_stats = tf.convert_to_tensor(use_batch_stats)

    input_shape = input_batch.get_shape()
    output_shape = [-1] + input_shape.as_list()[1:]

    flat_image_size = np.prod(self._image_shape, dtype=np.int32)

    if len(self._data_format) == 4:
      fusable_data_format = self._data_format
      fusable_batch = input_batch
    elif self._channel_index == 1 and self._image_shape:
      fusable_data_format = "NCHW"
      fusable_batch = tf.reshape(
          input_batch,
          shape=(-1, self._num_channels, 1, flat_image_size))
    else:
      # The CPU implementation of FusedBatchNorm only supports NHWC tensor
      # format for now.
      fusable_data_format = "NHWC"
      fusable_batch = tf.reshape(
          input_batch,
          shape=(-1, 1, flat_image_size, self._num_channels))

    common_args = {
        "scale": gamma_flatten,
        "offset": beta_flatten,
        "epsilon": self._eps,
        "data_format": fusable_data_format,
        "name": "batch_norm"
    }

    def use_batch_stats_fused_batch_norm():
      return tf.nn.fused_batch_norm(
          fusable_batch,
          mean=None,
          variance=None,
          is_training=True,
          **common_args)

    def moving_average_fused_batch_norm():
      return tf.nn.fused_batch_norm(
          fusable_batch,
          mean=flatten_mean,
          variance=flatten_variance,
          is_training=False,
          **common_args)

    batch_norm_op, mean, variance = utils.smart_cond(
        use_batch_stats, use_batch_stats_fused_batch_norm,
        moving_average_fused_batch_norm)

    if len(self._data_format) != 4:
      batch_norm_op = tf.reshape(batch_norm_op, output_shape)
    mean = tf.reshape(mean, mean_shape)
    variance = tf.reshape(variance, variance_shape)
    return batch_norm_op, mean, variance
441372
static void shiftLeftDestructive(Slice decimal, int leftShifts)
    {
        if (leftShifts == 0) {
            return;
        }

        int wordShifts = leftShifts / 64;
        int bitShiftsInWord = leftShifts % 64;
        int shiftRestore = 64 - bitShiftsInWord;

        // check overflow
        if (bitShiftsInWord != 0) {
            if ((getLong(decimal, 1 - wordShifts) & (-1L << shiftRestore)) != 0) {
                throwOverflowException();
            }
        }
        if (wordShifts == 1) {
            if (getLong(decimal, 1) != 0) {
                throwOverflowException();
            }
        }

        // Store negative before settings values to result.
        boolean negative = isNegative(decimal);

        long low;
        long high;

        switch (wordShifts) {
            case 0:
                low = getLong(decimal, 0);
                high = getLong(decimal, 1);
                break;
            case 1:
                low = 0;
                high = getLong(decimal, 0);
                break;
            default:
                throw new IllegalArgumentException();
        }

        if (bitShiftsInWord > 0) {
            high = (high << bitShiftsInWord) | (low >>> shiftRestore);
            low = (low << bitShiftsInWord);
        }

        pack(decimal, low, high, negative);
    }
300551
function flipImageData (data, width, height) {
  const numComponents = data.length / (width * height)
  for (let y = 0; y < height / 2; y++) {
    for (let x = 0; x < width; x++) {
      for (let c = 0; c < numComponents; c++) {
        const i = (y * width + x) * numComponents + c
        const flippedI = ((height - y - 1) * width + x) * numComponents + c
        const tmp = data[i]
        data[i] = data[flippedI]
        data[flippedI] = tmp
      }
    }
  }
}
1326710
function parse_Window2(blob, length, opts) {
	if(opts && opts.biff >= 2 && opts.biff < 8) return {};
	var f = blob.read_shift(2);
	return { RTL: f & 0x40 };
}
1327835
function shift (size) {
		size = size || samplesPerFrame;

		//if still empty - return existing buffer
		if (isEmpty) return data;

		let output = data.slice(0, size)

		data.consume(size)

		//if size is too small, fill with silence
		if (output.length < size) {
			output = util.pad(output, size)
		}

		return output;
	}
1109561
static void shiftRight(Slice decimal, int rightShifts, boolean roundUp, Slice result)
    {
        if (rightShifts == 0) {
            copyUnscaledDecimal(decimal, result);
            return;
        }

        int wordShifts = rightShifts / 64;
        int bitShiftsInWord = rightShifts % 64;
        int shiftRestore = 64 - bitShiftsInWord;

        // check round-ups before settings values to result.
        // be aware that result could be the same object as decimal.
        boolean roundCarry;
        if (bitShiftsInWord == 0) {
            roundCarry = roundUp && getLong(decimal, wordShifts - 1) < 0;
        }
        else {
            roundCarry = roundUp && (getLong(decimal, wordShifts) & (1L << (bitShiftsInWord - 1))) != 0;
        }

        // Store negative before settings values to result.
        boolean negative = isNegative(decimal);

        long low;
        long high;

        switch (wordShifts) {
            case 0:
                low = getLong(decimal, 0);
                high = getLong(decimal, 1);
                break;
            case 1:
                low = getLong(decimal, 1);
                high = 0;
                break;
            default:
                throw new IllegalArgumentException();
        }

        if (bitShiftsInWord > 0) {
            low = (low >>> bitShiftsInWord) | (high << shiftRestore);
            high = (high >>> bitShiftsInWord);
        }

        if (roundCarry) {
            if (low != ALL_BITS_SET_64) {
                low++;
            }
            else {
                low = 0;
                high++;
            }
        }

        pack(result, low, high, negative);
    }
466824
def swapWH(self):
        
        width = self.width
        self.width = self.height
        self.height = width