<commit_before>define(['marionette',

    'modules/imaging/collections/imagers',
    'modules/imaging/collections/inspections',

    'collections/containers',
    'modules/shipment/views/containers',

    'views/filter',
    'views/table', 'utils/table',
    'tpl!templates/imaging/dashboard.html',
    ], function(Marionette,
        Imagers, ContainerInspections,

        Containers, ContainersView,

        FilterView, TableView, table,
        template) {

    var ClickableRow = Backgrid.Row.extend({
        events: {
            'click': 'onClick',
        },
        onClick: function() {
            // dont do this :(
            // should not be using the global event handler
            app.trigger('select:imager', this.model.get('IMAGERID'))
        },
    })

    var ClickableRow2 = Backgrid.Row.extend({
        events: {
            'click': 'onClick',
        },

        onClick: function(e) {
            if ($(e.target).is('i') || $(e.target).is('a') || $(e.target).hasClass('editable')) return
            if (this.cookie && this.model.get('PROP')) app.cookie(this.model.get('PROP'))
            app.trigger('container:show', this.model.get('CONTAINERID'), this.model.get('CONTAINERINSPECTIONID'))
        },
    })

    return Marionette.LayoutView.extend({
        className: 'content',
        template: template,

        regions: {
            imgrs: '.imagers',
            insp: '.inspections',
            insf: '.inspection_filter',
            ctrs: '.ctrs',
        },

        initialize: function(options) {
            this.imagers = new Imagers()
            this.imagers.fetch()

            this.inspections = new ContainerInspections()
            this.inspections.queryParams.all = 1
            this.inspections.queryParams.allStates = 1
            this.inspections.setSorting('BLTIMESTAMP', 1)
            this.inspections.fetch()

            this.containers = new Containers()
            this.containers.queryParams.imager = 1
            this.containers.queryParams.all = 1
            this.containers.fetch()

            this.listenTo(app, 'select:imager', this.selectImager, this)
        },

        selectImager: function(iid) {
            this.containers.queryParams.iid = iid
            this.containers.fetch()
        },

        onRender: function() {
            var columns = [{ name: 'NAME', label: 'Name', cell: 'string', editable: false },
                         { name: 'TEMPERATURE', label: 'Temperature', cell: 'string', editable: false },
                         { name: 'SERIAL', label: 'Serial', cell: 'string', editable: false },
                         { name: 'CAPACITY', label: 'Capacity', cell: 'string', editable: false },
                         { name: 'PUSAGE', label: 'Usage (%)', cell: 'string', editable: false },
            ]

            this.imgrs.show(new TableView({
                collection: this.imagers,
                columns: columns,
                tableClass: 'imagers',
                loading: true, pages: false,
                backgrid: { emptyText: 'No imagers found', row: ClickableRow }
            }))

            var columns = [{ name: 'PROP', label: 'Proposal', cell: 'string', editable: false },
                         { name: 'VISIT_NUMBER', label: 'Visit', cell: 'string', editable: false },
                         { name: 'CONTAINER', label: 'Container', cell: 'string', editable: false },
                         { name: 'CONTAINERID', label: 'Container ID', cell: 'string', editable: false },
                         { name: 'CONTAINERINSPECTIONID', label: 'Inspection ID', cell: 'string', editable: false },
                         { name: 'STATE', label: 'State', cell: 'string', editable: false },
                         { label: 'Adhoc', cell: table.TemplateCell, editable: false, template: "<%=SCHEDULECOMPONENTID ? 'No' : 'Yes' %>" },
                         { label: 'Manual', cell: table.TemplateCell, editable: false, template: "<%=MANUAL == '1' ? 'Yes':'No' %>" },
                         { name: 'INSPECTIONTYPE', label: 'Type', cell: 'string', editable: false },
                         { name: 'SCHEDULEDTIMESTAMP', label: 'Scheduled', cell: 'string', editable: false },
                         { name: 'BLTIMESTAMP', label: 'Started', cell: 'string', editable: false },
                         { name: 'DURATION', label: 'Took (m)', cell: 'string', editable: false },
                         { name: 'DWELL', label: 'Dwell (d)', cell: 'string', editable: false },
                         { name: 'AGE', label: 'Age (d)', cell: 'string', editable: false },
                         { label: 'Scored', cell: table.TemplateCell, editable: false, template: "<%=IMAGESSCORED == '1' ? 'Yes' : 'No' %>" },

            ]

            this.insp.show(new TableView({
                collection: this.inspections,
                columns: columns,
                tableClass: 'inspections',
                loading: true,
                filter: 's',
                backgrid: { emptyText: 'No inspections found', row: ClickableRow2 },
                noPageUrl: true,
            }))

            var filters = [
                { name: 'Completed', id: 'COMPLETED' },
                { name: 'Incomplete', id: 'INCOMPLETE' },
                { name: 'Scheduled', id: 'SCHEDULED' },
                { name: 'Adhoc', id: 'ADHOC' },
                { name: 'Manual', id: 'MANUAL' },
            ]

            this.ty = new FilterView({ collection: this.inspections, filters: filters, mobile: true, url: false, name: 'ty' })
            this.insf.show(this.ty)

            this.ctrs.show(new ContainersView({ collection: this.containers, params: {} }))
        },

    })

})
<commit_msg>change prop as needed<commit_after>define(['marionette',

    'modules/imaging/collections/imagers',
    'modules/imaging/collections/inspections',

    'collections/containers',
    'modules/shipment/views/containers',

    'views/filter',
    'views/table', 'utils/table',
    'tpl!templates/imaging/dashboard.html',
    ], function(Marionette,
        Imagers, ContainerInspections,

        Containers, ContainersView,

        FilterView, TableView, table,
        template) {

    var ClickableRow = Backgrid.Row.extend({
        events: {
            'click': 'onClick',
        },
        onClick: function() {
            // dont do this :(
            // should not be using the global event handler
            app.trigger('select:imager', this.model.get('IMAGERID'))
        },
    })

    var ClickableRow2 = Backgrid.Row.extend({
        events: {
            'click': 'onClick',
        },

        onClick: function(e) {
            if ($(e.target).is('i') || $(e.target).is('a') || $(e.target).hasClass('editable')) return
            if (this.model.get('PROP')) app.cookie(this.model.get('PROP'))
            app.trigger('container:show', this.model.get('CONTAINERID'), this.model.get('CONTAINERINSPECTIONID'))
        },
    })

    return Marionette.LayoutView.extend({
        className: 'content',
        template: template,

        regions: {
            imgrs: '.imagers',
            insp: '.inspections',
            insf: '.inspection_filter',
            ctrs: '.ctrs',
        },

        initialize: function(options) {
            this.imagers = new Imagers()
            this.imagers.fetch()

            this.inspections = new ContainerInspections()
            this.inspections.queryParams.all = 1
            this.inspections.queryParams.allStates = 1
            this.inspections.setSorting('BLTIMESTAMP', 1)
            this.inspections.fetch()

            this.containers = new Containers()
            this.containers.queryParams.imager = 1
            this.containers.queryParams.all = 1
            this.containers.fetch()

            this.listenTo(app, 'select:imager', this.selectImager, this)
        },

        selectImager: function(iid) {
            this.containers.queryParams.iid = iid
            this.containers.fetch()
        },

        onRender: function() {
            var columns = [{ name: 'NAME', label: 'Name', cell: 'string', editable: false },
                         { name: 'TEMPERATURE', label: 'Temperature', cell: 'string', editable: false },
                         { name: 'SERIAL', label: 'Serial', cell: 'string', editable: false },
                         { name: 'CAPACITY', label: 'Capacity', cell: 'string', editable: false },
                         { name: 'PUSAGE', label: 'Usage (%)', cell: 'string', editable: false },
            ]

            this.imgrs.show(new TableView({
                collection: this.imagers,
                columns: columns,
                tableClass: 'imagers',
                loading: true, pages: false,
                backgrid: { emptyText: 'No imagers found', row: ClickableRow }
            }))

            var columns = [{ name: 'PROP', label: 'Proposal', cell: 'string', editable: false },
                         { name: 'VISIT_NUMBER', label: 'Visit', cell: 'string', editable: false },
                         { name: 'CONTAINER', label: 'Container', cell: 'string', editable: false },
                         { name: 'CONTAINERID', label: 'Container ID', cell: 'string', editable: false },
                         { name: 'CONTAINERINSPECTIONID', label: 'Inspection ID', cell: 'string', editable: false },
                         { name: 'STATE', label: 'State', cell: 'string', editable: false },
                         { label: 'Adhoc', cell: table.TemplateCell, editable: false, template: "<%=SCHEDULECOMPONENTID ? 'No' : 'Yes' %>" },
                         { label: 'Manual', cell: table.TemplateCell, editable: false, template: "<%=MANUAL == '1' ? 'Yes':'No' %>" },
                         { name: 'INSPECTIONTYPE', label: 'Type', cell: 'string', editable: false },
                         { name: 'SCHEDULEDTIMESTAMP', label: 'Scheduled', cell: 'string', editable: false },
                         { name: 'BLTIMESTAMP', label: 'Started', cell: 'string', editable: false },
                         { name: 'DURATION', label: 'Took (m)', cell: 'string', editable: false },
                         { name: 'DWELL', label: 'Dwell (d)', cell: 'string', editable: false },
                         { name: 'AGE', label: 'Age (d)', cell: 'string', editable: false },
                         { label: 'Scored', cell: table.TemplateCell, editable: false, template: "<%=IMAGESSCORED == '1' ? 'Yes' : 'No' %>" },

            ]

            this.insp.show(new TableView({
                collection: this.inspections,
                columns: columns,
                tableClass: 'inspections',
                loading: true,
                filter: 's',
                backgrid: { emptyText: 'No inspections found', row: ClickableRow2 },
                noPageUrl: true,
            }))

            var filters = [
                { name: 'Completed', id: 'COMPLETED' },
                { name: 'Incomplete', id: 'INCOMPLETE' },
                { name: 'Scheduled', id: 'SCHEDULED' },
                { name: 'Adhoc', id: 'ADHOC' },
                { name: 'Manual', id: 'MANUAL' },
            ]

            this.ty = new FilterView({ collection: this.inspections, filters: filters, mobile: true, url: false, name: 'ty' })
            this.insf.show(this.ty)

            this.ctrs.show(new ContainersView({ collection: this.containers, params: {} }))
        },

    })

})
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */
import * as mongo from 'mongodb';
import Post from '../../models/post';
import serialize from '../../serializers/post';
import es from '../../db/elasticsearch';

