<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

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

var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextMode = require("./text").Mode;
var JavaScriptMode = require("./javascript").Mode;
var CssMode = require("./css").Mode;
var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var HtmlFoldMode = require("./folding/html").FoldMode;
var HtmlCompletions = require("./html_completions").HtmlCompletions;
var WorkerClient = require("../worker/worker_client").WorkerClient;

// http://www.w3.org/TR/html5/syntax.html#void-elements
var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"];
var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"];

var Mode = function(options) {
    this.fragmentContext = options && options.fragmentContext;
    this.HighlightRules = HtmlHighlightRules;
    this.$behaviour = new XmlBehaviour();
    this.$completer = new HtmlCompletions();

    this.createModeDelegates({
        "js-": JavaScriptMode,
        "css-": CssMode
    });

    this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags));
};
oop.inherits(Mode, TextMode);

(function() {

    this.blockComment = {start: "<!--", end: "-->"};

    this.voidElements = lang.arrayToMap(voidElements);

    this.getNextLineIndent = function(state, line, tab) {
        return this.$getIndent(line);
    };

    this.checkOutdent = function(state, line, input) {
        return false;
    };

    this.getCompletions = function(state, session, pos, prefix) {
        return this.$completer.getCompletions(state, session, pos, prefix);
    };

    this.createWorker = function(session) {
        if (this.constructor != Mode)
            return;
        var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker");
        worker.attachToDocument(session.getDocument());

        if (this.fragmentContext)
            worker.call("setOptions", [{context: this.fragmentContext}]);

        worker.on("error", function(e) {
            session.setAnnotations(e.data);
        });

        worker.on("terminate", function() {
            session.clearAnnotations();
        });

        return worker;
    };

    this.$id = "ace/mode/html";
}).call(Mode.prototype);

exports.Mode = Mode;
});
<commit_msg>add menuitem to the list of void tags<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

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

var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextMode = require("./text").Mode;
var JavaScriptMode = require("./javascript").Mode;
var CssMode = require("./css").Mode;
var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var HtmlFoldMode = require("./folding/html").FoldMode;
var HtmlCompletions = require("./html_completions").HtmlCompletions;
var WorkerClient = require("../worker/worker_client").WorkerClient;

// http://www.w3.org/TR/html5/syntax.html#void-elements
var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"];
var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"];

var Mode = function(options) {
    this.fragmentContext = options && options.fragmentContext;
    this.HighlightRules = HtmlHighlightRules;
    this.$behaviour = new XmlBehaviour();
    this.$completer = new HtmlCompletions();

    this.createModeDelegates({
        "js-": JavaScriptMode,
        "css-": CssMode
    });

    this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags));
};
oop.inherits(Mode, TextMode);

(function() {

    this.blockComment = {start: "<!--", end: "-->"};

    this.voidElements = lang.arrayToMap(voidElements);

    this.getNextLineIndent = function(state, line, tab) {
        return this.$getIndent(line);
    };

    this.checkOutdent = function(state, line, input) {
        return false;
    };

    this.getCompletions = function(state, session, pos, prefix) {
        return this.$completer.getCompletions(state, session, pos, prefix);
    };

    this.createWorker = function(session) {
        if (this.constructor != Mode)
            return;
        var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker");
        worker.attachToDocument(session.getDocument());

        if (this.fragmentContext)
            worker.call("setOptions", [{context: this.fragmentContext}]);

        worker.on("error", function(e) {
            session.setAnnotations(e.data);
        });

        worker.on("terminate", function() {
            session.clearAnnotations();
        });

        return worker;
    };

    this.$id = "ace/mode/html";
}).call(Mode.prototype);

exports.Mode = Mode;
});
<|endoftext|>


<commit_before>var _ = require('underscore');
var uuid = require('./utils/uuid');
var Diagnostics = require('./diagnostics');
var StatusConstants = require('../constants/status');

function ActionPayload(options) {
  options || (options = {});

  var rollbackHandlers = [];
  var status = StatusConstants.PENDING;
  var handlers = options.handlers || [];

  _.extend(this, options);

  this.id = options.id || uuid.small();
  this.type = actionType(options.type);
  this.arguments = _.toArray(options.arguments);

  this.error = null;
  this.toJSON = toJSON;
  this.toString = toString;
  this.rollback = rollback;
  this.internal = !!options.internal;
  this.addViewHandler = addViewHandler;
  this.addStoreHandler = addStoreHandler;
  this.addRollbackHandler = addRollbackHandler;
  this.timestamp = options.timestamp || new Date();

  Object.defineProperty(this, 'handlers', {
    get: function () {
      return handlers;
    }
  });

  Object.defineProperty(this, 'status', {
    get: function () {
      return status;
    }
  });

  Object.defineProperty(this, 'pending', {
    get: function () {
      return status === StatusConstants.PENDING;
    }
  });

  Object.defineProperty(this, 'failed', {
    get: function () {
      return status === StatusConstants.FAILED;
    }
  });

  Object.defineProperty(this, 'done', {
    get: function () {
      return status === StatusConstants.DONE;
    }
  });

  function actionType(type) {
    if (_.isFunction(type)) {
      return type.toString();
    }

    return type;
  }

  function toString() {
    return JSON.stringify(this.toJSON(), null, 2);
  }

  function toJSON() {
    var json = _.pick(this,
      'id',
      'type',
      'error',
      'source',
      'creator',
      'internal',
      'handlers',
      'arguments',
      'timestamp'
    );

    json.status = this.status.toString();

    return json;
  }

  function rollback() {
    _.each(rollbackHandlers, function (rollback) {
      rollback(this.error);
    }, this);
  }

  function addViewHandler(name, view) {
    var storeHandler = handlers[handlers.length - 1];

    var viewHandler = {
      name: name,
      error: null,
      id: uuid.small(),
    };

    storeHandler.views.push(viewHandler);

    return {
      dispose: function () {
        if (Diagnostics.devtoolsEnabled) {
          viewHandler.state = view.state;
        }
      },
      failed: function (err) {
        viewHandler.error = err;
      }
    };
  }

  function addStoreHandler(store, handlerName) {
    var handler = {
      views: [],
      error: null,
      type: 'Store',
      id: uuid.small(),
      name: handlerName,
      store: store.displayName,
    };

    handlers.push(handler);

    return {
      dispose: function () {
        if (Diagnostics.devtoolsEnabled) {
          handler.state = (store.serialize || store.getState)();
        }
      },
      failed: function (err) {
        handler.error = err;
      }
    };
  }

  function addRollbackHandler(rollbackHandler, context) {
    if (_.isFunction(rollbackHandler)) {
      if (context) {
        rollbackHandler = _.bind(rollbackHandler, context);
      }

      rollbackHandlers.push(rollbackHandler);
    }
  }
}

module.exports = ActionPayload;<commit_msg>Serializing state to JSON. Fixes #109<commit_after>var _ = require('underscore');
var uuid = require('./utils/uuid');
var Diagnostics = require('./diagnostics');
var StatusConstants = require('../constants/status');

function ActionPayload(options) {
  options || (options = {});

  var rollbackHandlers = [];
  var status = StatusConstants.PENDING;
  var handlers = options.handlers || [];

  _.extend(this, options);

  this.id = options.id || uuid.small();
  this.type = actionType(options.type);
  this.arguments = _.toArray(options.arguments);

  this.error = null;
  this.toJSON = toJSON;
  this.toString = toString;
  this.rollback = rollback;
  this.internal = !!options.internal;
  this.addViewHandler = addViewHandler;
  this.addStoreHandler = addStoreHandler;
  this.addRollbackHandler = addRollbackHandler;
  this.timestamp = options.timestamp || new Date();

  Object.defineProperty(this, 'handlers', {
    get: function () {
      return handlers;
    }
  });

  Object.defineProperty(this, 'status', {
    get: function () {
      return status;
    }
  });

  Object.defineProperty(this, 'pending', {
    get: function () {
      return status === StatusConstants.PENDING;
    }
  });

  Object.defineProperty(this, 'failed', {
    get: function () {
      return status === StatusConstants.FAILED;
    }
  });

  Object.defineProperty(this, 'done', {
    get: function () {
      return status === StatusConstants.DONE;
    }
  });

  function actionType(type) {
    if (_.isFunction(type)) {
      return type.toString();
    }

    return type;
  }

  function toString() {
    return JSON.stringify(this.toJSON(), null, 2);
  }

  function toJSON() {
    var json = _.pick(this,
      'id',
      'type',
      'error',
      'source',
      'creator',
      'internal',
      'handlers',
      'arguments',
      'timestamp'
    );

    json.status = this.status.toString();

    return json;
  }

  function rollback() {
    _.each(rollbackHandlers, function (rollback) {
      rollback(this.error);
    }, this);
  }

  function addViewHandler(name, view) {
    var storeHandler = handlers[handlers.length - 1];

    var viewHandler = {
      name: name,
      error: null,
      id: uuid.small(),
    };

    storeHandler.views.push(viewHandler);

    return {
      dispose: function () {
        if (Diagnostics.devtoolsEnabled) {
          var state = view.state;
          if (state) {
            viewHandler.state = JSON.parse(JSON.stringify(state));
          }
        }
      },
      failed: function (err) {
        viewHandler.error = err;
      }
    };
  }

  function addStoreHandler(store, handlerName) {
    var handler = {
      views: [],
      error: null,
      type: 'Store',
      id: uuid.small(),
      name: handlerName,
      store: store.displayName,
    };

    handlers.push(handler);

    return {
      dispose: function () {
        if (Diagnostics.devtoolsEnabled) {
          var state = (store.serialize || store.getState)();

          if (state) {
            handler.state = JSON.parse(JSON.stringify(state));
          }
        }
      },
      failed: function (err) {
        handler.error = err;
      }
    };
  }

  function addRollbackHandler(rollbackHandler, context) {
    if (_.isFunction(rollbackHandler)) {
      if (context) {
        rollbackHandler = _.bind(rollbackHandler, context);
      }

      rollbackHandlers.push(rollbackHandler);
    }
  }
}

module.exports = ActionPayload;<|endoftext|>


<commit_before>
module.exports = function (github, payload, react) {
  return github.reactions.createForIssue(
    payload.toIssue({content: react})
  );
};
<commit_msg>Warn that reactions does not work<commit_after>// NOTE: The reactions API is not yet available for Integrations, so this action
//       does not currently work.
// https://developer.github.com/early-access/integrations/available-endpoints/
module.exports = function (github, payload, react) {
  return github.reactions.createForIssue(
    payload.toIssue({content: react})
  );
};
<|endoftext|>


<commit_before>const request = require('request-promise');
const co = require('co');
const csv = require('csv');
const messages = require('elasticio-node').messages;
const client = require('elasticio-rest-node')();

let stringifier;
let signedUrl;
let timeout;
let rowCount = 0;

exports.init = init;
exports.process = processAction;

function init() {
    return co(function* gen() {

        stringifier = csv.stringify({
            header: true
        });

        signedUrl = yield client.resources.storage.createSignedUrl();

        let putUrl = signedUrl.put_url;
        console.log('CSV file to be uploaded file to uri=%s', putUrl);

        stringifier.pipe(request.put(putUrl));
    });
}

