Temporary solution: WOA for surface track
489762
def woa_track_from_file(d, lat, lon, filename, varnames=None):
    
    d = np.asanyarray(d)
    lat = np.asanyarray(lat)
    lon = np.asanyarray(lon)

    lon[lon < 0] += 360

    doy = np.array([int(dd.strftime('%j')) for dd in d])

    nc = netCDF4.Dataset(expanduser(filename), 'r')

    if varnames is None:
        varnames = {}
        for v in nc.variables.keys():
            if nc.variables[v].dimensions == \
                    (u'time', u'depth', u'lat', u'lon'):
                        varnames[v] = v

    output = {}
    for v in varnames:
        output[v] = []

    for d_n, lat_n, lon_n in zip(doy, lat, lon):
        # Get the nearest point. In the future interpolate.
        n_d = (np.abs(d_n - nc.variables['time'][:])).argmin()
        n_x = (np.abs(lon_n - nc.variables['lon'][:])).argmin()
        n_y = (np.abs(lat_n - nc.variables['lat'][:])).argmin()

        for v in varnames:
            output[v].append(nc.variables[varnames[v]][n_d, 0, n_y, n_x])

    for v in varnames:
        output[v] = ma.fix_invalid(output[v])

    return output
3246
public void associateAllToDetected() {
		// initialize data structures
		List<CombinedTrack<TD>> all = new ArrayList<>();
		all.addAll(tracksReactivated);
		all.addAll(tracksDormant);
		all.addAll(tracksPureKlt);

		int numTainted = tracksReactivated.size() + tracksDormant.size();

		tracksReactivated.clear();
		tracksDormant.clear();

		// detect features
		detector.detect(input);
		// associate features
		associateToDetected(all);

		FastQueue<AssociatedIndex> matches = associate.getMatches();

		// See which features got respawned and which ones are made dormant
		for( int i = 0; i < numTainted; i++ ) {
			associated[i] = false;
		}

		for( AssociatedIndex a : matches.toList() ) {
			// don't mess with pure-KLT tracks
			if( a.src >= numTainted )
				continue;

			CombinedTrack<TD> t = all.get(a.src);

			t.set(detector.getLocation(a.dst));
			trackerKlt.setDescription((float) t.x, (float) t.y, t.track);
			tracksReactivated.add(t);
			associated[a.src] = true;
		}

		for( int i = 0; i < numTainted; i++ ) {
			if( !associated[i] ) {
				tracksDormant.add(all.get(i));
			}
		}
	}
980073
private void fastadd(int wo, int off) {
		this.buffer.add(off - this.sizeinwords);
		this.buffer.add(wo);
		this.sizeinwords = off + 1;
	}
1028453
private void refineMotionEstimate() {

		// use observations from the inlier set
		List<Stereo2D3D> data = new ArrayList<>();

		int N = matcher.getMatchSet().size();
		for( int i = 0; i < N; i++ ) {
			int index = matcher.getInputIndex(i);

			PointTrack l = candidates.get(index);
			LeftTrackInfo info = l.getCookie();
			PointTrack r = info.right;

			Stereo2D3D stereo = info.location;
			// compute normalized image coordinate for track in left and right image
			leftImageToNorm.compute(l.x,l.y,info.location.leftObs);
			rightImageToNorm.compute(r.x,r.y,info.location.rightObs);

			data.add(stereo);
		}

		// refine the motion estimate using non-linear optimization
		Se3_F64 keyToCurr = currToKey.invert(null);
		Se3_F64 found = new Se3_F64();
		if( modelRefiner.fitModel(data,keyToCurr,found) ) {
			found.invert(currToKey);
		}
	}
580684
private boolean estimateClose() {

		// estimate 2D motion
		if (!planeMotion.process(planeSamples.toList()))
			return false;

		// save solutions
		closeMotionKeyToCurr = planeMotion.getModelParameters();
		closeInlierCount = planeMotion.getMatchSet().size();

		// mark inliers as used
		for (int i = 0; i < closeInlierCount; i++) {
			int index = planeMotion.getInputIndex(i);
			VoTrack p = tracksOnPlane.get(index).getCookie();
			p.lastInlier = tick;
		}

		return true;
	}
295524
private void pruneTracks(SetTrackInfo<Desc> info, GrowQueue_I32 unassociated) {
		if( unassociated.size > maxInactiveTracks ) {
			// make the first N elements the ones which will be dropped
			int numDrop = unassociated.size-maxInactiveTracks;
			for (int i = 0; i < numDrop; i++) {
				int selected = rand.nextInt(unassociated.size-i)+i;
				int a = unassociated.get(i);
				unassociated.data[i] = unassociated.data[selected];
				unassociated.data[selected] = a;
			}
			List<PointTrack> dropList = new ArrayList<>();
			for (int i = 0; i < numDrop; i++) {
				dropList.add( info.tracks.get(unassociated.get(i)) );
			}
			for (int i = 0; i < dropList.size(); i++) {
				dropTrack(dropList.get(i));
			}
		}
	}
543482
function(){

            var tr
                ,intr
                ,aabb
                ,list = this.tracked
                ,i = list.length
                ;

            // for all tracked bodies
            while ( (--i) >= 0 ){

                tr = list[ i ];
                intr = tr.interval;
                aabb = tr.body.aabb();

                // copy the position (plus or minus) the aabb half-dimensions
                // into the min/max intervals
                intr.min.val.clone( aabb ).sub( aabb.hw, aabb.hh );
                intr.max.val.clone( aabb ).add( aabb.hw, aabb.hh );
            }
        }
877070
def clean_surface(surface, span):
    """"""
    surface = surface.replace('-', ' ')
    no_start = ['and', ' ']
    no_end = [' and', ' ']

    found = True
    while found:
        found = False
        for word in no_start:
            if surface.lower().startswith(word):
                surface = surface[len(word):]
                span = (span[0] + len(word), span[1])
                found = True
        for word in no_end:
            if surface.lower().endswith(word):
                surface = surface[:-len(word)]
                span = (span[0], span[1] - len(word))
                found = True

    if not surface:
        return None, None

    split = surface.lower().split()
    if split[0] in ['one', 'a', 'an'] and len(split) > 1 and split[1] in \
            r.UNITS + r.TENS:
        span = (span[0] + len(surface.split()[0]) + 1, span[1])
        surface = ' '.join(surface.split()[1:])

    return surface, span
1372242
protected void prepareDraw() {
    VertexAttribArrayState previousNio = null;
    int previousElementSize = 0;

    if (useNioBuffer == 0 && enabledArrays == previouslyEnabledArrays) {
      return;
    }

    for(int i = 0; i < VERTEX_ATTRIB_ARRAY_COUNT; i++) {
      int mask = 1 << i;
      int enabled = enabledArrays & mask;
      if (enabled != (previouslyEnabledArrays & mask)) {
        if (enabled != 0) {
          gl.enableVertexAttribArray(i);
        } else {
          gl.disableVertexAttribArray(i);
        }
      }
      if (enabled != 0 && (useNioBuffer & mask) != 0) {
        VertexAttribArrayState data = vertexAttribArrayState[i];
        if (previousNio != null && previousNio.nioBuffer == data.nioBuffer &&
            previousNio.nioBufferLimit >= data.nioBufferLimit) {
          if (boundArrayBuffer != previousNio.webGlBuffer) {
            gl.bindBuffer(ARRAY_BUFFER, previousNio.webGlBuffer);
            boundArrayBuffer = data.webGlBuffer;
          }
          gl.vertexAttribPointer(i, data.size, data.type, data.normalize, data.stride,
                                 data.nioBufferPosition * previousElementSize);
        } else {
          if (boundArrayBuffer != data.webGlBuffer) {
            gl.bindBuffer(ARRAY_BUFFER, data.webGlBuffer);
            boundArrayBuffer = data.webGlBuffer;
          }
          int elementSize = getElementSize(data.nioBuffer);
          int savePosition = data.nioBuffer.position();
          if (data.nioBufferPosition * elementSize < data.stride) {
            data.nioBuffer.position(0);
            gl.bufferData(ARRAY_BUFFER, getTypedArray(data.nioBuffer, data.type, data.nioBufferLimit *
                                                      elementSize), STREAM_DRAW);
            gl.vertexAttribPointer(i, data.size, data.type, data.normalize, data.stride,
                                   data.nioBufferPosition * elementSize);
            previousNio = data;
            previousElementSize = elementSize;
          } else {
            data.nioBuffer.position(data.nioBufferPosition);
            gl.bufferData(ARRAY_BUFFER, getTypedArray(data.nioBuffer, data.type,
                                                      (data.nioBufferLimit - data.nioBufferPosition) *
                                                      elementSize), STREAM_DRAW);
            gl.vertexAttribPointer(i, data.size, data.type, data.normalize, data.stride, 0);
          }
          data.nioBuffer.position(savePosition);
        }
      }
    }
    previouslyEnabledArrays = enabledArrays;
  }
732977
public static ArrayList<Trajectory> splitTrackInSubTracks(Trajectory t, int windowWidth, boolean overlapping){
		int increment = 1;
		if(overlapping==false){
			increment=windowWidth;
		}
		ArrayList<Trajectory> subTrajectories = new ArrayList<Trajectory>();
		boolean trackEndReached = false;
		
		for(int i = 0; i < t.size(); i=i+increment)
		{
			int upperBound = i+(windowWidth);
			if(upperBound>t.size()){
				upperBound=t.size();
				trackEndReached=true;
			}
			Trajectory help = new Trajectory(2, i);
			for(int j = i; j < upperBound; j++){
				help.add(t.get(j));
			}
			subTrajectories.add(help);
			if(trackEndReached){
				i=t.size();
			}
		}
		return subTrajectories;
	}
1094509
def _pooling_output_shape(input_shape, pool_size=(2, 2),
                          strides=None, padding='VALID'):
  """"""
  dims = (1,) + pool_size + (1,)  # NHWC
  spatial_strides = strides or (1,) * len(pool_size)
  strides = (1,) + spatial_strides + (1,)
  pads = padtype_to_pads(input_shape, dims, strides, padding)
  operand_padded = onp.add(input_shape, onp.add(*zip(*pads)))
  t = onp.floor_divide(onp.subtract(operand_padded, dims), strides) + 1
  return tuple(t)
46146
function( cylinder, head, sector ) {

    if( this.headsPerTrack < 0 || this.sectorsPerTrack < 0 )
      throw new Error( 'Unspecified device geometry' )

    return ( cylinder * this.headsPerTrack + head ) *
      this.sectorsPerTrack + ( sector - 1 )

  }
1207167
private void addNewTracks() {
		tracker.spawnTracks();
		List<PointTrack> spawned = tracker.getNewTracks(null);

		// estimate 3D coordinate using stereo vision
		for (PointTrack t : spawned) {
//			System.out.println("track spawn "+t.x+" "+t.y);
			VoTrack p = t.getCookie();
			if (p == null) {
				t.cookie = p = new VoTrack();
			}

			// compute normalized image coordinate
			pixelToNorm.compute(t.x, t.y, n);

//			System.out.println("         pointing "+pointing.x+" "+pointing.y+" "+pointing.z);

			// See if the point ever intersects the ground plane or not
			if (planeProjection.normalToPlane(n.x, n.y, p.ground)) {
				// the line above computes the 2D plane position of the point
				p.onPlane = true;
			} else {
				// Handle points at infinity which are off plane.

				// rotate observation pointing vector into plane reference frame
				pointing.set(n.x, n.y, 1);
				GeometryMath_F64.mult(cameraToPlane.getR(), pointing, pointing);
				pointing.normalize();

				// save value of y-axis in pointing vector
				double normXZ = Math.sqrt(pointing.x * pointing.x + pointing.z * pointing.z);
				p.pointingY = pointing.y / normXZ;

				// save the angle as a vector
				p.ground.x = pointing.z;
				p.ground.y = -pointing.x;
				// normalize to make later calculations easier
				p.ground.x /= normXZ;
				p.ground.y /= normXZ;

				p.onPlane = false;
			}

			p.lastInlier = tick;
		}
	}
1335236
protected void updateTrackLocation( SetTrackInfo<Desc> info, FastQueue<AssociatedIndex> matches) {
		info.matches.resize(matches.size);
		for (int i = 0; i < matches.size; i++) {
			info.matches.get(i).set(matches.get(i));
		}

		tracksActive.clear();
		for( int i = 0; i < info.matches.size; i++ ) {
			AssociatedIndex indexes = info.matches.data[i];
			PointTrack track = info.tracks.get(indexes.src);
			Point2D_F64 loc = info.locDst.data[indexes.dst];
			track.set(loc.x, loc.y);
			tracksActive.add(track);
		}
	}
1200945
private void associateToDetected( List<CombinedTrack<TD>> known ) {
		// initialize data structures
		detectedDesc.reset();
		knownDesc.reset();

		// create a list of detected feature descriptions
		int N = detector.getNumberOfFeatures();
		for( int i = 0; i < N; i++ ) {
			detectedDesc.add(detector.getDescription(i));
		}

		// create a list of previously created track descriptions
		for( CombinedTrack<TD> t : known ) {
			knownDesc.add(t.desc);
		}

		// associate features
		associate.setSource(knownDesc);
		associate.setDestination(detectedDesc);
		associate.associate();

		N = Math.max(known.size(),detector.getNumberOfFeatures());
		if( associated.length < N )
			associated = new boolean[N];
	}
