Compute CRC16

    :param frame: frame
    :type frame: str (Python2) or class bytes (Python3)
    :returns: CRC16
    :rtype: int
197476
def crc16(frame):
    
    crc = 0xFFFF
    for index, item in enumerate(bytearray(frame)):
        next_byte = item
        crc ^= next_byte
        for i in range(8):
            lsb = crc & 1
            crc >>= 1
            if lsb:
                crc ^= 0xA001
    return crc
703341
def _get_crc32(self, filename):
        
        buffer = self.zip.read(filename)
        if filename not in self.files_crc32:
            self.files_crc32[filename] = crc32(buffer)
            if self.files_crc32[filename] != self.zip.getinfo(filename).CRC:
                log.error("File '{}' has different CRC32 after unpacking! "
                          "Declared: {:08x}, Calculated: {:08x}".format(filename,
                                                                        self.zip.getinfo(filename).CRC,
                                                                        self.files_crc32[filename]))
        return buffer
473329
def sixteen2eight(I: np.ndarray, Clim: tuple) -> np.ndarray:
    
    Q = normframe(I, Clim)
    Q *= 255  # stretch to [0,255] as a float
    return Q.round().astype(np.uint8)
732632
def swd_read16(self, offset):
        
        value = self._dll.JLINK_SWD_GetU16(offset)
        return ctypes.c_uint16(value).value
616614
def _calculate_crc_ccitt(data):
    
    global CRC_CCITT_TABLE
    if not CRC_CCITT_TABLE:
        crc_ccitt_table = []
        for i in range(0, 256):
            crc = 0
            c = i << 8

            for j in range(0, 8):
                if (crc ^ c) & 0x8000:
                    crc = c_ushort(crc << 1).value ^ 0x1021
                else:
                    crc = c_ushort(crc << 1).value

                c = c_ushort(c << 1).value

            crc_ccitt_table.append(crc)
            CRC_CCITT_TABLE = crc_ccitt_table

    is_string = _is_string(data)
    crc_value = 0x0000  # XModem version

    for c in data:
        d = ord(c) if is_string else c
        tmp = ((crc_value >> 8) & 0xff) ^ d
        crc_value = ((crc_value << 8) & 0xff00) ^ CRC_CCITT_TABLE[tmp]

    return crc_value
821798
def process_frame(self, f, frame_str):
        
        frame_type = f.cmd.lower()
        if frame_type in ['connected', 'message', 'receipt', 'error', 'heartbeat']:
            if frame_type == 'message':
                (f.headers, f.body) = self.notify('before_message', f.headers, f.body)
            if log.isEnabledFor(logging.DEBUG):
                log.debug("Received frame: %r, headers=%r, body=%r", f.cmd, f.headers, f.body)
            else:
                log.info("Received frame: %r, len(body)=%r", f.cmd, utils.length(f.body))
            self.notify(frame_type, f.headers, f.body)
        else:
            log.warning("Unknown response frame type: '%s' (frame length was %d)", frame_type, utils.length(frame_str))
438873
def calc_crc(self, data, crc=0):
        '''
        

        '''
        for char in data:
            crc = (crc << 8) ^ self.crctable[((crc >> 8) ^ ord(char)) & 0xff]
        return crc & 0xffff
1213485
int read_frame_data(int bytesize) throws BitstreamException
	{
 		int	numread = 0;
		numread = readFully(frame_bytes, 0, bytesize);
		framesize = bytesize;
		wordpointer = -1;
	    bitindex = -1;
	    return numread;
	}
439362
def frame_size(self):
        """"""
        if self.sample_type == SampleType.S16NativeEndian:
            # Sample size is 2 bytes
            return self.sample_size * self.channels
        else:
            raise ValueError('Unknown sample type: %d', self.sample_type)
1346249
def find_importer_frame():
    
    byte = lambda ch: ord(ch) if PY2 else ch
    frame = inspect.currentframe()
    try:
        while frame:
            code = frame.f_code
            lasti = frame.f_lasti
            if byte(code.co_code[lasti]) == dis.opmap['IMPORT_NAME']:
                # FIXME: Support EXTENDED_ARG.
                arg = (
                    byte(code.co_code[lasti + 1])
                    + byte(code.co_code[lasti + 2]) * 256)
                name = code.co_names[arg]
                if name == 'end':
                    break
                end
            end
            frame = frame.f_back
        end
        return frame
    finally:
        del frame
    end
9963
def set_framebuffer_size_callback(window, cbfun):
    
    window_addr = ctypes.cast(ctypes.pointer(window),
                              ctypes.POINTER(ctypes.c_long)).contents.value
    if window_addr in _framebuffer_size_callback_repository:
        previous_callback = _framebuffer_size_callback_repository[window_addr]
    else:
        previous_callback = None
    if cbfun is None:
        cbfun = 0
    c_cbfun = _GLFWframebuffersizefun(cbfun)
    _framebuffer_size_callback_repository[window_addr] = (cbfun, c_cbfun)
    cbfun = c_cbfun
    _glfw.glfwSetFramebufferSizeCallback(window, cbfun)
    if previous_callback is not None and previous_callback[0] != 0:
        return previous_callback[0]
