/* The older, non-quantised, smooth gradient.
326565
function drawGradient(legend, barGroup, y) {
  var id = "terriajs-legend-gradient" + ++gradientCount;
  var defs = addSvgElement(legend, "defs", {}); // apparently it's ok to have the defs anywhere in the doc
  var linearGradient = svgElement(legend, "linearGradient", {
    x1: "0",
    x2: "0",
    y1: "1",
    y2: "0",
    id: id
  });
  legend.gradientColorMap.forEach(function(c, i) {
    linearGradient.appendChild(
      svgElement(legend, "stop", {
        offset: c.offset,
        "stop-color": c.color
      })
    );
  });
  defs.appendChild(linearGradient);

  var gradientItems = legend.items.filter(function(item) {
    return !defined(item.color);
  });

  var totalSpacingAbove = gradientItems.reduce(function(prev, item) {
    return prev + (item.spacingAbove || 0);
  }, 0);
  var barHeight = Math.max(
    (legend.computedItemHeight + legend.itemSpacing) * gradientItems.length +
      totalSpacingAbove,
    legend.barHeightMin
  );

  addSvgElement(
    legend,
    "rect",
    {
      x: legend.barLeft,
      y: y,
      width: legend.itemWidth,
      height: barHeight,
      fill: "url(#" + id + ")"
    },
    "gradient-bar"
  );

  return barHeight;
}
954687
function normalize(property, value, prefix){
  var result = value.toString(),
      args;

  /* Fixing the gradients */
  if (~result.indexOf('gradient(')) {

    /* Normalize color stops */
    result = result.replace(RE_GRADIENT_STOPS,'$1$4$3$2');

    /* Normalize legacy gradients */
    result = result.replace(RE_GRADIENT_VAL, function(){
        args = [].slice.call(arguments, 1);
        return normalizeGradient(args, prefix);
    });

    /* Adding prefixes to the legacy gradients */
    if (prefix) result = result.replace(RE_GRADIENT_TYPE, '-' + prefix + '-$1');
  }

  /* Adding prefixes to the `transform` values of legacy `transition` property */
  if (prefix && (property == "'transition'" || property == "'transition-property'")) {
    result = result.replace(RE_TRANSFORM, '-' + prefix + '-$1');
  }

  /* Removing `fill` keyword from the legacy `border-image` property */
  if (prefix && (property == "'border-image'" || property == "'border-image-slice'")) {
    result = result.replace(RE_FILL_KEYWORD, ' ');
  }

  return result;
}
1232612
def adjust_distributions_using_gradient
      return if @recent_scores.length < 3
      vx = (1..@recent_scores.length).to_a.to_numeric
      vy = @recent_scores.reverse.to_numeric
      r = Statsample::Regression::Simple.new_from_vectors(vx,vy)
      slope = r.b
      if slope > 0
        @distributions.each_pair { |k, d| d.tighten slope }
      elsif slope < 0
        @distributions.each_pair { |k, d| d.loosen slope }
      end
    end
1170549
def gradient(self):
        
        functional = self

        class KLCrossEntropyGradient(Operator):

            """The gradient operator of this functional."""

            def __init__(self):
                """Initialize a new instance."""
                super(KLCrossEntropyGradient, self).__init__(
                    functional.domain, functional.domain, linear=False)

            def _call(self, x):
                """Apply the gradient operator to the given point.

                The gradient is not defined in for points with components less
                than or equal to zero.
                """
                if functional.prior is None:
                    tmp = np.log(x)
                else:
                    tmp = np.log(x / functional.prior)

                if np.all(np.isfinite(tmp)):
                    return tmp
                else:
                    # The derivative is not defined.
                    raise ValueError('The gradient of the Kullback-Leibler '
                                     'Cross Entropy functional is not defined '
                                     'for `x` with one or more components '
                                     'less than or equal to zero.'.format(x))

        return KLCrossEntropyGradient()
313326
function regularizeL2(weights, gradientCount, stepSize, regParam) {
  const [gradient, count] = gradientCount;

  for (let i = 0; i < gradient.length; i++) {
    let grad = (gradient[i] || 0) / count;
    weights[i] = weights[i] || 0;
    weights[i] -= stepSize * (grad + regParam * weights[i]);
  }
}
814907
function Gradient(parsedNode) {
    this.node = {};
    this.preludeNodes = [];
    this.stops = [];
    this.afterNodes = [];
    this.setNode(parsedNode);

    this._actionQueue = [];
    this._walking = false;
}
1187851
private void declareDerivativeImages(ImageGradient<T, D> gradient, ImageHessian<D> hessian, Class<D> derivType) {
		if( gradient != null || hessian != null ) {
			derivX = GeneralizedImageOps.createSingleBand(derivType, 1, 1);
			derivY = GeneralizedImageOps.createSingleBand(derivType,1,1);
		}
		if( hessian != null ) {
			derivXX = GeneralizedImageOps.createSingleBand(derivType,1,1);
			derivYY = GeneralizedImageOps.createSingleBand(derivType,1,1);
			derivXY = GeneralizedImageOps.createSingleBand(derivType,1,1);
		}
	}
