Best JavaScript code snippet using devicefarmer-stf
coq-packages.js
Source:coq-packages.js  
1"use strict";2class PackageManager {3    /**4     * Creates the packages UI and loading manager.5     *6     * @param {Element} panel_dom <div> element to hold the package entries7     * @param {object} packages an object containing package URLs and lists of 8     *   names in the format9     *   `{'base_uri1', ['pkg_name1', 'pkg_name2', ...], 'base_uri2': ...}`.10     * @param {object} pkg_path_aliases mnemonic for specific base URIs11     * @param {CoqWorker} coq reference to the Coq worker instance to send12     *   load requests to13     */14    constructor(panel_dom, packages, pkg_path_aliases, coq) {15        this.panel         = panel_dom;16        this.bundles       = {};17        this.loaded_pkgs   = [];18        this.coq           = coq;19        this.coq.observers.push(this);20        this.initializePackageList(packages, pkg_path_aliases);21    }22    /**23     * Creates CoqPkgInfo objects according to the paths in names in the given24     * `packages` object.25     * @param {object} packages (see constructor)26     * @param {object} aliases (ditto)27     */28    initializePackageList(packages, aliases={}) {29        this.packages = [];30        this.packages_by_name = {};31        this.packages_by_uri = {};32        // normalize all URI paths to end with a slash33        let mkpath = path => path && path.replace(/([^/])$/, '$1/');34        for (let [key, pkg_names] of Object.entries(packages)) {35            let base_uri = mkpath(aliases[key] || key);36            for (let pkg of pkg_names) {37                var uri = mkpath(aliases[`${key}/${pkg}`]) || base_uri;38                this.addPackage(new CoqPkgInfo(pkg, uri));39            }40        }41    }42    static defaultPkgPath() {43        return {44            'js': new URL('../coq-pkgs/', CoqWorker.scriptUrl).href,45            'wa': new URL('../bin/coq/', CoqWorker.defaultScriptPath()).href46        }[JsCoq.backend];47    }48    populate() {49        this.index = new PackageIndex();50        return Promise.all(this.packages.map(async pkg => {51            var manifest = await pkg.fetchInfo();52            if (manifest) this.addBundleInfo(pkg.name, manifest);53            else this.coqLibError(pkg.name);54        }));55    }56    addPackage(pkg) {57        this.packages.push(pkg);58        this.packages_by_name[pkg.name] = pkg;59        (this.packages_by_uri[pkg.base_uri] = 60            this.packages_by_uri[pkg.base_uri] || []).push(pkg.name);61    }62    getPackage(pkg_name) {63        var pkg = this.packages_by_name[pkg_name];64        if (!pkg) throw new Error(`internal error: unrecognized package '${pkg_name}'`);65        return pkg;66    }67    hasPackageInfo(pkg_name) {68        var pkg = this.packages_by_name[pkg_name];69        return pkg && pkg.info;70    }71    addRow(bname, desc = bname, parent) {72        var row = $('<div>').addClass('package-row').attr('data-name', bname)73            .append($('<button>').addClass('download-icon')74                    .attr('title', "Download package")75                    .on('click', () => { this.loadPkg(bname); }))76            .append($('<span>').addClass('desc').text(desc)77                    .on('click', () => { this._expandCollapseRow(row); }));78        if (parent) {79            parent.row.append(row);80        }81        else {82            // Find bundle's proper place in the order among existing entries83            var pkg_names = this.packages.map(p => p.name),84                place_before = null, idx = pkg_names.indexOf(bname);85            if (idx > -1) {86                for (let e of $(this.panel).children()) {87                    let eidx = pkg_names.indexOf($(e).attr('data-name'));88                    if (eidx == -1 || eidx > idx) {89                        place_before = e;90                        break;91                    }92                }93            }94            this.panel.insertBefore(row[0], place_before /* null == at end */ );95        }96        return this.bundles[bname] = { row };97    }98    addBundleInfo(bname, pkg_info, parent) {99        var bundle = this.addRow(bname, pkg_info.name, parent);100        var pkg = this.getPackage(bname);101        pkg.info = pkg_info;102        if (pkg_info.chunks) {103            pkg.chunks = [];104            for (let chunk of pkg_info.chunks) {105                var subpkg = new CoqPkgInfo(chunk.name, pkg.base_uri);106                subpkg.info = chunk;107                this.addPackage(subpkg);108                this.addBundleInfo(subpkg.name, chunk, bundle);109                pkg.chunks.push(subpkg);110                subpkg.parent = pkg;111            }112        }113        else {114            pkg.setArchive(pkg_info.archive);115        }116        if (pkg.archive) {117            pkg.archive.onProgress = evt => this.showPackageProgress(bname, evt);118        }119        else {120            /** @todo is this case even needed? */121            if (!pkg.chunks)122                throw new Error("packages without archives are obsolete");123        }124        this.index.add(pkg_info);125        this.dispatchEvent(new Event('change'));126    }127    async addBundleZip(bname, resource, pkg_info) {128        pkg_info = pkg_info || {};129        var archive = await new CoqPkgArchive(resource).load();130        return archive.getPackageInfo().then(pi => {131            bname = bname || pi.name;132            if (!bname) throw new Error('invalid archive: missing package manifest (coq-pkg.json)');133            if (this.packages_by_name[bname] && this.packages_by_name[bname].info)134                throw new Error(`package ${bname} is already present`);135            for (let k in pi)136                if (!pkg_info[k]) pkg_info[k] = pi[k];137            var pkg = new CoqPkgInfo(bname, '');138            this.packages.push(pkg);139            this.packages_by_name[bname] = pkg;140            this.addBundleInfo(bname, pkg_info);141            pkg.archive = archive;142            return pkg;143        });144    }145    waitFor(init_pkgs) {146        let all_set = () => init_pkgs.every(x => this.hasPackageInfo(x));147        return new Promise((resolve, reject) => {148            var observe = () => {149                if (all_set()) {150                    this.removeEventListener('change', observe);151                    resolve();152                    return true;153                }154            };155            if (!observe())156                this.addEventListener('change', observe);157            /** @todo reject the promise if there are no more packages whose infos are pending */158        });159    }160    getUrl(pkg_name, resource) {161        return this.packages_by_name[pkg_name].getUrl(resource);162    }163    getLoadPath() {164        switch (JsCoq.backend) {165        case 'js':166            return this.loaded_pkgs.map( pkg_name => {167                let pkg = this.getPackage(pkg_name),168                    phys = pkg.archive ? ['/lib'] : [];169                return pkg.info.pkgs.map( pkg => [pkg.pkg_id, phys] );170            }).flatten();171        case 'wa':172            return ['/lib'];173        }174    }175    showPackage(bname) {176        var bundle = this.bundles[bname];177        if (bundle && bundle.row) {178            bundle.row.parents('div.package-row').addClass('expanded');179            this._scrollTo(bundle.row[0]);180        }181    }182    _scrollTo(el) {183        if (el.scrollIntoViewIfNeeded) el.scrollIntoViewIfNeeded();184        else el.scrollIntoView();185    }186    /**187     * Updates the download progress bar on the UI.188     * @param {string} bname package bundle name189     * @param {object} info? {loaded: <number>, total: <number>}190     */191    showPackageProgress(bname, info) {192        var bundle = this.bundles[bname];193        if (!bundle.bar) {194            // Add the progress bar if it does not exist already195            bundle.bar = $('<div>').addClass('progressbar');196            bundle.egg = $('<div>').addClass('progress-egg');197            bundle.bar.append(bundle.egg);198            bundle.row.append($('<div>').addClass('rel-pos').append(bundle.bar));199        }200        if (info && info.total) {201            var progress = (info.downloaded || info.loaded) / info.total,202                angle    = (progress * 1500) % 360;203            bundle.egg.css('transform', `rotate(${angle}deg)`);204            bundle.bar.css('width', `${Math.min(1.0, progress) * 100}%`);205        }206    }207    /**208     * Marks the package download as complete, removing the progress bar.209     * @param {string} bname package bundle name210     */211    showPackageCompleted(bname) {212        var bundle = this.bundles[bname];213        bundle.row.children('.rel-pos').remove();214        bundle.row.children('button.download-icon').addClass('checked')215                  .attr('title', 'Downloaded');216        var pkg = this.getPackage(bname);217        pkg.status = 'loaded';218        if (pkg.parent) this.showLoadedChunks(pkg.parent);219    }220    showLoadedChunks(pkg) {221        var bundle = this.bundles[pkg.name];222        bundle.row.addClass('has-chunks');223        var span = bundle.row.find('.loaded-chunks');224        if (span.length === 0)225            span = $('<span>').addClass('loaded-chunks')226                              .insertAfter(bundle.row.children('.desc'));227        var prefix = pkg.name + '-',228            shorten = name => name.startsWith(prefix) ? 229                              name.substr(prefix.length) : name;230        span.empty();231        for (let chunk of pkg.chunks) {232            if (chunk.status === 'loaded')233                span.append($('<span>').text(shorten(chunk.name)));234        }235        if (pkg.chunks.every(chunk => chunk.status === 'loaded'))236            this.showPackageCompleted(pkg.name);237    }238    /**239     * Adds a package from a dropped file and immediately downloads it.240     * @param {Blob} file a dropped File or a Blob that contains an archive241     */242    dropPackage(file) {243        this.expand();244        this.addBundleZip(undefined, file).then(pkg => {245            this._scrollTo(this.bundles[pkg.name].row[0]);246            this.loadPkg(pkg.name);247        })248        .catch(err => { alert(`${file.name}: ${err}`); });249    }250    _packageByURL(url) {251        var s = this._absoluteURL(url);252        for (let pkg of this.packages) {253            if (pkg.archive && s == pkg.archive.url) return pkg.name;254        }255    }256    _absoluteURL(url) {257        return new URL(url, this.coq._worker_script).toString();258    }259    coqLibProgress(evt) {260        var pkg_name = this._packageByURL(evt.uri);261        if (pkg_name) {262            this.showPackageProgress(pkg_name, evt.download);263        }264    }265    coqLibLoaded(pkg) {266        var pkg_name = this._packageByURL(pkg) || pkg;267        this.loaded_pkgs.push(pkg_name);268        try {269            var pkg = this.getPackage(pkg_name);270            if (pkg._resolve) pkg._resolve();271            else pkg.promise = Promise.resolve();272            this.showPackageCompleted(pkg_name);273        }274        catch(e) { console.warn(e); }275    }276    coqLibError(pkg) {277        var pkg_name = this._packageByURL(pkg) || pkg;278        try {279            var pkg = this.getPackage(pkg_name),280                err = {msg: `error loading package '${pkg_name}'`};281            if (pkg._reject) pkg._reject(err);282            else pkg.promise = Promise.reject(err);283        }284        catch(e) { console.warn(e);  /* do we even care? */ }285    }286    /**287     * Loads a package from the preconfigured path.288     * @param {string} pkg_name name of package (e.g., 'init', 'mathcomp')289     * @param {boolean} show if `true`, the package is exposed in the list290     */291    loadPkg(pkg_name, show=true) {292        var pkg = this.getPackage(pkg_name), promise;293        if (pkg.promise) return pkg.promise;  /* load issued already */294        if (pkg.info.chunks) {295            promise = this.loadDeps(pkg.info.chunks.map(x => x.name), show);296        }297        else {298            promise = Promise.all([this.loadDeps(pkg.info.deps || [], show),299                                   this.loadArchive(pkg)]);300        }301        if (show) this.showPackage(pkg_name);302        pkg.promise = promise;303        return promise.then(() => pkg);304    }305    async loadDeps(deps, show=true) {306        await this.waitFor(deps);307        return Promise.all(308            deps.map(pkg => this.loadPkg(pkg, show)));309    }310    loadArchive(pkg) {311        switch (JsCoq.backend) {312        case 'js':313            return pkg.archive.unpack(this.coq)314                              .then(() => this.coqLibLoaded(pkg.name));315        case 'wa':316            return new Promise((resolve, reject) => {317                pkg._resolve = resolve; pkg._reject = reject;318                this.coq.loadPkg(pkg.getDownloadURL());319            });320        }321    }322    /**323     * Make all loaded packages unloaded.324     * This is called after the worker is restarted.325     * Does not drop downloaded/cached archives.326     */327    reset() {328        for (let pkg of this.packages) {329            delete pkg.promise;330        }331    }332    collapse() {333        this.panel.parentNode.classList.add('collapsed');334    }335    expand() {336        this.panel.parentNode.classList.remove('collapsed');337    }338    _expandCollapseRow(row) {339        row.toggleClass('expanded');340        if (row.hasClass('expanded')) {341            // account for CSS transition342            var anim = setInterval(() => row[0].scrollIntoViewIfNeeded(), 40);343            setTimeout(() => clearInterval(anim), 600);344        }345    }346    /**347     * (auxiliary method) traverses a graph spanned by a list of roots348     * and an adjacency functor. Implements DFS.349     * @param {array} roots starting points350     * @param {function} adjacent_out u => array of successors351     */352    _scan(roots, adjacent_out) {353        var collect = new Set(),354            work = roots.slice();355        while (work.length) {356            var u = work.pop();357            if (!collect.has(u)) {358                collect.add(u);359                for (let v of adjacent_out(u)) work.push(v);360            }361        }362        return collect;363    }364    // No portable way to create EventTarget instances of our own yet;365    // hijack the panel DOM element :\366    dispatchEvent(evt)             { this.panel.dispatchEvent(evt); }367    addEventListener(type, cb)     { this.panel.addEventListener(type, cb); }368    removeEventListener(type, cb)  { this.panel.removeEventListener(type, cb); }369}370/**371 * Holds list of modules in packages and resolves dependencies.372 */373class PackageIndex {374    constructor() {375        this.moduleIndex = new Map();376        this.intrinsicPrefix = "Coq";377    }378    add(pkgInfo) {379        if (JsCoq.backend === 'js')380            pkgInfo.modules = this._listModules(pkgInfo);381        for (let mod in pkgInfo.modules || {})382            this.moduleIndex.set(mod, pkgInfo);383    }384    _listModules(pkgInfo) {385        /** @todo for jsCoq; should put this in the manifest like in waCoq */386        var modules = {};387        for (let {pkg_id, vo_files} of pkgInfo.pkgs || []) {388            for (let [vo] of vo_files) {389                var mod = [...pkg_id, vo.replace(/[.]vo$/, '')].join('.');390                modules[mod] = {deps: (pkgInfo.modDeps || {})[mod] || []};391            }392        }393        return modules;394    }395    *findModules(prefix, suffix, exact=false) {396        if (Array.isArray(prefix)) prefix = prefix.join('.');397        if (Array.isArray(suffix)) suffix = suffix.join('.');398        if (exact) {399            prefix = prefix ? prefix + '.' : '';400            if (this.moduleIndex.has(prefix + suffix)) yield prefix + suffix;401        }402        else {403            var dotsuffix = '.' + suffix,404                dotprefix = (prefix || this.intrinsicPrefix) + '.';405            for (let k of this.moduleIndex.keys()) {406                if (!prefix && k == suffix ||407                        k.startsWith(dotprefix) && k.endsWith(dotsuffix))408                    yield k;409            }410        }411    }412    findPackageDeps(prefix, suffix, exact=false) {413        var pdeps = new Set();414        for (let m of this.alldeps(this.findModules(prefix, suffix, exact)))415            pdeps.add(this.moduleIndex.get(m).name);416        return pdeps;417    }418    alldeps(mods) {419        return closure(new Set(mods), mod => {420            let pkg = this.moduleIndex.get(mod),421                o = (pkg && pkg.modules || {})[mod];422            return (o && o.deps) || [];423        });424    }425    426}427// function closure<T>(s: Set<T>, tr: (t: T) => T[]) {428function closure(s, tr) {429    var wl = [...s];430    while (wl.length > 0) {431        var u = wl.shift();432        for (let v of tr(u))433            if (!s.has(v)) { s.add(v); wl.push(v); }434    }435    return s;436}437class CoqPkgInfo {438    constructor(name, base_uri) {439        this.name = name;440        this.base_uri = base_uri;441        this.info = undefined;442        this.archive = undefined;443        this.chunks = undefined;444        this.parent = undefined;445    }446    getUrl(resource) {447        // Generate URL with the package's base_uri as the base448        return new URL(resource, new URL(this.base_uri, location));449    }450    getDownloadURL() {451        // @todo create blob url for dropped files452        return this.archive && this.archive.url;453    }454    async fetchInfo(resource = `${this.name}.json`) {455        var req = await fetch(this.getUrl(resource));456        if (req.status == 200)457            return await req.json();458    }459    setArchive(resource = `${this.name}.coq-pkg`) {460        this.archive = new CoqPkgArchive(this.getUrl(resource));461    }462}463/**464 * Represents a bundle stored in a Zip archive; either a remote465 * file that has to be downloaded or a local one.466 */467class CoqPkgArchive {468    constructor(resource) {469        if (resource instanceof URL || typeof resource === 'string')470            this.url = resource;471        else if (resource instanceof Blob)472            this.blob = resource;473        else if (resource.file /* JSZip-like */)474            this.zip = resource;475        else476            throw new Error(`invalid resource for archive: '${resource}'`);477        this.onProgress = () => {};478    }479    load() {480        return this.zip ? Promise.resolve(this) :481            this.download().then(data =>482                JSZip.loadAsync(data)).then(zip =>483                    { this.zip = zip; return this; });484    }485    download() {486        if (this.blob) {487            return this.blob.arrayBuffer();488        }489        else {490            // Here comes some boilerplate491            return new Promise((resolve, reject) => {492                var xhr = new XMLHttpRequest();493                xhr.responseType = 'arraybuffer';494                xhr.onload = () => resolve(xhr.response);495                xhr.onprogress = (evt) => requestAnimationFrame(() => this.onProgress(evt));496                xhr.onerror = () => reject(new Error("download failed"));497                xhr.open('GET', this.url);498                xhr.send();499            });500        }501    }502    readManifest() {503        var manifest = this.zip.file('coq-pkg.json');504        return manifest ?505                manifest.async('text').then(data => JSON.parse(data))506                .catch(err => {507                    console.warn(`malformed 'coq-pkg.json' in bundle ${this.url || ''} (${err})`);508                    return {}; 509                })510              : Promise.resolve({});511    }512    getPackageInfo() {513        return this.readManifest().then(pkg_info => {514            var entries_by_dir = {};515            this.zip.forEach((rel_path, entry) => {516                var mo = /^(?:(.*)[/])(.*[.](?:vo|vio|cm[ao]))$/.exec(rel_path);517                if (mo) {518                    var [, dir, fn] = mo;519                    (entries_by_dir[dir] = entries_by_dir[dir] || []).push(fn);520                }521            });522            var pkgs = [];523            for (let dir in entries_by_dir) {524                pkgs.push({525                    pkg_id: dir.split('/'),526                    vo_files: entries_by_dir[dir].map(x => [x])527                });528            }529            pkg_info.pkgs = pkgs;530            return pkg_info;531        });532    }533    async unpack(worker) {534        await this.load();535        var asyncs = [];536        this.zip.forEach((rel_path, entry) => {537            if (!entry.dir)538                asyncs.push((async () => {539                    var content = await entry.async('arraybuffer');540                    await worker.put(`/lib/${rel_path}`, content, 541                            /*transferOwnership=*/true);542                })());543        });544        await Promise.all(asyncs);545    }546}547if (typeof document !== 'undefined' && document.currentScript)548    PackageManager.scriptUrl = new URL(document.currentScript.attributes.src.value, window.location);549if (typeof module !== 'undefined')550    module.exports = {CoqPkgArchive}551// Local Variables:552// js-indent-level: 4...Gruntfile.js
Source:Gruntfile.js  
1/*global module:false*/2module.exports = function(grunt) {3  var packageJSON = grunt.file.readJSON('package.json');4  var bumpFiles = ["package.json", "bower.json", "composer.json"];5  var commitFiles = bumpFiles.concat(["./dist/*"]);6  // Project configuration.7  grunt.initConfig({8    // Metadata9    pkg: packageJSON,10    // Task configuration.11    header: {12      dist: {13        options: {14          text: "/*! =======================================================\n                      VERSION  <%= pkg.version %>              \n========================================================= */"15        },16        files: {17          '<%= pkg.gruntConfig.dist.js %>': '<%= pkg.gruntConfig.temp.js %>',18          '<%= pkg.gruntConfig.dist.jsMin %>': '<%= pkg.gruntConfig.temp.jsMin %>',19          '<%= pkg.gruntConfig.dist.css %>': '<%= pkg.gruntConfig.temp.css %>',20          '<%= pkg.gruntConfig.dist.cssMin %>': '<%= pkg.gruntConfig.temp.cssMin %>'21        }22      }23    },24    uglify: {25      options: {26        preserveComments: 'some'27      },28      dist: {29        src: '<%= pkg.gruntConfig.temp.js %>',30        dest: '<%= pkg.gruntConfig.temp.jsMin %>'31      }32    },33    babel: {34      options: {35        presets: ['es2015']36      },37      dist: {38        src: '<%= pkg.gruntConfig.js.slider %>',39        dest: '<%= pkg.gruntConfig.temp.js %>'40      }41    },42    jshint: {43      ignore_warning: {44        options: {45          '-W099': true46        },47        src: '<%= pkg.gruntConfig.js.slider %>'48      },49      options: {50        esnext: true,51        curly: true,52        eqeqeq: true,53        immed: true,54        latedef: false,55        newcap: true,56        noarg: true,57        sub: true,58        undef: true,59        unused: true,60        boss: true,61        eqnull: true,62        browser: true,63        globals: {64          $ : true,65          Modernizr : true,66          console: true,67          define: true,68          module: true,69          require: true70        },71        "-W099": true72      },73      gruntfile: {74        src: 'Gruntfile.js'75      },76      js: {77        src: '<%= pkg.gruntConfig.js.slider %>'78      },79      spec : {80        src: '<%= pkg.gruntConfig.spec %>',81        options : {82          globals : {83            document: true,84            console: false,85            Slider: false,86            $: false,87            jQuery: false,88            _: false,89            _V_: false,90            afterEach: false,91            beforeEach: false,92            confirm: false,93            context: false,94            describe: false,95            expect: false,96            it: false,97            jasmine: false,98            JSHINT: false,99            mostRecentAjaxRequest: false,100            qq: false,101            runs: false,102            spyOn: false,103            spyOnEvent: false,104            waitsFor: false,105            xdescribe: false106          }107        }108      }109    },110    sasslint: {111      options: {112        configFile: './.sass-lint.yml',113      },114      target: ['./src/sass/**/*.scss']115    },116    lesslint: {117      src: ['./src/less/bootstrap-slider.less']118    },119    jasmine : {120      src : '<%= pkg.gruntConfig.temp.js %>',121      options : {122        specs : '<%= pkg.gruntConfig.spec %>',123        vendor : ['<%= pkg.gruntConfig.js.jquery %>', '<%= pkg.gruntConfig.js.bindPolyfill %>'],124        styles : ['<%= pkg.gruntConfig.css.bootstrap %>', '<%= pkg.gruntConfig.temp.css %>'],125        template : '<%= pkg.gruntConfig.tpl.SpecRunner %>'126      }127    },128    template : {129      'generate-index-page' : {130        options : {131          data : {132            js : {133              highlightjs: '<%= pkg.gruntConfig.js.highlightjs %>',134              modernizr : '<%= pkg.gruntConfig.js.modernizr %>',135              jquery : '<%= pkg.gruntConfig.js.jquery %>',136              slider : '<%= pkg.gruntConfig.temp.js %>'137            },138            css : {139              highlightjs: '<%= pkg.gruntConfig.css.highlightjs %>',140              bootstrap : '<%= pkg.gruntConfig.css.bootstrap %>',141              slider : '<%= pkg.gruntConfig.temp.css %>'142            }143          }144        },145        files : {146          'index.html' : ['<%= pkg.gruntConfig.tpl.index %>']147        }148      },149      'generate-gh-pages' : {150        options : {151          data : {152            js : {153              highlightjs: '<%= pkg.gruntConfig.js.highlightjs %>',154              modernizr : '<%= pkg.gruntConfig.js.modernizr %>',155              jquery : '<%= pkg.gruntConfig.js.jquery %>',156              slider : 'js/bootstrap-slider.js'157            },158            css : {159              highlightjs: '<%= pkg.gruntConfig.css.highlightjs %>',160              bootstrap : 'css/bootstrap.min.css',161              slider : 'css/bootstrap-slider.css'162            }163          }164        },165        files : {166          'index.html' : ['<%= pkg.gruntConfig.tpl.index %>']167        }168      }169    },170    watch: {171      options: {172        livereload: true173      },174      js: {175        files: '<%= pkg.gruntConfig.js.slider %>',176        tasks: ['jshint:js', 'babel', 'jasmine']177      },178      gruntfile: {179        files: '<%= jshint.gruntfile %>',180        tasks: ['jshint:gruntfile']181      },182      spec: {183        files: '<%= pkg.gruntConfig.spec %>',184        tasks: ['jshint:spec', 'jasmine:src']185      },186      css: {187        files: [188          '<%= pkg.gruntConfig.less.slider %>',189          '<%= pkg.gruntConfig.less.rules %>',190          '<%= pkg.gruntConfig.less.variables %>'191        ],192        tasks: ['less:development']193      },194      index: {195        files: '<%= pkg.gruntConfig.tpl.index %>',196        tasks: ['template:generate-index-page']197      }198    },199    connect: {200      server: {201        options: {202          port: "<%= pkg.gruntConfig.devPort %>"203        }204      }205    },206    open : {207      development : {208        path: 'http://localhost:<%= connect.server.options.port %>'209      }210    },211    less: {212      options: {213        paths: ["bower_components/bootstrap/less"]214      },215      development: {216        files: {217          '<%= pkg.gruntConfig.temp.css %>': '<%= pkg.gruntConfig.less.slider %>'218        }219      },220      production: {221        files: {222         '<%= pkg.gruntConfig.temp.css %>': '<%= pkg.gruntConfig.less.slider %>',223        }224      },225      "production-min": {226        options: {227          yuicompress: true228        },229        files: {230         '<%= pkg.gruntConfig.temp.cssMin %>': '<%= pkg.gruntConfig.less.slider %>'231        }232      }233    },234    clean: {235      dist: ["dist"],236      temp: ["temp"]237    },238    bump: {239      options: {240        files: bumpFiles,241        updateConfigs: [],242        commit: true,243        commitMessage: 'Release v%VERSION%',244        commitFiles: commitFiles,245        createTag: true,246        tagName: 'v%VERSION%',247        tagMessage: 'Version %VERSION%',248        push: false,249        pushTo: 'origin'250      }251    }252  });253  // These plugins provide necessary tasks.254  grunt.loadNpmTasks('grunt-contrib-uglify');255  grunt.loadNpmTasks('grunt-contrib-jshint');256  grunt.loadNpmTasks('grunt-contrib-jasmine');257  grunt.loadNpmTasks('grunt-contrib-watch');258  grunt.loadNpmTasks('grunt-contrib-connect');259  grunt.loadNpmTasks('grunt-contrib-clean');260  grunt.loadNpmTasks('grunt-contrib-less');261  grunt.loadNpmTasks('grunt-open');262  grunt.loadNpmTasks('grunt-template');263  grunt.loadNpmTasks('grunt-header');264  grunt.loadNpmTasks('grunt-bump');265  grunt.loadNpmTasks('grunt-babel');266  grunt.loadNpmTasks('grunt-sass-lint');267  grunt.loadNpmTasks('grunt-lesslint');268  // Create custom tasks269  grunt.registerTask('append-header', ['header', 'clean:temp']);270  grunt.registerTask('lint', [271    'jshint',272    'lesslint',273    'sasslint'274  ]);275  grunt.registerTask('test', [276    'babel',277    'less:development',278    'jasmine',279    'clean:temp'280  ]);281  grunt.registerTask('build', [282    'less:development',283    'test',284    'template:generate-index-page'285  ]);286  grunt.registerTask('build-gh-pages', [287    'less:development',288    'babel',289    'template:generate-gh-pages'290  ]);291  grunt.registerTask('dist', [292    'clean:dist',293    'less:production',294    'less:production-min',295    'babel',296    'uglify',297    'append-header'298  ]);299  grunt.registerTask('development', [300    'less:development',301    'babel',302    'template:generate-index-page',303    'connect',304    'open:development',305    'watch'306  ]);307  grunt.registerTask('production', ['dist']);308  grunt.registerTask('dev', 'development');309  grunt.registerTask('prod', 'production');310  grunt.registerTask('default', ['build']);...test.js
Source:test.js  
1'use strict';2require('mocha');3const fs = require('fs');4const path = require('path');5const assert = require('assert');6const writeJson = require('write-json');7const del = require('delete');8const Store = require('./');9const fixtures = path.resolve.bind(path, 'fixtures');10let pkg;11describe('store', function() {12  beforeEach(function() {13    return writeJson(fixtures('package.json'), {})14      .then(() => {15        pkg = new Store(fixtures());16      });17  });18  afterEach(function() {19    return del(fixtures());20  });21  describe('resolve store path', function() {22    it('should get a store at the given "cwd"', function() {23      return writeJson(fixtures('foo/package.json'), {})24        .then(() => {25          pkg = new Store(fixtures('foo'));26          pkg.set('foo', 'bar');27          assert.equal(path.basename(pkg.path), 'package.json');28          assert(pkg.data.hasOwnProperty('foo'));29          assert.equal(pkg.data.foo, 'bar');30          assert(fs.existsSync('fixtures/foo/package.json'));31        });32    });33    it('should get a store at the given "options.path"', function() {34      return writeJson(fixtures('foo/bar.json'), {})35        .then(() => {36          pkg = new Store({path: fixtures('foo/bar.json')});37          pkg.set('foo', 'bar');38          assert.equal(path.basename(pkg.path), 'bar.json');39          assert(pkg.data.hasOwnProperty('foo'));40          assert.equal(pkg.data.foo, 'bar');41          assert(fs.existsSync('fixtures/foo/bar.json'));42        });43    });44  });45  describe('.set', function() {46    it('should set a value on the store', function() {47      pkg.set('one', 'two');48      assert.equal(pkg.data.one, 'two');49    });50    it('should set an object', function() {51      pkg.set({four: 'five', six: 'seven'});52      assert.equal(pkg.data.four, 'five');53      assert.equal(pkg.data.six, 'seven');54    });55    it('should set a nested value', function() {56      pkg.set('a.b.c.d', {e: 'f'});57      assert.equal(pkg.data.a.b.c.d.e, 'f');58    });59  });60  describe('.union', function() {61    it('should union a value on the store', function() {62      pkg.union('one', 'two');63      assert.deepEqual(pkg.data.one, ['two']);64    });65    it('should not union duplicate values', function() {66      pkg.union('one', 'two');67      assert.deepEqual(pkg.data.one, ['two']);68      pkg.union('one', ['two']);69      assert.deepEqual(pkg.data.one, ['two']);70    });71    it('should concat an existing array:', function() {72      pkg.union('one', 'a');73      assert.deepEqual(pkg.data.one, ['a']);74      pkg.union('one', ['b']);75      assert.deepEqual(pkg.data.one, ['a', 'b']);76      pkg.union('one', ['c', 'd']);77      assert.deepEqual(pkg.data.one, ['a', 'b', 'c', 'd']);78    });79  });80  describe('.has', function() {81    it('should return true if a key has on the store', function() {82      pkg.set('foo', 'bar');83      pkg.set('baz', null);84      pkg.set('qux', undefined);85      assert(pkg.has('baz'));86      assert(pkg.has('foo'));87      assert(!pkg.has('bar'));88      assert(!pkg.has('qux'));89    });90    it('should return true if a nested key has on the store', function() {91      pkg.set('a.b.c.d', {x: 'zzz'});92      pkg.set('a.b.c.e', {f: null});93      pkg.set('a.b.g.j', {k: undefined});94      assert(pkg.has('a.b.c.d'));95      assert(pkg.has('a.b.c.d.x'));96      assert(pkg.has('a.b.c.e'));97      assert(pkg.has('a.b.g.j'));98      assert(pkg.has('a.b.c.e.f'));99      assert(!pkg.has('a.b.bar'));100      assert(!pkg.has('a.b.c.d.z'));101      assert(!pkg.has('a.b.c.e.z'));102      assert(!pkg.has('a.b.g.j.k'));103      assert(!pkg.has('a.b.g.j.z'));104    });105  });106  describe('.get', function() {107    it('should get a stored value', function() {108      pkg.set('three', 'four');109      assert.equal(pkg.get('three'), 'four');110    });111    it('should get a nested value', function() {112      pkg.set({a: {b: {c: 'd'}}});113      assert.equal(pkg.get('a.b.c'), 'd');114    });115  });116  describe('.save', function() {117    it('should save the store', function() {118      pkg.set('three', 'four');119      pkg.save();120      var obj = require(fixtures('package.json'));121      assert.deepEqual(obj, {three: 'four'});122    });123  });124  describe('.del', function() {125    it('should delete a stored value', function() {126      pkg.set('a', 'b');127      pkg.set('c', 'd');128      assert(pkg.data.hasOwnProperty('a'));129      assert.equal(pkg.data.a, 'b');130      assert(pkg.data.hasOwnProperty('c'));131      assert.equal(pkg.data.c, 'd');132      pkg.del('a');133      pkg.del('c');134      assert(!pkg.data.hasOwnProperty('a'));135      assert(!pkg.data.hasOwnProperty('c'));136    });137    it('should delete multiple stored values', function() {138      pkg.set('a', 'b');139      pkg.set('c', 'd');140      pkg.set('e', 'f');141      pkg.del(['a', 'c', 'e']);142      assert.deepEqual(pkg.data, {});143    });144  });...invalid-dep-version-filtering.js
Source:invalid-dep-version-filtering.js  
1'use strict'2var path = require('path')3var test = require('tap').test4var mr = require('npm-registry-mock')5var common = require('../common-tap')6var Tacks = require('tacks')7var File = Tacks.File8var Dir = Tacks.Dir9var testdir = path.join(__dirname, path.basename(__filename, '.js'))10var cachedir = path.join(testdir, 'cache')11var fixture = new Tacks(Dir({12  cache: Dir(),13  node_modules: Dir(),14  tarballs: Dir({15    'pkgA.tgz': File(new Buffer(16      '1f8b0800000000000003edcfcf0a0221100670cf3ec5e0396cfcb703bd8d' +17      '842cb5e4ca5a5da2776f5da153b78408fc5d3e6684e133f9e3e4c7b04f35' +18      'e539cf9135868883b5509206b725ea3a6f9c01a634598d8e48134365d0e0' +19      'fadebac827b77cf5cb5ae5db3bf52bf0ce3ff1e00022fa4b100710691abd' +20      'd895cd3d2cf934c7b25412250afee4bfaeda755dd735f40211b5bced0008' +21      '0000',22      'hex'23    )),24    'pkgB1.tgz': File(new Buffer(25      '1f8b0800000000000003edcfc10a0221140550d77ec5c375d8d3d111fa1b' +26      '0b196ac891b16913fd7be308adda2544f0cee6e25d3caec99f463f847daa' +27      '292f798aac3144ec8d8192aeb75ba2aeef8ded8029ed8c46eb1c1a86aa43' +28      'bd76d87ac8274bbef9799df2ed9dfa1578e79f78700011fd35880388340e' +29      '47b12bcd3dccf93cc5522a8912057ff25f4f258410d2d00b247d22080008' +30      '0000',31      'hex'32    ))33  })34}))35var pkgAtgz = path.join(testdir, 'tarballs', 'pkgA.tgz')36var pkgB1tgz = path.join(testdir, 'tarballs', 'pkgB1.tgz')37var server38var pkgA = {39  name: 'pkg-a',40  'dist-tags': {41    latest: '1.0.0'42  },43  versions: {44    '1.0.0': {45      name: 'pkg-a',46      version: '1.0.0',47      dependencies: {48        'pkg-b': '1.0.0'49      },50      dist: {51        shasum: 'dc5471ce0439f0f47749bb01473cad4570cc7dc5',52        tarball: common.registry + '/pkg-a/-/pkg-a-1.0.0.tgz'53      }54    }55  }56}57var pkgB = {58  name: 'pkg-b',59  'dist-tags': {60    latest: '1.0.0'61  },62  versions: {63    '1.0.0': {64      name: 'pkg-b',65      version: '1.0.0',66      dist: {67        shasum: '53031aa2cf774c0e841c6fdbbe54c13825cd5640',68        tarball: common.registry + '/pkg-b/-/pkg-b-1.0.0.tgz'69      }70    },71    '1.0.0rc1': {72      name: 'pkg-b',73      version: '1.0.0rc1',74      dist: {75        shasum: '7f4b1bf680e3a31113d77619b4dc7c3b4c7dc15c',76        tarball: common.registry + '/pkg-b/-/pkg-b-1.0.0-rc1.tgz'77      }78    }79  }80}81function setup () {82  cleanup()83  fixture.create(testdir)84}85function cleanup () {86  fixture.remove(testdir)87}88test('setup', function (t) {89  setup()90  mr({ port: common.port, throwOnUnmatched: true }, function (err, s) {91    t.ifError(err, 'registry mocked successfully')92    server = s93    t.end()94  })95})96test('invalid versions should be ignored', function (t) {97  server.get('/pkg-a').reply(200, pkgA)98  server.get('/pkg-b').reply(200, pkgB)99  server.get('/pkg-a/-/pkg-a-1.0.0.tgz').replyWithFile(200, pkgAtgz)100  server.get('/pkg-b/-/pkg-b-1.0.0.tgz').replyWithFile(200, pkgB1tgz)101  common.npm(102    [103      'install',104      '--cache', cachedir,105      '--registry', common.registry,106      '--fetch-retries=0',107      'pkg-a@1.0.0'108    ],109    {cwd: testdir},110    function (err, code, stdout, stderr) {111      if (err) throw err112      t.equal(code, 0, 'install succeded')113      t.comment(stdout.trim())114      t.comment(stderr.trim())115      server.done()116      t.end()117    }118  )119})120test('cleanup', function (t) {121  server.close()122  cleanup()123  t.end()...decompose-actions.js
Source:decompose-actions.js  
1'use strict'2var validate = require('aproba')3var asyncMap = require('slide').asyncMap4var npm = require('../npm.js')5module.exports = function (differences, decomposed, next) {6  validate('AAF', arguments)7  asyncMap(differences, function (action, done) {8    var cmd = action[0]9    var pkg = action[1]10    switch (cmd) {11      case 'add':12        addSteps(decomposed, pkg, done)13        break14      case 'update':15        updateSteps(decomposed, pkg, done)16        break17      case 'move':18        moveSteps(decomposed, pkg, done)19        break20      case 'remove':21        removeSteps(decomposed, pkg, done)22        break23      default:24        defaultSteps(decomposed, cmd, pkg, done)25    }26  }, next)27}28function addSteps (decomposed, pkg, done) {29  if (!pkg.fromBundle && !pkg.isLink) {30    decomposed.push(['fetch', pkg])31    decomposed.push(['extract', pkg])32  }33  if (!pkg.fromBundle || npm.config.get('rebuild-bundle')) {34    decomposed.push(['preinstall', pkg])35    decomposed.push(['build', pkg])36    decomposed.push(['install', pkg])37    decomposed.push(['postinstall', pkg])38  }39  if (!pkg.fromBundle || !pkg.isLink) {40    decomposed.push(['finalize', pkg])41  }42  decomposed.push(['refresh-package-json', pkg])43  done()44}45function updateSteps (decomposed, pkg, done) {46  removeSteps(decomposed, pkg.oldPkg, () => {47    addSteps(decomposed, pkg, done)48  })49}50function removeSteps (decomposed, pkg, done) {51  decomposed.push(['unbuild', pkg])52  decomposed.push(['remove', pkg])53  done()54}55function moveSteps (decomposed, pkg, done) {56  decomposed.push(['move', pkg])57  decomposed.push(['build', pkg])58  decomposed.push(['install', pkg])59  decomposed.push(['postinstall', pkg])60  decomposed.push(['refresh-package-json', pkg])61  done()62}63function defaultSteps (decomposed, cmd, pkg, done) {64  decomposed.push([cmd, pkg])65  done()...Using AI Code Generation
1const { pkg } = require('devicefarmer-stf-client');2const { pkg } = require('devicefarmer-stf-client');3const { pkg } = require('devicefarmer-stf-client');4const { pkg } = require('devicefarmer-stf-client');5const { pkg } = require('devicefarmer-stf-client');6const { pkg } = require('devicefarmer-stf-client');7const { pkg } = require('devicefarmer-stf-client');8const { pkg } = require('devicefarmer-stf-client');9const { pkg } = require('devicefarmer-stf-client');10const { pkg } = require('devicefarmer-stf-client');11const { pkg } = require('devicefarmer-stf-client');12const { pkg } = require('devicefarmer-stf-client');13const { pkg } = require('devicefarmer-stf-client');14const { pkg } = require('devicefarmer-stf-client');15const { pkg } = require('devicefarmer-stf-client');Using AI Code Generation
1var pkg = require('devicefarmer-stf-client').pkg;2pkg('com.android.chrome');3var pkg = require('devicefarmer-stf-client').pkg;4pkg('com.android.chrome');5var pkg = require('devicefarmer-stf-client').pkg;6pkg('com.android.chrome');7var pkg = require('devicefarmer-stf-client').pkg;8pkg('com.android.chrome');9var pkg = require('devicefarmer-stf-client').pkg;10pkg('com.android.chrome');11var pkg = require('devicefarmer-stf-client').pkg;12pkg('com.android.chrome');13var pkg = require('devicefarmer-stf-client').pkg;14pkg('com.android.chrome');15var pkg = require('devicefarmer-stf-client').pkg;16pkg('com.android.chrome');17var pkg = require('devicefarmer-stf-client').pkg;18pkg('com.android.chrome');19var pkg = require('devicefarmer-stf-client').pkg;20pkg('com.android.chrome');21var pkg = require('devicefarmer-stf-client').pkg;22pkg('com.android.chrome');23var pkg = require('devicefarmer-stf-client').pkg;24pkg('com.android.chrome');25var pkg = require('devicefarmer-stf-client').pkg;26pkg('comUsing AI Code Generation
1var pkg = require('devicefarmer-stf-client').pkg;2var devices = require('devicefarmer-stf-client').devices;3var pkg = require('devicefarmer-stf-client').pkg;4var devices = require('devicefarmer-stf-client').devices;5var pkg = require('devicefarmer-stf-client').pkg;6var devices = require('devicefarmer-stf-client').devices;7var pkg = require('devicefarmer-stf-client').pkg;8var devices = require('devicefarmer-stf-client').devices;9var pkg = require('devicefarmer-stf-client').pkg;10var devices = require('devicefarmer-stf-client').devices;11var pkg = require('devicefarmer-stf-client').pkg;12var devices = require('devicefarmer-stf-client').devices;13var pkg = require('devicefarmer-stf-client').pkg;14var devices = require('devicefarmer-stf-client').devices;15var pkg = require('devicefarmer-stf-client').pkg;16var devices = require('devicefarmer-stf-client').devices;17var pkg = require('devicefarmer-stf-client').pkg;18var devices = require('devicefarmer-stf-client').devices;19var pkg = require('devicefarmer-stf-client').pkg;20var devices = require('devicefarmer-stf-client').devices;21var pkg = require('devicefarmer-stf-client').pkg;22var devices = require('devicefarmer-stf-client').devices;23var pkg = require('devicefarmer-stf-client').pkg;24var devices = require('devicefarmer-stf-client').devices;Using AI Code Generation
1var pkg = require('devicefarmer-stf').pkg;2pkg('com.android.chrome');3var pkg = require('devicefarmer-stf/lib/adb').pkg;4pkg('com.android.chrome');5var pkg = require('devicefarmer-stf/lib/adb/adb').pkg;6pkg('com.android.chrome');7var pkg = require('devicefarmer-stf/lib/adb/adb.js').pkg;8pkg('com.android.chrome');9var pkg = require('devicefarmer-stf/lib/adb/adb.js.js').pkg;10pkg('com.android.chrome');11var pkg = require('devicefarmer-stf/lib/adb/adb.js.js.js').pkg;12pkg('com.android.chrome');13var pkg = require('devicefarmer-stf/lib/adb/adb.js.js.js.js').pkg;14pkg('com.android.chrome');15var pkg = require('devicefarmer-stf/lib/adb/adb.js.js.js.js.js').pkg;16pkg('com.android.chrome');17var pkg = require('devicefarmer-stf/lib/adb/adb.js.js.js.js.js.js').pkg;18pkg('com.android.chrome');19var pkg = require('devicefarmer-stf/lib/adb/adb.js.js.js.js.js.js.js').pkg;20pkg('com.android.chrome');21var pkg = require('devicefarmer-stf/lib/adb/adb.js.js.js.js.js.js.js.jsUsing AI Code Generation
1var pkg = require('devicefarmer-stf').pkg;2pkg('com.android.settings', function(err, result) {3    if(err) {4        console.log('Error: ', err);5    }6    else {7        console.log('Result: ', result);8    }9});10var device = require('devicefarmer-stf').device;11device('com.android.settings', function(err, result) {12    if(err) {13        console.log('Error: ', err);14    }15    else {16        console.log('Result: ', result);17    }18});19var devices = require('devicefarmer-stf').devices;20devices(function(err, result) {21    if(err) {22        console.log('Error: ', err);23    }24    else {25        console.log('Result: ', result);26    }27});28var screenshot = require('devicefarmer-stf').screenshot;29screenshot('com.android.settings', function(err, result) {30    if(err) {31        console.log('Error: ', err);32    }33    else {34        console.log('Result: ', result);35    }36});37var screenshot = require('devicefarmer-stf').screenshot;38screenshot('com.android.settings', function(err, result) {39    if(err) {40        console.log('Error: ', err);41    }42    else {43        console.log('Result: ', result);44    }45});46var screenshot = require('devicefarmer-stf').screenshot;47screenshot('com.android.settings', function(err, result) {48    if(err) {49        console.log('Error: ', err);50    }51    else {52        console.log('Result: ', result);53    }54});55var screenshot = require('devicefarmer-stf').screenshot;56screenshot('com.android.settings', function(err, result) {57    if(err) {58        console.log('Error: ', err);59    }60    else {Using AI Code Generation
1var pkg = require('devicefarmer-stf').pkg;2var path = require('path');3var pkgPath = path.resolve('C:/Users/username/Desktop/MyApp.apk');4pkg.install(pkgPath, function(err){5    if(err) throw err;6    console.log("package installed");7});8var pkg = require('devicefarmer-stf').pkg;9var path = require('path');10var pkgPath = path.resolve('C:/Users/username/Desktop/MyApp.apk');11pkg.uninstall(pkgPath, function(err){12    if(err) throw err;13    console.log("package uninstalled");14});15var pkg = require('devicefarmer-stf').pkg;16var path = require('path');17var pkgPath = path.resolve('C:/Users/username/Desktop/MyApp.apk');18pkg.install(pkgPath, function(err){19    if(err) throw err;20    console.log("package installed");21    pkg.uninstall(pkgPath, function(err){22        if(err) throw err;23        console.log("package uninstalled");24    });25});26var pkg = require('devicefarmer-stf').pkg;27var path = require('path');28var pkgPath = path.resolve('C:/Users/username/Desktop/MyApp.apk');29pkg.install(pkgPath, function(err){30    if(err) throw err;31    console.log("package installed");32    pkg.uninstall(pkgPath, function(err){33        if(err) throw err;34        console.log("package uninstalled");35        pkg.install(pkgPath, function(err){36            if(err) throw err;37            console.log("package installed");38        });39    });40});41var pkg = require('devicefarmer-stf').pkg;42var path = require('path');43var pkgPath = path.resolve('C:/Users/username/Desktop/MyApp.apk');44pkg.install(pkgPath, function(err){45    if(err) throw err;46    console.log("package installed");47    pkg.uninstall(pkgPath, function(err){48        if(err) throw err;49        console.log("package uninstalled");50        pkg.install(pkgPath, functionUsing AI Code Generation
1const pkg = require('devicefarmer-stf').pkg;2const device = require('devicefarmer-stf').device;3var deviceID = device.getDeviceID();4var packageName = pkg.getPackageName(deviceID);5pkg.install(deviceID, "path/to/apk");6pkg.uninstall(deviceID, packageName);7var versionCode = pkg.getVersionCode(deviceID, packageName);8var versionName = pkg.getVersionName(deviceID, packageName);9var apkPath = pkg.getApkPath(deviceID, packageName);10var isInstalled = pkg.isInstalled(deviceID, packageName);11var isSystemApp = pkg.isSystemApp(deviceID, packageName);12var isDebuggable = pkg.isDebuggable(deviceID, packageName);13var isDisabled = pkg.isDisabled(deviceID, packageName);14var isEnabled = pkg.isEnabled(deviceID, packageName);15var isStopped = pkg.isStopped(deviceID, packageName);16var isRunning = pkg.isRunning(deviceID, packageName);17var uid = pkg.getUid(deviceID, packageName);18var sharedUserId = pkg.getSharedUserId(deviceID, packageName);19var sharedUserLabel = pkg.getSharedUserLabel(deviceID, packageName);20var firstInstallTime = pkg.getFirstInstallTime(deviceID, packageName);21var lastUpdateTime = pkg.getLastUpdateTime(deviceID, packageName);22var signatures = pkg.getSignatures(deviceID, packageName);23var permissions = pkg.getPermissions(deviceID, packageName);24var requestedPermissions = pkg.getRequestedPermissions(deviceID, packageName);Using AI Code Generation
1var pkg = require('devicefarmer-stf-client').pkg;2pkg.install('/Users/username/Desktop/MyApp.apk', 'serialnumber');3pkg.uninstall('com.mypackage', 'serialnumber');4pkg.list('serialnumber');5var screen = require('devicefarmer-stf-client').screen;6screen.rotate(90, 'serialnumber');7screen.getRotation('serialnumber');8var screenshot = require('devicefarmer-stf-client').screenshot;9screenshot.take('serialnumber');10var settings = require('devicefarmer-stf-client').settings;11settings.get('serialnumber');12settings.put('serialnumber', 'key', 'value');13var shell = require('devicefarmer-stf-client').shell;14shell.exec('serialnumber', 'command');15var start = require('devicefarmer-stf-client').start;16start.app('com.mypackage', 'serialnumber');17var stop = require('devicefarmer-stf-client').stop;18stop.app('com.mypackage', 'serialnumber');19var sysinfo = require('devicefarmer-stf-client').sysinfo;20sysinfo.get('serialnumber');21var unlock = require('devicefarmer-stf-client').unlock;22unlock('serialnumber');23var video = require('devicefarmer-stf-client').video;24video.get('serialnumber');25var websocket = require('devicefarmer-stf-client').websocket;26websocket.connect('serialnumber', 'command');Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