function processAction(msg) {
    const self = this;

    if (timeout) {
        clearTimeout(timeout);
    }

    timeout = setTimeout(()=> {
        console.log('Closing the stream due to inactivity');
        co(function* gen() {
            console.log('The resulting CSV file contains %s rows', rowCount);
            stringifier.end();

            const messageToEmit = messages.newMessageWithBody({
                rowCount
            });
            const fileName = messageToEmit.id + '.csv';
            messageToEmit.attachments[fileName] = {
                "content-type": "text/csv",
                url: signedUrl.get_url
            };
            signedUrl = null;
            rowCount = 0;

            console.log('Emitting message %j', messageToEmit);
            self.emit('data', messageToEmit);

            yield init();
        });
    }, 10000);

    console.log('Writing to stream', msg.body);

    stringifier.write(msg.body);
    rowCount++;
    this.emit('end');
}

/**

co(function* proc() {
    yield init();

    for (let i = 0; i <= 100; i++) {

        processAction({
            body: {
                run: i,
                timestamp: Date.now()
            }
        });
    }

    setTimeout(()=> {

        console.log('Next round');

        for (let i = 100; i <= 200; i++) {

            processAction({
                body: {
                    run: i,
                    timestamp: Date.now()
                }
            });
        }
    }, 10000);
});
 **/
<commit_msg>Removed unnecessary log<commit_after>const request = require('request-promise');
const co = require('co');
const csv = require('csv');
const messages = require('elasticio-node').messages;
const client = require('elasticio-rest-node')();

let stringifier;
let signedUrl;
let timeout;
let rowCount = 0;

exports.init = init;
exports.process = processAction;

function init() {
    return co(function* gen() {

        stringifier = csv.stringify({
            header: true
        });

        signedUrl = yield client.resources.storage.createSignedUrl();

        let putUrl = signedUrl.put_url;
        console.log('CSV file to be uploaded file to uri=%s', putUrl);

        stringifier.pipe(request.put(putUrl));
    });
}

function processAction(msg) {
    const self = this;

    if (timeout) {
        clearTimeout(timeout);
    }

    timeout = setTimeout(()=> {
        console.log('Closing the stream due to inactivity');
        co(function* gen() {
            console.log('The resulting CSV file contains %s rows', rowCount);
            stringifier.end();

            const messageToEmit = messages.newMessageWithBody({
                rowCount
            });
            const fileName = messageToEmit.id + '.csv';
            messageToEmit.attachments[fileName] = {
                "content-type": "text/csv",
                url: signedUrl.get_url
            };
            signedUrl = null;
            rowCount = 0;

            console.log('Emitting message %j', messageToEmit);
            self.emit('data', messageToEmit);

            yield init();
        });
    }, 10000);

    stringifier.write(msg.body);
    rowCount++;
    this.emit('end');
}

/**

co(function* proc() {
    yield init();

    for (let i = 0; i <= 100; i++) {

        processAction({
            body: {
                run: i,
                timestamp: Date.now()
            }
        });
    }

    setTimeout(()=> {

        console.log('Next round');

        for (let i = 100; i <= 200; i++) {

            processAction({
                body: {
                    run: i,
                    timestamp: Date.now()
                }
            });
        }
    }, 10000);
});
 **/
<|endoftext|>


<commit_before>'use strict';

const tools = require('../tools.js');

function addInstance(ip, device, options, callback) {
    let instance = tools.findInstance(options, 'emby', obj => obj.native.ip === ip);

    if (!instance) {
        instance = {
            _id: tools.getNextInstanceID('emby', options),
            common: {
                name: 'emby',
                title: 'Emby (' + ip + (device._name ? (' - ' + device._name) : '') + ')'
            },
            native: {
                ip: ip + ":8096",
                apiKey: "",
                deviceIds: "",
                timeout: 1500
            },
            comment: {
                add: "Multimedia Server"
            }
        };
        options.newInstances.push(instance);
        callback(null, true, ip);
    } else {
        callback(null, false, ip);
    } // endElse
} // endAddSonnen

function detect(ip, device, options, callback) {
    tools.httpGet('http://' + ip + ':8096/Users', (err, data) => {
        if (err) {
            if (callback) {
                return callback(null, false, ip);
            } // endIf
        } else {
            if (data == "Access token is required.") {
                addInstance(ip, device, options, callback);
            } else if (callback) {
                return callback(null, false, ip);
            } // endElse

        } // endElse

    });
} // endDetect

exports.detect = detect;
exports.type = ['ip']; // TODO make to once and upd lookup
exports.timeout = 1500;<commit_msg>Fixed check emby instance<commit_after>'use strict';

const tools = require('../tools.js');

function addInstance(ip, device, options, callback) {
    let instance = tools.findInstance(options, 'emby', obj => obj.native.ip === ip + ":8096");

    if (!instance) {
        instance = {
            _id: tools.getNextInstanceID('emby', options),
            common: {
                name: 'emby',
                title: 'Emby (' + ip + (device._name ? (' - ' + device._name) : '') + ')'
            },
            native: {
                ip: ip + ":8096",
                apiKey: "",
                deviceIds: "",
                timeout: 1500
            },
            comment: {
                add: "Multimedia Server"
            }
        };
        options.newInstances.push(instance);
        callback(null, true, ip);
    } else {
        callback(null, false, ip);
    } // endElse
} // endAddSonnen

function detect(ip, device, options, callback) {
    tools.httpGet('http://' + ip + ':8096/Users', (err, data) => {
        if (err) {
            if (callback) {
                return callback(null, false, ip);
            } // endIf
        } else {
            if (data == "Access token is required.") {
                addInstance(ip, device, options, callback);
            } else if (callback) {
                return callback(null, false, ip);
            } // endElse

        } // endElse

    });
} // endDetect

exports.detect = detect;
exports.type = ['ip']; // TODO make to once and upd lookup
exports.timeout = 1500;
<|endoftext|>


<commit_before>define(['../utilities'], function(utils) {

    'use strict';

    /**
     * Documents API
     *
     * @namespace
     * @name api.documents
     */
    return function documents() {
        var dataHeaders = {
                'Content-Type': 'application/vnd.mendeley-document.1+json'
            },

            listDocuments = utils.requestFun('GET', '/documents/'),
            listFolder = utils.requestFun('GET', '/folders/{id}/documents', ['id']);

        return {

            /**
             * Create a new document
             *
             * @method
             * @memberof api.documents
             * @param {object} data - The document data
             * @returns {promise}
             */
            create: utils.requestWithDataFun('POST', '/documents', false, dataHeaders, true),

            /**
             * Create a new document from a file
             *
             * @method
             * @memberof api.documents
             * @param {object} file - A file object
             * @returns {promise}
             */
            createFromFile: utils.requestWithFileFun('POST', '/documents'),

            /**
             * Create a new group document from a file
             *
             * @method
             * @memberof api.documents
             * @param {object} file - A file object
             * @param {string} groupId - A group UUID
             * @returns {promise}
             */
            createFromFileInGroup: utils.requestWithFileFun('POST', '/documents', 'group'),

            /**
             * Retrieve a document
             *
             * @method
             * @memberof api.documents
             * @param {string} id - A document UUID
             * @returns {promise}
             */
            retrieve: utils.requestFun('GET', '/documents/{id}', ['id']),

            /**
             * Update document
             *
             * @method
             * @memberof api.documents
             * @param {object} data - The new document data
             * @returns {promise}
             */
            update: utils.requestWithDataFun('PATCH', '/documents/{id}', ['id'], dataHeaders, true),

            /**
             * Clone a document from user library to a group ( or vice versa )
             *
             * @method
             * @memberof api.documents
             * @param {object} id - A document UUID
             * @returns {promise}
             */
            clone: utils.requestWithDataFun('POST', '/documents/{id}/actions/cloneTo', ['id'], dataHeaders, true),

            /**
             * List documents
             *
             * @method
             * @memberof api.documents
             * @param {object} params - Query paramaters
             * @returns {promise}
             */
            list: function(params) {
                if (!params || typeof params.folderId === 'undefined') {
                    return listDocuments.call(this, params);
                } else {
                    var folderId = params.folderId,
                        callParams = {
                            limit: params.limit
                        };
                    delete params.folderId;
                    return listFolder.call(this, folderId, callParams);
                }
            },

            /**
             * Search documents
             *
             * @method
             * @memberof api.documents
             * @param {object} params - Search paramaters
             * @returns {promise}
             */
            search: utils.requestFun('GET', '/search/documents'),

            /**
             * Move a document to the trash
             *
             * @method
             * @memberof api.documents
             * @param {object} id - A document UUID
             * @returns {promise}
             */
            trash: utils.requestFun('POST', '/documents/{id}/trash', ['id'], dataHeaders),

            /**
             * The total number of documents - set after the first call to documents.list()
             *
             * @var
             * @memberof api.documents
             * @type {integer}
             */
            count: 0,

            /**
             * Get the next page of documents
             *
             * @method
             * @memberof api.documents
             * @returns {promise}
             */
            nextPage: utils.requestPageFun('next'),

            /**
             * Get the previous page of documents
             *
             * @method
             * @memberof api.documents
             * @returns {promise}
             */
            previousPage: utils.requestPageFun('previous'),

            /**
             * Get the last page of documents
             *
             * @method
             * @memberof api.documents
             * @returns {promise}
             */
            lastPage: utils.requestPageFun('last'),

            /**
             * Get pagination links
             *
             * @method
             * @memberof api.documents
             * @returns {object}
             */
            paginationLinks: {
                last: false,
                next: false,
                previous: false
            },

            /**
             * Reset all pagination
             *
             * @method
             * @memberof api.documents
             */
            resetPagination: utils.resetPaginationLinks

        };
    };

});
<commit_msg>Fixing clone document content type<commit_after>define(['../utilities'], function(utils) {

    'use strict';

    /**
     * Documents API
     *
     * @namespace
     * @name api.documents
     */
    return function documents() {
        var dataHeaders = {
                'Content-Type': 'application/vnd.mendeley-document.1+json'
            },
            cloneDataHeaders = {
                'Content-Type': 'application/vnd.mendeley-document-clone.1+json'
            },

            listDocuments = utils.requestFun('GET', '/documents/'),
            listFolder = utils.requestFun('GET', '/folders/{id}/documents', ['id']);

        return {

            /**
             * Create a new document
             *
             * @method
             * @memberof api.documents
             * @param {object} data - The document data
             * @returns {promise}
             */
            create: utils.requestWithDataFun('POST', '/documents', false, dataHeaders, true),

            /**
             * Create a new document from a file
             *
             * @method
             * @memberof api.documents
             * @param {object} file - A file object
             * @returns {promise}
             */
            createFromFile: utils.requestWithFileFun('POST', '/documents'),

            /**
             * Create a new group document from a file
             *
             * @method
             * @memberof api.documents
             * @param {object} file - A file object
             * @param {string} groupId - A group UUID
             * @returns {promise}
             */
            createFromFileInGroup: utils.requestWithFileFun('POST', '/documents', 'group'),

            /**
             * Retrieve a document
             *
             * @method
             * @memberof api.documents
             * @param {string} id - A document UUID
             * @returns {promise}
             */
            retrieve: utils.requestFun('GET', '/documents/{id}', ['id']),

            /**
             * Update document
             *
             * @method
             * @memberof api.documents
             * @param {object} data - The new document data
             * @returns {promise}
             */
            update: utils.requestWithDataFun('PATCH', '/documents/{id}', ['id'], dataHeaders, true),

            /**
             * Clone a document from user library to a group ( or vice versa )
             *
             * @method
             * @memberof api.documents
             * @param {object} id - A document UUID
             * @returns {promise}
             */
            clone: utils.requestWithDataFun('POST', '/documents/{id}/actions/cloneTo', ['id'], cloneDataHeaders, true),

            /**
             * List documents
             *
             * @method
             * @memberof api.documents
             * @param {object} params - Query paramaters
             * @returns {promise}
             */
            list: function(params) {
                if (!params || typeof params.folderId === 'undefined') {
                    return listDocuments.call(this, params);
                } else {
                    var folderId = params.folderId,
                        callParams = {
                            limit: params.limit
                        };
                    delete params.folderId;
                    return listFolder.call(this, folderId, callParams);
                }
            },

            /**
             * Search documents
             *
             * @method
             * @memberof api.documents
             * @param {object} params - Search paramaters
             * @returns {promise}
             */
            search: utils.requestFun('GET', '/search/documents'),

            /**
             * Move a document to the trash
             *
             * @method
             * @memberof api.documents
             * @param {object} id - A document UUID
             * @returns {promise}
             */
            trash: utils.requestFun('POST', '/documents/{id}/trash', ['id'], dataHeaders),

            /**
             * The total number of documents - set after the first call to documents.list()
             *
             * @var
             * @memberof api.documents
             * @type {integer}
             */
            count: 0,

            /**
             * Get the next page of documents
             *
             * @method
             * @memberof api.documents
             * @returns {promise}
             */
            nextPage: utils.requestPageFun('next'),

            /**
             * Get the previous page of documents
             *
             * @method
             * @memberof api.documents
             * @returns {promise}
             */
            previousPage: utils.requestPageFun('previous'),

            /**
             * Get the last page of documents
             *
             * @method
             * @memberof api.documents
             * @returns {promise}
             */
            lastPage: utils.requestPageFun('last'),

            /**
             * Get pagination links
             *
             * @method
             * @memberof api.documents
             * @returns {object}
             */
            paginationLinks: {
                last: false,
                next: false,
                previous: false
            },

            /**
             * Reset all pagination
             *
             * @method
             * @memberof api.documents
             */
            resetPagination: utils.resetPaginationLinks

        };
    };

});
<|endoftext|>