const size = 10;

/**
 * Search a post
 *
 * @param {Object} params
 * @param {Object} user
 * @return {Promise<object>}
 */
module.exports = (params, user) =>
	new Promise(async (res, rej) =>
{
	// Init 'query' parameter
	let query = params.query;
	if (query === undefined || query === null || query.trim() === '') {
		return rej('query is required');
	}

	// Init 'page' parameter
	let page = params.page;
	if (page === undefined) {
		page = 0;
	}

	const from = page * size;

	es.search({
		index: 'misskey',
		type: 'post',
		body: {
			size: size,
			from: from,
			query: {
				simple_query_string: {
					fields: ['text'],
					query: query,
					default_operator: 'and'
				}
			}
		}
	}, async (error, response) => {
		if (error) {
			console.error(error);
			return res(500);
		}

		if (response.hits.total === 0) {
			return res([]);
		}

		const hits = response.hits.hits.map(hit => new mongo.ObjectID(hit._id));

		const posts = await Post
			.find({
				_id: {
					$in: hits
				}
			})
			.toArray();

		// Serialize
		res(await Promise.all(posts.map(async post =>
			await serialize(post))));
	});
});
<commit_msg>Include highlighted text<commit_after>'use strict';

/**
 * Module dependencies
 */
import * as mongo from 'mongodb';
import Post from '../../models/post';
import serialize from '../../serializers/post';
import es from '../../db/elasticsearch';

const size = 10;

/**
 * Search a post
 *
 * @param {Object} params
 * @param {Object} user
 * @return {Promise<object>}
 */
module.exports = (params, user) =>
	new Promise(async (res, rej) =>
{
	// Init 'query' parameter
	let query = params.query;
	if (query === undefined || query === null || query.trim() === '') {
		return rej('query is required');
	}

	// Init 'page' parameter
	let page = params.page;
	if (page === undefined) {
		page = 0;
	}

	const from = page * size;

	es.search({
		index: 'misskey',
		type: 'post',
		body: {
			size: size,
			from: from,
			query: {
				simple_query_string: {
					fields: ['text'],
					query: query,
					default_operator: 'and'
				}
			},
			highlight: {
				pre_tags: ['<mark>'],
				post_tags: ['</mark>'],
				encoder: 'html',
				fields: {
					text: {}
				}
			}
		}
	}, async (error, response) => {
		if (error) {
			console.error(error);
			return res(500);
		}

		if (response.hits.total === 0) {
			return res([]);
		}

		const hits = response.hits.hits.map(hit => new mongo.ObjectID(hit._id));

		const posts = await Post
			.find({
				_id: {
					$in: hits
				}
			})
			.toArray();

		posts.map(post => {
			post._highlight = response.hits.hits.filter(hit => hit._id == post._id.toString())[0].highlight.text[0];
		});

		// Serialize
		res(await Promise.all(posts.map(async post =>
			await serialize(post))));
	});
});
<|endoftext|>


<commit_before>//   Automatic Dictionary Switcher Add-on for Firefox
//   Copyright 2015 Daniel Naber
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

const minimumCharacterLength = 25,
      feedBackDivRefreshRate = 100;
      feedBackWaitText = "...";

let userPreferences,
     // a div that shows feedback of detected language:
    feedbackDiv = document.createElement("div"),
    feedbackTimeout,
    // input element which the addon operates on currently (e.g. textarea):
    currentInputElement,
    ignoreSignature;

// Initialize the feedback div. It has our unique id:
feedbackDiv.id = "danielnaber-firefox-dict-switcher-tooltip";

// Listen to a message from the main script containing user preferences
self.port.on("config", function (prefs)
{
    // We require the presence of user preferences just to know the languages for which the user chose "Don't
    // detect this language" option so that we disable spell checking if we encountered text in these languages
    userPreferences = prefs;
    ignoreSignature = userPreferences["ignoreSignature"];
});

// The main script sends this message after it receives the detected language code, and found the language dialect
// (ie. the dictionary) that will be used, or found that there's no dictionary for the detected language
// See the changeDictionary function in main.js
self.port.on("feedback", function (feedback)
{
    showFeedback(currentInputElement, feedback.language, feedback.message, feedback.isWarning);
});

function detectAndSetLanguage(targetElement, text)
{
    // If spell checking was disabled by the page developer, we honor the setting and don't set the value of
    // the spellcheck attribute to true, but we still try to detect the language and keep the ordinary operation
    // of the addon because the user can manually enable spell checking from the context menu, and the spellcheck
    // attribute stays false.
    // I set the developerDisabledSpellChecking to indicate this case
    // (see how the firefoxDictSwitcherDisabledSpellCheck flag is set later)
    const developerDisabledSpellChecking = targetElement.spellcheck === false &&
                                          !targetElement.dataset.firefoxDictSwitcherDisabledSpellCheck;

    // text is an optional parameter used when handling the paste event only. Otherwise, we read the text from
    // the element itself
    text = text || targetElement.value || targetElement.textContent;

    if(ignoreSignature)
    {
        let signatureDelimiterPos = text.indexOf("-- \n");

        if(signatureDelimiterPos >= 0)
        {
            // cut off signature: it may be written in a different language than
            // the main text and would thus decrease language detection quality:
            text = text.substring(0, signatureDelimiterPos);
        }
    }

    // we are only going to check language if there is some amount of text available as
    // that will increase our chances of detecting language correctly.
    if(text.length > minimumCharacterLength)
    {
        //const startTime = performance.now();

        // Looks like we have enough text to reliably detect the language.
        let detectableLanguages = getDetectableLanguages();

        var language;
        try {
            language = franc(text,
                {
                    // top 20 + user settings:
                    'whitelist': detectableLanguages
                });
        } catch (e) {
            showFeedback(targetElement, "??", "Error: Could not detect language: " + e.toString(), true);
            return;
        }

        var shortCode;
        if(language === "und")  // 'unknown'
        {
            showFeedback(targetElement, feedBackWaitText, "Language not configured or need more characters to detect language");
            return;
        }
        else
        {
            var languageInfo = iso6393[language];
            if(!languageInfo)
            {
                showFeedback(targetElement, "??", "Error: Could not find short language code for '" + language + "'", true);
                return;
            }
            shortCode = languageInfo.iso6391;
        }

        //console.log(`Detected language code is (${language}) in ${performance.now() - startTime} ms`);

        // If the language wasn't successfully identified
        // If the user chose to ignore the detected language (see the configs in package.json)
        if(userPreferences[shortCode] == "-")
            showFeedback(targetElement, "--", "Detected " + shortCode + " but it's disabled in configuration");
        else
        {
            // We won't show the feedback tooltip until the main script sends us the language dialect that
            // will be used, and whether or not it found a dictionary for this dialect, so, keep a reference
            // for the input element the user currently edits so that we can show the feedback tooltip on it
            // later.
            // Notice that we are either passed targetElement as a parameter or use the current activeElement
            // (in case of paste events only)
            currentInputElement = targetElement || document.activeElement;

            // If the language was detected successfully enable spell checking and send its code to the main script
            if(!developerDisabledSpellChecking)
            {
                // We enable spell checking only if the attribute wasn't already set to false by the page developer
                targetElement.spellcheck = true;
            }

            self.port.emit("changeDictionary", shortCode);

            return;
        }

        // Disable spell checking...
        targetElement.spellcheck = false;

        // ...send null to indicate to the main script that either we failed to detect or the language is disabled...
        //self.port.emit("changeDictionary", null);

        // ...and set a flag to indicate that it's our code who disabled spell checking not the page developer's
        // We do so only if the attribute wasn't already set to false be the page developer
        if(!developerDisabledSpellChecking)
            targetElement.dataset.firefoxDictSwitcherDisabledSpellCheck = "1";
    }
    else
    {
        showFeedback(targetElement, feedBackWaitText, "Need more characters to detect language");

        // Because we can't detect the language, disable spell checking
        targetElement.spellcheck = false;

        // Sending null to the main script also indicates that the input text is too short to detect the language
        self.port.emit("changeDictionary", null);

        // And set a flag to indicate that it's our code who disabled spell checking not the page developer's
        // We do so only if the attribute wasn't already set to false be the page developer
        if(!developerDisabledSpellChecking)
            targetElement.dataset.firefoxDictSwitcherDisabledSpellCheck = "1";
    }
}

function getDetectableLanguages()
{
    let detectableLanguages = ['cmn', 'spa', 'eng', 'rus', 'arb', 'ben', 'hin', 'por', 'ind', 'jpn',
                               'fra', 'deu', 'jav', 'kor', 'tel', 'vie', 'mar', 'ita', 'tam', 'tur'];
    addAdditionalLanguages(detectableLanguages);
    removeDisabledLanguages(detectableLanguages);
    return detectableLanguages;
}

function addAdditionalLanguages(detectableLanguages)
{
    for (var i = 1; i <= 3; i++)
    {
        let additionalLanguage = userPreferences["additionalLanguage"+i];
        if (additionalLanguage && additionalLanguage !== '-')
        {
            detectableLanguages.push(additionalLanguage);
        }
    }
}

function removeDisabledLanguages(detectableLanguages)
{
    const potentiallyDisabledLanguages = [
        { short: 'en', long: 'eng' },
        { short: 'es', long: 'spa' },
        { short: 'de', long: 'deu' },
        { short: 'pt', long: 'por' } ];  // these have variants and a "Don't detect this language" option in the settings
    for (let idx in potentiallyDisabledLanguages)
    {
        let shortCode = potentiallyDisabledLanguages[idx].short;
        if (userPreferences[shortCode] === '-')
        {
            let longCode = potentiallyDisabledLanguages[idx].long;
            let pos = detectableLanguages.indexOf(longCode);
            if (pos > -1)
            {
                detectableLanguages.splice(pos, 1);
            }
        }
    }
}

function showFeedback(element, feedbackText, feedbackTitle, isWarning)
{
    // Detach the feedback div from the document if it were previously attached
    if(feedbackDiv.parentElement)
        feedbackDiv.parentElement.removeChild(feedbackDiv);

    //const parentElement = element.offsetParent;

    //// offsetParent is null if the element itself is hidden. If the element is hidden we exit as, of course,
    //// we won't show feedback on a hidden element
    //if(!parentElement)
    //    return;

    currentInputElement = element;

    feedbackDiv.title = feedbackTitle;
    feedbackDiv.textContent = feedbackText;

    if(isWarning)
        feedbackDiv.classList.add("firefox-dict-switcher-warning");
    else
        feedbackDiv.classList.remove("firefox-dict-switcher-warning");

    document.body.appendChild(feedbackDiv);

    // Instantly position the feedback div
    positionFeedbackDiv();

    // Initialize the positioning loop
    setTimeout(positionFeedbackDiv, feedBackDivRefreshRate);

    // the feedback item can cover text, so hide it after some time (unless it's "...", i.e. not detection yet):
    if (feedbackText !== feedBackWaitText) {
        if (feedbackTimeout)
        {
            clearTimeout(feedbackTimeout);
        }
        let feedbackHideSeconds = userPreferences["feedbackHideSeconds"] * 1000;
        // TODO: not robust enough yet:
        //feedbackTimeout = setTimeout(function() {fadeOut(feedbackDiv)}, feedbackHideSeconds);
        feedbackTimeout = setTimeout(function() {feedbackDiv.parentElement.removeChild(feedbackDiv)}, feedbackHideSeconds);
    }
}

function fadeOut(el)
{
    el.style.opacity = 1;
    (function fade()
    {
        if ((el.style.opacity -= 0.05) < 0)
        {
            if (feedbackDiv.parentElement)
            {
                feedbackDiv.parentElement.removeChild(feedbackDiv);
                el.style.opacity = 1;
            }
        }
        else
        {
            requestAnimationFrame(fade);
        }
    })();
}

// This function keeps the feedback div always positioned properly relative to
function positionFeedbackDiv()
{
    const parentElement = feedbackDiv.parentElement;

    if(!parentElement)
        return;

    const clientRect = currentInputElement.getBoundingClientRect(),
          leftPos = clientRect.left + window.scrollX + currentInputElement.offsetWidth - feedbackDiv.offsetWidth - 18,
          topPos = clientRect.top + window.scrollY + currentInputElement.offsetHeight - feedbackDiv.offsetHeight - 5;

    feedbackDiv.style.left = leftPos + "px";
    feedbackDiv.style.top = topPos + "px";

    // Keep the loop going but don't waste CPU
    setTimeout(positionFeedbackDiv, feedBackDivRefreshRate);
}

function isEligible(element)
{
    // The addon operates only on textarea elements or elements with the contentEditable attribute set
    return element.tagName == "TEXTAREA" ||
           element.contentEditable === 'true';
}

// Note from Ashraf: I commented the old code that initially iterates over all TEXTAREA elements and instead
// used event delegation by attaching event handlers only to the root element. This is better for performance
// and covers the elements that are later appended to the DOM
document.documentElement.addEventListener("keydown", function (evt)
{
    if(isEligible(evt.target))
    {
        var key = evt.keyCode || evt.charCode;

        // check if user has finished entering a word
        if(key == 32/*space*/ || key == 188/*comma*/ || key == 190/*dot*/)
        {
            detectAndSetLanguage(evt.target);
        }
    }
});

// HACK: The focus event doesn't bubble, so I set the useCapture parameter of addEventListener to true.
// We should use the focusin event which bubbles but it's not supported on Firefox as of the date I wrote this.
// See the note on this article https://developer.mozilla.org/en-US/docs/Web/Events/focusin
document.documentElement.addEventListener("focus", function (evt)
{
    // Set correct language when we set the focus to already filled textarea
    if(isEligible(evt.target))
        detectAndSetLanguage(evt.target);
}, true);

// HACK: The blur event doesn't bubble, so I set the useCapture parameter of addEventListener to true.
// We should use the focusout event which bubbles but it's not supported on Firefox as of the date I wrote this.
// See the note on this article https://developer.mozilla.org/en-US/docs/Web/Events/focusout
document.documentElement.addEventListener("blur", function (evt)
{
    // When the focus gets out of an element, detach the feedback div from the document
    if(feedbackDiv.parentElement)
        feedbackDiv.parentElement.removeChild(feedbackDiv);
}, true);

document.documentElement.addEventListener("paste", function (e)
{
    // We act only when data is pasted on a TEXTAREA element
    if(isEligible(e.target))
    {
        // We try to detect only if the pasted data is available in plain text format
        const text = e.clipboardData.getData("text/plain");

        if(text)
            detectAndSetLanguage(e.target, text);
    }
});<commit_msg>don't re-show message after auto-hide<commit_after>//   Automatic Dictionary Switcher Add-on for Firefox
//   Copyright 2015 Daniel Naber
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

const minimumCharacterLength = 25,
      feedBackDivRefreshRate = 100;
      feedBackWaitText = "...";

let userPreferences,
     // a div that shows feedback of detected language:
    feedbackDiv = document.createElement("div"),
    feedbackTimeout,
    // input element which the addon operates on currently (e.g. textarea):
    currentInputElement,
    ignoreSignature;

// Initialize the feedback div. It has our unique id:
feedbackDiv.id = "danielnaber-firefox-dict-switcher-tooltip";

// Listen to a message from the main script containing user preferences
self.port.on("config", function (prefs)
{
    // We require the presence of user preferences just to know the languages for which the user chose "Don't
    // detect this language" option so that we disable spell checking if we encountered text in these languages
    userPreferences = prefs;
    ignoreSignature = userPreferences["ignoreSignature"];
});

// The main script sends this message after it receives the detected language code, and found the language dialect
// (ie. the dictionary) that will be used, or found that there's no dictionary for the detected language
// See the changeDictionary function in main.js
self.port.on("feedback", function (feedback)
{
    showFeedback(currentInputElement, feedback.language, feedback.message, feedback.isWarning);
});

function detectAndSetLanguage(targetElement, text)
{
    // If spell checking was disabled by the page developer, we honor the setting and don't set the value of
    // the spellcheck attribute to true, but we still try to detect the language and keep the ordinary operation
    // of the addon because the user can manually enable spell checking from the context menu, and the spellcheck
    // attribute stays false.
    // I set the developerDisabledSpellChecking to indicate this case
    // (see how the firefoxDictSwitcherDisabledSpellCheck flag is set later)
    const developerDisabledSpellChecking = targetElement.spellcheck === false &&
                                          !targetElement.dataset.firefoxDictSwitcherDisabledSpellCheck;

    // text is an optional parameter used when handling the paste event only. Otherwise, we read the text from
    // the element itself
    text = text || targetElement.value || targetElement.textContent;

    if(ignoreSignature)
    {
        let signatureDelimiterPos = text.indexOf("-- \n");

        if(signatureDelimiterPos >= 0)
        {
            // cut off signature: it may be written in a different language than
            // the main text and would thus decrease language detection quality:
            text = text.substring(0, signatureDelimiterPos);
        }
    }

    // we are only going to check language if there is some amount of text available as
    // that will increase our chances of detecting language correctly.
    if(text.length > minimumCharacterLength)
    {
        //const startTime = performance.now();

        // Looks like we have enough text to reliably detect the language.
        let detectableLanguages = getDetectableLanguages();

        var language;
        try {
            language = franc(text,
                {
                    // top 20 + user settings:
                    'whitelist': detectableLanguages
                });
        } catch (e) {
            showFeedback(targetElement, "??", "Error: Could not detect language: " + e.toString(), true);
            return;
        }

        var shortCode;
        if(language === "und")  // 'unknown'
        {
            showFeedback(targetElement, feedBackWaitText, "Language not configured or need more characters to detect language");
            return;
        }
        else
        {
            var languageInfo = iso6393[language];
            if(!languageInfo)
            {
                showFeedback(targetElement, "??", "Error: Could not find short language code for '" + language + "'", true);
                return;
            }
            shortCode = languageInfo.iso6391;
        }

        //console.log(`Detected language code is (${language}) in ${performance.now() - startTime} ms`);

        // If the language wasn't successfully identified
        // If the user chose to ignore the detected language (see the configs in package.json)
        if(userPreferences[shortCode] == "-")
            showFeedback(targetElement, "--", "Detected " + shortCode + " but it's disabled in configuration");
        else
        {
            // We won't show the feedback tooltip until the main script sends us the language dialect that
            // will be used, and whether or not it found a dictionary for this dialect, so, keep a reference
            // for the input element the user currently edits so that we can show the feedback tooltip on it
            // later.
            // Notice that we are either passed targetElement as a parameter or use the current activeElement
            // (in case of paste events only)
            currentInputElement = targetElement || document.activeElement;

            // If the language was detected successfully enable spell checking and send its code to the main script
            if(!developerDisabledSpellChecking)
            {
                // We enable spell checking only if the attribute wasn't already set to false by the page developer
                targetElement.spellcheck = true;
            }

            self.port.emit("changeDictionary", shortCode);

            return;
        }

        // Disable spell checking...
        targetElement.spellcheck = false;

        // ...send null to indicate to the main script that either we failed to detect or the language is disabled...
        //self.port.emit("changeDictionary", null);

        // ...and set a flag to indicate that it's our code who disabled spell checking not the page developer's
        // We do so only if the attribute wasn't already set to false be the page developer
        if(!developerDisabledSpellChecking)
            targetElement.dataset.firefoxDictSwitcherDisabledSpellCheck = "1";
    }
    else
    {
        showFeedback(targetElement, feedBackWaitText, "Need more characters to detect language");

        // Because we can't detect the language, disable spell checking
        targetElement.spellcheck = false;

        // Sending null to the main script also indicates that the input text is too short to detect the language
        self.port.emit("changeDictionary", null);

        // And set a flag to indicate that it's our code who disabled spell checking not the page developer's
        // We do so only if the attribute wasn't already set to false be the page developer
        if(!developerDisabledSpellChecking)
            targetElement.dataset.firefoxDictSwitcherDisabledSpellCheck = "1";
    }
}

function getDetectableLanguages()
{
    let detectableLanguages = ['cmn', 'spa', 'eng', 'rus', 'arb', 'ben', 'hin', 'por', 'ind', 'jpn',
                               'fra', 'deu', 'jav', 'kor', 'tel', 'vie', 'mar', 'ita', 'tam', 'tur'];
    addAdditionalLanguages(detectableLanguages);
    removeDisabledLanguages(detectableLanguages);
    return detectableLanguages;
}

function addAdditionalLanguages(detectableLanguages)
{
    for (var i = 1; i <= 3; i++)
    {
        let additionalLanguage = userPreferences["additionalLanguage"+i];
        if (additionalLanguage && additionalLanguage !== '-')
        {
            detectableLanguages.push(additionalLanguage);
        }
    }
}

function removeDisabledLanguages(detectableLanguages)
{
    const potentiallyDisabledLanguages = [
        { short: 'en', long: 'eng' },
        { short: 'es', long: 'spa' },
        { short: 'de', long: 'deu' },
        { short: 'pt', long: 'por' } ];  // these have variants and a "Don't detect this language" option in the settings
    for (let idx in potentiallyDisabledLanguages)
    {
        let shortCode = potentiallyDisabledLanguages[idx].short;
        if (userPreferences[shortCode] === '-')
        {
            let longCode = potentiallyDisabledLanguages[idx].long;
            let pos = detectableLanguages.indexOf(longCode);
            if (pos > -1)
            {
                detectableLanguages.splice(pos, 1);
            }
        }
    }
}

function showFeedback(element, feedbackText, feedbackTitle, isWarning)
{

    if (feedbackDiv.textContent === feedbackText)
    {
        // don't always show the same feedback after is has been hidden
        return;
    }

    // Detach the feedback div from the document if it were previously attached
    if(feedbackDiv.parentElement)
        feedbackDiv.parentElement.removeChild(feedbackDiv);

    //const parentElement = element.offsetParent;

    //// offsetParent is null if the element itself is hidden. If the element is hidden we exit as, of course,
    //// we won't show feedback on a hidden element
    //if(!parentElement)
    //    return;

    currentInputElement = element;

    feedbackDiv.title = feedbackTitle;
    feedbackDiv.textContent = feedbackText;

    if(isWarning)
        feedbackDiv.classList.add("firefox-dict-switcher-warning");
    else
        feedbackDiv.classList.remove("firefox-dict-switcher-warning");

    document.body.appendChild(feedbackDiv);

    // Instantly position the feedback div
    positionFeedbackDiv();

    // Initialize the positioning loop
    setTimeout(positionFeedbackDiv, feedBackDivRefreshRate);

    // the feedback item can cover text, so hide it after some time (unless it's "...", i.e. not detection yet):
    if (feedbackText !== feedBackWaitText) {
        if (feedbackTimeout)
        {
            clearTimeout(feedbackTimeout);
        }
        let feedbackHideSeconds = userPreferences["feedbackHideSeconds"] * 1000;
        // TODO: not robust enough yet:
        //feedbackTimeout = setTimeout(function() {fadeOut(feedbackDiv)}, feedbackHideSeconds);
        feedbackTimeout = setTimeout(function() {
            if (feedbackDiv.parentElement)
            {
                feedbackDiv.parentElement.removeChild(feedbackDiv);
            }
        }, feedbackHideSeconds);
    }
}

function fadeOut(el)
{
    el.style.opacity = 1;
    (function fade()
    {
        if ((el.style.opacity -= 0.05) < 0)
        {
            if (feedbackDiv.parentElement)
            {
                feedbackDiv.parentElement.removeChild(feedbackDiv);
                feedbackDiv.textContent = feedBackWaitText;
                el.style.opacity = 1;
            }
        }
        else
        {
            requestAnimationFrame(fade);
        }
    })();
}

// This function keeps the feedback div always positioned properly relative to
function positionFeedbackDiv()
{
    const parentElement = feedbackDiv.parentElement;

    if(!parentElement)
        return;

    const clientRect = currentInputElement.getBoundingClientRect(),
          leftPos = clientRect.left + window.scrollX + currentInputElement.offsetWidth - feedbackDiv.offsetWidth - 18,
          topPos = clientRect.top + window.scrollY + currentInputElement.offsetHeight - feedbackDiv.offsetHeight - 5;

    feedbackDiv.style.left = leftPos + "px";
    feedbackDiv.style.top = topPos + "px";

    // Keep the loop going but don't waste CPU
    setTimeout(positionFeedbackDiv, feedBackDivRefreshRate);
}

function isEligible(element)
{
    // The addon operates only on textarea elements or elements with the contentEditable attribute set
    return element.tagName == "TEXTAREA" ||
           element.contentEditable === 'true';
}

// Note from Ashraf: I commented the old code that initially iterates over all TEXTAREA elements and instead
// used event delegation by attaching event handlers only to the root element. This is better for performance
// and covers the elements that are later appended to the DOM
document.documentElement.addEventListener("keydown", function (evt)
{
    if(isEligible(evt.target))
    {
        var key = evt.keyCode || evt.charCode;

        // check if user has finished entering a word
        if(key == 32/*space*/ || key == 188/*comma*/ || key == 190/*dot*/)
        {
            detectAndSetLanguage(evt.target);
        }
    }
});

// HACK: The focus event doesn't bubble, so I set the useCapture parameter of addEventListener to true.
// We should use the focusin event which bubbles but it's not supported on Firefox as of the date I wrote this.
// See the note on this article https://developer.mozilla.org/en-US/docs/Web/Events/focusin
document.documentElement.addEventListener("focus", function (evt)
{
    // Set correct language when we set the focus to already filled textarea
    if(isEligible(evt.target))
        detectAndSetLanguage(evt.target);
}, true);

// HACK: The blur event doesn't bubble, so I set the useCapture parameter of addEventListener to true.
// We should use the focusout event which bubbles but it's not supported on Firefox as of the date I wrote this.
// See the note on this article https://developer.mozilla.org/en-US/docs/Web/Events/focusout
document.documentElement.addEventListener("blur", function (evt)
{
    // When the focus gets out of an element, detach the feedback div from the document
    if(feedbackDiv.parentElement)
        feedbackDiv.parentElement.removeChild(feedbackDiv);
        // when user enters field later, feedback will be shown again:
        feedbackDiv.textContent = feedBackWaitText;
}, true);

document.documentElement.addEventListener("paste", function (e)
{
    // We act only when data is pasted on a TEXTAREA element
    if(isEligible(e.target))
    {
        // We try to detect only if the pasted data is available in plain text format
        const text = e.clipboardData.getData("text/plain");

        if(text)
            detectAndSetLanguage(e.target, text);
    }
});<|endoftext|>


<commit_before>define(['backbone'], function(Backbone){

    return Backbone.Model.extend({
        idAttribute: 'AID',

        initialize: function(options) {
            this.addClasses()
            this.addIcon()
        },

        addClasses: function() {
            if (this.get('PROCESSINGSTATUS') == '0') return

            this.attributes.CLASS = { RMERGE: {}, RMEAS: {}, COMPLETENESS: {} }
            _.each(['overall', 'innerShell', 'outerShell'], function(k) {
                var c = this.get('SHELLS')[k].COMPLETENESS
                this.attributes.CLASS.COMPLETENESS[k] = c > 95 ? 'active' : (c > 80 ? 'minor' : 'inactive')

                var r = this.get('SHELLS')[k].RMEAS
                this.attributes.CLASS.RMEAS[k] = r < 0.5 ? 'active' : (r < 0.6 ? 'minor' : 'inactive')
            }, this)
        },

        addIcon: function() {
            var icons = {
                ERROR: '',
                WARNING: ''
            }
            var priorities = ['WARNING', 'ERROR']

            var priority = -1
            var icon = ''
            _.each(this.get('MESSAGES'), function(m) {
                var p = priorities.indexOf(m.SEVERITY)
                if (p > priority) {
                    priority = p
                    if (icons[m.SEVERITY]) icon = ' '+icons[m.SEVERITY]
                }
            })

            console.log('type icon', this.get('TYPE')+icon)
            this.set({
                ICON: icon,
                'TYPEICON': this.get('TYPE')+icon
            })
        },
    })

})
<commit_msg>Handle the case where autoprocessing claims success but without shells<commit_after>define(['backbone'], function(Backbone){

    return Backbone.Model.extend({
        idAttribute: 'AID',

        initialize: function(options) {
            this.addClasses()
            this.addIcon()
        },

        addClasses: function() {
            if (this.get('PROCESSINGSTATUS') == '0') return
            var shells = this.get('SHELLS')
            if (!shells) return

            this.attributes.CLASS = { RMERGE: {}, RMEAS: {}, COMPLETENESS: {} }
            _.each(['overall', 'innerShell', 'outerShell'], function(k) {
                var c = shells[k] ? shells[k].COMPLETENESS : null
                this.attributes.CLASS.COMPLETENESS[k] = c > 95 ? 'active' : (c > 80 ? 'minor' : 'inactive')

                var r = shells[k] ? shells[k].RMEAS : null
                this.attributes.CLASS.RMEAS[k] = r < 0.5 ? 'active' : (r < 0.6 ? 'minor' : 'inactive')
            }, this)
        },

        addIcon: function() {
            var icons = {
                ERROR: '',
                WARNING: ''
            }
            var priorities = ['WARNING', 'ERROR']

            var priority = -1
            var icon = ''
            _.each(this.get('MESSAGES'), function(m) {
                var p = priorities.indexOf(m.SEVERITY)
                if (p > priority) {
                    priority = p
                    if (icons[m.SEVERITY]) icon = ' '+icons[m.SEVERITY]
                }
            })

            console.log('type icon', this.get('TYPE')+icon)
            this.set({
                ICON: icon,
                'TYPEICON': this.get('TYPE')+icon
            })
        },
    })

})
<|endoftext|>


<commit_before>import { find } from "lodash-es";
import PropTypes from "prop-types";
import React from "react";
import { connect } from "react-redux";
import { Button, Modal, ModalBody, ModalFooter, ModalHeader } from "../../../../base";
import SegmentForm from "./Form";

const getInitialState = () => ({
    newEntry: {
        name: "",
        molecule: "",
        required: true,
        showError: false,
        nameTaken: false
    }
});

class Add extends React.Component {
    constructor(props) {
        super(props);
        this.state = getInitialState();
    }

    handleChange = entry => {
        this.setState({
            newEntry: {
                name: entry.name,
                molecule: entry.molecule,
                required: entry.required
            }
        });
    };

    handleSubmit = e => {
        e.preventDefault();

        const checkName = find(this.props.schema, ["name", this.state.newEntry.name]);

        if (checkName) {
            this.setState({ newEntry: { ...this.state.newEntry, nameTaken: true } });
        } else if (this.state.newEntry.name) {
            this.setState({ newEntry: { ...this.state.newEntry, nameTaken: false } });
            this.props.onSubmit([...this.props.schema, this.state.newEntry]);
        } else {
            this.setState({
                newEntry: { ...this.state.newEntry, showError: true, nameTaken: false }
            });
        }
    };

    handleExited = () => {
        this.setState(getInitialState());
    };

    render() {
        return (
            <Modal label="Add Segment" show={this.props.show} onExited={this.handleExited} onHide={this.props.onHide}>
                <ModalHeader>Add Segment</ModalHeader>
                <form onSubmit={this.handleSubmit}>
                    <ModalBody>
                        <SegmentForm onChange={this.handleChange} newEntry={this.state.newEntry} />
                    </ModalBody>
                    <ModalFooter>
                        <Button color="blue" type="submit">
                            Save
                        </Button>
                    </ModalFooter>
                </form>
            </Modal>
        );
    }
}

Add.propTypes = {
    schema: PropTypes.arrayOf(PropTypes.object),
    show: PropTypes.bool.isRequired,
    onHide: PropTypes.func,
    onSubmit: PropTypes.func
};

const mapStateToProps = state => ({
    schema: state.otus.detail.schema ? state.otus.detail.schema : []
});

export default connect(mapStateToProps)(Add);
<commit_msg>Add icon to button in add segment dialog<commit_after>import { find } from "lodash-es";
import PropTypes from "prop-types";
import React from "react";
import { connect } from "react-redux";
import { Modal, ModalBody, ModalFooter, ModalHeader, SaveButton } from "../../../../base";
import SegmentForm from "./Form";

const getInitialState = () => ({
    newEntry: {
        name: "",
        molecule: "",
        required: true,
        showError: false,
        nameTaken: false
    }
});

class Add extends React.Component {
    constructor(props) {
        super(props);
        this.state = getInitialState();
    }

    handleChange = entry => {
        this.setState({
            newEntry: {
                name: entry.name,
                molecule: entry.molecule,
                required: entry.required
            }
        });
    };

    handleSubmit = e => {
        e.preventDefault();

        const checkName = find(this.props.schema, ["name", this.state.newEntry.name]);

        if (checkName) {
            this.setState({ newEntry: { ...this.state.newEntry, nameTaken: true } });
        } else if (this.state.newEntry.name) {
            this.setState({ newEntry: { ...this.state.newEntry, nameTaken: false } });
            this.props.onSubmit([...this.props.schema, this.state.newEntry]);
        } else {
            this.setState({
                newEntry: { ...this.state.newEntry, showError: true, nameTaken: false }
            });
        }
    };

    handleExited = () => {
        this.setState(getInitialState());
    };

    render() {
        return (
            <Modal label="Add Segment" show={this.props.show} onExited={this.handleExited} onHide={this.props.onHide}>
                <ModalHeader>Add Segment</ModalHeader>
                <form onSubmit={this.handleSubmit}>
                    <ModalBody>
                        <SegmentForm onChange={this.handleChange} newEntry={this.state.newEntry} />
                    </ModalBody>
                    <ModalFooter>
                        <SaveButton />
                    </ModalFooter>
                </form>
            </Modal>
        );
    }
}

Add.propTypes = {
    schema: PropTypes.arrayOf(PropTypes.object),
    show: PropTypes.bool.isRequired,
    onHide: PropTypes.func,
    onSubmit: PropTypes.func
};

const mapStateToProps = state => ({
    schema: state.otus.detail.schema ? state.otus.detail.schema : []
});

export default connect(mapStateToProps)(Add);
<|endoftext|>


<commit_before>var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');

module.exports = {
    development: {
        rootPath: rootPath,
        db: 'mongodb://localhost/test', // switch this out for db....
        port: process.env.PORT || 3030
    },
    production: {
        rootPath: rootPath,
        db: 'mongodb://username:password@ds013619.mlab.com:13619/test', // switch this out for remote db....
        port: process.env.PORT || 80
    }
}
<commit_msg>mongodb config.<commit_after>var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');

