segment to segment distance, ported from http://geomalgorithms.com/a07-_distance.html by Dan Sunday
483798
function sqSegSegDist(x0, y0, x1, y1, x2, y2, x3, y3) {
    var ux = x1 - x0;
    var uy = y1 - y0;
    var vx = x3 - x2;
    var vy = y3 - y2;
    var wx = x0 - x2;
    var wy = y0 - y2;
    var a = ux * ux + uy * uy;
    var b = ux * vx + uy * vy;
    var c = vx * vx + vy * vy;
    var d = ux * wx + uy * wy;
    var e = vx * wx + vy * wy;
    var D = a * c - b * b;

    var sc, sN, tc, tN;
    var sD = D;
    var tD = D;

    if (D === 0) {
        sN = 0;
        sD = 1;
        tN = e;
        tD = c;
    } else {
        sN = b * e - c * d;
        tN = a * e - b * d;
        if (sN < 0) {
            sN = 0;
            tN = e;
            tD = c;
        } else if (sN > sD) {
            sN = sD;
            tN = e + b;
            tD = c;
        }
    }

    if (tN < 0.0) {
        tN = 0.0;
        if (-d < 0.0) sN = 0.0;
        else if (-d > a) sN = sD;
        else {
            sN = -d;
            sD = a;
        }
    } else if (tN > tD) {
        tN = tD;
        if ((-d + b) < 0.0) sN = 0;
        else if (-d + b > a) sN = sD;
        else {
            sN = -d + b;
            sD = a;
        }
    }

    sc = sN === 0 ? 0 : sN / sD;
    tc = tN === 0 ? 0 : tN / tD;

    var cx = (1 - sc) * x0 + sc * x1;
    var cy = (1 - sc) * y0 + sc * y1;
    var cx2 = (1 - tc) * x2 + tc * x3;
    var cy2 = (1 - tc) * y2 + tc * y3;
    var dx = cx2 - cx;
    var dy = cy2 - cy;

    return dx * dx + dy * dy;
}
1358764
def merge_and_fit(self, segment):
        
        self.points = sort_segment_points(self.points, segment.points)
        return self
1077025
function() {
        var length = 0.0;
        if ( this.components && (this.components.length > 1)) {
            for(var i=1, len=this.components.length; i<len; i++) {
                length += this.components[i-1].distanceTo(this.components[i]);
            }
        }
        return length;
    }
1315908
function(unit, distance, round) {

			if(distance == 0 || typeof distance == 'undefined') {

				if(geolib.distance == 0) {
					// throw 'No distance given.';
					return 0;
				} else {
					distance = geolib.distance;
				}

			}

			unit = unit || 'm';
			round = (null == round ? 4 : round);

			switch(unit) {

				case 'm':    // Meter
					return geolib.round(distance, round);
					break;
				case 'km':    // Kilometer
					return geolib.round(distance / 1000, round);
					break;
				case 'cm':    // Centimeter
					return geolib.round(distance * 100, round);
					break;
				case 'mm':    // Millimeter
					return geolib.round(distance * 1000, round);
					break;
				case 'mi':    // Miles
					return geolib.round(distance * (1 / 1609.344), round);
					break;
				case 'sm':    // Seamiles
					return geolib.round(distance * (1 / 1852.216), round);
					break;
				case 'ft':    // Feet
					return geolib.round(distance * (100 / 30.48), round);
					break;
				case 'in':    // Inch
					return geolib.round(distance * 100 / 2.54, round);
					break;
				case 'yd':    // Yards
					return geolib.round(distance * (1 / 0.9144), round);
					break;
			}

			return distance;

		}
388994
def fast_distance(r1: 'Region', r2: 'Region'):
        
        return abs(r1.x - r2.x) + abs(r1.y - r2.y)