<commit_before><<<<<<< HEAD
'use babel';
var path = require('path');
var homeDir = path.resolve(__dirname);
var audio = new Audio(homeDir + '/test.mp3')
=======
'use babel'
>>>>>>> f3629480383fda948285ca2e97bb181ca88ba357

export default class AtomRipView {

  constructor(serializedState) {
//     this.element = document.createElement('div') // div 만들고
//     this.element.classList.add('atom-rip') // class atom-rip 추가
//
//     // const message = document.createElement('div')
//     // message.textContent = 'The AtomRip package is Alive! It\'s ALIVE!'
//     // message.classList.add('message')
//     // this.element.appendChild(message)
//     // document.getElementsByTagName('body')[0].appendChild(this.element)
//
//     const = document.createElement('div')
//     const.classList.add('moviePlayer')
//
//     const movieVideo = document.createElement('video') // video elment 가져옴
//     const movieSource = document.createElement('source') // video  source
//     movieSource.setAttribute('src', 'https://www.youtube.com/watch?v=CbTvcda__ns') // 속성 셋
//     movieVideo.appendChild(movieSource)
//
//     this.element.appendChild(movieVideo);
    this.hidden = true

    this.element = document.createElement('div')
    this.element.classList.add('atom-rip', 'hidden')

    const title = document.createElement('h1')
    title.textContent = '잠시 휴식을 가지세요'

    const subtitle = document.createElement('h2')
    subtitle.textContent = '과도한 코딩은 일상생활에 지장을 줄 수 있습니다.'

    this.element.appendChild(title)
    this.element.appendChild(subtitle)
    document.getElementsByTagName('body')[0].appendChild(this.element)

  }

  toggle () {
    this.element.classList[this.hidden ? 'remove' : 'add']('hidden')
    this.hidden = !this.hidden
  }

  // Returns an object that can be retrieved when package is activated
  serialize () {}

  // Tear down any state and detach
  destroy() {
    this.element.remove();
    // audio.stopBGM();
  }

  getElement() {
    return this.element
  }

  playBGM(){
    audio.play()
    // setTimeout(stopBGM, 30000)
  }

  stopBGM(){
    if(audio.played.length >0) audio.pause()
  }
}
<commit_msg>conflict modify<commit_after>'use babel'

var path = require('path')
var homeDir = path.resolve(__dirname)
var audio = new Audio(homeDir + '/test.mp3')

export default class AtomRipView {

  constructor(serializedState) {
//     this.element = document.createElement('div') // div 만들고
//     this.element.classList.add('atom-rip') // class atom-rip 추가
//
//     // const message = document.createElement('div')
//     // message.textContent = 'The AtomRip package is Alive! It\'s ALIVE!'
//     // message.classList.add('message')
//     // this.element.appendChild(message)
//     // document.getElementsByTagName('body')[0].appendChild(this.element)
//
//     const = document.createElement('div')
//     const.classList.add('moviePlayer')
//
//     const movieVideo = document.createElement('video') // video elment 가져옴
//     const movieSource = document.createElement('source') // video  source
//     movieSource.setAttribute('src', 'https://www.youtube.com/watch?v=CbTvcda__ns') // 속성 셋
//     movieVideo.appendChild(movieSource)
//
//     this.element.appendChild(movieVideo);
    this.hidden = true

    this.element = document.createElement('div')
    this.element.classList.add('atom-rip', 'hidden')

    const title = document.createElement('h1')
    title.textContent = '잠시 휴식을 가지세요'

    const subtitle = document.createElement('h2')
    subtitle.textContent = '과도한 코딩은 일상생활에 지장을 줄 수 있습니다.'

    this.element.appendChild(title)
    this.element.appendChild(subtitle)
    document.getElementsByTagName('body')[0].appendChild(this.element)

  }

  toggle () {
    this.element.classList[this.hidden ? 'remove' : 'add']('hidden')
    this.hidden = !this.hidden
  }

  // Returns an object that can be retrieved when package is activated
  serialize () {}

  // Tear down any state and detach
  destroy() {
    this.element.remove();
    // audio.stopBGM();
  }

  getElement() {
    return this.element
  }

  playBGM(){
    audio.play()
    // setTimeout(stopBGM, 30000)
  }

  stopBGM(){
    if(audio.played.length >0) audio.pause()
  }
}
<|endoftext|>


<commit_before>var querystring       = require('querystring');
var debug             = require('debug')('azure:authorization');
var utils             = require('./utils');

/*
 * Authorize the request with a shared-access-signature that is refreshed with
 * the a function given as `options.sas`.
 * Intended to define `<Queue|Table|Blob>.prototype.authorize`.
 */
var authorizeWithRefreshSAS = function authorizeWithRefreshSAS(method, path, query, headers) {
  var self = this;
  // Check if we should refresh SAS
  if (Date.now() > this._nextSASRefresh && this._nextSASRefresh !== 0) {
    debug("Refreshing shared-access-signature");
    // Avoid refreshing more than once
    this._nextSASRefresh = 0;
    // Refresh SAS
    this._sas = Promise.resolve(this.options.sas());
    // Update _nextSASRefresh when the SAS has been refreshed
    this._sas.then(function(sas) {
      sas = querystring.parse(sas);
      // Find next sas refresh time
      self._nextSASRefresh = (
        new Date(sas.se).getTime() - self.options.minSASAuthExpiry
      );
      debug("Refreshed shared-access-signature, will refresh in %s ms",
        self._nextSASRefresh);
      // Throw an error if the signature expiration comes too soon
      if (Date.now() > self._nextSASRefresh) {
        throw new Error("Refreshed SAS, but got a Shared-Access-Signature " +
          "that expires less than options.minSASAuthExpiry " +
          "from now, signature expiry: " + sas.se);
      }
    }).catch(function(err) {
      // If we have an error freshing SAS that's bad and we'll emit it; for most
      // apps it's probably best to ignore this error and just crash.
      self.emit('error', err);
    });
  }

  // Construct request options, whenever the `_sas` promise is resolved.
  return this._sas.then(function(sas) {
    // Serialize query-string
    var qs = querystring.stringify(query);
    if (qs.length > 0) {
      qs += '&';
    }
    qs += sas
    return {
      host:       self.hostname,
      method:     method,
      path:       path + '?' + qs,
      headers:    headers,
      agent:      self.options.agent,
    };
  });
}

exports.authorizeWithRefreshSAS = authorizeWithRefreshSAS;

/*
 * Authorize the request with a shared-access-signature that is given with
 * `options.sas` as string.
 * Intended to define `<Queue|Table|Blob>.prototype.authorize`.
 */
function authorizeWithSAS(method, path, query, headers) {
  // Serialize query-string
  var qs = querystring.stringify(query);
  if (qs.length > 0) {
    qs += '&';
  }
  qs += this.options.sas;
  // Construct request options
  return Promise.resolve({
    host:       this.hostname,
    method:     method,
    path:       path + '?' + qs,
    headers:    headers,
    agent:      this.options.agent,
  });
}

exports.authorizeWithSAS = authorizeWithSAS;

/*
 * Authorize the request with shared key
 * Intended to define `<Queue|Table|Blob>.prototype.authorize`.
 *
 * Note that this function should be called in the service context.
 * @param {string} service - the name of the service: queue|blob|table
 * @param {Array} queryParamsSupported - a sorted array which contains the query parameters supported by the storage service
 */
