<commit_before>var ToRegisterCard = {
    name: 'ToRegisterCard',
    dom_target: undefined,
    render_init: function () {
        WSData.fetch_notice_data(ToRegisterCard.render_upon_data, ToRegisterCard.render_error);
    },
    render_upon_data: function () {
        if (!ToRegisterCard._has_all_data()) {
            return;
        }
        ToRegisterCard._render();
    },

    _has_all_data: function () {
        if (WSData.notice_data()) {
            return true;
        }
        return false;
    },

    _render: function () {
        var source = $("#ns_to_register").html();
        var template = Handlebars.compile(source);
        var no_orient = Notices.get_notices_for_tag("checklist_no_orient");
        var post_orient = Notices.get_notices_for_tag("checklist_orient_after");
        var pre_iss = Notices.get_notices_for_tag("checklist_iss_before");
        var post_iss = Notices.get_notices_for_tag("checklist_iss_after");
        var pre_measles = Notices.get_notices_for_tag("checklist_measles_before");
        var post_measles = Notices.get_notices_for_tag("checklist_measles_after");
        var pre_orient = Notices.get_notices_for_tag("checklist_orient_before");

        if (no_orient.length > 0) {
            no_msg = no_orient[0];
            $.each(no_msg.attributes, function(idx, attrib){
                if(attrib.name === "Date") {
                    no_orient_date = attrib.formatted_value;
                }

            });
        }

        var notice_count =  no_orient.length +
            post_orient.length +
            pre_iss.length +
            post_iss.length +
            pre_measles.length +
            post_measles.length +
            pre_orient.length;
        if (notice_count > 0){
            ToRegisterCard.dom_target.html(template({'no_orient': no_orient,
                                                     'no_orient_date': no_orient_date,
                                                     'post_orient': post_orient,
                                                     'pre_iss': pre_iss,
                                                     'post_iss': post_iss,
                                                     'pre_measles': pre_measles,
                                                     'post_measles': post_measles,
                                                     'pre_orient': pre_orient}));
        } else {
            ToRegisterCard.dom_target.hide();
        }

    },
    render_error: function () {
        ToRegisterCard.dom_target.html(CardWithError.render(ToRegisterCard.name));
    },
};
<commit_msg>fixing display issue when no orient date is unset<commit_after>var ToRegisterCard = {
    name: 'ToRegisterCard',
    dom_target: undefined,
    render_init: function () {
        WSData.fetch_notice_data(ToRegisterCard.render_upon_data, ToRegisterCard.render_error);
    },
    render_upon_data: function () {
        if (!ToRegisterCard._has_all_data()) {
            return;
        }
        ToRegisterCard._render();
    },

    _has_all_data: function () {
        if (WSData.notice_data()) {
            return true;
        }
        return false;
    },

    _render: function () {
        var source = $("#ns_to_register").html();
        var template = Handlebars.compile(source);
        var no_orient = Notices.get_notices_for_tag("checklist_no_orient");
        var post_orient = Notices.get_notices_for_tag("checklist_orient_after");
        var pre_iss = Notices.get_notices_for_tag("checklist_iss_before");
        var post_iss = Notices.get_notices_for_tag("checklist_iss_after");
        var pre_measles = Notices.get_notices_for_tag("checklist_measles_before");
        var post_measles = Notices.get_notices_for_tag("checklist_measles_after");
        var pre_orient = Notices.get_notices_for_tag("checklist_orient_before");
        var no_orient_date = false;

        if (no_orient.length > 0) {
            no_msg = no_orient[0];
            $.each(no_msg.attributes, function(idx, attrib){
                if(attrib.name === "Date") {
                    no_orient_date = attrib.formatted_value;
                }

            });
        }

        var notice_count =  no_orient.length +
            post_orient.length +
            pre_iss.length +
            post_iss.length +
            pre_measles.length +
            post_measles.length +
            pre_orient.length;
        if (notice_count > 0){
            ToRegisterCard.dom_target.html(template({'no_orient': no_orient,
                                                     'no_orient_date': no_orient_date,
                                                     'post_orient': post_orient,
                                                     'pre_iss': pre_iss,
                                                     'post_iss': post_iss,
                                                     'pre_measles': pre_measles,
                                                     'post_measles': post_measles,
                                                     'pre_orient': pre_orient}));
        } else {
            ToRegisterCard.dom_target.hide();
        }

    },
    render_error: function () {
        ToRegisterCard.dom_target.html(CardWithError.render(ToRegisterCard.name));
    },
};
<|endoftext|>


<commit_before>"use strict";
/*jshint eqnull:true */
/*jshint node:true */
/*eslint-disable no-console */

// APP

var extensionServeStatic = require('extension-serve-static');
var _ = require('lodash');

// var Promises = require('best-promise');

var backend = require("backend-plus");
var MiniTools = require("mini-tools");

var Promises = require("promise-plus");

var AccountingMachine = require('accounting-machine');

class AppAccounting extends backend.AppBackend{
    configList(){
        return super.configList().concat([
            'def-config.yaml',
            'local-config.yaml'
        ]);
    }
    obtenerEstructura(){
        var be = this;
        if(this.estructura){
            return Promises.resolve(this.estructura);
        }else{
            this.registroVacio={};
            return this.readStructure('node_modules/accounting-machine/estructuras/estructura-asiento.yaml').then(function(estructura){
                be.estructura = estructura;
                return estructura;
            });
        }
    }
    addLoggedServices(){
        var be = this;
        be.app.get('/',MiniTools.serveJade(this.rootPath+'client/pandora'));
        super.addLoggedServices();
        var am = new (AccountingMachine.Machine)(be.config);
        be.app.use('/',extensionServeStatic(this.rootPath+'client',{staticExtensions:['jpg','png','html','gif']}));
        be.app.get('/structure/asiento', function(req,res){
            be.registroVacio = {};
            be.obtenerEstructura().then(function(estructura){
                MiniTools.serveJson(estructura)(req,res);
            }).catch(MiniTools.serveErr(req,res));
        });
        be.app.post('/agregarAsiento', function(req,res){
            var asiento = JSON.parse(req.body.asiento);
            asiento.encabezado.fecha = new Date(asiento.encabezado.fecha||null);
            asiento.renglones = asiento.renglones.map(function(renglon){
                renglon.fecha = new Date(renglon.fecha||asiento.encabezado.fecha||null);
                renglon.vencimiento = new Date(renglon.vencimiento||renglon.fecha||null);
                renglon.subc = renglon.subc||'';
                return renglon;
            }).filter(function(renglon){
                return !!renglon.importe && !isNaN(renglon.importe);
            });
            am.agregarAsiento(asiento).then(function(result){
                res.end('¡Grabado!');
            }).catch(MiniTools.serveErr(req,res));
        });
        be.app.post('/obtenerSaldos', function(req,res){
            var parametros = JSON.parse(req.body.parametros);
            be.obtenerEstructura().then(function(){
                parametros.forEach(function(parametro){
                    if(be.estructura.formularios.renglones.celdas.filter(function(celda){
                        return celda.tipo=='pregunta' && celda.variable==parametro;
                    }).length==0){
                        console.log('parametro invalido para el corte de obtenerSaldos',parametro);
                        throw new Error('parametro invalido para el corte de obtenerSaldos');
                    }
                });
                return am.obtenerSaldos(parametros)
            }).then(function(lista){
                MiniTools.serveJson(lista)(req,res);
            }).catch(MiniTools.serveErr(req,res));
        });
        be.app.post('/obtenerCuenta', function(req,res){
            var parametros = JSON.parse(req.body.parametros);
            be.obtenerEstructura().then(function(){
                _.forEach(parametros, function(valor, parametro){
                    if(be.estructura.formularios.renglones.celdas.filter(function(celda){
                        return celda.tipo=='pregunta' && celda.variable==parametro;
                    }).length>0){
                    }
                });
                return am.obtenerCuenta(parametros);
            }).then(function(lista){
                MiniTools.serveJson(lista)(req,res);
            }).catch(MiniTools.serveErr(req,res));
        });
        be.app.post('/obtenerCuentas', function(req,res){
            Promises.start(function(){
                return am.obtenerCuentas();
            }).then(function(lista){
                MiniTools.serveJson(lista)(req,res);
            }).catch(MiniTools.serveErr(req,res));
        });
    }
}

process.on('uncaughtException', function(err){
  console.log("Caught exception:",err);
  process.exit(1);
});

process.on('unhandledRejection', function(err){
  console.log("unhandledRejection:",err);
});

new AppAccounting().start();
<commit_msg>agrego el --dir<commit_after>"use strict";
/*jshint eqnull:true */
/*jshint node:true */
/*eslint-disable no-console */

// APP

if(process.argv[2]=='--dir'){
    process.chdir(process.argv[3]);
    console.log('cwd',process.cwd());
}

var extensionServeStatic = require('extension-serve-static');
var _ = require('lodash');

// var Promises = require('best-promise');

var backend = require("backend-plus");
var MiniTools = require("mini-tools");

var Promises = require("promise-plus");