675501
private void computeGradientAndHessian(DMatrixRMaj param  )
    {
        // residuals = f(x) - y
        function.compute(param, residuals);

        computeNumericalJacobian(param,jacobian);

        CommonOps_DDRM.multTransA(jacobian, residuals, g);
        CommonOps_DDRM.multTransA(jacobian, jacobian,  H);

        CommonOps_DDRM.extractDiag(H,Hdiag);
    }
232860
function regularizeNone(weights, gradientCount) {
  const [gradient, count] = gradientCount;

  for (let i = 0; i < gradient.length; i++) {
    let grad = (gradient[i] || 0) / count;
    weights[i] = (weights[i] || 0) - grad;
  }
}
210943
public static <T extends ImageGray<T>>
	void naiveGradient(T ii, double tl_x, double tl_y, double samplePeriod ,
					   int regionSize, double kernelSize,
					   boolean useHaar, double[] derivX, double derivY[])
	{
		SparseScaleGradient<T,?> gg =  SurfDescribeOps.createGradient(useHaar,(Class<T>)ii.getClass());
		gg.setWidth(kernelSize);
		gg.setImage(ii);
		SparseGradientSafe g = new SparseGradientSafe(gg);

		// add 0.5 to c_x and c_y to have it round when converted to an integer pixel
		// this is faster than the straight forward method
		tl_x += 0.5;
		tl_y += 0.5;

		int i = 0;
		for( int y = 0; y < regionSize; y++ ) {
			for( int x = 0; x < regionSize; x++ , i++) {
				int xx = (int)(tl_x + x * samplePeriod);
				int yy = (int)(tl_y + y * samplePeriod);

				GradientValue deriv = g.compute(xx,yy);
				derivX[i] = deriv.getX();
				derivY[i] = deriv.getY();
//				System.out.printf("%2d %2d %2d %2d dx = %6.2f  dy = %6.2f\n",x,y,xx,yy,derivX[i],derivY[i]);
			}
		}
	}