var authorizeWithSharedKey = function (service, queryParamsSupported) {
  var self = this;
  return function(method, path, query, headers) {
    // Find account id
    var accountId = self.options.accountId;

    // Build string to sign
    var stringToSign;
    if(service === 'table') {
      stringToSign = (
        method + '\n' +
        (headers['content-md5']  || '') + '\n' +
        (headers['content-type'] || '') + '\n' +
        headers['x-ms-date']
      );
      stringToSign += '\n/' + accountId + path;
      if (query.comp !== undefined) {
        stringToSign += '?comp=' + query.comp;
      }
    } else {
      stringToSign = (
        method + '\n' +
        (headers['content-encoding']     || '') + '\n' +
        (headers['content-language']     || '') + '\n' +
        (headers['content-length']       || '') + '\n' +
        (headers['content-md5']          || '') + '\n' +
        (headers['content-type']         || '') + '\n' +
        '\n' + // we always include x-ms-date, so we never specify date header
        (headers['if-modified-since']    || '') + '\n' +
        (headers['if-match']             || '') + '\n' +
        (headers['if-none-match']        || '') + '\n' +
        (headers['if-unmodified-since']  || '') + '\n' +
        (headers['range']                || '')
      );

      // Construct fields as a sorted list of 'x-ms-' prefixed headers
      var fields = [];
      for (var field in headers) {
        if (/^x-ms-/.test(field)) {
          fields.push(field);
        }
      }
      fields.sort();

      // Add lines for canonicalized headers using presorted list of fields
      var N = fields.length;
      for(var i = 0; i < N; i++) {
        var field = fields[i];
        var value = headers[field];
        if (value) {
          // Convert each HTTP header to lower case and
          // trim any white space around the colon in the header.
          stringToSign += '\n' + field.toLowerCase() + ':' + value.trim();
        }
      }

      // Added lines from canonicalized resource and query-string parameters
      // supported by this library in lexicographical order as presorted in
      // QUERY_PARAMS_SUPPORTED
      stringToSign += '\n/' + accountId + path;
      var M = queryParamsSupported.length;
      for(var j = 0; j < M; j++) {
        var param = queryParamsSupported[j];
        var value = query[param];
        if (value) {
          stringToSign += '\n' + param + ':' + value;
        }
      }
    }

    // Compute signature
    var signature = utils.hmacSha256(self._accessKey, stringToSign);

    // Set authorization header
    headers.authorization = 'SharedKey ' + accountId + ':' + signature;

    // Encode query string
    var qs = querystring.stringify(query);

    // Construct request options
    return Promise.resolve({
      host:       self.hostname,
      method:     method,
      path:       (qs.length > 0 ? path + '?' + qs : path),
      headers:    headers,
      agent:      self.options.agent,
    });
  };
}

exports.authorizeWithSharedKey = authorizeWithSharedKey;<commit_msg>don't try to emit errors<commit_after>var querystring       = require('querystring');
var debug             = require('debug')('azure:authorization');
var utils             = require('./utils');

/*
 * Authorize the request with a shared-access-signature that is refreshed with
 * the a function given as `options.sas`.
 * Intended to define `<Queue|Table|Blob>.prototype.authorize`.
 */
var authorizeWithRefreshSAS = function authorizeWithRefreshSAS(method, path, query, headers) {
  var self = this;
  // Check if we should refresh SAS
  if (Date.now() > this._nextSASRefresh && this._nextSASRefresh !== 0) {
    debug("Refreshing shared-access-signature");
    // Avoid refreshing more than once
    this._nextSASRefresh = 0;
    // Refresh SAS
    this._sas = Promise.resolve(this.options.sas());
    // Update _nextSASRefresh when the SAS has been refreshed
    this._sas.then(function(sas) {
      sas = querystring.parse(sas);
      // Find next sas refresh time
      self._nextSASRefresh = (
        new Date(sas.se).getTime() - self.options.minSASAuthExpiry
      );
      debug("Refreshed shared-access-signature, will refresh in %s ms",
        self._nextSASRefresh);
      // Throw an error if the signature expiration comes too soon
      if (Date.now() > self._nextSASRefresh) {
        throw new Error("Refreshed SAS, but got a Shared-Access-Signature " +
          "that expires less than options.minSASAuthExpiry " +
          "from now, signature expiry: " + sas.se);
      }
    });
  }

  // Construct request options, whenever the `_sas` promise is resolved.
  return this._sas.then(function(sas) {
    // Serialize query-string
    var qs = querystring.stringify(query);
    if (qs.length > 0) {
      qs += '&';
    }
    qs += sas
    return {
      host:       self.hostname,
      method:     method,
      path:       path + '?' + qs,
      headers:    headers,
      agent:      self.options.agent,
    };
  });
}

exports.authorizeWithRefreshSAS = authorizeWithRefreshSAS;

/*
 * Authorize the request with a shared-access-signature that is given with
 * `options.sas` as string.
 * Intended to define `<Queue|Table|Blob>.prototype.authorize`.
 */
function authorizeWithSAS(method, path, query, headers) {
  // Serialize query-string
  var qs = querystring.stringify(query);
  if (qs.length > 0) {
    qs += '&';
  }
  qs += this.options.sas;
  // Construct request options
  return Promise.resolve({
    host:       this.hostname,
    method:     method,
    path:       path + '?' + qs,
    headers:    headers,
    agent:      this.options.agent,
  });
}

exports.authorizeWithSAS = authorizeWithSAS;

/*
 * Authorize the request with shared key
 * Intended to define `<Queue|Table|Blob>.prototype.authorize`.
 *
 * Note that this function should be called in the service context.
 * @param {string} service - the name of the service: queue|blob|table
 * @param {Array} queryParamsSupported - a sorted array which contains the query parameters supported by the storage service
 */
var authorizeWithSharedKey = function (service, queryParamsSupported) {
  var self = this;
  return function(method, path, query, headers) {
    // Find account id
    var accountId = self.options.accountId;

    // Build string to sign
    var stringToSign;
    if(service === 'table') {
      stringToSign = (
        method + '\n' +
        (headers['content-md5']  || '') + '\n' +
        (headers['content-type'] || '') + '\n' +
        headers['x-ms-date']
      );
      stringToSign += '\n/' + accountId + path;
      if (query.comp !== undefined) {
        stringToSign += '?comp=' + query.comp;
      }
    } else {
      stringToSign = (
        method + '\n' +
        (headers['content-encoding']     || '') + '\n' +
        (headers['content-language']     || '') + '\n' +
        (headers['content-length']       || '') + '\n' +
        (headers['content-md5']          || '') + '\n' +
        (headers['content-type']         || '') + '\n' +
        '\n' + // we always include x-ms-date, so we never specify date header
        (headers['if-modified-since']    || '') + '\n' +
        (headers['if-match']             || '') + '\n' +
        (headers['if-none-match']        || '') + '\n' +
        (headers['if-unmodified-since']  || '') + '\n' +
        (headers['range']                || '')
      );

      // Construct fields as a sorted list of 'x-ms-' prefixed headers
      var fields = [];
      for (var field in headers) {
        if (/^x-ms-/.test(field)) {
          fields.push(field);
        }
      }
      fields.sort();

      // Add lines for canonicalized headers using presorted list of fields
      var N = fields.length;
      for(var i = 0; i < N; i++) {
        var field = fields[i];
        var value = headers[field];
        if (value) {
          // Convert each HTTP header to lower case and
          // trim any white space around the colon in the header.
          stringToSign += '\n' + field.toLowerCase() + ':' + value.trim();
        }
      }

      // Added lines from canonicalized resource and query-string parameters
      // supported by this library in lexicographical order as presorted in
      // QUERY_PARAMS_SUPPORTED
      stringToSign += '\n/' + accountId + path;
      var M = queryParamsSupported.length;
      for(var j = 0; j < M; j++) {
        var param = queryParamsSupported[j];
        var value = query[param];
        if (value) {
          stringToSign += '\n' + param + ':' + value;
        }
      }
    }

    // Compute signature
    var signature = utils.hmacSha256(self._accessKey, stringToSign);

    // Set authorization header
    headers.authorization = 'SharedKey ' + accountId + ':' + signature;

    // Encode query string
    var qs = querystring.stringify(query);

    // Construct request options
    return Promise.resolve({
      host:       self.hostname,
      method:     method,
      path:       (qs.length > 0 ? path + '?' + qs : path),
      headers:    headers,
      agent:      self.options.agent,
    });
  };
}

exports.authorizeWithSharedKey = authorizeWithSharedKey;
<|endoftext|>


<commit_before>"use strict";
// Generated by CoffeeScript 1.8.0
var Utils = {
  getCurrentVersion: function() {
    return chrome.runtime.getManifest().version;
  },
  _escapeRegex: /[&<>]/g,
  _escapeCallback: function(c, n) {
    n = c.charCodeAt(0);
    return (n === 60) ? "<" : (n === 62) ? ">" : "&";
  },
  escapeHtml: function(s) {
    return s.replace(this._escapeRegex, this._escapeCallback);
  },
  _chromePrefixes: ["about", "view-source", "chrome-search", "chrome-extension", "data", "javascript"],
  hasChromePrefix: function(url) {
    var index = url.indexOf(':');
    return index > 3 && index < 17 && this._chromePrefixes.indexOf(url.substring(0, index)) >= 0;
  },
  _urlPrefix: /^[a-z]{3,}:\/\/./,
  hasOrdinaryUrlPrefix: function(url) {
    return this._urlPrefix.test(url);
  },
  isRefusingIncognito: function(url) {
    url = url.toLowerCase();
    if (url.startsWith('chrome://')) {
      return !url.startsWith("chrome://downloads/");
    }
    return url !== Settings.ChromeInnerNewTab && (url.startsWith('chrome') || !this._urlPrefix.test(url));
  },
  _hostRegex: /^(?:[^:]+(?::[^:]+)?@)?([^:]+|\[[^\]]+\])(?::\d+)?$/,
  _longTlds: ["arpa", "asia", "coop", "info", "jobs", "local", "mobi", "museum", "name", "onion"],
  // condition: .length <= 3
  _fileExts: ["exe", "dll", "doc", "gz", "pdf", "tar", "tgz", "txt", "zip", "log"],
  _ipRegex: /^(\d{1,3}\.){3}\d{1,3}$/,
  _spacesRegex: /[\s\u3000]+/g,
  _nonDomainRegex: /[^0-9A-Za-z]/,
  convertToUrl: function(string) {
    var host, arr, type = -1, expected = 1, index, index0, oldString;
    oldString = string.replace(this._spacesRegex, ' ').trim();
    string = oldString.toLowerCase();
    index = string.indexOf(' ');
    if (index > 0 && string.startsWith("javascript:")) {
      type = 0;
    }
    else if (index > 0) {
      string = string.substring(0, index);
      if ((index = string.indexOf('/')) <= 0) {
        type = 2;
      }
      else if ((index0 = string.indexOf(':')) > 0) {
        if (string.substring(index0, index0 + 3) !== "://") {
          if (this._chromePrefixes.indexOf(string.substring(0, index0)) >= 0) {
            type = 2;
          } else {
            index0 = -1;
          }
        }
        else if (this._urlPrefix.test(string)) {
          expected = 0;
          if (string.startsWith("file:///")) {
            index0 = string.charCodeAt(8);
            type = (index0 > 32 && index0 !== 47) ? 0 : 2;
          }
        } else if (!this.startsWith("chrome")) {
          type = 2;
        }
      } else if (index0 === 0) {
        type = 2;
      }
      if (type < 0) {
        if (index0 > 0) {
          index0 += 3;
          index = string.indexOf('/', index0);
        } else {
          index0 = 0;
        }
        if (index > index0 && (type = string.charCodeAt(index + 1)) > 32 && type !== 47) {
          host = string.substring(index0, index);
          type = -1;
        } else {
          type = 2;
        }
      }
    }
    else if (this._urlPrefix.test(string)) {
      if (string.startsWith("file:") || string.startsWith("chrome:")) {
        type = 0;
      } else {
        index0 = string.indexOf(':') + 3;
        index = string.indexOf('/', index0);
        host = string.substring(index0, index >= 0 ? index : string.length);
        expected = 0;
      }
    } else if (this.hasChromePrefix(string)) {
      type = 0;
    } else if ((index = string.indexOf('/')) >= 0) {
      host = string.substring(0, index);
    } else {
      host = string;
    }
    if (type >= 0) {
    }
    else if (!(arr = this._hostRegex.exec(host))) {
      type = 2;
    }
    else if ((host = arr[1]).indexOf(':') >= 0 || host.endsWith("localhost")) {
      type = expected;
    }
    else if ((index = host.lastIndexOf('.')) >= 0) {
      if (this._ipRegex.test(host) || (host = host.substring(index + 1), 2 <= host.length
        && ((host.length > 3) ? (this._longTlds.indexOf(host) >= 0)
          : (this._fileExts.indexOf(host) < 0 && !this._nonDomainRegex.test(host)))
      )) {
        type = expected;
      }
    } else {
      type = 2;
    }
    return type === 0 ? oldString : type === 1 ? ("http://" + oldString)
      : this.createSearchUrl(Settings.get("searchEnginesMap")["\\"], oldString.split(' ')).url;
  },
  _searchWordRegex: /%[sS]/g,
  createSearchUrl: function(pattern, query, $S) {
    if ($S != null ? ($S === true) : pattern.$S) {
      $S = query.join(' ');
    }
    if (pattern.$s) {
      query = query.map(encodeURIComponent).join('+');
    }
    query = pattern.url.replace(this._searchWordRegex, function(s) {
      return (s === "%s") ? query : $S;
    });
    return {
      url: query,
      $S: $S
    };
  },
  distinctCharacters: function(str) {
    var char, unique, _i, _len, _ref;
    unique = "";
    _ref = str.split("").sort();
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      char = _ref[_i];
      if (0 > unique.indexOf(char)) {
        unique += char;
      }
    }
    return unique;
  },
  compareVersions: function(versionA, versionB) {
    var a, b, i, _i, _ref;
    versionA = versionA.split('.');
    versionB = versionB.split('.');
    for (i = 0, _ref = Math.max(versionA.length, versionB.length); i < _ref; ++i) {
      a = parseInt(versionA[i] || 0, 10);
      b = parseInt(versionB[i] || 0, 10);
      if (a < b) {
        return -1;
      } else if (a > b) {
        return 1;
      }
    }
    return 0;
  }
};

