How to use rows method in stryker-parent

Best JavaScript code snippet using stryker-parent

distributed.py

Source:distributed.py Github

copy

Full Screen

...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]))...

Full Screen

Full Screen

jquery.gridnav.js

Source:jquery.gridnav.js Github

copy

Full Screen

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 };...

Full Screen

Full Screen

checkpoint_ops_test.py

Source:checkpoint_ops_test.py Github

copy

Full Screen

...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__':...

Full Screen

Full Screen

table.py

Source:table.py Github

copy

Full Screen

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 ...

Full Screen

Full Screen

verify_benchmarks.py

Source:verify_benchmarks.py Github

copy

Full Screen

1"""2sobh@illinois.edu3"""4import filecmp5import os6import time7verification_dir = '../data/verification/'8results_dir = '../test/run_dir/results'9def verify_benchmark(option, algo_name, BENCHMARK_name_list, BENCHMARK_YML):10 run_command = 'python3 ../src/general_clustering.py -run_directory ./run_dir -run_file ' + BENCHMARK_YML11 os.system(run_command)12 All_files_in_results_dir = os.listdir(results_dir)13 num_failed_tests = 014 num_succeed_tests = 015 for f in All_files_in_results_dir:16 for BENCHMARK_name in BENCHMARK_name_list:17 if BENCHMARK_name in f:18 RESULT = os.path.join(results_dir, f)19 BENCHMARK = os.path.join(verification_dir, option, algo_name, BENCHMARK_name + '.tsv')20 if filecmp.cmp(RESULT, BENCHMARK) == True:21 num_succeed_tests += 122 print(BENCHMARK, '______ PASS ______')23 else:24 num_failed_tests += 125 print(BENCHMARK, '****** FAIL ******')26 return num_succeed_tests, num_failed_tests27def main():28 BENCHMARK = {29 'binary': {30 'kmeans': [31 'BENCHMARK_1_kmeans_binary.yml',32 'rows_averages_by_cluster_kmeans',33 'rows_by_columns_heatmap_kmeans',34 'rows_variance_kmeans',35 'samples_label_by_cluster_kmeans',36 'silhouette_overall_score_kmeans',37 'silhouette_per_cluster_score_kmeans',38 'silhouette_per_sample_score_kmeans',39 'top_rows_by_cluster_kmeans'40 ],41 'hclust': [42 'BENCHMARK_3_hclust_binary.yml',43 'rows_averages_by_cluster_hclust',44 'rows_by_columns_heatmap_hclust',45 'rows_variance_hclust',46 'samples_label_by_cluster_hclust',47 'silhouette_overall_score_hclust',48 'silhouette_per_cluster_score_hclust',49 'silhouette_per_sample_score_hclust',50 'top_rows_by_cluster_hclust'51 ],52 'link_hclust': [53 'BENCHMARK_5_link_hclust_binary.yml',54 'rows_averages_by_cluster_link_hclust',55 'rows_by_columns_heatmap_link_hclust',56 'rows_variance_link_hclust',57 'samples_label_by_cluster_link_hclust',58 'silhouette_overall_score_link_hclust',59 'silhouette_per_cluster_score_link_hclust',60 'silhouette_per_sample_score_link_hclust',61 'top_rows_by_cluster_link_hclust'62 ],63 'cc_kmeans': [64 'BENCHMARK_7_cc_kmeans_binary.yml',65 'consensus_matrix_cc_kmeans',66 'rows_averages_by_cluster_cc_kmeans',67 'rows_by_columns_heatmap_cc_kmeans',68 'rows_variance_cc_kmeans',69 'samples_label_by_cluster_cc_kmeans',70 'silhouette_overall_score_cc_kmeans',71 'silhouette_per_cluster_score_cc_kmeans',72 'silhouette_per_sample_score_cc_kmeans',73 'top_rows_by_cluster_cc_kmeans'74 ],75 'cc_hclust': [76 'BENCHMARK_9_cc_hclust_binary.yml',77 'consensus_matrix_cc_hclust',78 'rows_averages_by_cluster_cc_hclust',79 'rows_by_columns_heatmap_cc_hclust',80 'rows_variance_cc_hclust',81 'samples_label_by_cluster_cc_hclust',82 'silhouette_overall_score_cc_hclust',83 'silhouette_per_cluster_score_cc_hclust',84 'silhouette_per_sample_score_cc_hclust',85 'top_rows_by_cluster_cc_hclust'86 ],87 'cc_link_hclust': [88 'BENCHMARK_11_cc_link_hclust_binary.yml',89 'consensus_matrix_cc_link_hclust',90 'rows_averages_by_cluster_cc_link_hclust',91 'rows_by_columns_heatmap_cc_link_hclust',92 'rows_variance_cc_link_hclust',93 'samples_label_by_cluster_cc_link_hclust',94 'silhouette_overall_score_cc_link_hclust',95 'silhouette_per_cluster_score_cc_link_hclust',96 'silhouette_per_sample_score_cc_link_hclust',97 'top_rows_by_cluster_cc_link_hclust'98 ],99 'kmeans_evaluation': [100 'BENCHMARK_13_kmeans_binary_evaluation.yml',101 'rows_averages_by_cluster_kmeans',102 'rows_by_columns_heatmap_kmeans',103 'rows_variance_kmeans',104 'samples_label_by_cluster_kmeans',105 'silhouette_overall_score_kmeans',106 'silhouette_per_cluster_score_kmeans',107 'silhouette_per_sample_score_kmeans',108 'top_rows_by_cluster_kmeans',109 'clustering_evaluation_result'110 ]111 },112 'continuous': {113 'kmeans': [114 'BENCHMARK_2_kmeans_continuous.yml',115 'rows_averages_by_cluster_kmeans',116 'rows_by_columns_heatmap_kmeans',117 'rows_variance_kmeans',118 'samples_label_by_cluster_kmeans',119 'silhouette_overall_score_kmeans',120 'silhouette_per_cluster_score_kmeans',121 'silhouette_per_sample_score_kmeans',122 'top_rows_by_cluster_kmeans'123 ],124 'hclust': [125 'BENCHMARK_4_hclust_continuous.yml',126 'rows_averages_by_cluster_hclust',127 'rows_by_columns_heatmap_hclust',128 'rows_variance_hclust',129 'samples_label_by_cluster_hclust',130 'silhouette_overall_score_hclust',131 'silhouette_per_cluster_score_hclust',132 'silhouette_per_sample_score_hclust',133 'top_rows_by_cluster_hclust'134 ],135 'link_hclust': [136 'BENCHMARK_6_link_hclust_continuous.yml',137 'rows_averages_by_cluster_link_hclust',138 'rows_by_columns_heatmap_link_hclust',139 'rows_variance_link_hclust',140 'samples_label_by_cluster_link_hclust',141 'silhouette_overall_score_link_hclust',142 'silhouette_per_cluster_score_link_hclust',143 'silhouette_per_sample_score_link_hclust',144 'top_rows_by_cluster_link_hclust'145 ],146 'cc_kmeans': [147 'BENCHMARK_8_cc_kmeans_continuous.yml',148 'consensus_matrix_cc_kmeans',149 'rows_averages_by_cluster_cc_kmeans',150 'rows_by_columns_heatmap_cc_kmeans',151 'rows_variance_cc_kmeans',152 'samples_label_by_cluster_cc_kmeans',153 'silhouette_overall_score_cc_kmeans',154 'silhouette_per_cluster_score_cc_kmeans',155 'silhouette_per_sample_score_cc_kmeans',156 'top_rows_by_cluster_cc_kmeans'157 ],158 'cc_hclust': [159 'BENCHMARK_X_cc_hclust_continuous.yml',160 'consensus_matrix_cc_hclust',161 'rows_averages_by_cluster_cc_hclust',162 'rows_by_columns_heatmap_cc_hclust',163 'rows_variance_cc_hclust',164 'samples_label_by_cluster_cc_hclust',165 'silhouette_overall_score_cc_hclust',166 'silhouette_per_cluster_score_cc_hclust',167 'silhouette_per_sample_score_cc_hclust',168 'top_rows_by_cluster_cc_hclust'169 ],170 'cc_link_hclust': [171 'BENCHMARK_12_cc_link_hclust_continuous.yml',172 'consensus_matrix_cc_link_hclust',173 'rows_averages_by_cluster_cc_link_hclust',174 'rows_by_columns_heatmap_cc_link_hclust',175 'rows_variance_cc_link_hclust',176 'samples_label_by_cluster_cc_link_hclust',177 'silhouette_overall_score_cc_link_hclust',178 'silhouette_per_cluster_score_cc_link_hclust',179 'silhouette_per_sample_score_cc_link_hclust',180 'top_rows_by_cluster_cc_link_hclust'181 ]182 }183 }184 os.system('make env_setup')185 start_time = time.time()186 total_success, total_failure = 0, 0187 for option in BENCHMARK.keys():188 for key in BENCHMARK[option].keys():189 BENCHMARK_list = BENCHMARK[option][key]190 BENCHMARK_YML = BENCHMARK_list[0]191 print()192 print("INFO: Running test ", "./run_dir/results/" + BENCHMARK_YML)193 # for BENCHMARK_name in BENCHMARK_list[1:]:194 num_succeed_tests, num_failed_tests = verify_benchmark(option, key, BENCHMARK_list[1:], BENCHMARK_YML)195 total_success += num_succeed_tests196 total_failure += num_failed_tests197 os.system('rm ./run_dir/results/*')198 end_time = time.time()199 print()200 print("Ran {} tests in {}s".format(total_success + total_failure, end_time - start_time))201 if (total_failure == 0):202 print("OK")203 print()204 else:205 print("FAILED(errors={})".format(total_failure))206if __name__ == "__main__":...

