subtract the sky from all the chips in the imagefile that imageSet represents

    imageSet is a single imageObject reference
    paramDict should be the subset from an actual config object
540877
def _skyUserFromHeaderKwd(imageSet,paramDict):
    
    _skyValue=0.0    #this will be the sky value computed for the exposure
    skyKW="MDRIZSKY" #header keyword that contains the sky that's been subtracted

    #just making sure, tricky users and all, these are things that will be used
    #by the sky function so we want them defined at least
    try:
        assert imageSet._numchips > 0, "invalid value for number of chips"
        assert imageSet._filename != '', "image object filename is empty!, doh!"
        assert imageSet._rootname != '', "image rootname is empty!, doh!"
        assert imageSet.scienceExt !='', "image object science extension is empty!"

    except AssertionError:
        raise AssertionError

    numchips=imageSet._numchips
    sciExt=imageSet.scienceExt

    # User Subtraction Case, User has done own sky subtraction,
    # so use the image header value for subtractedsky value
    skyuser=paramDict["skyuser"]

    if skyuser != '':
        print("User has computed their own sky values...")

        if skyuser != skyKW:
            print("    ...updating MDRIZSKY with supplied value.")
            for chip in range(1,numchips+1,1):
                chipext = '%s,%d'%(sciExt,chip)
                if not imageSet[chipext].group_member:
                    # skip extensions/chips that will not be processed
                    continue
                try:
                    _skyValue = imageSet[chipext].header[skyuser]
                except:
                    print("**************************************************************")
                    print("*")
                    print("*  Cannot find keyword ",skyuser," in ",imageSet._filename)
                    print("*")
                    print("**************************************************************\n\n\n")
                    raise KeyError

                _updateKW(imageSet[sciExt+','+str(chip)],
                          imageSet._filename,(sciExt,chip),skyKW,_skyValue)

                # Update internal record with subtracted sky value
                imageSet[chipext].subtractedSky = _skyValue
                imageSet[chipext].computedSky = None
                print("Setting ",skyKW,"=",_skyValue)
974240
def calibrate(self,
                  dataset_id,
                  pre_launch_coeffs=False,
                  calib_coeffs=None):
        
        tic = datetime.now()

        if calib_coeffs is None:
            calib_coeffs = {}

        units = {'reflectance': '%',
                 'brightness_temperature': 'K',
                 'counts': '',
                 'radiance': 'W*m-2*sr-1*cm ?'}

        if dataset_id.name in ("3a", "3b") and self._is3b is None:
            # Is it 3a or 3b:
            is3b = np.expand_dims(
                np.bitwise_and(
                    np.right_shift(self._data['scnlinbit'], 0), 1) == 1, 1)
            self._is3b = np.repeat(is3b,
                                   self._data['hrpt'][0].shape[0], axis=1)

        try:
            vis_idx = ['1', '2', '3a'].index(dataset_id.name)
            ir_idx = None
        except ValueError:
            vis_idx = None
            ir_idx = ['3b', '4', '5'].index(dataset_id.name)

        if vis_idx is not None:
            coeffs = calib_coeffs.get('ch' + dataset_id.name)
            ds = create_xarray(
                _vis_calibrate(self._data,
                               vis_idx,
                               dataset_id.calibration,
                               pre_launch_coeffs,
                               coeffs,
                               mask=(dataset_id.name == '3a' and self._is3b)))
        else:
            ds = create_xarray(
                _ir_calibrate(self._header,
                              self._data,
                              ir_idx,
                              dataset_id.calibration,
                              mask=(dataset_id.name == '3b' and
                                    np.logical_not(self._is3b))))

        if dataset_id.name == '3a' and np.all(np.isnan(ds)):
            raise ValueError("Empty dataset for channel 3A")
        if dataset_id.name == '3b' and np.all(np.isnan(ds)):
            raise ValueError("Empty dataset for channel 3B")

        ds.attrs['units'] = units[dataset_id.calibration]
        ds.attrs.update(dataset_id._asdict())

        logger.debug("Calibration time %s", str(datetime.now() - tic))

        return ds