window.extend = function(hash1, hash2) {
  for (var key in hash2) {
    hash1[key] = hash2[key];
  }
  return hash1;
};
<commit_msg>BackendUtils: better short domain checking<commit_after>"use strict";
// Generated by CoffeeScript 1.8.0
var Utils = {
  getCurrentVersion: function() {
    return chrome.runtime.getManifest().version;
  },
  _escapeRegex: /[&<>]/g,
  _escapeCallback: function(c, n) {
    n = c.charCodeAt(0);
    return (n === 60) ? "<" : (n === 62) ? ">" : "&";
  },
  escapeHtml: function(s) {
    return s.replace(this._escapeRegex, this._escapeCallback);
  },
  _chromePrefixes: ["about", "view-source", "chrome-search", "chrome-extension", "data", "javascript"],
  hasChromePrefix: function(url) {
    var index = url.indexOf(':');
    return index > 3 && index < 17 && this._chromePrefixes.indexOf(url.substring(0, index)) >= 0;
  },
  _urlPrefix: /^[a-z]{3,}:\/\/./,
  hasOrdinaryUrlPrefix: function(url) {
    return this._urlPrefix.test(url);
  },
  isRefusingIncognito: function(url) {
    url = url.toLowerCase();
    if (url.startsWith('chrome://')) {
      return !url.startsWith("chrome://downloads/");
    }
    return url !== Settings.ChromeInnerNewTab && (url.startsWith('chrome') || !this._urlPrefix.test(url));
  },
  _hostRegex: /^(?:[^:]+(?::[^:]+)?@)?([^:]+|\[[^\]]+\])(?::\d+)?$/,
  _longTlds: ["arpa", "asia", "coop", "info", "jobs", "local", "mobi", "museum", "name", "onion"],
  // condition: .length in [2, 3]
  _fileExts: ["7z", "bz", "cpp", "exe", "dll", "doc", "gz", "hpp" //
    , "log", "pdf", "rar", "tar", "tgz", "txt", "zip" //
  ],
  _ipRegex: /^(\d{1,3}\.){3}\d{1,3}$/,
  _spacesRegex: /[\s\u3000]+/g,
  _nonDomainRegex: /[^a-z]/,
  convertToUrl: function(string) {
    var host, arr, type = -1, expected = 1, index, index0, oldString;
    oldString = string.replace(this._spacesRegex, ' ').trim();
    string = oldString.toLowerCase();
    index = string.indexOf(' ');
    if (index > 0 && string.startsWith("javascript:")) {
      type = 0;
    }
    else if (index > 0) {
      string = string.substring(0, index);
      if ((index = string.indexOf('/')) <= 0) {
        type = 2;
      }
      else if ((index0 = string.indexOf(':')) > 0) {
        if (string.substring(index0, index0 + 3) !== "://") {
          if (this._chromePrefixes.indexOf(string.substring(0, index0)) >= 0) {
            type = 2;
          } else {
            index0 = -1;
          }
        }
        else if (this._urlPrefix.test(string)) {
          expected = 0;
          if (string.startsWith("file:///")) {
            index0 = string.charCodeAt(8);
            type = (index0 > 32 && index0 !== 47) ? 0 : 2;
          }
        } else if (!this.startsWith("chrome")) {
          type = 2;
        }
      } else if (index0 === 0) {
        type = 2;
      }
      if (type < 0) {
        if (index0 > 0) {
          index0 += 3;
          index = string.indexOf('/', index0);
        } else {
          index0 = 0;
        }
        if (index > index0 && (type = string.charCodeAt(index + 1)) > 32 && type !== 47) {
          host = string.substring(index0, index);
          type = -1;
        } else {
          type = 2;
        }
      }
    }
    else if (this._urlPrefix.test(string)) {
      if (string.startsWith("file:") || string.startsWith("chrome:")) {
        type = 0;
      } else {
        index0 = string.indexOf(':') + 3;
        index = string.indexOf('/', index0);
        host = string.substring(index0, index >= 0 ? index : string.length);
        expected = 0;
      }
    } else if (this.hasChromePrefix(string)) {
      type = 0;
    } else if ((index = string.indexOf('/')) >= 0) {
      host = string.substring(0, index);
    } else {
      host = string;
    }
    if (type >= 0) {
    }
    else if (!(arr = this._hostRegex.exec(host))) {
      type = 2;
    }
    else if ((host = arr[1]).indexOf(':') >= 0 || host.endsWith("localhost")) {
      type = expected;
    }
    else if ((index = host.lastIndexOf('.')) >= 0) {
      if (this._ipRegex.test(host) || (host = host.substring(index + 1), 2 <= host.length
        && ((host.length > 3) ? (this._longTlds.indexOf(host) >= 0)
          : (this._fileExts.indexOf(host) < 0 && !this._nonDomainRegex.test(host)))
      )) {
        type = expected;
      }
    } else {
      type = 2;
    }
    return type === 0 ? oldString : type === 1 ? ("http://" + oldString)
      : this.createSearchUrl(Settings.get("searchEnginesMap")["\\"], oldString.split(' ')).url;
  },
  _searchWordRegex: /%[sS]/g,
  createSearchUrl: function(pattern, query, $S) {
    if ($S != null ? ($S === true) : pattern.$S) {
      $S = query.join(' ');
    }
    if (pattern.$s) {
      query = query.map(encodeURIComponent).join('+');
    }
    query = pattern.url.replace(this._searchWordRegex, function(s) {
      return (s === "%s") ? query : $S;
    });
    return {
      url: query,
      $S: $S
    };
  },
  distinctCharacters: function(str) {
    var char, unique, _i, _len, _ref;
    unique = "";
    _ref = str.split("").sort();
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      char = _ref[_i];
      if (0 > unique.indexOf(char)) {
        unique += char;
      }
    }
    return unique;
  },
  compareVersions: function(versionA, versionB) {
    var a, b, i, _i, _ref;
    versionA = versionA.split('.');
    versionB = versionB.split('.');
    for (i = 0, _ref = Math.max(versionA.length, versionB.length); i < _ref; ++i) {
      a = parseInt(versionA[i] || 0, 10);
      b = parseInt(versionB[i] || 0, 10);
      if (a < b) {
        return -1;
      } else if (a > b) {
        return 1;
      }
    }
    return 0;
  }
};

window.extend = function(hash1, hash2) {
  for (var key in hash2) {
    hash1[key] = hash2[key];
  }
  return hash1;
};
<|endoftext|>


<commit_before>/**
 * Created by ctalmacel on 12/15/15.
 */

exports.registerTypeConverters = function(persistence){
    persistence.registerConverter("string",
        function(value){
            return value;
        },
        function(value){
            return value;
        },
        'varchar'
    )
    persistence.registerConverter("textString",
        function(value){
            return value;
        },
        function(value){
            return value;
        },
        'text'
    )

    persistence.registerConverter('int',
        function(value){
            return (value);
        },
        function(value){
            return value;
        },
        "int"
    )

    persistence.registerConverter('float',
        function(value){
            return value;
        },
        function(value){
            return value;
        },
        "float"
    )

    persistence.registerConverter('boolean',
        function(value){
            if(value == 1) {
                return true;
            }
            else {
                return false;
            }
        },
        function(value){
            if(value == true){
                return 1
            }
            else{
                return 0
            }
        },
        "tinyint(1)"
    );

    persistence.registerConverter('date',
        function(value){
            return value;
        },
        function(javascriptDate){
            return javascriptDate.toISOString().substring(0,10);
        },
        "date"
    );

    persistence.registerConverter('datetime',
        function(value){
            return value;
        },
        function(javascriptDate){
            return javascriptDate.toISOString().slice(0, 19).replace('T', ' ');
        },
        "datetime"
    );

    persistence.registerConverter("dateFormat",
        function(value, typeDescription){
            if(!value){
                return null;
            }
            var m = moment(value,typeDescription.format);
            return m;
        },
        function(value, typeDescription){
            var txt = value.format(typeDescription.format);
            return txt;
        },
        "varchar"
    );

    persistence.registerConverter("array",
        function(blobOfStuff, typeDescription){
            if (blobOfStuff == null || blobOfStuff == undefined){
                return "null";
            }
            return JSON.parse(blobOfStuff);
        },
        function(arrayOfStuff, typeDescription){
            if(arrayOfStuff == "null"){
                return null;
            }

            return JSON.stringify(arrayOfStuff)
        },
        'blob'
    );

    persistence.registerConverter("base64image",
        function(value){
            var buffer = new Buffer( value );
            var bufferBase64 = buffer.toString();
            return bufferBase64;
        },
        function(value){
            return value;
        },
        'blob'
    );

}<commit_msg>added JSON sql type<commit_after>/**
 * Created by ctalmacel on 12/15/15.
 */