1099467
private int calculateSegmentSize(int factor, int segmentSizeOld)
  {
    DatabaseKelp db = _table.database();
    
    long segmentFactor = _tableLength / db.getSegmentSizeMin();
  
    long segmentFactorNew = segmentFactor / factor;
    
    // segment size is (tableSize / factor), restricted to a power of 4
    // over the min segment size.
  
    if (segmentFactorNew > 0) {
      int bit = 63 - Long.numberOfLeadingZeros(segmentFactorNew);
    
      bit &= ~0x1;
    
      long segmentFactorPower = (1 << bit);
      
      if (segmentFactorPower < segmentFactorNew) {
        segmentFactorNew = 4 * segmentFactorPower;
      }
    }
    
    long segmentSizeNew = segmentFactorNew * db.getSegmentSizeMin();
    segmentSizeNew = Math.max(db.getSegmentSizeMin(), segmentSizeNew);
    
    long segmentSizeBlob = _blobSizeMax * 4;
    
    while (segmentSizeNew < segmentSizeBlob) {
      segmentSizeNew *= 4;
    }
    
    segmentSizeNew = Math.min(db.getSegmentSizeMax(), segmentSizeNew);
  
    return (int) Math.max(segmentSizeNew, segmentSizeOld);
  }
830379
def SegmentProd(a, ids):
    
    func = lambda idxs: reduce(np.multiply, a[idxs])
    return seg_map(func, a, ids),
1186029
def _get_segments(self):
        
        points = list(self.points)
        segments = [[]]
        lastWasOffCurve = False
        firstIsMove = points[0].type == "move"
        for point in points:
            segments[-1].append(point)
            if point.type != "offcurve":
                segments.append([])
            lastWasOffCurve = point.type == "offcurve"
        if len(segments[-1]) == 0:
            del segments[-1]
        if lastWasOffCurve and firstIsMove:
            # ignore trailing off curves
            del segments[-1]
        if lastWasOffCurve and not firstIsMove:
            segment = segments.pop(-1)
            segment.extend(segments[0])
            del segments[0]
            segments.append(segment)
        if not lastWasOffCurve and not firstIsMove:
            segment = segments.pop(0)
            segments.append(segment)
        # wrap into segments
        wrapped = []
        for points in segments:
            s = self.segmentClass()
            s._setPoints(points)
            self._setContourInSegment(s)
            wrapped.append(s)
        return wrapped
87384
def segment_similarity(A, B, T=CLOSE_DISTANCE_THRESHOLD):
    
    l_a = len(A.points)
    l_b = len(B.points)

    idx = index.Index()
    dex = 0
    for i in range(l_a-1):
        idx.insert(dex, bounding_box_from(A.points, i, i+1, T), obj=[A.points[i], A.points[i+1]])
        dex = dex + 1

    prox_acc = []

    for i in range(l_b-1):
        ti = B.points[i].gen2arr()
        ti1 = B.points[i+1].gen2arr()
        bb = bounding_box_from(B.points, i, i+1, T)
        intersects = idx.intersection(bb, objects=True)
        n_prox = []
        i_prox = 0
        a = 0
        for x in intersects:
            a = a + 1
            pi = x.object[0].gen2arr()
            pi1 = x.object[1].gen2arr()
            prox = line_similarity(ti, ti1, pi, pi1, T)
            i_prox = i_prox + prox
            n_prox.append(prox)

        if a != 0:
            prox_acc.append(i_prox / a)
            # prox_acc.append(max(n_prox))
        else:
            prox_acc.append(0)

    return np.mean(prox_acc), prox_acc
577612
function ( u, distance ) {

		var arcLengths = this.getLengths();

		var i = 0, il = arcLengths.length;

		var targetArcLength; // The targeted u distance value to get

		if ( distance ) {

			targetArcLength = distance;

		} else {

			targetArcLength = u * arcLengths[ il - 1 ];

		}

		//var time = Date.now();

		// binary search for the index with largest value smaller than target u distance

		var low = 0, high = il - 1, comparison;

		while ( low <= high ) {

			i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats

			comparison = arcLengths[ i ] - targetArcLength;

			if ( comparison < 0 ) {

				low = i + 1;

			} else if ( comparison > 0 ) {

				high = i - 1;

			} else {

				high = i;
				break;

				// DONE

			}

		}

		i = high;

		//console.log('b' , i, low, high, Date.now()- time);

		if ( arcLengths[ i ] === targetArcLength ) {

			var t = i / ( il - 1 );
			return t;

		}

		// we could get finer grain at lengths, or use simple interpolation between two points

		var lengthBefore = arcLengths[ i ];
		var lengthAfter = arcLengths[ i + 1 ];

		var segmentLength = lengthAfter - lengthBefore;

		// determine where we are between the 'before' and 'after' points

		var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;

		// add that fractional amount to t

		var t = ( i + segmentFraction ) / ( il - 1 );

		return t;

	}
