How to use B.all method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

executorspage.js

Source:executorspage.js Github

copy

Full Screen

1/*2 * Licensed to the Apache Software Foundation (ASF) under one or more3 * contributor license agreements.  See the NOTICE file distributed with4 * this work for additional information regarding copyright ownership.5 * The ASF licenses this file to You under the Apache License, Version 2.06 * (the "License"); you may not use this file except in compliance with7 * the License.  You may obtain a copy of the License at8 *9 *    http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS,13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14 * See the License for the specific language governing permissions and15 * limitations under the License.16 */17var threadDumpEnabled = false;18function setThreadDumpEnabled(val) {19    threadDumpEnabled = val;20}21function getThreadDumpEnabled() {22    return threadDumpEnabled;23}24function formatStatus(status, type, row) {25    if (row.isBlacklisted) {26        return "Blacklisted";27    }28    if (status) {29        if (row.blacklistedInStages.length == 0) {30            return "Active"31        }32        return "Active (Blacklisted in Stages: [" + row.blacklistedInStages.join(", ") + "])";33    }34    return "Dead"35}36jQuery.extend(jQuery.fn.dataTableExt.oSort, {37    "title-numeric-pre": function (a) {38        var x = a.match(/title="*(-?[0-9\.]+)/)[1];39        return parseFloat(x);40    },41    "title-numeric-asc": function (a, b) {42        return ((a < b) ? -1 : ((a > b) ? 1 : 0));43    },44    "title-numeric-desc": function (a, b) {45        return ((a < b) ? 1 : ((a > b) ? -1 : 0));46    }47});48$(document).ajaxStop($.unblockUI);49$(document).ajaxStart(function () {50    $.blockUI({message: '<h3>Loading Executors Page...</h3>'});51});52function createTemplateURI(appId) {53    var words = document.baseURI.split('/');54    var ind = words.indexOf("proxy");55    if (ind > 0) {56        var baseURI = words.slice(0, ind + 1).join('/') + '/' + appId + '/static/executorspage-template.html';57        return baseURI;58    }59    ind = words.indexOf("history");60    if(ind > 0) {61        var baseURI = words.slice(0, ind).join('/') + '/static/executorspage-template.html';62        return baseURI;63    }64    return location.origin + "/static/executorspage-template.html";65}66function getStandAloneppId(cb) {67    var words = document.baseURI.split('/');68    var ind = words.indexOf("proxy");69    if (ind > 0) {70        var appId = words[ind + 1];71        cb(appId);72        return;73    }74    ind = words.indexOf("history");75    if (ind > 0) {76        var appId = words[ind + 1];77        cb(appId);78        return;79    }80    //Looks like Web UI is running in standalone mode81    //Let's get application-id using REST End Point82    $.getJSON(location.origin + "/api/v1/applications", function(response, status, jqXHR) {83        if (response && response.length > 0) {84            var appId = response[0].id85            cb(appId);86            return;87        }88    });89}90function createRESTEndPoint(appId) {91    var words = document.baseURI.split('/');92    var ind = words.indexOf("proxy");93    if (ind > 0) {94        var appId = words[ind + 1];95        var newBaseURI = words.slice(0, ind + 2).join('/');96        return newBaseURI + "/api/v1/applications/" + appId + "/allexecutors"97    }98    ind = words.indexOf("history");99    if (ind > 0) {100        var appId = words[ind + 1];101        var attemptId = words[ind + 2];102        var newBaseURI = words.slice(0, ind).join('/');103        if (isNaN(attemptId)) {104            return newBaseURI + "/api/v1/applications/" + appId + "/allexecutors";105        } else {106            return newBaseURI + "/api/v1/applications/" + appId + "/" + attemptId + "/allexecutors";107        }108    }109    return location.origin + "/api/v1/applications/" + appId + "/allexecutors";110}111function formatLogsCells(execLogs, type) {112    if (type !== 'display') return Object.keys(execLogs);113    if (!execLogs) return;114    var result = '';115    $.each(execLogs, function (logName, logUrl) {116        result += '<div><a href=' + logUrl + '>' + logName + '</a></div>'117    });118    return result;119}120function logsExist(execs) {121    return execs.some(function(exec) {122        return !($.isEmptyObject(exec["executorLogs"]));123    });124}125// Determine Color Opacity from 0.5-1126// activeTasks range from 0 to maxTasks127function activeTasksAlpha(activeTasks, maxTasks) {128    return maxTasks > 0 ? ((activeTasks / maxTasks) * 0.5 + 0.5) : 1;129}130function activeTasksStyle(activeTasks, maxTasks) {131    return activeTasks > 0 ? ("hsla(240, 100%, 50%, " + activeTasksAlpha(activeTasks, maxTasks) + ")") : "";132}133// failedTasks range max at 10% failure, alpha max = 1134function failedTasksAlpha(failedTasks, totalTasks) {135    return totalTasks > 0 ?136        (Math.min(10 * failedTasks / totalTasks, 1) * 0.5 + 0.5) : 1;137}138function failedTasksStyle(failedTasks, totalTasks) {139    return failedTasks > 0 ?140        ("hsla(0, 100%, 50%, " + failedTasksAlpha(failedTasks, totalTasks) + ")") : "";141}142// totalDuration range from 0 to 50% GC time, alpha max = 1143function totalDurationAlpha(totalGCTime, totalDuration) {144    return totalDuration > 0 ?145        (Math.min(totalGCTime / totalDuration + 0.5, 1)) : 1;146}147// When GCTimePercent is edited change ToolTips.TASK_TIME to match148var GCTimePercent = 0.1;149function totalDurationStyle(totalGCTime, totalDuration) {150    // Red if GC time over GCTimePercent of total time151    return (totalGCTime > GCTimePercent * totalDuration) ?152        ("hsla(0, 100%, 50%, " + totalDurationAlpha(totalGCTime, totalDuration) + ")") : "";153}154function totalDurationColor(totalGCTime, totalDuration) {155    return (totalGCTime > GCTimePercent * totalDuration) ? "white" : "black";156}157$(document).ready(function () {158    $.extend($.fn.dataTable.defaults, {159        stateSave: true,160        lengthMenu: [[20, 40, 60, 100, -1], [20, 40, 60, 100, "All"]],161        pageLength: 20162    });163    executorsSummary = $("#active-executors");164    getStandAloneppId(function (appId) {165        var endPoint = createRESTEndPoint(appId);166        $.getJSON(endPoint, function (response, status, jqXHR) {167            var summary = [];168            var allExecCnt = 0;169            var allRDDBlocks = 0;170            var allMemoryUsed = 0;171            var allMaxMemory = 0;172            var allOnHeapMemoryUsed = 0;173            var allOnHeapMaxMemory = 0;174            var allOffHeapMemoryUsed = 0;175            var allOffHeapMaxMemory = 0;176            var allDiskUsed = 0;177            var allTotalCores = 0;178            var allMaxTasks = 0;179            var allActiveTasks = 0;180            var allFailedTasks = 0;181            var allCompletedTasks = 0;182            var allTotalTasks = 0;183            var allTotalDuration = 0;184            var allTotalGCTime = 0;185            var allTotalInputBytes = 0;186            var allTotalShuffleRead = 0;187            var allTotalShuffleWrite = 0;188            var allTotalBlacklisted = 0;189            var activeExecCnt = 0;190            var activeRDDBlocks = 0;191            var activeMemoryUsed = 0;192            var activeMaxMemory = 0;193            var activeOnHeapMemoryUsed = 0;194            var activeOnHeapMaxMemory = 0;195            var activeOffHeapMemoryUsed = 0;196            var activeOffHeapMaxMemory = 0;197            var activeDiskUsed = 0;198            var activeTotalCores = 0;199            var activeMaxTasks = 0;200            var activeActiveTasks = 0;201            var activeFailedTasks = 0;202            var activeCompletedTasks = 0;203            var activeTotalTasks = 0;204            var activeTotalDuration = 0;205            var activeTotalGCTime = 0;206            var activeTotalInputBytes = 0;207            var activeTotalShuffleRead = 0;208            var activeTotalShuffleWrite = 0;209            var activeTotalBlacklisted = 0;210            var deadExecCnt = 0;211            var deadRDDBlocks = 0;212            var deadMemoryUsed = 0;213            var deadMaxMemory = 0;214            var deadOnHeapMemoryUsed = 0;215            var deadOnHeapMaxMemory = 0;216            var deadOffHeapMemoryUsed = 0;217            var deadOffHeapMaxMemory = 0;218            var deadDiskUsed = 0;219            var deadTotalCores = 0;220            var deadMaxTasks = 0;221            var deadActiveTasks = 0;222            var deadFailedTasks = 0;223            var deadCompletedTasks = 0;224            var deadTotalTasks = 0;225            var deadTotalDuration = 0;226            var deadTotalGCTime = 0;227            var deadTotalInputBytes = 0;228            var deadTotalShuffleRead = 0;229            var deadTotalShuffleWrite = 0;230            var deadTotalBlacklisted = 0;231            response.forEach(function (exec) {232                var memoryMetrics = {233                    usedOnHeapStorageMemory: 0,234                    usedOffHeapStorageMemory: 0,235                    totalOnHeapStorageMemory: 0,236                    totalOffHeapStorageMemory: 0237                };238                exec.memoryMetrics = exec.hasOwnProperty('memoryMetrics') ? exec.memoryMetrics : memoryMetrics;239            });240            response.forEach(function (exec) {241                allExecCnt += 1;242                allRDDBlocks += exec.rddBlocks;243                allMemoryUsed += exec.memoryUsed;244                allMaxMemory += exec.maxMemory;245                allOnHeapMemoryUsed += exec.memoryMetrics.usedOnHeapStorageMemory;246                allOnHeapMaxMemory += exec.memoryMetrics.totalOnHeapStorageMemory;247                allOffHeapMemoryUsed += exec.memoryMetrics.usedOffHeapStorageMemory;248                allOffHeapMaxMemory += exec.memoryMetrics.totalOffHeapStorageMemory;249                allDiskUsed += exec.diskUsed;250                allTotalCores += exec.totalCores;251                allMaxTasks += exec.maxTasks;252                allActiveTasks += exec.activeTasks;253                allFailedTasks += exec.failedTasks;254                allCompletedTasks += exec.completedTasks;255                allTotalTasks += exec.totalTasks;256                allTotalDuration += exec.totalDuration;257                allTotalGCTime += exec.totalGCTime;258                allTotalInputBytes += exec.totalInputBytes;259                allTotalShuffleRead += exec.totalShuffleRead;260                allTotalShuffleWrite += exec.totalShuffleWrite;261                allTotalBlacklisted += exec.isBlacklisted ? 1 : 0;262                if (exec.isActive) {263                    activeExecCnt += 1;264                    activeRDDBlocks += exec.rddBlocks;265                    activeMemoryUsed += exec.memoryUsed;266                    activeMaxMemory += exec.maxMemory;267                    activeOnHeapMemoryUsed += exec.memoryMetrics.usedOnHeapStorageMemory;268                    activeOnHeapMaxMemory += exec.memoryMetrics.totalOnHeapStorageMemory;269                    activeOffHeapMemoryUsed += exec.memoryMetrics.usedOffHeapStorageMemory;270                    activeOffHeapMaxMemory += exec.memoryMetrics.totalOffHeapStorageMemory;271                    activeDiskUsed += exec.diskUsed;272                    activeTotalCores += exec.totalCores;273                    activeMaxTasks += exec.maxTasks;274                    activeActiveTasks += exec.activeTasks;275                    activeFailedTasks += exec.failedTasks;276                    activeCompletedTasks += exec.completedTasks;277                    activeTotalTasks += exec.totalTasks;278                    activeTotalDuration += exec.totalDuration;279                    activeTotalGCTime += exec.totalGCTime;280                    activeTotalInputBytes += exec.totalInputBytes;281                    activeTotalShuffleRead += exec.totalShuffleRead;282                    activeTotalShuffleWrite += exec.totalShuffleWrite;283                    activeTotalBlacklisted += exec.isBlacklisted ? 1 : 0;284                } else {285                    deadExecCnt += 1;286                    deadRDDBlocks += exec.rddBlocks;287                    deadMemoryUsed += exec.memoryUsed;288                    deadMaxMemory += exec.maxMemory;289                    deadOnHeapMemoryUsed += exec.memoryMetrics.usedOnHeapStorageMemory;290                    deadOnHeapMaxMemory += exec.memoryMetrics.totalOnHeapStorageMemory;291                    deadOffHeapMemoryUsed += exec.memoryMetrics.usedOffHeapStorageMemory;292                    deadOffHeapMaxMemory += exec.memoryMetrics.totalOffHeapStorageMemory;293                    deadDiskUsed += exec.diskUsed;294                    deadTotalCores += exec.totalCores;295                    deadMaxTasks += exec.maxTasks;296                    deadActiveTasks += exec.activeTasks;297                    deadFailedTasks += exec.failedTasks;298                    deadCompletedTasks += exec.completedTasks;299                    deadTotalTasks += exec.totalTasks;300                    deadTotalDuration += exec.totalDuration;301                    deadTotalGCTime += exec.totalGCTime;302                    deadTotalInputBytes += exec.totalInputBytes;303                    deadTotalShuffleRead += exec.totalShuffleRead;304                    deadTotalShuffleWrite += exec.totalShuffleWrite;305                    deadTotalBlacklisted += exec.isBlacklisted ? 1 : 0;306                }307            });308            var totalSummary = {309                "execCnt": ( "Total(" + allExecCnt + ")"),310                "allRDDBlocks": allRDDBlocks,311                "allMemoryUsed": allMemoryUsed,312                "allMaxMemory": allMaxMemory,313                "allOnHeapMemoryUsed": allOnHeapMemoryUsed,314                "allOnHeapMaxMemory": allOnHeapMaxMemory,315                "allOffHeapMemoryUsed": allOffHeapMemoryUsed,316                "allOffHeapMaxMemory": allOffHeapMaxMemory,317                "allDiskUsed": allDiskUsed,318                "allTotalCores": allTotalCores,319                "allMaxTasks": allMaxTasks,320                "allActiveTasks": allActiveTasks,321                "allFailedTasks": allFailedTasks,322                "allCompletedTasks": allCompletedTasks,323                "allTotalTasks": allTotalTasks,324                "allTotalDuration": allTotalDuration,325                "allTotalGCTime": allTotalGCTime,326                "allTotalInputBytes": allTotalInputBytes,327                "allTotalShuffleRead": allTotalShuffleRead,328                "allTotalShuffleWrite": allTotalShuffleWrite,329                "allTotalBlacklisted": allTotalBlacklisted330            };331            var activeSummary = {332                "execCnt": ( "Active(" + activeExecCnt + ")"),333                "allRDDBlocks": activeRDDBlocks,334                "allMemoryUsed": activeMemoryUsed,335                "allMaxMemory": activeMaxMemory,336                "allOnHeapMemoryUsed": activeOnHeapMemoryUsed,337                "allOnHeapMaxMemory": activeOnHeapMaxMemory,338                "allOffHeapMemoryUsed": activeOffHeapMemoryUsed,339                "allOffHeapMaxMemory": activeOffHeapMaxMemory,340                "allDiskUsed": activeDiskUsed,341                "allTotalCores": activeTotalCores,342                "allMaxTasks": activeMaxTasks,343                "allActiveTasks": activeActiveTasks,344                "allFailedTasks": activeFailedTasks,345                "allCompletedTasks": activeCompletedTasks,346                "allTotalTasks": activeTotalTasks,347                "allTotalDuration": activeTotalDuration,348                "allTotalGCTime": activeTotalGCTime,349                "allTotalInputBytes": activeTotalInputBytes,350                "allTotalShuffleRead": activeTotalShuffleRead,351                "allTotalShuffleWrite": activeTotalShuffleWrite,352                "allTotalBlacklisted": activeTotalBlacklisted353            };354            var deadSummary = {355                "execCnt": ( "Dead(" + deadExecCnt + ")" ),356                "allRDDBlocks": deadRDDBlocks,357                "allMemoryUsed": deadMemoryUsed,358                "allMaxMemory": deadMaxMemory,359                "allOnHeapMemoryUsed": deadOnHeapMemoryUsed,360                "allOnHeapMaxMemory": deadOnHeapMaxMemory,361                "allOffHeapMemoryUsed": deadOffHeapMemoryUsed,362                "allOffHeapMaxMemory": deadOffHeapMaxMemory,363                "allDiskUsed": deadDiskUsed,364                "allTotalCores": deadTotalCores,365                "allMaxTasks": deadMaxTasks,366                "allActiveTasks": deadActiveTasks,367                "allFailedTasks": deadFailedTasks,368                "allCompletedTasks": deadCompletedTasks,369                "allTotalTasks": deadTotalTasks,370                "allTotalDuration": deadTotalDuration,371                "allTotalGCTime": deadTotalGCTime,372                "allTotalInputBytes": deadTotalInputBytes,373                "allTotalShuffleRead": deadTotalShuffleRead,374                "allTotalShuffleWrite": deadTotalShuffleWrite,375                "allTotalBlacklisted": deadTotalBlacklisted376            };377            var data = {executors: response, "execSummary": [activeSummary, deadSummary, totalSummary]};378            $.get(createTemplateURI(appId), function (template) {379                executorsSummary.append(Mustache.render($(template).filter("#executors-summary-template").html(), data));380                var selector = "#active-executors-table";381                var conf = {382                    "data": response,383                    "columns": [384                        {385                            data: function (row, type) {386                                return type !== 'display' ? (isNaN(row.id) ? 0 : row.id ) : row.id;387                            }388                        },389                        {data: 'hostPort'},390                        {391                            data: 'isActive',392                            render: function (data, type, row) {393                                return formatStatus (data, type, row);394                            }395                        },396                        {data: 'rddBlocks'},397                        {398                            data: function (row, type) {399                                if (type !== 'display')400                                    return row.memoryUsed;401                                else402                                    return (formatBytes(row.memoryUsed, type) + ' / ' +403                                        formatBytes(row.maxMemory, type));404                            }405                        },406                        {407                            data: function (row, type) {408                                if (type !== 'display')409                                    return row.memoryMetrics.usedOnHeapStorageMemory;410                                else411                                    return (formatBytes(row.memoryMetrics.usedOnHeapStorageMemory, type) + ' / ' +412                                        formatBytes(row.memoryMetrics.totalOnHeapStorageMemory, type));413                            },414                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {415                                $(nTd).addClass('on_heap_memory')416                            }417                        },418                        {419                            data: function (row, type) {420                                if (type !== 'display')421                                    return row.memoryMetrics.usedOffHeapStorageMemory;422                                else423                                    return (formatBytes(row.memoryMetrics.usedOffHeapStorageMemory, type) + ' / ' +424                                        formatBytes(row.memoryMetrics.totalOffHeapStorageMemory, type));425                            },426                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {427                                $(nTd).addClass('off_heap_memory')428                            }429                        },430                        {data: 'diskUsed', render: formatBytes},431                        {data: 'totalCores'},432                        {433                            data: 'activeTasks',434                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {435                                if (sData > 0) {436                                    $(nTd).css('color', 'white');437                                    $(nTd).css('background', activeTasksStyle(oData.activeTasks, oData.maxTasks));438                                }439                            }440                        },441                        {442                            data: 'failedTasks',443                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {444                                if (sData > 0) {445                                    $(nTd).css('color', 'white');446                                    $(nTd).css('background', failedTasksStyle(oData.failedTasks, oData.totalTasks));447                                }448                            }449                        },450                        {data: 'completedTasks'},451                        {data: 'totalTasks'},452                        {453                            data: function (row, type) {454                                return type === 'display' ? (formatDuration(row.totalDuration) + ' (' + formatDuration(row.totalGCTime) + ')') : row.totalDuration455                            },456                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {457                                if (oData.totalDuration > 0) {458                                    $(nTd).css('color', totalDurationColor(oData.totalGCTime, oData.totalDuration));459                                    $(nTd).css('background', totalDurationStyle(oData.totalGCTime, oData.totalDuration));460                                }461                            }462                        },463                        {data: 'totalInputBytes', render: formatBytes},464                        {data: 'totalShuffleRead', render: formatBytes},465                        {data: 'totalShuffleWrite', render: formatBytes},466                        {name: 'executorLogsCol', data: 'executorLogs', render: formatLogsCells},467                        {468                            name: 'threadDumpCol',469                            data: 'id', render: function (data, type) {470                                return type === 'display' ? ("<a href='threadDump/?executorId=" + data + "'>Thread Dump</a>" ) : data;471                            }472                        }473                    ],474                    "order": [[0, "asc"]]475                };476    477                var dt = $(selector).DataTable(conf);478                dt.column('executorLogsCol:name').visible(logsExist(response));479                dt.column('threadDumpCol:name').visible(getThreadDumpEnabled());480                $('#active-executors [data-toggle="tooltip"]').tooltip();481    482                var sumSelector = "#summary-execs-table";483                var sumConf = {484                    "data": [activeSummary, deadSummary, totalSummary],485                    "columns": [486                        {487                            data: 'execCnt',488                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {489                                $(nTd).css('font-weight', 'bold');490                            }491                        },492                        {data: 'allRDDBlocks'},493                        {494                            data: function (row, type) {495                                if (type !== 'display')496                                    return row.allMemoryUsed497                                else498                                    return (formatBytes(row.allMemoryUsed, type) + ' / ' +499                                        formatBytes(row.allMaxMemory, type));500                            }501                        },502                        {503                            data: function (row, type) {504                                if (type !== 'display')505                                    return row.allOnHeapMemoryUsed;506                                else507                                    return (formatBytes(row.allOnHeapMemoryUsed, type) + ' / ' +508                                        formatBytes(row.allOnHeapMaxMemory, type));509                            },510                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {511                                $(nTd).addClass('on_heap_memory')512                            }513                        },514                        {515                            data: function (row, type) {516                                if (type !== 'display')517                                    return row.allOffHeapMemoryUsed;518                                else519                                    return (formatBytes(row.allOffHeapMemoryUsed, type) + ' / ' +520                                        formatBytes(row.allOffHeapMaxMemory, type));521                            },522                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {523                                $(nTd).addClass('off_heap_memory')524                            }525                        },526                        {data: 'allDiskUsed', render: formatBytes},527                        {data: 'allTotalCores'},528                        {529                            data: 'allActiveTasks',530                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {531                                if (sData > 0) {532                                    $(nTd).css('color', 'white');533                                    $(nTd).css('background', activeTasksStyle(oData.allActiveTasks, oData.allMaxTasks));534                                }535                            }536                        },537                        {538                            data: 'allFailedTasks',539                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {540                                if (sData > 0) {541                                    $(nTd).css('color', 'white');542                                    $(nTd).css('background', failedTasksStyle(oData.allFailedTasks, oData.allTotalTasks));543                                }544                            }545                        },546                        {data: 'allCompletedTasks'},547                        {data: 'allTotalTasks'},548                        {549                            data: function (row, type) {550                                return type === 'display' ? (formatDuration(row.allTotalDuration, type) + ' (' + formatDuration(row.allTotalGCTime, type) + ')') : row.allTotalDuration551                            },552                            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {553                                if (oData.allTotalDuration > 0) {554                                    $(nTd).css('color', totalDurationColor(oData.allTotalGCTime, oData.allTotalDuration));555                                    $(nTd).css('background', totalDurationStyle(oData.allTotalGCTime, oData.allTotalDuration));556                                }557                            }558                        },559                        {data: 'allTotalInputBytes', render: formatBytes},560                        {data: 'allTotalShuffleRead', render: formatBytes},561                        {data: 'allTotalShuffleWrite', render: formatBytes},562                        {data: 'allTotalBlacklisted'}563                    ],564                    "paging": false,565                    "searching": false,566                    "info": false567                };568    569                $(sumSelector).DataTable(sumConf);570                $('#execSummary [data-toggle="tooltip"]').tooltip();571    572            });573        });574    });...

Full Screen

Full Screen

getAllActive.js

Source:getAllActive.js Github

copy

Full Screen

1/*2 * Copyright (c) 2021 Huawei Device Co., Ltd.3 * Licensed under the Apache License, Version 2.0 (the "License");4 * you may not use this file except in compliance with the License.5 * You may obtain a copy of the License at6 *7 *     http://www.apache.org/licenses/LICENSE-2.08 *9 * Unless required by applicable law or agreed to in writing, software10 * distributed under the License is distributed on an "AS IS" BASIS,11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12 * See the License for the specific language governing permissions and13 * limitations under the License.14 */1516import notify from '@ohos.notification'17import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index'18var time = 50019describe('ActsAnsAllActiveTestOne', function () {20    console.info("===========ActsAnsAllActiveTestOne  start====================>");21    function getAllCallback(err, data){22        console.log("Ans_GetAllActive_0100 getAllCallback ============>");23        var i;24        console.log("Ans_GetAllActive_0100 getAllCallback  data.length============>"+data.length);25        expect(data.length).assertEqual(2);26        console.log("Ans_GetAllActive_0100 getAllCallback  data============>"+JSON.stringify(data));27        for (i = 0; i < data.length; i++) {28            if (i == 0){29                expect(data[i].content.normal.title).assertEqual("test_title_otherApp");30                console.log("=======Ans_GetAllActive_0100 getCallback title=====>"+data[i].content.normal.title)31                expect(data[i].content.normal.text).assertEqual("test_text_otherApp");32                console.log("=======Ans_GetAllActive_0100 getCallback text========>"+data[i].content.normal.text)33                expect(data[i].content.normal.additionalText).assertEqual("test_additionalText_otherApp");34                console.log("===Ans_GetAllActive_0100 getCallback text====>"+data[i].content.normal.additionalText)35                expect(data[i].id).assertEqual(2);36                console.log("============Ans_GetAllActive_0100 getCallback id============>"+data[i].id)37                expect(data[i].label).assertEqual("otherApp");38                console.log("============Ans_GetAllActive_0100 getCallback label=====>"+data[i].label)39            }else if(i == 1){40                expect(data[i].content.normal.title).assertEqual("test_title_currentApp");41                console.log("======Ans_GetAllActive_0100 getCallback title=========>"+data[i].content.normal.title)42                expect(data[i].content.normal.text).assertEqual("test_text_currentApp");43                console.log("==========Ans_GetAllActive_0100 getCallback text=======>"+data[i].content.normal.text)44                expect(data[i].content.normal.additionalText).assertEqual("test_additionalText_currentApp");45                console.log("===Ans_GetAllActive_0100 getCallback text=====>"+data[i].content.normal.additionalText)46                expect(data[i].id).assertEqual(1);47                console.log("============Ans_GetAllActive_0100 getCallback id============>"+data[i].id)48                expect(data[i].label).assertEqual("currentApp_0100");49                console.log("============Ans_GetAllActive_0100 getCallback label=====>"+data[i].label)50            }51        }52    }5354    /*55    * @tc.number: Ans_GetAllActive_010056    * @tc.name: getAllActiveNotifications(callback: AsyncCallback<Array<NotificationRequest>>): void;57    * @tc.desc: Verify: After the current app and other apps publish two notifications,58                get all active notifications in the system(callback)59    */60    it('Ans_GetAllActive_0100', 0, async function (done) {61        console.debug("===============Ans_GetAllActive_0100 start==================>");62        await notify.cancelAll();63        var notificationRequestOfCurrentApp = {64            content:{65                contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,66                normal: {67                    title: "test_title_currentApp",68                    text: "test_text_currentApp",69                    additionalText: "test_additionalText_currentApp"70                },71            },72            id: 1,73            label: "currentApp_0100",74        }75        await notify.publish(notificationRequestOfCurrentApp);76        console.debug("===============Ans_GetAllActive_0100 publish CurrentApp notify end==================>");77        notify.getAllActiveNotifications(getAllCallback);78        console.debug("===============Ans_GetAllActive_0100 getAllActiveNotifications end==================>");79        setTimeout(function(){80            console.debug("===============Ans_GetAllActive_0100 setTimeout==================>");81            done();82        }, time);83    })8485    /*86    * @tc.number: Ans_GetAllActive_020087    * @tc.name: getAllActiveNotifications(): Promise<Array<NotificationRequest>>88    * @tc.desc: Verify: After the current app and other apps publish two notifications,89                get all active notifications in the system(promise)90    */91    it('Ans_GetAllActive_0200', 0, async function (done) {92        console.debug("===============Ans_GetAllActive_0200 start==================>");93        await notify.cancelAll();94        var notificationRequestOfCurrentApp = {95            content:{96                contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,97                normal: {98                    title: "test_title_currentApp",99                    text: "test_text_currentApp",100                    additionalText: "test_additionalText_currentApp"101                },102            },103            id: 1,104            label: "currentApp_0200",105        }106        await notify.publish(notificationRequestOfCurrentApp);107        console.debug("===============Ans_GetAllActive_0200 publish CurrentApp notify end==================>");108        var promiseData = await notify.getAllActiveNotifications();109        console.debug("===============Ans_GetAllActive_0200 getActiveNotifications end==================>");110        expect(promiseData.length).assertEqual(2);111        var i;112        for (i = 0; i < promiseData.length; i++) {113            if (i == 0){114                expect(promiseData[i].content.normal.title).assertEqual("test_title_otherApp");115                console.log("=======Ans_GetAllActive_0200 title=====>"+promiseData[i].content.normal.title)116                expect(promiseData[i].content.normal.text).assertEqual("test_text_otherApp");117                console.log("=======Ans_GetAllActive_0200 text========>"+promiseData[i].content.normal.text)118                expect(promiseData[i].content.normal.additionalText).assertEqual("test_additionalText_otherApp");119                console.log("===Ans_GetAllActive_0200 text====>"+promiseData[i].content.normal.additionalText)120                expect(promiseData[i].id).assertEqual(2);121                console.log("============Ans_GetAllActive_0200 id============>"+promiseData[i].id)122                expect(promiseData[i].label).assertEqual("otherApp");123                console.log("============Ans_GetAllActive_0200 label=====>"+promiseData[i].label)124            }else if(i == 1){125                expect(promiseData[i].content.normal.title).assertEqual("test_title_currentApp");126                console.log("====Ans_GetAllActive_0200 title=====>"+promiseData[i].content.normal.title)127                expect(promiseData[i].content.normal.text).assertEqual("test_text_currentApp");128                console.log("======Ans_GetAllActive_0200 text=====>"+promiseData[i].content.normal.text)129                expect(promiseData[i].content.normal.additionalText).assertEqual("test_additionalText_currentApp");130                console.log("Ans_GetAllActive_0200 text===>"+promiseData[i].content.normal.additionalText)131                expect(promiseData[i].id).assertEqual(1);132                console.log("============Ans_GetAllActive_0200 id============>"+promiseData[i].id)133                expect(promiseData[i].label).assertEqual("currentApp_0200");134                console.log("============Ans_GetAllActive_0200 label=====>"+promiseData[i].label)135            }136        }137        setTimeout(function(){138            console.debug("===============Ans_GetAllActive_0200 setTimeout==================>");139            done();140        }, time);141    })142143    function getAllCallbackThree(err, data){144        console.log("Ans_GetAllActive_0300 getAllCallbackThree ============>");145        console.log("Ans_GetAllActive_0300 getAllCallbackThree  data.length============>"+data.length);146        console.log("Ans_GetAllActive_0300 getAllCallbackThree  data============>"+JSON.stringify(data));147        expect(data.length).assertEqual(1);148        var i;149        for (i = 0; i < data.length; i++) {150            expect(data[i].content.normal.title).assertEqual("test_title_otherApp");151            console.log("==========Ans_GetAllActive_0300 getCallback title=========>"+data[i].content.normal.title)152            expect(data[i].content.normal.text).assertEqual("test_text_otherApp");153            console.log("==========Ans_GetAllActive_0300 getCallback text============>"+data[i].content.normal.text)154            expect(data[i].content.normal.additionalText).assertEqual("test_additionalText_otherApp");155            console.log("======Ans_GetAllActive_0300 getCallback text=======>"+data[i].content.normal.additionalText)156            expect(data[i].id).assertEqual(2);157            console.log("============Ans_GetAllActive_0300 getCallback id============>"+data[i].id)158            expect(data[i].label).assertEqual("otherApp");159            console.log("============Ans_GetAllActive_0300 getCallback label=====>"+data[i].label)160        }161    }162163    /*164    * @tc.number: Ans_GetAllActive_0300165    * @tc.name: getAllActiveNotifications(callback: AsyncCallback<Array<NotificationRequest>>): void;166    * @tc.desc: Verify: After the current app and other apps publish two notifications, cancel the notifications167                of the current app, get all active notifications in the system(callback)168    */169    it('Ans_GetAllActive_0300', 0, async function (done) {170        console.debug("===============Ans_GetAllActive_0300 start==================>");171        await notify.cancelAll();172        var notificationRequestOfCurrentApp = {173            content:{174                contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,175                normal: {176                    title: "test_title_currentApp",177                    text: "test_text_currentApp",178                    additionalText: "test_additionalText_currentApp"179                },180            },181            id: 1,182            label: "currentApp_0300",183        }184        await notify.publish(notificationRequestOfCurrentApp);185        console.debug("===============Ans_GetAllActive_0300 publish CurrentApp notify end==================>");186        await notify.cancel(1, "currentApp_0300");187        notify.getAllActiveNotifications(getAllCallbackThree);188        console.debug("===============Ans_GetAllActive_0300 getAllActiveNotifications end==================>");189        setTimeout(function(){190            console.debug("===============Ans_GetAllActive_0300 setTimeout==================>");191            done();192        }, time);193    })194195    /*196    * @tc.number: Ans_GetAllActive_0400197    * @tc.name: getAllActiveNotifications(): Promise<Array<NotificationRequest>>;198    * @tc.desc: Verify: after publishing two notifications,199                cancel one of the notifications, get all active notifications info(promise)200    */201    it('Ans_GetAllActive_0400', 0, async function (done) {202        console.debug("===============Ans_GetAllActive_0400 start==================>");203        await notify.cancelAll();204        var notificationRequestOfCurrentApp = {205            content:{206                contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,207                normal: {208                    title: "test_title_currentApp",209                    text: "test_text_currentApp",210                    additionalText: "test_additionalText_currentApp"211                },212            },213            id: 1,214            label: "currentApp_0400",215        }216        await notify.publish(notificationRequestOfCurrentApp);217        console.debug("===============Ans_GetAllActive_0400 publish CurrentApp notify end==================>");218        await notify.cancel(1, "currentApp_0400");219        console.debug("===============Ans_GetAllActive_0400 cancel end==================>");220        var promiseData = await notify.getAllActiveNotifications();221        var i;222        for (i = 0; i < promiseData.length; i++) {223            expect(promiseData[i].content.normal.title).assertEqual("test_title_otherApp");224            console.log("=======Ans_GetAllActive_0400 title=====>"+promiseData[i].content.normal.title)225            expect(promiseData[i].content.normal.text).assertEqual("test_text_otherApp");226            console.log("=======Ans_GetAllActive_0400 text========>"+promiseData[i].content.normal.text)227            expect(promiseData[i].content.normal.additionalText).assertEqual("test_additionalText_otherApp");228            console.log("===Ans_GetAllActive_0400 text====>"+promiseData[i].content.normal.additionalText)229            expect(promiseData[i].id).assertEqual(2);230            console.log("============Ans_GetAllActive_0400 id============>"+promiseData[i].id)231            expect(promiseData[i].label).assertEqual("otherApp");232            console.log("============Ans_GetAllActive_0400 label=====>"+promiseData[i].label)233        }234        console.debug("===============Ans_GetAllActive_0400 getAllActiveNotifications end==================>");235        setTimeout(function(){236            console.debug("===============Ans_GetAllActive_0400 setTimeout==================>");237            done();238        }, time);239    })240241    function getAllCallbackFive(err, data){242        console.log("Ans_GetAllActive_0500 getAllCallbackFive data.length============>"+data.length);243        console.log("Ans_GetAllActive_0500 getAllCallbackFive data============>"+JSON.stringify(data));244        expect(data.length).assertEqual(0);245    }246    /*247    * @tc.number: Ans_GetAllActive_0500248    * @tc.name: getAllActiveNotifications(callback: AsyncCallback<Array<NotificationRequest>>): void;249    * @tc.desc: Verify: After the current app and other apps publish two notifications, remove all the notifications250                of the system, get all active notifications in the system(callback)251    */252    it('Ans_GetAllActive_0500', 0, async function (done) {253        console.debug("===============Ans_GetAllActive_0500 start==================>");254        await notify.cancelAll();255        var notificationRequestOfCurrentApp = {256            content:{257                contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,258                normal: {259                    title: "test_title_currentApp",260                    text: "test_text_currentApp",261                    additionalText: "test_additionalText_currentApp"262                },263            },264            id: 1,265            label: "currentApp_0500",266        }267        await notify.publish(notificationRequestOfCurrentApp);268        console.debug("===============Ans_GetAllActive_0500 publish CurrentApp notify end==================>");269        await notify.removeAll();270        notify.getAllActiveNotifications(getAllCallbackFive);271        console.debug("===============Ans_GetAllActive_0500 getAllActiveNotifications end==================>");272        setTimeout(function(){273            console.debug("===============Ans_GetAllActive_0500 setTimeout==================>");274            done();275        }, time);276    })277278    /*279    * @tc.number: Ans_GetAllActive_0600280    * @tc.name: getAllActiveNotifications(): Promise<Array<NotificationRequest>>;281    * @tc.desc: Verify: After the current app and other apps publish two notifications, remove all the notifications282                of the system, get all active notifications in the system(promise)283    */284    it('Ans_GetAllActive_0600', 0, async function (done) {285        console.debug("===============Ans_GetAllActive_0600 start==================>");286        await notify.cancelAll();287        var notificationRequestOfCurrentApp = {288            content:{289                contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,290                normal: {291                    title: "test_title_currentApp",292                    text: "test_text_currentApp",293                    additionalText: "test_additionalText_currentApp"294                },295            },296            id: 1,297            label: "currentApp_0600",298        }299        await notify.publish(notificationRequestOfCurrentApp);300        console.debug("==========Ans_GetAllActive_0600 publish CurrentApp notify end==================>");301        await notify.removeAll();302        var promiseData = await notify.getAllActiveNotifications();303        expect(promiseData.length).assertEqual(0);304        console.debug("=======Ans_GetAllActive_0600 promiseData.length==========>"+promiseData.length);305        console.debug("=======Ans_GetAllActive_0600 promiseData==========>"+JSON.stringify(promiseData));306        setTimeout(function(){307            console.debug("===============Ans_GetAllActive_0600 setTimeout==================>");308            done();309        }, time);310    })311312    function getAllCallbackSeven(err, data){313        console.log("Ans_GetAllActive_0700 getAllCallbackSeven  data.length============>"+data.length);314        console.log("Ans_GetAllActive_0700 getAllCallbackSeven  data============>"+JSON.stringify(data));315        expect(data.length).assertEqual(0);316    }317    /*318    * @tc.number: Ans_GetAllActive_0700319    * @tc.name: getAllActiveNotifications(callback: AsyncCallback<Array<NotificationRequest>>): void;320    * @tc.desc: Verify:No active notifications in the system, get all active notifications in the system(callback)321    */322    it('Ans_GetAllActive_0700', 0, async function (done) {323        console.debug("===============Ans_GetAllActive_0700 start==================>");324        await notify.removeAll();325        notify.getAllActiveNotifications(getAllCallbackSeven);326        console.debug("===============Ans_GetAllActive_0700 getAllActiveNotifications end==================>");327        setTimeout(function(){328            console.debug("===============Ans_GetAllActive_0700 setTimeout==================>");329            done();330        }, time);331    })332333    /*334    * @tc.number: Ans_GetAllActive_0800335    * @tc.name: getAllActiveNotifications(): Promise<Array<NotificationRequest>>;336    * @tc.desc: Verify: No active notifications in the system, get all active notifications in the system(promise)337    */338    it('Ans_GetAllActive_0800', 0, async function (done) {339        console.debug("==========Ans_GetAllActive_0800 start==================>");340        await notify.removeAll();341        var promiseData = await notify.getAllActiveNotifications();342        console.debug("=========Ans_GetAllActive_0800 promiseData.length=============>"+promiseData.length);343        expect(promiseData.length).assertEqual(0);344        setTimeout(function(){345            console.debug("===============Ans_GetAllActive_0800 setTimeout==================>");346            done();347        }, time);348    })349})
...

Full Screen

Full Screen

sort.js

Source:sort.js Github

copy

Full Screen

1/*2Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.3For licensing, see LICENSE.html or http://ckeditor.com/license4*/5jQuery(document).ready(function() {6    function Tools(event, ui) {7        //outer loop for rows8        var tools = "[\n";9        rows = jQuery("#groupLayout div.sortableListDiv").length;10        jQuery.each(jQuery("#groupLayout div.sortableListDiv"), function(rowIndex, rowValue) {11            if (jQuery("li",rowValue).length > 0) {12                tools = tools + "    [";13            }14            //inner loop for toolbar buttons15            jQuery.each(jQuery("li",rowValue), function(buttonIndex, buttonValue) {16                if (jQuery(buttonValue).hasClass('spacer')) {17                    tools = tools + ",'-'";18                }19                else if (jQuery(buttonValue).hasClass('group')) {20                    tools = tools + "],\n    [";21                }22                else {23                    tools = tools + ",'" + jQuery(buttonValue).attr('id') + "'" ;24                }25            });26            if (jQuery("li" ,rowValue).length > 0) {27                if (rowIndex < (rows -1)) {28                    tools = tools + "],\n    '/',\n";29                }30                else {31                    tools = tools + "]\n";32                }33            }34        });35        tools = tools + "]";36        tools = tools.replace(/\[,/g, '[');37        tools = tools.replace(/\[],/g, '');38        jQuery("#edit-toolbar").attr('value', tools);39    }40    Drupal.ckeditorToolbaInit = function() {41        Drupal.ckeditorToolbarUsedRender();42        Drupal.ckeditorToolbarAllRender();43        var firefox = navigator.userAgent.toLowerCase().match(/firefox\/[0-9]\./);44        jQuery(".sortableList").sortable({45            connectWith: ".sortableList",46            items: "div.sortableListDiv",47            sort: function(event, ui) {48                if (firefox){49                    ui.helper.css({'top' : ui.position.top - 35 + 'px'});50                }51            },52            stop: function(event, ui) {53                Tools(event, ui);54            }55        }).disableSelection();56        jQuery(".sortableRow").sortable({57            connectWith: ".sortableRow",58            items: "li.sortableItem",59            sort: function(event, ui) {60                if (firefox){61                    ui.helper.css({'top' : ui.position.top - 35 + 'px'});62                }63            },64            stop: function(event, ui) {65                Tools(event, ui);66            }67        }).disableSelection();68        jQuery("li.sortableItem").mouseover(function(){69            jQuery(".sortableList").sortable("disable");70        });71        jQuery("li.sortableItem").mouseout(function(){72            jQuery(".sortableList").sortable("enable");73        });74    }75    Drupal.ckeditorToolbarReload = function() {76        jQuery(".sortableList").sortable('destroy');77        jQuery(".sortableRow").sortable('destroy');78        jQuery("li.sortableItem").unbind();79        Drupal.ckeditorToolbaInit();80    }81    Drupal.ckeditorToolbarUsedRender = function() {82        var toolbar = jQuery('#edit-toolbar').val();83        toolbar = eval(toolbar);84        var html = '<div class="sortableListDiv"><span class="sortableListSpan"><ul class="sortableRow">';85        var group = false;86        for (var row in toolbar) {87            if (typeof toolbar[row] == 'string' && toolbar[row] == '/') {88                group = false;89                html += '</ul></span></div><div class="sortableListDiv"><span class="sortableListSpan"><ul class="sortableRow">';90            }91            else {92                if (group == false){93                    group = true;94                }95                else {96                    html += '<li class="sortableItem group"><img src="' + Drupal.settings.cke_toolbar_buttons_all['__group']['icon'] + '" alt="group" title="group" /></li>';97                }98                for (var button in toolbar[row]) {99                    if (toolbar[row][button] == '-') {100                        html += '<li class="sortableItem spacer"><img src="' + Drupal.settings.cke_toolbar_buttons_all['__spacer']['icon'] + '" alt="spacer" title="spacer" /></li>';101                    }102                    else if (Drupal.settings.cke_toolbar_buttons_all[toolbar[row][button]]) {103                        html += '<li class="sortableItem" id="' + Drupal.settings.cke_toolbar_buttons_all[toolbar[row][button]]['name'] + '"><img src="' + Drupal.settings.cke_toolbar_buttons_all[toolbar[row][button]]['icon'] + '" alt="' + Drupal.settings.cke_toolbar_buttons_all[toolbar[row][button]]['title'] + '" title="' + Drupal.settings.cke_toolbar_buttons_all[toolbar[row][button]]['title'] + '" /></li>';104                    }105                }106            }107        }108        html += '</ul></span></div>';109        jQuery('#groupLayout').empty().append(html);110    }111    Drupal.ckeditorToolbarAllRender = function() {112        var toolbarUsed = jQuery('#edit-toolbar').val();113        var toolbarAll = Drupal.settings.cke_toolbar_buttons_all;114        var htmlArray = new Array();115        var html = '';116        for (var i in toolbarAll) {117            if (new RegExp("\'[\s]*" + toolbarAll[i].name + "[\s]*\'").test(toolbarUsed) == false) {118                if (toolbarAll[i].name == false) continue;119                if (typeof htmlArray[toolbarAll[i].row] == 'undefined') htmlArray[toolbarAll[i].row] = '';120                htmlArray[toolbarAll[i].row] += '<li class="sortableItem" id="' + toolbarAll[i].name + '"><img src="' + toolbarAll[i].icon + '" alt="' + toolbarAll[i].title + '" title="' + toolbarAll[i].title + '" /></li>';121            }122        }123        if (typeof htmlArray[5] == 'undefined') htmlArray[5] = '';124        htmlArray[5] += '<li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li><li class="sortableItem group"><img src="' + toolbarAll['__group'].icon + '" alt="' + toolbarAll['__group'].title + '" title="' + toolbarAll['__group'].title + '" /></li>';125        if (typeof htmlArray[6] == 'undefined') htmlArray[6] = '';126        htmlArray[6] += '<li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li><li class="sortableItem spacer"><img src="' + toolbarAll['__spacer'].icon + '" alt="' + toolbarAll['__spacer'].title + '" title="' + toolbarAll['__spacer'].title + '" /></li>';127        if (typeof htmlArray[7] == 'undefined') htmlArray[7] = '';128        for (var j in htmlArray){129            html += '<div class="sortableListDiv"><span class="sortableListSpan"><ul class="sortableRow">' + htmlArray[j] + '</ul></span></div>';130        }131        jQuery('#allButtons').empty().append(html);132    }133    Drupal.ckeditorToolbaInit();...

Full Screen

Full Screen

solution.js

Source:solution.js Github

copy

Full Screen

1'use strict'; /*jslint node:true*/2/* Description:3 * Algo is trying to calculate op values by used offers.4 * After that, using values with best cost (for op) calculate offers cost for opp.5 * In the end, search optimal offer for me and op.6 *7 * In details:8 * combine_values, combine_offers, get_ind are support methods.9 * combine_values used to get array with all possible values for provided counts.10 * combine_offer does the same for offers.11 * get_ind search array index in array of arrays. Used to search in values and offers arrays.12 *13 * init_op_costs, update_op_costs, recalc_op_offers_cost main methods to predict op values and offers cost.14 * init_op_costs - with first op offer init op values array. Calculate cost for this offer and find max value.15 * update_op_costs - every next op offer updates values array.16 * recalc_op_offers_cost - simply creates op offers cost array, using predicted values array (max values only).17 *18 * get_best_offer_ind - main method for searching offers.19 * Algo is greedy before last trading round. At last trading round op offer can cost not more than +1 to me.20 * Also at last trading round algo can change offer to op_best_offer_ind (op offer with maximum cost for me seen during21 * trading rounds). Harder to exploit me.22 *23 * I think, that's all. :-) Good luck!24 */25module.exports = class Agent {26  constructor(me, counts, values, max_rounds, log) {27    this.me = me;28    this.counts = counts;29    this.values = values;30    this.max_rounds = max_rounds;31    this.rounds = max_rounds;32    this.log = log;33    this.total = 0;34    for (let i = 0; i<counts.length; i++)35        this.total += counts[i]*values[i];36    // get all possible values (total the same for both)37    this.all_values = [];38    this.combine_values([], 0, 0);39    this.values_ind_me = this.get_ind(this.all_values, this.values);40    this.used_offers_ind = [];41    this.op_best_offer_ind = 0;42    this.my_last_offer_ind = 0;43    // get all possible offers44    this.all_offers = [];45    this.combine_offers([], 0);46    this.all_offers_cost_me = [];47    for (let i = 0; i < this.all_offers.length; i++) {48      this.all_offers_cost_me.push(0);49      for (let j = 0; j < this.counts.length; j++) {50        this.all_offers_cost_me[i] += this.values[j] * this.all_offers[i][j];51      }52    }53  }54  offer(o) {55    this.rounds--;56    if (o) {57      this.offer_ind = this.get_ind(this.all_offers, o);58      // accept on last round anything with cost59      if (this.me == 1 && this.rounds == 0 && this.all_offers_cost_me[this.offer_ind] >= 1)60        return;61      62      if (!this.all_offers_cost_op)63        this.init_op_costs(o);64      else65        this.update_op_costs(o);66      if (this.all_offers_cost_me[this.offer_ind] >= this.all_offers_cost_me[this.op_best_offer_ind])67        this.op_best_offer_ind = this.offer_ind;68    }69    var my_offer = this.get_best_offer_ind();70    // accept if current offer not worse then founded for the last trading round only (harder to exploit me)71    if (((this.me == 0 && this.rounds == 0) || (this.me == 1 && this.rounds == 1))72      && this.all_offers_cost_me[this.offer_ind] >= this.all_offers_cost_me[my_offer]) {73      return;74    }75    if (this.used_offers_ind.indexOf(this.offer_ind) == -1)76      this.used_offers_ind.push(this.offer_ind);77    if (this.used_offers_ind.indexOf(my_offer) == -1)78      this.used_offers_ind.push(my_offer);79    this.my_last_offer_ind = my_offer;80    return this.all_offers[this.my_last_offer_ind];81  }82  get_best_offer_ind() {83    for (let cost = this.total; cost > 0; cost--) {84      // 1 - exclude "you get everyting", -1 for exclude "want everything" offers85      for (let i = 1; i < this.all_offers.length - 1; i++) {86        if (this.all_offers_cost_me[i] == cost && this.used_offers_ind.indexOf(i) == -1) {87          var op_max_ind = i;88          // maximize cost for op with same cost for me89          if (this.all_offers_cost_op) {90            for (let j = 0; j < this.all_offers.length - 1; j++) {91              if (this.used_offers_ind.indexOf(j) == -192                && this.all_offers_cost_me[j] == this.all_offers_cost_me[i]93                && this.all_offers_cost_op[j] >= this.all_offers_cost_op[i])94                op_max_ind = j;95              }96          }97          if (this.my_last_offer_ind != 0) {98            if (this.all_offers_cost_me[op_max_ind] >= this.all_offers_cost_me[this.my_last_offer_ind]99              && this.all_offers_cost_op[op_max_ind] <= this.all_offers_cost_op[this.my_last_offer_ind])100              break;101            // before last offer doesn't decrease cost for me more then for op102            var decrease = 0;103            if ((this.me == 0 && this.rounds == 0) || (this.me == 1 && this.rounds == 1))104              decrease = 1;105            if (this.all_offers_cost_me[op_max_ind] < this.all_offers_cost_op[op_max_ind] - decrease)106              op_max_ind = this.my_last_offer_ind;107            // on last trading round change offer by op best offer if cost is not worse108            if (this.op_best_offer_ind != 0109              && ((this.me == 0 && this.rounds == 0) || (this.me == 1 && this.rounds == 1))110              && this.all_offers_cost_me[op_max_ind] <= this.all_offers_cost_me[this.op_best_offer_ind]) {111              op_max_ind = this.op_best_offer_ind;112            }113          }114          return op_max_ind;115        }116      }117    }118    // can't find possible offer with cost > 0119    return this.my_last_offer_ind;120  }121  init_op_costs(o) {122    this.all_values_cost_op = [];123    this.all_values_cost_op_max_ind = 0;124    for (let i = 0; i < this.all_values.length; i++) {125      this.all_values_cost_op.push(0);126      if (i == this.values_ind_me)127        continue;128      for (let j = 0; j < o.length; j++) {129        if (this.all_values[i][j] == 0 && o[j] == 0) {130          this.all_values_cost_op[i] = 0;131          break;132        }133        this.all_values_cost_op[i] += this.all_values[i][j] * (this.counts[j] - o[j]);134      }135      if (this.all_values_cost_op[i] > this.all_values_cost_op[this.all_values_cost_op_max_ind])136        this.all_values_cost_op_max_ind = i;137    }138    this.recalc_op_offers_cost();139  }140  update_op_costs(o) {141    this.all_values_cost_op_max_ind = 0;142    for (let i = 0; i < this.all_values.length; i++) {143      if (i == this.values_ind_me)144        continue;145      var sum = 0;146      for (let j =0; j < o.length; j++) {147        if (this.all_values[i][j] == 0 && o[j] == 0 && this.counts[j] > 1) {148          sum = 0; 149          break;150        }151        sum += this.all_values[i][j] * (this.counts[j] - o[j]);152      }153      this.all_values_cost_op[i] = (this.all_values_cost_op[i] + sum) / 2;154      if (this.all_values_cost_op[i] > this.all_values_cost_op[this.all_values_cost_op_max_ind])155        this.all_values_cost_op_max_ind = i;156    }157    this.recalc_op_offers_cost();158  }159  recalc_op_offers_cost() {160    this.possible_values_op = [];161    for (let i = 0; i < this.all_values_cost_op.length; i++) {162      if (this.all_values_cost_op[i] >= this.all_values_cost_op[this.all_values_cost_op_max_ind] - 2) {163        this.possible_values_op.push(this.all_values[i]);164      }165    }166    this.all_offers_cost_op = [];167    for (let i = 0; i < this.all_offers.length; i++) {168      this.all_offers_cost_op.push(0);169      for (let k = 0; k < this.possible_values_op.length; k++) {170        for (let j = 0; j < this.counts.length; j++) {171          this.all_offers_cost_op[i] += this.possible_values_op[k][j] * (this.counts[j] - this.all_offers[i][j]);172        }173      }174      this.all_offers_cost_op[i] /= this.possible_values_op.length;175    }176  }177  /* get index in array of arrays */178  get_ind(array_ext, array_int) {179    for (let i = 0; i < array_ext.length; i++) {180      var found = 1;181      for (let j = 0; j < this.counts.length; j++) {182        if (array_ext[i][j] != array_int[j]) {183          found = 0;184          break;185        }186      }187      if (found == 1) {188        return i;189      }190    }191  }192  /* collect all possible values combinations (total the same) */193  combine_values(val, sum, index) {194    if (index == this.counts.length) {195      this.all_values.push(val);196    }197    for (let i = 0; i <= (this.total - sum)/this.counts[index]; i++) {198      var val2 = val.slice();199      if (index == this.counts.length - 1) {200        i = (this.total - sum)/this.counts[index];201        if (i !== Math.floor(i)) //not natural number202          break;203      }204      val2.push(i);205      this.combine_values(val2, sum + i * this.counts[index], index + 1);206    }207  }208  /* collect all possible offers combinations */209  combine_offers(val, index) {210    if (index == this.counts.length) {211      this.all_offers.push(val);212    }213    for (let i = 0; i <= this.counts[index]; i++) {214      var val2 = val.slice();215      val2.push(i);216      this.combine_offers(val2, index + 1);217    }218  }...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

1angular.module('19kdic.utils', [])2.factory('common', ['$rootScope', function($rootScope) {3  return {4    convertNumber: function(text) {5      var numberMap = {6        '0': '٠',7        '1': '١',8        '2': '٢',9        '3': '٣',10        '4': '٤',11        '5': '٥',12        '6': '٦',13        '7': '٧',14        '8': '٨',15        '9': '٩',16      };17      angular.forEach(numberMap, function(value, key) {18        text = text.replaceAll(key, value);19      });20      return text;21    },22    getRawQuery: function(query) {23      return query.trim().replaceAll("  ", " ").replaceAll("ی", "ي").replaceAll("ک", "ك");24    },25    getCleanQuery: function(query) {26      return query.trim().replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, " ").replaceAll("  ", " ").trim().replace(/^[ء]+|[ء]+$/g, "")27        .replaceAll("ي", "ی").replaceAll("ك", "ک")28        .replaceAll("آ", "ا").replaceAll("إ", "ا").replaceAll("أ", "ا").replaceAll("ٱ", "ا")29        .replaceAll("َ", "").replaceAll("ُ", "").replaceAll("ِ", "")30        .replaceAll("ً", "").replaceAll("ٌ", "").replaceAll("ٍ", "")31        .replaceAll("ّ", "").replaceAll("ْ", "")32        .replaceAll("ة", "ه").replaceAll("ۀ", "ه")33        .replaceAll("ء", "ی").replaceAll("ؤ", "و").replaceAll("ئ", "ی");34    },35    simpleLookup: function(rawQuery, cleanQuery, limit) {36      var allMatches = $rootScope.db({37        key: {38          leftnocase: cleanQuery39        }40      }).order("word");41      return allMatches.limit(limit).get();42    },43    unorderedLookup: function(rawQuery, cleanQuery, limit) {44      var allMatches = $rootScope.db({45        key: {46          likenocase: cleanQuery47        }48      }).order("word").limit(limit);49      return allMatches.get();50    },51    orderedLookup: function(rawQuery, cleanQuery, limit) {52      var partialMatches = $rootScope.db({53        key: {54          likenocase: cleanQuery55        }56      }).order("word").limit(limit);57      var exactMatches = $rootScope.db({58        word: {59          leftnocase: rawQuery60        }61      }).order("word").limit(limit);62      var allMatches = exactMatches.get();63      var words = $.map(allMatches, function(r, i) {64        return r.word;65      });66      partialMatches.each(function(record, recordnumber) {67        if (words.indexOf(record.word) == -1) {68          allMatches.push(record);69        }70      });71      return allMatches;72    },73    lookup: function(query, limit) {74      if (!limit) {75        limit = 50;76      }77      var rawQuery = this.getRawQuery(query);78      var cleanQuery = this.getCleanQuery(query);79      if (cleanQuery.length == 0) {80        return []81      } else if (cleanQuery.length < 3 || $rootScope.lightVersion) {82        return this.simpleLookup(rawQuery, cleanQuery, limit);83      } else {84        return this.orderedLookup(rawQuery, cleanQuery, limit);85      }86    },87    getWord: function(id) {88      return $rootScope.words[id];89    },90    getMeanings: function(id) {91      var _this = this;92      var lastParenthese = 0;93      var meanings = $rootScope.meanings[id];94      $.each(meanings.split(""), function(i, m) {95        if (m == "(") {96          lastParenthese = i;97        } else if (m == ")") {98          meanings = meanings.substr(0, lastParenthese) + meanings.substring(lastParenthese, i).replaceAll("-", "،") + meanings.substr(i);99        }100      });101      meanings = $.map(meanings.replaceAll("(", "-(").split("-"), function(m, i) {102        return _this.convertNumber(m.trim().replaceAll("  ", " ").replace(/^[\.]+|[\.]+$/g, ""));103      });104      return meanings;105    },106    getWordLink: function(word, queryWordId) {107      if (word.length < 3) {108        return word;109      }110      var cleanWord = this.getCleanQuery(word);111      var results = $rootScope.db({112        key: cleanWord113      });114      if (results.count() && results.first().id != parseInt(queryWordId)) {115        return '<a href="#/app/search/' + results.first().id + '"><strong>' + word + '</strong></a>';116      } else {117        return word;118      }119    }120  }121}])122.factory('localStorage', ['$window', function($window) {123  return {124    set: function(key, value) {125      $window.localStorage[key] = value;126    },127    get: function(key, defaultValue) {128      return $window.localStorage[key] || defaultValue;129    },130    remove: function(key) {131      delete $window.localStorage[key];132    },133    setObject: function(key, value) {134      $window.localStorage[key] = JSON.stringify(value);135    },136    getObject: function(key) {137      return JSON.parse($window.localStorage[key] || '{}');138    },139    setTiedObject: function(key, value) {140      var obj = this.getObject(key) || {};141      var apiKey = this.get('api_key');142      obj[apiKey] = value;143      this.setObject(key, obj);144    },145    getTiedObject: function(key, value) {146      var obj = this.getObject(key) || {};147      return obj[value];148    }149  }150}]);151String.prototype.replaceAll = function(search, replace) {152  search = new RegExp(search.replace(".", "\\.").replace("(", "\\(").replace(")", "\\)"), "g");153  return this.replace(search, replace);154}155String.prototype.trim = function() {156  return $.trim(this);...

Full Screen

Full Screen

allDayText.js

Source:allDayText.js Github

copy

Full Screen

1describe('allDayText', function() {2	beforeEach(function() {3		affix('#cal');4	});5	describe('when allDaySlots is not set', function() {6		describe('in agendaWeek', function() {7			it('should default allDayText to using \'all-day\'', function() {8				var options = {9					defaultView: 'agendaWeek'10				};11				$('#cal').fullCalendar(options);12				var allDayText = $('.fc-day-grid > .fc-row > .fc-bg .fc-axis').text();13				expect(allDayText).toEqual('all-day');14			});15		});16		describe('in agendaDay', function() {17			it('should default allDayText to using \'all-day\'', function() {18				var options = {19					defaultView: 'agendaDay'20				};21				$('#cal').fullCalendar(options);22				var allDayText = $('.fc-day-grid > .fc-row > .fc-bg .fc-axis').text();23				expect(allDayText).toEqual('all-day');24			});25		});26	});27	describe('when allDaySlots is set true', function() {28		describe('in agendaWeek', function() {29			it('should default allDayText to using \'all-day\'', function() {30				var options = {31					defaultView: 'agendaWeek',32					allDaySlot: true33				};34				$('#cal').fullCalendar(options);35				var allDayText = $('.fc-day-grid > .fc-row > .fc-bg .fc-axis').text();36				expect(allDayText).toEqual('all-day');37			});38		});39		describe('in agendaDay', function() {40			it('should default allDayText to using \'all-day\'', function() {41				var options = {42					defaultView: 'agendaDay',43					allDaySlot: true44				};45				$('#cal').fullCalendar(options);46				var allDayText = $('.fc-day-grid > .fc-row > .fc-bg .fc-axis').text();47				expect(allDayText).toEqual('all-day');48			});49		});50	});51	describe('when allDaySlots is set true and language is not default', function() {52		describe('in agendaWeek', function() {53			it('should use the language\'s all-day value', function() {54				var options = {55					defaultView: 'agendaWeek',56					allDaySlot: true,57					lang: 'pt-br'58				};59				$('#cal').fullCalendar(options);60				var allDayText = $('.fc-day-grid > .fc-row > .fc-bg .fc-axis').text();61				expect(allDayText).toEqual('dia inteiro');62			});63		});64		describe('in agendaDay', function() {65			it('should use the language\'s all-day value', function() {66				var options = {67					defaultView: 'agendaDay',68					allDaySlot: true,69					lang: 'pt-br'70				};71				$('#cal').fullCalendar(options);72				var allDayText = $('.fc-day-grid > .fc-row > .fc-bg .fc-axis').text();73				expect(allDayText).toEqual('dia inteiro');74			});75		});76	});77	describe('when allDaySlots is set true and allDayText is specified', function() {78		describe('in agendaWeek', function() {79			it('should show specified all day text', function() {80				var options = {81					defaultView: 'agendaWeek',82					allDaySlot: true,83					allDayText: 'axis-phosy'84				};85				$('#cal').fullCalendar(options);86				var allDayText = $('.fc-day-grid > .fc-row > .fc-bg .fc-axis').text();87				expect(allDayText).toEqual('axis-phosy');88			});89		});90		describe('in agendaDay', function() {91			it('should show specified all day text', function() {92				var options = {93					defaultView: 'agendaDay',94					allDayText: 'axis-phosy'95				};96				$('#cal').fullCalendar(options);97				var allDayText = $('.fc-day-grid > .fc-row > .fc-bg .fc-axis').text();98				expect(allDayText).toEqual('axis-phosy');99			});100		});101	});...

Full Screen

Full Screen

data.js

Source:data.js Github

copy

Full Screen

1import { deleteAllCarts } from './carts'2import {3  deleteAllCategories,4  importCategories5} from './categories'6import { deleteChannels, importChannels } from './channels'7import { deleteStores, importStores } from './stores'8import {9  deleteAllCustomers,10  deleteCustomerGroups,11  importCustomerGroups,12  importCustomers13} from './customers'14import { deleteInventory } from './inventory'15import {16  deleteAllLineItemStates,17  importLineItemStates18} from './lineitem-states'19import {20  importProductStates,21  deleteAllProductStates22} from './product-states'23import { deleteAllOrders, importOrders } from './orders'24import {25  deleteAllProducts,26  importProductTypes,27  importProducts,28  deleteAllProductTypes29} from './products'30import {31  deleteAllShippingMethods,32  importShippingMethods33} from './shipping-method'34import {35  deleteTaxCategories,36  importTaxCategories37} from './tax-categories'38import { deleteTypes, importTypes } from './types'39import { deleteAllZones, importZones } from './zones'40import { importProjectData } from './project-setup'41const nconf = require('nconf')42const taskReducer = (result, fn) => result.then(fn)43const deleteAllData = () => {44  // eslint-disable-next-line no-console45  console.log('--Deleting all project data--')46  return [47    deleteAllProducts,48    deleteAllProductTypes,49    deleteAllCategories,50    deleteInventory,51    deleteAllOrders,52    deleteAllCarts,53    deleteAllLineItemStates,54    deleteAllProductStates,55    deleteAllCustomers,56    deleteCustomerGroups,57    deleteStores,58    deleteAllShippingMethods,59    deleteAllZones,60    deleteTaxCategories,61    deleteChannels,62    deleteTypes63  ].reduce(taskReducer, Promise.resolve())64}65const importAllData = () => {66  // eslint-disable-next-line no-console67  console.log('--Importing all project data--')68  return [69    importTypes,70    importChannels,71    importTaxCategories,72    importZones,73    importProjectData,74    importLineItemStates,75    importProductStates,76    importStores,77    importShippingMethods,78    importCustomerGroups,79    importCustomers,80    importCategories,81    importProductTypes,82    importProducts,83    // importing 150k inventory items takes too long84    //   it can be imported with npm run import:inventory85    // importInventory,86    importOrders87  ].reduce(taskReducer, Promise.resolve())88}89const deleteAndImport = () =>90  [deleteAllData, importAllData].reduce(91    taskReducer,92    Promise.resolve()93  )94if (nconf.get('all:clean')) {95  deleteAllData().then(() =>96    // eslint-disable-next-line no-console97    console.log('--The project data is deleted--')98  )99} else if (nconf.get('all:import')) {100  importAllData().then(() =>101    // eslint-disable-next-line no-console102    console.log('--All data is imported--')103  )104} else if (nconf.get('start')) {105  deleteAndImport().then(() =>106    // eslint-disable-next-line no-console107    console.log('--All data is imported--')108  )...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1angular.module('epaOei').service('mapLayers', function() {2  var layers = {3    r_pctlowwa : {4      $service : 'epaSldMapRpctLowWaLayer'5    },6    d3bpo3 : {7      $service : 'epaSldMapD3Bpo3Layer'8    },9    all_b_all : {10      $service : 'nciCountyCancerRateLayer'11    },12    bla_b_all : {13      $service : 'nciCountyCancerRateLayer',14      site : 'bla_b_all',15      state : '29010'16    },17    brs_f_all : {18      $service : 'nciCountyCancerRateLayer',19      site : 'brs_f_all',20      state : '26000',21    },22    c19_b_all : {23      $service : 'nciCountyCancerRateLayer',24      site : 'c19_b_all',25      state : '21100',26    },27    col_b_all : {28      $service : 'nciCountyCancerRateLayer',29      site : 'col_b_all',30      state : '21041-21052',31    },32    krp_b_all : {33      $service : 'nciCountyCancerRateLayer',34      site : 'krp_b_all',35      state : '29020',36    },37    leu_b_all : {38      $service : 'nciCountyCancerRateLayer',39      site : 'leu_b_all',40      state : '35011-35043'41    },42    lng_b_all : {43      $service : 'nciCountyCancerRateLayer',44      site : 'lng_b_all',45      state : '22030',46    },47    mel_b_all : {48      $service : 'nciCountyCancerRateLayer',49      site : 'mel_b_all',50      state : '25010',51    },52    nhl_b_all : {53      $service : 'nciCountyCancerRateLayer',54      site : 'nhl_b_all',55      state : '33041-33042',56    },57    pro_m_all : {58      $service : 'nciCountyCancerRateLayer',59      site : 'pro_m_all',60      state : '28010',61    },62    thy_b_all : {63      $service : 'nciCountyCancerRateLayer',64      site : 'thy_b_all',65      state : '32010',66    },67    ute_f_all : {68      $service : 'nciCountyCancerRateLayer',69      site : 'ute_f_all',70      state : '27030',71    },72    nata : {73      $service : 'epaNataLayer'74    },75    trinet : {76      $service : 'epaTrinetLayer',77    },78    hsa : {79      $service : 'hsaAccessToCareLayer'80    }81  };82  83  function getLayers() {84    return layers;85  }86  87  return {88    getLayers : getLayers89  }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var appium = require('appium');3var AppiumBaseDriver = require('appium-base-driver').AppiumBaseDriver;4var B = require('bluebird');5var driver = wd.promiseChainRemote('localhost', 4723);6var desired = {7};8var driver = new AppiumBaseDriver();9var session = driver.createSession(desired);10var el = session.elementByAccessibilityId('test');11var el2 = session.elementByAccessibilityId('test2');12B.all([el, el2]).then(function (els) {13  console.log(els);14});15var wd = require('wd');16var appium = require('appium');17var AppiumBaseDriver = require('appium-base-driver').AppiumBaseDriver;18var AppiumAndroidDriver = require('appium-android-driver').AndroidDriver;19var B = require('bluebird');20var driver = wd.promiseChainRemote('localhost', 4723);21var desired = {22};23var driver = new AppiumAndroidDriver();24var session = driver.createSession(desired);25var el = session.elementByAccessibilityId('test');26var el2 = session.elementByAccessibilityId('test2');27B.all([el, el2]).then(function (els) {28  console.log(els);29});30var wd = require('wd');31var appium = require('appium');32var AppiumBaseDriver = require('appium-base-driver').AppiumBaseDriver;33var AppiumiOSDriver = require('appium-ios-driver').IOSDriver;34var B = require('bluebird');35var driver = wd.promiseChainRemote('localhost', 4723);36var desired = {37};38var driver = new AppiumiOSDriver();39var session = driver.createSession(desired);

Full Screen

Using AI Code Generation

copy

Full Screen

1var AppiumBaseDriver = require('appium-base-driver');2var B = AppiumBaseDriver.B;3var Promise = require('bluebird');4var B = Promise;5B.all([promise1, promise2]).then(function () {6});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var Appium = require('appium');3var AppiumBaseDriver = require('appium-base-driver');4var desiredCaps = {5};6driver.init(desiredCaps);7var adb = new Appium.ADB();8var baseDriver = new AppiumBaseDriver();9var opts = {10};11var driver = new Appium.AndroidDriver();12driver.createSession(opts);13var B = require('bluebird');14var wd = require('wd');15var Appium = require('appium');16var AppiumBaseDriver = require('appium-base-driver');17var desiredCaps = {18};19driver.init(desiredCaps);20var adb = new Appium.ADB();21var baseDriver = new AppiumBaseDriver();22var opts = {23};24var driver = new Appium.AndroidDriver();25driver.createSession(opts);26B.all([driver.init(desiredCaps), driver.createSession(opts)]).then(function (res) {27  console.log('res', res);28});

Full Screen

Using AI Code Generation

copy

Full Screen

1const B = require('bluebird');2const AppiumBaseDriver = require('appium-base-driver');3class AppiumDriver extends AppiumBaseDriver {4}5const driver = new AppiumDriver();6const element = driver.findElement('id', 'some_id');7const elements = driver.findElements('id', 'some_id');8B.all([element, elements]).then((results) => {9});10const B = require('bluebird');11const AppiumBaseDriver = require('appium-base-driver');12class AppiumDriver extends AppiumBaseDriver {13}14const driver = new AppiumDriver();15const element = driver.findElement('id', 'some_id');16const elements = driver.findElements('id', 'some_id');17B.all([element, elements]).then((results) => {18});19const B = require('bluebird');20const AppiumBaseDriver = require('appium-base-driver');21class AppiumDriver extends AppiumBaseDriver {22}23const driver = new AppiumDriver();24const element = driver.findElement('id', 'some_id');25const elements = driver.findElements('id', 'some_id');26B.all([element, elements]).then((results) => {27});28const B = require('bluebird');29const AppiumBaseDriver = require('appium-base-driver');30class AppiumDriver extends AppiumBaseDriver {31}32const driver = new AppiumDriver();33const element = driver.findElement('id', 'some_id');34const elements = driver.findElements('id', 'some_id');35B.all([element, elements]).then((results) => {36});37const B = require('bluebird');38const AppiumBaseDriver = require('app

Full Screen

Using AI Code Generation

copy

Full Screen

1const B = require('appium-base-driver');2const A = require('./app.js');3var a = new A();4var b = new B();5var c = new B();6var d = new B();7var e = new B();8var f = new B();9var g = new B();10var h = new B();11var i = new B();12var j = new B();13var k = new B();14var l = new B();15var m = new B();16var n = new B();17var o = new B();18var p = new B();19var q = new B();20var r = new B();21var s = new B();22var t = new B();23var u = new B();24var v = new B();25var w = new B();26var x = new B();27var y = new B();28var z = new B();29var aa = new B();30var ab = new B();31var ac = new B();32var ad = new B();33var ae = new B();34var af = new B();35var ag = new B();36var ah = new B();37var ai = new B();38var aj = new B();39var ak = new B();40var al = new B();41var am = new B();42var an = new B();43var ao = new B();44var ap = new B();45var aq = new B();46var ar = new B();47var as = new B();48var at = new B();49var au = new B();50var av = new B();51var aw = new B();52var ax = new B();53var ay = new B();54var az = new B();55var ba = new B();56var bb = new B();57var bc = new B();58var bd = new B();59var be = new B();60var bf = new B();61var bg = new B();62var bh = new B();63var bi = new B();64var bj = new B();65var bk = new B();66var bl = new B();67var bm = new B();68var bn = new B();69var bo = new B();70var bp = new B();71var bq = new B();72var br = new B();73var bs = new B();74var bt = new B();75var bu = new B();76var bv = new B();77var bw = new B();78var bx = new B();79var by = new B();80var bz = new B();81var ca = new B();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var B = require('bluebird');3var asserters = wd.asserters;4var _ = require('lodash');5var caps = {6};7var driver = wd.promiseChainRemote('

Full Screen

Using AI Code Generation

copy

Full Screen

1var B = require('appium-base-driver');2var b = new B();3b.all('session', 'element', 1, 'click', 1, 2, 3, 4).then(function () {4  console.log('all method worked!');5});6async all (...args) {7  return await B.promisify(this.driver.apply)(this.driver, args);8}9helpers.promisify = function (fn) {10  return function () {11    let args = _.toArray(arguments);12    return new B((resolve, reject) => {13      args.push((err, res) => {14        if (err) {15          reject(err);16        } else {17          resolve(res);18        }19      });20      fn.apply(this, args);21    });22  };23};

Full Screen

Using AI Code Generation

copy

Full Screen

1var B=require('appium-base-driver');2var C=require('appium-support').util;3var b=new B();4var c=new C();5var d=b.all(c.hasValue('a'),c.hasValue('b'),c.hasValue('c'));6var e=b.all(c.hasValue('a'),c.hasValue('b'),c.hasValue('c'),c.hasValue('d'));7console.log(d);8console.log(e);9var B=require('appium-base-driver');10var b=new B();11var d=b.all(true,true,true);12var e=b.all(true,true,true,false);13console.log(d);14console.log(e);15var B=require('appium-base-driver');16var b=new B();17var d=b.all(true,true,true);18var e=b.all(true,true,true,false);19console.log(d);20console.log(e);21var B=require('appium-base-driver');22var b=new B();23var d=b.all(true,true,true);24var e=b.all(true,true,true,false);25console.log(d);26console.log(e);

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 Appium Base Driver 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