Best JavaScript code snippet using mountebank
geo.py
Source:geo.py
...57 Axes.set_xlim(self, -np.pi, np.pi)58 Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0)59 def _set_lim_and_transforms(self):60 # A (possibly non-linear) projection on the (already scaled) data61 self.transProjection = self._get_core_transform(self.RESOLUTION)62 self.transAffine = self._get_affine_transform()63 self.transAxes = BboxTransformTo(self.bbox)64 # The complete data transformation stack -- from data all the65 # way to display coordinates66 self.transData = \67 self.transProjection + \68 self.transAffine + \69 self.transAxes70 # This is the transform for longitude ticks.71 self._xaxis_pretransform = \72 Affine2D() \73 .scale(1.0, self._longitude_cap * 2.0) \74 .translate(0.0, -self._longitude_cap)75 self._xaxis_transform = \76 self._xaxis_pretransform + \77 self.transData78 self._xaxis_text1_transform = \79 Affine2D().scale(1.0, 0.0) + \80 self.transData + \81 Affine2D().translate(0.0, 4.0)82 self._xaxis_text2_transform = \83 Affine2D().scale(1.0, 0.0) + \84 self.transData + \85 Affine2D().translate(0.0, -4.0)86 # This is the transform for latitude ticks.87 yaxis_stretch = Affine2D().scale(np.pi * 2.0, 1.0).translate(-np.pi, 0.0)88 yaxis_space = Affine2D().scale(1.0, 1.1)89 self._yaxis_transform = \90 yaxis_stretch + \91 self.transData92 yaxis_text_base = \93 yaxis_stretch + \94 self.transProjection + \95 (yaxis_space + \96 self.transAffine + \97 self.transAxes)98 self._yaxis_text1_transform = \99 yaxis_text_base + \100 Affine2D().translate(-8.0, 0.0)101 self._yaxis_text2_transform = \102 yaxis_text_base + \103 Affine2D().translate(8.0, 0.0)104 def _get_affine_transform(self):105 transform = self._get_core_transform(1)106 xscale, _ = transform.transform_point((np.pi, 0))107 _, yscale = transform.transform_point((0, np.pi / 2.0))108 return Affine2D() \109 .scale(0.5 / xscale, 0.5 / yscale) \110 .translate(0.5, 0.5)111 def get_xaxis_transform(self,which='grid'):112 if which not in ['tick1','tick2','grid']:113 msg = "'which' must be on of [ 'tick1' | 'tick2' | 'grid' ]"114 raise ValueError(msg)115 return self._xaxis_transform116 def get_xaxis_text1_transform(self, pad):117 return self._xaxis_text1_transform, 'bottom', 'center'118 def get_xaxis_text2_transform(self, pad):119 return self._xaxis_text2_transform, 'top', 'center'120 def get_yaxis_transform(self,which='grid'):121 if which not in ['tick1','tick2','grid']:122 msg = "'which' must be one of [ 'tick1' | 'tick2' | 'grid' ]"123 raise ValueError(msg)124 return self._yaxis_transform125 def get_yaxis_text1_transform(self, pad):126 return self._yaxis_text1_transform, 'center', 'right'127 def get_yaxis_text2_transform(self, pad):128 return self._yaxis_text2_transform, 'center', 'left'129 def _gen_axes_patch(self):130 return Circle((0.5, 0.5), 0.5)131 def _gen_axes_spines(self):132 return {'geo':mspines.Spine.circular_spine(self,133 (0.5, 0.5), 0.5)}134 def set_yscale(self, *args, **kwargs):135 if args[0] != 'linear':136 raise NotImplementedError137 set_xscale = set_yscale138 def set_xlim(self, *args, **kwargs):139 raise TypeError("It is not possible to change axes limits "140 "for geographic projections. Please consider "141 "using Basemap or Cartopy.")142 set_ylim = set_xlim143 def format_coord(self, lon, lat):144 'return a format string formatting the coordinate'145 lon = lon * (180.0 / np.pi)146 lat = lat * (180.0 / np.pi)147 if lat >= 0.0:148 ns = 'N'149 else:150 ns = 'S'151 if lon >= 0.0:152 ew = 'E'153 else:154 ew = 'W'155 return '%f\u00b0%s, %f\u00b0%s' % (abs(lat), ns, abs(lon), ew)156 def set_longitude_grid(self, degrees):157 """158 Set the number of degrees between each longitude grid.159 """160 number = (360.0 / degrees) + 1161 self.xaxis.set_major_locator(162 FixedLocator(163 np.linspace(-np.pi, np.pi, number, True)[1:-1]))164 self._logitude_degrees = degrees165 self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))166 def set_latitude_grid(self, degrees):167 """168 Set the number of degrees between each longitude grid.169 """170 number = (180.0 / degrees) + 1171 self.yaxis.set_major_locator(172 FixedLocator(173 np.linspace(-np.pi / 2.0, np.pi / 2.0, number, True)[1:-1]))174 self._latitude_degrees = degrees175 self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))176 def set_longitude_grid_ends(self, degrees):177 """178 Set the latitude(s) at which to stop drawing the longitude grids.179 """180 self._longitude_cap = degrees * (np.pi / 180.0)181 self._xaxis_pretransform \182 .clear() \183 .scale(1.0, self._longitude_cap * 2.0) \184 .translate(0.0, -self._longitude_cap)185 def get_data_ratio(self):186 '''187 Return the aspect ratio of the data itself.188 '''189 return 1.0190 ### Interactive panning191 def can_zoom(self):192 """193 Return *True* if this axes supports the zoom box button functionality.194 This axes object does not support interactive zoom box.195 """196 return False197 def can_pan(self) :198 """199 Return *True* if this axes supports the pan/zoom button functionality.200 This axes object does not support interactive pan/zoom.201 """202 return False203 def start_pan(self, x, y, button):204 pass205 def end_pan(self):206 pass207 def drag_pan(self, button, key, x, y):208 pass209class AitoffAxes(GeoAxes):210 name = 'aitoff'211 class AitoffTransform(Transform):212 """213 The base Aitoff transform.214 """215 input_dims = 2216 output_dims = 2217 is_separable = False218 def __init__(self, resolution):219 """220 Create a new Aitoff transform. Resolution is the number of steps221 to interpolate between each input line segment to approximate its222 path in curved Aitoff space.223 """224 Transform.__init__(self)225 self._resolution = resolution226 def transform_non_affine(self, ll):227 longitude = ll[:, 0:1]228 latitude = ll[:, 1:2]229 # Pre-compute some values230 half_long = longitude / 2.0231 cos_latitude = np.cos(latitude)232 alpha = np.arccos(cos_latitude * np.cos(half_long))233 # Mask this array or we'll get divide-by-zero errors234 alpha = ma.masked_where(alpha == 0.0, alpha)235 # The numerators also need to be masked so that masked236 # division will be invoked.237 # We want unnormalized sinc. numpy.sinc gives us normalized238 sinc_alpha = ma.sin(alpha) / alpha239 x = (cos_latitude * ma.sin(half_long)) / sinc_alpha240 y = (ma.sin(latitude) / sinc_alpha)241 return np.concatenate((x.filled(0), y.filled(0)), 1)242 transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__243 def transform_path_non_affine(self, path):244 vertices = path.vertices245 ipath = path.interpolated(self._resolution)246 return Path(self.transform(ipath.vertices), ipath.codes)247 transform_path_non_affine.__doc__ = Transform.transform_path_non_affine.__doc__248 def inverted(self):249 return AitoffAxes.InvertedAitoffTransform(self._resolution)250 inverted.__doc__ = Transform.inverted.__doc__251 class InvertedAitoffTransform(Transform):252 input_dims = 2253 output_dims = 2254 is_separable = False255 def __init__(self, resolution):256 Transform.__init__(self)257 self._resolution = resolution258 def transform_non_affine(self, xy):259 # MGDTODO: Math is hard ;(260 return xy261 transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__262 def inverted(self):263 return AitoffAxes.AitoffTransform(self._resolution)264 inverted.__doc__ = Transform.inverted.__doc__265 def __init__(self, *args, **kwargs):266 self._longitude_cap = np.pi / 2.0267 GeoAxes.__init__(self, *args, **kwargs)268 self.set_aspect(0.5, adjustable='box', anchor='C')269 self.cla()270 def _get_core_transform(self, resolution):271 return self.AitoffTransform(resolution)272class HammerAxes(GeoAxes):273 name = 'hammer'274 class HammerTransform(Transform):275 """276 The base Hammer transform.277 """278 input_dims = 2279 output_dims = 2280 is_separable = False281 def __init__(self, resolution):282 """283 Create a new Hammer transform. Resolution is the number of steps284 to interpolate between each input line segment to approximate its285 path in curved Hammer space.286 """287 Transform.__init__(self)288 self._resolution = resolution289 def transform_non_affine(self, ll):290 longitude = ll[:, 0:1]291 latitude = ll[:, 1:2]292 # Pre-compute some values293 half_long = longitude / 2.0294 cos_latitude = np.cos(latitude)295 sqrt2 = np.sqrt(2.0)296 alpha = np.sqrt(1.0 + cos_latitude * np.cos(half_long))297 x = (2.0 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha298 y = (sqrt2 * np.sin(latitude)) / alpha299 return np.concatenate((x, y), 1)300 transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__301 def transform_path_non_affine(self, path):302 vertices = path.vertices303 ipath = path.interpolated(self._resolution)304 return Path(self.transform(ipath.vertices), ipath.codes)305 transform_path_non_affine.__doc__ = Transform.transform_path_non_affine.__doc__306 def inverted(self):307 return HammerAxes.InvertedHammerTransform(self._resolution)308 inverted.__doc__ = Transform.inverted.__doc__309 class InvertedHammerTransform(Transform):310 input_dims = 2311 output_dims = 2312 is_separable = False313 def __init__(self, resolution):314 Transform.__init__(self)315 self._resolution = resolution316 def transform_non_affine(self, xy):317 x = xy[:, 0:1]318 y = xy[:, 1:2]319 quarter_x = 0.25 * x320 half_y = 0.5 * y321 z = np.sqrt(1.0 - quarter_x*quarter_x - half_y*half_y)322 longitude = 2 * np.arctan((z*x) / (2.0 * (2.0*z*z - 1.0)))323 latitude = np.arcsin(y*z)324 return np.concatenate((longitude, latitude), 1)325 transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__326 def inverted(self):327 return HammerAxes.HammerTransform(self._resolution)328 inverted.__doc__ = Transform.inverted.__doc__329 def __init__(self, *args, **kwargs):330 self._longitude_cap = np.pi / 2.0331 GeoAxes.__init__(self, *args, **kwargs)332 self.set_aspect(0.5, adjustable='box', anchor='C')333 self.cla()334 def _get_core_transform(self, resolution):335 return self.HammerTransform(resolution)336class MollweideAxes(GeoAxes):337 name = 'mollweide'338 class MollweideTransform(Transform):339 """340 The base Mollweide transform.341 """342 input_dims = 2343 output_dims = 2344 is_separable = False345 def __init__(self, resolution):346 """347 Create a new Mollweide transform. Resolution is the number of steps348 to interpolate between each input line segment to approximate its349 path in curved Mollweide space.350 """351 Transform.__init__(self)352 self._resolution = resolution353 def transform_non_affine(self, ll):354 def d(theta):355 delta = -(theta + np.sin(theta) - pi_sin_l) / (1 + np.cos(theta))356 return delta, np.abs(delta) > 0.001357 longitude = ll[:, 0]358 latitude = ll[:, 1]359 clat = np.pi/2 - np.abs(latitude)360 ihigh = clat < 0.087 # within 5 degrees of the poles361 ilow = ~ihigh362 aux = np.empty(latitude.shape, dtype=np.float)363 if ilow.any(): # Newton-Raphson iteration364 pi_sin_l = np.pi * np.sin(latitude[ilow])365 theta = 2.0 * latitude[ilow]366 delta, large_delta = d(theta)367 while np.any(large_delta):368 theta[large_delta] += delta[large_delta]369 delta, large_delta = d(theta)370 aux[ilow] = theta / 2371 if ihigh.any(): # Taylor series-based approx. solution372 e = clat[ihigh]373 d = 0.5 * (3 * np.pi * e**2) ** (1.0/3)374 aux[ihigh] = (np.pi/2 - d) * np.sign(latitude[ihigh])375 xy = np.empty(ll.shape, dtype=np.float)376 xy[:,0] = (2.0 * np.sqrt(2.0) / np.pi) * longitude * np.cos(aux)377 xy[:,1] = np.sqrt(2.0) * np.sin(aux)378 return xy379 transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__380 def transform_path_non_affine(self, path):381 vertices = path.vertices382 ipath = path.interpolated(self._resolution)383 return Path(self.transform(ipath.vertices), ipath.codes)384 transform_path_non_affine.__doc__ = Transform.transform_path_non_affine.__doc__385 def inverted(self):386 return MollweideAxes.InvertedMollweideTransform(self._resolution)387 inverted.__doc__ = Transform.inverted.__doc__388 class InvertedMollweideTransform(Transform):389 input_dims = 2390 output_dims = 2391 is_separable = False392 def __init__(self, resolution):393 Transform.__init__(self)394 self._resolution = resolution395 def transform_non_affine(self, xy):396 x = xy[:, 0:1]397 y = xy[:, 1:2]398 # from Equations (7, 8) of399 # http://mathworld.wolfram.com/MollweideProjection.html400 theta = np.arcsin(y / np.sqrt(2))401 lon = (np.pi / (2 * np.sqrt(2))) * x / np.cos(theta)402 lat = np.arcsin((2 * theta + np.sin(2 * theta)) / np.pi)403 return np.concatenate((lon, lat), 1)404 transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__405 def inverted(self):406 return MollweideAxes.MollweideTransform(self._resolution)407 inverted.__doc__ = Transform.inverted.__doc__408 def __init__(self, *args, **kwargs):409 self._longitude_cap = np.pi / 2.0410 GeoAxes.__init__(self, *args, **kwargs)411 self.set_aspect(0.5, adjustable='box', anchor='C')412 self.cla()413 def _get_core_transform(self, resolution):414 return self.MollweideTransform(resolution)415class LambertAxes(GeoAxes):416 name = 'lambert'417 class LambertTransform(Transform):418 """419 The base Lambert transform.420 """421 input_dims = 2422 output_dims = 2423 is_separable = False424 def __init__(self, center_longitude, center_latitude, resolution):425 """426 Create a new Lambert transform. Resolution is the number of steps427 to interpolate between each input line segment to approximate its428 path in curved Lambert space.429 """430 Transform.__init__(self)431 self._resolution = resolution432 self._center_longitude = center_longitude433 self._center_latitude = center_latitude434 def transform_non_affine(self, ll):435 longitude = ll[:, 0:1]436 latitude = ll[:, 1:2]437 clong = self._center_longitude438 clat = self._center_latitude439 cos_lat = np.cos(latitude)440 sin_lat = np.sin(latitude)441 diff_long = longitude - clong442 cos_diff_long = np.cos(diff_long)443 inner_k = (1.0 +444 np.sin(clat)*sin_lat +445 np.cos(clat)*cos_lat*cos_diff_long)446 # Prevent divide-by-zero problems447 inner_k = np.where(inner_k == 0.0, 1e-15, inner_k)448 k = np.sqrt(2.0 / inner_k)449 x = k*cos_lat*np.sin(diff_long)450 y = k*(np.cos(clat)*sin_lat -451 np.sin(clat)*cos_lat*cos_diff_long)452 return np.concatenate((x, y), 1)453 transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__454 def transform_path_non_affine(self, path):455 vertices = path.vertices456 ipath = path.interpolated(self._resolution)457 return Path(self.transform(ipath.vertices), ipath.codes)458 transform_path_non_affine.__doc__ = Transform.transform_path_non_affine.__doc__459 def inverted(self):460 return LambertAxes.InvertedLambertTransform(461 self._center_longitude,462 self._center_latitude,463 self._resolution)464 inverted.__doc__ = Transform.inverted.__doc__465 class InvertedLambertTransform(Transform):466 input_dims = 2467 output_dims = 2468 is_separable = False469 def __init__(self, center_longitude, center_latitude, resolution):470 Transform.__init__(self)471 self._resolution = resolution472 self._center_longitude = center_longitude473 self._center_latitude = center_latitude474 def transform_non_affine(self, xy):475 x = xy[:, 0:1]476 y = xy[:, 1:2]477 clong = self._center_longitude478 clat = self._center_latitude479 p = np.sqrt(x*x + y*y)480 p = np.where(p == 0.0, 1e-9, p)481 c = 2.0 * np.arcsin(0.5 * p)482 sin_c = np.sin(c)483 cos_c = np.cos(c)484 lat = np.arcsin(cos_c*np.sin(clat) +485 ((y*sin_c*np.cos(clat)) / p))486 lon = clong + np.arctan(487 (x*sin_c) / (p*np.cos(clat)*cos_c - y*np.sin(clat)*sin_c))488 return np.concatenate((lon, lat), 1)489 transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__490 def inverted(self):491 return LambertAxes.LambertTransform(492 self._center_longitude,493 self._center_latitude,494 self._resolution)495 inverted.__doc__ = Transform.inverted.__doc__496 def __init__(self, *args, **kwargs):497 self._longitude_cap = np.pi / 2.0498 self._center_longitude = kwargs.pop("center_longitude", 0.0)499 self._center_latitude = kwargs.pop("center_latitude", 0.0)500 GeoAxes.__init__(self, *args, **kwargs)501 self.set_aspect('equal', adjustable='box', anchor='C')502 self.cla()503 def cla(self):504 GeoAxes.cla(self)505 self.yaxis.set_major_formatter(NullFormatter())506 def _get_core_transform(self, resolution):507 return self.LambertTransform(508 self._center_longitude,509 self._center_latitude,510 resolution)511 def _get_affine_transform(self):512 return Affine2D() \513 .scale(0.25) \...
affinetransform.js
Source:affinetransform.js
1// Copyright 2008 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview Provides an object representation of an AffineTransform and16 * methods for working with it.17 */18goog.provide('goog.graphics.AffineTransform');19goog.require('goog.math');20/**21 * Creates a 2D affine transform. An affine transform performs a linear22 * mapping from 2D coordinates to other 2D coordinates that preserves the23 * "straightness" and "parallelness" of lines.24 *25 * Such a coordinate transformation can be represented by a 3 row by 3 column26 * matrix with an implied last row of [ 0 0 1 ]. This matrix transforms source27 * coordinates (x,y) into destination coordinates (x',y') by considering them28 * to be a column vector and multiplying the coordinate vector by the matrix29 * according to the following process:30 * <pre>31 * [ x'] [ m00 m01 m02 ] [ x ] [ m00x + m01y + m02 ]32 * [ y'] = [ m10 m11 m12 ] [ y ] = [ m10x + m11y + m12 ]33 * [ 1 ] [ 0 0 1 ] [ 1 ] [ 1 ]34 * </pre>35 *36 * This class is optimized for speed and minimizes calculations based on its37 * knowledge of the underlying matrix (as opposed to say simply performing38 * matrix multiplication).39 *40 * @param {number=} opt_m00 The m00 coordinate of the transform.41 * @param {number=} opt_m10 The m10 coordinate of the transform.42 * @param {number=} opt_m01 The m01 coordinate of the transform.43 * @param {number=} opt_m11 The m11 coordinate of the transform.44 * @param {number=} opt_m02 The m02 coordinate of the transform.45 * @param {number=} opt_m12 The m12 coordinate of the transform.46 * @constructor47 */48goog.graphics.AffineTransform = function(opt_m00, opt_m10, opt_m01,49 opt_m11, opt_m02, opt_m12) {50 if (arguments.length == 6) {51 this.setTransform(/** @type {number} */ (opt_m00),52 /** @type {number} */ (opt_m10),53 /** @type {number} */ (opt_m01),54 /** @type {number} */ (opt_m11),55 /** @type {number} */ (opt_m02),56 /** @type {number} */ (opt_m12));57 } else if (arguments.length != 0) {58 throw Error('Insufficient matrix parameters');59 } else {60 this.m00_ = this.m11_ = 1;61 this.m10_ = this.m01_ = this.m02_ = this.m12_ = 0;62 }63};64/**65 * @return {boolean} Whether this transform is the identity transform.66 */67goog.graphics.AffineTransform.prototype.isIdentity = function() {68 return this.m00_ == 1 && this.m10_ == 0 && this.m01_ == 0 &&69 this.m11_ == 1 && this.m02_ == 0 && this.m12_ == 0;70};71/**72 * @return {!goog.graphics.AffineTransform} A copy of this transform.73 */74goog.graphics.AffineTransform.prototype.clone = function() {75 return new goog.graphics.AffineTransform(this.m00_, this.m10_, this.m01_,76 this.m11_, this.m02_, this.m12_);77};78/**79 * Sets this transform to the matrix specified by the 6 values.80 *81 * @param {number} m00 The m00 coordinate of the transform.82 * @param {number} m10 The m10 coordinate of the transform.83 * @param {number} m01 The m01 coordinate of the transform.84 * @param {number} m11 The m11 coordinate of the transform.85 * @param {number} m02 The m02 coordinate of the transform.86 * @param {number} m12 The m12 coordinate of the transform.87 * @return {!goog.graphics.AffineTransform} This affine transform.88 */89goog.graphics.AffineTransform.prototype.setTransform = function(m00, m10, m01,90 m11, m02, m12) {91 if (!goog.isNumber(m00) || !goog.isNumber(m10) || !goog.isNumber(m01) ||92 !goog.isNumber(m11) || !goog.isNumber(m02) || !goog.isNumber(m12)) {93 throw Error('Invalid transform parameters');94 }95 this.m00_ = m00;96 this.m10_ = m10;97 this.m01_ = m01;98 this.m11_ = m11;99 this.m02_ = m02;100 this.m12_ = m12;101 return this;102};103/**104 * Sets this transform to be identical to the given transform.105 *106 * @param {!goog.graphics.AffineTransform} tx The transform to copy.107 * @return {!goog.graphics.AffineTransform} This affine transform.108 */109goog.graphics.AffineTransform.prototype.copyFrom = function(tx) {110 this.m00_ = tx.m00_;111 this.m10_ = tx.m10_;112 this.m01_ = tx.m01_;113 this.m11_ = tx.m11_;114 this.m02_ = tx.m02_;115 this.m12_ = tx.m12_;116 return this;117};118/**119 * Concatenates this transform with a scaling transformation.120 *121 * @param {number} sx The x-axis scaling factor.122 * @param {number} sy The y-axis scaling factor.123 * @return {!goog.graphics.AffineTransform} This affine transform.124 */125goog.graphics.AffineTransform.prototype.scale = function(sx, sy) {126 this.m00_ *= sx;127 this.m10_ *= sx;128 this.m01_ *= sy;129 this.m11_ *= sy;130 return this;131};132/**133 * Pre-concatenates this transform with a scaling transformation,134 * i.e. calculates the following matrix product:135 *136 * <pre>137 * [sx 0 0] [m00 m01 m02]138 * [ 0 sy 0] [m10 m11 m12]139 * [ 0 0 1] [ 0 0 1]140 * </pre>141 *142 * @param {number} sx The x-axis scaling factor.143 * @param {number} sy The y-axis scaling factor.144 * @return {!goog.graphics.AffineTransform} This affine transform.145 */146goog.graphics.AffineTransform.prototype.preScale = function(sx, sy) {147 this.m00_ *= sx;148 this.m01_ *= sx;149 this.m02_ *= sx;150 this.m10_ *= sy;151 this.m11_ *= sy;152 this.m12_ *= sy;153 return this;154};155/**156 * Concatenates this transform with a translate transformation.157 *158 * @param {number} dx The distance to translate in the x direction.159 * @param {number} dy The distance to translate in the y direction.160 * @return {!goog.graphics.AffineTransform} This affine transform.161 */162goog.graphics.AffineTransform.prototype.translate = function(dx, dy) {163 this.m02_ += dx * this.m00_ + dy * this.m01_;164 this.m12_ += dx * this.m10_ + dy * this.m11_;165 return this;166};167/**168 * Pre-concatenates this transform with a translate transformation,169 * i.e. calculates the following matrix product:170 *171 * <pre>172 * [1 0 dx] [m00 m01 m02]173 * [0 1 dy] [m10 m11 m12]174 * [0 0 1] [ 0 0 1]175 * </pre>176 *177 * @param {number} dx The distance to translate in the x direction.178 * @param {number} dy The distance to translate in the y direction.179 * @return {!goog.graphics.AffineTransform} This affine transform.180 */181goog.graphics.AffineTransform.prototype.preTranslate = function(dx, dy) {182 this.m02_ += dx;183 this.m12_ += dy;184 return this;185};186/**187 * Concatenates this transform with a rotation transformation around an anchor188 * point.189 *190 * @param {number} theta The angle of rotation measured in radians.191 * @param {number} x The x coordinate of the anchor point.192 * @param {number} y The y coordinate of the anchor point.193 * @return {!goog.graphics.AffineTransform} This affine transform.194 */195goog.graphics.AffineTransform.prototype.rotate = function(theta, x, y) {196 return this.concatenate(197 goog.graphics.AffineTransform.getRotateInstance(theta, x, y));198};199/**200 * Pre-concatenates this transform with a rotation transformation around an201 * anchor point.202 *203 * @param {number} theta The angle of rotation measured in radians.204 * @param {number} x The x coordinate of the anchor point.205 * @param {number} y The y coordinate of the anchor point.206 * @return {!goog.graphics.AffineTransform} This affine transform.207 */208goog.graphics.AffineTransform.prototype.preRotate = function(theta, x, y) {209 return this.preConcatenate(210 goog.graphics.AffineTransform.getRotateInstance(theta, x, y));211};212/**213 * Concatenates this transform with a shear transformation.214 *215 * @param {number} shx The x shear factor.216 * @param {number} shy The y shear factor.217 * @return {!goog.graphics.AffineTransform} This affine transform.218 */219goog.graphics.AffineTransform.prototype.shear = function(shx, shy) {220 var m00 = this.m00_;221 var m10 = this.m10_;222 this.m00_ += shy * this.m01_;223 this.m10_ += shy * this.m11_;224 this.m01_ += shx * m00;225 this.m11_ += shx * m10;226 return this;227};228/**229 * Pre-concatenates this transform with a shear transformation.230 * i.e. calculates the following matrix product:231 *232 * <pre>233 * [ 1 shx 0] [m00 m01 m02]234 * [shy 1 0] [m10 m11 m12]235 * [ 0 0 1] [ 0 0 1]236 * </pre>237 *238 * @param {number} shx The x shear factor.239 * @param {number} shy The y shear factor.240 * @return {!goog.graphics.AffineTransform} This affine transform.241 */242goog.graphics.AffineTransform.prototype.preShear = function(shx, shy) {243 var m00 = this.m00_;244 var m01 = this.m01_;245 var m02 = this.m02_;246 this.m00_ += shx * this.m10_;247 this.m01_ += shx * this.m11_;248 this.m02_ += shx * this.m12_;249 this.m10_ += shy * m00;250 this.m11_ += shy * m01;251 this.m12_ += shy * m02;252 return this;253};254/**255 * @return {string} A string representation of this transform. The format of256 * of the string is compatible with SVG matrix notation, i.e.257 * "matrix(a,b,c,d,e,f)".258 * @override259 */260goog.graphics.AffineTransform.prototype.toString = function() {261 return 'matrix(' +262 [this.m00_, this.m10_, this.m01_, this.m11_, this.m02_, this.m12_].join(263 ',') +264 ')';265};266/**267 * @return {number} The scaling factor in the x-direction (m00).268 */269goog.graphics.AffineTransform.prototype.getScaleX = function() {270 return this.m00_;271};272/**273 * @return {number} The scaling factor in the y-direction (m11).274 */275goog.graphics.AffineTransform.prototype.getScaleY = function() {276 return this.m11_;277};278/**279 * @return {number} The translation in the x-direction (m02).280 */281goog.graphics.AffineTransform.prototype.getTranslateX = function() {282 return this.m02_;283};284/**285 * @return {number} The translation in the y-direction (m12).286 */287goog.graphics.AffineTransform.prototype.getTranslateY = function() {288 return this.m12_;289};290/**291 * @return {number} The shear factor in the x-direction (m01).292 */293goog.graphics.AffineTransform.prototype.getShearX = function() {294 return this.m01_;295};296/**297 * @return {number} The shear factor in the y-direction (m10).298 */299goog.graphics.AffineTransform.prototype.getShearY = function() {300 return this.m10_;301};302/**303 * Concatenates an affine transform to this transform.304 *305 * @param {!goog.graphics.AffineTransform} tx The transform to concatenate.306 * @return {!goog.graphics.AffineTransform} This affine transform.307 */308goog.graphics.AffineTransform.prototype.concatenate = function(tx) {309 var m0 = this.m00_;310 var m1 = this.m01_;311 this.m00_ = tx.m00_ * m0 + tx.m10_ * m1;312 this.m01_ = tx.m01_ * m0 + tx.m11_ * m1;313 this.m02_ += tx.m02_ * m0 + tx.m12_ * m1;314 m0 = this.m10_;315 m1 = this.m11_;316 this.m10_ = tx.m00_ * m0 + tx.m10_ * m1;317 this.m11_ = tx.m01_ * m0 + tx.m11_ * m1;318 this.m12_ += tx.m02_ * m0 + tx.m12_ * m1;319 return this;320};321/**322 * Pre-concatenates an affine transform to this transform.323 *324 * @param {!goog.graphics.AffineTransform} tx The transform to preconcatenate.325 * @return {!goog.graphics.AffineTransform} This affine transform.326 */327goog.graphics.AffineTransform.prototype.preConcatenate = function(tx) {328 var m0 = this.m00_;329 var m1 = this.m10_;330 this.m00_ = tx.m00_ * m0 + tx.m01_ * m1;331 this.m10_ = tx.m10_ * m0 + tx.m11_ * m1;332 m0 = this.m01_;333 m1 = this.m11_;334 this.m01_ = tx.m00_ * m0 + tx.m01_ * m1;335 this.m11_ = tx.m10_ * m0 + tx.m11_ * m1;336 m0 = this.m02_;337 m1 = this.m12_;338 this.m02_ = tx.m00_ * m0 + tx.m01_ * m1 + tx.m02_;339 this.m12_ = tx.m10_ * m0 + tx.m11_ * m1 + tx.m12_;340 return this;341};342/**343 * Transforms an array of coordinates by this transform and stores the result344 * into a destination array.345 *346 * @param {!Array.<number>} src The array containing the source points347 * as x, y value pairs.348 * @param {number} srcOff The offset to the first point to be transformed.349 * @param {!Array.<number>} dst The array into which to store the transformed350 * point pairs.351 * @param {number} dstOff The offset of the location of the first transformed352 * point in the destination array.353 * @param {number} numPts The number of points to tranform.354 */355goog.graphics.AffineTransform.prototype.transform = function(src, srcOff, dst,356 dstOff, numPts) {357 var i = srcOff;358 var j = dstOff;359 var srcEnd = srcOff + 2 * numPts;360 while (i < srcEnd) {361 var x = src[i++];362 var y = src[i++];363 dst[j++] = x * this.m00_ + y * this.m01_ + this.m02_;364 dst[j++] = x * this.m10_ + y * this.m11_ + this.m12_;365 }366};367/**368 * @return {number} The determinant of this transform.369 */370goog.graphics.AffineTransform.prototype.getDeterminant = function() {371 return this.m00_ * this.m11_ - this.m01_ * this.m10_;372};373/**374 * Returns whether the transform is invertible. A transform is not invertible375 * if the determinant is 0 or any value is non-finite or NaN.376 *377 * @return {boolean} Whether the transform is invertible.378 */379goog.graphics.AffineTransform.prototype.isInvertible = function() {380 var det = this.getDeterminant();381 return goog.math.isFiniteNumber(det) &&382 goog.math.isFiniteNumber(this.m02_) &&383 goog.math.isFiniteNumber(this.m12_) &&384 det != 0;385};386/**387 * @return {!goog.graphics.AffineTransform} An AffineTransform object388 * representing the inverse transformation.389 */390goog.graphics.AffineTransform.prototype.createInverse = function() {391 var det = this.getDeterminant();392 return new goog.graphics.AffineTransform(393 this.m11_ / det,394 -this.m10_ / det,395 -this.m01_ / det,396 this.m00_ / det,397 (this.m01_ * this.m12_ - this.m11_ * this.m02_) / det,398 (this.m10_ * this.m02_ - this.m00_ * this.m12_) / det);399};400/**401 * Creates a transform representing a scaling transformation.402 *403 * @param {number} sx The x-axis scaling factor.404 * @param {number} sy The y-axis scaling factor.405 * @return {!goog.graphics.AffineTransform} A transform representing a scaling406 * transformation.407 */408goog.graphics.AffineTransform.getScaleInstance = function(sx, sy) {409 return new goog.graphics.AffineTransform().setToScale(sx, sy);410};411/**412 * Creates a transform representing a translation transformation.413 *414 * @param {number} dx The distance to translate in the x direction.415 * @param {number} dy The distance to translate in the y direction.416 * @return {!goog.graphics.AffineTransform} A transform representing a417 * translation transformation.418 */419goog.graphics.AffineTransform.getTranslateInstance = function(dx, dy) {420 return new goog.graphics.AffineTransform().setToTranslation(dx, dy);421};422/**423 * Creates a transform representing a shearing transformation.424 *425 * @param {number} shx The x-axis shear factor.426 * @param {number} shy The y-axis shear factor.427 * @return {!goog.graphics.AffineTransform} A transform representing a shearing428 * transformation.429 */430goog.graphics.AffineTransform.getShearInstance = function(shx, shy) {431 return new goog.graphics.AffineTransform().setToShear(shx, shy);432};433/**434 * Creates a transform representing a rotation transformation.435 *436 * @param {number} theta The angle of rotation measured in radians.437 * @param {number} x The x coordinate of the anchor point.438 * @param {number} y The y coordinate of the anchor point.439 * @return {!goog.graphics.AffineTransform} A transform representing a rotation440 * transformation.441 */442goog.graphics.AffineTransform.getRotateInstance = function(theta, x, y) {443 return new goog.graphics.AffineTransform().setToRotation(theta, x, y);444};445/**446 * Sets this transform to a scaling transformation.447 *448 * @param {number} sx The x-axis scaling factor.449 * @param {number} sy The y-axis scaling factor.450 * @return {!goog.graphics.AffineTransform} This affine transform.451 */452goog.graphics.AffineTransform.prototype.setToScale = function(sx, sy) {453 return this.setTransform(sx, 0, 0, sy, 0, 0);454};455/**456 * Sets this transform to a translation transformation.457 *458 * @param {number} dx The distance to translate in the x direction.459 * @param {number} dy The distance to translate in the y direction.460 * @return {!goog.graphics.AffineTransform} This affine transform.461 */462goog.graphics.AffineTransform.prototype.setToTranslation = function(dx, dy) {463 return this.setTransform(1, 0, 0, 1, dx, dy);464};465/**466 * Sets this transform to a shearing transformation.467 *468 * @param {number} shx The x-axis shear factor.469 * @param {number} shy The y-axis shear factor.470 * @return {!goog.graphics.AffineTransform} This affine transform.471 */472goog.graphics.AffineTransform.prototype.setToShear = function(shx, shy) {473 return this.setTransform(1, shy, shx, 1, 0, 0);474};475/**476 * Sets this transform to a rotation transformation.477 *478 * @param {number} theta The angle of rotation measured in radians.479 * @param {number} x The x coordinate of the anchor point.480 * @param {number} y The y coordinate of the anchor point.481 * @return {!goog.graphics.AffineTransform} This affine transform.482 */483goog.graphics.AffineTransform.prototype.setToRotation = function(theta, x, y) {484 var cos = Math.cos(theta);485 var sin = Math.sin(theta);486 return this.setTransform(cos, sin, -sin, cos,487 x - x * cos + y * sin, y - x * sin - y * cos);488};489/**490 * Compares two affine transforms for equality.491 *492 * @param {goog.graphics.AffineTransform} tx The other affine transform.493 * @return {boolean} whether the two transforms are equal.494 */495goog.graphics.AffineTransform.prototype.equals = function(tx) {496 if (this == tx) {497 return true;498 }499 if (!tx) {500 return false;501 }502 return this.m00_ == tx.m00_ &&503 this.m01_ == tx.m01_ &&504 this.m02_ == tx.m02_ &&505 this.m10_ == tx.m10_ &&506 this.m11_ == tx.m11_ &&507 this.m12_ == tx.m12_;...
_LookupTransformResult.py
Source:_LookupTransformResult.py
1# This Python file uses the following encoding: utf-82"""autogenerated by genpy from tf2_msgs/LookupTransformResult.msg. Do not edit."""3import sys4python3 = True if sys.hexversion > 0x03000000 else False5import genpy6import struct7import geometry_msgs.msg8import tf2_msgs.msg9import std_msgs.msg10class LookupTransformResult(genpy.Message):11 _md5sum = "3fe5db6a19ca9cfb675418c5ad875c36"12 _type = "tf2_msgs/LookupTransformResult"13 _has_header = False #flag to mark the presence of a Header object14 _full_text = """# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======15geometry_msgs/TransformStamped transform16tf2_msgs/TF2Error error17================================================================================18MSG: geometry_msgs/TransformStamped19# This expresses a transform from coordinate frame header.frame_id20# to the coordinate frame child_frame_id21#22# This message is mostly used by the 23# <a href="http://www.ros.org/wiki/tf">tf</a> package. 24# See its documentation for more information.25Header header26string child_frame_id # the frame id of the child frame27Transform transform28================================================================================29MSG: std_msgs/Header30# Standard metadata for higher-level stamped data types.31# This is generally used to communicate timestamped data 32# in a particular coordinate frame.33# 34# sequence ID: consecutively increasing ID 35uint32 seq36#Two-integer timestamp that is expressed as:37# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')38# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')39# time-handling sugar is provided by the client library40time stamp41#Frame this data is associated with42# 0: no frame43# 1: global frame44string frame_id45================================================================================46MSG: geometry_msgs/Transform47# This represents the transform between two coordinate frames in free space.48Vector3 translation49Quaternion rotation50================================================================================51MSG: geometry_msgs/Vector352# This represents a vector in free space. 53# It is only meant to represent a direction. Therefore, it does not54# make sense to apply a translation to it (e.g., when applying a 55# generic rigid transformation to a Vector3, tf2 will only apply the56# rotation). If you want your data to be translatable too, use the57# geometry_msgs/Point message instead.58float64 x59float64 y60float64 z61================================================================================62MSG: geometry_msgs/Quaternion63# This represents an orientation in free space in quaternion form.64float64 x65float64 y66float64 z67float64 w68================================================================================69MSG: tf2_msgs/TF2Error70uint8 NO_ERROR = 071uint8 LOOKUP_ERROR = 172uint8 CONNECTIVITY_ERROR = 273uint8 EXTRAPOLATION_ERROR = 374uint8 INVALID_ARGUMENT_ERROR = 475uint8 TIMEOUT_ERROR = 576uint8 TRANSFORM_ERROR = 677uint8 error78string error_string79"""80 __slots__ = ['transform','error']81 _slot_types = ['geometry_msgs/TransformStamped','tf2_msgs/TF2Error']82 def __init__(self, *args, **kwds):83 """84 Constructor. Any message fields that are implicitly/explicitly85 set to None will be assigned a default value. The recommend86 use is keyword arguments as this is more robust to future message87 changes. You cannot mix in-order arguments and keyword arguments.88 The available fields are:89 transform,error90 :param args: complete set of field values, in .msg order91 :param kwds: use keyword arguments corresponding to message field names92 to set specific fields.93 """94 if args or kwds:95 super(LookupTransformResult, self).__init__(*args, **kwds)96 #message fields cannot be None, assign default values for those that are97 if self.transform is None:98 self.transform = geometry_msgs.msg.TransformStamped()99 if self.error is None:100 self.error = tf2_msgs.msg.TF2Error()101 else:102 self.transform = geometry_msgs.msg.TransformStamped()103 self.error = tf2_msgs.msg.TF2Error()104 def _get_types(self):105 """106 internal API method107 """108 return self._slot_types109 def serialize(self, buff):110 """111 serialize message into buffer112 :param buff: buffer, ``StringIO``113 """114 try:115 _x = self116 buff.write(_struct_3I.pack(_x.transform.header.seq, _x.transform.header.stamp.secs, _x.transform.header.stamp.nsecs))117 _x = self.transform.header.frame_id118 length = len(_x)119 if python3 or type(_x) == unicode:120 _x = _x.encode('utf-8')121 length = len(_x)122 if python3:123 buff.write(struct.pack('<I%sB'%length, length, *_x))124 else:125 buff.write(struct.pack('<I%ss'%length, length, _x))126 _x = self.transform.child_frame_id127 length = len(_x)128 if python3 or type(_x) == unicode:129 _x = _x.encode('utf-8')130 length = len(_x)131 if python3:132 buff.write(struct.pack('<I%sB'%length, length, *_x))133 else:134 buff.write(struct.pack('<I%ss'%length, length, _x))135 _x = self136 buff.write(_struct_7dB.pack(_x.transform.transform.translation.x, _x.transform.transform.translation.y, _x.transform.transform.translation.z, _x.transform.transform.rotation.x, _x.transform.transform.rotation.y, _x.transform.transform.rotation.z, _x.transform.transform.rotation.w, _x.error.error))137 _x = self.error.error_string138 length = len(_x)139 if python3 or type(_x) == unicode:140 _x = _x.encode('utf-8')141 length = len(_x)142 if python3:143 buff.write(struct.pack('<I%sB'%length, length, *_x))144 else:145 buff.write(struct.pack('<I%ss'%length, length, _x))146 except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))147 except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))148 def deserialize(self, str):149 """150 unpack serialized message in str into this message instance151 :param str: byte array of serialized message, ``str``152 """153 try:154 if self.transform is None:155 self.transform = geometry_msgs.msg.TransformStamped()156 if self.error is None:157 self.error = tf2_msgs.msg.TF2Error()158 end = 0159 _x = self160 start = end161 end += 12162 (_x.transform.header.seq, _x.transform.header.stamp.secs, _x.transform.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])163 start = end164 end += 4165 (length,) = _struct_I.unpack(str[start:end])166 start = end167 end += length168 if python3:169 self.transform.header.frame_id = str[start:end].decode('utf-8')170 else:171 self.transform.header.frame_id = str[start:end]172 start = end173 end += 4174 (length,) = _struct_I.unpack(str[start:end])175 start = end176 end += length177 if python3:178 self.transform.child_frame_id = str[start:end].decode('utf-8')179 else:180 self.transform.child_frame_id = str[start:end]181 _x = self182 start = end183 end += 57184 (_x.transform.transform.translation.x, _x.transform.transform.translation.y, _x.transform.transform.translation.z, _x.transform.transform.rotation.x, _x.transform.transform.rotation.y, _x.transform.transform.rotation.z, _x.transform.transform.rotation.w, _x.error.error,) = _struct_7dB.unpack(str[start:end])185 start = end186 end += 4187 (length,) = _struct_I.unpack(str[start:end])188 start = end189 end += length190 if python3:191 self.error.error_string = str[start:end].decode('utf-8')192 else:193 self.error.error_string = str[start:end]194 return self195 except struct.error as e:196 raise genpy.DeserializationError(e) #most likely buffer underfill197 def serialize_numpy(self, buff, numpy):198 """199 serialize message with numpy array types into buffer200 :param buff: buffer, ``StringIO``201 :param numpy: numpy python module202 """203 try:204 _x = self205 buff.write(_struct_3I.pack(_x.transform.header.seq, _x.transform.header.stamp.secs, _x.transform.header.stamp.nsecs))206 _x = self.transform.header.frame_id207 length = len(_x)208 if python3 or type(_x) == unicode:209 _x = _x.encode('utf-8')210 length = len(_x)211 if python3:212 buff.write(struct.pack('<I%sB'%length, length, *_x))213 else:214 buff.write(struct.pack('<I%ss'%length, length, _x))215 _x = self.transform.child_frame_id216 length = len(_x)217 if python3 or type(_x) == unicode:218 _x = _x.encode('utf-8')219 length = len(_x)220 if python3:221 buff.write(struct.pack('<I%sB'%length, length, *_x))222 else:223 buff.write(struct.pack('<I%ss'%length, length, _x))224 _x = self225 buff.write(_struct_7dB.pack(_x.transform.transform.translation.x, _x.transform.transform.translation.y, _x.transform.transform.translation.z, _x.transform.transform.rotation.x, _x.transform.transform.rotation.y, _x.transform.transform.rotation.z, _x.transform.transform.rotation.w, _x.error.error))226 _x = self.error.error_string227 length = len(_x)228 if python3 or type(_x) == unicode:229 _x = _x.encode('utf-8')230 length = len(_x)231 if python3:232 buff.write(struct.pack('<I%sB'%length, length, *_x))233 else:234 buff.write(struct.pack('<I%ss'%length, length, _x))235 except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))236 except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))237 def deserialize_numpy(self, str, numpy):238 """239 unpack serialized message in str into this message instance using numpy for array types240 :param str: byte array of serialized message, ``str``241 :param numpy: numpy python module242 """243 try:244 if self.transform is None:245 self.transform = geometry_msgs.msg.TransformStamped()246 if self.error is None:247 self.error = tf2_msgs.msg.TF2Error()248 end = 0249 _x = self250 start = end251 end += 12252 (_x.transform.header.seq, _x.transform.header.stamp.secs, _x.transform.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])253 start = end254 end += 4255 (length,) = _struct_I.unpack(str[start:end])256 start = end257 end += length258 if python3:259 self.transform.header.frame_id = str[start:end].decode('utf-8')260 else:261 self.transform.header.frame_id = str[start:end]262 start = end263 end += 4264 (length,) = _struct_I.unpack(str[start:end])265 start = end266 end += length267 if python3:268 self.transform.child_frame_id = str[start:end].decode('utf-8')269 else:270 self.transform.child_frame_id = str[start:end]271 _x = self272 start = end273 end += 57274 (_x.transform.transform.translation.x, _x.transform.transform.translation.y, _x.transform.transform.translation.z, _x.transform.transform.rotation.x, _x.transform.transform.rotation.y, _x.transform.transform.rotation.z, _x.transform.transform.rotation.w, _x.error.error,) = _struct_7dB.unpack(str[start:end])275 start = end276 end += 4277 (length,) = _struct_I.unpack(str[start:end])278 start = end279 end += length280 if python3:281 self.error.error_string = str[start:end].decode('utf-8')282 else:283 self.error.error_string = str[start:end]284 return self285 except struct.error as e:286 raise genpy.DeserializationError(e) #most likely buffer underfill287_struct_I = genpy.struct_I288_struct_3I = struct.Struct("<3I")...
convertTransform.js
Source:convertTransform.js
...75 if (params.removeUseless) {76 data = removeUseless(data);77 }78 if (data.length) {79 item.attr(attrName).value = js2transform(data, params);80 } else {81 item.removeAttr(attrName);82 }83}84/**85 * Defines precision to work with certain parts.86 * transformPrecision - for scale and four first matrix parameters (needs a better precision due to multiplying),87 * floatPrecision - for translate including two last matrix and rotate parameters,88 * degPrecision - for rotate and skew. By default it's equal to (rougly)89 * transformPrecision - 2 or floatPrecision whichever is lower. Can be set in params.90 *91 * @param {Array} transforms input array92 * @param {Object} params plugin params93 * @return {Array} output array94 */95function definePrecision(data, params) {96 /* jshint validthis: true */97 var matrixData = data.reduce(getMatrixData, []),98 significantDigits = params.transformPrecision;99 // Clone params so it don't affect other elements transformations.100 params = EXTEND({}, params);101 // Limit transform precision with matrix one. Calculating with larger precision doesn't add any value.102 if (matrixData.length) {103 params.transformPrecision = Math.min(params.transformPrecision,104 Math.max.apply(Math, matrixData.map(floatDigits)) || params.transformPrecision);105 significantDigits = Math.max.apply(Math, matrixData.map(function(n) {106 return String(n).replace(/\D+/g, '').length; // Number of digits in a number. 123.45 â 5107 }));108 }109 // No sense in angle precision more then number of significant digits in matrix.110 if (!('degPrecision' in params)) {111 params.degPrecision = Math.max(0, Math.min(params.floatPrecision, significantDigits - 2));112 }113 floatRound = params.floatPrecision >= 1 && params.floatPrecision < 20 ?114 smartRound.bind(this, params.floatPrecision) :115 round;116 degRound = params.degPrecision >= 1 && params.floatPrecision < 20 ?117 smartRound.bind(this, params.degPrecision) :118 round;119 transformRound = params.transformPrecision >= 1 && params.floatPrecision < 20 ?120 smartRound.bind(this, params.transformPrecision) :121 round;122 return params;123}124/**125 * Gathers four first matrix parameters.126 *127 * @param {Array} a array of data128 * @param {Object} transform129 * @return {Array} output array130 */131function getMatrixData(a, b) {132 return b.name == 'matrix' ? a.concat(b.data.slice(0, 4)) : a;133}134/**135 * Returns number of digits after the point. 0.125 â 3136 */137function floatDigits(n) {138 return (n = String(n)).slice(n.indexOf('.')).length - 1;139}140/**141 * Convert transforms to the shorthand alternatives.142 *143 * @param {Array} transforms input array144 * @param {Object} params plugin params145 * @return {Array} output array146 */147function convertToShorts(transforms, params) {148 for(var i = 0; i < transforms.length; i++) {149 var transform = transforms[i];150 // convert matrix to the short aliases151 if (152 params.matrixToTransform &&153 transform.name === 'matrix'154 ) {155 var decomposed = matrixToTransform(transform, params);156 if (decomposed != transform &&157 js2transform(decomposed, params).length <= js2transform([transform], params).length) {158 transforms.splice.apply(transforms, [i, 1].concat(decomposed));159 }160 transform = transforms[i];161 }162 // fixed-point numbers163 // 12.754997 â 12.755164 roundTransform(transform);165 // convert long translate transform notation to the shorts one166 // translate(10 0) â translate(10)167 if (168 params.shortTranslate &&169 transform.name === 'translate' &&170 transform.data.length === 2 &&171 !transform.data[1]172 ) {173 transform.data.pop();174 }175 // convert long scale transform notation to the shorts one176 // scale(2 2) â scale(2)177 if (178 params.shortScale &&179 transform.name === 'scale' &&180 transform.data.length === 2 &&181 transform.data[0] === transform.data[1]182 ) {183 transform.data.pop();184 }185 // convert long rotate transform notation to the short one186 // translate(cx cy) rotate(a) translate(-cx -cy) â rotate(a cx cy)187 if (188 params.shortRotate &&189 transforms[i - 2] &&190 transforms[i - 2].name === 'translate' &&191 transforms[i - 1].name === 'rotate' &&192 transforms[i].name === 'translate' &&193 transforms[i - 2].data[0] === -transforms[i].data[0] &&194 transforms[i - 2].data[1] === -transforms[i].data[1]195 ) {196 transforms.splice(i - 2, 3, {197 name: 'rotate',198 data: [199 transforms[i - 1].data[0],200 transforms[i - 2].data[0],201 transforms[i - 2].data[1]202 ]203 });204 // splice compensation205 i -= 2;206 transform = transforms[i];207 }208 }209 return transforms;210}211/**212 * Remove useless transforms.213 *214 * @param {Array} transforms input array215 * @return {Array} output array216 */217function removeUseless(transforms) {218 return transforms.filter(function(transform) {219 // translate(0), rotate(0[, cx, cy]), skewX(0), skewY(0)220 if (221 ['translate', 'rotate', 'skewX', 'skewY'].indexOf(transform.name) > -1 &&222 (transform.data.length == 1 || transform.name == 'rotate') &&223 !transform.data[0] ||224 // translate(0, 0)225 transform.name == 'translate' &&226 !transform.data[0] &&227 !transform.data[1] ||228 // scale(1)229 transform.name == 'scale' &&230 transform.data[0] == 1 &&231 (transform.data.length < 2 || transform.data[1] == 1) ||232 // matrix(1 0 0 1 0 0)233 transform.name == 'matrix' &&234 transform.data[0] == 1 &&235 transform.data[3] == 1 &&236 !(transform.data[1] || transform.data[2] || transform.data[4] || transform.data[5])237 ) {238 return false;239 }240 return true;241 });242}243/**244 * Convert transforms JS representation to string.245 *246 * @param {Array} transformJS JS representation array247 * @param {Object} params plugin params248 * @return {String} output string249 */250function js2transform(transformJS, params) {251 var transformString = '';252 // collect output value string253 transformJS.forEach(function(transform) {254 roundTransform(transform);255 transformString += (transformString && ' ') + transform.name + '(' + cleanupOutData(transform.data, params) + ')';256 });257 return transformString;258}259function roundTransform(transform) {260 switch (transform.name) {261 case 'translate':262 transform.data = floatRound(transform.data);263 break;264 case 'rotate':...
View.js
Source:View.js
1/**2 * Simple view coordinate system3 * Mapping given x, y to transformd view x, y4 */5define(function (require) {6 var vector = require('zrender/core/vector');7 var matrix = require('zrender/core/matrix');8 var Transformable = require('zrender/mixin/Transformable');9 var zrUtil = require('zrender/core/util');10 var BoundingRect = require('zrender/core/BoundingRect');11 var v2ApplyTransform = vector.applyTransform;12 // Dummy transform node13 function TransformDummy() {14 Transformable.call(this);15 }16 zrUtil.mixin(TransformDummy, Transformable);17 function View(name) {18 /**19 * @type {string}20 */21 this.name = name;22 /**23 * @type {Object}24 */25 this.zoomLimit;26 Transformable.call(this);27 this._roamTransform = new TransformDummy();28 this._viewTransform = new TransformDummy();29 this._center;30 this._zoom;31 }32 View.prototype = {33 constructor: View,34 type: 'view',35 /**36 * @param {Array.<string>}37 * @readOnly38 */39 dimensions: ['x', 'y'],40 /**41 * Set bounding rect42 * @param {number} x43 * @param {number} y44 * @param {number} width45 * @param {number} height46 */47 // PENDING to getRect48 setBoundingRect: function (x, y, width, height) {49 this._rect = new BoundingRect(x, y, width, height);50 return this._rect;51 },52 /**53 * @return {module:zrender/core/BoundingRect}54 */55 // PENDING to getRect56 getBoundingRect: function () {57 return this._rect;58 },59 /**60 * @param {number} x61 * @param {number} y62 * @param {number} width63 * @param {number} height64 */65 setViewRect: function (x, y, width, height) {66 width = width;67 height = height;68 this.transformTo(x, y, width, height);69 this._viewRect = new BoundingRect(x, y, width, height);70 },71 /**72 * Transformed to particular position and size73 * @param {number} x74 * @param {number} y75 * @param {number} width76 * @param {number} height77 */78 transformTo: function (x, y, width, height) {79 var rect = this.getBoundingRect();80 var viewTransform = this._viewTransform;81 viewTransform.transform = rect.calculateTransform(82 new BoundingRect(x, y, width, height)83 );84 viewTransform.decomposeTransform();85 this._updateTransform();86 },87 /**88 * Set center of view89 * @param {Array.<number>} [centerCoord]90 */91 setCenter: function (centerCoord) {92 if (!centerCoord) {93 return;94 }95 this._center = centerCoord;96 this._updateCenterAndZoom();97 },98 /**99 * @param {number} zoom100 */101 setZoom: function (zoom) {102 zoom = zoom || 1;103 var zoomLimit = this.zoomLimit;104 if (zoomLimit) {105 if (zoomLimit.max != null) {106 zoom = Math.min(zoomLimit.max, zoom);107 }108 if (zoomLimit.min != null) {109 zoom = Math.max(zoomLimit.min, zoom);110 }111 }112 this._zoom = zoom;113 this._updateCenterAndZoom();114 },115 /**116 * Get default center without roam117 */118 getDefaultCenter: function () {119 // Rect before any transform120 var rawRect = this.getBoundingRect();121 var cx = rawRect.x + rawRect.width / 2;122 var cy = rawRect.y + rawRect.height / 2;123 return [cx, cy];124 },125 getCenter: function () {126 return this._center || this.getDefaultCenter();127 },128 getZoom: function () {129 return this._zoom || 1;130 },131 /**132 * @return {Array.<number}133 */134 getRoamTransform: function () {135 return this._roamTransform;136 },137 _updateCenterAndZoom: function () {138 // Must update after view transform updated139 var viewTransformMatrix = this._viewTransform.getLocalTransform();140 var roamTransform = this._roamTransform;141 var defaultCenter = this.getDefaultCenter();142 var center = this.getCenter();143 var zoom = this.getZoom();144 center = vector.applyTransform([], center, viewTransformMatrix);145 defaultCenter = vector.applyTransform([], defaultCenter, viewTransformMatrix);146 roamTransform.origin = center;147 roamTransform.position = [148 defaultCenter[0] - center[0],149 defaultCenter[1] - center[1]150 ];151 roamTransform.scale = [zoom, zoom];152 this._updateTransform();153 },154 /**155 * Update transform from roam and mapLocation156 * @private157 */158 _updateTransform: function () {159 var roamTransform = this._roamTransform;160 var viewTransform = this._viewTransform;161 viewTransform.parent = roamTransform;162 roamTransform.updateTransform();163 viewTransform.updateTransform();164 viewTransform.transform165 && matrix.copy(this.transform || (this.transform = []), viewTransform.transform);166 if (this.transform) {167 this.invTransform = this.invTransform || [];168 matrix.invert(this.invTransform, this.transform);169 }170 else {171 this.invTransform = null;172 }173 this.decomposeTransform();174 },175 /**176 * @return {module:zrender/core/BoundingRect}177 */178 getViewRect: function () {179 return this._viewRect;180 },181 /**182 * Get view rect after roam transform183 * @return {module:zrender/core/BoundingRect}184 */185 getViewRectAfterRoam: function () {186 var rect = this.getBoundingRect().clone();187 rect.applyTransform(this.transform);188 return rect;189 },190 /**191 * Convert a single (lon, lat) data item to (x, y) point.192 * @param {Array.<number>} data193 * @return {Array.<number>}194 */195 dataToPoint: function (data) {196 var transform = this.transform;197 return transform198 ? v2ApplyTransform([], data, transform)199 : [data[0], data[1]];200 },201 /**202 * Convert a (x, y) point to (lon, lat) data203 * @param {Array.<number>} point204 * @return {Array.<number>}205 */206 pointToData: function (point) {207 var invTransform = this.invTransform;208 return invTransform209 ? v2ApplyTransform([], point, invTransform)210 : [point[0], point[1]];211 }212 /**213 * @return {number}214 */215 // getScalarScale: function () {216 // // Use determinant square root of transform to mutiply scalar217 // var m = this.transform;218 // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));219 // return det;220 // }221 };222 zrUtil.mixin(View, Transformable);223 return View;...
test_transform.py
Source:test_transform.py
1import bokeh.transform as bt2from bokeh.models import CategoricalColorMapper, Dodge, FactorRange, Jitter, LinearColorMapper, LogColorMapper3def test_transform():4 t = bt.transform("foo", "junk")5 assert t == dict(field="foo", transform="junk")6def test_dodge():7 t = bt.dodge("foo", 0.5)8 assert isinstance(t, dict)9 assert set(t) == {"field", "transform"}10 assert t['field'] == "foo"11 assert isinstance(t['transform'], Dodge)12 assert t['transform'].value == 0.513 assert t['transform'].range is None14def test_dodge_with_range():15 r = FactorRange("a")16 t = bt.dodge("foo", 0.5, range=r)17 assert isinstance(t, dict)18 assert set(t) == {"field", "transform"}...
SVGTransform.js
Source:SVGTransform.js
1description("This test checks the SVGTransform API");2var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");3var transform = svgElement.createSVGTransform();4debug("");5debug("Check initial transform values");6shouldBe("transform.type", "SVGTransform.SVG_TRANSFORM_MATRIX");7shouldBe("transform.angle", "0");8shouldBe("transform.matrix.a", "1");9shouldBe("transform.matrix.b", "0");10shouldBe("transform.matrix.c", "0");11shouldBe("transform.matrix.d", "1");12shouldBe("transform.matrix.e", "0");13shouldBe("transform.matrix.f", "0");14debug("");15debug("Change to skewX transformation");16shouldBeUndefined("transform.setSkewX(45)");17shouldBe("transform.type", "SVGTransform.SVG_TRANSFORM_SKEWX");18shouldBe("transform.angle", "45");19shouldBe("transform.matrix.a", "1");20shouldBe("transform.matrix.b", "0");21shouldBeEqualToString("transform.matrix.c.toFixed(1)", "1.0");22shouldBe("transform.matrix.d", "1");23shouldBe("transform.matrix.e", "0");24shouldBe("transform.matrix.f", "0");25debug("");26debug("Changing matrix.e to 100, should reset transformation type to MATRIX, and angle should be 0");27shouldBe("transform.matrix.e = 100", "100");28shouldBe("transform.type", "SVGTransform.SVG_TRANSFORM_MATRIX");29shouldBe("transform.angle", "0");30shouldBe("transform.matrix.a", "1");31shouldBe("transform.matrix.b", "0");32shouldBeEqualToString("transform.matrix.c.toFixed(1)", "1.0");33shouldBe("transform.matrix.d", "1");34shouldBe("transform.matrix.e", "100");35shouldBe("transform.matrix.f", "0");36debug("");37debug("Now revert to initial matrix");38shouldBeNull("transform.matrix.c = null");39shouldBe("transform.matrix.e = 0", "0");40shouldBe("transform.type", "SVGTransform.SVG_TRANSFORM_MATRIX");41shouldBe("transform.angle", "0");42shouldBe("transform.matrix.a", "1");43shouldBe("transform.matrix.b", "0");44shouldBe("transform.matrix.c", "0");45shouldBe("transform.matrix.d", "1");46shouldBe("transform.matrix.e", "0");47shouldBe("transform.matrix.f", "0");48debug("");49debug("Check passing invalid arguments to 'setMatrix'");50shouldThrow("transform.setMatrix()");51shouldThrow("transform.setMatrix(transform)");52shouldThrow("transform.setMatrix(svgElement)");53shouldThrow("transform.setMatrix('aString')");54shouldThrow("transform.setMatrix(1)");55shouldThrow("transform.setMatrix(false)");56debug("");57debug("Check passing invalid arguments to 'setTranslate'");58shouldThrow("transform.setTranslate()");59shouldThrow("transform.setTranslate(transform)");60shouldThrow("transform.setTranslate(svgElement)");61shouldThrow("transform.setTranslate('aString')");62shouldBeUndefined("transform.setTranslate(1, transform)");63shouldBeUndefined("transform.setTranslate(1, svgElement)");64shouldBeUndefined("transform.setTranslate(1, 'aString')");65shouldBeUndefined("transform.setTranslate(transform, 1)");66shouldBeUndefined("transform.setTranslate(svgElement, 1)");67shouldBeUndefined("transform.setTranslate('aString', 1)");68shouldBeUndefined("transform.setTranslate(transform, transform)");69shouldBeUndefined("transform.setTranslate(svgElement, svgElement)");70shouldBeUndefined("transform.setTranslate('aString', 'aString')");71debug("");72debug("Check passing invalid arguments to 'setScale'");73shouldThrow("transform.setScale()");74shouldThrow("transform.setScale(transform)");75shouldThrow("transform.setScale(svgElement)");76shouldThrow("transform.setScale('aString')");77shouldBeUndefined("transform.setScale(1, transform)");78shouldBeUndefined("transform.setScale(1, svgElement)");79shouldBeUndefined("transform.setScale(1, 'aString')");80shouldBeUndefined("transform.setScale(transform, 1)");81shouldBeUndefined("transform.setScale(svgElement, 1)");82shouldBeUndefined("transform.setScale('aString', 1)");83shouldBeUndefined("transform.setScale(transform, transform)");84shouldBeUndefined("transform.setScale(svgElement, svgElement)");85shouldBeUndefined("transform.setScale('aString', 'aString')");86debug("");87debug("Check passing invalid arguments to 'setRotate'");88shouldThrow("transform.setRotate()");89shouldThrow("transform.setRotate(transform)");90shouldThrow("transform.setRotate(svgElement)");91shouldThrow("transform.setRotate('aString')");92shouldThrow("transform.setRotate(1, transform)");93shouldThrow("transform.setRotate(1, svgElement)");94shouldThrow("transform.setRotate(1, 'aString')");95shouldBeUndefined("transform.setRotate(1, 1, transform)");96shouldBeUndefined("transform.setRotate(1, 1, svgElement)");97shouldBeUndefined("transform.setRotate(1, 1, 'aString')");98debug("");99debug("Check passing invalid arguments to 'setSkewX'");100shouldThrow("transform.setSkewX()");101shouldBeUndefined("transform.setSkewX(transform)");102shouldBeUndefined("transform.setSkewX(svgElement)");103shouldBeUndefined("transform.setSkewX('aString')");104debug("");105debug("Check passing invalid arguments to 'setSkewY'");106shouldThrow("transform.setSkewY()");107shouldBeUndefined("transform.setSkewY(transform)");108shouldBeUndefined("transform.setSkewY(svgElement)");109shouldBeUndefined("transform.setSkewY('aString')");...
Cube.js
Source:Cube.js
1/**2 * @private3 */4Ext.define('Ext.fx.animation.Cube', {5 extend: 'Ext.fx.animation.Abstract',6 alias: 'animation.cube',7 config: {8 /**9 * @cfg10 * @inheritdoc11 */12 before: {13// 'transform-style': 'preserve-3d'14 },15 after: {},16 /**17 * @cfg {String} direction The direction of which the slide animates18 * @accessor19 */20 direction: 'right',21 out: false22 },23// getData: function() {24// var to = this.getTo(),25// from = this.getFrom(),26// out = this.getOut(),27// direction = this.getDirection(),28// el = this.getElement(),29// elW = el.getWidth(),30// elH = el.getHeight(),31// halfWidth = (elW / 2),32// halfHeight = (elH / 2),33// fromTransform = {},34// toTransform = {},35// originalFromTransform = {36// rotateY: 0,37// translateX: 0,38// translateZ: 039// },40// originalToTransform = {41// rotateY: 90,42// translateX: halfWidth,43// translateZ: halfWidth44// },45// originalVerticalFromTransform = {46// rotateX: 0,47// translateY: 0,48// translateZ: 049// },50// originalVerticalToTransform = {51// rotateX: 90,52// translateY: halfHeight,53// translateZ: halfHeight54// },55// tempTransform;56//57// if (direction == "left" || direction == "right") {58// if (out) {59// toTransform = originalToTransform;60// fromTransform = originalFromTransform;61// } else {62// toTransform = originalFromTransform;63// fromTransform = originalToTransform;64// fromTransform.rotateY *= -1;65// fromTransform.translateX *= -1;66// }67//68// if (direction === 'right') {69// tempTransform = fromTransform;70// fromTransform = toTransform;71// toTransform = tempTransform;72// }73// }74//75// if (direction == "up" || direction == "down") {76// if (out) {77// toTransform = originalVerticalFromTransform;78// fromTransform = {79// rotateX: -90,80// translateY: halfHeight,81// translateZ: halfHeight82// };83// } else {84// fromTransform = originalVerticalFromTransform;85// toTransform = {86// rotateX: 90,87// translateY: -halfHeight,88// translateZ: halfHeight89// };90// }91//92// if (direction == "up") {93// tempTransform = fromTransform;94// fromTransform = toTransform;95// toTransform = tempTransform;96// }97// }98//99// from.set('transform', fromTransform);100// to.set('transform', toTransform);101//102// return this.callParent(arguments);103// },104 getData: function() {105 var to = this.getTo(),106 from = this.getFrom(),107 before = this.getBefore(),108 after = this.getAfter(),109 out = this.getOut(),110 direction = this.getDirection(),111 el = this.getElement(),112 elW = el.getWidth(),113 elH = el.getHeight(),114 origin = out ? '100% 100%' : '0% 0%',115 fromOpacity = 1,116 toOpacity = 1,117 transformFrom = {118 rotateY: 0,119 translateZ: 0120 },121 transformTo = {122 rotateY: 0,123 translateZ: 0124 };125 if (direction == "left" || direction == "right") {126 if (out) {127 toOpacity = 0.5;128 transformTo.translateZ = elW;129 transformTo.rotateY = -90;130 } else {131 fromOpacity = 0.5;132 transformFrom.translateZ = elW;133 transformFrom.rotateY = 90;134 }135 }136 before['transform-origin'] = origin;137 after['transform-origin'] = null;138 to.set('transform', transformTo);139 from.set('transform', transformFrom);140 from.set('opacity', fromOpacity);141 to.set('opacity', toOpacity);142 return this.callParent(arguments);143 }...
Using AI Code Generation
1const imposter = {2 {3 {4 "is": {5 "headers": {6 },7 "body": {8 }9 }10 }11 {12 "equals": {13 }14 }15 }16}17const mb = require('mountebank');18mb.create(imposter)19 .then(function (imposter) {20 console.log(imposter.port);21 })22 .catch(function (error) {23 console.error(error);24 });
Using AI Code Generation
1var request = require('request');2var options = {3 json: {4 {5 {6 "is": {7 }8 }9 }10 }11};12request(options, function (error, response, body) {13 console.log(body);14});15var request = require('request');16var options = {17 json: {18 {19 {20 "is": {21 }22 }23 }24 {25 {26 "equals": {27 }28 },29 {30 "equals": {31 }32 }33 }34 {35 "response": {36 "body": {37 }38 }39 }40 }41};42request(options, function (error, response, body) {43 console.log(body);44});45var request = require('request');46var options = {47 json: {48 {49 {50 "is": {51 }52 }53 }54 {55 {56 "equals": {57 }58 },59 {60 "equals": {61 }62 }63 }64 {65 "response": {66 "body": {
Using AI Code Generation
1var imposter = {2 stubs: [{3 predicates: [{4 equals: {5 }6 }],7 responses: [{8 is: {9 headers: {10 },11 }12 }]13 }]14};15var options = {16};17request(options, function (error, response, body) {18 if (error) {19 console.log(error);20 } else {21 console.log(body);22 }23});24var imposter = {25 stubs: [{26 predicates: [{27 equals: {28 }29 }],30 responses: [{31 is: {32 headers: {33 },34 }35 }]36 }]37};38var options = {39};40request(options, function (error, response, body) {41 if (error) {42 console.log(error);43 } else {44 console.log(body);45 }46});
Using AI Code Generation
1const mb = require('mountebank');2const imposter = {3 stubs: [{4 predicates: [{5 equals: {6 }7 }],8 responses: [{9 is: {10 headers: {11 },12 body: JSON.stringify({status: 'success'})13 },14 _behaviors: {15 _inject: 'function(response) {response.body = JSON.stringify({status: "success", data: {message: "Hello"}})}'16 }17 }]18 }]19};20mb.create(imposter).then(function () {21 console.log('Imposter created');22}).catch(function (error) {23 console.error('Error creating imposter', error);24});25const request = require('request-promise');26const mb = require('mountebank');27const imposter = {28 stubs: [{29 predicates: [{30 equals: {31 }32 }],33 responses: [{34 is: {35 headers: {36 },37 body: JSON.stringify({status: 'success'})38 },39 _behaviors: {40 _inject: 'function(response) {response.body = JSON.stringify({status: "success", data: {message: "Hello"}})}'41 }42 }]43 }]44};45describe('test', function () {46 before(function () {47 return mb.create(imposter);48 });49 after(function () {50 return mb.stopAll();51 });52 it('should return the correct message', function () {53 expect(response).to.equal(JSON.stringify({status: 'success', data: {message: 'Hello'}}));54 });55 });56});
Using AI Code Generation
1const mb = require('mountebank');2const response = {3 headers: {4 },5 body: {6 }7};8const predicateGenerators = {9 matches: {10 matches: {11 }12 }13};14const imposters = [{15 stubs: [{16 responses: [{17 _behaviors: {18 decorate: function (request) {19 return {20 body: {21 }22 };23 }24 }25 }],26 predicates: [{27 matches: {28 }29 }]30 }]31}];32mb.create({33}, function (error, imposters) {34 if (error) {35 console.error('Error creating mountebank server', error);36 } else {37 console.log('Mountebank server successfully created', imposters);38 }39});40const mb = require('mountebank');41const response = {42 headers: {43 },44 body: {45 }46};47const predicateGenerators = {48 matches: {49 matches: {50 }51 }52};53const imposters = [{54 stubs: [{55 responses: [{56 _behaviors: {57 decorate: function (request) {58 return {59 body: {60 }61 };62 }63 }64 }],65 predicates: [{66 matches: {67 }68 }]69 }]70}];71mb.create({
Using AI Code Generation
1var request = require('request');2var fs = require('fs');3var path = require('path');4var mountebank = require('mountebank');5 {6 {7 {8 is: {9 headers: {10 },11 body: JSON.stringify({12 })13 }14 }15 }16 }17];18var server = mountebank.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log' });19server.then(function (server) {20 server.createImposter(imposters[0]);21});22var options = {23 headers: {24 }25};26request(options, function (error, response, body) {27 console.log(body);28});
Using AI Code Generation
1var transform = require('mountebank').transform;2var request = require('mountebank').request;3var response = require('mountebank').response;4var logger = require('mountebank').logger;5var Q = require('q');6var jp = require('jsonpath');7var _ = require('lodash');8var moment = require('moment');9var faker = require('faker');10var uuid = require('uuid');11var request = require('request');12var xml2js = require('xml2js');13var fs = require('fs');14var path = require('path');15var os = require('os');16var child_process = require('child_process');17var util = require('util');18var tls = require('tls');19var https = require('https');20var http = require('http');21var url = require('url');22var querystring = require('querystring');23var crypto = require('crypto');24var zlib = require('zlib');25var assert = require('assert');26var events = require('events');27var stream = require('stream');28var buffer = require('buffer');29var net = require('net');30var string_decoder = require('string_decoder');31var constants = require('constants');32var timers = require('tim
Using AI Code Generation
1const request = require('request-promise-native');2const mbHelper = require('./mountebank-helper');3const mbPort = 2525;4const mbHost = 'localhost';5 {6 stubs: [{7 responses: [{8 is: { body: 'Hello, World!' }9 }]10 }]11 }12];13mbHelper.mbStart(mbUrl, mbPort, imposters)14 .then(() => {15 })16 .then((response) => {17 console.log(response);18 return mbHelper.mbStop(mbUrl);19 })20 .catch((err) => {21 console.log(err);22 });23const request = require('request-promise-native');24const mbHelper = {25 mbStart: (mbUrl, mbPort, imposters) => {26 return request.post(`${mbUrl}/imposters`, {27 body: { imposters }28 })29 .then(() => {30 return new Promise((resolve) => {31 setTimeout(() => {32 resolve();33 }, 1000);34 });35 })36 .then(() => {37 return request.get(`${mbUrl}/imposters`);38 })39 .then((response) => {40 const imposterJson = JSON.parse(response);41 if (imposterJson.length === 0) {42 throw new Error('Mountebank did not start!');43 }44 });45 },46 mbStop: (mbUrl) => {47 return request.delete(`${mbUrl}/imposters`);48 }49};50module.exports = mbHelper;
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!