exports.registerTypeConverters = function(persistence){
    persistence.registerConverter("string",
        function(value){
            return value;
        },
        function(value){
            return value;
        },
        'varchar'
    )
    persistence.registerConverter("textString",
        function(value){
            return value;
        },
        function(value){
            return value;
        },
        'text'
    )

    persistence.registerConverter('int',
        function(value){
            return (value);
        },
        function(value){
            return value;
        },
        "int"
    )

    persistence.registerConverter('float',
        function(value){
            return value;
        },
        function(value){
            return value;
        },
        "float"
    )

    persistence.registerConverter('boolean',
        function(value){
            if(value == 1) {
                return true;
            }
            else {
                return false;
            }
        },
        function(value){
            if(value == true){
                return 1
            }
            else{
                return 0
            }
        },
        "tinyint(1)"
    );

    persistence.registerConverter('date',
        function(value){
            return value;
        },
        function(javascriptDate){
            return javascriptDate.toISOString().substring(0,10);
        },
        "date"
    );

    persistence.registerConverter('datetime',
        function(value){
            return value;
        },
        function(javascriptDate){
            return javascriptDate.toISOString().slice(0, 19).replace('T', ' ');
        },
        "datetime"
    );

    persistence.registerConverter("dateFormat",
        function(value, typeDescription){
            if(!value){
                return null;
            }
            var m = moment(value,typeDescription.format);
            return m;
        },
        function(value, typeDescription){
            var txt = value.format(typeDescription.format);
            return txt;
        },
        "varchar"
    );

    persistence.registerConverter("array",
        function(blobOfStuff, typeDescription){
            if (blobOfStuff == null || blobOfStuff == undefined){
                return "null";
            }
            return JSON.parse(blobOfStuff);
        },
        function(arrayOfStuff, typeDescription){
            if(arrayOfStuff == "null"){
                return null;
            }

            return JSON.stringify(arrayOfStuff)
        },
        'blob'
    );

    persistence.registerConverter("base64image",
        function(value){
            var buffer = new Buffer( value );
            var bufferBase64 = buffer.toString();
            return bufferBase64;
        },
        function(value){
            return value;
        },
        'blob'
    );
    persistence.registerConverter('JSON',
        function(value){
            return JSON.parse(value);
        },
        function(value){
            return JSON.stringify(value);
        },
        'JSON'
    );

}<|endoftext|>


<commit_before>'use strict';

const http = require('http');
const url = require('url');
const uws = require('uws');

const native = uws.native;

//
// uws v0.12.0+ needs a set "no operation" callback.
//
if (native.setNoop) native.setNoop(() => {});

/**
 * Server of µWebSockets transformer.
 *
 * @runat server
 * @api private
 */
module.exports = function server() {
  const opts = Object.assign({
    perMessageDeflate: this.primus.options.compression,
    maxPayload: this.primus.options.maxLength
  }, this.primus.options.transport);

  const group = native.server.group.create(
    opts.perMessageDeflate ? 1 : 0,
    opts.maxPayload
  );

  let upgradeReq = null;

  native.server.group.onConnection(group, (socket) => {
    const spark = new this.Spark(
      upgradeReq.headers,               // HTTP request headers.
      upgradeReq,                       // IP address location.
      url.parse(upgradeReq.url).query,  // Optional query string.
      null,                             // We don't have an unique id.
      upgradeReq                        // Reference to the HTTP req.
    );

    native.setUserData(socket, spark);

    spark.ultron.on('outgoing::end', () => native.server.close(socket));
    spark.on('outgoing::data', (data) => {
      const opcode = Buffer.isBuffer(data)
        ? uws.OPCODE_BINARY
        : uws.OPCODE_TEXT;

      native.server.send(socket, data, opcode, undefined, true);
    });
  });

  native.server.group.onDisconnection(group, (socket, code, msg, spark) => {
    native.clearUserData(socket);
    spark.ultron.remove('outgoing::end');
    spark.emit('incoming::end');
  });

  native.server.group.onMessage(group, (msg, spark) => {
    //
    // Binary data is passed zero-copy as an `ArrayBuffer` so we first have to
    // convert it to a `Buffer` and then copy it to a new `Buffer`.
    //
    if ('string' !== typeof msg) msg = Buffer.from(Buffer.from(msg));

    spark.emit('incoming::data', msg);
  });

  native.server.group.onPing(group, (msg, spark) => spark.emit('incoming::pong'));

  //
  // Listen to upgrade requests.
  //
  this.on('upgrade', (req, soc) => {
    const secKey = req.headers['sec-websocket-key'];

    if (soc.readable && soc.writable && secKey && secKey.length === 24) {
      soc.setNoDelay(opts.noDelay);

      let socketHandle = soc._handle;
      let sslState = null;

      if (soc.ssl) {
        socketHandle = soc._parent._handle;
        sslState = soc.ssl._external;
      }

      const ticket = native.transfer(
        socketHandle.fd === -1 ? socketHandle : socketHandle.fd,
        sslState
      );

      soc.on('close', () => {
        upgradeReq = req;
        native.upgrade(
          group,
          ticket,
          secKey,
          req.headers['sec-websocket-extensions']
        );

        //
        // Delete references to destroyed socket.
        //
        req.client = req.connection = req.socket = null;
        upgradeReq = null;
      });
    }

    soc.destroy();
  });

  //
  // Listen to non-upgrade requests.
  //
  this.on('request', (req, res) => {
    res.writeHead(426, { 'content-type': 'text/plain' });
    res.end(http.STATUS_CODES[426]);
  });

  this.once('close', () => native.server.group.close(group));
};
<commit_msg>[fix] Fix permessage-deflate options handling in uws transformer<commit_after>'use strict';

const http = require('http');
const url = require('url');
const uws = require('uws');

const native = uws.native;

//
// uws v0.12.0+ needs a set "no operation" callback.
//
if (native.setNoop) native.setNoop(() => {});

/**
 * Server of µWebSockets transformer.
 *
 * @runat server
 * @api private
 */
module.exports = function server() {
  const opts = Object.assign({
    perMessageDeflate: !!this.primus.options.compression,
    maxPayload: this.primus.options.maxLength
  }, this.primus.options.transport);

  let flags = 0;

  if (opts.perMessageDeflate) {
    flags |= uws.PERMESSAGE_DEFLATE;
    if (opts.perMessageDeflate.serverNoContextTakeover === false) {
      flags |= uws.SLIDING_DEFLATE_WINDOW;
    }
  }

  const group = native.server.group.create(flags, opts.maxPayload);
  let upgradeReq = null;

  native.server.group.onConnection(group, (socket) => {
    const spark = new this.Spark(
      upgradeReq.headers,               // HTTP request headers.
      upgradeReq,                       // IP address location.
      url.parse(upgradeReq.url).query,  // Optional query string.
      null,                             // We don't have an unique id.
      upgradeReq                        // Reference to the HTTP req.
    );

    native.setUserData(socket, spark);

    spark.ultron.on('outgoing::end', () => native.server.close(socket));
    spark.on('outgoing::data', (data) => {
      const opcode = Buffer.isBuffer(data)
        ? uws.OPCODE_BINARY
        : uws.OPCODE_TEXT;

      native.server.send(socket, data, opcode, undefined, true);
    });
  });

  native.server.group.onDisconnection(group, (socket, code, msg, spark) => {
    native.clearUserData(socket);
    spark.ultron.remove('outgoing::end');
    spark.emit('incoming::end');
  });

  native.server.group.onMessage(group, (msg, spark) => {
    //
    // Binary data is passed zero-copy as an `ArrayBuffer` so we first have to
    // convert it to a `Buffer` and then copy it to a new `Buffer`.
    //
    if ('string' !== typeof msg) msg = Buffer.from(Buffer.from(msg));

    spark.emit('incoming::data', msg);
  });

  native.server.group.onPing(group, (msg, spark) => spark.emit('incoming::pong'));

  //
  // Listen to upgrade requests.
  //
  this.on('upgrade', (req, soc) => {
    const secKey = req.headers['sec-websocket-key'];

    if (soc.readable && soc.writable && secKey && secKey.length === 24) {
      soc.setNoDelay(opts.noDelay);

      let socketHandle = soc._handle;
      let sslState = null;

      if (soc.ssl) {
        socketHandle = soc._parent._handle;
        sslState = soc.ssl._external;
      }

      const ticket = native.transfer(
        socketHandle.fd === -1 ? socketHandle : socketHandle.fd,
        sslState
      );

      soc.on('close', () => {
        upgradeReq = req;
        native.upgrade(
          group,
          ticket,
          secKey,
          req.headers['sec-websocket-extensions']
        );

        //
        // Delete references to destroyed socket.
        //
        req.client = req.connection = req.socket = null;
        upgradeReq = null;
      });
    }

    soc.destroy();
  });

  //
  // Listen to non-upgrade requests.
  //
  this.on('request', (req, res) => {
    res.writeHead(426, { 'content-type': 'text/plain' });
    res.end(http.STATUS_CODES[426]);
  });

  this.once('close', () => native.server.group.close(group));
};
<|endoftext|>


<commit_before>var orsay = require('cordova/platform');

module.exports = {
    getDeviceInfo: function(success, error) {
        try {
            setTimeout(function{
                success({
                    cordova: orsay.cordovaVersion,
                    platform: 'sectv-orsay',
                    model: webapis.tv.info.getModel(), // "15_HAWKP_UHD"
                    version: webapis.tv.info.getFirmware(), // "T-HKPAKUC-0017.10"
                    uuid: webapis.tv.info.getDeviceID(), // "U7CJYBPYKOKD6"
                    manufacturer : "Samsung Orsay TV"
                });
            },0);
        } catch (e) {
            setTimeout(function{
                error (e);
            },0);
        }
    }
};

require("cordova/exec/proxy").add("Device", module.exports);<commit_msg>bug fix in plugin device<commit_after>var orsay = require('cordova/platform');

module.exports = {
    getDeviceInfo: function(success, error) {
        try {
            setTimeout(function(){
                success({
                    cordova: orsay.cordovaVersion,
                    platform: 'sectv-orsay',
                    model: webapis.tv.info.getModel(), // "15_HAWKP_UHD"
                    version: webapis.tv.info.getFirmware(), // "T-HKPAKUC-0017.10"
                    uuid: webapis.tv.info.getDeviceID(), // "U7CJYBPYKOKD6"
                    manufacturer : "Samsung Orsay TV"
                });
            },0);
        } catch (e) {
            setTimeout(function(){
                error (e);
            },0);
        }
    }
};

require("cordova/exec/proxy").add("Device", module.exports);<|endoftext|>


<commit_before>// This file contains global variables and functions.  This file
// should be minimized and abstracted whenever possible.  It is
// best to refrain from adding new variables/functions to this
// file.

var wait_for_input;
var edit_popup_open = 0;
var num_orig_anno;
var global_count = 0;
var req_submit;
var submission_edited = 0; // If polygon has been edited.

// Allowable user actions:
var action_CreatePolygon = 1;
var action_RenameExistingObjects = 0;
var action_ModifyControlExistingObjects = 0;
var action_DeleteExistingObjects = 0;

// Which polygons are visible:
var view_Existing = 1;
var view_Deleted = 0;

// Flag for right-hand object list:
var view_ObjList = true;

// MT variables:
var LMbaseurl = 'http://' + window.location.host + window.location.pathname;
var MThelpPage = 'annotationTools/html/mt_instructions.html';
var externalSubmitURL = 'http://mturk.com/mturk/externalSubmit';
var externalSubmitURLsandbox = 'http://workersandbox.mturk.com/mturk/externalSubmit';
var mt_N = 'inf';