var AccountingMachine = require('accounting-machine');

class AppAccounting extends backend.AppBackend{
    configList(){
        return super.configList().concat([
            'def-config.yaml',
            'local-config.yaml'
        ]);
    }
    obtenerEstructura(){
        var be = this;
        if(this.estructura){
            return Promises.resolve(this.estructura);
        }else{
            this.registroVacio={};
            return this.readStructure('node_modules/accounting-machine/estructuras/estructura-asiento.yaml').then(function(estructura){
                be.estructura = estructura;
                return estructura;
            });
        }
    }
    addLoggedServices(){
        var be = this;
        be.app.get('/',MiniTools.serveJade(this.rootPath+'client/pandora'));
        super.addLoggedServices();
        var am = new (AccountingMachine.Machine)(be.config);
        be.app.use('/',extensionServeStatic(this.rootPath+'client',{staticExtensions:['jpg','png','html','gif']}));
        be.app.get('/structure/asiento', function(req,res){
            be.registroVacio = {};
            be.obtenerEstructura().then(function(estructura){
                MiniTools.serveJson(estructura)(req,res);
            }).catch(MiniTools.serveErr(req,res));
        });
        be.app.post('/agregarAsiento', function(req,res){
            var asiento = JSON.parse(req.body.asiento);
            asiento.encabezado.fecha = new Date(asiento.encabezado.fecha||null);
            asiento.renglones = asiento.renglones.map(function(renglon){
                renglon.fecha = new Date(renglon.fecha||asiento.encabezado.fecha||null);
                renglon.vencimiento = new Date(renglon.vencimiento||renglon.fecha||null);
                renglon.subc = renglon.subc||'';
                return renglon;
            }).filter(function(renglon){
                return !!renglon.importe && !isNaN(renglon.importe);
            });
            am.agregarAsiento(asiento).then(function(result){
                res.end('¡Grabado!');
            }).catch(MiniTools.serveErr(req,res));
        });
        be.app.post('/obtenerSaldos', function(req,res){
            var parametros = JSON.parse(req.body.parametros);
            be.obtenerEstructura().then(function(){
                parametros.forEach(function(parametro){
                    if(be.estructura.formularios.renglones.celdas.filter(function(celda){
                        return celda.tipo=='pregunta' && celda.variable==parametro;
                    }).length==0){
                        console.log('parametro invalido para el corte de obtenerSaldos',parametro);
                        throw new Error('parametro invalido para el corte de obtenerSaldos');
                    }
                });
                return am.obtenerSaldos(parametros)
            }).then(function(lista){
                MiniTools.serveJson(lista)(req,res);
            }).catch(MiniTools.serveErr(req,res));
        });
        be.app.post('/obtenerCuenta', function(req,res){
            var parametros = JSON.parse(req.body.parametros);
            be.obtenerEstructura().then(function(){
                _.forEach(parametros, function(valor, parametro){
                    if(be.estructura.formularios.renglones.celdas.filter(function(celda){
                        return celda.tipo=='pregunta' && celda.variable==parametro;
                    }).length>0){
                    }
                });
                return am.obtenerCuenta(parametros);
            }).then(function(lista){
                MiniTools.serveJson(lista)(req,res);
            }).catch(MiniTools.serveErr(req,res));
        });
        be.app.post('/obtenerCuentas', function(req,res){
            Promises.start(function(){
                return am.obtenerCuentas();
            }).then(function(lista){
                MiniTools.serveJson(lista)(req,res);
            }).catch(MiniTools.serveErr(req,res));
        });
    }
}

process.on('uncaughtException', function(err){
  console.log("Caught exception:",err);
  process.exit(1);
});

process.on('unhandledRejection', function(err){
  console.log("unhandledRejection:",err);
});

new AppAccounting().start();
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    env = process.env.NODE_ENV || 'development',
    config = require('../../config/config')[env],
    Schema = mongoose.Schema,
    _ = require('lodash');

var customNameSchema = new Schema({
    type: Schema.ObjectId,
    displayName: String
});

var toolEnabledSchema = new Schema({
    "name": String,
    "active": Boolean,
    "slug": String
});

/**
 * Vendor Schema
 * @todo refactor tools to be use slug as keys? is this possible?
 */
var VendorSchema = new Schema({
    "created": {
        type: Date,
        "default": Date.now
    },
    "searchString" : {
        type: String,
        "default": ''
    },
    "name": {
        type: String,
        "default": '',
        trim: true
    },
    "contactPerson": {
        "name": {
            type: String,
            "default": '',
            trim: true
        },
        "email": {
            type: String,
            "default": '',
            trim: true
        },
        "phone": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "salesRep": {
        type: Schema.ObjectId,
        ref: 'User'
    },
    "vendorRep": {
        type: Schema.ObjectId,
        ref: 'User'
    },
    "logo": {
        "original": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "website": {
        type: String,
        "default": '',
        trim: true
    },
    "legalTerms": {
        type: String,
        "default": '',
        trim: true
    },
    "businessPhone": {
        type: String,
        "default": '',
        trim: true
    },
    "businessAddress": {
        "address1": {
            type: String,
            "default": '',
            trim: true
        },
        "address2": {
            type: String,
            "default": '',
            trim: true
        },
        "city": {
            type: String,
            "default": '',
            trim: true
        },
        "state": {
            type: String,
            "default": '',
            trim: true
        },
        "zip": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "geo": {
        "latitude": {
            type: Number,
            "default": null
        },
        "longitude": {
            type: Number,
            "default": null
        }
    },
    "tools": [toolEnabledSchema],
    "programs": [{
        type: Schema.ObjectId,
        ref: 'Program'
    }],
    "programCustomNames": [customNameSchema],
    "customField": {
        required: {
            type: Boolean,
            "default": false
        },
        enabled: {
            type: Boolean,
            "default": false
        },
        displayName: {
            type: String,
            "default": '',
            trim: true
        }
    }
});

var troop = require('mongoose-troop');
VendorSchema.plugin(troop.merge);

var taggable = require('mongoose-taggable');
VendorSchema.plugin(taggable, {'path':'tags'});

/**
 * Statics
 */
VendorSchema.statics = {

    // this gets called when a vendorId is present in the req.params
    // its a clever way to be able to access req.vendor in the next middlewares
    //
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).populate('programs salesRep vendorRep').exec(cb);
    }
};

/**
 * Runs similar to "after get" callback
 *
 */
VendorSchema.pre('init', function(next, data) {

    // iterate through each program and replace its name with custom name if set
    // @todo not the most effecient
    // attempts to just "merge" the 2 datasets failed, and replaced all the props
    // of programs with custom name
    _.each(data.programs, function(item) {
        var customName = _.where(data.programCustomNames, {
            _id: item._id
        });
        item.displayName = customName.length ? customName[0].displayName : null;
    });

    next();
});

function convertToSlug(Text) {
    return Text
        .toLowerCase()
        .replace(/ /g, '-')
        .replace(/[^\w\-]+/g, '');
}

VendorSchema.pre('save', function(next) {

    /**
    * Process tags from dashboard
    * --------------------------------
    *
    * @note tags are sent as vendorTags which are then saved into vendor.tags
    * @todo refactor with fulltext mondules that @pickle was looking into
    * @note when calling addTag() and removeTag() without a callback, it happens in memory
    *       only and thus will not be refrected in vendor.tags until vendor.save() is complete
    *
    */
    var vendor = this;

    var vendorTags = [];  // tags that are currently being passed from the vendor

    // create a unified array of current vendor tags
    _.each(vendor.vendorTags, function(item) {
        vendorTags.push(item.text);
    });

    var newTags = _.difference(vendorTags, vendor.tags);
    var removeTags = _.difference(vendor.tags, vendorTags);

    _.each(newTags, function(item) {
        vendor.addTag(item, function(err, addedTag) {
            console.log('Added: ' + item);
        });
    });

    _.each(removeTags, function(item) {
        vendor.removeTag(item, function(err, removedTag) {
            console.log('Removed: ' + item);
        });
    });

    /**
    * A nice way to create a search string that we can use on the dealer locator
    * --------------------------------
    *
    * @todo refactor with fulltext mondules that @pickle was looking into
    *       with a fultext search in place, we could just send tag searches as get queries
    *       and let the server do all the work.
    *
    */
    vendor.searchString = '';

    // will be present when updating from dashboard
    if(vendor.vendorTags) {
        _.each(vendor.vendorTags, function(tag) {
            vendor.searchString += tag.text + ' ';
        });

    // on seed data
    } else {
        _.each(vendor.tags, function(tag) {
            vendor.searchString += tag + ' ';
        });
    }

    /**
    * Standardize tool slugs
    *
    */
    _.each(vendor.tools, function(item) {
        item.slug = convertToSlug(item.name);
    });

    next();
});

VendorSchema.statics = {

    getCurrentReps: function(vendorId, cb) {

        // attempt to get the sales rep, which we save with the quote
        // for easy geting from the database
        return this.findOne({
            _id: vendorId
        }, function(err, result) {
            if (err) return cb(err);
            if (result && result._id) {
                console.log(result);
                return cb(null, result);
            } else {
                return cb(new Error(vendorId + ' is Not a valid vendor id'));
            }
        });
    },
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).populate('programs salesRep vendorRep').exec(cb);
    }
};