641448
def crc16_nojit(s, crc=0):
  """"""
  for ch in bytearray(s):  # bytearray's elements are integers in both python 2 and 3
    crc = ((crc << 8) & 0xFFFF) ^ _crc16_tab[((crc >> 8) & 0xFF) ^ (ch & 0xFF)]
    crc &= 0xFFFF
  return crc
878615
def register_frame(self, frame):
        
        self._frame = frame
        self.string_len = wcswidth if self._frame.canvas.unicode_aware else len
1339384
def req2frame(req, N: int=0):
    
    if req is None:
        frame = np.arange(N, dtype=np.int64)
    elif isinstance(req, int):  # the user is specifying a step size
        frame = np.arange(0, N, req, dtype=np.int64)
    elif len(req) == 1:
        frame = np.arange(0, N, req[0], dtype=np.int64)
    elif len(req) == 2:
        frame = np.arange(req[0], req[1], dtype=np.int64)
    elif len(req) == 3:
        # this is -1 because user is specifying one-based index
        frame = np.arange(req[0], req[1], req[2],
                          dtype=np.int64) - 1  # keep -1 !
    else:  # just return all frames
        frame = np.arange(N, dtype=np.int64)

    return frame
106363
def getDMCframe(f, iFrm: int, finf: dict, verbose: bool=False):
    
    # on windows, "int" is int32 and overflows at 2.1GB!  We need np.int64
    currByte = iFrm * finf['bytesperframe']
# %% advance to start of frame in bytes
    if verbose:
        print(f'seeking to byte {currByte}')

    assert isinstance(iFrm, (int, int64)), 'int32 will fail on files > 2GB'

    try:
        f.seek(currByte, 0)
    except IOError as e:
        raise IOError(f'I couldnt seek to byte {currByte:d}. try using a 64-bit integer for iFrm \n'
                      'is {f.name} a DMCdata file?  {e}')
# %% read data ***LABVIEW USES ROW-MAJOR C ORDERING!!
    try:
        currFrame = fromfile(f, uint16,
                             finf['pixelsperimage']).reshape((finf['supery'], finf['superx']),
                                                             order='C')
    except ValueError as e:
        raise ValueError(f'read past end of file?  {e}')

    rawFrameInd = meta2rawInd(f, finf['nmetadata'])

    if rawFrameInd is None:  # 2011 no metadata file
        rawFrameInd = iFrm + 1  # fallback

    return currFrame, rawFrameInd
510281
def _multiframe_to_block(multiframe_dicom):
    
    # Calculate the amount of stacks and slices in the stack
    number_of_stack_slices = int(common.get_ss_value(multiframe_dicom[Tag(0x2001, 0x105f)][0][Tag(0x2001, 0x102d)]))
    number_of_stacks = int(int(multiframe_dicom.NumberOfFrames) / number_of_stack_slices)

    # We create a numpy array
    size_x = multiframe_dicom.pixel_array.shape[2]
    size_y = multiframe_dicom.pixel_array.shape[1]
    size_z = number_of_stack_slices
    size_t = number_of_stacks
    # get the format
    format_string = common.get_numpy_type(multiframe_dicom)

    # get header info needed for ordering
    frame_info = multiframe_dicom[0x5200, 0x9230]

    data_4d = numpy.zeros((size_z, size_y, size_x, size_t), dtype=format_string)

    # loop over each slice and insert in datablock
    t_location_index = _get_t_position_index(multiframe_dicom)
    for slice_index in range(0, size_t * size_z):

        z_location = frame_info[slice_index].FrameContentSequence[0].InStackPositionNumber - 1
        if t_location_index is None:
            t_location = frame_info[slice_index].FrameContentSequence[0].TemporalPositionIndex - 1
        else:
            t_location = frame_info[slice_index].FrameContentSequence[0].DimensionIndexValues[t_location_index] - 1

        block_data = multiframe_dicom.pixel_array[slice_index, :, :]
        # apply scaling
        rescale_intercept = frame_info[slice_index].PixelValueTransformationSequence[0].RescaleIntercept
        rescale_slope = frame_info[slice_index].PixelValueTransformationSequence[0].RescaleSlope
        block_data = common.do_scaling(block_data,
                                       rescale_slope, rescale_intercept)
        # switch to float if needed
        if block_data.dtype != data_4d.dtype:
            data_4d = data_4d.astype(block_data.dtype)
        data_4d[z_location, :, :, t_location] = block_data

    full_block = numpy.zeros((size_x, size_y, size_z, size_t), dtype=data_4d.dtype)

    # loop over each stack and reorganize the data
    for t_index in range(0, size_t):
        # transpose the block so the directions are correct
        data_3d = numpy.transpose(data_4d[:, :, :, t_index], (2, 1, 0))
        # add the block the the full data
        full_block[:, :, :, t_index] = data_3d

    return full_block
1163310
func (f *Frame) CRC() uint16 {
	var crc uint16
	if !f.Header.Protection() {
		return 0
	}
	crcdata := bytes.NewReader(f.buf[4:6])
	binary.Read(crcdata, binary.BigEndian, &crc)
	return crc
}