module.exports = {
    development: {
        rootPath: rootPath,
        db: 'mongodb://localhost/portfoliodb', // switch this out for db....
        port: process.env.PORT || 3030
    },
    production: {
        rootPath: rootPath,
        db: 'mongodb://<username>:<password>@ds013619.mlab.com:13619/<dbname>', // switch this out for remote db....
        port: process.env.PORT || 80
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50,  */
/*global brackets, require, define, Mustache, $, setInterval */

define(function (require, exports, module) {
    "use strict";

    // Brackets modules
    var DocumentManager     = brackets.getModule("document/DocumentManager"),
        LanguageManager     = brackets.getModule("language/LanguageManager"),
        ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
        NodeConnection      = brackets.getModule("utils/NodeConnection"),
        ProjectManager      = brackets.getModule("project/ProjectManager");

    var inspectHtml         = require("text!htmlContent/inspect.html"),
        SkyLabController    = require("lib/inspect/skylab").SkyLabController,
        SkyLabPopup         = require("lib/inspect/skylabpopup"),
        SkyLabView          = require("lib/inspect/skylabview"),
        Strings             = require("strings");

    var $inspect,
        $inspectPopoverArrow,
        inspectEnabled = false,
        inspectShown = false,
        projectRoot,
        serverAddress,
        currentURL = null,
        nodeConnection = new NodeConnection(),
        inspectPromise;

    function inspectEvent(event) {
        var EVENT_NAMESPACE = ".edge-code-inspect";

        if (event === undefined) {
            return EVENT_NAMESPACE;
        } else if (arguments.length > 1) {
            return Array.prototype.slice
                .call(arguments)
                .map(function (elem) {
                    return inspectEvent(elem);
                })
                .join(" ");
        } else if (typeof event === "string") {
            return event + EVENT_NAMESPACE;
        }
    }

    function refreshCurrentURL() {
        if (currentURL) {
            console.log("Refreshing URL: " + currentURL);
            SkyLabController.followUrl(currentURL, "false");
        }
    }

    function updateCurrentURL() {
        var document = DocumentManager.getCurrentDocument();

        if (document && document.file) {
            var fullPath    = document.file.fullPath,
                language    = LanguageManager.getLanguageForPath(fullPath),
                rootIndex   = fullPath.indexOf(projectRoot),
                relativePath;

            if (rootIndex === 0) {
                if (language.getId() === "html") {
                    relativePath = fullPath.substring(projectRoot.length - 1,
                                                      fullPath.length);
                    relativePath = encodeURIComponent(relativePath);
                    relativePath = relativePath.replace(/%2F/g, "/");
                    currentURL = "http://" + serverAddress.address + ":" +
                        serverAddress.port + relativePath;

                    console.log("New URL: " + currentURL);
                    return true;
                }
            } else {
                throw new Error("Document root does not match project root",
                                projectRoot,
                                fullPath);
            }
        }
        return false;
    }

    function connectToNode() {
        console.log("Connecting to node...");
        if (nodeConnection.connected()) {
            return $.Deferred().resolve().promise();
        } else {
            return nodeConnection.connect(true);
        }
    }

    function loadDomains() {
        console.log("Loading domains...");
        if (nodeConnection.connected()) {
            var modulePath = ExtensionUtils.getModulePath(module, "node/InspectHTTPDomain");
            return nodeConnection.loadDomains([modulePath], true);
        } else {
            return $.Deferred().reject().promise();
        }
    }

    function openHTTPServer(root) {
        console.log("Opening server connection...");
        if (nodeConnection.connected()) {
            return nodeConnection.domains.inspectHttpServer.getServer(root);
        } else {
            return $.Deferred().reject().promise();
        }
    }

    function closeHTTPServer(root) {
        console.log("Closing server connection...");
        if (nodeConnection.connected()) {
            return nodeConnection.domains.inspectHttpServer.closeServer(root);
        } else {
            return $.Deferred().reject().promise();
        }
    }

    function stopServer(root) {
        var deferred = $.Deferred();

        connectToNode().done(function () {
            loadDomains().done(function () {
                closeHTTPServer(root).done(function () {
                    console.log("Closed connection");
                    serverAddress = null;
                    deferred.resolve();
                }).fail(function () {
                    deferred.reject();
                });
            }).fail(function () {
                deferred.reject();
            });
        }).fail(function () {
            deferred.reject();
        });

        return deferred.promise();
    }

    function startServer(root) {
        var deferred = $.Deferred();

        connectToNode().done(function () {
            loadDomains().done(function () {
                openHTTPServer(root).done(function (address) {
                    console.log("Opened connection: " + JSON.stringify(address));
                    serverAddress = address;
                    deferred.resolve();
                }).fail(function () {
                    deferred.reject();
                });
            }).fail(function () {
                deferred.reject();
            });
        }).fail(function () {
            deferred.reject();
        });

        return deferred.promise();
    }

    function stopInspect(root) {
        var deferred = $.Deferred();

        inspectEnabled = false;
        currentURL = null;

        $(nodeConnection).off(inspectEvent());

        inspectPromise.done(function () {
            stopServer(root).done(function () {
                deferred.resolve();
            });
        }).fail(function () {
            inspectEnabled = true;
            deferred.reject();
            console.log("Failed to disable Inspect");
        });

        return deferred.promise();
    }

    function startInspect(root) {
        inspectEnabled = true;
        return startServer(projectRoot).done(function () {
            if (updateCurrentURL()) {
                refreshCurrentURL();
            }

            $(nodeConnection).on(inspectEvent("base.newDomains"), function () {
                console.log("New domains!");
                if (inspectEnabled) {
                    stopInspect(projectRoot);
                    inspectPromise = startInspect(projectRoot);
                }
            });

        }).fail(function () {
            inspectEnabled = false;
            console.log("Failed to enable Inspect");
        });
    }

    function onFollowToggle() {
        var $toolbarIcon = $("#inspect-toolbar");

        if (SkyLabPopup.getFollowState() === "on") {
            if (!inspectEnabled) {
                projectRoot = ProjectManager.getProjectRoot().fullPath;
                inspectPromise = startInspect(projectRoot);
                inspectPromise.done(function () {
                    $(ProjectManager)
                        .on(inspectEvent("beforeProjectClose", "beforeAppClose"), function () {
                            console.log("Changing project...");
                            if (inspectEnabled) {
                                stopInspect(projectRoot);
                                projectRoot = null;
                            }
                        })
                        .on(inspectEvent("projectOpen"), function (event, newProjectRoot) {
                            if (!inspectEnabled) {
                                projectRoot = newProjectRoot.fullPath;
                                console.log("New project: " + projectRoot);
                                inspectPromise = startInspect(projectRoot);
                            }
                        });

                    $(DocumentManager)
                        .on(inspectEvent("documentSaved"), refreshCurrentURL)
                        .on(inspectEvent("currentDocumentChange"), function () {
                            inspectPromise.done(function () {
                                if (updateCurrentURL()) {
                                    refreshCurrentURL();
                                }
                            });
                        });

                    $toolbarIcon.addClass("active");
                }).fail(function () {
                    inspectEnabled = false;
                });
            } else {
                console.log("Toggle state switched on but Inspect is enabled");
            }
        } else {
            if (inspectEnabled) {
                stopInspect(projectRoot).done(function () {
                    $(ProjectManager).off(inspectEvent());
                    $(DocumentManager).off(inspectEvent());
                    $toolbarIcon.addClass("active");
                });
            } else {
                console.log("Toggle state switched off but Inspect is disabled");
            }
        }
    }

    function hideControls() {
        $("#inspect, .inspectPopoverArrow").fadeOut(50, function () {
            $inspect.css("display", "");
            $inspect.removeClass("visible");
            $inspectPopoverArrow.css("display", "");
            $inspectPopoverArrow.removeClass("visible");
        });

        $(".content, .sidebar")
            .off(inspectEvent());
        inspectShown = false;
    }

    function showControls() {
        var $toolbarIcon    = $("#inspect-toolbar"),
            iconOffset      = $toolbarIcon.offset().top,
            inspectTop      = iconOffset - 20,
            arrowTop        = inspectTop + 22;

        $inspect.css("top", inspectTop);
        $inspectPopoverArrow.css("top", arrowTop);
        $inspect.addClass("visible");
        $inspectPopoverArrow.addClass("visible");

        $(".content, .sidebar")
            .on(inspectEvent("mousedown", "keyup"), hideControls);
        inspectShown = true;
    }

    function handleInspectControls() {
        if (inspectShown) {
            hideControls();
        } else {
            showControls();
        }
    }

    function init() {
        var $mainContent = Mustache.render(inspectHtml, Strings);
        $("body").append($mainContent);

        $inspect = $("#inspect");
        $inspectPopoverArrow = $(".inspectPopoverArrow");
        $inspect.on("Inspect:followtoggle", onFollowToggle);

        SkyLabView.initialize();
        SkyLabPopup.initInspect($inspect, Strings);
        SkyLabPopup.startListening();

        return nodeConnection.connect(true);
    }

    exports.init = init;
    exports.handleInspectControls = handleInspectControls;
});<commit_msg>Only query the document language if the project root matches the document root.<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50,  */
/*global brackets, require, define, Mustache, $, setInterval */

define(function (require, exports, module) {
    "use strict";

    // Brackets modules
    var DocumentManager     = brackets.getModule("document/DocumentManager"),
        LanguageManager     = brackets.getModule("language/LanguageManager"),
        ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
        NodeConnection      = brackets.getModule("utils/NodeConnection"),
        ProjectManager      = brackets.getModule("project/ProjectManager");

    var inspectHtml         = require("text!htmlContent/inspect.html"),
        SkyLabController    = require("lib/inspect/skylab").SkyLabController,
        SkyLabPopup         = require("lib/inspect/skylabpopup"),
        SkyLabView          = require("lib/inspect/skylabview"),
        Strings             = require("strings");

    var $inspect,
        $inspectPopoverArrow,
        inspectEnabled = false,
        inspectShown = false,
        projectRoot,
        serverAddress,
        currentURL = null,
        nodeConnection = new NodeConnection(),
        inspectPromise;

    function inspectEvent(event) {
        var EVENT_NAMESPACE = ".edge-code-inspect";

        if (event === undefined) {
            return EVENT_NAMESPACE;
        } else if (arguments.length > 1) {
            return Array.prototype.slice
                .call(arguments)
                .map(function (elem) {
                    return inspectEvent(elem);
                })
                .join(" ");
        } else if (typeof event === "string") {
            return event + EVENT_NAMESPACE;
        }
    }

    function refreshCurrentURL() {
        if (currentURL) {
            console.log("Refreshing URL: " + currentURL);
            SkyLabController.followUrl(currentURL, "false");
        }
    }

    function updateCurrentURL() {
        var document = DocumentManager.getCurrentDocument();

        if (document && document.file) {
            var fullPath    = document.file.fullPath,
                rootIndex   = fullPath.indexOf(projectRoot),
                relativePath;

            if (rootIndex === 0) {
                var language = LanguageManager.getLanguageForPath(fullPath);

                if (language.getId() === "html") {
                    relativePath = fullPath.substring(projectRoot.length - 1,
                                                      fullPath.length);
                    relativePath = encodeURIComponent(relativePath);
                    relativePath = relativePath.replace(/%2F/g, "/");
                    currentURL = "http://" + serverAddress.address + ":" +
                        serverAddress.port + relativePath;

                    console.log("New URL: " + currentURL);
                    return true;
                }
            } else {
                throw new Error("Document root does not match project root",
                                projectRoot,
                                fullPath);
            }
        }
        return false;
    }

    function connectToNode() {
        console.log("Connecting to node...");
        if (nodeConnection.connected()) {
            return $.Deferred().resolve().promise();
        } else {
            return nodeConnection.connect(true);
        }
    }

    function loadDomains() {
        console.log("Loading domains...");
        if (nodeConnection.connected()) {
            var modulePath = ExtensionUtils.getModulePath(module, "node/InspectHTTPDomain");
            return nodeConnection.loadDomains([modulePath], true);
        } else {
            return $.Deferred().reject().promise();
        }
    }

    function openHTTPServer(root) {
        console.log("Opening server connection...");
        if (nodeConnection.connected()) {
            return nodeConnection.domains.inspectHttpServer.getServer(root);
        } else {
            return $.Deferred().reject().promise();
        }
    }

    function closeHTTPServer(root) {
        console.log("Closing server connection...");
        if (nodeConnection.connected()) {
            return nodeConnection.domains.inspectHttpServer.closeServer(root);
        } else {
            return $.Deferred().reject().promise();
        }
    }

    function stopServer(root) {
        var deferred = $.Deferred();

        connectToNode().done(function () {
            loadDomains().done(function () {
                closeHTTPServer(root).done(function () {
                    console.log("Closed connection");
                    serverAddress = null;
                    deferred.resolve();
                }).fail(function () {
                    deferred.reject();
                });
            }).fail(function () {
                deferred.reject();
            });
        }).fail(function () {
            deferred.reject();
        });

        return deferred.promise();
    }

    function startServer(root) {
        var deferred = $.Deferred();

        connectToNode().done(function () {
            loadDomains().done(function () {
                openHTTPServer(root).done(function (address) {
                    console.log("Opened connection: " + JSON.stringify(address));
                    serverAddress = address;
                    deferred.resolve();
                }).fail(function () {
                    deferred.reject();
                });
            }).fail(function () {
                deferred.reject();
            });
        }).fail(function () {
            deferred.reject();
        });

        return deferred.promise();
    }

    function stopInspect(root) {
        var deferred = $.Deferred();

        inspectEnabled = false;
        currentURL = null;

        $(nodeConnection).off(inspectEvent());

        inspectPromise.done(function () {
            stopServer(root).done(function () {
                deferred.resolve();
            });
        }).fail(function () {
            inspectEnabled = true;
            deferred.reject();
            console.log("Failed to disable Inspect");
        });

        return deferred.promise();
    }

    function startInspect(root) {
        inspectEnabled = true;
        return startServer(projectRoot).done(function () {
            if (updateCurrentURL()) {
                refreshCurrentURL();
            }

            $(nodeConnection).on(inspectEvent("base.newDomains"), function () {
                console.log("New domains!");
                if (inspectEnabled) {
                    stopInspect(projectRoot);
                    inspectPromise = startInspect(projectRoot);
                }
            });

        }).fail(function () {
            inspectEnabled = false;
            console.log("Failed to enable Inspect");
        });
    }

    function onFollowToggle() {
        var $toolbarIcon = $("#inspect-toolbar");

        if (SkyLabPopup.getFollowState() === "on") {
            if (!inspectEnabled) {
                projectRoot = ProjectManager.getProjectRoot().fullPath;
                inspectPromise = startInspect(projectRoot);
                inspectPromise.done(function () {
                    $(ProjectManager)
                        .on(inspectEvent("beforeProjectClose", "beforeAppClose"), function () {
                            console.log("Changing project...");
                            if (inspectEnabled) {
                                stopInspect(projectRoot);
                                projectRoot = null;
                            }
                        })
                        .on(inspectEvent("projectOpen"), function (event, newProjectRoot) {
                            if (!inspectEnabled) {
                                projectRoot = newProjectRoot.fullPath;
                                console.log("New project: " + projectRoot);
                                inspectPromise = startInspect(projectRoot);
                            }
                        });

                    $(DocumentManager)
                        .on(inspectEvent("documentSaved"), refreshCurrentURL)
                        .on(inspectEvent("currentDocumentChange"), function () {
                            inspectPromise.done(function () {
                                if (updateCurrentURL()) {
                                    refreshCurrentURL();
                                }
                            });
                        });

                    $toolbarIcon.addClass("active");
                }).fail(function () {
                    inspectEnabled = false;
                });
            } else {
                console.log("Toggle state switched on but Inspect is enabled");
            }
        } else {
            if (inspectEnabled) {
                stopInspect(projectRoot).done(function () {
                    $(ProjectManager).off(inspectEvent());
                    $(DocumentManager).off(inspectEvent());
                    $toolbarIcon.addClass("active");
                });
            } else {
                console.log("Toggle state switched off but Inspect is disabled");
            }
        }
    }

    function hideControls() {
        $("#inspect, .inspectPopoverArrow").fadeOut(50, function () {
            $inspect.css("display", "");
            $inspect.removeClass("visible");
            $inspectPopoverArrow.css("display", "");
            $inspectPopoverArrow.removeClass("visible");
        });

        $(".content, .sidebar")
            .off(inspectEvent());
        inspectShown = false;
    }

    function showControls() {
        var $toolbarIcon    = $("#inspect-toolbar"),
            iconOffset      = $toolbarIcon.offset().top,
            inspectTop      = iconOffset - 20,
            arrowTop        = inspectTop + 22;

        $inspect.css("top", inspectTop);
        $inspectPopoverArrow.css("top", arrowTop);
        $inspect.addClass("visible");
        $inspectPopoverArrow.addClass("visible");

        $(".content, .sidebar")
            .on(inspectEvent("mousedown", "keyup"), hideControls);
        inspectShown = true;
    }

    function handleInspectControls() {
        if (inspectShown) {
            hideControls();
        } else {
            showControls();
        }
    }

    function init() {
        var $mainContent = Mustache.render(inspectHtml, Strings);
        $("body").append($mainContent);

        $inspect = $("#inspect");
        $inspectPopoverArrow = $(".inspectPopoverArrow");
        $inspect.on("Inspect:followtoggle", onFollowToggle);

        SkyLabView.initialize();
        SkyLabPopup.initInspect($inspect, Strings);
        SkyLabPopup.startListening();

        return nodeConnection.connect(true);
    }

    exports.init = init;
    exports.handleInspectControls = handleInspectControls;
});<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs  = require('fs'),
    path = require('path'),
    http = require('http'),
    BufferStream = require('bufferstream'),

// http://www.ksu.ru/eng/departments/ktk/test/perl/lib/unicode/UCDFF301.html
keys =  ['value', 'name', 'category', 'class',
    'bidirectional_category', 'mapping', 'decimal_digit_value', 'digit_value',
    'numeric_value', 'mirrored', 'unicode_name', 'comment', 'uppercase_mapping',
    'lowercase_mapping', 'titlecase_mapping'],
systemfiles = [
    "/usr/share/unicode/UnicodeData.txt", // debian
    "/usr/share/unicode-data/UnicodeData.txt", // gentoo
    "UnicodeData.txt", // manually downloaded
],
unicodedatafile = {
    host: "unicode.org",
    path: "/Public/UNIDATA/UnicodeData.txt",
    method: 'GET',
    port:80,
},

counter = 0,

stringFromCharCode = String.fromCharCode,

// Based on http://mths.be/punycode
encode = function (codePoint) {
    var output = '';
    if (codePoint > 0xFFFF) {
        codePoint -= 0x10000;
        output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800);
        codePoint = 0xDC00 | codePoint & 0x3FF;
    }
    output += stringFromCharCode(codePoint);
    return output;
},

save = function (filename, object, callback) {
    var filename = path.join(__dirname, "category", filename);
    var data = "module.exports=" + JSON.stringify(object);
    fs.writeFile(filename, data, 'utf8', function (err) {
        if (err) throw err;
        if (!--counter) console.log("done.");
        callback(!counter);
    });
},

parser = function (callback) {
    var data = {},
        buffer = new BufferStream({encoding:'utf8', size:'flexible'});

    buffer.split('\n', function (line) {
        var v, c, char = {},
            values = line.toString().split(';');
        for(var i = 0 ; i < 15 ; i++)
            char[keys[i]] = values[i];
        v = parseInt(char.value, 16);
        char.symbol = encode(v);
        c = char.category;
        if (!data[c])
            data[c] = {};
        data[c][v] = char;
    });

    buffer.on('end', function () {
        var cat, categories = Object.keys(data),
            len = counter = categories.length;
        for(var i = 0 ; i < len ; i++) {
            cat = categories[i];
            console.log("saving data as %s.js …", cat);
            save(cat + ".js", data[cat], function (done) {
                if (done) callback();
            });
        }
    });

    buffer.on('error', function (err) {
        if (typeof err === 'string')
            err = new Error(err);
        throw err;
    });

    return buffer;
},

read_file = function (success_cb, error_cb) {
    var systemfile, sysfiles = systemfiles.slice(),
    try_reading = function (success, error) {
        systemfile = sysfiles.shift();
        if (!systemfile) return error_cb();
        console.log("try to read file %s …", systemfile);
        fs.exists(systemfile, function (exists) {
            if (!exists) {
                console.error("%s not found.", systemfile);
                return try_reading(success_cb, error_cb);
            }
            console.log("parsing …");
            fs.createReadStream(systemfile, 'utf8').pipe(parser(success_cb));
        });

    };
    try_reading(success_cb, error_cb);
},

download_file = function (callback) {
    console.log("%s %s:%d%s", unicodedatafile.method, unicodedatafile.host,
                unicodedatafile.port, unicodedatafile.path);
    http.get(unicodedatafile, function (res) {
        console.log("fetching …");

        res.setEncoding('utf8');
        res.pipe(parser(callback));
    }).on('error', function (err) {
        console.error("Error while downloading %s: %s",
                      path.basename(unicodedatafile.path), err);
        console.log("Please download file manually,",
                    "put it next to the install.js file and",
                    "run `node install.js` again.");
        callback();
    });
    setTimeout(function () {
        console.error("request timed out.");
        callback();
    }, 30 * 1000);
};

// run

read_file(process.exit, function () {
    console.log("try to download …");
    download_file(process.exit);
});

<commit_msg>dont build up a huge json blob in memory<commit_after>#!/usr/bin/env node

var fs  = require('fs'),
    path = require('path'),
    http = require('http'),
    BufferStream = require('bufferstream'),

// http://www.ksu.ru/eng/departments/ktk/test/perl/lib/unicode/UCDFF301.html
keys =  ['value', 'name', 'category', 'class',
    'bidirectional_category', 'mapping', 'decimal_digit_value', 'digit_value',
    'numeric_value', 'mirrored', 'unicode_name', 'comment', 'uppercase_mapping',
    'lowercase_mapping', 'titlecase_mapping'],
systemfiles = [
    "/usr/share/unicode/UnicodeData.txt", // debian
    "/usr/share/unicode-data/UnicodeData.txt", // gentoo
    "UnicodeData.txt", // manually downloaded
],
unicodedatafile = {
    host: "unicode.org",
    path: "/Public/UNIDATA/UnicodeData.txt",
    method: 'GET',
    port:80,
},

refs = 0,

stringFromCharCode = String.fromCharCode,

// Based on http://mths.be/punycode
encode = function (codePoint) {
    var output = '';
    if (codePoint > 0xFFFF) {
        codePoint -= 0x10000;
        output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800);
        codePoint = 0xDC00 | codePoint & 0x3FF;
    }
    output += stringFromCharCode(codePoint);
    return output;
},