686531
def update_gradients_full(self, dL_dK, X, X2=None):
        """"""
        if X2 is None: X2 = X
        FX  = self._cos(self.basis_alpha[None,:],self.basis_omega[None,:],self.basis_phi[None,:])(X)
        FX2 = self._cos(self.basis_alpha[None,:],self.basis_omega[None,:],self.basis_phi[None,:])(X2)

        La = np.column_stack((self.a[0]*np.ones((self.n_basis,1)),self.a[1]*self.basis_omega))
        Lo = np.column_stack((self.basis_omega,self.basis_omega))
        Lp = np.column_stack((self.basis_phi,self.basis_phi+np.pi/2))
        r,omega,phi =  self._cos_factorization(La,Lo,Lp)
        Gint = self._int_computation( r,omega,phi, r,omega,phi)

        Flower = np.array(self._cos(self.basis_alpha,self.basis_omega,self.basis_phi)(self.lower))[:,None]

        #dK_dvar
        dK_dvar = 1./self.variance*mdot(FX,self.Gi,FX2.T)

        #dK_dlen
        da_dlen = [-1./self.lengthscale**2,0.]
        dLa_dlen =  np.column_stack((da_dlen[0]*np.ones((self.n_basis,1)),da_dlen[1]*self.basis_omega))
        r1,omega1,phi1 = self._cos_factorization(dLa_dlen,Lo,Lp)
        dGint_dlen = self._int_computation(r1,omega1,phi1, r,omega,phi)
        dGint_dlen = dGint_dlen + dGint_dlen.T
        dG_dlen = 1./2*Gint + self.lengthscale/2*dGint_dlen
        dK_dlen = -mdot(FX,self.Gi,dG_dlen/self.variance,self.Gi,FX2.T)

        #dK_dper
        dFX_dper  = self._cos(-self.basis_alpha[None,:]*self.basis_omega[None,:]/self.period*X ,self.basis_omega[None,:],self.basis_phi[None,:]+np.pi/2)(X)
        dFX2_dper = self._cos(-self.basis_alpha[None,:]*self.basis_omega[None,:]/self.period*X2,self.basis_omega[None,:],self.basis_phi[None,:]+np.pi/2)(X2)

        dLa_dper = np.column_stack((-self.a[0]*self.basis_omega/self.period, -self.a[1]*self.basis_omega**2/self.period))
        dLp_dper = np.column_stack((self.basis_phi+np.pi/2,self.basis_phi+np.pi))
        r1,omega1,phi1 =  self._cos_factorization(dLa_dper,Lo,dLp_dper)

        IPPprim1 =  self.upper*(1./(omega+omega1.T)*np.cos((omega+omega1.T)*self.upper+phi+phi1.T-np.pi/2)  +  1./(omega-omega1.T)*np.cos((omega-omega1.T)*self.upper+phi-phi1.T-np.pi/2))
        IPPprim1 -= self.lower*(1./(omega+omega1.T)*np.cos((omega+omega1.T)*self.lower+phi+phi1.T-np.pi/2)  +  1./(omega-omega1.T)*np.cos((omega-omega1.T)*self.lower+phi-phi1.T-np.pi/2))
        # SIMPLIFY!!!       IPPprim1 = (self.upper - self.lower)*np.cos((omega+omega1.T)*self.upper+phi+phi1.T-np.pi/2)  +  1./(omega-omega1.T)*np.cos((omega-omega1.T)*self.upper+phi-phi1.T-np.pi/2))
        IPPprim2 =  self.upper*(1./(omega+omega1.T)*np.cos((omega+omega1.T)*self.upper+phi+phi1.T-np.pi/2)  + self.upper*np.cos(phi-phi1.T))
        IPPprim2 -= self.lower*(1./(omega+omega1.T)*np.cos((omega+omega1.T)*self.lower+phi+phi1.T-np.pi/2)  + self.lower*np.cos(phi-phi1.T))
        IPPprim = np.where(np.logical_or(np.isnan(IPPprim1), np.isinf(IPPprim1)), IPPprim2, IPPprim1)


        IPPint1 =  1./(omega+omega1.T)**2*np.cos((omega+omega1.T)*self.upper+phi+phi1.T-np.pi)  +  1./(omega-omega1.T)**2*np.cos((omega-omega1.T)*self.upper+phi-phi1.T-np.pi)
        IPPint1 -= 1./(omega+omega1.T)**2*np.cos((omega+omega1.T)*self.lower+phi+phi1.T-np.pi)  +  1./(omega-omega1.T)**2*np.cos((omega-omega1.T)*self.lower+phi-phi1.T-np.pi)
        IPPint2 =  1./(omega+omega1.T)**2*np.cos((omega+omega1.T)*self.upper+phi+phi1.T-np.pi)  + 1./2*self.upper**2*np.cos(phi-phi1.T)
        IPPint2 -= 1./(omega+omega1.T)**2*np.cos((omega+omega1.T)*self.lower+phi+phi1.T-np.pi)  + 1./2*self.lower**2*np.cos(phi-phi1.T)
        #IPPint2[0,0] = (self.upper**2 - self.lower**2)*np.cos(phi[0,0])*np.cos(phi1[0,0])
        IPPint = np.where(np.isnan(IPPint1),IPPint2,IPPint1)

        dLa_dper2 = np.column_stack((-self.a[1]*self.basis_omega/self.period))
        dLp_dper2 = np.column_stack((self.basis_phi+np.pi/2))
        r2,omega2,phi2 = dLa_dper2.T,Lo[:,0:1],dLp_dper2.T

        dGint_dper = np.dot(r,r1.T)/2 * (IPPprim - IPPint) + self._int_computation(r2,omega2,phi2, r,omega,phi)
        dGint_dper = dGint_dper + dGint_dper.T

        dFlower_dper  = np.array(self._cos(-self.lower*self.basis_alpha*self.basis_omega/self.period,self.basis_omega,self.basis_phi+np.pi/2)(self.lower))[:,None]

        dG_dper = 1./self.variance*(self.lengthscale/2*dGint_dper + self.b[0]*(np.dot(dFlower_dper,Flower.T)+np.dot(Flower,dFlower_dper.T)))

        dK_dper = mdot(dFX_dper,self.Gi,FX2.T) - mdot(FX,self.Gi,dG_dper,self.Gi,FX2.T) + mdot(FX,self.Gi,dFX2_dper.T)

        self.variance.gradient = np.sum(dK_dvar*dL_dK)
        self.lengthscale.gradient = np.sum(dK_dlen*dL_dK)
        self.period.gradient = np.sum(dK_dper*dL_dK)