var object_choices = '...';

// Access LabelMe object field.
// i - object index
// fieldname - object field name, e.g. "name", "deleted"
function LMgetObjectField(xml,i,fieldname) {
  if(!xml.getElementsByTagName('object')[i] || !xml.getElementsByTagName('object')[i].getElementsByTagName(fieldname)[0]) return "";
  return xml.getElementsByTagName('object')[i].getElementsByTagName(fieldname)[0].innerHTML;
}

// Returns number of LabelMe objects.
function LMnumberOfObjects(xml) {
  return xml.getElementsByTagName('object').length;
}

// Get the x position of the mouse event.
function GetEventPosX(event) {
  if(IsNetscape()) return event.layerX;
  return event.offsetX;
}

// Get the y position of the mouse event.
function GetEventPosY(event) {
  if(IsNetscape()) return event.layerY;
  return event.offsetY;
}

function RemoveSpecialChars(str) {
  var re = /\$|@|#|~|`|\%|\*|\^|\&|\+|\=|\[|\]|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$/g;
  return str.replace(re,"_");
}

function WaitForInput() {
  alert("Need to enter object name.");
}

// Return true if the username is "anonymous".
function IsUserAnonymous() {
  return (username=='anonymous');
}

function IsUserAdmin() {
  var is_admin = false;
  var folder = main_media.GetFileInfo().GetDirName();
  var idx = folder.indexOf('/');
  if((idx != -1) && (folder.substring(0,idx)=='users')) {
    folder = folder.substring(idx+1,folder.length);
    idx = folder.indexOf('/');
    if((idx != -1) && (folder.substring(0,idx)==username)) is_admin = true;
  }
  return (username=='admin') | (username=='mtsupervisor') | is_admin | ((username.indexOf('submitted')!=-1)&(username==folder));
}

function IsCreator(u) {
  return (username==u);
}

function WriteLogMsg(msg) {
  var url = 'annotationTools/perl/write_logfile.cgi';
  var req_submit;
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_submit = new XMLHttpRequest();
    req_submit.open("POST", url, true);
    req_submit.send(msg);
  }
  else if (window.ActiveXObject) {
    req_submit = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_submit) {
      req_submit.open("POST", url, true);
      req_submit.send(msg);
    }
  }
}

// This function gets called when the user clicks on the "Next image" button.
function ShowNextImage() {
  if(wait_for_input) return WaitForInput();
  if(draw_anno) {
    alert("Need to close current polygon first.");
    return;
  }

  // Remove the image:
  $('#main_media').remove();

  // Remove the object list:
  RemoveObjectList();

  // Get a new image and reset URL to reflect new image:
  main_media.GetFileInfo().SetURL(document.URL);
}

function XMLGet(fname) {
  var url = 'annotationTools/perl/get_anno_file.cgi';
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_anno = new XMLHttpRequest();
    req_anno.open("POST", url, false);
    req_anno.send(fname);
  }
  else if (window.ActiveXObject) {
    req_anno = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_anno) {
      req_anno.open("POST", url, false);
      req_anno.send(fname);
    }
  }
  return req_anno;
}

function InsertServerLogData(modifiedControlPoints) {
  var old_pri = LM_xml.getElementsByTagName("private");
  for(ii=0;ii<old_pri.length;ii++) {
    old_pri[ii].parentNode.removeChild(old_pri[ii]);
  }

  // Add information to go into the log:
  var elt_pri = LM_xml.createElement("private");
  var elt_gct = LM_xml.createElement("global_count");
  var elt_user = LM_xml.createElement("pri_username");
  var elt_edt = LM_xml.createElement("edited");
  var elt_onm = LM_xml.createElement("old_name");
  var elt_nnm = LM_xml.createElement("new_name");
  var elt_mcp = LM_xml.createElement("modified_cpts");

  var txt_gct = LM_xml.createTextNode(global_count);
  var txt_user = LM_xml.createTextNode(username);
  var txt_edt = LM_xml.createTextNode(submission_edited);
  var txt_onm = LM_xml.createTextNode(old_name);
  var txt_nnm = LM_xml.createTextNode(new_name);
  var txt_mcp = LM_xml.createTextNode(modifiedControlPoints);
  var txt_pri = LM_xml.createTextNode(ref);

  LM_xml.documentElement.appendChild(elt_pri);
  elt_pri.appendChild(elt_gct);
  elt_pri.appendChild(elt_user);
  elt_pri.appendChild(elt_edt);
  elt_pri.appendChild(elt_onm);
  elt_pri.appendChild(elt_nnm);
  elt_pri.appendChild(elt_mcp);
  elt_pri.appendChild(txt_pri);

  elt_gct.appendChild(txt_gct);
  elt_user.appendChild(txt_user);
  elt_edt.appendChild(txt_edt);
  elt_onm.appendChild(txt_onm);
  elt_nnm.appendChild(txt_nnm);
  elt_mcp.appendChild(txt_mcp);
}

function PermissionError() {
  var m = main_media.GetFileInfo().GetMode();
  if((m=='im') || (m=='mt')) {
    alert('This polygon was entered by another user.  You can only modify polygons that you have entered.');
  }
  else {
    alert('This polygon was entered by another user.  You can only modify polygons that you have entered.  Do not forget to sign in if you want to be able to edit your annotations');
  }
}

function GetTimeStamp() {
  var url = 'annotationTools/perl/get_timestamp.cgi';
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_anno = new XMLHttpRequest();
    req_anno.open("POST", url, false);
    req_anno.send();
  }
  else if (window.ActiveXObject) {
    req_anno = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_anno) {
      req_anno.open("POST", url, false);
      req_anno.send();
    }
  }

  if(req_anno.status==200) return req_anno.responseText;
  return '';
}

// Set object list choices for points and lines:
function SetObjectChoicesPointLine(num_control_points) {
  // If point has been labeled, then make autocomplete have "point"
  // be option:
  var isPoint = 0;
  if((num_control_points==1) && (object_choices=='...')) {
    object_choices = 'point';
    object_choices = object_choices.split(/,/);
    isPoint = 1;
  }

  // If line has been labeled, then make autocomplete have "line"
  // and "horizon line" be options:
  var isLine = 0;
  if((num_control_points==2) && (object_choices=='...')) {
    object_choices = 'line,horizon line';
    object_choices = object_choices.split(/,/);
    isLine = 1;
  }

  return (isPoint || isLine);
}

// Returns true if the point (x,y) is close to polygon p.
function IsNearPolygon(x,y,p) {
  var sx = x / main_media.GetImRatio();
  var sy = y / main_media.GetImRatio();

  var pt = AllAnnotations[p].ClosestPoint(sx,sy);
  var minDist = pt[2];

  // This is the sensitivity area around the outline of the polygon.
  // Also, when you move the mouse over the sensitivity area, the area
  // gets bigger so you won't move off of it on accident.
  var buffer = 5;
  if(selected_poly != -1) buffer = 13;

  // Note: need to multiply by im_ratio so that the sensitivity area
  // is not huge when you're zoomed in.
  return ((minDist*main_media.GetImRatio()) < buffer);
}

// Render filled polygons for selected objects:
function selectObject(idx) {
  if(selected_poly==idx) return;
  unselectObjects();
  selected_poly = idx;
  if(view_ObjList) ChangeLinkColorFG(idx);
  AllAnnotations[selected_poly].FillPolygon();

  // Select object parts:
  var selected_poly_parts = getPartChildrens(idx);
  for (var i=0; i<selected_poly_parts.length; i++) {
    if((selected_poly_parts[i]!=selected_poly) && AllAnnotations[selected_poly_parts[i]].hidden) {
      AllAnnotations[selected_poly_parts[i]].DrawPolygon(main_media.GetImRatio());
    }
    AllAnnotations[selected_poly_parts[i]].FillPolygon();
  }
}

// Stop fill polygon rendering for selected objects:
function unselectObjects() {
  if(selected_poly == -1) return;
  if(view_ObjList) ChangeLinkColorBG(selected_poly);
  AllAnnotations[selected_poly].UnfillPolygon();

  // Unselect object parts:
  var selected_poly_parts = getPartChildrens(selected_poly);
  for (var i=0; i<selected_poly_parts.length; i++) {
    if((selected_poly_parts[i]!=selected_poly) && AllAnnotations[selected_poly_parts[i]].hidden) {
      AllAnnotations[selected_poly_parts[i]].DeletePolygon();
    }
    AllAnnotations[selected_poly_parts[i]].UnfillPolygon();
  }

  // Reset selected_poly variable:
  selected_poly = -1;
}

// Deletes the currently selected polygon from the canvas.
function DeleteSelectedPolygon() {
  if(selected_poly == -1) return;

  if((IsUserAnonymous() || (!IsCreator(AllAnnotations[selected_poly].GetUsername()))) && (!IsUserAdmin()) && (selected_poly<num_orig_anno) && !action_DeleteExistingObjects) {
    alert('You do not have permission to delete this polygon');
    return;
  }

  if(AllAnnotations[selected_poly].GetVerified()) {
    StartEditEvent(selected_poly,null);
    return;
  }

  submission_edited = 0;
  old_name = LMgetObjectField(LM_xml,AllAnnotations[selected_poly].anno_id,'name');
  new_name = old_name;

  // Write to logfile:
  WriteLogMsg('*Deleting_object');
  InsertServerLogData('cpts_not_modified');

  // Set <deleted> in LM_xml:
  $(LM_xml).children("annotation").children("object").eq(selected_poly).children("deleted").text('1');

  // Write XML to server:
  WriteXML(SubmitXmlUrl,LM_xml,function(){return;});

  //     SubmitAnnotations(0);

  // Need to keep track of the selected polygon since it gets reset
  // in the next step:
  var ndx = selected_poly;

  // Unselect the object:
  unselectObjects();
  if(view_ObjList) RenderObjectList();

  // Delete the polygon from the canvas:
  AllAnnotations[ndx].DeletePolygon();
}

// UTILITIES
function CheckXMLExists() {
  if(req_submit.readyState==4) {
    if(req_submit.status != 200) {
      alert("The XML annotation file does not exist yet.  Please label an object and try again");
    }
    else {
      window.open(main_media.GetFileInfo().GetAnnotationPath());
    }
  }
}

function GetXMLFile() {
  var xml_url = main_media.GetFileInfo().GetAnnotationPath();

  // Check if VRML file exists:
  if (window.XMLHttpRequest) {
    req_submit = new XMLHttpRequest();
    req_submit.onreadystatechange = CheckXMLExists;
    req_submit.open("GET", xml_url, true);
    req_submit.send('');
  }
  else if (window.ActiveXObject) {
    req_submit = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_submit) {
      req_submit.onreadystatechange = CheckXMLExists;
      req_submit.open("GET", xml_url, true);
      req_submit.send('');
    }
  }
}

<commit_msg>Removed XMLGet since it is no longer used<commit_after>// This file contains global variables and functions.  This file
// should be minimized and abstracted whenever possible.  It is
// best to refrain from adding new variables/functions to this
// file.

var wait_for_input;
var edit_popup_open = 0;
var num_orig_anno;
var global_count = 0;
var req_submit;
var submission_edited = 0; // If polygon has been edited.

