Best Python code snippet using pyatom_python
distributed.py
Source:distributed.py
...81 else:82 raise TypeError("rows should be an RDD of vectors, got %s" % type(rows))83 self._java_matrix_wrapper = JavaModelWrapper(java_matrix)84 @property85 def rows(self):86 """87 Rows of the RowMatrix stored as an RDD of vectors.88 >>> mat = RowMatrix(sc.parallelize([[1, 2, 3], [4, 5, 6]]))89 >>> rows = mat.rows90 >>> rows.first()91 DenseVector([1.0, 2.0, 3.0])92 """93 return self._java_matrix_wrapper.call("rows")94 def numRows(self):95 """96 Get or compute the number of rows.97 >>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6],98 ... [7, 8, 9], [10, 11, 12]])99 >>> mat = RowMatrix(rows)100 >>> print(mat.numRows())101 4102 >>> mat = RowMatrix(rows, 7, 6)103 >>> print(mat.numRows())104 7105 """106 return self._java_matrix_wrapper.call("numRows")107 def numCols(self):108 """109 Get or compute the number of cols.110 >>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6],111 ... [7, 8, 9], [10, 11, 12]])112 >>> mat = RowMatrix(rows)113 >>> print(mat.numCols())114 3115 >>> mat = RowMatrix(rows, 7, 6)116 >>> print(mat.numCols())117 6118 """119 return self._java_matrix_wrapper.call("numCols")120 @since('2.0.0')121 def computeColumnSummaryStatistics(self):122 """123 Computes column-wise summary statistics.124 :return: :class:`MultivariateStatisticalSummary` object125 containing column-wise summary statistics.126 >>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6]])127 >>> mat = RowMatrix(rows)128 >>> colStats = mat.computeColumnSummaryStatistics()129 >>> colStats.mean()130 array([ 2.5, 3.5, 4.5])131 """132 java_col_stats = self._java_matrix_wrapper.call("computeColumnSummaryStatistics")133 return MultivariateStatisticalSummary(java_col_stats)134 @since('2.0.0')135 def computeCovariance(self):136 """137 Computes the covariance matrix, treating each row as an138 observation.139 .. note:: This cannot be computed on matrices with more than 65535 columns.140 >>> rows = sc.parallelize([[1, 2], [2, 1]])141 >>> mat = RowMatrix(rows)142 >>> mat.computeCovariance()143 DenseMatrix(2, 2, [0.5, -0.5, -0.5, 0.5], 0)144 """145 return self._java_matrix_wrapper.call("computeCovariance")146 @since('2.0.0')147 def computeGramianMatrix(self):148 """149 Computes the Gramian matrix `A^T A`.150 .. note:: This cannot be computed on matrices with more than 65535 columns.151 >>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6]])152 >>> mat = RowMatrix(rows)153 >>> mat.computeGramianMatrix()154 DenseMatrix(3, 3, [17.0, 22.0, 27.0, 22.0, 29.0, 36.0, 27.0, 36.0, 45.0], 0)155 """156 return self._java_matrix_wrapper.call("computeGramianMatrix")157 @since('2.0.0')158 def columnSimilarities(self, threshold=0.0):159 """160 Compute similarities between columns of this matrix.161 The threshold parameter is a trade-off knob between estimate162 quality and computational cost.163 The default threshold setting of 0 guarantees deterministically164 correct results, but uses the brute-force approach of computing165 normalized dot products.166 Setting the threshold to positive values uses a sampling167 approach and incurs strictly less computational cost than the168 brute-force approach. However the similarities computed will169 be estimates.170 The sampling guarantees relative-error correctness for those171 pairs of columns that have similarity greater than the given172 similarity threshold.173 To describe the guarantee, we set some notation:174 * Let A be the smallest in magnitude non-zero element of175 this matrix.176 * Let B be the largest in magnitude non-zero element of177 this matrix.178 * Let L be the maximum number of non-zeros per row.179 For example, for {0,1} matrices: A=B=1.180 Another example, for the Netflix matrix: A=1, B=5181 For those column pairs that are above the threshold, the182 computed similarity is correct to within 20% relative error183 with probability at least 1 - (0.981)^10/B^184 The shuffle size is bounded by the *smaller* of the following185 two expressions:186 * O(n log(n) L / (threshold * A))187 * O(m L^2^)188 The latter is the cost of the brute-force approach, so for189 non-zero thresholds, the cost is always cheaper than the190 brute-force approach.191 :param: threshold: Set to 0 for deterministic guaranteed192 correctness. Similarities above this193 threshold are estimated with the cost vs194 estimate quality trade-off described above.195 :return: An n x n sparse upper-triangular CoordinateMatrix of196 cosine similarities between columns of this matrix.197 >>> rows = sc.parallelize([[1, 2], [1, 5]])198 >>> mat = RowMatrix(rows)199 >>> sims = mat.columnSimilarities()200 >>> sims.entries.first().value201 0.91914503...202 """203 java_sims_mat = self._java_matrix_wrapper.call("columnSimilarities", float(threshold))204 return CoordinateMatrix(java_sims_mat)205 @since('2.0.0')206 def tallSkinnyQR(self, computeQ=False):207 """208 Compute the QR decomposition of this RowMatrix.209 The implementation is designed to optimize the QR decomposition210 (factorization) for the RowMatrix of a tall and skinny shape.211 Reference:212 Paul G. Constantine, David F. Gleich. "Tall and skinny QR213 factorizations in MapReduce architectures"214 ([[http://dx.doi.org/10.1145/1996092.1996103]])215 :param: computeQ: whether to computeQ216 :return: QRDecomposition(Q: RowMatrix, R: Matrix), where217 Q = None if computeQ = false.218 >>> rows = sc.parallelize([[3, -6], [4, -8], [0, 1]])219 >>> mat = RowMatrix(rows)220 >>> decomp = mat.tallSkinnyQR(True)221 >>> Q = decomp.Q222 >>> R = decomp.R223 >>> # Test with absolute values224 >>> absQRows = Q.rows.map(lambda row: abs(row.toArray()).tolist())225 >>> absQRows.collect()226 [[0.6..., 0.0], [0.8..., 0.0], [0.0, 1.0]]227 >>> # Test with absolute values228 >>> abs(R.toArray()).tolist()229 [[5.0, 10.0], [0.0, 1.0]]230 """231 decomp = JavaModelWrapper(self._java_matrix_wrapper.call("tallSkinnyQR", computeQ))232 if computeQ:233 java_Q = decomp.call("Q")234 Q = RowMatrix(java_Q)235 else:236 Q = None237 R = decomp.call("R")238 return QRDecomposition(Q, R)239 @since('2.2.0')240 def computeSVD(self, k, computeU=False, rCond=1e-9):241 """242 Computes the singular value decomposition of the RowMatrix.243 The given row matrix A of dimension (m X n) is decomposed into244 U * s * V'T where245 * U: (m X k) (left singular vectors) is a RowMatrix whose246 columns are the eigenvectors of (A X A')247 * s: DenseVector consisting of square root of the eigenvalues248 (singular values) in descending order.249 * v: (n X k) (right singular vectors) is a Matrix whose columns250 are the eigenvectors of (A' X A)251 For more specific details on implementation, please refer252 the Scala documentation.253 :param k: Number of leading singular values to keep (`0 < k <= n`).254 It might return less than k if there are numerically zero singular values255 or there are not enough Ritz values converged before the maximum number of256 Arnoldi update iterations is reached (in case that matrix A is ill-conditioned).257 :param computeU: Whether or not to compute U. If set to be258 True, then U is computed by A * V * s^-1259 :param rCond: Reciprocal condition number. All singular values260 smaller than rCond * s[0] are treated as zero261 where s[0] is the largest singular value.262 :returns: :py:class:`SingularValueDecomposition`263 >>> rows = sc.parallelize([[3, 1, 1], [-1, 3, 1]])264 >>> rm = RowMatrix(rows)265 >>> svd_model = rm.computeSVD(2, True)266 >>> svd_model.U.rows.collect()267 [DenseVector([-0.7071, 0.7071]), DenseVector([-0.7071, -0.7071])]268 >>> svd_model.s269 DenseVector([3.4641, 3.1623])270 >>> svd_model.V271 DenseMatrix(3, 2, [-0.4082, -0.8165, -0.4082, 0.8944, -0.4472, 0.0], 0)272 """273 j_model = self._java_matrix_wrapper.call(274 "computeSVD", int(k), bool(computeU), float(rCond))275 return SingularValueDecomposition(j_model)276 @since('2.2.0')277 def computePrincipalComponents(self, k):278 """279 Computes the k principal components of the given row matrix280 .. note:: This cannot be computed on matrices with more than 65535 columns.281 :param k: Number of principal components to keep.282 :returns: :py:class:`pyspark.mllib.linalg.DenseMatrix`283 >>> rows = sc.parallelize([[1, 2, 3], [2, 4, 5], [3, 6, 1]])284 >>> rm = RowMatrix(rows)285 >>> # Returns the two principal components of rm286 >>> pca = rm.computePrincipalComponents(2)287 >>> pca288 DenseMatrix(3, 2, [-0.349, -0.6981, 0.6252, -0.2796, -0.5592, -0.7805], 0)289 >>> # Transform into new dimensions with the greatest variance.290 >>> rm.multiply(pca).rows.collect() # doctest: +NORMALIZE_WHITESPACE291 [DenseVector([0.1305, -3.7394]), DenseVector([-0.3642, -6.6983]), \292 DenseVector([-4.6102, -4.9745])]293 """294 return self._java_matrix_wrapper.call("computePrincipalComponents", k)295 @since('2.2.0')296 def multiply(self, matrix):297 """298 Multiply this matrix by a local dense matrix on the right.299 :param matrix: a local dense matrix whose number of rows must match the number of columns300 of this matrix301 :returns: :py:class:`RowMatrix`302 >>> rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]]))303 >>> rm.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect()304 [DenseVector([2.0, 3.0]), DenseVector([6.0, 11.0])]305 """306 if not isinstance(matrix, DenseMatrix):307 raise ValueError("Only multiplication with DenseMatrix "308 "is supported.")309 j_model = self._java_matrix_wrapper.call("multiply", matrix)310 return RowMatrix(j_model)311class SingularValueDecomposition(JavaModelWrapper):312 """313 Represents singular value decomposition (SVD) factors.314 .. versionadded:: 2.2.0315 """316 @property317 @since('2.2.0')318 def U(self):319 """320 Returns a distributed matrix whose columns are the left321 singular vectors of the SingularValueDecomposition if computeU was set to be True.322 """323 u = self.call("U")324 if u is not None:325 mat_name = u.getClass().getSimpleName()326 if mat_name == "RowMatrix":327 return RowMatrix(u)328 elif mat_name == "IndexedRowMatrix":329 return IndexedRowMatrix(u)330 else:331 raise TypeError("Expected RowMatrix/IndexedRowMatrix got %s" % mat_name)332 @property333 @since('2.2.0')334 def s(self):335 """336 Returns a DenseVector with singular values in descending order.337 """338 return self.call("s")339 @property340 @since('2.2.0')341 def V(self):342 """343 Returns a DenseMatrix whose columns are the right singular344 vectors of the SingularValueDecomposition.345 """346 return self.call("V")347class IndexedRow(object):348 """349 Represents a row of an IndexedRowMatrix.350 Just a wrapper over a (long, vector) tuple.351 :param index: The index for the given row.352 :param vector: The row in the matrix at the given index.353 """354 def __init__(self, index, vector):355 self.index = long(index)356 self.vector = _convert_to_vector(vector)357 def __repr__(self):358 return "IndexedRow(%s, %s)" % (self.index, self.vector)359def _convert_to_indexed_row(row):360 if isinstance(row, IndexedRow):361 return row362 elif isinstance(row, tuple) and len(row) == 2:363 return IndexedRow(*row)364 else:365 raise TypeError("Cannot convert type %s into IndexedRow" % type(row))366class IndexedRowMatrix(DistributedMatrix):367 """368 Represents a row-oriented distributed Matrix with indexed rows.369 :param rows: An RDD of IndexedRows or (long, vector) tuples.370 :param numRows: Number of rows in the matrix. A non-positive371 value means unknown, at which point the number372 of rows will be determined by the max row373 index plus one.374 :param numCols: Number of columns in the matrix. A non-positive375 value means unknown, at which point the number376 of columns will be determined by the size of377 the first row.378 """379 def __init__(self, rows, numRows=0, numCols=0):380 """381 Note: This docstring is not shown publicly.382 Create a wrapper over a Java IndexedRowMatrix.383 Publicly, we require that `rows` be an RDD. However, for384 internal usage, `rows` can also be a Java IndexedRowMatrix385 object, in which case we can wrap it directly. This386 assists in clean matrix conversions.387 >>> rows = sc.parallelize([IndexedRow(0, [1, 2, 3]),388 ... IndexedRow(1, [4, 5, 6])])389 >>> mat = IndexedRowMatrix(rows)390 >>> mat_diff = IndexedRowMatrix(rows)391 >>> (mat_diff._java_matrix_wrapper._java_model ==392 ... mat._java_matrix_wrapper._java_model)393 False394 >>> mat_same = IndexedRowMatrix(mat._java_matrix_wrapper._java_model)395 >>> (mat_same._java_matrix_wrapper._java_model ==396 ... mat._java_matrix_wrapper._java_model)397 True398 """399 if isinstance(rows, RDD):400 rows = rows.map(_convert_to_indexed_row)401 # We use DataFrames for serialization of IndexedRows from402 # Python, so first convert the RDD to a DataFrame on this403 # side. This will convert each IndexedRow to a Row404 # containing the 'index' and 'vector' values, which can405 # both be easily serialized. We will convert back to406 # IndexedRows on the Scala side.407 java_matrix = callMLlibFunc("createIndexedRowMatrix", rows.toDF(),408 long(numRows), int(numCols))409 elif (isinstance(rows, JavaObject)410 and rows.getClass().getSimpleName() == "IndexedRowMatrix"):411 java_matrix = rows412 else:413 raise TypeError("rows should be an RDD of IndexedRows or (long, vector) tuples, "414 "got %s" % type(rows))415 self._java_matrix_wrapper = JavaModelWrapper(java_matrix)416 @property417 def rows(self):418 """419 Rows of the IndexedRowMatrix stored as an RDD of IndexedRows.420 >>> mat = IndexedRowMatrix(sc.parallelize([IndexedRow(0, [1, 2, 3]),421 ... IndexedRow(1, [4, 5, 6])]))422 >>> rows = mat.rows423 >>> rows.first()424 IndexedRow(0, [1.0,2.0,3.0])425 """426 # We use DataFrames for serialization of IndexedRows from427 # Java, so we first convert the RDD of rows to a DataFrame428 # on the Scala/Java side. Then we map each Row in the429 # DataFrame back to an IndexedRow on this side.430 rows_df = callMLlibFunc("getIndexedRows", self._java_matrix_wrapper._java_model)431 rows = rows_df.rdd.map(lambda row: IndexedRow(row[0], row[1]))...
jquery.gridnav.js
Source:jquery.gridnav.js
1(function($) {2 jQuery.fn.reverse = Array.prototype.reverse;3 4 var 5 // auxiliar functions6 aux = {7 setup : function( $wrapper, $items, opts ) {8 9 // set the wrappers position to relative10 $wrapper.css('position', 'relative');11 12 // save the items position13 aux.saveInitialPosition( $items );14 15 // set the items to absolute and assign top & left16 $items.each(function(i) {17 var $item = $(this);18 $item.css({19 position : 'absolute',20 left : $item.data('left'),21 top : $item.data('top')22 });23 });24 25 // check how many items we have per row26 var rowCount = Math.floor( $wrapper.width() / $items.width() ),27 // number of items to show is rowCount * n rows28 shown = rowCount * opts.rows,29 // total number of rows30 totalRows = Math.ceil( $items.length / rowCount );31 32 // save this values for later33 var config = {};34 config.currentRow = 1;35 config.totalRows = totalRows;36 config.rowCount = rowCount;37 config.shownItems = shown;38 $wrapper.data('config', config);39 40 // show n rowns41 $wrapper.children(':gt(' + (shown - 1) + ')').hide();42 43 // assign row classes to the items44 $items.each(function(i) {45 var $item = $(this),46 row = Math.ceil( (i + 1) / rowCount );47 48 $item.addClass('tj_row_' + row); 49 });50 51 nav.setup( $wrapper, $items, opts );52 53 },54 saveInitialPosition : function( $items ) {55 $items.each(function(i) {56 var $item = $(this);57 58 $item.data({59 left : $item.position().left + 'px',60 top : $item.position().top + 'px'61 }); 62 });63 }64 },65 // navigation types66 nav = {67 setup : function( $wrapper, $items, opts ) {68 nav[opts.type.mode].setup( $wrapper, $items, opts );69 },70 def : {71 setup : function( $wrapper, $items, opts ) {72 var config = $wrapper.data('config');73 $items.each(function(i) {74 var $item = $(this),75 row = Math.ceil( (i + 1) / config.rowCount ),76 t,77 f = row % opts.rows;78 79 if( f === 1 ) {80 t = '0px'; 81 } else if( f === 0 ) {82 t = (opts.rows - 1) * $items.height() + 'px'; 83 } else {84 t = (f - 1) * $items.height() + 'px';85 }86 87 $item.css({ top : t });88 }); 89 },90 pagination : function( $wrapper, dir, opts ) {91 var config = $wrapper.data('config');92 if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 93 ( dir === -1 && config.currentRow - opts.rows <= 0 )94 ) {95 $wrapper.data( 'anim', false );96 return false;97 }98 99 var currentRows = '', nextRows = '';100 101 for( var i = 0; i < opts.rows; ++i ) {102 currentRows += '.tj_row_' + (config.currentRow + i) + ',';103 104 (dir === 1)105 ? nextRows += '.tj_row_' + (config.currentRow + opts.rows + i) + ','106 : nextRows += '.tj_row_' + (config.currentRow - 1 - i) + ',';107 }108 109 $wrapper.children(currentRows).hide();110 $wrapper.children(nextRows).show();111 112 (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;113 114 $wrapper.data( 'anim', false );115 $wrapper.data('config', config);116 }117 },118 fade : {119 setup : function( $wrapper, $items, opts ) {120 // same like def mode121 nav['def'].setup( $wrapper, $items, opts );122 },123 pagination : function( $wrapper, dir, opts ) {124 var config = $wrapper.data('config');125 if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) ||126 ( dir === -1 && config.currentRow - opts.rows <= 0 )127 ) {128 $wrapper.data( 'anim', false );129 return false;130 }131 132 var currentRows = '', nextRows = '';133 134 for( var i = 0; i < opts.rows; ++i ) {135 currentRows += '.tj_row_' + (config.currentRow + i) + ',';136 137 (dir === 1)138 ? nextRows += '.tj_row_' + (config.currentRow + opts.rows + i) + ','139 : nextRows += '.tj_row_' + (config.currentRow - 1 - i) + ',';140 }141 142 $wrapper.children(currentRows).fadeOut( opts.type.speed, opts.type.easing );143 144 var $nextRowElements= $wrapper.children(nextRows),145 totalNextRows = $nextRowElements.length,146 cnt = 0;147 148 $nextRowElements.fadeIn( opts.type.speed, opts.type.easing, function() {149 ++cnt;150 if( cnt === totalNextRows ) {151 $wrapper.data( 'anim', false );152 } 153 });154 155 (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;156 $wrapper.data('config', config);157 }158 },159 seqfade : {160 setup : function( $wrapper, $items, opts ) {161 // same like def mode162 nav['def'].setup( $wrapper, $items, opts );163 },164 pagination : function( $wrapper, dir, opts ) {165 var config = $wrapper.data('config');166 if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 167 ( dir === -1 && config.currentRow - opts.rows <= 0 )168 ) {169 $wrapper.data( 'anim', false );170 return false;171 }172 173 var currentRows = '', nextRows = '';174 for( var i = 0; i < opts.rows; ++i ) {175 currentRows += '.tj_row_' + (config.currentRow + i) + ',';176 177 (dir === 1)178 ? nextRows += '.tj_row_' + (config.currentRow + opts.rows + i) + ','179 : nextRows += '.tj_row_' + (config.currentRow - 1 - i) + ',';180 }181 182 var seq_t = opts.type.factor;183 184 var $currentRowElements;185 ( dir === 1 )186 ? $currentRowElements = $wrapper.children(currentRows)187 : $currentRowElements = $wrapper.children(currentRows).reverse();188 189 $currentRowElements.each(function(i) {190 var $el = $(this);191 setTimeout(function() {192 $el.fadeOut( opts.type.speed, opts.type.easing )193 }, seq_t + i * seq_t);194 });195 196 var $nextRowElements;197 ( dir === 1 )198 ? $nextRowElements = $wrapper.children(nextRows)199 : $nextRowElements = $wrapper.children(nextRows).reverse();200 201 var total_elems = $nextRowElements.length,202 cnt = 0;203 204 $nextRowElements.each(function(i) {205 var $el = $(this);206 setTimeout(function() {207 $el.fadeIn( opts.type.speed, opts.type.easing, function() {208 ++cnt;209 if( cnt === total_elems ) { 210 $wrapper.data( 'anim', false );211 } 212 })213 }, (seq_t * 2) + i * seq_t);214 });215 216 (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;217 $wrapper.data('config', config);218 }219 },220 updown : {221 setup : function( $wrapper, $items, opts ) {222 var config = $wrapper.data('config');223 $wrapper.children(':gt(' + (config.shownItems - 1) + ')').css('opacity', 0);224 225 $items.each(function(i) {226 var $item = $(this),227 row = Math.ceil( (i + 1) / config.rowCount ),228 t = $item.position().top,229 f = row % opts.rows;230 231 if( row > opts.rows ) {232 t = (opts.rows * $items.height()); 233 }234 235 $item.css({ top : t + 'px'});236 });237 },238 pagination : function( $wrapper, dir, opts ) {239 var config = $wrapper.data('config');240 if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 241 ( dir === -1 && config.currentRow - 1 <= 0 )242 ) {243 $wrapper.data( 'anim', false );244 return false;245 }246 247 var movingRows = '';248 249 for( var i = 0; i <= opts.rows; ++i ) {250 ( dir === 1 )251 ? movingRows += '.tj_row_' + (config.currentRow + i) + ','252 : movingRows += '.tj_row_' + (config.currentRow + (i - 1)) + ',';253 }254 255 var $elements;256 257 ( dir === 1 )258 ? $elements = $wrapper.children(movingRows)259 : $elements = $wrapper.children(movingRows).reverse();260 261 var total_elems = $elements.length,262 cnt = 0;263 264 $elements.each(function(i) {265 var $el = $(this),266 row = $el.attr('class'),267 animParam = {},268 269 currentRow = config.currentRow;270 271 // if first row fade out272 // if last row fade in273 // for all the rows move them up / down274 if( dir === 1 ) {275 if( row === 'tj_row_' + (currentRow) ) {276 animParam.opacity = 0;277 }278 else if( row === 'tj_row_' + (currentRow + opts.rows) ) {279 animParam.opacity = 1;280 }281 }282 else {283 if( row === 'tj_row_' + (currentRow - 1) ) {284 animParam.opacity = 1;285 }286 else if( row === 'tj_row_' + (currentRow + opts.rows - 1) ) {287 animParam.opacity = 0;288 }289 }290 291 $el.show();292 293 (dir === 1)294 ? animParam.top = $el.position().top - $el.height() + 'px'295 : animParam.top = $el.position().top + $el.height() + 'px'296 297 $el.stop().animate(animParam, opts.type.speed, opts.type.easing, function() {298 if( parseInt( animParam.top ) < 0 || parseInt( animParam.top ) > $el.height() * (opts.rows - 1) )299 $el.hide();300 301 ++cnt;302 if( cnt === total_elems ) {303 $wrapper.data( 'anim', false );304 } 305 });306 });307 308 (dir === 1) ? config.currentRow += 1 : config.currentRow -= 1;309 $wrapper.data('config', config);310 }311 },312 sequpdown : {313 setup : function( $wrapper, $items, opts ) {314 // same like updown mode315 nav['updown'].setup( $wrapper, $items, opts );316 },317 pagination : function( $wrapper, dir, opts ) {318 var config = $wrapper.data('config');319 if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 320 ( dir === -1 && config.currentRow - 1 <= 0 ) 321 ) {322 $wrapper.data( 'anim', false );323 return false;324 }325 326 var movingRows = '';327 328 for( var i = 0; i <= opts.rows; ++i ) {329 ( dir === 1 )330 ? movingRows += '.tj_row_' + (config.currentRow + i) + ','331 : movingRows += '.tj_row_' + (config.currentRow + (i - 1)) + ',';332 }333 334 var seq_t = opts.type.factor,335 $elements;336 337 var dircond = 1;338 if( opts.type.reverse ) dircond = -1;339 ( dir === dircond )340 ? $elements = $wrapper.children(movingRows)341 : $elements = $wrapper.children(movingRows).reverse();342 343 var total_elems = $elements.length,344 cnt = 0;345 346 $elements.each(function(i) {347 var $el = $(this),348 row = $el.attr('class'),349 animParam = {},350 351 currentRow = config.currentRow;352 353 setTimeout(function() {354 // if first row fade out355 // if last row fade in356 // for all the rows move them up / down357 if( dir === 1 ) {358 if( row === 'tj_row_' + (currentRow) ) {359 animParam.opacity = 0;360 }361 else if( row === 'tj_row_' + (currentRow + opts.rows) ) {362 animParam.opacity = 1;363 }364 }365 else {366 if( row === 'tj_row_' + (currentRow - 1) ) {367 animParam.opacity = 1;368 }369 else if( row === 'tj_row_' + (currentRow + opts.rows - 1) ) {370 animParam.opacity = 0;371 }372 }373 374 $el.show();375 376 (dir === 1)377 ? animParam.top = $el.position().top - $el.height() + 'px'378 : animParam.top = $el.position().top + $el.height() + 'px'379 380 $el.stop().animate(animParam, opts.type.speed, opts.type.easing, function() {381 if( parseInt( animParam.top ) < 0 || parseInt( animParam.top ) > $el.height() * (opts.rows - 1) )382 $el.hide();383 384 ++cnt;385 if( cnt === total_elems ) { 386 $wrapper.data( 'anim', false );387 } 388 }); 389 }, seq_t + i * seq_t);390 });391 392 (dir === 1) ? config.currentRow += 1 : config.currentRow -= 1;393 $wrapper.data('config', config);394 }395 },396 showhide : {397 setup : function( $wrapper, $items, opts ) {398 var config = $wrapper.data('config');399 $items.each(function(i) {400 var $item = $(this),401 row = Math.ceil( (i + 1) / config.rowCount ),402 t,403 f = row % opts.rows;404 405 if( f === 1 ) {406 t = '0px'; 407 } else if( f === 0 ) {408 t = (opts.rows - 1) * $items.height() + 'px'; 409 } else {410 t = (f - 1) * $items.height() + 'px';411 }412 413 $item.css({ top : t });414 }); 415 },416 pagination : function( $wrapper, dir, opts ) {417 var config = $wrapper.data('config');418 if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 419 ( dir === -1 && config.currentRow - opts.rows <= 0 )420 ) {421 $wrapper.data( 'anim', false );422 return false;423 }424 425 var currentRows = '', nextRows = '';426 427 for( var i = 0; i < opts.rows; ++i ) {428 currentRows += '.tj_row_' + (config.currentRow + i) + ',';429 430 (dir === 1)431 ? nextRows += '.tj_row_' + (config.currentRow + opts.rows + i) + ','432 : nextRows += '.tj_row_' + (config.currentRow - 1 - i) + ',';433 }434 435 $wrapper.children(currentRows).hide( opts.type.speed, opts.type.easing );436 437 var $nextRowElements= $wrapper.children(nextRows),438 totalNextRows = $nextRowElements.length,439 cnt = 0;440 441 $nextRowElements.show( opts.type.speed, opts.type.easing, function() {442 ++cnt;443 if( cnt === totalNextRows ) {444 $wrapper.data( 'anim', false );445 } 446 });447 448 (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;449 $wrapper.data('config', config);450 }451 },452 disperse : {453 setup : function( $wrapper, $items, opts ) {454 var config = $wrapper.data('config');455 $items.each(function(i) {456 var $item = $(this),457 row = Math.ceil( (i + 1) / config.rowCount ),458 t,459 f = row % opts.rows;460 461 if( f === 1 ) {462 t = '0px'; 463 } else if( f === 0 ) {464 t = (opts.rows - 1) * $items.height() + 'px'; 465 } else {466 t = (f - 1) * $items.height() + 'px';467 }468 469 $item.css({ top : t }).data('top', t);470 });471 },472 pagination : function( $wrapper, dir, opts ) {473 var config = $wrapper.data('config');474 if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 475 ( dir === -1 && config.currentRow - opts.rows <= 0 )476 ) {477 $wrapper.data( 'anim', false );478 return false;479 }480 481 var currentRows = '', nextRows = '';482 for( var i = 0; i < opts.rows; ++i ) {483 currentRows += '.tj_row_' + (config.currentRow + i) + ',';484 485 (dir === 1)486 ? nextRows += '.tj_row_' + (config.currentRow + opts.rows + i) + ','487 : nextRows += '.tj_row_' + (config.currentRow - 1 - i) + ',';488 }489 490 $wrapper.children(currentRows).each(function(i) {491 var $el = $(this);492 $el.stop().animate({493 left : $el.position().left + Math.floor( Math.random() * 101 ) - 50 + 'px',494 top : $el.position().top + Math.floor( Math.random() * 101 ) - 50 + 'px',495 opacity : 0496 }, opts.type.speed, opts.type.easing, function() {497 $el.css({498 left : $el.data('left'),499 top : $el.data('top')500 }).hide();501 });502 });503 504 var $nextRowElements = $wrapper.children(nextRows);505 total_elems = $nextRowElements.length,506 cnt = 0;507 508 $nextRowElements.each(function(i) {509 var $el = $(this);510 511 $el.css({512 left : parseInt($el.data('left')) + Math.floor( Math.random() * 301 ) - 150 + 'px', 513 top : parseInt($el.data('top')) + Math.floor( Math.random() * 301 ) - 150 + 'px',514 opacity : 0515 })516 .show()517 .animate({518 left : $el.data('left'),519 top : $el.data('top'),520 opacity : 1521 }, opts.type.speed, opts.type.easing, function() {522 ++cnt;523 if( cnt === total_elems ) { 524 $wrapper.data( 'anim', false );525 }526 });527 });528 529 (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;530 $wrapper.data('config', config);531 }532 },533 rows : {534 setup : function( $wrapper, $items, opts ) {535 // same like def mode536 nav['def'].setup( $wrapper, $items, opts );537 },538 pagination : function( $wrapper, dir, opts ) {539 var config = $wrapper.data('config');540 if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 541 ( dir === -1 && config.currentRow - opts.rows <= 0 )542 ) {543 $wrapper.data( 'anim', false );544 return false;545 }546 547 var currentRows = '', nextRows = '';548 for( var i = 0; i < opts.rows; ++i ) {549 currentRows += '.tj_row_' + (config.currentRow + i) + ',';550 551 (dir === 1)552 ? nextRows += '.tj_row_' + (config.currentRow + opts.rows + i) + ','553 : nextRows += '.tj_row_' + (config.currentRow - 1 - i) + ',';554 }555 556 $wrapper.children(currentRows).each(function(i) {557 var $el = $(this),558 rownmb = $el.attr('class').match(/tj_row_(\d+)/)[1],559 diff;560 561 if( rownmb%2 === 0 ) {562 diff = opts.type.factor;563 }564 else {565 diff = -opts.type.factor;566 }567 568 $el.stop().animate({569 left : $el.position().left + diff + 'px',570 opacity : 0571 }, opts.type.speed, opts.type.easing, function() {572 $el.css({573 left : $el.data('left')574 }).hide();575 });576 });577 578 var $nextRowElements = $wrapper.children(nextRows);579 total_elems = $nextRowElements.length,580 cnt = 0;581 582 $nextRowElements.each(function(i) {583 var $el = $(this),584 rownmb = $el.attr('class').match(/tj_row_(\d+)/)[1],585 diff;586 587 if( rownmb%2 === 0 ) {588 diff = opts.type.factor;589 }590 else {591 diff = -opts.type.factor;592 }593 594 $el.css({595 left : parseInt($el.data('left')) + diff + 'px',596 opacity : 0597 })598 .show()599 .animate({600 left : $el.data('left'),601 opacity : 1602 }, opts.type.speed, opts.type.easing, function() {603 ++cnt;604 if( cnt === total_elems ) { 605 $wrapper.data( 'anim', false );606 }607 });608 });609 610 (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;611 $wrapper.data('config', config);612 }613 }614 },615 methods = {616 init : function( options ) {617 618 if( this.length ) {619 620 var settings = {621 rows : 2,622 navL : '#tj_prev',623 navR : '#tj_next',624 type : {625 mode : 'def', // use def | fade | seqfade | updown | sequpdown | showhide | disperse | rows626 speed : 500, // for fade, seqfade, updown, sequpdown, showhide, disperse, rows627 easing : 'jswing', // for fade, seqfade, updown, sequpdown, showhide, disperse, rows 628 factor : 50, // for seqfade, sequpdown, rows629 reverse : false // for sequpdown630 }631 };632 633 return this.each(function() {634 635 // if options exist, lets merge them with our default settings636 if ( options ) {637 $.extend( settings, options );638 }639 640 var $el = $(this).css( 'visibility', 'hidden' ),641 // the ul642 $wrapper = $el.find('ul.tj_gallery'),643 // the items644 $thumbs = $wrapper.children('li'),645 total = $thumbs.length,646 // the navigation elements647 $p_nav = $(settings.navL),648 $n_nav = $(settings.navR);649 650 // save current row for later (first visible row)651 //config.currentRow = 1;652 653 // flag to control animation progress654 $wrapper.data( 'anim', false );655 656 // preload thumbs657 var loaded = 0;658 $thumbs.find('img').each( function(i) {659 var $img = $(this);660 $('<img/>').load( function() {661 ++loaded;662 if( loaded === total ) {663 664 // setup665 aux.setup( $wrapper, $thumbs, settings );666 $el.css( 'visibility', 'visible' );667 668 // navigation events669 if( $p_nav.length ) {670 $p_nav.bind('click.gridnav', function( e ) {671 if( $wrapper.data( 'anim' ) ) return false;672 $wrapper.data( 'anim', true );673 nav[settings.type.mode].pagination( $wrapper, -1, settings );674 return false;675 });676 }677 if( $n_nav.length ) {678 $n_nav.bind('click.gridnav', function( e ) {679 if( $wrapper.data( 'anim' ) ) return false;680 $wrapper.data( 'anim', true );681 nav[settings.type.mode].pagination( $wrapper, 1, settings );682 return false;683 });684 }685 /*686 adds events to the mouse687 */688 $el.bind('mousewheel.gridnav', function(e, delta) {689 if(delta > 0) {690 if( $wrapper.data( 'anim' ) ) return false;691 $wrapper.data( 'anim', true );692 nav[settings.type.mode].pagination( $wrapper, -1, settings );693 } 694 else {695 if( $wrapper.data( 'anim' ) ) return false;696 $wrapper.data( 'anim', true );697 nav[settings.type.mode].pagination( $wrapper, 1, settings );698 } 699 return false;700 });701 702 }703 }).attr( 'src', $img.attr('src') );704 });705 706 });707 }708 }709 };710 711 $.fn.gridnav = function(method) {712 if ( methods[method] ) {713 return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));714 } else if ( typeof method === 'object' || ! method ) {715 return methods.init.apply( this, arguments );716 } else {717 $.error( 'Method ' + method + ' does not exist on jQuery.gridnav' );718 }719 };...
checkpoint_ops_test.py
Source:checkpoint_ops_test.py
...172 [33, init_val, init_val, init_val, 1, init_val], [3, 2])173 with self.cached_session():174 self.assertAllClose(expected_remapped_matrix,175 self.evaluate(remapped_matrix))176 def test_load_and_remap_all_missing_rows(self):177 """Tests when all the rows are missing and need to be initialized."""178 num_rows = 7179 initializing_values = [42] * num_rows * self.old_num_cols180 remapped_matrix = gen_checkpoint_ops.load_and_remap_matrix(181 ckpt_path=[self.bundle_file],182 old_tensor_name=self.old_tensor_name,183 row_remapping=[-1] * num_rows,184 col_remapping=[],185 initializing_values=initializing_values,186 num_rows=num_rows,187 num_cols=self.old_num_cols)188 with self.cached_session():189 self.assertAllClose(190 np.reshape(initializing_values, (num_rows, self.old_num_cols)),191 self.evaluate(remapped_matrix))192 def test_load_and_remap_all_missing_rows_and_cols(self):193 """Tests when all the rows & cols are missing and need to be initialized."""194 num_rows = 7195 num_cols = 4196 initializing_values = [42] * num_rows * num_cols197 remapped_matrix = gen_checkpoint_ops.load_and_remap_matrix(198 ckpt_path=[self.bundle_file],199 old_tensor_name=self.old_tensor_name,200 row_remapping=[-1] * num_rows,201 col_remapping=[-1] * num_cols,202 initializing_values=initializing_values,203 num_rows=num_rows,204 num_cols=num_cols)205 with self.cached_session():206 self.assertAllClose(207 np.reshape(initializing_values, (num_rows, num_cols)),208 self.evaluate(remapped_matrix))209 @test_util.run_deprecated_v1210 def test_load_and_remap_invalid_remapping(self):211 """Tests that errors are raised when an ID maps to multiple new IDs.212 (This should usually not happen when using public APIs).213 """214 invalid_remapping = [1, 0, 0, 0, 1, 2]215 # Invalid row remapping.216 remapped_matrix = gen_checkpoint_ops.load_and_remap_matrix(217 ckpt_path=[self.bundle_file],218 old_tensor_name=self.old_tensor_name,219 row_remapping=invalid_remapping,220 col_remapping=[],221 initializing_values=[],222 num_rows=len(invalid_remapping),223 num_cols=self.old_num_cols)224 with self.cached_session(), self.assertRaises(errors.UnimplementedError):225 self.evaluate(remapped_matrix)226 # Invalid column remapping.227 remapped_matrix = gen_checkpoint_ops.load_and_remap_matrix(228 ckpt_path=[self.bundle_file],229 old_tensor_name=self.old_tensor_name,230 row_remapping=list(range(self.old_num_rows)),231 col_remapping=invalid_remapping,232 initializing_values=[],233 num_rows=self.old_num_rows,234 num_cols=len(invalid_remapping))235 with self.cached_session(), self.assertRaises(errors.UnimplementedError):236 self.evaluate(remapped_matrix)237 @test_util.run_deprecated_v1238 def test_load_and_remap_incorrect_initializing_values(self):239 """Tests that errors are raised with incorrect number of init values."""240 remapped_matrix = gen_checkpoint_ops.load_and_remap_matrix(241 ckpt_path=[self.bundle_file],242 old_tensor_name=self.old_tensor_name,243 row_remapping=[2, -1, 0],244 col_remapping=[1, -1],245 # Too few initializing values - there should be 4. For some reason,246 # initializing_values must contain no element (instead of 3 or fewer) to247 # ensure that a seg fault would reliably occur if the check raising the248 # InvalidArgumentError were not present.249 initializing_values=[],250 num_rows=3,251 num_cols=2)252 with self.cached_session(), self.assertRaises(errors.InvalidArgumentError):253 self.evaluate(remapped_matrix)254 remapped_matrix = gen_checkpoint_ops.load_and_remap_matrix(255 ckpt_path=[self.bundle_file],256 old_tensor_name=self.old_tensor_name,257 row_remapping=[2, -1, 0],258 col_remapping=[1, -1],259 # Too many initializing values - there should be 4.260 initializing_values=[0] * 5,261 num_rows=3,262 num_cols=2)263 with self.cached_session(), self.assertRaises(errors.InvalidArgumentError):264 self.evaluate(remapped_matrix)265class LoadAndRemapMatrixWithMaxRowsTest(test.TestCase):266 """Tests for the load_and_remap_matrix() op.267 (Specifically focused on the max_rows_in_memory arg and its effects on268 TensorBundle's BundleReader and TensorSlice logic).269 """270 def _test_loading_variable_with_max_rows(self, np_value, partitioner,271 max_rows_in_memory):272 """Helper function for various tests using max_rows_in_memory."""273 ops.reset_default_graph()274 old_tensor_name = 'matrix_to_load_and_remap'275 matrix = variable_scope.get_variable(276 old_tensor_name,277 dtype=dtypes.float32,278 initializer=constant_op.constant(np_value, dtype=dtypes.float32),279 partitioner=partitioner)280 with self.cached_session() as sess:281 ckpt_path = os.path.join(test.get_temp_dir(), 'temp_ckpt')282 save = saver.Saver([matrix])283 self.evaluate(variables.global_variables_initializer())284 save.save(sess, ckpt_path)285 num_rows, num_cols = np_value.shape286 # Tests loading the entire tensor (except reversed).287 remapped_matrix = gen_checkpoint_ops.load_and_remap_matrix(288 ckpt_path=ckpt_path,289 old_tensor_name=old_tensor_name,290 # Simply reverses the rows of the matrix.291 row_remapping=list(range(num_rows - 1, -1, -1)),292 col_remapping=[],293 initializing_values=[],294 num_rows=num_rows,295 num_cols=num_cols,296 max_rows_in_memory=max_rows_in_memory)297 self.assertAllClose(np_value[::-1], self.evaluate(remapped_matrix))298 # Tests loading the tensor (except for the first and last rows), with299 # uninitialized values. Requires num_rows to be at least 3 since we're300 # skipping the first and last rows.301 self.assertGreater(num_rows, 2)302 prefix_rows = 2303 suffix_rows = 3304 remapped_matrix = gen_checkpoint_ops.load_and_remap_matrix(305 ckpt_path=ckpt_path,306 old_tensor_name=old_tensor_name,307 # Reverses the rows of the matrix, then prepends and appends308 # uninitialized rows.309 row_remapping=([-1] * prefix_rows + list(range(1, num_rows - 1)) +310 [-1] * suffix_rows),311 col_remapping=[],312 initializing_values=[42] * (prefix_rows + suffix_rows) * num_cols,313 num_rows=num_rows - 2 + prefix_rows + suffix_rows,314 num_cols=num_cols,315 max_rows_in_memory=max_rows_in_memory)316 self.assertAllClose(317 np.vstack([318 np.tile(42, [prefix_rows, num_cols]), np_value[1:-1],319 np.tile(42, [suffix_rows, num_cols])320 ]), self.evaluate(remapped_matrix))321 # Tests when everything is taken from initializing_values.322 new_rows = 7323 initializing_values = [42] * new_rows * num_cols324 remapped_matrix = gen_checkpoint_ops.load_and_remap_matrix(325 ckpt_path=ckpt_path,326 old_tensor_name=old_tensor_name,327 # Nothing is loaded from the old tensor.328 row_remapping=[-1] * new_rows,329 col_remapping=[],330 initializing_values=initializing_values,331 num_rows=new_rows,332 num_cols=num_cols,333 max_rows_in_memory=max_rows_in_memory)334 self.assertAllClose(335 np.reshape(initializing_values, (new_rows, num_cols)),336 self.evaluate(remapped_matrix))337 @test_util.run_deprecated_v1338 def test_loading_rows_divisible_by_max_rows(self):339 """Tests loading normal var when rows are evenly divisible by max_rows."""340 self._test_loading_variable_with_max_rows(341 np_value=np.reshape(list(range(0, 36)), (9, 4)),342 partitioner=None,343 # 9 is evenly divisible by 3.344 max_rows_in_memory=3)345 @test_util.run_deprecated_v1346 def test_loading_rows_not_divisible_by_max_rows(self):347 """Tests loading normal var when rows aren't divisible by max_rows."""348 self._test_loading_variable_with_max_rows(349 np_value=np.reshape(list(range(0, 36)), (9, 4)),350 partitioner=None,351 # 9 is not evenly divisible by 4.352 max_rows_in_memory=4)353 @test_util.run_deprecated_v1354 def test_loading_rows_less_than_max_rows(self):355 """Tests loading normal var as a single slice.356 (When the specified max_rows_in_memory is larger than the number of rows)357 """358 self._test_loading_variable_with_max_rows(359 np_value=np.reshape(list(range(0, 36)), (9, 4)),360 partitioner=None,361 # 10 > 9.362 max_rows_in_memory=10)363 @test_util.run_deprecated_v1364 def test_loading_no_max_rows(self):365 """Tests loading normal var as a single slice with no valid max_rows."""366 self._test_loading_variable_with_max_rows(367 np_value=np.reshape(list(range(0, 18)), (6, 3)),368 partitioner=None,369 max_rows_in_memory=-1)370 @test_util.run_deprecated_v1371 def test_loading_partitions_equals_max_rows(self):372 """Tests loading partitioned var sliced on partition boundary."""373 self._test_loading_variable_with_max_rows(374 np_value=np.reshape(list(range(0, 36)), (9, 4)),375 partitioner=partitioned_variables.fixed_size_partitioner(3),376 # With a tensor of shape [9, 3] and 3 partitions, each partition has377 # exactly 3 rows.378 max_rows_in_memory=3)379 @test_util.run_deprecated_v1380 def test_loading_partitions_greater_than_max_rows(self):381 """Tests loading partitioned var with more slices than partitions."""382 self._test_loading_variable_with_max_rows(383 np_value=np.reshape(list(range(0, 36)), (9, 4)),384 partitioner=partitioned_variables.fixed_size_partitioner(3),385 # Even though each partition has 3 rows, we'll only load the tensor one386 # row at a time.387 max_rows_in_memory=1)388 @test_util.run_deprecated_v1389 def test_loading_partitions_less_than_max_rows(self):390 """Tests loading partitioned var as a single slice.391 (When the specified max_rows_in_memory is larger than the number of rows)392 """393 self._test_loading_variable_with_max_rows(394 np_value=np.reshape(list(range(0, 36)), (9, 4)),395 partitioner=partitioned_variables.fixed_size_partitioner(3),396 max_rows_in_memory=10)397 @test_util.run_deprecated_v1398 def test_loading_partitions_no_max_rows(self):399 """Tests loading partitioned var as single slice with no valid max_rows."""400 self._test_loading_variable_with_max_rows(401 np_value=np.reshape(list(range(0, 36)), (9, 4)),402 partitioner=partitioned_variables.fixed_size_partitioner(3),403 max_rows_in_memory=-1)404if __name__ == '__main__':...
table.py
Source:table.py
1"""2"""3from const import *4import container5class Table(container.Container):6 """A table style container.7 8 <p>If you know HTML, this should all work roughly how you would expect. If you are not9 familiar with HTML, please read <a href="http://www.w3.org/TR/REC-html40/struct/tables.html">Tables in HTML Documents</a>. Pay attention to TABLE, TR, TD related parts of the document.</p>10 11 <pre>Table()</pre>12 13 <strong>Example</strong>14 <code>15 t = gui.Table()16 17 t.tr()18 t.td(gui.Label("First Name"), align=-1)19 t.td(gui.Input())20 t.tr()21 t.td(gui.Label("Last Name"), align=-1)22 t.td(gui.Input())23 </code>24 25 """26 27 28 def __init__(self, **params):29 params.setdefault('cls','table')30 container.Container.__init__(self, **params)31 self._rows = []32 self._curRow = 033 self._trok = False34 35 def getRows(self):36 return len(self._rows)37 38 def getColumns(self):39 if self._rows:40 return len(self._rows[0])41 else:42 return 043 44 def remove_row(self, n): #NOTE: won't work in all cases.45 if n >= self.getRows():46 print "Trying to remove a nonexistant row:", n, "there are only", self.getRows(), "rows"47 return48 49 for cell in self._rows[n]:50 if isinstance(cell, dict) and cell["widget"] in self.widgets:51 #print 'removing widget'52 self.widgets.remove(cell["widget"])53 del self._rows[n]54 #print "got here"55 56 for w in self.widgets:57 if w.style.row > n: w.style.row -= 158 59 if self._curRow >= n:60 self._curRow -= 161 62 #self.rect.w, self.rect.h = self.resize()63 #self.repaint()64 65 self.chsize()66 67 def clear(self):68 self._rows = []69 self._curRow = 070 self._trok = False71 self.widgets = []72 73 self.chsize()74 75 #print 'clear',self,self._rows76 77 def _addRow(self):78 self._rows.append([None for x in xrange(self.getColumns())])79 80 def tr(self):81 """Start on the next row."""82 if not self._trok:83 self._trok = True84 return 85 self._curRow += 186 if self.getRows() <= self._curRow:87 self._addRow()88 89 def _addColumn(self):90 if not self._rows:91 self._addRow()92 for row in self._rows:93 row.append(None)94 95 def _setCell(self, w, col, row, colspan=1, rowspan=1):96 #make room for the widget by adding columns and rows97 while self.getColumns() < col + colspan:98 self._addColumn()99 while self.getRows() < row + rowspan:100 self._addRow()101 102 #print w.__class__.__name__,col,row,colspan,rowspan103 104 #actual widget setting and modification stuff105 w.container = self106 w.style.row = row #HACK - to work with gal's list107 w.style.col = col #HACK - to work with gal's list108 self._rows[row][col] = {"widget":w, "colspan":colspan, "rowspan":rowspan}109 self.widgets.append(self._rows[row][col]["widget"])110 111 #set the spanned columns112 #for acell in xrange(col + 1, col + colspan):113 # self._rows[row][acell] = True114 115 #set the spanned rows and the columns on them116 #for arow in xrange(row + 1, row + rowspan):117 # for acell in xrange(col, col + colspan): #incorrect?118 # self._rows[arow][acell] = True119 120 for arow in xrange(row, row + rowspan):121 for acell in xrange(col, col + colspan): #incorrect?122 if row != arow or col != acell:123 self._rows[arow][acell] = True124 125 126 def td(self, w, col=None, row=None, colspan=1, rowspan=1, **params):127 """Add a widget to a table after wrapping it in a TD container.128 129 <pre>Table.td(w,col=None,row=None,colspan=1,rowspan=1,**params)</pre>130 131 <dl>132 <dt>w<dd>widget133 <dt>col<dd>column134 <dt>row<dd>row135 <dt>colspan<dd>colspan136 <dt>rowspan<dd>rowspan137 <dt>align<dd>horizontal alignment (-1,0,1)138 <dt>valign<dd>vertical alignment (-1,0,1)139 <dt>params<dd>other params for the TD container, style information, etc140 </dl>141 """142 143 Table.add(self,_Table_td(w, **params), col=col, row=row, colspan=colspan, rowspan=rowspan)144 145 def add(self, w, col=None, row=None, colspan=1, rowspan=1):146 """Add a widget directly into the table, without wrapping it in a TD container.147 148 <pre>Table.add(w,col=None,row=None,colspan=1,rowspan=1)</pre>149 150 <p>See Table.td for an explanation of the parameters.</p>151 """152 self._trok = True153 #if no row was specifically specified, set it to the current row154 if row is None:155 row = self._curRow156 #print row157 158 #if its going to be a new row, have it be on the first column159 if row >= self.getRows():160 col = 0161 162 #try to find an open cell for the widget163 if col is None:164 for cell in xrange(self.getColumns()):165 if col is None and not self._rows[row][cell]:166 col = cell167 break168 169 #otherwise put the widget in a new column170 if col is None:171 col = self.getColumns()172 173 self._setCell(w, col, row, colspan=colspan, rowspan=rowspan)174 175 self.chsize()176 return177 178 def remove(self,w):179 if hasattr(w,'_table_td'): w = w._table_td180 row,col = w.style.row,w.style.col181 cell = self._rows[row][col]182 colspan,rowspan = cell['colspan'],cell['rowspan']183 184 for arow in xrange(row , row + rowspan):185 for acell in xrange(col, col + colspan): #incorrect?186 self._rows[arow][acell] = False187 self.widgets.remove(w)188 self.chsize()189 190 191 192 def resize(self, width=None, height=None):193 #if 1 or self.getRows() == 82:194 #print ''195 #print 'resize',self.getRows(),self.getColumns(),width,height196 #import inspect197 #for obj,fname,line,fnc,code,n in inspect.stack()[9:20]:198 # print fname,line,':',fnc,code[0].strip()199 200 #resize the widgets to their smallest size201 for w in self.widgets:202 w.rect.w, w.rect.h = w.resize()203 204 #calculate row heights and column widths205 rowsizes = [0 for y in xrange(self.getRows())]206 columnsizes = [0 for x in xrange(self.getColumns())]207 for row in xrange(self.getRows()):208 for cell in xrange(self.getColumns()):209 if self._rows[row][cell] and self._rows[row][cell] is not True:210 if not self._rows[row][cell]["colspan"] > 1:211 columnsizes[cell] = max(columnsizes[cell], self._rows[row][cell]["widget"].rect.w)212 if not self._rows[row][cell]["rowspan"] > 1:213 rowsizes[row] = max(rowsizes[row], self._rows[row][cell]["widget"].rect.h)214 215 #distribute extra space if necessary for wide colspanning/rowspanning216 for row in xrange(self.getRows()):217 for cell in xrange(self.getColumns()):218 if self._rows[row][cell] and self._rows[row][cell] is not True:219 if self._rows[row][cell]["colspan"] > 1:220 columns = xrange(cell, cell + self._rows[row][cell]["colspan"])221 totalwidth = 0222 for acol in columns:223 totalwidth += columnsizes[acol]224 if totalwidth < self._rows[row][cell]["widget"].rect.w:225 for acol in columns:226 columnsizes[acol] += _table_div(self._rows[row][cell]["widget"].rect.w - totalwidth, self._rows[row][cell]["colspan"],acol)227 if self._rows[row][cell]["rowspan"] > 1:228 rows = xrange(row, row + self._rows[row][cell]["rowspan"])229 totalheight = 0230 for arow in rows:231 totalheight += rowsizes[arow]232 if totalheight < self._rows[row][cell]["widget"].rect.h:233 for arow in rows:234 rowsizes[arow] += _table_div(self._rows[row][cell]["widget"].rect.h - totalheight, self._rows[row][cell]["rowspan"],arow)235 236 #make everything fill out to self.style.width, self.style.heigh, not exact, but pretty close...237 w, h = sum(columnsizes), sum(rowsizes)238 if w > 0 and w < self.style.width and len(columnsizes):239 d = (self.style.width - w) 240 for n in xrange(0, len(columnsizes)):241 v = columnsizes[n]242 columnsizes[n] += v * d / w243 if h > 0 and h < self.style.height and len(rowsizes):244 d = (self.style.height - h) / len(rowsizes)245 for n in xrange(0, len(rowsizes)):246 v = rowsizes[n]247 rowsizes[n] += v * d / h248 249 #set the widget's position by calculating their row/column x/y offset250 cellpositions = [[[sum(columnsizes[0:cell]), sum(rowsizes[0:row])] for cell in xrange(self.getColumns())] for row in xrange(self.getRows())]251 for row in xrange(self.getRows()):252 for cell in xrange(self.getColumns()):253 if self._rows[row][cell] and self._rows[row][cell] is not True:254 x, y = cellpositions[row][cell]255 w = sum(columnsizes[cell:cell+self._rows[row][cell]["colspan"]])256 h = sum(rowsizes[row:row+self._rows[row][cell]["rowspan"]])257 258 widget = self._rows[row][cell]["widget"]259 widget.rect.x = x260 widget.rect.y = y261 if 1 and (w,h) != (widget.rect.w,widget.rect.h):262# if h > 20:263# print widget.widget.__class__.__name__, (widget.rect.w,widget.rect.h),'=>',(w,h)264 widget.rect.w, widget.rect.h = widget.resize(w, h)265 266 #print self._rows[row][cell]["widget"].rect267 268 #print columnsizes269 #print sum(columnsizes)270 #size = sum(columnsizes), sum(rowsizes); print size271 272 #return the tables final size273 return sum(columnsizes),sum(rowsizes)274 275def _table_div(a,b,c):276 v,r = a/b, a%b277 if r != 0 and (c%b)<r: v += 1278 return v279class _Table_td(container.Container):280 def __init__(self,widget,**params):#hexpand=0,vexpand=0,281 container.Container.__init__(self,**params)282 self.widget = widget283 #self.hexpand=hexpand284 #self.vexpand=vexpand285 widget._table_td = self286 self.add(widget,0,0)287 288 def resize(self,width=None,height=None):289 w = self.widget290 291 #expansion code, but i didn't like the idea that much..292 #a bit obscure, fairly useless when a user can just293 #add a widget to a table instead of td it in.294 #ww,hh=None,None295 #if self.hexpand: ww = self.style.width296 #if self.vexpand: hh = self.style.height297 #if self.hexpand and width != None: ww = max(ww,width)298 #if self.vexpand and height != None: hh = max(hh,height)299 #w.rect.w,w.rect.h = w.resize(ww,hh)300 301 #why bother, just do the lower mentioned item...302 w.rect.w,w.rect.h = w.resize()303 304 #this should not be needed, widgets should obey their sizing on their own.305 306# if (self.style.width!=0 and w.rect.w > self.style.width) or (self.style.height!=0 and w.rect.h > self.style.height):307# ww,hh = None,None308# if self.style.width: ww = self.style.width309# if self.style.height: hh = self.style.height310# w.rect.w,w.rect.h = w.resize(ww,hh)311 312 313 #in the case that the widget is too big, we try to resize it314 if (width != None and width < w.rect.w) or (height != None and height < w.rect.h):315 w.rect.w,w.rect.h = w.resize(width,height)316 317 width = max(width,w.rect.w,self.style.width) #,self.style.cell_width)318 height = max(height,w.rect.h,self.style.height) #,self.style.cell_height)319 320 dx = width-w.rect.w321 dy = height-w.rect.h322 w.rect.x = (self.style.align+1)*dx/2323 w.rect.y = (self.style.valign+1)*dy/2324 ...
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!!