Best JavaScript code snippet using sinon
report.js
Source:report.js  
1/*2 * Copyright 2017-present, Yudong (Dom) Wang3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *      http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16var reportData = @REPORT_DATA@;17// Run the code when the DOM is ready ss18$(pieChart);19function pieChart() {20    // Config settings21    var chartSizePercent = 55; // The chart radius relative to the canvas width/height (in percent)22    var sliceBorderWidth = 1; // Width (in pixels) of the border around each slice23    var sliceBorderStyle = "#fff"; // Colour of the border around each slice24    var sliceGradientColour = "#ddd"; // Colour to use for one end of the chart gradient25    var maxPullOutDistance = 25; // How far, in pixels, to pull slices out when clicked26    var pullOutFrameStep = 4; // How many pixels to move a slice with each animation frame27    var pullOutFrameInterval = 40; // How long (in ms) between each animation frame28    var pullOutLabelPadding = 65; // Padding between pulled-out slice and its label  29    var pullOutLabelFont = "bold 16px 'Trebuchet MS', Verdana, sans-serif"; // Pull-out slice label font30    var pullOutValueFont = "bold 12px 'Trebuchet MS', Verdana, sans-serif"; // Pull-out slice value font31    var pullOutShadowColour = "rgba( 0, 0, 0, .5 )"; // Colour to use for the pull-out slice shadow32    var pullOutShadowOffsetX = 5; // X-offset (in pixels) of the pull-out slice shadow33    var pullOutShadowOffsetY = 5; // Y-offset (in pixels) of the pull-out slice shadow34    var pullOutShadowBlur = 5; // How much to blur the pull-out slice shadow35    var pullOutBorderWidth = 1; // Width (in pixels) of the pull-out slice border36    var pullOutBorderStyle = "#333"; // Colour of the pull-out slice border37    var chartStartAngle = -.5 * Math.PI; // Start the chart at 12 o'clock instead of 3 o'clock38    // Declare some variables for the chart39    var canvas; // The canvas element in the page40    var currentPullOutSlice = -1; // The slice currently pulled out (-1 = no slice)41    var currentPullOutDistance = 0; // How many pixels the pulled-out slice is currently pulled out in the animation42    var animationId = 0; // Tracks the interval ID for the animation created by setInterval()43    var chartData = []; // Chart data (labels, values, and angles)44    var chartColours = []; // Chart colours (pulled from the HTML table)45    var totalValue = 0; // Total of all the values in the chart46    var canvasWidth; // Width of the canvas, in pixels47    var canvasHeight; // Height of the canvas, in pixels48    var centreX; // X-coordinate of centre of the canvas/chart49    var centreY; // Y-coordinate of centre of the canvas/chart50    var chartRadius; // Radius of the pie chart, in pixels51    // Load report detail information52    report_detail();53    // Set things up and draw the chart54    init();55    /**56     * Load information from json file57     */58    function report_detail() {59        var $tasks = $("#tasks");60        var styleAttr = "";61        //$tasks.empty();62        $.each(reportData.hists, function(i, hist) {63            if (hist["result"] == 'PASS') {64                styleAttr = "style=\"color:#0AC37C\"";65            } else if (hist["result"] == 'ERROR') {66                styleAttr = "style=\"color:#F90606\"";67            } else if (hist["result"] == 'FAILURE') {68                styleAttr = "style=\"color:#0B6AF6\"";69            } else {70                styleAttr = "";71            }72            $tasks.append("<tr>" + "<td>" + (i + 1) + "</td>"73            		             + "<td>" + hist["request"].method + " "  + hist["request"].url + "</td>" 74            		             + "<td>" + hist["response"].status + "</td>" 75            		             + "<td>" + hist["response"].date + "</td>" 76            		             + "<td>" + hist["response"].time + " ms" + "</td>"77            		             + "<td>" + hist["descr"] + "</td>"78            		             + "<td " + styleAttr + ">" + hist["result"] + "</td>" 79            		             + "<td>" + hist["cause"] + "</td>" +80            		      "</tr>");81        });82    }83    /**84     * Set up the chart data and colours, as well as the chart and table click handlers,85     * and draw the initial pie chart86     */87    function init() {88        // Get the canvas element in the page89        canvas = document.getElementById('chart');90        // Exit if the browser isn't canvas-capable91        if (typeof canvas.getContext === 'undefined') return;92        // Initialise some properties of the canvas and chart93        canvasWidth = canvas.width;94        canvasHeight = canvas.height;95        centreX = canvasWidth / 2;96        centreY = canvasHeight / 2;97        chartRadius = Math.min(canvasWidth, canvasHeight) / 2 * (chartSizePercent / 100);98        // Grab the data from the table,99        // and assign click handlers to the table data cells100        var currentRow = -1;101        var currentCell = 0;102        $('#chartData td').each(function() {103            currentCell++;104            if (currentCell % 2 != 0) {105                currentRow++;106                chartData[currentRow] = [];107                chartData[currentRow]['label'] = $(this).text();108            } else {109                var value = parseFloat($(this).text());110                totalValue += value;111                value = value.toFixed(0);112                chartData[currentRow]['value'] = value;113            }114            // Store the slice index in this cell, and attach a click handler to it115            $(this).data('slice', currentRow);116            $(this).click(handleTableClick);117            // Extract and store the cell colour118            if (rgb = $(this).css('color').match(/rgb\((\d+), (\d+), (\d+)/)) {119                chartColours[currentRow] = [rgb[1], rgb[2], rgb[3]];120            } else if (hex = $(this).css('color').match(/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/)) {121                chartColours[currentRow] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];122            } else {123                alert("Error: Colour could not be determined! Please specify table colours using the format '#xxxxxx'");124                return;125            }126        });127        // Now compute and store the start and end angles of each slice in the chart data128        var currentPos = 0; // The current position of the slice in the pie (from 0 to 1)129        for (var slice in chartData) {130            chartData[slice]['startAngle'] = 2 * Math.PI * currentPos;131            chartData[slice]['endAngle'] = 2 * Math.PI * (currentPos + (chartData[slice]['value'] / totalValue));132            currentPos += chartData[slice]['value'] / totalValue;133        }134        // All ready! Now draw the pie chart, and add the click handler to it135        drawChart();136        $('#chart').click(handleChartClick);137    }138    /**139     * Process mouse clicks in the chart area.140     *141     * If a slice was clicked, toggle it in or out.142     * If the user clicked outside the pie, push any slices back in.143     *144     * @param Event The click event145     */146    function handleChartClick(clickEvent) {147        // Get the mouse cursor position at the time of the click, relative to the canvas148        var mouseX = clickEvent.pageX - this.offsetLeft;149        var mouseY = clickEvent.pageY - this.offsetTop;150        // Was the click inside the pie chart?151        var xFromCentre = mouseX - centreX;152        var yFromCentre = mouseY - centreY;153        var distanceFromCentre = Math.sqrt(Math.pow(Math.abs(xFromCentre), 2) + Math.pow(Math.abs(yFromCentre), 2));154        if (distanceFromCentre <= chartRadius) {155            // Yes, the click was inside the chart.156            // Find the slice that was clicked by comparing angles relative to the chart centre.157            var clickAngle = Math.atan2(yFromCentre, xFromCentre) - chartStartAngle;158            if (clickAngle < 0) clickAngle = 2 * Math.PI + clickAngle;159            for (var slice in chartData) {160                if (clickAngle >= chartData[slice]['startAngle'] && clickAngle <= chartData[slice]['endAngle']) {161                    // Slice found. Pull it out or push it in, as required.162                    toggleSlice(slice);163                    return;164                }165            }166        }167        // User must have clicked outside the pie. Push any pulled-out slice back in.168        pushIn();169    }170    /**171     * Process mouse clicks in the table area.172     *173     * Retrieve the slice number from the jQuery data stored in the174     * clicked table cell, then toggle the slice175     *176     * @param Event The click event177     */178    function handleTableClick(clickEvent) {179        var slice = $(this).data('slice');180        toggleSlice(slice);181    }182    /**183     * Push a slice in or out.184     *185     * If it's already pulled out, push it in. Otherwise, pull it out.186     *187     * @param Number The slice index (between 0 and the number of slices - 1)188     */189    function toggleSlice(slice) {190        if (slice == currentPullOutSlice) {191            pushIn();192        } else {193            startPullOut(slice);194        }195    }196    /**197     * Start pulling a slice out from the pie.198     *199     * @param Number The slice index (between 0 and the number of slices - 1)200     */201    function startPullOut(slice) {202        // Exit if we're already pulling out this slice203        if (currentPullOutSlice == slice) return;204        // Record the slice that we're pulling out, clear any previous animation, then start the animation205        currentPullOutSlice = slice;206        currentPullOutDistance = 0;207        clearInterval(animationId);208        animationId = setInterval(function() {209            animatePullOut(slice);210        }, pullOutFrameInterval);211        // Highlight the corresponding row in the key table212        $('#chartData td').removeClass('highlight');213        var labelCell = $('#chartData td:eq(' + (slice * 2) + ')');214        var valueCell = $('#chartData td:eq(' + (slice * 2 + 1) + ')');215        labelCell.addClass('highlight');216        valueCell.addClass('highlight');217    }218    /**219     * Draw a frame of the pull-out animation.220     *221     * @param Number The index of the slice being pulled out222     */223    function animatePullOut(slice) {224        // Pull the slice out some more225        currentPullOutDistance += pullOutFrameStep;226        // If we've pulled it right out, stop animating227        if (currentPullOutDistance >= maxPullOutDistance) {228            clearInterval(animationId);229            return;230        }231        // Draw the frame232        drawChart();233    }234    /**235     * Push any pulled-out slice back in.236     *237     * Resets the animation variables and redraws the chart.238     * Also un-highlights all rows in the table.239     */240    function pushIn() {241        currentPullOutSlice = -1;242        currentPullOutDistance = 0;243        clearInterval(animationId);244        drawChart();245        $('#chartData td').removeClass('highlight');246    }247    /**248     * Draw the chart.249     *250     * Loop through each slice of the pie, and draw it.251     */252    function drawChart() {253        // Get a drawing context254        var context = canvas.getContext('2d');255        // Clear the canvas, ready for the new frame256        context.clearRect(0, 0, canvasWidth, canvasHeight);257        // Draw each slice of the chart, skipping the pull-out slice (if any)258        for (var slice in chartData) {259            if (slice != currentPullOutSlice) drawSlice(context, slice);260        }261        // If there's a pull-out slice in effect, draw it.262        // (We draw the pull-out slice last so its drop shadow doesn't get painted over.)263        if (currentPullOutSlice != -1) drawSlice(context, currentPullOutSlice);264    }265    /**266     * Draw an individual slice in the chart.267     *268     * @param Context A canvas context to draw on269     * @param Number The index of the slice to draw270     */271    function drawSlice(context, slice) {272        // Compute the adjusted start and end angles for the slice273        var startAngle = chartData[slice]['startAngle'] + chartStartAngle;274        var endAngle = chartData[slice]['endAngle'] + chartStartAngle;275        if (slice == currentPullOutSlice) {276            // We're pulling (or have pulled) this slice out.277            // Offset it from the pie centre, draw the text label,278            // and add a drop shadow.279            var midAngle = (startAngle + endAngle) / 2;280            var actualPullOutDistance = currentPullOutDistance * easeOut(currentPullOutDistance / maxPullOutDistance, .8);281            startX = centreX + Math.cos(midAngle) * actualPullOutDistance;282            startY = centreY + Math.sin(midAngle) * actualPullOutDistance;283            context.fillStyle = 'rgb(' + chartColours[slice].join(',') + ')';284            context.textAlign = "center";285            context.font = pullOutLabelFont;286            context.fillText(chartData[slice]['label'], centreX + Math.cos(midAngle) * (chartRadius + maxPullOutDistance + pullOutLabelPadding), centreY + Math.sin(midAngle) * (chartRadius + maxPullOutDistance + pullOutLabelPadding));287            context.font = pullOutValueFont;288            context.fillText(chartData[slice]['value'] + " (" + (parseInt(chartData[slice]['value'] / totalValue * 100 + .5)) + "%)", centreX + Math.cos(midAngle) * (chartRadius + maxPullOutDistance + pullOutLabelPadding), centreY + Math.sin(midAngle) * (chartRadius + maxPullOutDistance + pullOutLabelPadding) + 20);289            context.shadowOffsetX = pullOutShadowOffsetX;290            context.shadowOffsetY = pullOutShadowOffsetY;291            context.shadowBlur = pullOutShadowBlur;292        } else {293            // This slice isn't pulled out, so draw it from the pie centre294            startX = centreX;295            startY = centreY;296        }297        // Set up the gradient fill for the slice298        var sliceGradient = context.createLinearGradient(0, 0, canvasWidth * .75, canvasHeight * .75);299        sliceGradient.addColorStop(0, sliceGradientColour);300        sliceGradient.addColorStop(1, 'rgb(' + chartColours[slice].join(',') + ')');301        // Draw the slice302        context.beginPath();303        context.moveTo(startX, startY);304        context.arc(startX, startY, chartRadius, startAngle, endAngle, false);305        context.lineTo(startX, startY);306        context.closePath();307        context.fillStyle = sliceGradient;308        context.shadowColor = (slice == currentPullOutSlice) ? pullOutShadowColour : "rgba( 0, 0, 0, 0 )";309        context.fill();310        context.shadowColor = "rgba( 0, 0, 0, 0 )";311        // Style the slice border appropriately312        if (slice == currentPullOutSlice) {313            context.lineWidth = pullOutBorderWidth;314            context.strokeStyle = pullOutBorderStyle;315        } else {316            context.lineWidth = sliceBorderWidth;317            context.strokeStyle = sliceBorderStyle;318        }319        // Draw the slice border320        context.stroke();321    }322    /**323     * Easing function.324     *325     * A bit hacky but it seems to work! (Note to self: Re-read my school maths books sometime)326     *327     * @param Number The ratio of the current distance travelled to the maximum distance328     * @param Number The power (higher numbers = more gradual easing)329     * @return Number The new ratio330     */331    function easeOut(ratio, power) {332        return (Math.pow(1 - ratio, power) + 1);333    }...group-pictures.js
Source:group-pictures.js  
...27   * @returns {string}28   */29  group2Layout1: function (pictures) {30    return this.getHTML([31      pictures.slice(0, 1),32      pictures.slice(1)33    ]);34  },35  /**36   * 2-237   *38   * â¡ â¡39   *40   * @param pictures41   */42  group2Layout2: function (pictures) {43    return this.getHTML(pictures);44  },45  /**46   * 3-147   *48   * â¡ â¡ â¡49   *50   * @param pictures51   */52  group3Layout1: function (pictures) {53    return this.getHTML(pictures);54  },55  /**56   * 3-257   *58   *  â¡59   * â¡ â¡60   *61   * @param pictures62   */63  group3Layout2: function (pictures) {64    return this.getHTML([65      pictures.slice(0, 1),66      pictures.slice(1)67    ]);68  },69  /**70   * 3-371   *72   * â¡ â¡73   *  â¡74   *75   * @param pictures76   */77  group3Layout3: function (pictures) {78    return this.getHTML([79      pictures.slice(0, 2),80      pictures.slice(2)81    ]);82  },83  /**84   * 4-185   *86   *  â¡87   * â¡ â¡88   *  â¡89   *90   * @param pictures91   */92  group4Layout1: function (pictures) {93    return this.getHTML([94      pictures.slice(0, 1),95      pictures.slice(1, 3),96      pictures.slice(3)97    ]);98  },99  /**100   * 4-2101   *102   *   â¡103   * â¡ â¡ â¡104   *105   * @param pictures106   */107  group4Layout2: function (pictures) {108    return this.getHTML([109      pictures.slice(0, 1),110      pictures.slice(1)111    ]);112  },113  /**114   * 4-3115   *116   * â¡ â¡117   * â¡ â¡118   *119   * @param pictures120   */121  group4Layout3: function (pictures) {122    return this.getHTML([123      pictures.slice(0, 2),124      pictures.slice(2)125    ]);126  },127  /**128   * 4-4129   *130   * â¡ â¡ â¡131   *   â¡132   *133   * @param pictures134   */135  group4Layout4: function (pictures) {136    return this.getHTML([137      pictures.slice(0, 3),138      pictures.slice(3)139    ]);140  },141  /**142   * 5-1143   *144   *  â¡145   * â¡ â¡146   * â¡ â¡147   *148   * @param pictures149   */150  group5Layout1: function (pictures) {151    return this.getHTML([152      pictures.slice(0, 1),153      pictures.slice(1, 3),154      pictures.slice(3)155    ]);156  },157  /**158   * 5-2159   *160   * â¡ â¡161   *  â¡162   * â¡ â¡163   *164   * @param pictures165   */166  group5Layout2: function (pictures) {167    return this.getHTML([168      pictures.slice(0, 2),169      pictures.slice(2, 3),170      pictures.slice(3)171    ]);172  },173  /**174   * 5-3175   *176   *  â¡ â¡177   * â¡ â¡ â¡178   *179   * @param pictures180   */181  group5Layout3: function (pictures) {182    return this.getHTML([183      pictures.slice(0, 2),184      pictures.slice(2)185    ]);186  },187  /**188   * 5-4189   *190   * â¡ â¡ â¡191   *  â¡ â¡192   *193   * @param pictures194   */195  group5Layout4: function (pictures) {196    return this.getHTML([197      pictures.slice(0, 3),198      pictures.slice(3)199    ]);200  },201  /**202   * 6-1203   *204   *   â¡205   *  â¡ â¡206   * â¡ â¡ â¡207   *208   * @param pictures209   */210  group6Layout1: function (pictures) {211    return this.getHTML([212      pictures.slice(0, 1),213      pictures.slice(1, 3),214      pictures.slice(3)215    ]);216  },217  /**218   * 6-2219   *220   *   â¡221   * â¡ â¡ â¡222   *  â¡ â¡223   *224   * @param pictures225   */226  group6Layout2: function (pictures) {227    return this.getHTML([228      pictures.slice(0, 1),229      pictures.slice(1, 4),230      pictures.slice(4)231    ]);232  },233  /**234   * 6-3235   *236   *  â¡ â¡237   *   â¡238   * â¡ â¡ â¡239   *240   * @param pictures241   */242  group6Layout3: function (pictures) {243    return this.getHTML([244      pictures.slice(0, 2),245      pictures.slice(2, 3),246      pictures.slice(3)247    ]);248  },249  /**250   * 6-4251   *252   * â¡ â¡253   * â¡ â¡254   * â¡ â¡255   *256   * @param pictures257   */258  group6Layout4: function (pictures) {259    return this.getHTML([260      pictures.slice(0, 2),261      pictures.slice(2, 4),262      pictures.slice(4)263    ]);264  },265  /**266   * 6-5267   *268   * â¡ â¡ â¡269   * â¡ â¡ â¡270   *271   * @param pictures272   */273  group6Layout5: function (pictures) {274    return this.getHTML([275      pictures.slice(0, 3),276      pictures.slice(3)277    ]);278  },279  /**280   * 7-1281   *282   *  â¡283   * â¡ â¡284   * â¡ â¡285   * â¡ â¡286   *287   * @param pictures288   */289  group7Layout1: function (pictures) {290    return this.getHTML([291      pictures.slice(0, 1),292      pictures.slice(1, 3),293      pictures.slice(3, 5),294      pictures.slice(5)295    ]);296  },297  /**298   * 7-2299   *300   *   â¡301   * â¡ â¡ â¡302   * â¡ â¡ â¡303   *304   * @param pictures305   */306  group7Layout2: function (pictures) {307    return this.getHTML([308      pictures.slice(0, 1),309      pictures.slice(1, 4),310      pictures.slice(4)311    ]);312  },313  /**314   * 7-3315   *316   *  â¡ â¡317   *  â¡ â¡318   * â¡ â¡ â¡319   *320   * @param pictures321   */322  group7Layout3: function (pictures) {323    return this.getHTML([324      pictures.slice(0, 2),325      pictures.slice(2, 4),326      pictures.slice(4)327    ]);328  },329  /**330   * 7-4331   *332   *  â¡ â¡333   * â¡ â¡ â¡334   *  â¡ â¡335   *336   * @param pictures337   */338  group7Layout4: function (pictures) {339    return this.getHTML([340      pictures.slice(0, 2),341      pictures.slice(2, 5),342      pictures.slice(5)343    ]);344  },345  /**346   * 7-5347   *348   * â¡ â¡ â¡349   *  â¡ â¡350   *  â¡ â¡351   *352   * @param pictures353   */354  group7Layout5: function (pictures) {355    return this.getHTML([356      pictures.slice(0, 3),357      pictures.slice(3, 5),358      pictures.slice(5)359    ]);360  },361  /**362   * 8-1363   *364   *   â¡365   *  â¡ â¡366   *  â¡ â¡367   * â¡ â¡ â¡368   *369   * @param pictures370   */371  group8Layout1: function (pictures) {372    return this.getHTML([373      pictures.slice(0, 1),374      pictures.slice(1, 3),375      pictures.slice(3, 5),376      pictures.slice(5)377    ]);378  },379  /**380   * 8-2381   *382   *   â¡383   *  â¡ â¡384   * â¡ â¡ â¡385   *  â¡ â¡386   *387   * @param pictures388   */389  group8Layout2: function (pictures) {390    return this.getHTML([391      pictures.slice(0, 1),392      pictures.slice(1, 3),393      pictures.slice(3, 6),394      pictures.slice(6)395    ]);396  },397  /**398   * 8-3399   *400   *   â¡401   * â¡ â¡ â¡402   *  â¡ â¡403   *  â¡ â¡404   * @param pictures405   */406  group8Layout3: function (pictures) {407    return this.getHTML([408      pictures.slice(0, 1),409      pictures.slice(1, 4),410      pictures.slice(4, 6),411      pictures.slice(6)412    ]);413  },414  /**415   * 8-4416   *417   * â¡ â¡418   * â¡ â¡419   * â¡ â¡420   * â¡ â¡421   *422   * @param pictures423   */424  group8Layout4: function (pictures) {425    return this.getHTML([426      pictures.slice(0, 2),427      pictures.slice(2, 4),428      pictures.slice(4, 6),429      pictures.slice(6)430    ]);431  },432  /**433   * 8-5434   *435   *  â¡ â¡436   * â¡ â¡ â¡437   * â¡ â¡ â¡438   *439   * @param pictures440   */441  group8Layout5: function (pictures) {442    return this.getHTML([443      pictures.slice(0, 2),444      pictures.slice(2, 5),445      pictures.slice(5)446    ]);447  },448  /**449   * 8-6450   *451   * â¡ â¡ â¡452   *  â¡ â¡453   * â¡ â¡ â¡454   *455   * @param pictures456   */457  group8Layout6: function (pictures) {458    return this.getHTML([459      pictures.slice(0, 3),460      pictures.slice(3, 5),461      pictures.slice(5)462    ]);463  },464  /**465   * 8-7466   *467   * â¡ â¡ â¡468   * â¡ â¡ â¡469   *  â¡ â¡470   *471   * @param pictures472   */473  group8Layout7: function (pictures) {474    return this.getHTML([475      pictures.slice(0, 3),476      pictures.slice(3, 6),477      pictures.slice(6)478    ]);479  },480  /**481   * 9-1482   *483   *   â¡484   *  â¡ â¡485   * â¡ â¡ â¡486   * â¡ â¡ â¡487   *488   * @param pictures489   */490  group9Layout1: function (pictures) {491    return this.getHTML([492      pictures.slice(0, 1),493      pictures.slice(1, 3),494      pictures.slice(3, 6),495      pictures.slice(6)496    ]);497  },498  /**499   * 9-2500   *501   *   â¡502   * â¡ â¡ â¡503   *  â¡ â¡504   * â¡ â¡ â¡505   *506   * @param pictures507   */508  group9Layout2: function (pictures) {509    return this.getHTML([510      pictures.slice(0, 1),511      pictures.slice(1, 4),512      pictures.slice(4, 6),513      pictures.slice(6)514    ]);515  },516  /**517   * 9-3518   *519   *  â¡ â¡520   *  â¡ â¡521   *  â¡ â¡522   * â¡ â¡ â¡523   *524   * @param pictures525   */526  group9Layout3: function (pictures) {527    return this.getHTML([528      pictures.slice(0, 2),529      pictures.slice(2, 4),530      pictures.slice(4, 6),531      pictures.slice(6)532    ]);533  },534  /**535   * 9-4536   *537   *  â¡ â¡538   *  â¡ â¡539   * â¡ â¡ â¡540   *  â¡ â¡541   *542   * @param pictures543   */544  group9Layout4: function (pictures) {545    return this.getHTML([546      pictures.slice(0, 2),547      pictures.slice(2, 4),548      pictures.slice(4, 7),549      pictures.slice(7)550    ]);551  },552  /**553   * 9-5554   *555   *  â¡ â¡556   * â¡ â¡ â¡557   *  â¡ â¡558   *  â¡ â¡559   *560   * @param pictures561   */562  group9Layout5: function (pictures) {563    return this.getHTML([564      pictures.slice(0, 2),565      pictures.slice(2, 5),566      pictures.slice(5, 7),567      pictures.slice(7)568    ]);569  },570  /**571   * 9-6572   *573   * â¡ â¡ â¡574   *  â¡ â¡575   *  â¡ â¡576   *  â¡ â¡577   *578   * @param pictures579   */580  group9Layout6: function (pictures) {581    return this.getHTML([582      pictures.slice(0, 3),583      pictures.slice(3, 5),584      pictures.slice(5, 7),585      pictures.slice(7)586    ]);587  },588  /**589   * 9-7590   *591   * â¡ â¡ â¡592   * â¡ â¡ â¡593   * â¡ â¡ â¡594   *595   * @param pictures596   */597  group9Layout7: function (pictures) {598    return this.getHTML([599      pictures.slice(0, 3),600      pictures.slice(3, 6),601      pictures.slice(6)602    ]);603  },604  /**605   * 10-1606   *607   *   â¡608   * â¡ â¡ â¡609   * â¡ â¡ â¡610   * â¡ â¡ â¡611   *612   * @param pictures613   */614  group10Layout1: function (pictures) {615    return this.getHTML([616      pictures.slice(0, 1),617      pictures.slice(1, 4),618      pictures.slice(4, 7),619      pictures.slice(7)620    ]);621  },622  /**623   * 10-2624   *625   *  â¡ â¡626   *  â¡ â¡627   * â¡ â¡ â¡628   * â¡ â¡ â¡629   *630   * @param pictures631   */632  group10Layout2: function (pictures) {633    return this.getHTML([634      pictures.slice(0, 2),635      pictures.slice(2, 4),636      pictures.slice(4, 7),637      pictures.slice(7)638    ]);639  },640  /**641   * 10-3642   *643   *  â¡ â¡644   * â¡ â¡ â¡645   *  â¡ â¡646   * â¡ â¡ â¡647   *648   * @param pictures649   */650  group10Layout3: function (pictures) {651    return this.getHTML([652      pictures.slice(0, 2),653      pictures.slice(2, 5),654      pictures.slice(5, 7),655      pictures.slice(7)656    ]);657  },658  /**659   * 10-4660   *661   *  â¡ â¡662   * â¡ â¡ â¡663   * â¡ â¡ â¡664   *  â¡ â¡665   *666   * @param pictures667   */668  group10Layout4: function (pictures) {669    return this.getHTML([670      pictures.slice(0, 2),671      pictures.slice(2, 5),672      pictures.slice(5, 8),673      pictures.slice(8)674    ]);675  },676  /**677   * 10-5678   *679   * â¡ â¡ â¡680   *  â¡ â¡681   *  â¡ â¡682   * â¡ â¡ â¡683   *684   * @param pictures685   */686  group10Layout5: function (pictures) {687    return this.getHTML([688      pictures.slice(0, 3),689      pictures.slice(3, 5),690      pictures.slice(5, 7),691      pictures.slice(7)692    ]);693  },694  /**695   * 10-6696   *697   * â¡ â¡ â¡698   *  â¡ â¡699   * â¡ â¡ â¡700   *  â¡ â¡701   *702   * @param pictures703   */704  group10Layout6: function (pictures) {705    return this.getHTML([706      pictures.slice(0, 3),707      pictures.slice(3, 5),708      pictures.slice(5, 8),709      pictures.slice(8)710    ]);711  },712  /**713   * 10-7714   *715   * â¡ â¡ â¡716   * â¡ â¡ â¡717   *  â¡ â¡718   *  â¡ â¡719   *720   * @param pictures721   */722  group10Layout7: function (pictures) {723    return this.getHTML([724      pictures.slice(0, 3),725      pictures.slice(3, 6),726      pictures.slice(6, 8),727      pictures.slice(8)728    ]);729  },730  /**731   * Defaults Layout732   *733   * â¡ â¡ â¡734   * â¡ â¡ â¡735   * ...736   *737   * @param pictures738   */739  defaults: function (pictures) {740    var ROW_SIZE = 3;741    var rows = pictures.length / ROW_SIZE + 1;742    var pictureArr = [];743    for (var i = 0; i < rows; i++) {744      pictureArr.push(pictures.slice(i * ROW_SIZE, (i + 1) * ROW_SIZE));745    }746    return this.getHTML(pictureArr);747  },748  getHTML: function (rows) {749    var rowHTML = '';750    for (var i = 0; i < rows.length; i++) {751      rowHTML += this.getRowHTML(rows[i]);752    }753    return '<div class="group-picture-container">' + rowHTML + '</div>';754  },755  getRowHTML: function (pictures) {756    return (757      '<div class="group-picture-row">' +758        this.getColumnHTML(pictures) +...Infinite.js
Source:Infinite.js  
1/**2 * @private3 */4Ext.define('Ext.scroll.scroller.Infinite', {5    extend: 'Ext.scroll.scroller.CssPosition',6    config: {7        itemLength: 30,8        slicesCount: 6,9        sliceLengthFactor: 1,10        functions: {11            render: Ext.emptyFn,12            recycle: Ext.emptyFn,13            activate: Ext.emptyFn,14            deactivate: Ext.emptyFn,15            scope: null16        },17        direction: 'vertical'18    },19    itemsCountPerSlice: 0,20    sliceLength: 0,21    recycleIndexOffset: 0,22    constructor: function() {23        this.preparedSlices = {};24        this.emptySlices = [];25        this.slices = [];26        this.activeSlices = {27            upper: null,28            lower: null29        };30        return this.callParent(arguments);31    },32    getMaxPosition: function(determine) {33        var maxPosition = this.maxPosition;34        if (determine) {35            maxPosition.x = Infinity;36            maxPosition.y = Infinity;37        }38        return maxPosition;39    },40    getCurrentAxis: function() {41        return (this.getDirection() === 'horizontal') ? 'x' : 'y';42    },43    applyDirection: function(direction) {44        if (direction !== 'vertical' && direction !== 'horizontal') {45            direction = 'vertical';46        }47        return direction;48    },49    applyItemLength: function(length) {50        if (typeof length == 'number' && length > 0) {51            return length;52        }53        //<debug error>54        Ext.Logger.error("Invalid itemLength, must be a number greater than 0");55        //</debug>56    },57    updateItemLength: function(length, oldLength) {58        var containerSize = this.getContainerSize(true),59            sliceLengthFactor = this.getSliceLengthFactor(),60            itemsCountPerSlice,61            width, height, sliceLength;62        if (this.isAxisEnabled('x')) {63            height = containerSize.y;64            itemsCountPerSlice = Math.ceil(containerSize.x / length) * sliceLengthFactor;65            sliceLength = width = itemsCountPerSlice * length;66        }67        else {68            width = containerSize.x;69            itemsCountPerSlice = Math.ceil(containerSize.y / length) * sliceLengthFactor;70            sliceLength = height = itemsCountPerSlice * length;71        }72        this.itemsCountPerSlice = itemsCountPerSlice;73        this.sliceLength = sliceLength;74        this.setSliceSize(width, height);75        if (oldLength) {76            this.refresh();77        }78    },79    applySlicesCount: function(count) {80        if (typeof count == 'number' && count >= 4) {81            return count;82        }83        //<debug error>84        Ext.Logger.error("Invalid slicesCount, must be a number greater or equal to 4");85        //</debug>86    },87    updateSlicesCount: function(count, oldCount) {88        var slices = this.slices,89            emptySlices = this.emptySlices,90            slice, i;91        if (oldCount) {92            this.destroySlices();93        }94        for (i = 0; i < count; i++) {95            slice = this.createSlice();96            slices[i] = slice;97            emptySlices.push(slice);98        }99        this.recycleIndexOffset = Math.floor((count - 2) / 2);100        if (oldCount) {101            this.refresh();102        }103    },104    destroySlices: function() {105        var slices = this.slices,106            i, ln, slice;107        for (i = 0, ln = slices.length; i < ln; i++) {108            slice.destroy();109        }110        slices.length = 0;111        this.emptySlices.length = 0;112        this.preparedSlices.length = 0;113    },114    createSlice: function() {115        var element = this.getElement(),116            slice = element.createChild({}),117            style = slice.dom.style;118        style.position = 'absolute';119//        style.display = 'none';120        return slice;121    },122    setSliceSize: function(width, height) {123        this.getSlicesCount();124        var slices = this.slices,125            i, ln, slice, style;126        width = width + 'px';127        height = height + 'px';128        for (i = 0,ln = slices.length; i < ln; i++) {129            slice = slices[i];130            style = slice.dom.style;131            style.width = width;132            style.height = height;133        }134        return this;135    },136    prepareSlice: function(index) {137        var preparedSlices = this.preparedSlices,138            itemsCountPerSlice = this.itemsCountPerSlice,139            functions = this.getFunctions(),140            startItemIndex, endItemIndex, slice;141        if (!preparedSlices[index]) {142            slice = this.getEmptySlice();143            startItemIndex = index * itemsCountPerSlice;144            endItemIndex = startItemIndex + itemsCountPerSlice - 1;145            preparedSlices[index] = slice;146            functions.render.call(functions.scope, slice, startItemIndex, endItemIndex);147        }148        return preparedSlices[index];149    },150    getSlice: function(index) {151        if (index > 0) {152            this.prepareSlice(index - 1);153        }154        this.prepareSlice(index + 1);155        return this.prepareSlice(index);156    },157    getEmptySlice: function() {158        var recycleIndexOffset = this.recycleIndexOffset,159            upperIndex = this.upperSliceIndex - recycleIndexOffset,160            lowerIndex = this.lowerSliceIndex + recycleIndexOffset,161            preparedSlices = this.preparedSlices,162            emptySlices = this.emptySlices,163            i;164        for (i in preparedSlices) {165            if (preparedSlices.hasOwnProperty(i)) {166                if (i <= upperIndex || i >= lowerIndex) {167                    emptySlices.push(preparedSlices[i]);168                    delete preparedSlices[i];169                }170            }171        }172        return emptySlices.pop();173    },174    setSlicePosition: function(slice, position, axis) {175        var style = slice.dom.style;176        position = (-position) + 'px';177        if (axis === 'x') {178            style.left = position;179        }180        else {181            if (Ext.os.is.iOS || Ext.os.is.Android3) {182                style.webkitTransform = 'translate3d(0px, ' + position + ', 0px)';183            }184            else {185                style.top = position;186            }187        }188    },189    setActiveSlices: function(upper, lower) {190        var activeSlices = this.activeSlices,191            oldUpper = activeSlices.upper,192            oldLower = activeSlices.lower;193        if (oldUpper && oldLower) {194            if (oldUpper !== upper) {195                if (oldUpper !== lower) {196                    this.deactivateSlice(oldUpper);197                }198                if (upper !== oldLower) {199                    this.activateSlice(upper, 2);200                }201            }202            if (oldLower !== lower) {203                if (oldLower !== upper) {204                    this.deactivateSlice(oldLower);205                }206                if (lower !== oldUpper) {207                    this.activateSlice(lower, 1);208                }209            }210        }211        else {212            this.activateSlice(upper, 2);213            this.activateSlice(lower, 1);214        }215        activeSlices.upper = upper;216        activeSlices.lower = lower;217        return this;218    },219    activateSlice: function(slice, zIndex) {220        var functions = this.getFunctions(),221            style = slice.dom.style;222//        style.zIndex = zIndex;223//        style.display = '';224        functions.activate.call(functions.scope, slice);225    },226    deactivateSlice: function(slice) {227        var functions = this.getFunctions(),228            style = slice.dom.style;229//        style.display = 'none';230        if (Ext.os.is.iOS || Ext.os.is.Android3) {231            style.webkitTransform = 'translate3d(0px, -10000px, 0px)';232        }233        else {234            style.top = '-10000px';235        }236//        this.setSlicePosition(slice, 0, this.getCurrentAxis());237        functions.deactivate.call(functions.scope, slice);238    },239    doScrollTo: function(x, y) {240        var axis = this.getCurrentAxis(),241            sliceLength = this.sliceLength,242            upperPosition = ((axis === 'x') ? x : y),243            upperSliceIndex = Math.max(0, Math.floor(upperPosition / this.sliceLength)),244            lowerSliceIndex = upperSliceIndex + 1;245        this.upperSliceIndex = upperSliceIndex;246        this.lowerSliceIndex = lowerSliceIndex;247        var upperSlice = this.getSlice(upperSliceIndex),248            lowerSlice = this.getSlice(lowerSliceIndex),249            containerSize = this.getContainerSize()[axis],250            lowerPosition;251        upperPosition = upperPosition % sliceLength;252        lowerPosition = upperPosition - sliceLength;253        this.setActiveSlices(upperSlice, lowerSlice);254        this.setSlicePosition(upperSlice, upperPosition, axis);255        if (lowerPosition >= -containerSize) {256            this.setSlicePosition(lowerSlice, lowerPosition, axis);257        }258    }...test_lib.py
Source:test_lib.py  
...34    def test_maybe_indices_to_slice_left_edge(self):35        target = np.arange(100)36        # slice37        indices = np.array([], dtype=np.intp)38        maybe_slice = lib.maybe_indices_to_slice(indices, len(target))39        assert isinstance(maybe_slice, slice)40        tm.assert_numpy_array_equal(target[indices], target[maybe_slice])41        for end in [1, 2, 5, 20, 99]:42            for step in [1, 2, 4]:43                indices = np.arange(0, end, step, dtype=np.intp)44                maybe_slice = lib.maybe_indices_to_slice(indices, len(target))45                assert isinstance(maybe_slice, slice)46                tm.assert_numpy_array_equal(target[indices], target[maybe_slice])47                # reverse48                indices = indices[::-1]49                maybe_slice = lib.maybe_indices_to_slice(indices, len(target))50                assert isinstance(maybe_slice, slice)51                tm.assert_numpy_array_equal(target[indices], target[maybe_slice])52        # not slice53        for case in [[2, 1, 2, 0], [2, 2, 1, 0], [0, 1, 2, 1], [-2, 0, 2], [2, 0, -2]]:54            indices = np.array(case, dtype=np.intp)55            maybe_slice = lib.maybe_indices_to_slice(indices, len(target))56            assert not isinstance(maybe_slice, slice)57            tm.assert_numpy_array_equal(maybe_slice, indices)58            tm.assert_numpy_array_equal(target[indices], target[maybe_slice])59    def test_maybe_indices_to_slice_right_edge(self):60        target = np.arange(100)61        # slice62        for start in [0, 2, 5, 20, 97, 98]:63            for step in [1, 2, 4]:64                indices = np.arange(start, 99, step, dtype=np.intp)65                maybe_slice = lib.maybe_indices_to_slice(indices, len(target))66                assert isinstance(maybe_slice, slice)67                tm.assert_numpy_array_equal(target[indices], target[maybe_slice])68                # reverse69                indices = indices[::-1]70                maybe_slice = lib.maybe_indices_to_slice(indices, len(target))71                assert isinstance(maybe_slice, slice)72                tm.assert_numpy_array_equal(target[indices], target[maybe_slice])73        # not slice74        indices = np.array([97, 98, 99, 100], dtype=np.intp)75        maybe_slice = lib.maybe_indices_to_slice(indices, len(target))76        assert not isinstance(maybe_slice, slice)77        tm.assert_numpy_array_equal(maybe_slice, indices)78        msg = "index 100 is out of bounds for axis (0|1) with size 100"79        with pytest.raises(IndexError, match=msg):80            target[indices]81        with pytest.raises(IndexError, match=msg):82            target[maybe_slice]83        indices = np.array([100, 99, 98, 97], dtype=np.intp)84        maybe_slice = lib.maybe_indices_to_slice(indices, len(target))85        assert not isinstance(maybe_slice, slice)86        tm.assert_numpy_array_equal(maybe_slice, indices)87        with pytest.raises(IndexError, match=msg):88            target[indices]89        with pytest.raises(IndexError, match=msg):90            target[maybe_slice]91        for case in [[99, 97, 99, 96], [99, 99, 98, 97], [98, 98, 97, 96]]:92            indices = np.array(case, dtype=np.intp)93            maybe_slice = lib.maybe_indices_to_slice(indices, len(target))94            assert not isinstance(maybe_slice, slice)95            tm.assert_numpy_array_equal(maybe_slice, indices)96            tm.assert_numpy_array_equal(target[indices], target[maybe_slice])97    def test_maybe_indices_to_slice_both_edges(self):98        target = np.arange(10)99        # slice100        for step in [1, 2, 4, 5, 8, 9]:101            indices = np.arange(0, 9, step, dtype=np.intp)102            maybe_slice = lib.maybe_indices_to_slice(indices, len(target))103            assert isinstance(maybe_slice, slice)104            tm.assert_numpy_array_equal(target[indices], target[maybe_slice])105            # reverse106            indices = indices[::-1]107            maybe_slice = lib.maybe_indices_to_slice(indices, len(target))108            assert isinstance(maybe_slice, slice)109            tm.assert_numpy_array_equal(target[indices], target[maybe_slice])110        # not slice111        for case in [[4, 2, 0, -2], [2, 2, 1, 0], [0, 1, 2, 1]]:112            indices = np.array(case, dtype=np.intp)113            maybe_slice = lib.maybe_indices_to_slice(indices, len(target))114            assert not isinstance(maybe_slice, slice)115            tm.assert_numpy_array_equal(maybe_slice, indices)116            tm.assert_numpy_array_equal(target[indices], target[maybe_slice])117    def test_maybe_indices_to_slice_middle(self):118        target = np.arange(100)119        # slice120        for start, end in [(2, 10), (5, 25), (65, 97)]:121            for step in [1, 2, 4, 20]:122                indices = np.arange(start, end, step, dtype=np.intp)123                maybe_slice = lib.maybe_indices_to_slice(indices, len(target))124                assert isinstance(maybe_slice, slice)125                tm.assert_numpy_array_equal(target[indices], target[maybe_slice])126                # reverse127                indices = indices[::-1]128                maybe_slice = lib.maybe_indices_to_slice(indices, len(target))129                assert isinstance(maybe_slice, slice)130                tm.assert_numpy_array_equal(target[indices], target[maybe_slice])131        # not slice132        for case in [[14, 12, 10, 12], [12, 12, 11, 10], [10, 11, 12, 11]]:133            indices = np.array(case, dtype=np.intp)134            maybe_slice = lib.maybe_indices_to_slice(indices, len(target))135            assert not isinstance(maybe_slice, slice)136            tm.assert_numpy_array_equal(maybe_slice, indices)137            tm.assert_numpy_array_equal(target[indices], target[maybe_slice])138    def test_maybe_booleans_to_slice(self):139        arr = np.array([0, 0, 1, 1, 1, 0, 1], dtype=np.uint8)140        result = lib.maybe_booleans_to_slice(arr)141        assert result.dtype == np.bool_142        result = lib.maybe_booleans_to_slice(arr[:0])143        assert result == slice(0, 0)144    def test_get_reverse_indexer(self):145        indexer = np.array([-1, -1, 1, 2, 0, -1, 3, 4], dtype=np.intp)146        result = lib.get_reverse_indexer(indexer, 5)147        expected = np.array([4, 2, 3, 6, 7], dtype=np.intp)148        tm.assert_numpy_array_equal(result, expected)149def test_cache_readonly_preserve_docstrings():150    # GH18197151    assert Index.hasnans.__doc__ is not None152def test_no_default_pickle():153    # GH#40397154    obj = tm.round_trip_pickle(lib.no_default)...slice.js
Source:slice.js  
1var Gdn_Slices = {2   Prepare: function() {3      Gdn_Slices.SliceUniq = Math.floor(Math.random() * 9999999);4      Gdn_Slices.Slices = [];5      6      Gdn_Slices.Load();7   },8   Load: function(Root) {9      if (Root != undefined) {10         var Candidates = Root.find('.Slice');11      } else {12         var Candidates = $('.Slice');13      }14      15      Candidates.each(jQuery.proxy(function(i,Slice) {16         var NextSliceID = Gdn_Slices.SliceUniq++;17         $(Slice).attr('slice', NextSliceID);18         var MySlice = new Gdn_Slice(Slice, NextSliceID);19         Gdn_Slices.Slices.push(MySlice);20         MySlice.Go();21      },this));22   }23};24function Gdn_Slice(SliceElement, SliceID) {25   this.Slice = $(SliceElement);26   this.RawSlice = SliceElement;27   this.Slice.css('position','relative');28   29   this.SliceID = SliceID;30   this.RawSlice.SliceID = this.SliceID;31   32   Gdn_Slice.prototype.Go = function() {33      this.RawSlice.Slice = this;34      35      if (this.Slice.hasClass('Async')) {36         this.Slice.removeClass('Async');37         this.GetSlice();38      } else39         this.ParseSlice();40   }41   42   Gdn_Slice.prototype.PrepareSliceForRequest = function() {43      var SliceDimensions = {44         'width': this.Slice.width(),45         'height': this.Slice.height()46      };47      48      if (!SliceDimensions.height) {49         this.Slice.css('height', '30px');50         SliceDimensions.height = 30;51      }52      var Overlay = document.createElement('div');53      Overlay.className = 'SliceOverlay';54      $(Overlay).css({55         'position': 'absolute',56         'top': '0px',57         'left': '0px',58         'background-color': '#DBF3FC',59         'width': SliceDimensions.width-30,60         'height': SliceDimensions.height+20,61         'color': '#222222',62         'line-height': SliceDimensions.height+'px',63         'font-size': '12px',64         'padding': '0px 15px',65         'opacity': 066      });67      68      var ImgPath = gdn.definition('WebRoot')+"/applications/dashboard/design/images/progress_sm.gif";69      $(Overlay).html('<img src="'+ImgPath+'"/>');70      this.Slice.append(Overlay);71      $(Overlay).fadeTo('fast',0.7);72   }73   74   Gdn_Slice.prototype.GetSlice = function(PassiveGet) {75      if (PassiveGet !== true)76         this.SliceURL = this.Slice.attr('rel');77         78      this.PrepareSliceForRequest();79      80      var SliceURL = gdn.url(this.SliceURL);81      jQuery.ajax({82         url: SliceURL,83         type: 'GET',84         data: {'DeliveryType':'VIEW'},85         success: jQuery.proxy(this.GotSlice,this)86      });87   }88   89   Gdn_Slice.prototype.PostSlice = function(Event) {90      this.PrepareSliceForRequest();91      92      var SliceForm = $(Event.target).parents('form').first();93      94      95      if (this.SliceForm) {96         if ($(SliceForm).attr('jsaction'))97            var SliceURL = $(SliceForm).attr('jsaction');98         else99            var SliceURL = $(SliceForm).attr('action');100      } else {101         var SliceURL = this.SliceURL;102      }103      104      SliceURL = gdn.url(SliceURL);105      106      jQuery.ajax({107         url: SliceURL,108         type: 'POST',109         data: this.GetSliceData(SliceForm),110         success: jQuery.proxy(this.GotSlice,this)111      });112      return false;113   }114   115   Gdn_Slice.prototype.ReplaceSlice = function(NewSliceURL) {116      this.Slice.attr('rel', NewSliceURL);117      this.SliceURL = NewSliceURL;118      this.GetSlice(true);119   }120   121   Gdn_Slice.prototype.GotSlice = function(Data, Status, XHR) {122   123      var DataObj = $(Data);124      if (!DataObj.find('.Slice').length && !DataObj.hasClass('Slice')) {125         // The slice isn't wrapped in anything so just put it inside the existing slice div.126         var SliceWrap = this.Slice.clone().empty().append(DataObj);127         DataObj = SliceWrap;128      }129   130      this.Slice.find('.SliceOverlay').fadeTo('fast', 0,jQuery.proxy(function(){131         this.Slice.css({132            'height': '',133            'width': ''134         });135         136         this.Slice.html('');137         for (var i = 0; i < DataObj.length; i++) {138            139            if (DataObj[i].tagName !== 'SCRIPT') {140               this.Slice.append($(DataObj[i]).html());141            } else {142               eval($(DataObj[i]).text());143            }144         }145         146         var SliceConfig = this.Slice.find('.SliceConfig').first();147         if (SliceConfig.length) {148            SliceConfig = $.parseJSON(SliceConfig.html());149            $(SliceConfig.css).each(function(i,el){150               var v_css  = document.createElement('link');151               v_css.rel = 'stylesheet'152               v_css.type = 'text/css';153               v_css.href = gdn.url(el);154               document.getElementsByTagName('head')[0].appendChild(v_css);155            });156            157            $(SliceConfig.js).each(function(i,el){158               var v_js  = document.createElement('script');159               v_js.type = 'text/javascript';160               v_js.src = gdn.url(el);161               document.getElementsByTagName('head')[0].appendChild(v_js);162            });163         }164         165         this.ParseSlice();166      },this));167   }168   169   Gdn_Slice.prototype.ParseSlice = function() {170      this.SliceURL = this.Slice.attr('rel');171      172      this.Slice.find('input.SliceSubmit').each(jQuery.proxy(function(i,Input){173         if ($(Input).parents('.Slice').attr('slice') != this.SliceID) return;174         175         $(Input).one('click',jQuery.proxy(this.PostSlice,this));176         var SliceForm = $(Input).parents('form').first()[0];177         178         this.SliceForm = false;179         if ($(Input).hasClass('SliceForm'))180            this.SliceForm = true;181         182         SliceForm.SliceFields = [];183         $(SliceForm).find('input').each(jQuery.proxy(function(i,LoopedInput){184            SliceForm.SliceFields.push(LoopedInput);185         },this));186      },this));187      188      jQuery(document).trigger('SliceReady');189      190      // Load potential inner slices191      Gdn_Slices.Load(this.Slice);192   }193   194   Gdn_Slice.prototype.GetSliceData = function(SliceForm) {195      SliceForm = $(SliceForm).first()[0];196      var SubmitData = {'DeliveryType':'VIEW'};197      $(SliceForm.SliceFields).each(jQuery.proxy(function(i,Field){198         Field = $(Field);199         200         if (Field.attr('type').toLowerCase() == 'checkbox') {201            if (Field.attr('checked'))202               SubmitData[Field.attr('name')] = Field.val();203         } else {204            SubmitData[Field.attr('name')] = Field.val();205         }206      },this));207      return SubmitData;208   }209   210   Gdn_Slice.prototype.Log = function(Message) {211      console.log('[sid:'+this.SliceID+'] '+Message);212   }213}214$(document).ready(function(){215   Gdn_Slices.Prepare();...sliceEditor.js
Source:sliceEditor.js  
1/* This is a demo of using xoslib with Marionette2   The main window is split into two halves. The left half has a CollectionView3   (SliceListView) that lists all slices the user has access to. The right half4   has an ItemView (SliceDetailView) that allows the user to edit the5   name and description of a slice, as well as a <Save> button to save it.6*/7SliceEditorApp = new Marionette.Application();8SliceEditorApp.addRegions({9  sliceList: "#sliceEditorList",10  sliceDetail: "#sliceEditorDetail",11});12/* SliceListItemView: This is the item view that is used by SliceListView to13   display slice names.14*/15SliceEditorApp.SliceListItemView = Marionette.ItemView.extend({16  template: "#sliceeditor-listitem-template",17  tagName: 'li',18  className: 'sliceeditor-listitem',1920  events: {"click": "changeSlice"},2122  changeSlice: function(e) {23        e.preventDefault();24        e.stopPropagation();2526        if (SliceEditorApp.sliceDetail.currentView && SliceEditorApp.sliceDetail.currentView.dirty) {27            if (!confirm("discard current changes?")) {28                return;29            }30        }3132        /* create a new SliceDetailView and set the sliceDetail region to33           display it.34        */3536        var sliceDetailView = new SliceEditorApp.SliceDetailView({37            model: this.model,38        });39        SliceEditorApp.sliceDetail.show(sliceDetailView);40  },41});4243/* SliceListView: This displays a list of slice names.44*/45SliceEditorApp.SliceListView = Marionette.CollectionView.extend({46  tagName: "ul",47  childView: SliceEditorApp.SliceListItemView,4849  initialize: function() {50      /* CollectionViews don't automatically listen for change events, but we51         want to, so we pick up changes from the DetailView, and we pick up52         changes from the server.53      */54      this.listenTo(this.collection, 'change', this._renderChildren);55  },5657  attachHtml: function(compositeView, childView, index) {58      // The REST API will let admin users see everything. For the developer59      // view we still want to hide slices we are not members of.60      if (childView.model.get("sliceInfo").roles.length == 0) {61          return;62      }63      SliceEditorApp.SliceListView.__super__.attachHtml(compositeView, childView, index);64  },65});6667/* SliceDetailView: Display the slice and allow it to be edited */6869SliceEditorApp.SliceDetailView = Marionette.ItemView.extend({70    template: "#sliceeditor-sliceedit-template",71    tagName: 'div',7273    events: {"click button.js-submit": "submitClicked",74             "change input": "inputChanged"},7576    /* inputChanged is watching the onChange events of the input controls. We77       do this to track when this view is 'dirty', so we can throw up a warning78       if the user tries to change his slices without saving first.79    */8081    inputChanged: function(e) {82        this.dirty = true;83    },8485    submitClicked: function(e) {86        e.preventDefault();87        var data = Backbone.Syphon.serialize(this);88        this.model.save(data);89        this.dirty = false;90    },91});92SliceEditorApp.on("start", function() {93  var sliceListView = new SliceEditorApp.SliceListView({94    collection: xos.slicesPlus95  });96  SliceEditorApp.sliceList.show(sliceListView);97  xos.slicesPlus.startPolling();98});99$(document).ready(function(){100  SliceEditorApp.start();...JDK-8010804.js
Source:JDK-8010804.js  
...31x[4294967294] = 1;32print(x.length);33x[4294967295] = 1;34print(x.length);35print(x.slice(4294967293).length);36print(x.slice(4294967294).length);37print(x.slice(4294967295).length);38print(x.slice(4294967296).length);39print(x.slice(-4294967293).length);40print(x.slice(-4294967294).length);41print(x.slice(-4294967295).length);42print(x.slice(-4294967296).length);43print(x.slice(0, 4294967293).length);44print(x.slice(0, 4294967294).length);45print(x.slice(0, 4294967295).length);46print(x.slice(0, 4294967296).length);47print(x.slice(0, -4294967293).length);48print(x.slice(0, -4294967294).length);49print(x.slice(0, -4294967295).length);50print(x.slice(0, -4294967296).length);51print(x.slice(9223371036854775807).length);52print(x.slice(9223372036854775807).length);53print(x.slice(9223373036854775807).length);54print(x.slice(9223374036854775807).length);55print(x.slice(-9223371036854775807).length);56print(x.slice(-9223372036854775807).length);57print(x.slice(-9223373036854775807).length);58print(x.slice(-9223374036854775807).length);59print(x.slice(-9223371036854775807, 1).length);60print(x.slice(-9223372036854775807, 1).length);61print(x.slice(-9223373036854775807, 1).length);62print(x.slice(-9223374036854775807, 1).length);63print(x.slice(-9223371036854775807, -1).length);64print(x.slice(-9223372036854775807, -1).length);65print(x.slice(-9223373036854775807, -1).length);66print(x.slice(-9223374036854775807, -1).length);67print(x.slice(Infinity).length);68print(x.slice(Infinity, Infinity).length);69print(x.slice(Infinity, -Infinity).length);70print(x.slice(-Infinity).length);71print(x.slice(-Infinity, Infinity).length);72print(x.slice(-Infinity, -Infinity).length);73var d = new Date();74d.setYear(Infinity);...ru.js
Source:ru.js  
...11		return grammarForms[ form ][ word ];12	}13	switch ( form ) {14		case 'genitive': // ÑодиÑелÑнÑй падеж15			if ( word.slice( -1 ) === 'Ñ' ) {16				word = word.slice( 0, -1 ) + 'Ñ';17			} else if ( word.slice( -2 ) === 'иÑ' ) {18				word = word.slice( 0, -2 ) + 'ии';19			} else if ( word.slice( -2 ) === 'ка' ) {20				word = word.slice( 0, -2 ) + 'ки';21			} else if ( word.slice( -2 ) === 'Ñи' ) {22				word = word.slice( 0, -2 ) + 'Ñей';23			} else if ( word.slice( -2 ) === 'дÑ' ) {24				word = word.slice( 0, -2 ) + 'дов';25			} else if ( word.slice( -1 ) === 'д' ) {26				word = word.slice( 0, -1 ) + 'да';27			} else if ( word.slice( -3 ) === 'нÑе' ) {28				word = word.slice( 0, -3 ) + 'нÑÑ
';29			} else if ( word.slice( -3 ) === 'ник' ) {30				word = word.slice( 0, -3 ) + 'ника';31			}32			break;33		case 'prepositional': // пÑедложнÑй падеж34			if ( word.slice( -1 ) === 'Ñ' ) {35				word = word.slice( 0, -1 ) + 'е';36			} else if ( word.slice( -2 ) === 'иÑ' ) {37				word = word.slice( 0, -2 ) + 'ии';38			} else if ( word.slice( -2 ) === 'ка' ) {39				word = word.slice( 0, -2 ) + 'ке';40			} else if ( word.slice( -2 ) === 'Ñи' ) {41				word = word.slice( 0, -2 ) + 'ÑÑÑ
';42			} else if ( word.slice( -2 ) === 'дÑ' ) {43				word = word.slice( 0, -2 ) + 'даÑ
';44			} else if ( word.slice( -1 ) === 'д' ) {45				word = word.slice( 0, -1 ) + 'де';46			} else if ( word.slice( -3 ) === 'нÑе' ) {47				word = word.slice( 0, -3 ) + 'нÑÑ
';48			} else if ( word.slice( -3 ) === 'ник' ) {49				word = word.slice( 0, -3 ) + 'нике';50			}51			break;52	}53	return word;...Using AI Code Generation
1var slice = Array.prototype.slice;2var mySpy = sinon.spy();3var mySpy2 = sinon.spy();4var mySpy3 = sinon.spy();5var mySpy4 = sinon.spy();6var mySpy5 = sinon.spy();7var mySpy6 = sinon.spy();8var mySpy7 = sinon.spy();9var mySpy8 = sinon.spy();10mySpy(1,2,3,4,5);11console.log(mySpy.getCall(0).args);12console.log(mySpy.getCall(0).args.slice(0,2));13console.log(mySpy.getCall(0).args.slice(0,3));14console.log(mySpy.getCall(0).args.slice(0,4));15console.log(mySpy.getCall(0).args.slice(0,5));16console.log(mySpy.getCall(0).args.slice(0,6));17console.log(mySpy.getCall(0).args.slice(0,7));18console.log(mySpy.getCall(0).args.slice(0,8));19console.log(mySpy.getCall(0).args.slice(0,9));20console.log(mySpy.getCall(0).args.slice(0,10));21console.log(mySpy.getCall(0).args.slice(0,11));22console.log(mySpy.getCall(0).args.slice(0,12));23console.log(mySpy.getCall(0).args.slice(0,13));24console.log(mySpy.getCall(0).args.slice(0,14));25console.log(mySpy.getCall(0).args.slice(0,15));26console.log(mySpy.getCall(0).args.slice(0,16));27console.log(mySpy.getCall(0).args.slice(0,17));28console.log(mySpy.getCall(0).args.slice(0,18));29console.log(mySpy.getCall(0).args.slice(0,19));30console.log(mySpy.getCall(0).args.slice(0,20));31console.log(mySpy.getCall(0).args.slice(0,21));32console.log(mySpy.getCall(0).args.slice(0,22));33console.log(mySpy.getCall(0).args.slice(0,23));34console.log(mySpy.getCall(0).args.slice(0,24));35console.log(mySpy.getCall(0).args.slice(0,25));36console.log(mySpy.getCall(0).args.slice(0,26));37console.log(mySpy.getUsing AI Code Generation
1var sinon = require('sinon');2var slice = Array.prototype.slice;3var spy = sinon.spy(slice);4spy(1, 2, 3);5assert(spy.calledWith(1, 2, 3));6var sinon = require('sinon');7var slice = Array.prototype.slice;8var spy = sinon.spy(slice);9spy(1, 2, 3);10assert(spy.calledWith(1, 2, 3));11var sinon = require('sinon');12var slice = Array.prototype.slice;13var spy = sinon.spy(slice);14spy(1, 2, 3);15assert(spy.calledWith(1, 2, 3));16var sinon = require('sinon');17var slice = Array.prototype.slice;18var spy = sinon.spy(slice);19spy(1, 2, 3);20assert(spy.calledWith(1, 2, 3));21var sinon = require('sinon');22var slice = Array.prototype.slice;23var spy = sinon.spy(slice);24spy(1, 2, 3);25assert(spy.calledWith(1, 2, 3));26var sinon = require('sinon');27var slice = Array.prototype.slice;28var spy = sinon.spy(slice);29spy(1, 2, 3);30assert(spy.calledWith(1, 2, 3));31var sinon = require('sinon');32var slice = Array.prototype.slice;33var spy = sinon.spy(slice);34spy(1, 2, 3);35assert(spy.calledWith(1, 2, 3));36var sinon = require('sinon');37var slice = Array.prototype.slice;38var spy = sinon.spy(slice);39spy(1, 2, 3);40assert(spy.calledWith(1, 2, 3));41var sinon = require('sinon');42var slice = Array.prototype.slice;43var spy = sinon.spy(slice);44spy(1, 2, 3);45assert(spy.calledWith(1, 2, 3));Using AI Code Generation
1var sinon = require('sinon');2var assert = require('assert');3var myObj = {4    myMethod: function (arg1, arg2) {5        return arg1 + arg2;6    }7};8var spy = sinon.spy(myObj, "myMethod");9myObj.myMethod(1, 2);10assert(spy.calledWith(1, 2));11spy.restore();12var sinon = require('sinon');13var assert = require('assert');14var myObj = {15    myMethod: function (arg1, arg2) {16        return arg1 + arg2;17    }18};19var spy = sinon.spy(myObj, "myMethod");20myObj.myMethod(1, 2);21assert(spy.withArgs(1, 2).calledOnce);22spy.restore();23var sinon = require('sinon');24var assert = require('assert');25var myObj = {26    myMethod: function (arg1, arg2) {27        return arg1 + arg2;28    }29};30var stub = sinon.stub(myObj, "myMethod").returns(42);31assert(myObj.myMethod() === 42);32stub.restore();33var sinon = require('sinon');34var assert = require('assert');35var myObj = {36    myMethod: function (arg1, arg2) {37        return arg1 + arg2;38    }39};40var stub = sinon.stub(myObj, "myMethod");41stub.withArgs(1, 2).returns(42);42assert(myObj.myMethod(1, 2) === 42);43stub.restore();44var sinon = require('sinon');45var assert = require('assert');46var myObj = {47    myMethod: function (arg1, arg2) {48        return arg1 + arg2;49    }50};51var stub = sinon.stub(myObj, "myMethod");52stub.onCall(0).returns(42);53stub.onCall(1).returns(43);54assert(myObj.myMethod() === 42);55assert(myObj.myMethod() === 43);56stub.restore();57var sinon = require('sinon');58var assert = require('assert');59var myObj = {60    myMethod: function (arg1, arg2)Using AI Code Generation
1var slice = Array.prototype.slice;2var myArray = [1, 2, 3, 4, 5];3console.log(myArraySlice);4var slice = Array.prototype.slice;5var myArray = [1, 2, 3, 4, 5];6console.log(myArraySlice);7var slice = Array.prototype.slice;8var myArray = [1, 2, 3, 4, 5];9console.log(myArraySlice);10var slice = Array.prototype.slice;11var myArray = [1, 2, 3, 4, 5];12console.log(myArraySlice);13var slice = Array.prototype.slice;14var myArray = [1, 2, 3, 4, 5];15console.log(myArraySlice);16var slice = Array.prototype.slice;17var myArray = [1, 2, 3, 4, 5];18console.log(myArraySlice);19var slice = Array.prototype.slice;20var myArray = [1, 2, 3, 4, 5];21console.log(myArraySlice);22var slice = Array.prototype.slice;Using AI Code Generation
1var sinon = require('sinon');2var assert = require('assert');3var myObj = {4    myMethod: function (arg1, arg2, callback) {5        callback(arg1 + arg2);6    }7};8describe('myObj', function () {9    it('should call the callback with 3 as an argument', function () {10        var callback = sinon.spy();11        myObj.myMethod(1, 2, callback);12        assert(callback.calledWith(3));13    });14});Using AI Code Generation
1var sinon = require('sinon');2var myobj = {3    myfunc: function() {4        console.log('myfunc');5    }6};7var spy = sinon.spy(myobj, 'myfunc');8console.log(spy.called);9myobj.myfunc();10console.log(spy.called);11console.log(spy.callCount);12var sinon = require('sinon');13var myobj = {14    myfunc: function() {15        console.log('myfunc');16    }17};18var spy = sinon.spy(myobj, 'myfunc');19console.log(spy.called);20myobj.myfunc();21console.log(spy.called);22console.log(spy.callCount);23var sinon = require('sinon');24var myobj = {25    myfunc: function() {26        console.log('myfunc');27    }28};29var spy = sinon.spy(myobj, 'myfunc');30console.log(spy.called);31myobj.myfunc();32console.log(spy.called);33console.log(spy.callCount);34var sinon = require('sinon');35var myobj = {36    myfunc: function() {37        console.log('myfunc');38    }39};40var spy = sinon.spy(myobj, 'myfunc');41console.log(spy.called);42myobj.myfunc();43console.log(spy.called);44console.log(spy.callCount);45var sinon = require('sinon');46var myobj = {47    myfunc: function() {48        console.log('myfunc');49    }50};51var spy = sinon.spy(myobj, 'myfunc');52console.log(spy.called);53myobj.myfunc();54console.log(spy.called);55console.log(spy.callCount);56var sinon = require('sinon');57var myobj = {Using AI Code Generation
1var sinon = require('sinon');2var slice = Array.prototype.slice;3var spy = sinon.spy();4slice.call(arguments, 0);5console.log(spy.called);6var sinon = require('sinon');7var slice = Array.prototype.slice;8var spy = sinon.spy();9slice.apply(arguments, [0]);10console.log(spy.called);11var sinon = require('sinon');12var slice = Array.prototype.slice;13var spy = sinon.spy();14slice.apply(arguments, 0);15console.log(spy.called);16var sinon = require('sinon');17var slice = Array.prototype.slice;18var spy = sinon.spy();19slice.apply(arguments, [0, 1]);20console.log(spy.called);21var sinon = require('sinon');22var slice = Array.prototype.slice;23var spy = sinon.spy();24slice.apply(arguments, 0, 1);25console.log(spy.called);26var sinon = require('sinon');27var slice = Array.prototype.slice;28var spy = sinon.spy();29slice.apply(arguments, 0, [1]);30console.log(spy.called);31var sinon = require('sinon');32var slice = Array.prototype.slice;33var spy = sinon.spy();34slice.apply(arguments, [0], 1);35console.log(spy.called);36var sinon = require('sinon');37var slice = Array.prototype.slice;38var spy = sinon.spy();39slice.apply(arguments, [0], [1]);40console.log(spy.called);41var sinon = require('sinon');42var slice = Array.prototype.slice;43var spy = sinon.spy();44slice.apply(arguments, [0, 1], 2);45console.log(spy.called);Using AI Code Generation
1var sinon = require('sinon');2var assert = require('assert');3var myFunc = require('./myFunc');4var myFuncStub = sinon.stub(myFunc, 'myFunc');5myFuncStub.withArgs(1).returns(1);6myFuncStub.withArgs(2).returns(2);7myFuncStub.withArgs(3).returns(3);8myFuncStub.withArgs(4).returns(4);9myFuncStub.withArgs(5).returns(5);10myFuncStub.withArgs(6).returns(6);11myFuncStub.withArgs(7).returns(7);12myFuncStub.withArgs(8).returns(8);13myFuncStub.withArgs(9).returns(9);14myFuncStub.withArgs(10).returns(10);15myFuncStub.withArgs(11).returns(11);16myFuncStub.withArgs(12).returns(12);17myFuncStub.withArgs(13).returns(13);18myFuncStub.withArgs(14).returns(14);19myFuncStub.withArgs(15).returns(15);20myFuncStub.withArgs(16).returns(16);21myFuncStub.withArgs(17).returns(17);22myFuncStub.withArgs(18).returns(18);23myFuncStub.withArgs(19).returns(19);24myFuncStub.withArgs(20).returns(20);25myFuncStub.withArgs(21).returns(21);26myFuncStub.withArgs(22).returns(22);27myFuncStub.withArgs(23).returns(23);28myFuncStub.withArgs(24).returns(24);29myFuncStub.withArgs(25).returns(25);30myFuncStub.withArgs(26).returns(26);31myFuncStub.withArgs(27).returns(27);32myFuncStub.withArgs(28).returns(28);33myFuncStub.withArgs(29).returns(29);34myFuncStub.withArgs(30).returns(30);35myFuncStub.withArgs(31).returns(31);36myFuncStub.withArgs(32).returns(32);37myFuncStub.withArgs(33).returns(33);38myFuncStub.withArgs(34).returns(34);39myFuncStub.withArgs(35).returns(35);40myFuncStub.withArgs(36).returns(36);41myFuncStub.withArgs(37).returns(37);42myFuncStub.withArgs(38).returnsUsing AI Code Generation
1var fs = require('fs');2var data = fs.readFileSync('test.js', 'utf8');3var lines = data.split('\r4');5var firstTen = [];6var restOfLines = [];7for (var i = 0; i < lines.length; i++) {8    if (i === 9) {9        firstTen.push(lines[i]);10        restOfLines = lines.slice(10);11    } else {12        firstTen.push(lines[i]);13    }14}15fs.writeFile('firstTen.txt', firstTen.join('\r16'), function (err) {17    if (err) {18        throw err;19    }20});21fs.writeFile('restOfLines.txt', restOfLines.join('\r22'), function (err) {23    if (err) {24        throw err;25    }26});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!!