stringify = function (key, value) {
    var data = {};
    data[key] = value;
    return JSON.stringify(data).replace(/^{(.*)}$/, "$1");
},

newFile = function (name, callback) {
    var filename = path.join(__dirname, "category", name + ".js"),
        file = fs.createWriteStream(filename, 'utf8');
    file.once('close', function () {
        if (!--refs) {
            console.log("done.");
            callback();
        }
    });
    refs++;
    return file;
},

parser = function (callback) {
    var data = {},
        buffer = new BufferStream({encoding:'utf8', size:'flexible'}),
        resume = buffer.resume.bind(buffer);

    buffer.split('\n', function (line) {
        var v, c, char = {},
            values = line.toString().split(';');
        for(var i = 0 ; i < 15 ; i++)
            char[keys[i]] = values[i];
        v = parseInt(char.value, 16);
        char.symbol = encode(v);
        c = char.category;
        if (!data[c]) {
            data[c] = newFile(c, callback)
                .on('drain', resume)
                .once('open', function () {
                    console.log("saving data as %s.js …", c);
                    this.write('module.exports={' + stringify(v, char));
                    buffer.resume();
                });
            buffer.pause();
        } else if (!data[c].write("," + stringify(v, char))) {
            buffer.pause();
        }
    });

    buffer.on('end', function () {
        var cat, categories = Object.keys(data),
            len = categories.length;
        for(var i = 0 ; i < len ; i++) {
            cat = categories[i];
            data[cat].end("};");
        }
    });

    buffer.on('error', function (err) {
        if (typeof err === 'string')
            err = new Error(err);
        throw err;
    });

    return buffer;
},