785699
def tenengrad(img, ksize=3):
    '''''''
    Gx = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=ksize)
    Gy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=ksize)
    FM = Gx*Gx + Gy*Gy
    mn = cv2.mean(FM)[0]
    if np.isnan(mn):
        return np.nanmean(FM)
    return mn
247700
def generateXY(self, **kwargs):
        
        #x,y,flux,sharp,round = idlphot.find(array,self.pars['hmin'],self.pars['fwhm'],
        #                    roundlim=self.pars['roundlim'], sharplim=self.pars['sharplim'])
        print("  #  Source finding for '{}', EXT={} started at: {}"
              .format(self.fnamenoext, self.wcs.extname, util._ptime()[0]))
        if self.pars['computesig']:
            # compute sigma for this image
            sigma = self._compute_sigma()
        else:
            sigma = self.pars['skysigma']
        skymode = sigma**2
        log.info('   Finding sources using sky sigma = %f'%sigma)
        if self.pars['threshold'] in [None,"INDEF",""," "]:
            hmin = skymode
        else:
            hmin = sigma*self.pars['threshold']

        if 'mask' in kwargs and kwargs['mask'] is not None:
            dqmask = np.asarray(kwargs['mask'], dtype=bool)
        else:
            dqmask = None

        # get the mask for source finding:
        mask = self._combine_exclude_mask(dqmask)

        x, y, flux, src_id, sharp, round1, round2 = tweakutils.ndfind(
            self.source,
            hmin,
            self.pars['conv_width'],
            skymode,
            sharplim=[self.pars['sharplo'],self.pars['sharphi']],
            roundlim=[self.pars['roundlo'],self.pars['roundhi']],
            peakmin=self.pars['peakmin'],
            peakmax=self.pars['peakmax'],
            fluxmin=self.pars['fluxmin'],
            fluxmax=self.pars['fluxmax'],
            nsigma=self.pars['nsigma'],
            ratio=self.pars['ratio'],
            theta=self.pars['theta'],
            mask=mask,
            use_sharp_round=self.use_sharp_round,
            nbright=self.nbright
        )

        if len(x) == 0:
            if  not self.pars['computesig']:
                sigma = self._compute_sigma()
                hmin = sigma * self.pars['threshold']
                log.info('No sources found with original thresholds. Trying automatic settings.')
                x, y, flux, src_id, sharp, round1, round2 = tweakutils.ndfind(
                    self.source,
                    hmin,
                    self.pars['conv_width'],
                    skymode,
                    sharplim=[self.pars['sharplo'],self.pars['sharphi']],
                    roundlim=[self.pars['roundlo'],self.pars['roundhi']],
                    peakmin=self.pars['peakmin'],
                    peakmax=self.pars['peakmax'],
                    fluxmin=self.pars['fluxmin'],
                    fluxmax=self.pars['fluxmax'],
                    nsigma=self.pars['nsigma'],
                    ratio=self.pars['ratio'],
                    theta=self.pars['theta'],
                    mask = mask,
                    use_sharp_round = self.use_sharp_round,
                    nbright=self.nbright
                )
        if len(x) == 0:
            xypostypes = 3*[float]+[int]+(3 if self.use_sharp_round else 0)*[float]
            self.xypos = [np.empty(0, dtype=i) for i in xypostypes]
            warnstr = textutil.textbox('WARNING: \n'+
                'No valid sources found with the current parameter values!')
            for line in warnstr.split('\n'):
                log.warning(line)
            print(warnstr)
        else:
            # convert the positions from numpy 0-based to FITS 1-based
            if self.use_sharp_round:
                self.xypos = [x+1, y+1, flux, src_id+self.start_id, sharp, round1, round2]
            else:
                self.xypos = [x+1, y+1, flux, src_id+self.start_id]

        log.info('###Source finding finished at: %s'%(util._ptime()[0]))

        self.in_units = 'pixels' # Not strictly necessary, but documents units when determined
        self.sharp = sharp
        self.round1 = round1
        self.round2 = round2
        self.numcols = 7 if self.use_sharp_round else 4
        self.num_objects = len(x)
        self._apply_flux_limits = False