1372530
function gradientBox(angle, rect) {
  const [x, y, w, h] = rect;

  angle %= 360;
  if(angle < 0) {
    angle += 360;
  }

  let ret = [x, y, x + w, y + h];
  if(angle >= 0 && angle < 90) {
    const tan = Math.tan((Math.PI * angle) / 180);

    let d = tan * w;

    if(d <= h) {
      ret = [x, y, x + w, y + d];
    } else {
      d = h / tan;
      ret = [x, y, x + d, y + h];
    }
  } else if(angle >= 90 && angle < 180) {
    const tan = Math.tan((Math.PI * (angle - 90)) / 180);

    let d = tan * h;

    if(d <= w) {
      ret = [x + w, y, x + w - d, y + h];
    } else {
      d = w / tan;
      ret = [x + w, y, x, y + d];
    }
  } else if(angle >= 180 && angle < 270) {
    const tan = Math.tan((Math.PI * (angle - 180)) / 180);

    let d = tan * w;

    if(d <= h) {
      ret = [x + w, y + h, x, y + h - d];
    } else {
      d = h / tan;
      ret = [x + w, y + h, x + w - d, y];
    }
  } else if(angle >= 270 && angle < 360) {
    const tan = Math.tan((Math.PI * (angle - 270)) / 180);

    let d = tan * h;

    if(d <= w) {
      ret = [x, y + h, x + d, y];
    } else {
      d = w / tan;
      ret = [x, y + h, x + w, y + h - d];
    }
  }

  return ret;
}
1292473
def gradient_descent(alpha=0.01, num_iters=1500)
      m = @xs.length
      alpha_m = (alpha / m)

      (num_iters).times do

        @thetas = 
          @xs.map do |x_row|
            x_row.zip(@thetas).map do |x, theta|
             x * theta
            end.inject(:+)
          end.zip(@ys).map do |(predict_val, y)|  
            predict_val - y 
          end.zip(@xs).map do |(y, x_row)|
            x_row.map { |x| x * y }
          end.reduce([0.0] * 2) do |sum, val|
            sum.zip(val).map { |(a, b)| a + b}
          end.map do |value|
            alpha_m * value
          end.zip( @thetas ).map do |(a, b)|
            b - a
          end
      end

      @thetas
    end
170179
function(ctx, from, to, width, gradient) {

        var innerWidth = width - 4;
        var outerWidth = width;
        var buttFrom = g.point(from).move(to, -outerWidth / 2);
        var buttTo = g.point(to).move(from, -outerWidth / 2);

        ctx.beginPath();
        ctx.lineWidth = outerWidth;
        ctx.strokeStyle = 'rgba(0,0,0,0.6)';

        ctx.moveTo(from.x, from.y);
        ctx.lineTo(to.x, to.y);
        ctx.stroke();
        ctx.closePath();

        gradient.addColorStop(0.000, 'rgba(86, 170, 255, 1)');
        gradient.addColorStop(0.500, 'rgba(255, 255, 255, 1)');
        gradient.addColorStop(1.000, 'rgba(86, 170, 255, 1)');

        ctx.beginPath();
        ctx.lineWidth = innerWidth;
        ctx.strokeStyle = gradient;
        ctx.moveTo(from.x, from.y);

        ctx.lineTo(to.x, to.y);
        ctx.stroke();
        ctx.closePath();

        ctx.lineCap = "square";

        ctx.beginPath();
        ctx.lineWidth = innerWidth;
        ctx.strokeStyle = 'rgba(0,0,0,0.5)';
        ctx.moveTo(from.x, from.y);
        ctx.lineTo(buttFrom.x, buttFrom.y);
        ctx.stroke();
        ctx.closePath();

        ctx.beginPath();
        ctx.lineWidth = innerWidth;
        ctx.strokeStyle = 'rgba(0,0,0,0.5)';
        ctx.moveTo(to.x, to.y);
        ctx.lineTo(buttTo.x, buttTo.y);
        ctx.stroke();
        ctx.closePath();
    }
711534
def gradient(self, mu, dist):
        
        return dist.levels/(mu*(dist.levels - mu))
837947
def smooth_rectangle(x, y, rec_w, rec_h, gaussian_width_x, gaussian_width_y):
    

    gaussian_x_coord = abs(x)-rec_w/2.0
    gaussian_y_coord = abs(y)-rec_h/2.0

    box_x=np.less(gaussian_x_coord,0.0)
    box_y=np.less(gaussian_y_coord,0.0)
    sigmasq_x=gaussian_width_x*gaussian_width_x
    sigmasq_y=gaussian_width_y*gaussian_width_y

    with float_error_ignore():
        falloff_x=x*0.0 if sigmasq_x==0.0 else \
            np.exp(np.divide(-gaussian_x_coord*gaussian_x_coord,2*sigmasq_x))
        falloff_y=y*0.0 if sigmasq_y==0.0 else \
            np.exp(np.divide(-gaussian_y_coord*gaussian_y_coord,2*sigmasq_y))

    return np.minimum(np.maximum(box_x,falloff_x), np.maximum(box_y,falloff_y))
1041459
def gradient(self):
        """"""
        result = np.zeros((self.numc, 3), float)
        for index1 in range(self.numc):
            result[index1] = self.gradient_component(index1)
        return result