107834
def find_segment(self, ea):
        
        for seg in self.seglist:
            if seg.startea <= ea < seg.endea:
                return seg
952471
def _horizontal_segment(old_offs, new_offs, spacing, diameter):
    '''
    '''
    return np.array(((old_offs[0], old_offs[1] + spacing[1]),
                     (new_offs[0], old_offs[1] + spacing[1]),
                     (new_offs[0], old_offs[1] + spacing[1] - diameter),
                     (old_offs[0], old_offs[1] + spacing[1] - diameter)))
32104
def build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0):
    
    seg_result = segmentlist([])
    sum_result = segmentlist([])

    # Is there any way to get segment and segement summary in one query?
    # Maybe some sort of outer join where we keep track of which segment
    # summaries we've already seen.
    sql = "SELECT segment_summary.start_time, segment_summary.end_time "
    sql += "FROM segment_definer, segment_summary "
    sql += "WHERE segment_summary.segment_def_id = segment_definer.segment_def_id "
    sql += "AND   segment_definer.ifos = '%s' " % ifo
    if engine.__class__ == query_engine.LdbdQueryEngine:
       sql += "AND segment_summary.segment_def_cdb = segment_definer.creator_db "
    sql += "AND   segment_definer.name = '%s' " % segment_name
    sql += "AND   segment_definer.version = %s " % version
    sql += "AND NOT (%s > segment_summary.end_time OR segment_summary.start_time > %s)" % (gps_start_time, gps_end_time)

    rows = engine.query(sql)

    for sum_start_time, sum_end_time in rows:
        sum_start_time = (sum_start_time < gps_start_time) and gps_start_time or sum_start_time
        sum_end_time = (sum_end_time > gps_end_time) and gps_end_time or sum_end_time

        sum_result |= segmentlist([segment(sum_start_time, sum_end_time)])

    # We can't use queries paramaterized with ? since the ldbd protocol doesn't support it...
    sql = "SELECT segment.start_time + %d, segment.end_time + %d " % (start_pad, end_pad)
    sql += "FROM segment, segment_definer "
    sql += "WHERE segment.segment_def_id = segment_definer.segment_def_id "

    if engine.__class__ == query_engine.LdbdQueryEngine:
       sql += "AND segment.segment_def_cdb = segment_definer.creator_db "
    sql += "AND   segment_definer.ifos = '%s' " % ifo
    sql += "AND   segment_definer.name = '%s' " % segment_name
    sql += "AND   segment_definer.version = %s " % version
    sql += "AND NOT (%s > segment.end_time OR segment.start_time > %s)" % (gps_start_time, gps_end_time)

    rows = engine.query(sql)
    
    for seg_start_time, seg_end_time in rows:
        seg_start_time = (seg_start_time < gps_start_time) and gps_start_time or seg_start_time
        seg_end_time = (seg_end_time > gps_end_time) and gps_end_time or seg_end_time

        seg_result |= segmentlist([segment(seg_start_time, seg_end_time)])

    engine.close()

    return sum_result, seg_result
803570
def segment_lengths(neurites, neurite_type=NeuriteType.all):
    ''''''
    def _seg_len(sec):
        '''list of segment lengths of a section'''
        return np.linalg.norm(np.diff(sec.points[:, COLS.XYZ], axis=0), axis=1)

    return map_segments(_seg_len, neurites, neurite_type)
276828
function(segment, segmentType) {
        var points = this.getElementsByTagNameNS(segment, segment.namespaceURI, segmentType);
        var point_features = [];
        for (var i = 0, len = points.length; i < len; i++) {
            point_features.push(new OpenLayers.Geometry.Point(points[i].getAttribute("lon"), points[i].getAttribute("lat")));
        }
        return new OpenLayers.Geometry.LineString(point_features);
    }
243998
def keep_segments(self, segments_to_keep, preserve_segmentation=True):
        '''
        
        '''
        v_ind, f_ind = self.vertex_indices_in_segments(segments_to_keep, ret_face_indices=True)
        self.segm = {name: self.segm[name] for name in segments_to_keep}

        if not preserve_segmentation:
            self.segm = None
            self.f = self.f[f_ind]
            if self.ft is not None:
                self.ft = self.ft[f_ind]

        self.keep_vertices(v_ind)
151766
def q(segmentation, s1, s2):
    
    index1 = find_index(segmentation, s1)
    index2 = find_index(segmentation, s2)
    return index1 == index2