528579
public static int numExamplesTrain(Set dataSet) {
        switch (dataSet) {
            case COMPLETE:
                return NUM_COMPLETE_TRAIN;
            case MERGE:
                return NUM_MERGE_TRAIN;
            case BALANCED:
                return NUM_BALANCED_TRAIN;
            case LETTERS:
                return NUM_LETTERS_TRAIN;
            case DIGITS:
                return NUM_DIGITS_TRAIN;
            case MNIST:
                return NUM_MNIST_TRAIN;
            default:
                throw new UnsupportedOperationException("Unknown Set: " + dataSet);
        }
    }
411340
private void calc() {
        int hMin = (int) ((this.cImage.getHeight()) / 4.0);
        int hMax = (int) ((this.cImage.getHeight()) * 3.0 / 4.0);
        init();

        for (int y = hMin; y < hMax; y++) {
            for (int x = 1; x < (this.cImage.getWidth() - 2); x++) {
                // only lower edges are considered
                if (ImageUtil.isBlack(this.cImage, x, y)) {
                    if (!ImageUtil.isBlack(this.cImage, x, y + 1)) {
                        calc(x, y);
                    }
                }
            }
        }

    }
176444
function isSubSet (aTestArray, aRefArray) {
		function isOutsideSet(sTestValue) {
			return aRefArray.indexOf(sTestValue) < 0; // value is not part of the reference set
		}
		return aTestArray && aRefArray && !aTestArray.some(isOutsideSet);
	}
1205138
function setToPairs(set) {
    var index = -1,
        result = Array(set.size);

    set.forEach(function(value) {
      result[++index] = [value, value];
    });
    return result;
  }
177239
def _canonize_content_input(self, dataset, single_style):
        
        unpack = lambda x: x
        if isinstance(dataset, _tc.SArray):
            dataset = _tc.SFrame({self.content_feature: dataset})
            if single_style:
                unpack = lambda sf: sf['stylized_' + self.content_feature]
        elif isinstance(dataset, _tc.Image):
            dataset = _tc.SFrame({self.content_feature: [dataset]})
            if single_style:
                unpack = lambda sf: sf['stylized_' + self.content_feature][0]
        return dataset, unpack
220249
def rm_subsets(ctx, dataset, kwargs):
    ""

    kwargs = parse_kwargs(kwargs)
    data(dataset, **ctx.obj).rm_subsets(**kwargs)
1038661
public static IntSet difference (IntSet set1, IntSet set2)
    {
        return and(set1, notView(set2));
    }
1196487
def _set_image(self, image, nodata=None):
        
        # convert to masked array:
        if isinstance(image, np.ma.core.MaskedArray):
            masked = image
        elif isinstance(image, np.core.ndarray):
            masked = self._build_masked_array(image, nodata)
        else:
            raise GeoRaster2NotImplementedError('only ndarray or masked array supported, got %s' % type(image))

        # make sure array is 3d:
        if len(masked.shape) == 3:
            self._image = masked
        elif len(masked.shape) == 2:
            self._image = masked[np.newaxis, :, :]
        else:
            raise GeoRaster2Error('expected 2d or 3d image, got shape=%s' % masked.shape)

        # update shape
        if self._shape is None:
            self._set_shape(self._image.shape)

        self._image_after_load_validations()
        if self._image_readonly:
            self._image.setflags(write=0)