read_file = function (success_cb, error_cb) {
    var systemfile, sysfiles = systemfiles.slice(),
    try_reading = function (success, error) {
        systemfile = sysfiles.shift();
        if (!systemfile) return error_cb();
        console.log("try to read file %s …", systemfile);
        fs.exists(systemfile, function (exists) {
            if (!exists) {
                console.error("%s not found.", systemfile);
                return try_reading(success_cb, error_cb);
            }
            console.log("parsing …");
            fs.createReadStream(systemfile, 'utf8').pipe(parser(success_cb));
        });

    };
    try_reading(success_cb, error_cb);
},

download_file = function (callback) {
    console.log("%s %s:%d%s", unicodedatafile.method, unicodedatafile.host,
                unicodedatafile.port, unicodedatafile.path);
    http.get(unicodedatafile, function (res) {
        console.log("fetching …");

        res.setEncoding('utf8');
        res.pipe(parser(callback));
    }).on('error', function (err) {
        console.error("Error while downloading %s: %s",
                      path.basename(unicodedatafile.path), err);
        console.log("Please download file manually,",
                    "put it next to the install.js file and",
                    "run `node install.js` again.");
        callback();
    });
    setTimeout(function () {
        console.error("request timed out.");
        callback();
    }, 30 * 1000);
};

// run

read_file(process.exit, function () {
    console.log("try to download …");
    download_file(process.exit);
});

<|endoftext|>


<commit_before>function FindProxyForURL(url, host) {
  if(isInNet(host, "203.104.209.71", "255.255.255.255") ||
     isInNet(host, "125.6.184.15", "255.255.255.255") ||
     isInNet(host, "125.6.184.16", "255.255.255.255") ||
     isInNet(host, "125.6.187.205", "255.255.255.255") ||
     isInNet(host, "125.6.187.229", "255.255.255.255") ||
     isInNet(host, "125.6.187.253", "255.255.255.255") ||
     isInNet(host, "125.6.188.25", "255.255.255.255") ||
     isInNet(host, "203.104.248.135", "255.255.255.255") ||
     isInNet(host, "125.6.189.7", "255.255.255.255") ||
     isInNet(host, "125.6.189.39", "255.255.255.255") ||
     isInNet(host, "125.6.189.71", "255.255.255.255") ||
     isInNet(host, "125.6.189.103", "255.255.255.255") ||
     isInNet(host, "125.6.189.135", "255.255.255.255") ||
     isInNet(host, "125.6.189.167", "255.255.255.255") ||
     isInNet(host, "125.6.189.215", "255.255.255.255") ||
     isInNet(host, "125.6.189.247", "255.255.255.255") ||
     isInNet(host, "203.104.209.23", "255.255.255.255") ||
     isInNet(host, "203.104.209.39", "255.255.255.255")) {
       return "PROXY localhost:8080";
    }
  else {
    return "DIRECT";
  }
}
<commit_msg>Fix proxy.pac<commit_after>function FindProxyForURL(url, host) {
  if(isInNet(host, "203.104.209.71", "255.255.255.255") ||
     isInNet(host, "125.6.184.15", "255.255.255.255") ||
     isInNet(host, "125.6.184.16", "255.255.255.255") ||
     isInNet(host, "125.6.187.205", "255.255.255.255") ||
     isInNet(host, "125.6.187.229", "255.255.255.255") ||
     isInNet(host, "125.6.187.253", "255.255.255.255") ||
     isInNet(host, "125.6.188.25", "255.255.255.255") ||
     isInNet(host, "203.104.248.135", "255.255.255.255") ||
     isInNet(host, "125.6.189.7", "255.255.255.255") ||
     isInNet(host, "125.6.189.39", "255.255.255.255") ||
     isInNet(host, "125.6.189.71", "255.255.255.255") ||
     isInNet(host, "125.6.189.103", "255.255.255.255") ||
     isInNet(host, "125.6.189.135", "255.255.255.255") ||
     isInNet(host, "125.6.189.167", "255.255.255.255") ||
     isInNet(host, "125.6.189.215", "255.255.255.255") ||
     isInNet(host, "125.6.189.247", "255.255.255.255") ||
     isInNet(host, "203.104.209.23", "255.255.255.255") ||
     isInNet(host, "203.104.209.39", "255.255.255.255") ||
     isInNet(host, "203.104.209.55", "255.255.255.255")) {
       return "PROXY localhost:8080";
    }
  else {
    return "DIRECT";
  }
}
<|endoftext|>


<commit_before>'use strict';

function createSwitchGitDecoder (lib, Node) {
  'use strict';
  if (!Node) {
    console.trace();
    process.exit(1);
  }

  var q = lib.q,
    Git = require('allex_githelperssdklib')(lib);

  function decode (target) {
    if (target.substring(target.length-4) === '.git') {
      var name = git.getRepoName(target);
      //it's a pure git repo ...
      return q({
        modulename: name,
        gitclonestring: target,
        rtarget: Node.Path.join('node_modules', name)
      });
    }
    return lib.moduleRecognition(target).then(nodemodulizer);
  }

  function nodemodulizer (r) {
    if (r && r.modulename) {
      r.rtarget = Node.Path.join('node_modules', r.modulename);
      return q(r);
    }
    return q(null);
  }

  return decode;
}

module.exports = createSwitchGitDecoder;
<commit_msg>typo fixed<commit_after>'use strict';

function createSwitchGitDecoder (lib, Node) {
  'use strict';
  if (!Node) {
    console.trace();
    process.exit(1);
  }

  var q = lib.q,
    Git = require('allex_githelperssdklib')(lib);

  function decode (target) {
    if (target.substring(target.length-4) === '.git') {
      var name = Git.getRepoName(target);
      //it's a pure git repo ...
      return q({
        modulename: name,
        gitclonestring: target,
        rtarget: Node.Path.join('node_modules', name)
      });
    }
    return lib.moduleRecognition(target).then(nodemodulizer);
  }

  function nodemodulizer (r) {
    if (r && r.modulename) {
      r.rtarget = Node.Path.join('node_modules', r.modulename);
      return q(r);
    }
    return q(null);
  }

  return decode;
}

module.exports = createSwitchGitDecoder;
<|endoftext|>