mongoose.model('Vendor', VendorSchema);<commit_msg>Set default vendor logo if logo isn't set.<commit_after>/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    env = process.env.NODE_ENV || 'development',
    config = require('../../config/config')[env],
    Schema = mongoose.Schema,
    _ = require('lodash');

var customNameSchema = new Schema({
    type: Schema.ObjectId,
    displayName: String
});

var toolEnabledSchema = new Schema({
    "name": String,
    "active": Boolean,
    "slug": String
});

/**
 * Vendor Schema
 * @todo refactor tools to be use slug as keys? is this possible?
 */
var VendorSchema = new Schema({
    "created": {
        type: Date,
        "default": Date.now
    },
    "searchString" : {
        type: String,
        "default": ''
    },
    "name": {
        type: String,
        "default": '',
        trim: true
    },
    "contactPerson": {
        "name": {
            type: String,
            "default": '',
            trim: true
        },
        "email": {
            type: String,
            "default": '',
            trim: true
        },
        "phone": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "salesRep": {
        type: Schema.ObjectId,
        ref: 'User'
    },
    "vendorRep": {
        type: Schema.ObjectId,
        ref: 'User'
    },
    "logo": {
        "original": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "website": {
        type: String,
        "default": '',
        trim: true
    },
    "legalTerms": {
        type: String,
        "default": '',
        trim: true
    },
    "businessPhone": {
        type: String,
        "default": '',
        trim: true
    },
    "businessAddress": {
        "address1": {
            type: String,
            "default": '',
            trim: true
        },
        "address2": {
            type: String,
            "default": '',
            trim: true
        },
        "city": {
            type: String,
            "default": '',
            trim: true
        },
        "state": {
            type: String,
            "default": '',
            trim: true
        },
        "zip": {
            type: String,
            "default": '',
            trim: true
        }
    },
    "geo": {
        "latitude": {
            type: Number,
            "default": null
        },
        "longitude": {
            type: Number,
            "default": null
        }
    },
    "tools": [toolEnabledSchema],
    "programs": [{
        type: Schema.ObjectId,
        ref: 'Program'
    }],
    "programCustomNames": [customNameSchema],
    "customField": {
        required: {
            type: Boolean,
            "default": false
        },
        enabled: {
            type: Boolean,
            "default": false
        },
        displayName: {
            type: String,
            "default": '',
            trim: true
        }
    }
});

var troop = require('mongoose-troop');
VendorSchema.plugin(troop.merge);

var taggable = require('mongoose-taggable');
VendorSchema.plugin(taggable, {'path':'tags'});

/**
 * Statics
 */
VendorSchema.statics = {

    // this gets called when a vendorId is present in the req.params
    // its a clever way to be able to access req.vendor in the next middlewares
    //
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).populate('programs salesRep vendorRep').exec(cb);
    }
};

/**
 * Runs similar to "after get" callback
 *
 */
VendorSchema.pre('init', function(next, data) {

    // iterate through each program and replace its name with custom name if set
    // @todo not the most effecient
    // attempts to just "merge" the 2 datasets failed, and replaced all the props
    // of programs with custom name
    _.each(data.programs, function(item) {
        var customName = _.where(data.programCustomNames, {
            _id: item._id
        });
        item.displayName = customName.length ? customName[0].displayName : null;
    });

    //If there is no vendor logo set default
    if(!data.logo.original){
        data.logo.original = "http://placekitten.com/520/390";
    }

    next();
});

function convertToSlug(Text) {
    return Text
        .toLowerCase()
        .replace(/ /g, '-')
        .replace(/[^\w\-]+/g, '');
}

VendorSchema.pre('save', function(next) {

    /**
    * Process tags from dashboard
    * --------------------------------
    *
    * @note tags are sent as vendorTags which are then saved into vendor.tags
    * @todo refactor with fulltext mondules that @pickle was looking into
    * @note when calling addTag() and removeTag() without a callback, it happens in memory
    *       only and thus will not be refrected in vendor.tags until vendor.save() is complete
    *
    */
    var vendor = this;

    var vendorTags = [];  // tags that are currently being passed from the vendor

    // create a unified array of current vendor tags
    _.each(vendor.vendorTags, function(item) {
        vendorTags.push(item.text);
    });

    var newTags = _.difference(vendorTags, vendor.tags);
    var removeTags = _.difference(vendor.tags, vendorTags);

    _.each(newTags, function(item) {
        vendor.addTag(item, function(err, addedTag) {
            console.log('Added: ' + item);
        });
    });

    _.each(removeTags, function(item) {
        vendor.removeTag(item, function(err, removedTag) {
            console.log('Removed: ' + item);
        });
    });

    /**
    * A nice way to create a search string that we can use on the dealer locator
    * --------------------------------
    *
    * @todo refactor with fulltext mondules that @pickle was looking into
    *       with a fultext search in place, we could just send tag searches as get queries
    *       and let the server do all the work.
    *
    */
    vendor.searchString = '';

    // will be present when updating from dashboard
    if(vendor.vendorTags) {
        _.each(vendor.vendorTags, function(tag) {
            vendor.searchString += tag.text + ' ';
        });

    // on seed data
    } else {
        _.each(vendor.tags, function(tag) {
            vendor.searchString += tag + ' ';
        });
    }

    /**
    * Standardize tool slugs
    *
    */
    _.each(vendor.tools, function(item) {
        item.slug = convertToSlug(item.name);
    });

    next();
});

VendorSchema.statics = {

    getCurrentReps: function(vendorId, cb) {

        // attempt to get the sales rep, which we save with the quote
        // for easy geting from the database
        return this.findOne({
            _id: vendorId
        }, function(err, result) {
            if (err) return cb(err);
            if (result && result._id) {
                console.log(result);
                return cb(null, result);
            } else {
                return cb(new Error(vendorId + ' is Not a valid vendor id'));
            }
        });
    },
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).populate('programs salesRep vendorRep').exec(cb);
    }
};

mongoose.model('Vendor', VendorSchema);<|endoftext|>


<commit_before>/* AJAX SETUP FOR CSRF */
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
/* END AJAX SETUP */

$(document).ready(function() {
    $('#image-name').hide();

//Ajax request to remove profile image
    $('#confirm-delete').click(function() {
        confirmRemoveImage();
    });

    function confirmRemoveImage() {
        $.ajax({
            method: 'DELETE',
            url: 'removeprofileimage/',
            success: function(res) {
                console.log(res);
                res = JSON.parse(res);
                $('img#profile-image').attr('src', res['url']);
                $('#remove-image-modal').modal("hide");
            },
            error: function() {
                alert("Error!")
            },
            crossDomain: false
        });
    }

    $('#userprofile-tabs > li > a').click(function() {
        updateActiveTab(this.getAttribute('href').substr(1));
    })

    function updateActiveTab(activetab) {
        var data = JSON.stringify({active_tab : activetab});
        $.ajax({
            method: 'POST',
            data: data,
            url: 'updateactivetab/',
            crossDomain: false
        });
    }

    $('.privacybox').click(
        function() {
            var checkbox = $(this).find('input');
            var checked = checkbox.is(':checked');
            checkbox.prop('checked', !checked)

            animatePrivacyBox(this, checked);
        }
    )

    function animatePrivacyBox(checkbox, state) {
        if(state) {
            $(checkbox).stop().animate(
                {  opacity: 0.30  }, 100
            );
            $(checkbox).removeClass("on");
            $(checkbox).addClass("off");
        }
        else {
            $(checkbox).removeClass("off");
            $(checkbox).addClass("on");
            $(checkbox).stop().animate(
                {  opacity: 1.0 }, 100
            );
        }
    }

    // Popover for privacy
    $('#privacy-help').popover({placement: 'bottom'});

    /* Image cropping and uploading */
    var api;
    var formData = false;
    var x, y, x2, y2, w, h;

    if(window.FormData) {
        formData = new FormData();
    }

    $('input[type=file]').change(function() {
        readURL(this);
    });

    function readURL(input) {

        if (input.files && input.files[0]) {
            var file = input.files[0];

            if (!file.type.match(/image.*/)) {
                return;
            }

            var reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onloadend = function(e) {
                $('#image-resize').attr('src', e.target.result);
                $('#image-resize').Jcrop({
                    // start off with jcrop-light class
                    bgOpacity: 0.5,
                    bgColor: 'white',
                    setSelect: [100,100,50,50],
                    addClass: 'jcrop-light',
                    boxHeight: 300,
                    aspectRatio: 3/4,
                    onChange: updateCoords,
                    onSelect: updateCoords
                },function() {
                    api = this;
                    api.setOptions({ bgFade: true });
                    api.ui.selection.addClass('jcrop-selection');
                    api.allowResize = true;
                });
                api.setImage(e.target.result);

                if(formData) {
                    formData.append("image", file);
                }

                $('#upload-button').show();
            }
        }
    }

    function updateCoords(c) {
        x = c.x;
        y = c.y;
        x2 = c.x2;
        y2 = c.y2;
        w = c.w;
        h = c.h;
        $('#inputx').val(c.x);
        $('#inputy').val(c.y);
        $('#inputx2').val(c.x2);
        $('#inputy2').val(c.y2);
        $('#inputw').val(c.w);
        $('#inputh').val(c.h);
    }

    var setStatus = function(statusMsg) {
        $('#status').html(statusMsg);
    }

    $('#upload-image-form').submit(function(e) {
        if (formData) {
            e.preventDefault();

            if(!imageChosen()) return;

            setStatus("Laster opp bildet...")

            //JCrop select coordinates
            formData.append("x", x);
            formData.append("y", y);
            formData.append("x2", x2);
            formData.append("y2", y2);
            formData.append("w", w);
            formData.append("h", h);

            $.ajax({
                url: "uploadimage/",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                crossDomain: false,
                success: function (res) {
                    res = JSON.parse(res);
                    setStatus(res['message']);
                    $('#profile-image').attr("src", res['image-url']);
                    $('#upload-image-modal').modal('hide');
                },
                error: function(res) {
                    setStatus(res);
                }
            });
        }
        else {
            if(!imageChosen()) {
                e.preventDefault();
            }
        }
    });

    function imageChosen() {
        var fileInput = $('input[type=file]')[0];
            if(!fileInput || fileInput.files.length < 1) {
                setStatus("Ingen fil valgt.");
                return false;
            }
        return true;
    }

    /* End image cropping and uploading*/

/*
 JS for email management.
*/

    $('button.addnewemail').click(function() {
        $('tr.addnewemail').show();
        $(this).hide();
    });
    $('.emptyonclick').focus(function() {
        $(this).val('');
    });

    $('tr').each(function(i, row) {
// Ajax request to delete an email
        $(row).find('button.delete').click(function() {
            if ($(row).find('button.active').length) {
                alert("Du kan ikke fjerne din primæraddresse.");
            }
            else {
                email = $(row).find('span.email').text();
                deleteEmail(email, row);
            }
        });
// Ajax request to set email as primary
        $(row).find('button.primary').click(function() {
            email = $(row).find('span.email').text();
            setPrimaryEmail(email, row);
        });
// Ajax request to send verification mail
        $(row).find('button.verify').click(function() {
            email = $(row).find('span.email').text();
            verifyEmail(email, row);
        });
    });

    function deleteEmail(email, row) {
        $.ajax({
            method: 'POST',
            url: 'delete_email/',
            data: {'email':email, },
            success: function() {
                // TODO Make animation
                $(row).hide();
            },
            error: function(res) {
                if (status = 412) {
                    res = JSON.parse(res['responseText']);
                    alert(res['message']);
                }
                else {
                // TODO write a proper error function
                    alert("Error!");
                }
            },
            crossDomain: false
        });
    }

    function setPrimaryEmail(email, row) {
        $.ajax({
            method: 'POST',
            url: 'set_primary/',
            data: {'email':email, },
            success: function() {
                $('button.active').removeClass('active').removeClass('btn-success').addClass('btn-default')
                    .prop('disabled', false).text('Sett primær');
                $(row).find('button.primary').addClass('active').removeClass('btn-default').addClass('btn-success')
                    .prop('disabled', true).text('Primær');
            },
            error: function(res) {
                if (status = 412) {
                    res = JSON.parse(res['responseText']);
                    alert(res['message']);
                }
                else {
                // TODO write a proper error function
                    alert("Error!");
                }
            },
            crossDomain: false
        });
    }

    function verifyEmail(email, row) {
        $.ajax({
            method: 'POST',
            url: 'verify_email/',
            data: {'email':email, },
            success: function() {
                alert("tada");
            },
            error: function(res) {
                if (status = 412) {
                    res = JSON.parse(res['responseText']);
                    alert(res['message']);
                }
                else {
                // TODO write a proper error function
                    alert("Error!");
                }
            },
            crossDomain: false
        });
    }
});

<commit_msg>Small javascript fixes.<commit_after>/* AJAX SETUP FOR CSRF */
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
/* END AJAX SETUP */

$(document).ready(function() {
    $('#image-name').hide();

//Ajax request to remove profile image
    $('#confirm-delete').click(function() {
        confirmRemoveImage();
    });

    function confirmRemoveImage() {
        $.ajax({
            method: 'DELETE',
            url: 'removeprofileimage/',
            success: function(res) {
                console.log(res);
                res = JSON.parse(res);
                $('img#profile-image').attr('src', res['url']);
                $('#remove-image-modal').modal("hide");
            },
            error: function() {
                alert("Error!")
            },
            crossDomain: false
        });
    }

    $('#userprofile-tabs > li > a').click(function() {
        updateActiveTab(this.getAttribute('href').substr(1));
    })

    function updateActiveTab(activetab) {
        var data = JSON.stringify({active_tab : activetab});
        $.ajax({
            method: 'POST',
            data: data,
            url: 'updateactivetab/',
            crossDomain: false
        });
    }

    $('.privacybox').click(
        function() {
            var checkbox = $(this).find('input');
            var checked = checkbox.is(':checked');
            checkbox.prop('checked', !checked)

            animatePrivacyBox(this, checked);
        }
    )

    function animatePrivacyBox(checkbox, state) {
        if(state) {
            $(checkbox).stop().animate(
                {  opacity: 0.30  }, 100
            );
            $(checkbox).removeClass("on");
            $(checkbox).addClass("off");
        }
        else {
            $(checkbox).removeClass("off");
            $(checkbox).addClass("on");
            $(checkbox).stop().animate(
                {  opacity: 1.0 }, 100
            );
        }
    }

    // Popover for privacy
    $('#privacy-help').popover({placement: 'bottom'});

    /* Image cropping and uploading */
    var api;
    var formData = false;
    var x, y, x2, y2, w, h;

    if(window.FormData) {
        formData = new FormData();
    }

    $('input[type=file]').change(function() {
        readURL(this);
    });

    function readURL(input) {

        if (input.files && input.files[0]) {
            var file = input.files[0];

            if (!file.type.match(/image.*/)) {
                return;
            }

            var reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onloadend = function(e) {
                $('#image-resize').attr('src', e.target.result);
                $('#image-resize').Jcrop({
                    // start off with jcrop-light class
                    bgOpacity: 0.5,
                    bgColor: 'white',
                    setSelect: [100,100,50,50],
                    addClass: 'jcrop-light',
                    boxHeight: 300,
                    aspectRatio: 3/4,
                    onChange: updateCoords,
                    onSelect: updateCoords
                },function() {
                    api = this;
                    api.setOptions({ bgFade: true });
                    api.ui.selection.addClass('jcrop-selection');
                    api.allowResize = true;
                });
                api.setImage(e.target.result);

                if(formData) {
                    formData.append("image", file);
                }

                $('#upload-button').show();
            }
        }
    }

    function updateCoords(c) {
        x = c.x;
        y = c.y;
        x2 = c.x2;
        y2 = c.y2;
        w = c.w;
        h = c.h;
        $('#inputx').val(c.x);
        $('#inputy').val(c.y);
        $('#inputx2').val(c.x2);
        $('#inputy2').val(c.y2);
        $('#inputw').val(c.w);
        $('#inputh').val(c.h);
    }

    var setStatus = function(statusMsg) {
        $('#status').html(statusMsg);
    }

    $('#upload-image-form').submit(function(e) {
        if (formData) {
            e.preventDefault();

            if(!imageChosen()) return;

            setStatus("Laster opp bildet...")

            //JCrop select coordinates
            formData.append("x", x);
            formData.append("y", y);
            formData.append("x2", x2);
            formData.append("y2", y2);
            formData.append("w", w);
            formData.append("h", h);

            $.ajax({
                url: "uploadimage/",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                crossDomain: false,
                success: function (res) {
                    res = JSON.parse(res);
                    setStatus(res['message']);
                    $('#profile-image').attr("src", res['image-url']);
                    $('#upload-image-modal').modal('hide');
                },
                error: function(res) {
                    setStatus(res);
                }
            });
        }
        else {
            if(!imageChosen()) {
                e.preventDefault();
            }
        }
    });

    function imageChosen() {
        var fileInput = $('input[type=file]')[0];
            if(!fileInput || fileInput.files.length < 1) {
                setStatus("Ingen fil valgt.");
                return false;
            }
        return true;
    }

    /* End image cropping and uploading*/

/*
 JS for email management.
*/

    $('button.addnewemail').click(function() {
        $('tr.addnewemail').show();
        $(this).hide();
    });
    $('.emptyonclick').focus(function() {
        $(this).val('');
    });

    $('tr').each(function(i, row) {
// Ajax request to delete an email
        $(row).find('button.delete').click(function() {
            if ($(row).find('button.active').length) {
                alert("Du kan ikke fjerne din primæraddresse.");
            }
            else {
                email = $(row).find('span.email').text();
                deleteEmail(email, row);
            }
        });
// Ajax request to set email as primary
        $(row).find('button.primary').click(function() {
            email = $(row).find('span.email').text();
            setPrimaryEmail(email, row);
        });
// Ajax request to send verification mail
        $(row).find('button.verify').click(function() {
            email = $(row).find('span.email').text();
            verifyEmail(email, row);
        });
    });

    var deleteEmail = function(email, row) {
        $.ajax({
            method: 'POST',
            url: 'delete_email/',
            data: {'email':email, },
            success: function() {
                // TODO Make animation
                $(row).hide();
            },
            error: function(res) {
                if (status === 412) {
                    res = JSON.parse(res['responseText']);
                    alert(res['message']);
                }
                else {
                // TODO write a proper error function
                    alert("Error!");
                }
            },
            crossDomain: false
        });
    }

    var setPrimaryEmail = function(email, row) {
        $.ajax({
            method: 'POST',
            url: 'set_primary/',
            data: {'email':email, },
            success: function() {
                $('button.active').removeClass('active').removeClass('btn-success').addClass('btn-default')
                    .prop('disabled', false).text('Sett primær');
                $(row).find('button.primary').addClass('active').removeClass('btn-default').addClass('btn-success')
                    .prop('disabled', true).text('Primær');
            },
            error: function(res) {
                if (status === 412) {
                    res = JSON.parse(res['responseText']);
                    alert(res['message']);
                }
                else {
                // TODO write a proper error function
                    alert("Error!");
                }
            },
            crossDomain: false
        });
    }

    var verifyEmail = function(email, row) {
        $.ajax({
            method: 'POST',
            url: 'verify_email/',
            data: {'email':email, },
            success: function() {
                alert("tada");
            },
            error: function(res) {
                if (status === 412) {
                    res = JSON.parse(res['responseText']);
                    alert(res['message']);
                }
                else {
                // TODO write a proper error function
                    alert("Error!");
                }
            },
            crossDomain: false
        });
    }
});

<|endoftext|>


<commit_before>MWF.xApplication.service.InvokeDesigner.LP = {
    "title": "InvokeEditor",
    "newInvoke": "Create Invoke",
    "invokeLibrary": "Invoke Library",
    "property": "Property",
    "include": "Include",

    "id": "ID",
    "name": "Name",
    "alias": "Alias",
    "description": "Description",

    "validated": "Is the code format correct",
    "isEnable": "Whether to enable",
    "remoteAddrRegex": "Allow access address expression",
    "lastStartTime": "Last Start Time",
    "lastEndTime": "Last EndTime",

    "true" : "Yes",
    "false" : "No",

    "enable": "Click to enable",
    "disable": "Click to disable",

    "invokeUri": "Invoke address",
    "invokeMethod": "Invoke Method",
    "enableToken": "Enable authentication",

    "enableTokenInfo": "After enabling authentication, you must use the authentication client name and encrypted token to call the service",

    "openLogViewer": "Open LogViewer",
    "debugger": "Debug",
    "run": "Simulation Run",
    "runSuccess": "Run successfully",
    "invokeHead": "head",

    "notice": {
        "save_success": "The interface was saved successfully!",

        "deleteDataTitle": "Delete Data Confirmation",
        "deleteData": "Are you sure to delete the current data and its sub-data?",

        "changeTypeTitle": "Change Data Type Confirmation",
        "changeTypeDeleteChildren": "Changing the data type will delete all child data. Are you sure you want to execute it?",
        "changeType": "Changing the data type will change the value of the data. Are you sure you want to execute it?",

        "inputTypeError": "The data type you entered is wrong, please re-enter",
        "sameKey": "The item name you entered already exists in the object, please re-enter",
        "emptyKey": "Project name cannot be empty, please re-enter",
        "numberKey": "The item name cannot be a number, please re-enter",

        "inputName": "Please enter the interface name",
        "inputCron": "Timed task corn expression cannot be empty"
    },
    "comment" : {
        "entityManager": "EntityManager",
        "applications" : "Services in the system",
        "requestText" : "RequestBody Text",
        "request" : "Request Object",
        "currentPerson": "Current Person",
        "response": "Response Object。Set the response content through \"this.response.setBody(data)\"",
        "organization" : "Organization visit",
        "org" : "Organization quick access method",
        "service" : "webSerivces client"

    }
};
<commit_msg>修改save方法的api描述<commit_after>MWF.xApplication.service.InvokeDesigner.LP = {
    "title": "InvokeEditor",
    "newInvoke": "Create Invoke",
    "invokeLibrary": "Invoke Library",
    "property": "Property",
    "include": "Include",

    "id": "ID",
    "name": "Name",
    "alias": "Alias",
    "description": "Description",

    "validated": "Is the code format correct",
    "isEnable": "Whether to enable",
    "remoteAddrRegex": "Allow access address expression",
    "lastStartTime": "Last Start Time",
    "lastEndTime": "Last EndTime",

    "true" : "Yes",
    "false" : "No",

    "enable": "Click to enable",
    "disable": "Click to disable",

    "invokeUri": "Invoke address",
    "invokeMethod": "Invoke Method",
    "enableToken": "Enable authentication",
    "enableTokenInfo": "After enabling authentication, you must use the authentication client name and encrypted token to call the service",
    "invokeHead": "head",

    "openLogViewer": "Open LogViewer",
    "debugger": "Debug",
    "run": "Simulation Run",
    "runSuccess": "Run successfully",
    "requireArguments": "Request Arguments",
    "runResult": "Execution Result",

    "notice": {
        "save_success": "The interface was saved successfully!",

        "deleteDataTitle": "Delete Data Confirmation",
        "deleteData": "Are you sure to delete the current data and its sub-data?",

        "changeTypeTitle": "Change Data Type Confirmation",
        "changeTypeDeleteChildren": "Changing the data type will delete all child data. Are you sure you want to execute it?",
        "changeType": "Changing the data type will change the value of the data. Are you sure you want to execute it?",

        "inputTypeError": "The data type you entered is wrong, please re-enter",
        "sameKey": "The item name you entered already exists in the object, please re-enter",
        "emptyKey": "Project name cannot be empty, please re-enter",
        "numberKey": "The item name cannot be a number, please re-enter",

        "inputName": "Please enter the interface name",
        "inputCron": "Timed task corn expression cannot be empty"
    },
    "comment" : {
        "entityManager": "EntityManager",
        "applications" : "Services in the system",
        "requestText" : "RequestBody Text",
        "request" : "Request Object",
        "currentPerson": "Current Person",
        "response": "Response Object。Set the response content through \"this.response.setBody(data)\"",
        "organization" : "Organization visit",
        "org" : "Organization quick access method",
        "service" : "webSerivces client"

    }
};
<|endoftext|>


<commit_before>/*
 * Handles currency display
 *
 * It process 'socket.send({payout_currencies:1})` response
 * and display them
 */
function MBDisplayCurrencies(selected, showClass) {
    'use strict';

    var target = document.getElementById('currency'),
        fragment =  document.createDocumentFragment(),
        currencies = page.client.get_storage_value('currencies').split(',');

    if (!target) {
        return;
    }

    while (target && target.firstChild) {
        target.removeChild(target.firstChild);
    }

    if (currencies.length > 1) {
        currencies.forEach(function (currency) {
            var option = document.createElement('option'),
                content = document.createTextNode(currency);

            option.setAttribute('value', currency);
            if (selected && selected == key) {
                option.setAttribute('selected', 'selected');
            }

            option.appendChild(content);
            fragment.appendChild(option);
        });

        target.appendChild(fragment);
        MBDefaults.set('currency', target.value);
    } else {
        $('#currency').replaceWith('' +
                                    (MBTradePage.is_trading_page() && japanese_client() ? '✕' : format_currency(currencies[0])) + '');
        MBDefaults.set('currency', currencies[0]);
    }
}

module.exports = {
    MBDisplayCurrencies: MBDisplayCurrencies,
};
<commit_msg>fix drop down menu for logged out with jp language<commit_after>/*
 * Handles currency display
 *
 * It process 'socket.send({payout_currencies:1})` response
 * and display them
 */
function MBDisplayCurrencies(selected, showClass) {
    'use strict';

    var target = document.getElementById('currency'),
        fragment =  document.createDocumentFragment(),
        currencies = page.client.get_storage_value('currencies').split(',');

    if (!target) {
        return;
    }

    while (target && target.firstChild) {
        target.removeChild(target.firstChild);
    }

    if (currencies.length > 1 && !japanese_client()) {
        currencies.forEach(function (currency) {
            var option = document.createElement('option'),
                content = document.createTextNode(currency);

            option.setAttribute('value', currency);
            if (selected && selected == key) {
                option.setAttribute('selected', 'selected');
            }

            option.appendChild(content);
            fragment.appendChild(option);
        });

        target.appendChild(fragment);
        MBDefaults.set('currency', target.value);
    } else {
        $('#currency').replaceWith('' +
                                    (MBTradePage.is_trading_page() && japanese_client() ? '✕' : format_currency(currencies[0])) + '');
        MBDefaults.set('currency', currencies[0]);
    }
}

module.exports = {
    MBDisplayCurrencies: MBDisplayCurrencies,
};
<|endoftext|>


<commit_before>import * as util from '../../flows/utils'

/* eslint-disable no-await-in-loop */
/* eslint-disable no-unused-vars */

const clickSaveContinue = async () => {
  console.log('here')
  await util.clickButton('Save and continue')
}

const createBrief = async () => {
  await util.clickLink('/2/outcome-choice', true)
  await util.clickLink('/2/buyer-rfx/create', true)
  await util.clickLink('Create and publish request')
  await util.clickButton('Start now')
}

const selectDropBox = async () => {
  const rfxPanelCategory = process.env.RFX_PANEL_CATEGORY
  await page.select(`#seller-search-category-select`, rfxPanelCategory)

  const rfxSellerName = process.env.RFX_SELLER_NAME
  await util.sleep(100)
  await util.typeInReactInput('seller-search', { value: rfxSellerName })
  let searchResult = await util.getElementHandles(`//input[@id="seller-search"]/../../ul/li[1]/a`)
  let sr = searchResult[0]
  sr.click()

  await util.typeInReactInput('seller-search', { value: '%%%' })
  searchResult = await util.getElementHandles('//input[@id="seller-search"]/../../ul/li')
  const resultCount = searchResult.length
  for (let i = 1; i <= resultCount; i += 1) {
    if (i > 1) {
      await util.sleep(100)
      await util.typeInReactInput('seller-search', { value: '%%%' })
    }
    searchResult = await util.getElementHandles(`//input[@id="seller-search"]/../../ul/li[${i}]/a`)
    sr = searchResult[0]
    sr.click()
  }
  await clickSaveContinue()
}

const fillWhoCanRespond = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must select at least one panel category')
  await selectDropBox()
}

const fillAbout = async (role, locations) => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add a title')
  await util.matchText('li', 'You must add the name of your department, agency or organisation')
  await util.matchText('li', 'You must add a summary of work to be done')
  await util.matchText('li', 'You must add the working arrangements')
  await util.matchText('li', 'You must select a location of where the work can be done')
  await util.typeInReactInput('title', { value: role })
  await util.typeInReactInput('organisation', { numberOfCharacters: 100 })
  await util.typeInReactInput('summary', { numberOfWords: 150 })

  /*
  for (let i; i < locations.length; i+=1) {
    const location = locations[i]
    await util.selectCheck(location)
  }

  */

  locations.forEach(async location => {
    await util.selectCheck(location)
  })

  await util.typeInReactInput('working_arrangements', { numberOfCharacters: 150 })
  await util.typeInReactInput('clearance', { numberOfCharacters: 100 })
  await clickSaveContinue()
}

const fillResponseFormats = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must choose what you would like sellers to provide through the Marketplace')
  await util.selectCheck('Written proposal')
  await clickSaveContinue()
  await util.matchText('li', 'You must select at least one proposal type.')
  await util.selectCheck('Breakdown of costs')
  await util.selectCheck('Case study')
  await util.selectCheck('References')
  await util.selectCheck('Résumés')
  await util.selectCheck('Response template')
  await util.selectCheck('Presentation')
  await clickSaveContinue()
}

const fillRequirements = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must upload a requirements document')
  await util.upload('file_0', 'document.pdf', 'Requirements document')
  await util.upload('file_0', 'document.pdf', 'Response template')
  await util.upload('file_0', 'document.pdf', 'Additional documents (optional)')
  await util.typeInReactInput('industryBriefing', { numberOfWords: 150 })
  await clickSaveContinue()
}
const fillTimeframesAndBudget = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add an estimated start date')
  await util.matchText('li', 'You must add a contract length')
  await util.typeInReactInput('start_date', { numberOfCharacters: 150 })
  await util.typeInReactInput('contract_length-label', { numberOfCharacters: 50 })
  await util.typeInReactInput('contract_extensions', { numberOfCharacters: 50 })
  await util.typeInReactInput('budget_range', { numberOfWords: 150 })
  await clickSaveContinue()
}

const fillEvaluationCriteria = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must not have any empty criteria.')
  await util.matchText('li', 'Weightings must be greater than 0.')
  await util.matchText('li', 'You must not have any empty criteria.')
  await util.clickLink('Add another criteria')
  await util.typeInReactInput('criteria_0', { numberOfWords: 50 })
  await util.typeInReactInput('weighting_0', { value: '50' })
  await util.typeInReactInput('criteria_1', { numberOfWords: 50 })
  await util.typeInReactInput('weighting_1', { value: '50' })
  await clickSaveContinue()
}

const fillClosingDate = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add a closing date at least 2 days from now')
  await util.matchText('li', 'You must add a contact number')
  const now = new Date()
  const future = new Date(now.setDate(now.getDate() + 14))
  await util.typeInReactInput('day', { value: `${future.getDate()}` })
  await util.typeInReactInput('month', { value: `${future.getMonth() + 1}` })
  await util.typeInReactInput('year', { value: `${future.getFullYear()}` })
  await util.typeInReactInput('contact', { value: '0123456789' })
  await clickSaveContinue()
}

const fillPublishBrief = async () => {
  await util.clickButton('Publish')
  await util.matchText('h1', 'Your opportunity is now live, and the invited sellers have been notified.')
}

const create = async params => {
  console.log('Starting to create outcome RXF brief')
  await createBrief()
  await fillWhoCanRespond()
  await fillAbout(params.title, params.locations)
  await fillResponseFormats()
  await fillRequirements()
  await fillTimeframesAndBudget()
  await fillEvaluationCriteria()
  await fillClosingDate()
  await fillPublishBrief()
}

export default create

<commit_msg>Update rfx.js<commit_after>import * as util from '../../flows/utils'

/* eslint-disable no-await-in-loop */
/* eslint-disable no-unused-vars */

const clickSaveContinue = async () => {
  console.log('here')
  await util.clickButton('Save and continue')
}

const createBrief = async () => {
  await util.clickLink('/2/outcome-choice', true)
  await util.clickLink('/2/buyer-rfx/create', true)
  await util.clickLink('Create and publish request')
  await util.clickButton('Start now')
}

const selectDropBox = async () => {
  const rfxPanelCategory = process.env.RFX_PANEL_CATEGORY
  await page.select(`#seller-search-category-select`, rfxPanelCategory)

  const rfxSellerName = process.env.RFX_SELLER_NAME
  await util.sleep(100)
  await util.typeInReactInput('seller-search', { value: rfxSellerName })
  let searchResult = await util.getElementHandles(`//input[@id="seller-search"]/../../ul/li[1]/a`)
  let sr = searchResult[0]
  sr.click()

  await util.typeInReactInput('seller-search', { value: '%%%' })
  searchResult = await util.getElementHandles('//input[@id="seller-search"]/../../ul/li')
  const resultCount = searchResult.length
  for (let i = 1; i <= resultCount; i += 1) {
    if (i > 1) {
      await util.sleep(100)
      await util.typeInReactInput('seller-search', { value: '%%%' })
    }
    searchResult = await util.getElementHandles(`//input[@id="seller-search"]/../../ul/li[${i}]/a`)
    sr = searchResult[0]
    sr.click()
  }
  await clickSaveContinue()
}

const fillWhoCanRespond = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must select at least one panel category')
  await selectDropBox()
}

const fillAbout = async (role, locations) => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add a title')
  await util.matchText('li', 'You must add the name of your department, agency or organisation')
  await util.matchText('li', 'You must add a summary of work to be done')
  await util.matchText('li', 'You must add the working arrangements')
  await util.matchText('li', 'You must select a location of where the work can be done')
  await util.typeInReactInput('title', { value: role })
  await util.typeInReactInput('organisation', { numberOfCharacters: 100 })
  await util.typeInReactInput('summary', { numberOfWords: 150 })

  /*
  for (let i; i < locations.length; i+=1) {
    const location = locations[i]
    await util.selectCheck(location)
  }

  */

  locations.forEach(async location => {
    await util.selectCheck(location)
  })

  await util.typeInReactInput('working_arrangements', { numberOfCharacters: 150 })
  await util.typeInReactInput('clearance', { numberOfCharacters: 100 })
  await clickSaveContinue()
}

const fillResponseFormats = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must choose what you would like sellers to provide through the Marketplace')
  await util.selectCheck('Written proposal')
  await clickSaveContinue()
  await util.matchText('li', 'You must select at least one proposal type.')
  await util.selectCheck('Breakdown of costs')
  await util.selectCheck('Case study')
  await util.selectCheck('References')
  await util.selectCheck('Résumés')
  await util.selectCheck('Response template')
  await util.selectCheck('Presentation')
  await clickSaveContinue()
}

const fillRequirements = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must upload a requirements document')
  await util.upload('file_0', 'document.pdf', 'Requirements document')
  await util.upload('file_0', 'document.pdf', 'Response template')
  await util.upload('file_0', 'document.pdf', 'Additional documents (optional)')
  await util.typeInReactInput('industryBriefing', { numberOfWords: 150 })
  await clickSaveContinue()
}
const fillTimeframesAndBudget = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add an estimated start date')
  await util.matchText('li', 'You must add a contract length')
  await util.typeInReactInput('start_date', { numberOfCharacters: 150 })
  await util.typeInReactInput('contract_length-label', { numberOfCharacters: 50 })
  await util.typeInReactInput('contract_extensions', { numberOfCharacters: 50 })
  await util.typeInReactInput('budget_range', { numberOfWords: 150 })
  await clickSaveContinue()
}

const fillEvaluationCriteria = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must not have any empty criteria.')
  await util.matchText('li', 'Weightings must be greater than 0.')
  await util.matchText('li', 'You must not have any empty criteria.')
  await util.clickLink('Add another criteria')
  await util.typeInReactInput('criteria_0', { numberOfWords: 50 })
  await util.typeInReactInput('weighting_0', { value: '50' })
  await util.typeInReactInput('criteria_1', { numberOfWords: 50 })
  await util.typeInReactInput('weighting_1', { value: '50' })
  await clickSaveContinue()
}

const fillClosingDate = async () => {
  await clickSaveContinue()
  await util.matchText('li', 'You must add a closing date at least 2 days from now')
  await util.matchText('li', 'You must add a contact number')
  const now = new Date()
  const future = new Date(now.setDate(now.getDate() + 14))
  await util.typeInReactInput('day', { value: `${future.getDate()}` })
  await util.typeInReactInput('month', { value: `${future.getMonth() + 1}` })
  await util.typeInReactInput('year', { value: `${future.getFullYear()}` })
  await util.typeInReactInput('contact', { value: '0123456789' })
  await clickSaveContinue()
}

const fillPublishBrief = async () => {
  await util.clickButton('Publish')
  await util.matchText('h1', 'Your opportunity is now live, and the invited sellers have been notified.')
}

const create = async params => {
  console.log('Starting to create outcome RXF brief')
  await createBrief()
  await fillWhoCanRespond()
  await fillAbout(params.title, params.locations)
  await fillResponseFormats()
  await fillRequirements()
  await fillTimeframesAndBudget()
  await fillEvaluationCriteria()
  await fillClosingDate()
  await fillPublishBrief()
}

export default create
<|endoftext|>


<commit_before>'use strict';

(function() {
  angular
      .module('bitcoincom.controllers')
      .controller('buyBitcoinPurchaseHistoryController', purchaseHistoryController);

  function purchaseHistoryController($scope) {
    var vm = this;

    vm.history = [];

    $scope.$on('$ionicView.beforeEnter', _onBeforeEnter);

    function _initVariables() {
      vm.history = [];
      moonPayService.getTransactions().then(
        function onGetTransactionsSuccess(transactions) {
          vm.history = transactions;
        }
      );
    }

    function _onBeforeEnter() {
      _initVariables();
    }

  }
})();
<commit_msg>Handle error for the purchase history<commit_after>'use strict';

(function() {
  angular
      .module('bitcoincom.controllers')
      .controller('buyBitcoinPurchaseHistoryController', purchaseHistoryController);

  function purchaseHistoryController(
    popupService,
    $scope, $ionicHistory
  ) {
    var vm = this;

    vm.history = [];

    $scope.$on('$ionicView.beforeEnter', _onBeforeEnter);

    function _initVariables() {
      vm.history = [];
      moonPayService.getTransactions().then(
        function onGetTransactionsSuccess(transactions) {
          vm.history = transactions;
        },
        function onGetTransactionsError(err) {
          var title = gettextCatalog.getString('Error Getting Transaction History');
          var message = err.message || gettextCatalog.getString('An error occurred when getting your transaction history.');
          var okText = gettextCatalog.getString('Go Back');
          popupService.showAlert(title, message,
            function onAlertDismissed() {
              $ionicHistory.goBack();
            },
            okText
          );
        }
      );
    }

    function _onBeforeEnter() {
      _initVariables();
    }

  }
})();
<|endoftext|>


<commit_before>var target : Transform;
var distance = 10.0;

var xSpeed = 250.0;
var ySpeed = 120.0;
var zSpeed = 100.0;

var yMinLimit = -20;
var yMaxLimit = 80;

private var x = 0.0;
private var y = 0.0;

@script AddComponentMenu("Camera-Control/Mouse Orbit")

function Start () {
    var angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

	// Make the rigid body not change rotation
  if (rigidbody)
		rigidbody.freezeRotation = true;
}

function LateUpdate () {
    if (target) {
        x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;

        var distRaw = -Input.GetAxis("Mouse ScrollWheel") * zSpeed;

        if( Input.GetKey("up") )
          --distRaw;
        if( Input.GetKey("down") )
          ++distRaw;

        distance += distRaw * 0.02;

        y = ClampAngle(y, yMinLimit, yMaxLimit);

        var rotation = Quaternion.Euler(y, x, 0);
        var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;

        transform.rotation = rotation;
        transform.position = position;
    }
}

static function ClampAngle (angle : float, min : float, max : float) {
	if (angle < -360)
		angle += 360;
	if (angle > 360)
		angle -= 360;
	return Mathf.Clamp (angle, min, max);
}<commit_msg>Camera distance min clamp<commit_after>var target : Transform;
var distance = 10.0;

var xSpeed = 250.0;
var ySpeed = 120.0;
var zSpeed = 100.0;

var yMinLimit = -20;
var yMaxLimit = 80;

private var x = 0.0;
private var y = 0.0;

@script AddComponentMenu("Camera-Control/Mouse Orbit")

function Start () {
    var angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

 // Make the rigid body not change rotation
  if (rigidbody)
   rigidbody.freezeRotation = true;
}

function LateUpdate ()
{
    if (target)
    {
        x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;

        var distRaw = -Input.GetAxis("Mouse ScrollWheel") * zSpeed;

        if( Input.GetKey("up") )
          --distRaw;
        if( Input.GetKey("down") )
          ++distRaw;

        distance = Mathf.Max( distance + distRaw * 0.02, 0 );

        y = ClampAngle(y, yMinLimit, yMaxLimit);

        var rotation = Quaternion.Euler(y, x, 0);
        var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;

        transform.rotation = rotation;
        transform.position = position;
    }
}

static function ClampAngle (angle : float, min : float, max : float) {
 if (angle < -360)
   angle += 360;
 if (angle > 360)
   angle -= 360;
 return Mathf.Clamp (angle, min, max);
}<|endoftext|>


<commit_before>import fr from 'element-ui/lib/locale/lang/fr';
import ru from 'element-ui/lib/locale/lang/ru-RU';
import es from 'element-ui/lib/locale/lang/es';
import en from 'element-ui/lib/locale/lang/en';

const languages = {
    fr, ru, es, en,
};

export function elLang() {
    const lang = document.documentElement.lang;
    return languages[lang] || languages.en;
}<commit_msg>load element-ui german locales<commit_after>import fr from 'element-ui/lib/locale/lang/fr';
import ru from 'element-ui/lib/locale/lang/ru-RU';
import es from 'element-ui/lib/locale/lang/es';
import en from 'element-ui/lib/locale/lang/en';
import de from 'element-ui/lib/locale/lang/de';

const languages = {
    fr, ru, es, en, de
};

export function elLang() {
    const lang = document.documentElement.lang;
    return languages[lang] || languages.en;
}<|endoftext|>


<commit_before>// @flow

import fs from "fs";
import path from "path";
import buildDebug from "debug";
import cloneDeep from "lodash/cloneDeep";
import * as t from "@babel/types";
import type { PluginPasses } from "../config";
import convertSourceMap, { typeof Converter } from "convert-source-map";
import { parse } from "@babel/parser";
import { codeFrameColumns } from "@babel/code-frame";
import File from "./file/file";
import generateMissingPluginMessage from "./util/missing-plugin-helper";

const debug = buildDebug("babel:transform:file");

export type NormalizedFile = {
  code: string,
  ast: {},
  inputMap: Converter | null,
};

export default function normalizeFile(
  pluginPasses: PluginPasses,
  options: Object,
  code: string,
  ast: ?(BabelNodeFile | BabelNodeProgram),
): File {
  code = `${code || ""}`;

  if (ast) {
    if (ast.type === "Program") {
      ast = t.file(ast, [], []);
    } else if (ast.type !== "File") {
      throw new Error("AST root must be a Program or File node");
    }
    ast = cloneDeep(ast);
  } else {
    // The parser's AST types aren't fully compatible with the types generated
    // by the logic in babel-types.
    // $FlowFixMe
    ast = parser(pluginPasses, options, code);
  }

  let inputMap = null;
  if (options.inputSourceMap !== false) {
    // If an explicit object is passed in, it overrides the processing of
    // source maps that may be in the file itself.
    if (typeof options.inputSourceMap === "object") {
      inputMap = convertSourceMap.fromObject(options.inputSourceMap);
    }

    if (!inputMap) {
      const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast);
      if (lastComment) {
        try {
          inputMap = convertSourceMap.fromComment(lastComment);
        } catch (err) {
          debug("discarding unknown inline input sourcemap", err);
        }
      }
    }

    if (!inputMap) {
      const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast);
      if (typeof options.filename === "string" && lastComment) {
        try {
          const inputMapFilename = EXTERNAL_SOURCEMAP_REGEX.exec(
            lastComment,
          )[1];
          inputMap = convertSourceMap.fromJSON(
            fs.readFileSync(
              path.resolve(path.dirname(options.filename), inputMapFilename),
            ),
          );
        } catch (err) {
          debug("discarding unknown file input sourcemap", err);
        }
      } else if (lastComment) {
        debug("discarding un-loadable file input sourcemap");
      }
    }
  }

  return new File(options, {
    code,
    ast,
    inputMap,
  });
}

function parser(
  pluginPasses: PluginPasses,
  { parserOpts, highlightCode = true, filename = "unknown" }: Object,
  code: string,
) {
  try {
    const results = [];
    for (const plugins of pluginPasses) {
      for (const plugin of plugins) {
        const { parserOverride } = plugin;
        if (parserOverride) {
          const ast = parserOverride(code, parserOpts, parse);

          if (ast !== undefined) results.push(ast);
        }
      }
    }

    if (results.length === 0) {
      return parse(code, parserOpts);
    } else if (results.length === 1) {
      if (typeof results[0].then === "function") {
        throw new Error(
          `You appear to be using an async parser plugin, ` +
            `which your current version of Babel does not support. ` +
            `If you're using a published plugin, you may need to upgrade ` +
            `your @babel/core version.`,
        );
      }
      return results[0];
    }
    throw new Error("More than one plugin attempted to override parsing.");
  } catch (err) {
    if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") {
      err.message +=
        "\nConsider renaming the file to '.mjs', or setting sourceType:module " +
        "or sourceType:unambiguous in your Babel config for this file.";
      // err.code will be changed to BABEL_PARSE_ERROR later.
    }

    const { loc, missingPlugin } = err;
    if (loc) {
      const codeFrame = codeFrameColumns(
        code,
        {
          start: {
            line: loc.line,
            column: loc.column + 1,
          },
        },
        {
          highlightCode,
        },
      );
      if (missingPlugin) {
        err.message =
          `${filename}: ` +
          generateMissingPluginMessage(missingPlugin[0], loc, codeFrame);
      } else {
        err.message = `${filename}: ${err.message}\n\n` + codeFrame;
      }
      err.code = "BABEL_PARSE_ERROR";
    }
    throw err;
  }
}

// These regexps are copied from the convert-source-map package,
// but without // or /* at the beginning of the comment.

// eslint-disable-next-line max-len
const INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/;
const EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/;

function extractCommentsFromList(regex, comments, lastComment) {
  if (comments) {
    comments = comments.filter(({ value }) => {
      if (regex.test(value)) {
        lastComment = value;
        return false;
      }
      return true;
    });
  }
  return [comments, lastComment];
}

function extractComments(regex, ast) {
  let lastComment = null;
  t.traverseFast(ast, node => {
    // $FlowIgnore destructuring with expressions is not supported
    [node.leadingComments, lastComment] = extractCommentsFromList(
      regex,
      node.leadingComments,
      lastComment,
    );
    // $FlowIgnore destructuring with expressions is not supported
    [node.innerComments, lastComment] = extractCommentsFromList(
      regex,
      node.innerComments,
      lastComment,
    );
    // $FlowIgnore destructuring with expressions is not supported
    [node.trailingComments, lastComment] = extractCommentsFromList(
      regex,
      node.trailingComments,
      lastComment,
    );
  });
  return lastComment;
}
<commit_msg>Fix flow<commit_after>// @flow

import fs from "fs";
import path from "path";
import buildDebug from "debug";
import cloneDeep from "lodash/cloneDeep";
import * as t from "@babel/types";
import type { PluginPasses } from "../config";
import convertSourceMap, { typeof Converter } from "convert-source-map";
import { parse } from "@babel/parser";
import { codeFrameColumns } from "@babel/code-frame";
import File from "./file/file";
import generateMissingPluginMessage from "./util/missing-plugin-helper";

const debug = buildDebug("babel:transform:file");

export type NormalizedFile = {
  code: string,
  ast: {},
  inputMap: Converter | null,
};

export default function normalizeFile(
  pluginPasses: PluginPasses,
  options: Object,
  code: string,
  ast: ?(BabelNodeFile | BabelNodeProgram),
): File {
  code = `${code || ""}`;

  if (ast) {
    if (ast.type === "Program") {
      ast = t.file(ast, [], []);
    } else if (ast.type !== "File") {
      throw new Error("AST root must be a Program or File node");
    }
    ast = cloneDeep(ast);
  } else {
    // The parser's AST types aren't fully compatible with the types generated
    // by the logic in babel-types.
    // $FlowFixMe
    ast = parser(pluginPasses, options, code);
  }

  let inputMap = null;
  if (options.inputSourceMap !== false) {
    // If an explicit object is passed in, it overrides the processing of
    // source maps that may be in the file itself.
    if (typeof options.inputSourceMap === "object") {
      inputMap = convertSourceMap.fromObject(options.inputSourceMap);
    }

    if (!inputMap) {
      const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast);
      if (lastComment) {
        try {
          inputMap = convertSourceMap.fromComment(lastComment);
        } catch (err) {
          debug("discarding unknown inline input sourcemap", err);
        }
      }
    }

    if (!inputMap) {
      const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast);
      if (typeof options.filename === "string" && lastComment) {
        try {
          const match = EXTERNAL_SOURCEMAP_REGEX.exec(lastComment);
          if (!match) throw new Error("Invalid source map comment format.");
          inputMap = convertSourceMap.fromJSON(
            fs.readFileSync(
              path.resolve(path.dirname(options.filename), match[1]),
              "utf8",
            ),
          );
        } catch (err) {
          debug("discarding unknown file input sourcemap", err);
        }
      } else if (lastComment) {
        debug("discarding un-loadable file input sourcemap");
      }
    }
  }

  return new File(options, {
    code,
    ast,
    inputMap,
  });
}

function parser(
  pluginPasses: PluginPasses,
  { parserOpts, highlightCode = true, filename = "unknown" }: Object,
  code: string,
) {
  try {
    const results = [];
    for (const plugins of pluginPasses) {
      for (const plugin of plugins) {
        const { parserOverride } = plugin;
        if (parserOverride) {
          const ast = parserOverride(code, parserOpts, parse);

          if (ast !== undefined) results.push(ast);
        }
      }
    }

    if (results.length === 0) {
      return parse(code, parserOpts);
    } else if (results.length === 1) {
      if (typeof results[0].then === "function") {
        throw new Error(
          `You appear to be using an async parser plugin, ` +
            `which your current version of Babel does not support. ` +
            `If you're using a published plugin, you may need to upgrade ` +
            `your @babel/core version.`,
        );
      }
      return results[0];
    }
    throw new Error("More than one plugin attempted to override parsing.");
  } catch (err) {
    if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") {
      err.message +=
        "\nConsider renaming the file to '.mjs', or setting sourceType:module " +
        "or sourceType:unambiguous in your Babel config for this file.";
      // err.code will be changed to BABEL_PARSE_ERROR later.
    }

    const { loc, missingPlugin } = err;
    if (loc) {
      const codeFrame = codeFrameColumns(
        code,
        {
          start: {
            line: loc.line,
            column: loc.column + 1,
          },
        },
        {
          highlightCode,
        },
      );
      if (missingPlugin) {
        err.message =
          `${filename}: ` +
          generateMissingPluginMessage(missingPlugin[0], loc, codeFrame);
      } else {
        err.message = `${filename}: ${err.message}\n\n` + codeFrame;
      }
      err.code = "BABEL_PARSE_ERROR";
    }
    throw err;
  }
}

// These regexps are copied from the convert-source-map package,
// but without // or /* at the beginning of the comment.

// eslint-disable-next-line max-len
const INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/;
const EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/;

function extractCommentsFromList(regex, comments, lastComment) {
  if (comments) {
    comments = comments.filter(({ value }) => {
      if (regex.test(value)) {
        lastComment = value;
        return false;
      }
      return true;
    });
  }
  return [comments, lastComment];
}

function extractComments(regex, ast) {
  let lastComment = null;
  t.traverseFast(ast, node => {
    // $FlowIgnore destructuring with expressions is not supported
    [node.leadingComments, lastComment] = extractCommentsFromList(
      regex,
      node.leadingComments,
      lastComment,
    );
    // $FlowIgnore destructuring with expressions is not supported
    [node.innerComments, lastComment] = extractCommentsFromList(
      regex,
      node.innerComments,
      lastComment,
    );
    // $FlowIgnore destructuring with expressions is not supported
    [node.trailingComments, lastComment] = extractCommentsFromList(
      regex,
      node.trailingComments,
      lastComment,
    );
  });
  return lastComment;
}
<|endoftext|>