// Allowable user actions:
var action_CreatePolygon = 1;
var action_RenameExistingObjects = 0;
var action_ModifyControlExistingObjects = 0;
var action_DeleteExistingObjects = 0;

// Which polygons are visible:
var view_Existing = 1;
var view_Deleted = 0;

// Flag for right-hand object list:
var view_ObjList = true;

// MT variables:
var LMbaseurl = 'http://' + window.location.host + window.location.pathname;
var MThelpPage = 'annotationTools/html/mt_instructions.html';
var externalSubmitURL = 'http://mturk.com/mturk/externalSubmit';
var externalSubmitURLsandbox = 'http://workersandbox.mturk.com/mturk/externalSubmit';
var mt_N = 'inf';

var object_choices = '...';

// Access LabelMe object field.
// i - object index
// fieldname - object field name, e.g. "name", "deleted"
function LMgetObjectField(xml,i,fieldname) {
  if(!xml.getElementsByTagName('object')[i] || !xml.getElementsByTagName('object')[i].getElementsByTagName(fieldname)[0]) return "";
  return xml.getElementsByTagName('object')[i].getElementsByTagName(fieldname)[0].innerHTML;
}

// Returns number of LabelMe objects.
function LMnumberOfObjects(xml) {
  return xml.getElementsByTagName('object').length;
}

// Get the x position of the mouse event.
function GetEventPosX(event) {
  if(IsNetscape()) return event.layerX;
  return event.offsetX;
}

// Get the y position of the mouse event.
function GetEventPosY(event) {
  if(IsNetscape()) return event.layerY;
  return event.offsetY;
}

function RemoveSpecialChars(str) {
  var re = /\$|@|#|~|`|\%|\*|\^|\&|\+|\=|\[|\]|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$/g;
  return str.replace(re,"_");
}

function WaitForInput() {
  alert("Need to enter object name.");
}

// Return true if the username is "anonymous".
function IsUserAnonymous() {
  return (username=='anonymous');
}

function IsUserAdmin() {
  var is_admin = false;
  var folder = main_media.GetFileInfo().GetDirName();
  var idx = folder.indexOf('/');
  if((idx != -1) && (folder.substring(0,idx)=='users')) {
    folder = folder.substring(idx+1,folder.length);
    idx = folder.indexOf('/');
    if((idx != -1) && (folder.substring(0,idx)==username)) is_admin = true;
  }
  return (username=='admin') | (username=='mtsupervisor') | is_admin | ((username.indexOf('submitted')!=-1)&(username==folder));
}

function IsCreator(u) {
  return (username==u);
}

function WriteLogMsg(msg) {
  var url = 'annotationTools/perl/write_logfile.cgi';
  var req_submit;
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_submit = new XMLHttpRequest();
    req_submit.open("POST", url, true);
    req_submit.send(msg);
  }
  else if (window.ActiveXObject) {
    req_submit = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_submit) {
      req_submit.open("POST", url, true);
      req_submit.send(msg);
    }
  }
}

// This function gets called when the user clicks on the "Next image" button.
function ShowNextImage() {
  if(wait_for_input) return WaitForInput();
  if(draw_anno) {
    alert("Need to close current polygon first.");
    return;
  }

  // Remove the image:
  $('#main_media').remove();

  // Remove the object list:
  RemoveObjectList();

  // Get a new image and reset URL to reflect new image:
  main_media.GetFileInfo().SetURL(document.URL);
}

function InsertServerLogData(modifiedControlPoints) {
  var old_pri = LM_xml.getElementsByTagName("private");
  for(ii=0;ii<old_pri.length;ii++) {
    old_pri[ii].parentNode.removeChild(old_pri[ii]);
  }

  // Add information to go into the log:
  var elt_pri = LM_xml.createElement("private");
  var elt_gct = LM_xml.createElement("global_count");
  var elt_user = LM_xml.createElement("pri_username");
  var elt_edt = LM_xml.createElement("edited");
  var elt_onm = LM_xml.createElement("old_name");
  var elt_nnm = LM_xml.createElement("new_name");
  var elt_mcp = LM_xml.createElement("modified_cpts");

  var txt_gct = LM_xml.createTextNode(global_count);
  var txt_user = LM_xml.createTextNode(username);
  var txt_edt = LM_xml.createTextNode(submission_edited);
  var txt_onm = LM_xml.createTextNode(old_name);
  var txt_nnm = LM_xml.createTextNode(new_name);
  var txt_mcp = LM_xml.createTextNode(modifiedControlPoints);
  var txt_pri = LM_xml.createTextNode(ref);

  LM_xml.documentElement.appendChild(elt_pri);
  elt_pri.appendChild(elt_gct);
  elt_pri.appendChild(elt_user);
  elt_pri.appendChild(elt_edt);
  elt_pri.appendChild(elt_onm);
  elt_pri.appendChild(elt_nnm);
  elt_pri.appendChild(elt_mcp);
  elt_pri.appendChild(txt_pri);

  elt_gct.appendChild(txt_gct);
  elt_user.appendChild(txt_user);
  elt_edt.appendChild(txt_edt);
  elt_onm.appendChild(txt_onm);
  elt_nnm.appendChild(txt_nnm);
  elt_mcp.appendChild(txt_mcp);
}

function PermissionError() {
  var m = main_media.GetFileInfo().GetMode();
  if((m=='im') || (m=='mt')) {
    alert('This polygon was entered by another user.  You can only modify polygons that you have entered.');
  }
  else {
    alert('This polygon was entered by another user.  You can only modify polygons that you have entered.  Do not forget to sign in if you want to be able to edit your annotations');
  }
}

function GetTimeStamp() {
  var url = 'annotationTools/perl/get_timestamp.cgi';
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_anno = new XMLHttpRequest();
    req_anno.open("POST", url, false);
    req_anno.send();
  }
  else if (window.ActiveXObject) {
    req_anno = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_anno) {
      req_anno.open("POST", url, false);
      req_anno.send();
    }
  }

  if(req_anno.status==200) return req_anno.responseText;
  return '';
}

// Set object list choices for points and lines:
function SetObjectChoicesPointLine(num_control_points) {
  // If point has been labeled, then make autocomplete have "point"
  // be option:
  var isPoint = 0;
  if((num_control_points==1) && (object_choices=='...')) {
    object_choices = 'point';
    object_choices = object_choices.split(/,/);
    isPoint = 1;
  }

  // If line has been labeled, then make autocomplete have "line"
  // and "horizon line" be options:
  var isLine = 0;
  if((num_control_points==2) && (object_choices=='...')) {
    object_choices = 'line,horizon line';
    object_choices = object_choices.split(/,/);
    isLine = 1;
  }

  return (isPoint || isLine);
}

// Returns true if the point (x,y) is close to polygon p.
function IsNearPolygon(x,y,p) {
  var sx = x / main_media.GetImRatio();
  var sy = y / main_media.GetImRatio();

  var pt = AllAnnotations[p].ClosestPoint(sx,sy);
  var minDist = pt[2];

  // This is the sensitivity area around the outline of the polygon.
  // Also, when you move the mouse over the sensitivity area, the area
  // gets bigger so you won't move off of it on accident.
  var buffer = 5;
  if(selected_poly != -1) buffer = 13;

  // Note: need to multiply by im_ratio so that the sensitivity area
  // is not huge when you're zoomed in.
  return ((minDist*main_media.GetImRatio()) < buffer);
}

// Render filled polygons for selected objects:
function selectObject(idx) {
  if(selected_poly==idx) return;
  unselectObjects();
  selected_poly = idx;
  if(view_ObjList) ChangeLinkColorFG(idx);
  AllAnnotations[selected_poly].FillPolygon();

  // Select object parts:
  var selected_poly_parts = getPartChildrens(idx);
  for (var i=0; i<selected_poly_parts.length; i++) {
    if((selected_poly_parts[i]!=selected_poly) && AllAnnotations[selected_poly_parts[i]].hidden) {
      AllAnnotations[selected_poly_parts[i]].DrawPolygon(main_media.GetImRatio());
    }
    AllAnnotations[selected_poly_parts[i]].FillPolygon();
  }
}

// Stop fill polygon rendering for selected objects:
function unselectObjects() {
  if(selected_poly == -1) return;
  if(view_ObjList) ChangeLinkColorBG(selected_poly);
  AllAnnotations[selected_poly].UnfillPolygon();

  // Unselect object parts:
  var selected_poly_parts = getPartChildrens(selected_poly);
  for (var i=0; i<selected_poly_parts.length; i++) {
    if((selected_poly_parts[i]!=selected_poly) && AllAnnotations[selected_poly_parts[i]].hidden) {
      AllAnnotations[selected_poly_parts[i]].DeletePolygon();
    }
    AllAnnotations[selected_poly_parts[i]].UnfillPolygon();
  }

  // Reset selected_poly variable:
  selected_poly = -1;
}

// Deletes the currently selected polygon from the canvas.
function DeleteSelectedPolygon() {
  if(selected_poly == -1) return;

  if((IsUserAnonymous() || (!IsCreator(AllAnnotations[selected_poly].GetUsername()))) && (!IsUserAdmin()) && (selected_poly<num_orig_anno) && !action_DeleteExistingObjects) {
    alert('You do not have permission to delete this polygon');
    return;
  }

  if(AllAnnotations[selected_poly].GetVerified()) {
    StartEditEvent(selected_poly,null);
    return;
  }

  submission_edited = 0;
  old_name = LMgetObjectField(LM_xml,AllAnnotations[selected_poly].anno_id,'name');
  new_name = old_name;

  // Write to logfile:
  WriteLogMsg('*Deleting_object');
  InsertServerLogData('cpts_not_modified');

  // Set <deleted> in LM_xml:
  $(LM_xml).children("annotation").children("object").eq(selected_poly).children("deleted").text('1');

  // Write XML to server:
  WriteXML(SubmitXmlUrl,LM_xml,function(){return;});

  //     SubmitAnnotations(0);

  // Need to keep track of the selected polygon since it gets reset
  // in the next step:
  var ndx = selected_poly;

  // Unselect the object:
  unselectObjects();
  if(view_ObjList) RenderObjectList();

  // Delete the polygon from the canvas:
  AllAnnotations[ndx].DeletePolygon();
}

// UTILITIES
function CheckXMLExists() {
  if(req_submit.readyState==4) {
    if(req_submit.status != 200) {
      alert("The XML annotation file does not exist yet.  Please label an object and try again");
    }
    else {
      window.open(main_media.GetFileInfo().GetAnnotationPath());
    }
  }
}

function GetXMLFile() {
  var xml_url = main_media.GetFileInfo().GetAnnotationPath();

  // Check if VRML file exists:
  if (window.XMLHttpRequest) {
    req_submit = new XMLHttpRequest();
    req_submit.onreadystatechange = CheckXMLExists;
    req_submit.open("GET", xml_url, true);
    req_submit.send('');
  }
  else if (window.ActiveXObject) {
    req_submit = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_submit) {
      req_submit.onreadystatechange = CheckXMLExists;
      req_submit.open("GET", xml_url, true);
      req_submit.send('');
    }
  }
}

<|endoftext|>