1261856
protected void trace( int x , int y , int indexInten ) {

		int dx,dy;

		int indexOut = output.getIndex(x,y);
		open.grow().set(x,y);
		output.data[indexOut] = 1;
		intensity.data[ indexInten ] = MARK_TRAVERSED;

		while( open.size() > 0 ) {
			active.set(open.removeTail());
			indexInten = intensity.getIndex(active.x,active.y);
			int indexDir = direction.getIndex(active.x,active.y);

			boolean first = true;

			while( true ) {
				//----- First check along the direction of the edge.  Only need to check 2 points this way
				switch( direction.data[ indexDir ] ) {
					case  0: dx =  0;dy=  1; break;
					case  1: dx =  1;dy= -1; break;
					case  2: dx =  1;dy=  0; break;
					case -1: dx =  1;dy=  1; break;
					default: throw new RuntimeException("Unknown direction: "+direction.data[ indexDir ]);
				}

				int indexForward = indexInten + dy*intensity.stride + dx;
				int indexBackward = indexInten - dy*intensity.stride - dx;

				int prevIndexDir = indexDir;

				boolean match = false;

				// pixel coordinate of forward and backward point
				x = active.x; y = active.y;
				int fx = active.x+dx, fy = active.y+dy;
				int bx = active.x-dx, by = active.y-dy;

				if( intensity.isInBounds(fx,fy) && intensity.data[ indexForward ] >= lower ) {
					intensity.data[ indexForward ] = MARK_TRAVERSED;
					output.unsafe_set(fx, fy, 1);
					active.set(fx, fy);
					match = true;
					indexInten = indexForward;
					indexDir = prevIndexDir  + dy*intensity.stride + dx;
				}
				if( intensity.isInBounds(bx,by) && intensity.data[ indexBackward ] >= lower ) {
					intensity.data[ indexBackward ] = MARK_TRAVERSED;
					output.unsafe_set(bx,by,1);
					if( match ) {
						open.grow().set(bx,by);
					} else {
						active.set(bx,by);
						match = true;
						indexInten = indexBackward;
						indexDir = prevIndexDir  - dy*intensity.stride - dx;
					}
				}

				if( first || !match ) {
					boolean priorMatch = match;
					// Check local neighbors if its one of the end points, which would be the first point or
					// any point for which no matches were found
					match = checkAllNeighbors(x,y,match);

					if( !match )
						break;
					else {
						// if it was the first it's no longer the first
						first = false;

						// the point at the end was just added and is to be searched in the next iteration
						if( !priorMatch ) {
							indexInten = intensity.getIndex(active.x, active.y);
							indexDir = direction.getIndex(active.x,active.y);
						}
					}
				}
			}
		}
	}
445355
def _interpolate_stream_track_kick_aA(self):
        """"""
        if hasattr(self,'_kick_interpolatedObsTrackAA'): #pragma: no cover
            return None #Already did this
        #Calculate 1D meanOmega on a fine grid in angle and interpolate
        dmOs= numpy.array([\
                super(streamgapdf,self).meanOmega(da,oned=True,
                                                  tdisrupt=self._tdisrupt
                                                  -self._timpact,
                                                  use_physical=False)
                for da in self._kick_interpolatedThetasTrack])
        self._kick_interpTrackAAdmeanOmegaOneD=\
            interpolate.InterpolatedUnivariateSpline(\
            self._kick_interpolatedThetasTrack,dmOs,k=3)
        #Build the interpolated AA
        self._kick_interpolatedObsTrackAA=\
            numpy.empty((len(self._kick_interpolatedThetasTrack),6))
        for ii in range(len(self._kick_interpolatedThetasTrack)):
            self._kick_interpolatedObsTrackAA[ii,:3]=\
                self._progenitor_Omega+dmOs[ii]*self._dsigomeanProgDirection\
                *self._gap_sigMeanSign
            self._kick_interpolatedObsTrackAA[ii,3:]=\
                self._progenitor_angle+self._kick_interpolatedThetasTrack[ii]\
                *self._dsigomeanProgDirection*self._gap_sigMeanSign\
                -self._timpact*self._progenitor_Omega
            self._kick_interpolatedObsTrackAA[ii,3:]=\
                numpy.mod(self._kick_interpolatedObsTrackAA[ii,3:],2.*numpy.pi)
        return None