Full Screen

Full Screen

jquery.autoResizeTextAreaQ-0.1.js

Source:jquery.autoResizeTextAreaQ-0.1.js Github

copy

Full Screen

1/*2 * jQuery autoResizeTextAreaQ plugin3 * @requires jQuery v1.4.2 or later4 *5 * Copyright (c) 2010 M. Brown (mbrowniebytes A gmail.com)6 * Licensed under the Revised BSD license:7 * http://www.opensource.org/licenses/bsd-license.php8 * http://en.wikipedia.org/wiki/BSD_licenses9 *10 * Versions:11 * 0.1 - 2010-07-2112 * initial13 *14 * usage:15 * $(document).ready( function() {16 * $('textarea').autoResizeTextAreaQ({"max_rows":8});17 * });18 *19 */20(function($) {21$.fn.autoResizeTextAreaQ = function(options) {22 var opts = $.extend({23 // ya prob want to use24 max_rows: 10, // # - max rows to resize too25 // ya may want to use, but defaults should be ok26 extra_rows: 1, // # - nbr extra rows after last line ie padding; 0|1 optimal27 // ya should really specify in html28 rows: null, // null|# - null infer from html; # override html29 cols: null, // null|# - null infer from html; # override html30 debug: false // true|false - turn on|off console.log()31 }, options);32 // extra padding based on browser33 /* Removed jQuery 1.9.x34 if ($.browser.msie) {35 opts.extra_rows += 1;36 } else if ($.browser.webkit) {37 opts.extra_rows += 1;38 } // else $.browser.mozilla39 */40 opts.extra_rows += 1; // use webkit only.41 // iterate over passed in selector, only process actual textareas42 return $(this).filter('textarea').each(function(index) {43 var ta = $(this);44 var orig = {};45 // textarea rows cols current state46 if (opts.cols != null && opts.cols > 0) {47 ta.attr('cols', opts.cols);48 }49 orig.cols = ta.attr('cols');50 if (opts.rows != null && opts.rows > 0) {51 ta.attr('rows', opts.rows);52 }53 orig.rows = ta.attr('rows');54 // validate max extra_rows55 if (opts.max_rows == null || opts.max_rows < orig.rows) {56 opts.max_rows = orig.rows;57 }58 if (opts.extra_rows == null || opts.extra_rows < 0) {59 opts.extra_rows = 0;60 }61 if (opts.debug) {62 console.log('opts: ', opts, ' orig: ', orig);63 }64 // resize textares on load65 resize(ta, orig);66 // check resize on key input67 ta.bind('keyup', function(e) {68 resize(ta, orig);69 });70 }); // end each()71 function resize(ta, orig) {72 // nbr explicit rows73 var nl_rows = ta.val().split('\n');74 // nbr inferred rows75 var nbr_ta_rows = 0;76 for (index in nl_rows) {77 // overly simple check to account for text being auto wrapped and thus a new line78 nbr_ta_rows += Math.floor((nl_rows[index].length / orig.cols)) + 1;79 }80 // get final nbr ta rows81 var final_nbr_ta_rows = nbr_ta_rows - 1; // deduct for current line82 final_nbr_ta_rows += opts.extra_rows; // add on extra rows83 // resize textarea84 // note: $.animate() doesnt work well here since only inc/dec row by one85 if (final_nbr_ta_rows >= opts.max_rows) {86 ta.attr('rows', opts.max_rows);87 } else if (final_nbr_ta_rows >= orig.rows) {88 ta.attr('rows', final_nbr_ta_rows);89 } else {90 ta.attr('rows', orig.rows);91 }92 if (opts.debug) {93 console.log('rows: ', ta.attr('rows'), ' nbr nl_rows: ', nl_rows.length, ' nbr_ta_rows: ', nbr_ta_rows, ' final_nbr_ta_rows: ', final_nbr_ta_rows);94 }95 } // end resize()96}; // end autoResizeTextAreaQ()...

Full Screen

Full Screen

script.js

Source:script.js Github

copy

Full Screen

1function sortName() {2 var table, rows, switching, i, x, y, shouldSwitch;3 table = document.getElementById("myTable");4 switching = true;5 while (switching) {6 switching = false;7 rows = table.rows;8 for (i = 1; i < (rows.length - 1); i++) {9 shouldSwitch = false;10 x = rows[i].getElementsByTagName("TD")[1];11 y = rows[i + 1].getElementsByTagName("TD")[1];12 if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {13 shouldSwitch = true;14 break;15 }16 }17 if (shouldSwitch) {18 rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);19 switching = true;20 }21 }22 }23function sortSeries() {24 var table, rows, switching, i, x, y, shouldSwitch;25 table = document.getElementById("myTable");26 switching = true;27 while (switching) {28 switching = false;29 rows = table.rows;30 for (i = 1; i < (rows.length - 1); i++) {31 shouldSwitch = false;32 x = rows[i].getElementsByTagName("TD")[2];33 y = rows[i + 1].getElementsByTagName("TD")[2];34 if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {35 shouldSwitch = true;36 break;37 }38 }39 if (shouldSwitch) {40 rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);41 switching = true;42 }43 }44 }45 function sortPrice() {46 var table, rows, switching, i, x, y, shouldSwitch;47 table = document.getElementById("myTable");48 switching = true;49 while (switching) {50 switching = false;51 rows = table.rows;52 for (i = 1; i < (rows.length - 1); i++) {53 shouldSwitch = false;54 x = rows[i].getElementsByTagName("TD")[3];55 y = rows[i + 1].getElementsByTagName("TD")[3];56 if (x.innerHTML > y.innerHTML) {57 shouldSwitch = true;58 break;59 }60 }61 if (shouldSwitch) {62 rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);63 switching = true;64 }65 }66 }67function sortAmount() {68 var table, rows, switching, i, x, y, shouldSwitch;69 table = document.getElementById("myTable");70 switching = true;71 while (switching) {72 switching = false;73 rows = table.rows;74 for (i = 1; i < (rows.length - 1); i++) {75 shouldSwitch = false;76 x = rows[i].getElementsByTagName("TD")[4];77 y = rows[i + 1].getElementsByTagName("TD")[4];78 if (x.innerHTML > y.innerHTML) {79 shouldSwitch = true;80 break;81 }82 }83 if (shouldSwitch) {84 rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);85 switching = true;86 }87 }...

Full Screen

Full Screen

updateSql.py

Source:updateSql.py Github

copy

Full Screen

1# ------------------------------------------2# 批量更新数据库的SQL语句用代码编写3# ------------------------------------------4# 批量更新方法一,数据量小与500条时效率高5def update(tableName, fieldName, datas):6 rows = ["CASE"]7 field = []8 for data in datas:9 row = "WHEN id=%s THEN %s" % (data['id'], data[fieldName])10 rows.append(row)11 field.append(data['id'])12 rows.append("END")13 rows = tuple(rows)14 field = tuple(field)15 rows = str(rows)16 field = str(field)17 rows = rows.replace("\'", "")18 field = field.replace("\'", "")19 rows = rows.replace(",", "")20 sql = 'UPDATE %s SET %s=%s WHERE id IN %s;' % (tableName, fieldName, rows,21 field)22 print(sql)23# 批量更新方法二,数据量大于与1000条时效率高24def update2(tableName, fieldName, datas):25 rows = []26 for data in datas:27 row = "SELECT %s AS id, %s AS %s UNION" % (data['id'], data[fieldName],28 fieldName)29 rows.append(row)30 strRows = str(tuple(rows))31 strRows = strRows.replace("\'", "")32 strRows = strRows.replace("UNION,", "!")33 strRows = strRows.replace("UNION", "")34 strRows = strRows.replace("!", "UNION")35 sql = "UPDATE %s a JOIN %s b USING(id) SET a.%s=b.%s;" % (36 tableName, strRows, fieldName, fieldName)37 print(sql)38datas = [{39 'id': 1,40 'name': 'shj',41 'sex': 'man',42 'year': 2743}, {44 'id': 2,45 'name': 'touot',46 'sex': 'woman',47 'year': 2548}, {49 'id': 3,50 'name': 'kouok',51 'sex': 'man',52 'year': 1853}]54update('test', 'name', datas)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const rows = require('stryker-parent').rows;2console.log(rows);3const {rows} = require('stryker-parent');4console.log(rows);5const {rows} = require('stryker-parent').rows;6console.log(rows);7const rows = require('stryker-parent').rows;8console.log(rows);9const {rows} = require('stryker-parent');10console.log(rows);11const {rows} = require('stryker-parent').rows;12console.log(rows);13const rows = require('stryker-parent').rows;14console.log(rows);15const {rows} = require('stryker-parent');16console.log(rows);17const {rows} = require('stryker-parent').rows;18console.log(rows);19const rows = require('stryker-parent').rows;20console.log(rows);21const {rows} = require('stryker-parent');22console.log(rows);23const {rows} = require('stryker-parent').rows;24console.log(rows);25const rows = require('stryker-parent').rows;26console.log(rows);27const {rows} = require('stryker-parent');28console.log(rows);29const {rows} = require('stryker-parent').rows;

Full Screen

Using AI Code Generation

copy

Full Screen

1const { rows } = require('stryker-parent')2const { rows } = require('stryker-child')3const { rows } = require('stryker-child')4const { rows } = require('stryker-parent')5const { rows } = require('stryker-parent')6const { rows } = require('stryker-child')7const { rows } = require('stryker-child')8const { rows } = require('stryker-parent')9const { rows } = require('stryker-parent')10const { rows } = require('stryker-child')11const { rows } = require('stryker-child')12const { rows } = require('stryker-parent')13const { rows } = require('stryker-parent')14const { rows } = require('stryker-child')15const { rows } = require('stryker-child')16const { rows } = require('stryker-parent')17const { rows } = require('stryker-parent')18const { rows } = require('stryker-child')19const { rows } = require('stryker-child')20const { rows } = require('stryker-parent')21const { rows } = require('stryker-parent')22const { rows } = require('stryker-child')23const { rows } = require('stryker-child')24const { rows } = require('stryker-parent')25const { rows } = require('stryker-parent')26const { rows } = require('stryker-child')27const { rows } = require('stryker-child')28const { rows } = require('stryker-parent')29const { rows } = require('stryker-parent')30const { rows } = require('stryker-child')31const { rows } = require('stryker-child')32const { rows } = require('stryker-parent')33const { rows } = require('stryker-parent')34const { rows } = require('stryker-child')35const { rows } = require('stryker-child')36const { rows } = require('stryker-parent')37const { rows } = require('stryker-parent')38const { rows } = require('stryker-child')39const { rows } = require('stryker-child')40const { rows } = require('stryker-parent')41const { rows } = require('stryker-parent')42const { rows } = require('stryker-child')43const { rows } = require('stryker-child')

Full Screen

Using AI Code Generation

copy

Full Screen

1var strykerParent = require('stryker-parent');2var rows = strykerParent.rows;3rows('test.txt', function (err, result) {4 if (err) {5 console.log(err);6 } else {7 console.log(result);8 }9});10var strykerParent = require('stryker-parent');11var rows = strykerParent.rows;12rows('test.txt', function (err, result) {13 if (err) {14 console.log(err);15 } else {16 console.log(result);17 }18});19var strykerParent = require('stryker-parent');20var rows = strykerParent.rows;21rows('test.txt', function (err, result) {22 if (err) {23 console.log(err);24 } else {25 console.log(result);26 }27});28var strykerParent = require('stryker-parent');29var rows = strykerParent.rows;30rows('test.txt', function (err, result) {31 if (err) {32 console.log(err);33 } else {34 console.log(result);35 }36});37var strykerParent = require('stryker-parent');38var rows = strykerParent.rows;39rows('test.txt', function (err, result) {40 if (err) {41 console.log(err);42 } else {43 console.log(result);44 }45});46var strykerParent = require('stryker-parent');47var rows = strykerParent.rows;48rows('test.txt', function (err, result) {49 if (err) {50 console.log(err);51 } else {52 console.log(result);53 }54});55var strykerParent = require('stryker-parent');56var rows = strykerParent.rows;57rows('test.txt', function (err, result) {58 if (err) {59 console.log(err);60 } else {61 console.log(result);62 }

Full Screen

Using AI Code Generation

copy

Full Screen

1var rows = require('stryker-parent').rows;2var myRows = rows(4);3console.log(myRows);4module.exports = {5 rows: function(rows) {6 var result = [];7 for (var i = 0; i < rows; i++) {8 result.push('row ' + i);9 }10 return result;11 }12};13{14}15module.exports = {16 rows: function(rows) {17 var result = [];18 for (var i = 0; i < rows; i++) {19 result.push('child row ' + i);20 }21 return result;22 }23};24{25}

Full Screen

Using AI Code Generation

copy

Full Screen

1var parent = require('stryker-parent');2var rows = parent.rows;3var row = rows('test.csv');4console.log(row);5console.log(rows('test.csv').length);6console.log(rows('test.csv')[0]);7console.log(rows('test.csv')[0].length);8console.log(rows('test.csv')[0][0]);9console.log(rows('test.csv')[0][1]);10console.log(rows('test.csv')[0][2]);11{"a":"1","b":"2","c":"3"}12{"a":"4","b":"5","c":"6"}

Full Screen

Using AI Code Generation

copy

Full Screen

1var Parent = require('stryker-parent');2var parent = new Parent();3parent.rows(function (err, rows) {4 console.log(rows);5});6rows(callback)7function (err, rows)

Full Screen

Using AI Code Generation

copy

Full Screen

1var rows = require('stryker-parent');2var data = rows(5);3console.log(data);4var rows = require('stryker-rows');5module.exports = rows;6module.exports = function rows(n) {7 var result = [];8 for (var i = 0; i < n; i++) {9 result.push((i + 1).toString());10 }11 return result;12};13var rowsPath = require.resolve('stryker-rows');14console.log(rowsPath);15var rowsPath = require.resolve('stryker-parent');16console.log(rowsPath);

Full Screen

Using AI Code Generation

copy

Full Screen

1var rows = require('stryker-parent').rows;2rows(10, function (err, result) {3 console.log(result);4});5module.exports = {6 rows: require('./lib/rows')7};8var rows = function (num, cb) {9 var result = [];10 for (var i = 0; i < num; i++) {11 result.push(i);12 }13 cb(null, result);14};15module.exports = rows;16module.exports = require('./lib/rows');17var rows = function (num, cb) {18 var result = [];19 for (var i = 0; i < num; i++) {20 result.push(i);21 }22 cb(null, result);23};24module.exports = rows;

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run stryker-parent automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful