Example #1
0
    function nodeDataExtract(node) {


        var data = {};

        if (node.children           === void 0 ||
            node.children.length    === 0) {
            if (node.attr !== void 0 &&
                !_.isEmpty(node.attr)) {
                return {
                    '_attributes' : node.attr,
                    '_value'      : node.val
                };
            }

            return node.val ;
        }

        _(node.children).each(function(child) {

            var tmp = null;
            if (child.children        !== void 0 &&
                child.children.length !== 0) {

                var childToExtract = child;
                if (child.children.length === 1) {
                    if (child.children[0].name === getName(child.name)) {
                        childToExtract = child.children[0];
                    }

                    data[getName(child.name)] = nodeDataExtract(childToExtract);
                }
                else
                {

                    if (!_.isArray(data[getName(child.name)])) {
                        if (_.isObject(data[getName(child.name)])) {
                            tmp = data[getName(child.name)];
                            data[getName(child.name)] = [];
                            data[getName(child.name)].push(tmp);
                        } else {
                            data[getName(child.name)] = [];
                        }
                    }

                    if (childToExtract.attr !== void 0 &&
                        !_.isEmpty(childToExtract.attr)) {
                        data[getName(child.name)].push({
                            '_attributes'   : childToExtract.attr,
                            '_value'        : nodeDataExtract(childToExtract, node.name)
                        });
                    }
                    else {
                        data[getName(child.name)].push(nodeDataExtract(childToExtract, node.name));
                        if (_.isArray(data[getName(child.name)])) {
                            if (data[getName(child.name)].length === 1) {
                                data[getName(child.name)] = data[getName(child.name)][0];
                            }
                        }
                    }
                }
            }
            else
            {
                if (data[getName(child.name)] !== void 0) {
                    if (!_.isArray(data[getName(child.name)])) {
                        tmp = data[getName(child.name)];
                        data[getName(child.name)] = [];
                        data[getName(child.name)].push(tmp);
                    }
                    data[getName(child.name)].push(nodeDataExtract(child, node.name));
                } else {
                    data[getName(child.name)] = nodeDataExtract(child, node.name);
                }
            }
        });



        return data;
    }
Example #2
0
            app[verb](uri, function(req, res) {
                var holder = {
                    params: {},
                    headers: {},
                    routeParams: {},
                    connection: {
                        remoteAddress: req.connection.remoteAddress
                    }
                };

                // get all query params
                collectHttpQueryParams(req, holder, false);

                // find a route (i.e. associated cooked script)
                var route = _(verbRouteVariants).chain()
                    .filter(function (verbRouteVariant) {
                        return _.isEqual(_.intersection(_.keys(holder.params), _.keys(verbRouteVariant.query)),
                            _.keys(verbRouteVariant.query))
                    })
                    .reduce(function (match, route) {
                        return match == null ?
                            route : _.keys(route.query).length > _.keys(match.query).length ? route : match;
                    }, null)
                    .value();

                if (!route) {
                    res.writeHead(400, 'Bad input', {
                        'content-type' : 'application/json'
                    });
                    res.write(JSON.stringify({'err' : 'No matching route'}));
                    res.end();
                    return;
                }

                // collect the path params
                var keys = _.keys(req.params);
                _.each(keys, function(key) {
                    holder.routeParams[key] = req.params[key];
                });

                _.each(route.query, function(queryParam, paramName) {
                    holder.routeParams[queryParam] = holder.params[paramName].toString();
                });

                // collect headers
                collectHttpHeaders(req, holder);
                holder.connection = {
                    remoteAddress: req.connection.remoteAddress
                }

                var execState = [];
                engine.execute(route.script,
                    {
                        request: holder,
                        route: uri,
                        context: req.body || {}
                    },
                    function(emitter) {
                        setupExecStateEmitter(emitter, execState, req.param('events'));
                        setupCounters(emitter);
                        emitter.on('end', function(err, results) {
                            return handleResponseCB(req, res, execState, err, results);
                        });
                    }
                );
            });
Example #3
0
			it('should call `load` for every project name', function() {
				_(expected.projectNames).each(function(projectName, index) {
					var args = mocks.projects.load.getCall(index).args;
					expect(args[0]).eql({name: projectName});
				});
			});
Example #4
0
 data: yaml.dump(_(data).reduce(function(memo,v,k) {
     if (!(k in defaults)) return memo;
     memo[k] = k === 'styles' ? _(v).keys() : v;
     return memo;
 }, {}), null, 2)
Example #5
0
 getContentItemsByIds: function(ids) {
     return _(this.allContentItems).filter(function(model) {
         return ids.indexOf(model.getId()) !== -1;
     });
 }
Example #6
0
 initialize: function() {
     _(this).bindAll('getRemainingCount');
 },
Example #7
0
 .then(function (records) {
     return _(records).pluck(primaryKey);
 })
Example #8
0
/*
Consider all integer combinations of a^b for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:

    2^2=4, 2^3=8, 2^4=16, 2^5=32
    3^2=9, 3^3=27, 3^4=81, 3^5=243
    4^2=16, 4^3=64, 4^4=256, 4^5=1024
    5^2=25, 5^3=125, 5^4=625, 5^5=3125

If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:

4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

How many distinct terms are in the sequence generated by a^b for 2 ≤ a ≤ 100
and 2 ≤ b ≤ 100?
*/

var Bigint = require('bigint');
var _ = require('underscore');

console.log(_((function() {
	var a, b, res = [];
	for (a=2; a<101; a++) {
		for (b=2; b<101; b++) {
			res.push(String(Bigint.pow(a, b)));
		}
	}
	return res;
}())).chain().flatten().uniq().value().length);

Example #9
0
const LotComponent = (props, reactContext) => {
    const context = props.context;

    // Sort characterization arrays
    const characterizations = _(context.characterizations).sortBy(characterization => (
        [characterization.target.label, characterization.target.organism.name]
    ));

    // Compile the document list
    const documentSpecs = [
        { documents: characterizations },
    ];

    // Build antibody status panel
    const PanelView = globals.panelViews.lookup(context);
    const antibodyStatuses = <PanelView context={context} key={context['@id']} />;

    // Make an array of targets with no falsy entries and no repeats
    const targets = {};
    if (context.lot_reviews && context.lot_reviews.length) {
        context.lot_reviews.forEach((lotReview) => {
            lotReview.targets.forEach((target) => {
                targets[target['@id']] = target;
            });
        });
    }
    const targetKeys = Object.keys(targets);

    // Set up the breadcrumbs
    const organismComponents = [];
    const organismTerms = [];
    const organismTips = [];
    const geneComponents = [];
    const geneTerms = [];
    const geneTips = [];
    targetKeys.forEach((key, i) => {
        const scientificName = targets[key].organism.scientific_name;
        const geneName = targets[key].gene_name;

        // Add to the information on organisms from the targets
        organismComponents.push(<span key={key}>{i > 0 ? <span> + <i>{scientificName}</i></span> : <i>{scientificName}</i>}</span>);
        organismTerms.push(`targets.organism.scientific_name=${scientificName}`);
        organismTips.push(scientificName);

        // Add to the information on gene names from the targets
        if (geneName && geneName !== 'unknown') {
            geneComponents.push(<span key={key}>{i > 0 ? <span> + {geneName}</span> : <span>{geneName}</span>}</span>);
            geneTerms.push(`targets.gene_name=${geneName}`);
            geneTips.push(geneName);
        }
    });

    const organismQuery = organismTerms.join('&');
    const geneQuery = geneTerms.join('&');
    const crumbs = [
        { id: 'Antibodies' },
        { id: organismComponents, query: organismQuery, tip: organismTips.join(' + ') },
        { id: geneComponents.length ? geneComponents : null, query: geneQuery, tip: geneTips.join(' + ') },
    ];

    // Make string of alternate accessions
    const altacc = context.alternate_accessions ? context.alternate_accessions.join(', ') : undefined;

    return (
        <div className={globals.itemClass(context, 'view-item')}>
            <header className="row">
                <div className="col-sm-12">
                    <Breadcrumbs root="/search/?type=antibody_lot" crumbs={crumbs} />
                    <h2>{context.accession}</h2>
                    {altacc ? <h4 className="repl-acc">Replaces {altacc}</h4> : null}
                    <h3>
                        {targetKeys.length ?
                            <span>Antibody against {Object.keys(targets).map((target, i) => {
                                const targetObj = targets[target];
                                return <span key={i}>{i !== 0 ? ', ' : ''}<em>{targetObj.organism.scientific_name}</em>{` ${targetObj.label}`}</span>;
                            })}</span>
                        :
                            <span>Antibody</span>
                        }
                    </h3>
                    <div className="status-line">
                        <div className="characterization-status-labels">
                            <StatusLabel title="Status" status={context.status} />
                        </div>
                        {props.auditIndicators(context.audit, 'antibody-audit', { session: reactContext.session })}
                    </div>
                </div>
            </header>
            {props.auditDetail(context.audit, 'antibody-audit', { except: context['@id'], session: reactContext.session })}

            {context.lot_reviews && context.lot_reviews.length ?
                <div className="antibody-statuses">
                    {antibodyStatuses}
                </div>
            :
                <div className="characterization-status-labels">
                    <StatusLabel status="Awaiting lab characterization" />
                </div>
            }

            <Panel addClasses="data-display">
                <PanelBody>
                    <dl className="key-value">
                        <div data-test="source">
                            <dt>Source (vendor)</dt>
                            <dd><a href={context.source.url}>{context.source.title}</a></dd>
                        </div>

                        <div data-test="productid">
                            <dt>Product ID</dt>
                            <dd><a href={context.url}>{context.product_id}</a></dd>
                        </div>

                        <div data-test="lotid">
                            <dt>Lot ID</dt>
                            <dd>{context.lot_id}</dd>
                        </div>

                        {Object.keys(targets).length ?
                            <div data-test="targets">
                                <dt>Targets</dt>
                                <dd>
                                    {targetKeys.map((target, i) => {
                                        const targetObj = targets[target];
                                        return <span key={i}>{i !== 0 ? ', ' : ''}<a href={target}>{targetObj.label}{' ('}<em>{targetObj.organism.scientific_name}</em>{')'}</a></span>;
                                    })}
                                </dd>
                            </div>
                        : null}

                        {context.lot_id_alias && context.lot_id_alias.length ?
                            <div data-test="lotidalias">
                                <dt>Lot ID aliases</dt>
                                <dd>{context.lot_id_alias.join(', ')}</dd>
                            </div>
                        : null}

                        <div data-test="host">
                            <dt>Host</dt>
                            <dd className="sentence-case">{context.host_organism.name}</dd>
                        </div>

                        {context.clonality ?
                            <div data-test="clonality">
                                <dt>Clonality</dt>
                                <dd className="sentence-case">{context.clonality}</dd>
                            </div>
                        : null}

                        {context.purifications && context.purifications.length ?
                            <div data-test="purifications">
                                <dt>Purification</dt>
                                <dd className="sentence-case">{context.purifications.join(', ')}</dd>
                            </div>
                        : null}

                        {context.isotype ?
                            <div data-test="isotype">
                                <dt>Isotype</dt>
                                <dd className="sentence-case">{context.isotype}</dd>
                            </div>
                        : null}

                        {context.antigen_description ?
                            <div data-test="antigendescription">
                                <dt>Antigen description</dt>
                                <dd>{context.antigen_description}</dd>
                            </div>
                        : null}

                        {context.antigen_sequence ?
                            <div data-test="antigensequence">
                                <dt>Antigen sequence</dt>
                                <dd className="sequence">{context.antigen_sequence}</dd>
                            </div>
                        : null}

                        {context.aliases && context.aliases.length ?
                            <div data-test="aliases">
                                <dt>Aliases</dt>
                                <dd>{context.aliases.join(', ')}</dd>
                            </div>
                        : null}

                        {context.dbxrefs && context.dbxrefs.length ?
                            <div data-test="dbxrefs">
                                <dt>External resources</dt>
                                <dd><DbxrefList values={context.dbxrefs} /></dd>
                            </div>
                        : null}
                    </dl>
                </PanelBody>
            </Panel>

            <RelatedItems
                title={'Experiments using this antibody'}
                url={`/search/?type=Experiment&replicates.antibody.accession=${context.accession}`}
                Component={ExperimentTable}
            />

            <DocumentsPanel title="Characterizations" documentSpecs={documentSpecs} />
        </div>
    );
};
Example #10
0
function main(ch, callback) {
	var $ = ch,
		summary = "",
		title = "",
		failure = false,
		cand = [],
		totalWords = 0,
		paragraphs = [],
		sentences = [],
		sentencesIndex = [],
		dict = [],
		selSentences = [],
		selSentencesWords = 0,
		ignore = [],
		dict_p_arr = [],
		dict_p_arr_balance = [],
		strip_s = "",
		i = 0;
	
	cand = $('p').toArray();
	_.each(cand, function(ele) {
		if ($(ele).find('div').length === 0 && $(ele).find('img').length === 0 && $(ele).find('script').length === 0 && $(ele).find('ul').length === 0) {
			
			var text = _($(ele).text()).stripTags().trim(),
				sent_count = countSentences(text),
				wp_ratio = calculateWPRatio(text);
				totalWords += countWords(text);
			
			if (percentageLetter(text) > 0.5 && sent_count > 0 && wp_ratio > 60) {
				paragraphs.push(text);
			}
		}
	});
	
	for(i = 0; i < paragraphs.length; i++) {
		var arr = splitContentToSentences(paragraphs[i]);
		if (arr.length > 1) {
			_.each(arr, function(s) {
				sentences.push(s);
				sentencesIndex.push(i);
			});
		}
	}
	
	_.each(paragraphs, function(p) {
		selSentences.push([]);
		dict_p_arr.push([]);
	});
	
	dict = getSentencesRank(sentences);
	
	for(i = 0; i < paragraphs.length; i++) {
		var p = paragraphs[i],
			arr = splitContentToSentences(p),
			max_score = 0,
			best_s = "",
			best_s_index = 0,
			dict_p = getSentencesRank(arr);
		dict_p_arr[i] = dict_p;
		dict_p_arr_balance[i] = sentences.length / arr.length;
		_.each(arr, function(s) {
			strip_s = formatSentence(s);
			if (s && dict_p[strip_s] > max_score && !arrayContainsObject(ignore, s)) {
				max_score = dict_p[strip_s];
				best_s = s;
			}
		});
		
		selSentences[i].push(best_s);
		selSentencesWords += countWords(best_s);
		ignore.push(best_s);
	}

	while(selSentencesWords < totalWords * 0.2) {
		var max_score = 0,
			best_s = "",
			best_s_index = 0;
		for(i = 0; i < sentences.length; i++) {
			strip_s = formatSentence(sentences[i]);
			if (sentences[i] && dict[strip_s] > max_score && !arrayContainsObject(ignore, sentences[i]) && (dict_p_arr[sentencesIndex[i]][strip_s] * dict_p_arr_balance[sentencesIndex[i]]) < (dict[strip_s])) {
				max_score = dict[strip_s];
				best_s = sentences[i];
				best_s_index = sentencesIndex[i];
			}
		}
		if (max_score == 0) {
			break;
		}
		
		selSentences[best_s_index].push(best_s);
		selSentencesWords += countWords(best_s);
		ignore.push(best_s);
	}

	_.each(selSentences, function(arr) {
		_.each(arr, function(s) {
			s = s.replace("...", ".").replace("..", ".").replace("  ", " ");
			summary += s.trim() + ' ';
		});
		summary = summary.trim() + '\n';
	});
	
	title = _($('h1[itemprop="name"]').text()).stripTags().trim();
	if (_(title).isBlank()) {
		var items = [];
		items = $('h1').toArray();
		items = items.concat($('h2').toArray());
		var highestScore = 0;
		var highestItem = '';
		_.each(items, function(ele) {
			if ($(ele).find('div').length === 0 && $(ele).find('img').length === 0 && $(ele).find('script').length === 0 && $(ele).find('ul').length === 0) {
				var text = _($(ele).text()).stripTags().trim();
				if (percentageLetter(text) > 0.5) {
					var score = 0;
					_.each(selSentences, function(s) {
						score += intersectSentences(text, s);
					});
					if (score > highestScore) {
						highestScore = score;
						highestItem = text;
					}
				}
			}
		});
		if (highestItem == '') {
			title = $('meta[name="title"]').attr('content');
			if (_(title).isBlank()) {
				title = $('title').text();
			}
			var title_comp = [];
			title_comp = title.split(/ -|–|:|\| /);
			title_comp = _.map(title_comp, function(title) {
				return _(title).trim();
			});
			var longest_streak = 0;
			_.each(title_comp, function(e) {
				var words = countWords(e);
				if (words > longest_streak) {
					longest_streak = words;
					title = e;
				}
			});
		} else {
			title = highestItem;
		}
	}
	
	if (title === "404 Not Found") {
		failure = true;
	}

	callback(_.clean(title.replace(/\n/g, '')), summary.trim(), failure);
}
Example #11
0
			title_comp = _.map(title_comp, function(title) {
				return _(title).trim();
			});
Example #12
0
		}, function(err, results) {
			callback(err, _(results).filter(function(post) {return post}));
		});
Example #13
0
 static CreateInstance(object: Object = {}) {
   return _(new Settings()).assign(object)
 }
Example #14
0
 child.run = function () {
     var vals = _(arguments).values();
     return child.apply(this, vals);
 };
Example #15
0
 var targets = _.map(rcpts, function (rcpt) { return _(rcpt).strLeft('@').split('+'); });
define("bundles/assess/assessmentTypes/phoenixQuiz/assessment.header",["require","exports","module","moment","underscore","bundles/assess/assessmentTypes/phoenixQuiz/assessment.examHeader.html","bundles/assess/assessmentTypes/phoenixQuiz/assessment.quizHeader.html","bundles/payments-common/components/ReactPriceDisplay","bundles/payments/promises/productPrices","bundles/phoenix/lib/view","bundles/ondemand/components/endOfCourse/components/CourseCompleteModal","bundles/assess/components/HeaderNumberOfAttempts","js/lib/imgix","js/lib/pluralize","js/lib/pluralizer","js/lib/ReactRouterAdapter","pages/open-course/common/constants","pages/open-course/common/views/performanceBar"],function(require,exports,module){"use strict";var e=require("moment"),_=require("underscore"),o=require("bundles/assess/assessmentTypes/phoenixQuiz/assessment.examHeader.html"),s=require("bundles/assess/assessmentTypes/phoenixQuiz/assessment.quizHeader.html"),a=require("bundles/payments-common/components/ReactPriceDisplay"),n=require("bundles/payments/promises/productPrices"),i=require("bundles/phoenix/lib/view"),r=require("bundles/ondemand/components/endOfCourse/components/CourseCompleteModal"),h=require("bundles/assess/components/HeaderNumberOfAttempts"),l=require("js/lib/imgix"),m=require("js/lib/pluralize"),d=require("js/lib/pluralizer"),c=require("js/lib/ReactRouterAdapter"),t=require("pages/open-course/common/constants"),p=require("pages/open-course/common/views/performanceBar"),u=i.extend({stateModelProperty:"model",initialize:function initialize(s){_(this).extend(_(s).pick("metadata","nextItem","courseMaterials","verificationDisplay")),this.learnerStoryImg=l.processImage(t.vcLandingLearnerPhoto,{height:68}),this.landingPagePath=t.vcLandingPagePath,this.initializeEvents(),this.initializeSubViews(),this.initializePluralizer(),this.moment=e},initializeSubViews:function initializeSubViews(){"exam"!==this.metadata.getTypeName()&&(this.performanceBar=new p({evaluation:this.model.get("evaluation"),showValue:!1}))},initializePluralizer:function initializePluralizer(){this.pluralize=m,this.pluralizer=new d(this.$el),this.pluralizer.setRules({"num-questions":{model:this.model,property:"questionInstances",converter:_.property("length")}})},initializeEvents:function initializeEvents(){this.listenTo(this.model,"question:added",this.renderMetadata),this.listenTo(this.model,"change:state",this.renderState),this.listenTo(this.model,"state:enter:submitted",this.renderEvaluation)},template:function template(e){return"exam"===this.metadata.getTypeName()?o(e):s(e)},renderSubviews:function renderSubviews(){if(this.performanceBar&&this.$$("performance-bar-container").html(this.performanceBar.render().el),"exam"===this.metadata.getTypeName()){var t=this.metadata.getDefinition("lockingConfiguration"),s=e(),a=e(s).add(t.allowedSubmissionsInterval,"milliseconds"),n=a.from(s,!0);this.renderReactInto(h,"HeaderNumberOfAttempts",{numberOfAttempts:t.allowedSubmissionsPerInterval,interval:n})}},renderCourseCompleteModal:function renderCourseCompleteModal(){this.renderReactInto(r,"CourseCompleteModal",{},{router:c.rr})},renderEvaluation:function renderEvaluation(){"exam"===this.metadata.getTypeName()?this.renderExamEvaluation():this.renderQuizEvaluation()},renderMetadata:function renderMetadata(){this.$$("num-questions-label").html(this.model.get("questionInstances").length)},renderQuizEvaluation:function renderQuizEvaluation(){var e=this.model.get("evaluation");if(!e)return;var t=e.isPassed(),s=this.$$(t?"next-button":"retake-button"),a=this.$$(t?"retake-button":"next-button"),n=this.$$(t?"passed-label":"not-passed-label"),i=this.$$(t?"not-passed-label":"passed-label");t?this.$$("performance-bar-container").removeClass("c-performance-bar-dim"):this.$$("performance-bar-container").addClass("c-performance-bar-dim"),s.removeClass("c-btn-white").addClass("bt3-btn-success"),a.removeClass("bt3-btn-success").addClass("c-btn-white"),n.show(),i.hide(),this.$$("num-points-earned-label").html(e.getDisplayScore()),this.$$("max-score-label").html(e.get("maxScore")),this.$$("passing-percent-label").html(e.getDisplayPassingPercent()),this.$$("percent-score-label").html(e.getHumanPercentScore())},renderExamEvaluation:function renderExamEvaluation(){var e=this.model.get("evaluation"),s=this.model.get("gradingAttempt"),o=s.get("attemptState");if(!e)return;var i=e.isPassed(),l=i?"passed":"not-passed";i?this.$$("exam-header").removeClass("c-exam-not-passed").addClass("c-exam-passed"):this.$$("exam-header").removeClass("c-exam-passed").addClass("c-exam-not-passed"),this.$("[data-passing-state]").hide(),this.$('[data-passing-state~="'+l+'"]').show();var r=void 0,t={none:"none",unverified:"unverified",pending:"pending"};if(this.verificationDisplay.shouldPromptForVerification()&&i){var m=_([[s.attemptStates.none,t.none],[s.attemptStates.unverified,t.unverified],[s.attemptStates.pending,t.pending],[s.attemptStates.verified,t.none]]).object();r=m[o]}else r=t.none;this.$("[data-verification-warning]").hide(),this.$('[data-verification-warning~="'+r+'"]').show(),r===t.none?this.$$("exam-header").removeClass("c-exam-verification-warning"):this.$$("exam-header").addClass("c-exam-verification-warning"),this.$$("passing-percent-label").html(e.getDisplayPassingPercent()),this.$$("num-points-earned-label").html(e.getDisplayScore()),this.$$("max-score-label").html(e.get("maxScore")),this.$$("percent-score-label").html(e.getHumanPercentScore()),this.verificationDisplay.showCCAdvertising()&&i&&(this.$$("vc-upsell").show(),n.getPriceForVC({courseId:this.metadata.get("course").get("id")}).then(function(e){this.renderReactInto(a,"ReactPriceDisplay",{value:e.getDisplayAmount(),currency:e.getDisplayCurrencyCode()})}.bind(this)).fail(function(e){if(!e.responseJSON)throw e}).done()),this.renderCourseCompleteModal()}});module.exports=u});
Example #17
0
'use strict';

var BaseDialect = require('../base');
var _ = require('underscore');
var util = require('util');
var blocksInit = require('./blocks');

var Dialect = module.exports = function(builder) {
	BaseDialect.call(this, builder);

	// init blocks
	blocksInit(this);
};

util.inherits(Dialect, BaseDialect);

Dialect.prototype.config = _({}).extend(BaseDialect.prototype.config);
(function(e,t){if("function"==typeof define&&define.amd)define(["backbone","underscore"],function(i,n){return e.Marionette=e.Mn=t(e,i,n)});else if("undefined"!=typeof exports){var i=require("backbone"),n=require("underscore");module.exports=t(e,i,n)}else e.Marionette=e.Mn=t(e,e.Backbone,e._)})(this,function(e,t,i){"use strict";(function(e,t){var i=e.ChildViewContainer;return e.ChildViewContainer=function(e,t){var i=function(e){this._views={},this._indexByModel={},this._indexByCustom={},this._updateLength(),t.each(e,this.add,this)};t.extend(i.prototype,{add:function(e,t){var i=e.cid;return this._views[i]=e,e.model&&(this._indexByModel[e.model.cid]=i),t&&(this._indexByCustom[t]=i),this._updateLength(),this},findByModel:function(e){return this.findByModelCid(e.cid)},findByModelCid:function(e){var t=this._indexByModel[e];return this.findByCid(t)},findByCustom:function(e){var t=this._indexByCustom[e];return this.findByCid(t)},findByIndex:function(e){return t.values(this._views)[e]},findByCid:function(e){return this._views[e]},remove:function(e){var i=e.cid;return e.model&&delete this._indexByModel[e.model.cid],t.any(this._indexByCustom,function(e,t){return e===i?(delete this._indexByCustom[t],!0):void 0},this),delete this._views[i],this._updateLength(),this},call:function(e){this.apply(e,t.tail(arguments))},apply:function(e,i){t.each(this._views,function(n){t.isFunction(n[e])&&n[e].apply(n,i||[])})},_updateLength:function(){this.length=t.size(this._views)}});var n=["forEach","each","map","find","detect","filter","select","reject","every","all","some","any","include","contains","invoke","toArray","first","initial","rest","last","without","isEmpty","pluck"];return t.each(n,function(e){i.prototype[e]=function(){var i=t.values(this._views),n=[i].concat(t.toArray(arguments));return t[e].apply(t,n)}}),i}(e,t),e.ChildViewContainer.VERSION="0.1.5",e.ChildViewContainer.noConflict=function(){return e.ChildViewContainer=i,this},e.ChildViewContainer})(t,i),function(e,t){var i=e.Wreqr,n=e.Wreqr={};return e.Wreqr.VERSION="1.3.1",e.Wreqr.noConflict=function(){return e.Wreqr=i,this},n.Handlers=function(e,t){var i=function(e){this.options=e,this._wreqrHandlers={},t.isFunction(this.initialize)&&this.initialize(e)};return i.extend=e.Model.extend,t.extend(i.prototype,e.Events,{setHandlers:function(e){t.each(e,function(e,i){var n=null;t.isObject(e)&&!t.isFunction(e)&&(n=e.context,e=e.callback),this.setHandler(i,e,n)},this)},setHandler:function(e,t,i){var n={callback:t,context:i};this._wreqrHandlers[e]=n,this.trigger("handler:add",e,t,i)},hasHandler:function(e){return!!this._wreqrHandlers[e]},getHandler:function(e){var t=this._wreqrHandlers[e];if(t)return function(){var e=Array.prototype.slice.apply(arguments);return t.callback.apply(t.context,e)}},removeHandler:function(e){delete this._wreqrHandlers[e]},removeAllHandlers:function(){this._wreqrHandlers={}}}),i}(e,t),n.CommandStorage=function(){var i=function(e){this.options=e,this._commands={},t.isFunction(this.initialize)&&this.initialize(e)};return t.extend(i.prototype,e.Events,{getCommands:function(e){var t=this._commands[e];return t||(t={command:e,instances:[]},this._commands[e]=t),t},addCommand:function(e,t){var i=this.getCommands(e);i.instances.push(t)},clearCommands:function(e){var t=this.getCommands(e);t.instances=[]}}),i}(),n.Commands=function(e){return e.Handlers.extend({storageType:e.CommandStorage,constructor:function(t){this.options=t||{},this._initializeStorage(this.options),this.on("handler:add",this._executeCommands,this);var i=Array.prototype.slice.call(arguments);e.Handlers.prototype.constructor.apply(this,i)},execute:function(e,t){e=arguments[0],t=Array.prototype.slice.call(arguments,1),this.hasHandler(e)?this.getHandler(e).apply(this,t):this.storage.addCommand(e,t)},_executeCommands:function(e,i,n){var r=this.storage.getCommands(e);t.each(r.instances,function(e){i.apply(n,e)}),this.storage.clearCommands(e)},_initializeStorage:function(e){var i,n=e.storageType||this.storageType;i=t.isFunction(n)?new n:n,this.storage=i}})}(n),n.RequestResponse=function(e){return e.Handlers.extend({request:function(){var e=arguments[0],t=Array.prototype.slice.call(arguments,1);return this.hasHandler(e)?this.getHandler(e).apply(this,t):void 0}})}(n),n.EventAggregator=function(e,t){var i=function(){};return i.extend=e.Model.extend,t.extend(i.prototype,e.Events),i}(e,t),n.Channel=function(){var i=function(t){this.vent=new e.Wreqr.EventAggregator,this.reqres=new e.Wreqr.RequestResponse,this.commands=new e.Wreqr.Commands,this.channelName=t};return t.extend(i.prototype,{reset:function(){return this.vent.off(),this.vent.stopListening(),this.reqres.removeAllHandlers(),this.commands.removeAllHandlers(),this},connectEvents:function(e,t){return this._connect("vent",e,t),this},connectCommands:function(e,t){return this._connect("commands",e,t),this},connectRequests:function(e,t){return this._connect("reqres",e,t),this},_connect:function(e,i,n){if(i){n=n||this;var r="vent"===e?"on":"setHandler";t.each(i,function(i,s){this[e][r](s,t.bind(i,n))},this)}}}),i}(n),n.radio=function(e){var i=function(){this._channels={},this.vent={},this.commands={},this.reqres={},this._proxyMethods()};t.extend(i.prototype,{channel:function(e){if(!e)throw Error("Channel must receive a name");return this._getChannel(e)},_getChannel:function(t){var i=this._channels[t];return i||(i=new e.Channel(t),this._channels[t]=i),i},_proxyMethods:function(){t.each(["vent","commands","reqres"],function(e){t.each(n[e],function(t){this[e][t]=r(this,e,t)},this)},this)}});var n={vent:["on","off","trigger","once","stopListening","listenTo","listenToOnce"],commands:["execute","setHandler","setHandlers","removeHandler","removeAllHandlers"],reqres:["request","setHandler","setHandlers","removeHandler","removeAllHandlers"]},r=function(e,t,i){return function(n){var r=e._getChannel(n)[t],s=Array.prototype.slice.call(arguments,1);return r[i].apply(r,s)}};return new i}(n),e.Wreqr}(t,i);var n=e.Marionette,r=t.Marionette={};r.VERSION="2.3.1",r.noConflict=function(){return e.Marionette=n,this},t.Marionette=r,r.Deferred=t.$.Deferred,r.extend=t.Model.extend,r.isNodeAttached=function(e){return t.$.contains(document.documentElement,e)},r.getOption=function(e,t){return e&&t?e.options&&void 0!==e.options[t]?e.options[t]:e[t]:void 0},r.proxyGetOption=function(e){return r.getOption(this,e)},r._getValue=function(e,t,n){return i.isFunction(e)&&(e=e.apply(t,n)),e},r.normalizeMethods=function(e){return i.reduce(e,function(e,t,n){return i.isFunction(t)||(t=this[t]),t&&(e[n]=t),e},{},this)},r.normalizeUIString=function(e,t){return e.replace(/@ui\.[a-zA-Z_$0-9]*/g,function(e){return t[e.slice(4)]})},r.normalizeUIKeys=function(e,t){return i.reduce(e,function(e,i,n){var s=r.normalizeUIString(n,t);return e[s]=i,e},{})},r.normalizeUIValues=function(e,t){return i.each(e,function(n,s){i.isString(n)&&(e[s]=r.normalizeUIString(n,t))}),e},r.actAsCollection=function(e,t){var n=["forEach","each","map","find","detect","filter","select","reject","every","all","some","any","include","contains","invoke","toArray","first","initial","rest","last","without","isEmpty","pluck"];i.each(n,function(n){e[n]=function(){var e=i.values(i.result(this,t)),r=[e].concat(i.toArray(arguments));return i[n].apply(i,r)}})};var s=r.deprecate=function(e,t){i.isObject(e)&&(e=e.prev+" is going to be removed in the future. "+"Please use "+e.next+" instead."+(e.url?" See: "+e.url:"")),void 0!==t&&t||s._cache[e]||(s._warn("Deprecation warning: "+e),s._cache[e]=!0)};s._warn="undefined"!=typeof console&&(console.warn||console.log)||function(){},s._cache={},r._triggerMethod=function(){function e(e,t,i){return i.toUpperCase()}var t=/(^|:)(\w)/gi;return function(n,r,s){var o=3>arguments.length;o&&(s=r,r=s[0]);var h,a="on"+r.replace(t,e),l=n[a];return i.isFunction(l)&&(h=l.apply(n,o?i.rest(s):s)),i.isFunction(n.trigger)&&(o+s.length>1?n.trigger.apply(n,o?s:[r].concat(i.rest(s,0))):n.trigger(r)),h}}(),r.triggerMethod=function(){return r._triggerMethod(this,arguments)},r.triggerMethodOn=function(e){var t=i.isFunction(e.triggerMethod)?e.triggerMethod:r.triggerMethod;return t.apply(e,i.rest(arguments))},r.MonitorDOMRefresh=function(e){function t(){e._isShown=!0,s()}function n(){e._isRendered=!0,s()}function s(){e._isShown&&e._isRendered&&r.isNodeAttached(e.el)&&i.isFunction(e.triggerMethod)&&e.triggerMethod("dom:refresh")}e.on({show:t,render:n})},function(e){function t(t,n,r,s){var o=s.split(/\s+/);i.each(o,function(i){var s=t[i];if(!s)throw new e.Error('Method "'+i+'" was configured as an event handler, but does not exist.');t.listenTo(n,r,s)})}function n(e,t,i,n){e.listenTo(t,i,n)}function r(e,t,n,r){var s=r.split(/\s+/);i.each(s,function(i){var r=e[i];e.stopListening(t,n,r)})}function s(e,t,i,n){e.stopListening(t,i,n)}function o(t,n,r,s,o){if(n&&r){if(!i.isObject(r))throw new e.Error({message:"Bindings must be an object or function.",url:"marionette.functions.html#marionettebindentityevents"});r=e._getValue(r,t),i.each(r,function(e,r){i.isFunction(e)?s(t,n,r,e):o(t,n,r,e)})}}e.bindEntityEvents=function(e,i,r){o(e,i,r,n,t)},e.unbindEntityEvents=function(e,t,i){o(e,t,i,s,r)},e.proxyBindEntityEvents=function(t,i){return e.bindEntityEvents(this,t,i)},e.proxyUnbindEntityEvents=function(t,i){return e.unbindEntityEvents(this,t,i)}}(r);var o=["description","fileName","lineNumber","name","message","number"];return r.Error=r.extend.call(Error,{urlRoot:"http://marionettejs.com/docs/v"+r.VERSION+"/",constructor:function(e,t){i.isObject(e)?(t=e,e=t.message):t||(t={});var n=Error.call(this,e);i.extend(this,i.pick(n,o),i.pick(t,o)),this.captureStackTrace(),t.url&&(this.url=this.urlRoot+t.url)},captureStackTrace:function(){Error.captureStackTrace&&Error.captureStackTrace(this,r.Error)},toString:function(){return this.name+": "+this.message+(this.url?" See: "+this.url:"")}}),r.Error.extend=r.extend,r.Callbacks=function(){this._deferred=r.Deferred(),this._callbacks=[]},i.extend(r.Callbacks.prototype,{add:function(e,t){var n=i.result(this._deferred,"promise");this._callbacks.push({cb:e,ctx:t}),n.then(function(i){t&&(i.context=t),e.call(i.context,i.options)})},run:function(e,t){this._deferred.resolve({options:e,context:t})},reset:function(){var e=this._callbacks;this._deferred=r.Deferred(),this._callbacks=[],i.each(e,function(e){this.add(e.cb,e.ctx)},this)}}),r.Controller=function(e){this.options=e||{},i.isFunction(this.initialize)&&this.initialize(this.options)},r.Controller.extend=r.extend,i.extend(r.Controller.prototype,t.Events,{destroy:function(){return r._triggerMethod(this,"before:destroy",arguments),r._triggerMethod(this,"destroy",arguments),this.stopListening(),this.off(),this},triggerMethod:r.triggerMethod,getOption:r.proxyGetOption}),r.Object=function(e){this.options=i.extend({},i.result(this,"options"),e),this.initialize.apply(this,arguments)},r.Object.extend=r.extend,i.extend(r.Object.prototype,t.Events,{initialize:function(){},destroy:function(){this.triggerMethod("before:destroy"),this.triggerMethod("destroy"),this.stopListening()},triggerMethod:r.triggerMethod,getOption:r.proxyGetOption,bindEntityEvents:r.proxyBindEntityEvents,unbindEntityEvents:r.proxyUnbindEntityEvents}),r.Region=r.Object.extend({constructor:function(e){if(this.options=e||{},this.el=this.getOption("el"),this.el=this.el instanceof t.$?this.el[0]:this.el,!this.el)throw new r.Error({name:"NoElError",message:'An "el" must be specified for a region.'});this.$el=this.getEl(this.el),r.Object.call(this,e)},show:function(e,t){if(this._ensureElement()){this._ensureViewIsIntact(e);var i=t||{},n=e!==this.currentView,s=!!i.preventDestroy,o=!!i.forceShow,h=!!this.currentView,a=n&&!s,l=n||o;if(h&&this.triggerMethod("before:swapOut",this.currentView,this,t),this.currentView&&delete this.currentView._parent,a?this.empty():h&&l&&this.currentView.off("destroy",this.empty,this),l){e.once("destroy",this.empty,this),e.render(),e._parent=this,h&&this.triggerMethod("before:swap",e,this,t),this.triggerMethod("before:show",e,this,t),r.triggerMethodOn(e,"before:show",e,this,t),h&&this.triggerMethod("swapOut",this.currentView,this,t);var u=r.isNodeAttached(this.el),d=[],c=i.triggerBeforeAttach||this.triggerBeforeAttach,g=i.triggerAttach||this.triggerAttach;return u&&c&&(d=this._displayedViews(e),this._triggerAttach(d,"before:")),this.attachHtml(e),this.currentView=e,u&&g&&(d=this._displayedViews(e),this._triggerAttach(d)),h&&this.triggerMethod("swap",e,this,t),this.triggerMethod("show",e,this,t),r.triggerMethodOn(e,"show",e,this,t),this}return this}},triggerBeforeAttach:!0,triggerAttach:!0,_triggerAttach:function(e,t){var n=(t||"")+"attach";i.each(e,function(e){r.triggerMethodOn(e,n,e,this)},this)},_displayedViews:function(e){return i.union([e],i.result(e,"_getNestedViews")||[])},_ensureElement:function(){if(i.isObject(this.el)||(this.$el=this.getEl(this.el),this.el=this.$el[0]),!this.$el||0===this.$el.length){if(this.getOption("allowMissingEl"))return!1;throw new r.Error('An "el" '+this.$el.selector+" must exist in DOM")}return!0},_ensureViewIsIntact:function(e){if(!e)throw new r.Error({name:"ViewNotValid",message:"The view passed is undefined and therefore invalid. You must pass a view instance to show."});if(e.isDestroyed)throw new r.Error({name:"ViewDestroyedError",message:'View (cid: "'+e.cid+'") has already been destroyed and cannot be used.'})},getEl:function(e){return t.$(e,r._getValue(this.options.parentEl,this))},attachHtml:function(e){this.$el.contents().detach(),this.el.appendChild(e.el)},empty:function(){var e=this.currentView;if(e)return e.off("destroy",this.empty,this),this.triggerMethod("before:empty",e),this._destroyView(),this.triggerMethod("empty",e),delete this.currentView,this},_destroyView:function(){var e=this.currentView;e.destroy&&!e.isDestroyed?e.destroy():e.remove&&(e.remove(),e.isDestroyed=!0)},attachView:function(e){return this.currentView=e,this},hasView:function(){return!!this.currentView},reset:function(){return this.empty(),this.$el&&(this.el=this.$el.selector),delete this.$el,this}},{buildRegion:function(e,t){if(i.isString(e))return this._buildRegionFromSelector(e,t);if(e.selector||e.el||e.regionClass)return this._buildRegionFromObject(e,t);if(i.isFunction(e))return this._buildRegionFromRegionClass(e);throw new r.Error({message:"Improper region configuration type.",url:"marionette.region.html#region-configuration-types"})},_buildRegionFromSelector:function(e,t){return new t({el:e})},_buildRegionFromObject:function(e,t){var n=e.regionClass||t,r=i.omit(e,"selector","regionClass");return e.selector&&!r.el&&(r.el=e.selector),new n(r)},_buildRegionFromRegionClass:function(e){return new e}}),r.RegionManager=r.Controller.extend({constructor:function(e){this._regions={},r.Controller.call(this,e),this.addRegions(this.getOption("regions"))},addRegions:function(e,t){return e=r._getValue(e,this,arguments),i.reduce(e,function(e,n,r){return i.isString(n)&&(n={selector:n}),n.selector&&(n=i.defaults({},n,t)),e[r]=this.addRegion(r,n),e},{},this)},addRegion:function(e,t){var i;return i=t instanceof r.Region?t:r.Region.buildRegion(t,r.Region),this.triggerMethod("before:add:region",e,i),i._parent=this,this._store(e,i),this.triggerMethod("add:region",e,i),i},get:function(e){return this._regions[e]},getRegions:function(){return i.clone(this._regions)},removeRegion:function(e){var t=this._regions[e];return this._remove(e,t),t},removeRegions:function(){var e=this.getRegions();return i.each(this._regions,function(e,t){this._remove(t,e)},this),e},emptyRegions:function(){var e=this.getRegions();return i.invoke(e,"empty"),e},destroy:function(){return this.removeRegions(),r.Controller.prototype.destroy.apply(this,arguments)},_store:function(e,t){this._regions[e]=t,this._setLength()},_remove:function(e,t){this.triggerMethod("before:remove:region",e,t),t.empty(),t.stopListening(),delete t._parent,delete this._regions[e],this._setLength(),this.triggerMethod("remove:region",e,t)},_setLength:function(){this.length=i.size(this._regions)}}),r.actAsCollection(r.RegionManager.prototype,"_regions"),r.TemplateCache=function(e){this.templateId=e},i.extend(r.TemplateCache,{templateCaches:{},get:function(e){var t=this.templateCaches[e];return t||(t=new r.TemplateCache(e),this.templateCaches[e]=t),t.load()},clear:function(){var e,t=i.toArray(arguments),n=t.length;if(n>0)for(e=0;n>e;e++)delete this.templateCaches[t[e]];else this.templateCaches={}}}),i.extend(r.TemplateCache.prototype,{load:function(){if(this.compiledTemplate)return this.compiledTemplate;var e=this.loadTemplate(this.templateId);return this.compiledTemplate=this.compileTemplate(e),this.compiledTemplate},loadTemplate:function(e){var i=t.$(e).html();if(!i||0===i.length)throw new r.Error({name:"NoTemplateError",message:'Could not find template: "'+e+'"'});return i},compileTemplate:function(e){return i.template(e)}}),r.Renderer={render:function(e,t){if(!e)throw new r.Error({name:"TemplateNotFoundError",message:"Cannot render the template since its false, null or undefined."});var n=i.isFunction(e)?e:r.TemplateCache.get(e);return n(t)}},r.View=t.View.extend({isDestroyed:!1,constructor:function(e){i.bindAll(this,"render"),e=r._getValue(e,this),this.options=i.extend({},i.result(this,"options"),e),this._behaviors=r.Behaviors(this),t.View.apply(this,arguments),r.MonitorDOMRefresh(this),this.on("show",this.onShowCalled)},getTemplate:function(){return this.getOption("template")},serializeModel:function(e){return e.toJSON.apply(e,i.rest(arguments))},mixinTemplateHelpers:function(e){e=e||{};var t=this.getOption("templateHelpers");return t=r._getValue(t,this),i.extend(e,t)},normalizeUIKeys:function(e){var t=i.result(this,"_uiBindings");return r.normalizeUIKeys(e,t||i.result(this,"ui"))},normalizeUIValues:function(e){var t=i.result(this,"ui"),n=i.result(this,"_uiBindings");return r.normalizeUIValues(e,n||t)},configureTriggers:function(){if(this.triggers){var e=this.normalizeUIKeys(i.result(this,"triggers"));return i.reduce(e,function(e,t,i){return e[i]=this._buildViewTrigger(t),e},{},this)}},delegateEvents:function(e){return this._delegateDOMEvents(e),this.bindEntityEvents(this.model,this.getOption("modelEvents")),this.bindEntityEvents(this.collection,this.getOption("collectionEvents")),i.each(this._behaviors,function(e){e.bindEntityEvents(this.model,e.getOption("modelEvents")),e.bindEntityEvents(this.collection,e.getOption("collectionEvents"))},this),this},_delegateDOMEvents:function(e){var n=r._getValue(e||this.events,this);n=this.normalizeUIKeys(n),i.isUndefined(e)&&(this.events=n);var s={},o=i.result(this,"behaviorEvents")||{},h=this.configureTriggers(),a=i.result(this,"behaviorTriggers")||{};i.extend(s,o,n,h,a),t.View.prototype.delegateEvents.call(this,s)},undelegateEvents:function(){return t.View.prototype.undelegateEvents.apply(this,arguments),this.unbindEntityEvents(this.model,this.getOption("modelEvents")),this.unbindEntityEvents(this.collection,this.getOption("collectionEvents")),i.each(this._behaviors,function(e){e.unbindEntityEvents(this.model,e.getOption("modelEvents")),e.unbindEntityEvents(this.collection,e.getOption("collectionEvents"))},this),this},onShowCalled:function(){},_ensureViewIsIntact:function(){if(this.isDestroyed)throw new r.Error({name:"ViewDestroyedError",message:'View (cid: "'+this.cid+'") has already been destroyed and cannot be used.'})},destroy:function(){if(!this.isDestroyed){var e=i.toArray(arguments);return this.triggerMethod.apply(this,["before:destroy"].concat(e)),this.isDestroyed=!0,this.triggerMethod.apply(this,["destroy"].concat(e)),this.unbindUIElements(),this.remove(),i.invoke(this._behaviors,"destroy",e),this}},bindUIElements:function(){this._bindUIElements(),i.invoke(this._behaviors,this._bindUIElements)},_bindUIElements:function(){if(this.ui){this._uiBindings||(this._uiBindings=this.ui);var e=i.result(this,"_uiBindings");this.ui={},i.each(e,function(e,t){this.ui[t]=this.$(e)},this)}},unbindUIElements:function(){this._unbindUIElements(),i.invoke(this._behaviors,this._unbindUIElements)},_unbindUIElements:function(){this.ui&&this._uiBindings&&(i.each(this.ui,function(e,t){delete this.ui[t]},this),this.ui=this._uiBindings,delete this._uiBindings)},_buildViewTrigger:function(e){var t=i.isObject(e),n=i.defaults({},t?e:{},{preventDefault:!0,stopPropagation:!0}),r=t?n.event:e;return function(e){e&&(e.preventDefault&&n.preventDefault&&e.preventDefault(),e.stopPropagation&&n.stopPropagation&&e.stopPropagation());var t={view:this,model:this.model,collection:this.collection};this.triggerMethod(r,t)}},setElement:function(){var e=t.View.prototype.setElement.apply(this,arguments);return i.invoke(this._behaviors,"proxyViewProperties",this),e},triggerMethod:function(){for(var e=r._triggerMethod,t=e(this,arguments),i=this._behaviors,n=0,s=i&&i.length;s>n;n++)e(i[n],arguments);return t},_getImmediateChildren:function(){return[]},_getNestedViews:function(){var e=this._getImmediateChildren();return e.length?i.reduce(e,function(e,t){return t._getNestedViews?e.concat(t._getNestedViews()):e},e):e},normalizeMethods:r.normalizeMethods,getOption:r.proxyGetOption,bindEntityEvents:r.proxyBindEntityEvents,unbindEntityEvents:r.proxyUnbindEntityEvents}),r.ItemView=r.View.extend({constructor:function(){r.View.apply(this,arguments)},serializeData:function(){if(!this.model&&!this.collection)return{};var e=[this.model||this.collection];return arguments.length&&e.push.apply(e,arguments),this.model?this.serializeModel.apply(this,e):{items:this.serializeCollection.apply(this,e)}},serializeCollection:function(e){return e.toJSON.apply(e,i.rest(arguments))},render:function(){return this._ensureViewIsIntact(),this.triggerMethod("before:render",this),this._renderTemplate(),this.bindUIElements(),this.triggerMethod("render",this),this},_renderTemplate:function(){var e=this.getTemplate();if(e!==!1){if(!e)throw new r.Error({name:"UndefinedTemplateError",message:"Cannot render the template since it is null or undefined."});var t=this.serializeData();t=this.mixinTemplateHelpers(t);var i=r.Renderer.render(e,t,this);return this.attachElContent(i),this}},attachElContent:function(e){return this.$el.html(e),this}}),r.CollectionView=r.View.extend({childViewEventPrefix:"childview",constructor:function(e){var t=e||{};i.isUndefined(this.sort)&&(this.sort=i.isUndefined(t.sort)?!0:t.sort),this.once("render",this._initialEvents),this._initChildViewStorage(),r.View.apply(this,arguments),this.initRenderBuffer()},initRenderBuffer:function(){this.elBuffer=document.createDocumentFragment(),this._bufferedChildren=[]},startBuffering:function(){this.initRenderBuffer(),this.isBuffering=!0},endBuffering:function(){this.isBuffering=!1,this._triggerBeforeShowBufferedChildren(),this.attachBuffer(this,this.elBuffer),this._triggerShowBufferedChildren(),this.initRenderBuffer()},_triggerBeforeShowBufferedChildren:function(){this._isShown&&i.each(this._bufferedChildren,i.partial(this._triggerMethodOnChild,"before:show"))},_triggerShowBufferedChildren:function(){this._isShown&&(i.each(this._bufferedChildren,i.partial(this._triggerMethodOnChild,"show")),this._bufferedChildren=[])},_triggerMethodOnChild:function(e,t){r.triggerMethodOn(t,e)},_initialEvents:function(){this.collection&&(this.listenTo(this.collection,"add",this._onCollectionAdd),this.listenTo(this.collection,"remove",this._onCollectionRemove),this.listenTo(this.collection,"reset",this.render),this.sort&&this.listenTo(this.collection,"sort",this._sortViews))},_onCollectionAdd:function(e){this.destroyEmptyView();var t=this.getChildView(e),i=this.collection.indexOf(e);this.addChild(e,t,i)},_onCollectionRemove:function(e){var t=this.children.findByModel(e);this.removeChildView(t),this.checkEmpty()},onShowCalled:function(){this.children.each(i.partial(this._triggerMethodOnChild,"show"))},render:function(){return this._ensureViewIsIntact(),this.triggerMethod("before:render",this),this._renderChildren(),this.triggerMethod("render",this),this},resortView:function(){this.render()},_sortViews:function(){var e=this.collection.find(function(e,t){var i=this.children.findByModel(e);return!i||i._index!==t},this);e&&this.resortView()},_emptyViewIndex:-1,_renderChildren:function(){this.destroyEmptyView(),this.destroyChildren(),this.isEmpty(this.collection)?this.showEmptyView():(this.triggerMethod("before:render:collection",this),this.startBuffering(),this.showCollection(),this.endBuffering(),this.triggerMethod("render:collection",this))},showCollection:function(){var e;this.collection.each(function(t,i){e=this.getChildView(t),this.addChild(t,e,i)},this)},showEmptyView:function(){var e=this.getEmptyView();if(e&&!this._showingEmptyView){this.triggerMethod("before:render:empty"),this._showingEmptyView=!0;var i=new t.Model;this.addEmptyView(i,e),this.triggerMethod("render:empty")}},destroyEmptyView:function(){this._showingEmptyView&&(this.triggerMethod("before:remove:empty"),this.destroyChildren(),delete this._showingEmptyView,this.triggerMethod("remove:empty"))},getEmptyView:function(){return this.getOption("emptyView")},addEmptyView:function(e,t){var n=this.getOption("emptyViewOptions")||this.getOption("childViewOptions");i.isFunction(n)&&(n=n.call(this,e,this._emptyViewIndex));var s=this.buildChildView(e,t,n);s._parent=this,this.proxyChildEvents(s),this._isShown&&r.triggerMethodOn(s,"before:show"),this.children.add(s),this.renderChildView(s,this._emptyViewIndex),this._isShown&&r.triggerMethodOn(s,"show")},getChildView:function(){var e=this.getOption("childView");if(!e)throw new r.Error({name:"NoChildViewError",message:'A "childView" must be specified'});return e},addChild:function(e,t,i){var n=this.getOption("childViewOptions");n=r._getValue(n,this,[e,i]);var s=this.buildChildView(e,t,n);return this._updateIndices(s,!0,i),this._addChildView(s,i),s._parent=this,s},_updateIndices:function(e,t,i){this.sort&&(t&&(e._index=i),this.children.each(function(i){i._index>=e._index&&(i._index+=t?1:-1)}))},_addChildView:function(e,t){this.proxyChildEvents(e),this.triggerMethod("before:add:child",e),this.children.add(e),this.renderChildView(e,t),this._isShown&&!this.isBuffering&&r.triggerMethodOn(e,"show"),this.triggerMethod("add:child",e)},renderChildView:function(e,t){return e.render(),this.attachHtml(this,e,t),e},buildChildView:function(e,t,n){var r=i.extend({model:e},n);return new t(r)},removeChildView:function(e){return e&&(this.triggerMethod("before:remove:child",e),e.destroy?e.destroy():e.remove&&e.remove(),delete e._parent,this.stopListening(e),this.children.remove(e),this.triggerMethod("remove:child",e),this._updateIndices(e,!1)),e},isEmpty:function(){return!this.collection||0===this.collection.length},checkEmpty:function(){this.isEmpty(this.collection)&&this.showEmptyView()},attachBuffer:function(e,t){e.$el.append(t)},attachHtml:function(e,t,i){e.isBuffering?(e.elBuffer.appendChild(t.el),e._bufferedChildren.push(t)):e._insertBefore(t,i)||e._insertAfter(t)},_insertBefore:function(e,t){var i,n=this.sort&&this.children.length-1>t;return n&&(i=this.children.find(function(e){return e._index===t+1})),i?(i.$el.before(e.el),!0):!1},_insertAfter:function(e){this.$el.append(e.el)},_initChildViewStorage:function(){this.children=new t.ChildViewContainer},destroy:function(){return this.isDestroyed?void 0:(this.triggerMethod("before:destroy:collection"),this.destroyChildren(),this.triggerMethod("destroy:collection"),r.View.prototype.destroy.apply(this,arguments))},destroyChildren:function(){var e=this.children.map(i.identity);return this.children.each(this.removeChildView,this),this.checkEmpty(),e},proxyChildEvents:function(e){var t=this.getOption("childViewEventPrefix");this.listenTo(e,"all",function(){var n=i.toArray(arguments),r=n[0],s=this.normalizeMethods(i.result(this,"childEvents"));n[0]=t+":"+r,n.splice(1,0,e),s!==void 0&&i.isFunction(s[r])&&s[r].apply(this,n.slice(1)),this.triggerMethod.apply(this,n)},this)},_getImmediateChildren:function(){return i.values(this.children._views)}}),r.CompositeView=r.CollectionView.extend({constructor:function(){r.CollectionView.apply(this,arguments)},_initialEvents:function(){this.collection&&(this.listenTo(this.collection,"add",this._onCollectionAdd),this.listenTo(this.collection,"remove",this._onCollectionRemove),this.listenTo(this.collection,"reset",this._renderChildren),this.sort&&this.listenTo(this.collection,"sort",this._sortViews))},getChildView:function(){var e=this.getOption("childView")||this.constructor;return e},serializeData:function(){var e={};return this.model&&(e=i.partial(this.serializeModel,this.model).apply(this,arguments)),e},render:function(){return this._ensureViewIsIntact(),this.isRendered=!0,this.resetChildViewContainer(),this.triggerMethod("before:render",this),this._renderTemplate(),this._renderChildren(),this.triggerMethod("render",this),this},_renderChildren:function(){this.isRendered&&r.CollectionView.prototype._renderChildren.call(this)},_renderTemplate:function(){var e={};e=this.serializeData(),e=this.mixinTemplateHelpers(e),this.triggerMethod("before:render:template");var t=this.getTemplate(),i=r.Renderer.render(t,e,this);this.attachElContent(i),this.bindUIElements(),this.triggerMethod("render:template")},attachElContent:function(e){return this.$el.html(e),this},attachBuffer:function(e,t){var i=this.getChildViewContainer(e);i.append(t)},_insertAfter:function(e){var t=this.getChildViewContainer(this,e);t.append(e.el)},getChildViewContainer:function(e){if("$childViewContainer"in e)return e.$childViewContainer;var t,i=r.getOption(e,"childViewContainer");if(i){var n=r._getValue(i,e);if(t="@"===n.charAt(0)&&e.ui?e.ui[n.substr(4)]:e.$(n),0>=t.length)throw new r.Error({name:"ChildViewContainerMissingError",message:'The specified "childViewContainer" was not found: '+e.childViewContainer})}else t=e.$el;return e.$childViewContainer=t,t},resetChildViewContainer:function(){this.$childViewContainer&&delete this.$childViewContainer}}),r.LayoutView=r.ItemView.extend({regionClass:r.Region,constructor:function(e){e=e||{},this._firstRender=!0,this._initializeRegions(e),r.ItemView.call(this,e)},render:function(){return this._ensureViewIsIntact(),this._firstRender?this._firstRender=!1:this._reInitializeRegions(),r.ItemView.prototype.render.apply(this,arguments)},destroy:function(){return this.isDestroyed?this:(this.regionManager.destroy(),r.ItemView.prototype.destroy.apply(this,arguments))},addRegion:function(e,t){var i={};return i[e]=t,this._buildRegions(i)[e]},addRegions:function(e){return this.regions=i.extend({},this.regions,e),this._buildRegions(e)},removeRegion:function(e){return delete this.regions[e],this.regionManager.removeRegion(e)},getRegion:function(e){return this.regionManager.get(e)},getRegions:function(){return this.regionManager.getRegions()},_buildRegions:function(e){var t={regionClass:this.getOption("regionClass"),parentEl:i.partial(i.result,this,"el")};return this.regionManager.addRegions(e,t)},_initializeRegions:function(e){var t;this._initRegionManager(),t=r._getValue(this.regions,this,[e])||{};var n=this.getOption.call(e,"regions");n=r._getValue(n,this,[e]),i.extend(t,n),t=this.normalizeUIValues(t),this.addRegions(t)},_reInitializeRegions:function(){this.regionManager.invoke("reset")},getRegionManager:function(){return new r.RegionManager},_initRegionManager:function(){this.regionManager=this.getRegionManager(),this.regionManager._parent=this,this.listenTo(this.regionManager,"before:add:region",function(e){this.triggerMethod("before:add:region",e)}),this.listenTo(this.regionManager,"add:region",function(e,t){this[e]=t,this.triggerMethod("add:region",e,t)}),this.listenTo(this.regionManager,"before:remove:region",function(e){this.triggerMethod("before:remove:region",e)}),this.listenTo(this.regionManager,"remove:region",function(e,t){delete this[e],this.triggerMethod("remove:region",e,t)})},_getImmediateChildren:function(){return i.chain(this.regionManager.getRegions()).pluck("currentView").compact().value()}}),r.Behavior=r.Object.extend({constructor:function(e,t){this.view=t,this.defaults=i.result(this,"defaults")||{},this.options=i.extend({},this.defaults,e),r.Object.apply(this,arguments)
Example #19
0
 props.forEach(function(prop) {
     if (_(act).has(prop) && _(act[prop]).isArray()) {
         recipients = recipients.concat(act[prop]);
     }
 });
define("bundles/content-feedback/components/ItemFeedback",["require","exports","module","underscore","react-with-addons","bundles/phoenix/template/models/userIdentity","pages/open-course/common/constants","bundles/content-feedback/components/item-feedback/ItemFeedbackContent","bundles/content-feedback/constants/ItemTypes","bundles/content-feedback/itemFeedbackApp","js/lib/retracked","vendor/cnpm/fluxible.v0-4/addons/FluxibleComponent","css!./__styles__/ItemFeedback"],function(require,exports,module){"use strict";function _defaults(e,o){for(var s=Object.getOwnPropertyNames(o),t=0;t<s.length;t++){var n=s[t],r=Object.getOwnPropertyDescriptor(o,n);r&&r.configurable&&void 0===e[n]&&Object.defineProperty(e,n,r)}return e}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):_defaults(t,e))}var s=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},t=function(){function defineProperties(r,n){for(var t=0;t<n.length;t++){var e=n[t];e.enumerable=e.enumerable||!1,e.configurable=!0,"value"in e&&(e.writable=!0),Object.defineProperty(r,e.key,e)}}return function(e,t,n){return t&&defineProperties(e.prototype,t),n&&defineProperties(e,n),e}}(),n=function get(s,a,p){var n=!0;e:for(;n;){var t=s,i=a,c=p;n=!1,null===t&&(t=Function.prototype);var e=Object.getOwnPropertyDescriptor(t,i);if(void 0===e){var r=Object.getPrototypeOf(t);if(null===r)return void 0;s=r,a=i,p=c,n=!0,e=r=void 0;continue e}if("value"in e)return e.value;var o=e.get;if(void 0===o)return void 0;return o.call(c)}},_=require("underscore"),e=require("react-with-addons"),i=require("bundles/phoenix/template/models/userIdentity"),o=require("pages/open-course/common/constants"),l=require("bundles/content-feedback/components/item-feedback/ItemFeedbackContent"),r=require("bundles/content-feedback/constants/ItemTypes"),a=require("bundles/content-feedback/itemFeedbackApp"),p=require("js/lib/retracked"),u=require("vendor/cnpm/fluxible.v0-4/addons/FluxibleComponent");require("css!./__styles__/ItemFeedback");var c=function(o){function ItemFeedback(){_classCallCheck(this,ItemFeedback),n(Object.getPrototypeOf(ItemFeedback.prototype),"constructor",this).apply(this,arguments)}return _inherits(ItemFeedback,o),t(ItemFeedback,[{key:"render",value:function render(){var t=-1===_(r).values().indexOf(this.props.itemType);if(!i.get("authenticated")||t)return null;return e.createElement("div",{className:"rc-ItemFeedback"},e.createElement(l,s({},this.props,{key:this.props.itemId})))}}],[{key:"propTypes",value:{courseId:e.PropTypes.string.isRequired,itemId:e.PropTypes.string.isRequired,itemType:e.PropTypes.string.isRequired,itemMetadata:e.PropTypes.object,tooltipPlacement:e.PropTypes.string,questionId:e.PropTypes.string},enumerable:!0},{key:"contextTypes",value:{track:e.PropTypes.func.isRequired},enumerable:!0},{key:"defaultProps",value:{tooltipPlacement:"bottom"},enumerable:!0}]),ItemFeedback}(e.Component),d=function(i){function TrackedItemFeedback(){_classCallCheck(this,TrackedItemFeedback),n(Object.getPrototypeOf(TrackedItemFeedback.prototype),"constructor",this).apply(this,arguments)}return _inherits(TrackedItemFeedback,i),t(TrackedItemFeedback,[{key:"getChildContext",value:function getChildContext(){return{track:p.makeTracker({namespace:"content_learner.rating_items",include:{bucket_id:"A2",course_id:o.courseId,item_id:this.props.itemId}})}}},{key:"render",value:function render(){return e.createElement(c,s({},this.props,{courseId:o.courseId}))}}],[{key:"propTypes",value:{itemId:e.PropTypes.string.isRequired,itemType:e.PropTypes.oneOf(_(r).values()).isRequired,itemMetadata:e.PropTypes.object,tooltipPlacement:e.PropTypes.string,questionId:e.PropTypes.string},enumerable:!0},{key:"childContextTypes",value:{track:e.PropTypes.func},enumerable:!0}]),TrackedItemFeedback}(e.Component),m=function(o){function FluxibleItemFeedback(){_classCallCheck(this,FluxibleItemFeedback),n(Object.getPrototypeOf(FluxibleItemFeedback.prototype),"constructor",this).apply(this,arguments)}return _inherits(FluxibleItemFeedback,o),t(FluxibleItemFeedback,[{key:"componentWillMount",value:function componentWillMount(){this.fluxibleContext=a.createContext()}},{key:"render",value:function render(){return e.createElement(u,{context:this.fluxibleContext.getComponentContext()},e.createElement(d,this.props))}}],[{key:"propTypes",value:{itemId:e.PropTypes.string.isRequired,itemType:e.PropTypes.oneOf(_(r).values()).isRequired,itemMetadata:e.PropTypes.object,tooltipPlacement:e.PropTypes.string},enumerable:!0},{key:"shouldShow",value:function value(){return i.get("authenticated")},enumerable:!0}]),FluxibleItemFeedback}(e.Component);module.exports=m,module.exports.BaseComp=c});
Example #21
0
var project = function(options, callback) {
    var id = options.id;
    var data = options.data;
    var perm = options.perm;

    if (!data && cache[id]) return callback(null, cache[id]);

    // Load for reads/writes.
    var load = function(data, xml) {
        var done = function(err, p) {
            data.id = id;
            cache[id] = cache[id] || p;
            cache[id].data = data;
            cache[id].data.background = _('rgba(<%=r%>,<%=g%>,<%=b%>,<%=(a/255).toFixed(2)%>)').template(cache[id]._map.background);
            cache[id].stats = {};
            return callback(null, cache[id]);
        };
        var opts = {};
        opts.xml = xml;
        opts.base = !tm.tmpid(id) ? id : opts.base;
        opts.scale = data.scale || 1;
        source({id:data.sources[0], base:data._id}, function(err, backend) {
            if (err) return callback(err);
            opts.backend = backend;
            return cache[id] ? cache[id].update(opts, done) : new Vector(opts, done);
        });
    };

    // Reading.
    if (!data) return project.info(id, function(err, data) {
        if (err) return callback(err);
        var stylesheets = {};
        var readstyles = function() {
            if (!data.styles || !data.styles.length) {
                data.styles = stylesheets;
                return project.toXML(data, function(err, xml) {
                    if (err) return callback(err);
                    return load(data, xml);
                });
            }
            var basename = data.styles.shift();
            fs.readFile(path.join(id, basename), 'utf8', function(err, mss) {
                if (err && err.code !== 'ENOENT') return callback(err);
                if (mss) stylesheets[basename] = mss;
                readstyles();
            });
        };
        readstyles();
    });

    // Writing.
    data = _(data).defaults(defaults);
    project.toXML(data, function(err, xml) {
        if (err) return callback(err);
        data.mtime = +new Date;
        if (!perm) return load(data, xml);

        var files = _(data.styles).map(function(v,k) { return { basename:k, data:v }; });
        files.push({
            basename: 'project.yml',
            data: yaml.dump(_(data).reduce(function(memo,v,k) {
                if (!(k in defaults)) return memo;
                memo[k] = k === 'styles' ? _(v).keys() : v;
                return memo;
            }, {}), null, 2)
        });

        // Include XML in files to be written.
        files.push({ basename: 'project.xml', data: xml });

        tm.writefiles(id, files, function(err) {
            if (err) return callback(err);
            load(data, xml);
            project.thumb({id:id, perm:true});
        });
    });
};
CoverMyDashboard.prototype.folderFilter = function (request) {
    return _(this.folders[this.currentFolder].workflow_statuses).contains(request.workflow_status);
};
Example #23
0
 getContentItemById: function(id, filteredList) {
     return _(filteredList || this.allContentItems).find(function(model) {
         return model.getId() === id;
     });
 },
 _(self.folders).each(function (folder, name) {
     if (_(folder.workflow_statuses).contains(request.workflow_status)) {
         folder.count += 1;
     }
 });
Example #25
0
            APIClient.reportVideoProgress(videoId, youTubeId, duration, secondsWatched, lastSecondWatched).then((result) => {
                if (!result) {
                    Util.warn("Video progress report returned null results!");
                    return;
                }
                Util.log("reportVideoProgress result: %o", result);

                var lastPoints = video.getPoints() || 0;
                var newPoints = lastPoints + result.points_earned;
                if (newPoints > 750) {
                    newPoints = 750;
                }

                // If they've watched some part of the video, and it's not almost the end
                // Otherwise check if we already have video progress for this item and we
                // therefore no longer need it.
                var lastSecondWatched;
                if (result.last_second_watched > 10 &&
                        duration - result.last_second_watched > 10) {
                    lastSecondWatched = result.last_second_watched;
                }

                // If we're just getting a completion of a video update
                // the user's overall points locally.
                if (result.points_earned > 0) {
                    // TODO: It would be better to store userInfo properties directly
                    // That way notificaitons will go out automatically.
                    var userInfo = CurrentUser.get("userInfo");
                    userInfo.points += result.points_earned;
                    CurrentUser._saveUserInfo();
                }

                video.set({
                    points: newPoints,
                    completed: result.is_video_completed,
                    started: !result.is_video_completed,
                    lastSecondWatched: lastSecondWatched
                });

                // Update locally stored cached info
                var index;
                if (result.is_video_completed) {
                    index = this.get("startedEntityIds").indexOf(video.getId());
                    if (index !== -1) {
                        this.get("startedEntityIds").splice(index, 1);
                    }
                    index = this.get("completedEntityIds").indexOf(video.getId());
                    if (index === -1) {
                        this.get("completedEntityIds").push(video.getId());
                    }
                } else {
                    index = this.get("startedEntityIds").indexOf(video.getId());
                    if (index === -1) {
                        this.get("startedEntityIds").push(video.getId());
                    }
                }

                var foundUserVideo = _(this.get("userVideos")).find((info) => {
                    info.video.id === video.getId();
                });
                var isNew = !foundUserVideo;
                foundUserVideo = foundUserVideo || {
                    video: {
                        id: video.getId()
                    },
                    duration: video.getDuration()
                };
                foundUserVideo["points"] = newPoints;
                foundUserVideo["last_second_watched"] = lastSecondWatched;
                if (isNew) {
                    this.get("userVideos").push(foundUserVideo);
                }

                this._saveStarted();
                this._saveCompleted();
                this._saveUserVideos();
                this._saveUserExercises();

                resolve({
                    completed: result.is_video_completed,
                    lastSecondWatched: result.last_second_watched,
                    pointsEarned: result.points_earned,
                    youtubeId: result.youtube_id,
                    videoId: videoId,
                    id: video.getId()
                });
            }).catch(() => {
// nodes after some interesting stages. by calling recurseAST. 
// The objective is that other concrete plugins register here and so the AST recursion is made 
// ONCE instead of using recurseAST in each of them.


var JsDocMaker = require('../core/class'); 
var PluginContainer = require('../core/plugin'); 
require('./util'); 
var _ = require('underscore'); 

// @class AfterTypeBindingRecurseASTPluginContainer it is both a plugin and a plugin container @extends PluginContainer
var AfterTypeBindingRecurseASTPluginContainer = function()
{
	return PluginContainer.apply(this, arguments); 
};
AfterTypeBindingRecurseASTPluginContainer.prototype = _({}).extend(PluginContainer.prototype);
_(AfterTypeBindingRecurseASTPluginContainer.prototype).extend(
{
	name: 'AfterTypeBindingRecurseASTPluginContainer'

	// for each AST node all child plugins will be executed - the objective is to recurse the ast only once.
,	execute: function(options)
	{
		// debugger;
		//TODO: this logic doesn't respect priority - don't copy and paste this logic here - define a cisitor method in super
		var result = null, self = this;
		options.jsdocmaker.recurseAST(function(node)
		{
			_(self.plugins).each(function(plugin) 
			{
				result = plugin.execute(node, plugin);
Example #27
0
			it('should call `junk.not` for every project name', function() {
				_(allProjectNames).each(function(projectName, index) {
					var args = mocks.junk.not.getCall(index).args;
					expect(args[0]).eql(projectName);
				});
			});
Example #28
0
  load: function() {
    var counter = 0;
    var files = [ this._entryFile ].concat(this._filesRequiredByFilters());

    this.loaded = false;
    this.error = null;
    this._compiledSrc = null;
    this._modules = [];
    this._moduleFileToIdMap = {};
    this._moduleHashToIdMap = {};
    this._moduleFileToModuleMap = {};
    this._multiFileIdSet = {};

    // for ensuring that extra requires don't also require themselves
    var userRequiredFiles = {};
    userRequiredFiles[this._entryFile] = true;
    this._userRequiredModuleIds = {};

    while (files.length > 0) {
      var file = path.resolve(files.shift());
      var id = this._moduleFileToIdMap[file];
      if (!id) { // We haven't seen this file before.
        var mod = new Module(file, this._options);

        // Ignore duplicates, i.e. identical files with different paths.
        // This comes up a lot because of how npm copies modules everywhere and
        // would be very wasteful when served over the network.
        var hash = mod.sha1();
        id = this._moduleHashToIdMap[hash];
        if (!id) { // This module is not a duplicate.
          id = (this._options.mangleNames ? counter++ : file);
          this._moduleHashToIdMap[hash] = id;
          mod.setId(id);

          this._modules.push(mod);

          var deps = mod.dependencies();
          // Mark user-required dependencies of user-required files as also being user-required.
          if (userRequiredFiles[file]) {
            _(deps).each(function(dep) {
              userRequiredFiles[dep] = true;
            });
          }
          files = files.concat(mod.extraDependencies().concat(deps));
        } else {
          this._multiFileIdSet[id] = true;
        }

        this._moduleFileToIdMap[file] = id;

        if (userRequiredFiles[file]) {
          this._userRequiredModuleIds[id] = true;
        }
      }
    }

    _(this._modules).each(function(mod) {
      var filename = mod.filename();
      this._updateModuleRequires(mod);
      if (this._options.watch) {
        this._moduleFileToModuleMap[filename] = mod;
        this._watchFile(filename);
      }
    }, this);

    this.loaded = true;
  },
Example #29
0
function render(resume) {
    var addressValues;
    var addressAttrs = ['address', 'city', 'region', 'countryCode', 'postalCode'];
    var css = fs.readFileSync(__dirname + '/assets/css/theme.css', 'utf-8');

    resume.basics.picture = utils.getUrlForPicture(resume);

    addressValues = _(addressAttrs).map(function(key) {
        return resume.basics.location[key];
    });

    resume.basics.computed_location = _.compact(addressValues).join(', ');

    if (resume.languages) {
        resume.basics.languages = _.pluck(resume.languages, 'language').join(', ');
    }

    _(resume.basics.profiles).each(function(profile) {
        var label = profile.network.toLowerCase();

        profile.url = utils.getUrlForProfile(resume, label);
        profile.label = label;
    });

    resume.basics.top_five_profiles = resume.basics.profiles.slice(0, 5);
    resume.basics.remaining_profiles = resume.basics.profiles.slice(5);


    _.each(resume.education, function(education_info) {
        _.each(['startDate', 'endDate'], function(type) {
            var date = education_info[type];

            if (date) {
                education_info[type] = utils.getFormattedDate(date);

                var end_date = new Date(date);
                var current_date = new Date();

                if (end_date > current_date) {
                  education_info[type] += " (expected)";
                }
            }
        });
    });

    _.each(resume.work, function(work_info) {
        var end_date;
        var start_date = moment(work_info.startDate, "YYYY-MM-DD");
        var did_leave_company = !!work_info.endDate;

        if (work_info.endDate) {
            end_date = moment(work_info.endDate, "YYYY-MM-DD");
            work_info.endDate = utils.getFormattedDate(end_date);
        }

        if (start_date) {
            end_date = end_date ? moment(end_date) : moment();
            work_info.startDate = utils.getFormattedDate(start_date);

            work_info.duration = moment.preciseDiff(start_date, end_date);
        }
    });

    _.each(resume.projects, function(project_info) {
        var duration;
        var start_date = project_info.startDate;
        var end_date = project_info.endDate;
        var did_leave_company = !!end_date;

        if (end_date) {
            project_info.endDate = utils.getFormattedDate(end_date);
        }

        if (start_date) {
            end_date = end_date || new Date();
            duration = utils.getDuration(start_date, end_date);
            project_info.startDate = utils.getFormattedDate(start_date);

            if (!duration.years() && !duration.months() && duration.days() > 1) {
                project_info.duration = 'Recently joined';
            } else {
                project_info.duration = utils.getDuration(start_date, end_date, true);
            }
        }
    });

    _.each(resume.volunteer, function(volunteer_info) {
        _.each(['startDate', 'endDate'], function (type) {
            var date = volunteer_info[type];

            if (date) {
                volunteer_info[type] = utils.getFormattedDate(date);
            }
        });
    });

    _.each(resume.skills, function(skill_info) {
        var levels = ['Beginner', 'Intermediate', 'Advanced', 'Master'];

        if (skill_info.level) {
            skill_info.skill_class = skill_info.level.toLowerCase();
            skill_info.level = capitalize(skill_info.level.trim());
            skill_info.display_progress_bar = _.contains(levels, skill_info.level);
        }
    });

    _.each(resume.awards, function(award) {
        var date = award.date;

        if (date) {
            award.date = utils.getFormattedDate(date, 'MMM DD, YYYY');
        }
    });

    _.each(resume.publications, function(publication_info) {
        var date = publication_info.releaseDate;

        if (date) {
            publication_info.releaseDate = utils.getFormattedDate(date, 'MMM DD, YYYY');
        }

        publication_info.author = publication_info.author.replace("Dongkwan Kim", "<b>Dongkwan Kim</b>")
    });

    return jade.renderFile(__dirname + '/index.jade', {
      resume: resume,
      floating_nav_items: getFloatingNavItems(resume),
      css: css,
      _: _
    });
}
Example #30
0
  , colors = require('colors');

process.chdir(path.resolve(__dirname, '../..'));

if (require.main === module) {
  args = parser.parseArgs();
  logFactory.init(args);
}

logger = logFactory.get('appium');

var appiumPermStat = fs.statSync(path.resolve(__dirname, '../../package.json'));

if (
  !isWindows &&
  (!_(process.env.SUDO_UID).isUndefined() || appiumPermStat.uid !== process.getuid()) &&
  !(process.env.SUDO_COMMAND || "").match(/grunt authorize/)
) {
  logger.error("Appium will not work if used or installed with sudo. " +
               "Please rerun/install as a non-root user. If you had to install " +
               "Appium using `sudo npm install -g appium`, the solution " +
               "is to reinstall Node using a method (Homebrew, for example) " +
               "that doesn't require sudo to install global npm packages.");
  process.exit(1);
}

var http = require('http')
  , express = require('express')
  , path = require('path')
  , appium = require('../appium.js')
  , parserWrap = require('./middleware').parserWrap