1222465
function normalizeSourceSet(data) {
	var sourceSet = data.srcSet || data.srcset;

	if (Array.isArray(sourceSet)) {
		return sourceSet.join();
	}

	return sourceSet;
}
150355
public static void main( String args[] ){

		BufferedImage input = UtilImageIO.loadImage(fileName);
		GrayF32 inputF32 = ConvertBufferedImage.convertFrom(input,(GrayF32)null);

		GrayF32 blurred = new GrayF32(inputF32.width,inputF32.height);
		GrayF32 derivX = new GrayF32(inputF32.width,inputF32.height);
		GrayF32 derivY = new GrayF32(inputF32.width,inputF32.height);
		GrayF32 intensity = new GrayF32(inputF32.width,inputF32.height);
		GrayF32 orientation = new GrayF32(inputF32.width,inputF32.height);
		GrayF32 suppressed = new GrayF32(inputF32.width,inputF32.height);
		GrayS8 direction = new GrayS8(inputF32.width,inputF32.height);
		GrayU8 output = new GrayU8(inputF32.width,inputF32.height);

		BlurStorageFilter<GrayF32> blur = FactoryBlurFilter.gaussian(GrayF32.class,-1,2);
		ImageGradient<GrayF32,GrayF32> gradient = FactoryDerivative.sobel(GrayF32.class,null);

		blur.process(inputF32,blurred);
		gradient.process(blurred,derivX,derivY);

		float threshLow = 5;
		float threshHigh = 40;

		GradientToEdgeFeatures.intensityE(derivX, derivY, intensity);
		GradientToEdgeFeatures.direction(derivX, derivY, orientation);
		GradientToEdgeFeatures.discretizeDirection4(orientation, direction);
		GradientToEdgeFeatures.nonMaxSuppression4(intensity, direction, suppressed);

		BufferedImage renderedOrientation = VisualizeEdgeFeatures.renderOrientation4(direction,suppressed,threshLow,null);

		HysteresisEdgeTraceMark hysteresis = new HysteresisEdgeTraceMark();
		hysteresis.process(suppressed,direction,threshLow,threshHigh,output);

		BufferedImage renderedLabel = VisualizeBinaryData.renderBinary(output, false, null);

		ListDisplayPanel gui =  new ListDisplayPanel();
		gui.addImage(suppressed,"Suppressed Intensity");
		gui.addImage(intensity,"Raw Intensity");
		gui.addImage(renderedOrientation,"Orientation");
		gui.addImage(renderedLabel, "Labeled Contours");

		ShowImages.showWindow(gui,"Visualized Canny Steps", true);
	}
628731
def _validate_slices_form_uniform_grid(slice_datasets):
    '''
    
    '''
    invariant_properties = [
        'Modality',
        'SOPClassUID',
        'SeriesInstanceUID',
        'Rows',
        'Columns',
        'PixelSpacing',
        'PixelRepresentation',
        'BitsAllocated',
        'BitsStored',
        'HighBit',
    ]

    for property_name in invariant_properties:
        _slice_attribute_equal(slice_datasets, property_name)

    _validate_image_orientation(slice_datasets[0].ImageOrientationPatient)
    _slice_ndarray_attribute_almost_equal(slice_datasets, 'ImageOrientationPatient', 1e-5)

    slice_positions = _slice_positions(slice_datasets)
    _check_for_missing_slices(slice_positions)
897224
function getRectangleFromImagePlane(imagePlane) {
  // Get the points
  const topLeft = imagePointToPatientPoint(
    {
      x: 0,
      y: 0,
    },
    imagePlane
  );
  const topRight = imagePointToPatientPoint(
    {
      x: imagePlane.columns,
      y: 0,
    },
    imagePlane
  );
  const bottomLeft = imagePointToPatientPoint(
    {
      x: 0,
      y: imagePlane.rows,
    },
    imagePlane
  );
  const bottomRight = imagePointToPatientPoint(
    {
      x: imagePlane.columns,
      y: imagePlane.rows,
    },
    imagePlane
  );

  // Get each side as a vector
  const rect = {
    top: new external.cornerstoneMath.Line3(topLeft, topRight),
    left: new external.cornerstoneMath.Line3(topLeft, bottomLeft),
    right: new external.cornerstoneMath.Line3(topRight, bottomRight),
    bottom: new external.cornerstoneMath.Line3(bottomLeft, bottomRight),
  };

  return rect;
}
590698
private static void verifyImageNames(List<ImageConfiguration> ret) {
        for (ImageConfiguration config : ret) {
            if (config.getName() == null) {
                throw new IllegalArgumentException("Configuration error: <image> must have a non-null <name>");
            }
        }
    }