<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

var path          = require('path'),
    fs            = require('fs'),
    shell         = require('shelljs'),
    platforms     = require('../platforms'),
    help          = require('./help'),
    events        = require('./events'),
    config        = require('./config'),
    lazy_load     = require('./lazy_load'),
    Q             = require('q'),
    CordovaError  = require('./CordovaError'),
    ConfigParser = require('./ConfigParser'),
    util          = require('./util');

var DEFAULT_NAME = "HelloCordova",
    DEFAULT_ID   = "io.cordova.hellocordova";

/**
 * Usage:
 * @dir - directory where the project will be created. Required.
 * @id - app id. Optional, default is DEFAULT_ID.
 * @name - app name. Optional, default is DEFAULT_NAME.
 * @cfg - extra config to be saved in .cordova/config.json
 **/
// Returns a promise.
module.exports = function create (dir, id, name, cfg, callback) {
    if (!dir ) {
        return Q(help());
    }

    // Massage parameters
    if (typeof cfg == 'string') {
        cfg = JSON.parse(cfg);
    }
    cfg = cfg || {};
    id = id || cfg.id || DEFAULT_ID;
    name = name || cfg.name || DEFAULT_NAME;

    // Make absolute.
    dir = path.resolve(dir);

    events.emit('log', 'Creating a new cordova project with name "' + name + '" and id "' + id + '" at location "' + dir + '"');

    var www_dir = path.join(dir, 'www');

    // dir must be either empty or not exist at all.

    // dir must be either empty except for .cordova config file or not exist at all..
    var sanedircontents = function (d) {
        var contents = fs.readdirSync(d);
        if (contents.length == 0) {
            return true;
        } else if (contents.length == 1) {
            if (contents[0] == '.cordova') {
                return true;
            }
        }
        return false;
    }

    if (fs.existsSync(dir) && !sanedircontents(dir)) {
        var err = new CordovaError('Path already exists and is not empty: ' + dir);
        if (callback) {
            callback(err);
            return null;
        }
        return Q.reject(err);
    }

    // Read / Write .cordova/config.json file if necessary.
    var config_json = config(dir, cfg);

    var p;
    var symlink = false; // Whether to symlink the www dir instead of copying.
    if (config_json.lib && config_json.lib.www) {
        events.emit('log', 'Using custom www assets from '+config_json.lib.www.uri);
        // TODO (kamrik): extend lazy_load for retrieval without caching to allow net urls for --src.
        var www_version = config_json.lib.www.version || 'not_versioned';
        var www_id = config_json.lib.www.id || 'dummy_id';
        symlink  = !!config_json.lib.www.link;
        if ( www_dir.indexOf(path.resolve(config_json.lib.www.uri)) === 0 ) {
            throw new CordovaError(
                'Project must not be created inside the www assets dir.' +
                '\n    project dir:\t' + dir +
                '\n    www assets dir:\t' + config_json.lib.www.uri
            );
        }
        if(symlink) {
            p = Q(config_json.lib.www.uri);
            events.emit('verbose', 'Symlinking custom www assets into "' + www_dir + '"');
        } else {
            p = lazy_load.custom(config_json.lib.www.uri, www_id, 'www', www_version)
            .then(function(d) {
                events.emit('verbose', 'Copying custom www assets into "' + www_dir + '"');
                return d;
            });
        }
    } else {
        // Nope, so use stock cordova-hello-world-app one.
        events.emit('verbose', 'Using stock cordova hello-world application.');
        p = lazy_load.cordova('www')
        .then(function(d) {
            events.emit('verbose', 'Copying stock Cordova www assets into "' + www_dir + '"');
            return d;
        });
    }

    ret = p.then(function(www_lib) {
        // Keep going into child "www" folder if exists in stock app package.
        while (fs.existsSync(path.join(www_lib, 'www'))) {
            www_lib = path.join(www_lib, 'www');
        }

        var dirAlreadyExisted = fs.existsSync(dir);
        if (!dirAlreadyExisted) {
            shell.mkdir(dir);
        }
        if (symlink) {
            try {
                fs.symlinkSync(www_lib, www_dir, 'dir');
            } catch (e) {
                if (!dirAlreadyExisted) {
                    fs.rmdirSync(dir);
                }
                if (process.platform.slice(0, 3) == 'win' && e.code == 'EPERM')  {
                    throw new CordovaError('Symlinks on Windows require Administrator privileges');
                }
                throw e;
            }
        } else {
            shell.mkdir(www_dir);
            shell.cp('-rf', path.join(www_lib, '*'), www_dir);
        }

        // Create basic project structure.
        shell.mkdir(path.join(dir, 'platforms'));
        shell.mkdir(path.join(dir, 'merges'));
        shell.mkdir(path.join(dir, 'plugins'));
        shell.mkdir(path.join(dir, 'hooks'));

        // Add hooks README.md
        shell.cp(path.join(__dirname, '..', 'templates', 'hooks-README.md'), path.join(dir, 'hooks', 'README.md'));

        var configPath = util.projectConfig(dir);
        // Add template config.xml for apps that are missing it
        if (!fs.existsSync(configPath)) {
            var template_config_xml = path.join(__dirname, '..', 'templates', 'config.xml');
            shell.cp(template_config_xml, configPath);
            // Write out id and name to config.xml
            var config = new ConfigParser(configPath);
            config.setPackageName(id);
            config.setName(name);
            config.write();
        }
    });

    if (callback) {
        return null;
    }

    return ret;
};
<commit_msg>CB-6338 Improve error for missing template<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

var path          = require('path'),
    fs            = require('fs'),
    shell         = require('shelljs'),
    platforms     = require('../platforms'),
    help          = require('./help'),
    events        = require('./events'),
    config        = require('./config'),
    lazy_load     = require('./lazy_load'),
    Q             = require('q'),
    CordovaError  = require('./CordovaError'),
    ConfigParser = require('./ConfigParser'),
    util          = require('./util');

var DEFAULT_NAME = "HelloCordova",
    DEFAULT_ID   = "io.cordova.hellocordova";

/**
 * Usage:
 * @dir - directory where the project will be created. Required.
 * @id - app id. Optional, default is DEFAULT_ID.
 * @name - app name. Optional, default is DEFAULT_NAME.
 * @cfg - extra config to be saved in .cordova/config.json
 **/
// Returns a promise.
module.exports = function create (dir, id, name, cfg, callback) {
    if (!dir ) {
        return Q(help());
    }

    // Massage parameters
    if (typeof cfg == 'string') {
        cfg = JSON.parse(cfg);
    }
    cfg = cfg || {};
    id = id || cfg.id || DEFAULT_ID;
    name = name || cfg.name || DEFAULT_NAME;

    // Make absolute.
    dir = path.resolve(dir);

    events.emit('log', 'Creating a new cordova project with name "' + name + '" and id "' + id + '" at location "' + dir + '"');

    var www_dir = path.join(dir, 'www');

    // dir must be either empty or not exist at all.

    // dir must be either empty except for .cordova config file or not exist at all..
    var sanedircontents = function (d) {
        var contents = fs.readdirSync(d);
        if (contents.length == 0) {
            return true;
        } else if (contents.length == 1) {
            if (contents[0] == '.cordova') {
                return true;
            }
        }
        return false;
    }

    if (fs.existsSync(dir) && !sanedircontents(dir)) {
        var err = new CordovaError('Path already exists and is not empty: ' + dir);
        if (callback) {
            callback(err);
            return null;
        }
        return Q.reject(err);
    }

    // Read / Write .cordova/config.json file if necessary.
    var config_json = config(dir, cfg);

    var p;
    var symlink = false; // Whether to symlink the www dir instead of copying.
    if (config_json.lib && config_json.lib.www) {
        events.emit('log', 'Using custom www assets from '+config_json.lib.www.uri);
        // TODO (kamrik): extend lazy_load for retrieval without caching to allow net urls for --src.
        var www_version = config_json.lib.www.version || 'not_versioned';
        var www_id = config_json.lib.www.id || 'dummy_id';
        symlink  = !!config_json.lib.www.link;
        if ( www_dir.indexOf(path.resolve(config_json.lib.www.uri)) === 0 ) {
            throw new CordovaError(
                'Project must not be created inside the www assets dir.' +
                '\n    project dir:\t' + dir +
                '\n    www assets dir:\t' + config_json.lib.www.uri
            );
        }
        if(symlink) {
            p = Q(config_json.lib.www.uri);
            events.emit('verbose', 'Symlinking custom www assets into "' + www_dir + '"');
        } else {
            p = lazy_load.custom(config_json.lib.www.uri, www_id, 'www', www_version)
            .then(function(d) {
                events.emit('verbose', 'Copying custom www assets into "' + www_dir + '"');
                return d;
            });
        }
    } else {
        // Nope, so use stock cordova-hello-world-app one.
        events.emit('verbose', 'Using stock cordova hello-world application.');
        p = lazy_load.cordova('www')
        .then(function(d) {
            events.emit('verbose', 'Copying stock Cordova www assets into "' + www_dir + '"');
            return d;
        });
    }

    ret = p.then(function(www_lib) {
        if (!fs.existsSync(www_lib)) {
            throw new CordovaError('Could not find directory: '+www_lib);
        }
        // Keep going into child "www" folder if exists in stock app package.
        while (fs.existsSync(path.join(www_lib, 'www'))) {
            www_lib = path.join(www_lib, 'www');
        }

        var dirAlreadyExisted = fs.existsSync(dir);
        if (!dirAlreadyExisted) {
            shell.mkdir(dir);
        }
        if (symlink) {
            try {
                fs.symlinkSync(www_lib, www_dir, 'dir');
            } catch (e) {
                if (!dirAlreadyExisted) {
                    fs.rmdirSync(dir);
                }
                if (process.platform.slice(0, 3) == 'win' && e.code == 'EPERM')  {
                    throw new CordovaError('Symlinks on Windows require Administrator privileges');
                }
                throw e;
            }
        } else {
            shell.mkdir(www_dir);
            shell.cp('-rf', path.join(www_lib, '*'), www_dir);
        }

        // Create basic project structure.
        shell.mkdir(path.join(dir, 'platforms'));
        shell.mkdir(path.join(dir, 'merges'));
        shell.mkdir(path.join(dir, 'plugins'));
        shell.mkdir(path.join(dir, 'hooks'));

        // Add hooks README.md
        shell.cp(path.join(__dirname, '..', 'templates', 'hooks-README.md'), path.join(dir, 'hooks', 'README.md'));

        var configPath = util.projectConfig(dir);
        // Add template config.xml for apps that are missing it
        if (!fs.existsSync(configPath)) {
            var template_config_xml = path.join(__dirname, '..', 'templates', 'config.xml');
            shell.cp(template_config_xml, configPath);
            // Write out id and name to config.xml
            var config = new ConfigParser(configPath);
            config.setPackageName(id);
            config.setName(name);
            config.write();
        }
    });

    if (callback) {
        return null;
    }

    return ret;
};
<|endoftext|>


<commit_before>import { Command } from 'azk/cli/command';
import Azk from 'azk';

class HelpCmd extends Command {
  action(opts) {
    this.output("Azk %s", Azk.version);
    return 0;
  }
}

export function init(cli) {
  (new HelpCmd('version', cli))
}
<commit_msg>[azk lowercase] Showing azk in lowercase at azk version command #222<commit_after>import { Command } from 'azk/cli/command';
import Azk from 'azk';

class HelpCmd extends Command {
  action(opts) {
    this.output("azk %s", Azk.version);
    return 0;
  }
}

export function init(cli) {
  (new HelpCmd('version', cli))
}
<|endoftext|>


<commit_before>var Csw4js = {};

Csw4js.version = '0.0.1';

Csw4js.Ows = {};
Csw4js.Fes = {};

Csw4js.NOTIE = true; // here's hoping

Csw4js.Proxy = '/cgi-bin/proxy.cgi?url=';
Csw4js.Util = {};

if (window.ActiveXObject) {
    Csw4js.NOTIE = false;
}

Csw4js.Namespaces = {
    'csw': 'http://www.opengis.net/cat/csw/2.0.2',
    'ogc': 'http://www.opengis.net/ogc',
    'ows': 'http://www.opengis.net/ows',
    'xlink': 'http://www.w3.org/1999/xlink'
};

Csw4js.nsResolver = function(prefix) {
    return Csw4js.Namespaces[prefix] || null;
};

Csw4js.getXPathNode = function(doc, xpath) {
    var evaluator = new XPathEvaluator();
    var result = evaluator.evaluate(xpath, doc, Csw4js.nsResolver,
                                    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    return result.singleNodeValue;
};

Csw4js.getXPathNodeList = function(doc, xpath) {
    var evaluator = new XPathEvaluator();
    var iter = evaluator.evaluate(xpath, doc, Csw4js.nsResolver,
                                  XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
    return iter;
};
Csw4js.getXPathValue = function(doc, xpath) {
    var evaluator = new XPathEvaluator();
    var result = evaluator.evaluate(xpath, doc, Csw4js.nsResolver,
                                    XPathResult.STRING_TYPE, null);
    return result.stringValue;
};

Csw4js.getXPathValueList = function(doc, xpath) {
    var list = [];
    var evaluator = new XPathEvaluator();
    var iter = evaluator.evaluate(xpath, doc, Csw4js.nsResolver,
                                  XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
    var node = iter.iterateNext();
    while (node) {
        list.push(node.textContent);
        node = iter.iterateNext();
    }
    return list;
};

Csw4js.Ows.ServiceIdentification = function(node) {
    this.title = Csw4js.getXPathValue(node, 'ows:Title');
    this.abstract = Csw4js.getXPathValue(node, 'ows:Abstract');
    this.keywords = Csw4js.getXPathValueList(node, 'ows:Keywords/ows:Keyword');
    this.type = Csw4js.getXPathValue(node, 'ows:ServiceType');
    this.version = Csw4js.getXPathValue(node, 'ows:ServiceTypeVersion');
    this.fees = Csw4js.getXPathValue(node, 'ows:Fees');
    this.accessconstraints = Csw4js.getXPathValue(node,
        'ows:AccessConstraints');
};

Csw4js.Ows.ServiceProvider = function(node) {
    this.name = Csw4js.getXPathValue(node, 'ows:ProviderName');
    this.url = Csw4js.getXPathValue(node, 'ows:ProviderSite/@xlink:href');

    var contact = Csw4js.getXPathNode(node, 'ows:ServiceContact');

    this.contact = {};
    this.contact.name = Csw4js.getXPathValue(contact, 'ows:IndividualName');
    this.contact.position = Csw4js.getXPathValue(contact, 'ows:PositionName');
    this.contact.role = Csw4js.getXPathValue(contact, '/ows:Role');

    var info = Csw4js.getXPathNode(contact, 'ows:ContactInfo');

    this.contact.phone = Csw4js.getXPathValue(info, 'ows:Phone/ows:Voice');
    this.contact.fax = Csw4js.getXPathValue(info, 'ows:Phone/ows:Facsimile');

    this.contact.address = {};
    var address = Csw4js.getXPathNode(info, 'ows:Address');

    this.contact.address.delivery = Csw4js.getXPathValue(address,
        'ows:DeliveryPoint');
    this.contact.address.city = Csw4js.getXPathValue(address,
        'ows:City');
    this.contact.address.adminarea = Csw4js.getXPathValue(address,
        'ows:AdministrativeArea');
    this.contact.address.postalcode = Csw4js.getXPathValue(address,
        'ows:PostalCode');
    this.contact.address.country = Csw4js.getXPathValue(address,
        'ows:Country');
    this.contact.address.email = Csw4js.getXPathValue(address,
        'ows:ElectronicMailAddress');

    this.contact.url = Csw4js.getXPathValue(info,
        'ows:OnlineResource/@xlink:href');
    this.contact.hours = Csw4js.getXPathValue(info, 'ows:HoursOfService');
    this.contact.instructions = Csw4js.getXPathValue(info,
        'ows:ContactInstructions');
};

Csw4js.Ows.OperationsMetadata = function(node) {
    var iter = null;
    var iter2 = null;
    var member = null;
    var member2 = null;
    var operation = null;
    var param = null;
    this.operations = [];
    this.parameters = [];
    this.constraints = [];

    iter = Csw4js.getXPathNodeList(node, 'ows:Operation');
    member = iter.iterateNext();
    while (member) {
        operation = {};
        operation.name = Csw4js.getXPathValue(member, '@name');
        operation.dcp = {'http': {}};
        operation.dcp.http.get = Csw4js.getXPathValue(member,
            'ows:DCP/ows:HTTP/ows:Get/@xlink:href');
        operation.dcp.http.post = Csw4js.getXPathValue(member,
            'ows:DCP/ows:HTTP/ows:Post/@xlink:href');

        operation.parameters = [];

        iter2 = Csw4js.getXPathNodeList(member, 'ows:Parameter');
        member2 = iter2.iterateNext();
        while (member2) {
            param = {};
            param.name = Csw4js.getXPathValue(member2, '@name');
            param.values = Csw4js.getXPathValueList(member2, 'ows:Value');
            operation.parameters.push(param);
            member2 = iter2.iterateNext();
        }

        operation.constraints = [];

        iter2 = Csw4js.getXPathNodeList(member, 'ows:Constraint');
        member2 = iter2.iterateNext();
        while (member2) {
            param = {};
            param.name = Csw4js.getXPathValue(member2, '@name');
            param.values = Csw4js.getXPathValueList(member2, 'ows:Value');
            operation.parameters.push(param);
            member2 = iter2.iterateNext();
        }
        this.operations.push(operation);
        member = iter.iterateNext();
    }

    iter = Csw4js.getXPathNodeList(node, 'ows:Parameter');
    member = iter.iterateNext();
    while (member) {
        param = {};
        param.name = Csw4js.getXPathValue(member, '@name');
        param.values = Csw4js.getXPathValueList(member, 'ows:Value');
        this.parameters.push(param);
        member = iter.iterateNext();
    }
    iter = Csw4js.getXPathNodeList(node, 'ows:Constraint');
    member = iter.iterateNext();
    while (member) {
        param = {};
        param.name = Csw4js.getXPathValue(member, '@name');
        param.values = Csw4js.getXPathValueList(member, 'ows:Value');
        this.constraints.push(param);
        member = iter.iterateNext();
    }

};

Csw4js.Fes.FilterCapabilities = function(node) {
    this.spatials = {};
    this.scalars = {};
    this.ids = {};

    this.spatials.geometries = Csw4js.getXPathValueList(node,
        'ogc:Spatial_Capabilities/ogc:GeometryOperands/ogc:GeometryOperand');
    this.spatials.operators = Csw4js.getXPathValueList(node,
        '//ogc:SpatialOperators/ogc:SpatialOperator/@name');

    this.scalars.comparisons = Csw4js.getXPathValueList(node,
        '//ogc:ComparisonOperators/ogc:ComparisonOperator');

    this.scalars.functions = Csw4js.getXPathValueList(node,
        '//ogc:FunctionNames/ogc:FunctionName');
};

Csw4js.Csw = function(url) {
    // init by doing a GetCapabilities and parsing metadata
    var node = null;
    this.url = url;
    this.version = '2.0.2';

    var params = {
        'service': 'CSW',
        'version': this.version,
        'request': 'GetCapabilities'
    };

    if (this.url.indexOf('http') === 0) {  // it's a string
        this.xml = Csw4js.loadXMLString(Csw4js.Util.buildUrl(this.url, params));
    }
    else {  // it's a URL
        this.xml = Csw4js.loadXMLDoc(Csw4js.Util.buildUrl(this.url, params));
    }

    // TODO: error checking, etc.

    // get main sections and parse them (TODO)
    node = Csw4js.getXPathNode(this.xml, '//ows:ServiceIdentification');
    this.identification = new Csw4js.Ows.ServiceIdentification(node);

    node = Csw4js.getXPathNode(this.xml, '//ows:ServiceProvider');
    this.provider = new Csw4js.Ows.ServiceProvider(node);

    node = Csw4js.getXPathNode(this.xml, '//ows:OperationsMetadata');
    this.operationsmetadata = new Csw4js.Ows.OperationsMetadata(node);

    node = Csw4js.getXPathNode(this.xml, '//ogc:Filter_Capabilities');
    this.filtercapabilities = new Csw4js.Fes.FilterCapabilities(node);
};

Csw4js.Csw.prototype.GetRecords = function() {
    return 'GetRecords called';
};

Csw4js.Csw.prototype.GetRecordById = function(id_list, esn,
    outputformat, outputschema) {
    var params = {
        'service': 'CSW',
        'version': this.version,
        'request': 'GetRecordById',
        'outputformat': outputformat || null,
        'outputschema': outputschema || null,
        'elementsetname': esn || null,
        'id': id_list.join(',')
    };
    this.xml = Csw4js.loadXMLDoc(Csw4js.Util.buildUrl(this.url, params));
};

Csw4js.Csw.prototype.getOperationByName = function(name) {
    for(var i = 0; i < this.operationsmetadata.operations.length; i++) {
        var opname = this.operationsmetadata.operations[i].name.toLowerCase();
        if (name.toLowerCase() === opname) {
            return this.operationsmetadata.operations[i];
        }
    }
    return false;
};

// util functions

Csw4js.loadXMLDoc = function(filename) {
    var xhttp = null;
    if (Csw4js.NOTIE) {
        xhttp = new XMLHttpRequest();
    }
    else {
        xhttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    xhttp.open('GET', filename, false);
    xhttp.send();
    return xhttp.responseXML;
};

Csw4js.loadXMLString = function(txt) {
    var parser = null;
    var xmlDoc = null;

    if (Csw4js.NOTIE) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(txt, 'text/xml');
    }
    else {
        xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
        xmlDoc.async = false;
        xmlDoc.loadXML(txt);
    }
    return xmlDoc;
};

Csw4js.Util.httpGet = function(url) {
    var httpRequest;
    try {
        try {
            httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {
            httpRequest = new XMLHttpRequest();
        }
        httpRequest.open('GET', url, false);
        httpRequest.send(null);
        return httpRequest;
    } catch (e) {
        console.error('Can\'t get XML document.');
        return null;
    }
};

Csw4js.Util.httpPost = function(url, lang, request) {
    var httpRequest;
    try {
        try {
            httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {
            httpRequest = new XMLHttpRequest();
        }
        httpRequest.open('POST', url, false);
        httpRequest.setRequestHeader('Accept-Language',lang);
        httpRequest.send(request);
        return httpRequest;
    } catch (e) {
        console.error('Can\'t post XML document.');
        return null;
    }
};

Csw4js.Util.buildUrl = function(url, params) {
    var kvps = [];

    for (var key in params) {
        if (params[key] !== null) {
            kvps.push(key+'='+params[key]);
        }
    }
    return url + escape('?' + kvps.join('&'));
};
<commit_msg>refactor URL fetching, add debugging<commit_after>var Csw4js = {};

Csw4js.version = '0.0.1';

Csw4js.Ows = {};
Csw4js.Fes = {};

Csw4js.NOTIE = true; // here's hoping

Csw4js.Proxy = '/cgi-bin/proxy.cgi?url=';
Csw4js.Util = {};

if (window.ActiveXObject) {
    Csw4js.NOTIE = false;
}

Csw4js.Namespaces = {
    'csw': 'http://www.opengis.net/cat/csw/2.0.2',
    'ogc': 'http://www.opengis.net/ogc',
    'ows': 'http://www.opengis.net/ows',
    'xlink': 'http://www.w3.org/1999/xlink'
};

Csw4js.IESelectionNamespaces = function() {
    var namespaces = [];
    for(var key in Csw4js.Namespaces) {
        namespaces.push(key + ':\'' + Csw4js.Namespaces[key] + '\'');
    }
    return namespaces.join(' ');
};

Csw4js.nsResolver = function(prefix) {
    return Csw4js.Namespaces[prefix] || null;
};

Csw4js.getXPathNode = function(doc, xpath) {
    var evaluator = new XPathEvaluator();
    var result = evaluator.evaluate(xpath, doc, Csw4js.nsResolver,
                                    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    return result.singleNodeValue;
};

Csw4js.getXPathNodeList = function(doc, xpath) {
    var evaluator = new XPathEvaluator();
    var iter = evaluator.evaluate(xpath, doc, Csw4js.nsResolver,
                                  XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
    return iter;
};
Csw4js.getXPathValue = function(doc, xpath) {
    var evaluator = new XPathEvaluator();
    var result = evaluator.evaluate(xpath, doc, Csw4js.nsResolver,
                                    XPathResult.STRING_TYPE, null);
    return result.stringValue;
};

Csw4js.getXPathValueList = function(doc, xpath) {
    var list = [];
    var evaluator = new XPathEvaluator();
    var iter = evaluator.evaluate(xpath, doc, Csw4js.nsResolver,
                                  XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
    var node = iter.iterateNext();
    while (node) {
        list.push(node.textContent);
        node = iter.iterateNext();
    }
    return list;
};

Csw4js.Ows.ServiceIdentification = function(node) {
    this.title = Csw4js.getXPathValue(node, 'ows:Title');
    this.abstract = Csw4js.getXPathValue(node, 'ows:Abstract');
    this.keywords = Csw4js.getXPathValueList(node, 'ows:Keywords/ows:Keyword');
    this.type = Csw4js.getXPathValue(node, 'ows:ServiceType');
    this.version = Csw4js.getXPathValue(node, 'ows:ServiceTypeVersion');
    this.fees = Csw4js.getXPathValue(node, 'ows:Fees');
    this.accessconstraints = Csw4js.getXPathValue(node,
        'ows:AccessConstraints');
};

Csw4js.Ows.ServiceProvider = function(node) {
    this.name = Csw4js.getXPathValue(node, 'ows:ProviderName');
    this.url = Csw4js.getXPathValue(node, 'ows:ProviderSite/@xlink:href');

    var contact = Csw4js.getXPathNode(node, 'ows:ServiceContact');

    this.contact = {};
    this.contact.name = Csw4js.getXPathValue(contact, 'ows:IndividualName');
    this.contact.position = Csw4js.getXPathValue(contact, 'ows:PositionName');
    this.contact.role = Csw4js.getXPathValue(contact, '/ows:Role');

    var info = Csw4js.getXPathNode(contact, 'ows:ContactInfo');

    this.contact.phone = Csw4js.getXPathValue(info, 'ows:Phone/ows:Voice');
    this.contact.fax = Csw4js.getXPathValue(info, 'ows:Phone/ows:Facsimile');

    this.contact.address = {};
    var address = Csw4js.getXPathNode(info, 'ows:Address');

    this.contact.address.delivery = Csw4js.getXPathValue(address,
        'ows:DeliveryPoint');
    this.contact.address.city = Csw4js.getXPathValue(address,
        'ows:City');
    this.contact.address.adminarea = Csw4js.getXPathValue(address,
        'ows:AdministrativeArea');
    this.contact.address.postalcode = Csw4js.getXPathValue(address,
        'ows:PostalCode');
    this.contact.address.country = Csw4js.getXPathValue(address,
        'ows:Country');
    this.contact.address.email = Csw4js.getXPathValue(address,
        'ows:ElectronicMailAddress');

    this.contact.url = Csw4js.getXPathValue(info,
        'ows:OnlineResource/@xlink:href');
    this.contact.hours = Csw4js.getXPathValue(info, 'ows:HoursOfService');
    this.contact.instructions = Csw4js.getXPathValue(info,
        'ows:ContactInstructions');
};

Csw4js.Ows.OperationsMetadata = function(node) {
    var iter = null;
    var iter2 = null;
    var member = null;
    var member2 = null;
    var operation = null;
    var param = null;
    this.operations = [];
    this.parameters = [];
    this.constraints = [];

    iter = Csw4js.getXPathNodeList(node, 'ows:Operation');
    member = iter.iterateNext();
    while (member) {
        operation = {};
        operation.name = Csw4js.getXPathValue(member, '@name');
        operation.dcp = {'http': {}};
        operation.dcp.http.get = Csw4js.getXPathValue(member,
            'ows:DCP/ows:HTTP/ows:Get/@xlink:href');
        operation.dcp.http.post = Csw4js.getXPathValue(member,
            'ows:DCP/ows:HTTP/ows:Post/@xlink:href');

        operation.parameters = [];

        iter2 = Csw4js.getXPathNodeList(member, 'ows:Parameter');
        member2 = iter2.iterateNext();
        while (member2) {
            param = {};
            param.name = Csw4js.getXPathValue(member2, '@name');
            param.values = Csw4js.getXPathValueList(member2, 'ows:Value');
            operation.parameters.push(param);
            member2 = iter2.iterateNext();
        }

        operation.constraints = [];

        iter2 = Csw4js.getXPathNodeList(member, 'ows:Constraint');
        member2 = iter2.iterateNext();
        while (member2) {
            param = {};
            param.name = Csw4js.getXPathValue(member2, '@name');
            param.values = Csw4js.getXPathValueList(member2, 'ows:Value');
            operation.parameters.push(param);
            member2 = iter2.iterateNext();
        }
        this.operations.push(operation);
        member = iter.iterateNext();
    }

    iter = Csw4js.getXPathNodeList(node, 'ows:Parameter');
    member = iter.iterateNext();
    while (member) {
        param = {};
        param.name = Csw4js.getXPathValue(member, '@name');
        param.values = Csw4js.getXPathValueList(member, 'ows:Value');
        this.parameters.push(param);
        member = iter.iterateNext();
    }
    iter = Csw4js.getXPathNodeList(node, 'ows:Constraint');
    member = iter.iterateNext();
    while (member) {
        param = {};
        param.name = Csw4js.getXPathValue(member, '@name');
        param.values = Csw4js.getXPathValueList(member, 'ows:Value');
        this.constraints.push(param);
        member = iter.iterateNext();
    }

};

Csw4js.Fes.FilterCapabilities = function(node) {
    this.spatials = {};
    this.scalars = {};
    this.ids = {};

    this.spatials.geometries = Csw4js.getXPathValueList(node,
        'ogc:Spatial_Capabilities/ogc:GeometryOperands/ogc:GeometryOperand');
    this.spatials.operators = Csw4js.getXPathValueList(node,
        '//ogc:SpatialOperators/ogc:SpatialOperator/@name');

    this.scalars.comparisons = Csw4js.getXPathValueList(node,
        '//ogc:ComparisonOperators/ogc:ComparisonOperator');

    this.scalars.functions = Csw4js.getXPathValueList(node,
        '//ogc:FunctionNames/ogc:FunctionName');
};

Csw4js.Csw = function(url) {
    // init by doing a GetCapabilities and parsing metadata
    var node = null;
    this.url = url;
    this.version = '2.0.2';

    var params = {
        'service': 'CSW',
        'version': this.version,
        'request': 'GetCapabilities'
    };

    console.log(this.url);
    try {
        try {
            console.debug('Fetching url with params');
            this.xml = Csw4js.loadXMLDoc(
                Csw4js.Util.buildUrl(this.url, params));
        } catch (err2) {
            console.debug('Fetching url with no params (static doc)');
            this.xml = Csw4js.loadXMLDoc(this.url, params);
        }
    } catch(err) {  // string
        console.error(err);
        this.xml = Csw4js.loadXMLString(this.url, params);
    }
    // TODO: error checking, etc.

    // get main sections and parse them (TODO)
    console.debug('Procesing ows:ServiceIdentificaiton');
    node = Csw4js.getXPathNode(this.xml, '//ows:ServiceIdentification');
    this.identification = new Csw4js.Ows.ServiceIdentification(node);

    console.debug('Procesing ows:ServiceProvider');
    node = Csw4js.getXPathNode(this.xml, '//ows:ServiceProvider');
    this.provider = new Csw4js.Ows.ServiceProvider(node);

    console.debug('Procesing ows:OpeartionsMetadata');
    node = Csw4js.getXPathNode(this.xml, '//ows:OperationsMetadata');
    this.operationsmetadata = new Csw4js.Ows.OperationsMetadata(node);

    console.debug('Procesing ogc:Filter_Capabilities');
    node = Csw4js.getXPathNode(this.xml, '//ogc:Filter_Capabilities');
    this.filtercapabilities = new Csw4js.Fes.FilterCapabilities(node);
};

Csw4js.Csw.prototype.GetRecords = function() {
    return 'GetRecords called';
};

Csw4js.Csw.prototype.GetRecordById = function(id_list, esn,
    outputformat, outputschema) {
    var params = {
        'service': 'CSW',
        'version': this.version,
        'request': 'GetRecordById',
        'outputformat': outputformat || null,
        'outputschema': outputschema || null,
        'elementsetname': esn || null,
        'id': id_list.join(',')
    };

    var url = this.getOperationByName('GetRecordById').dcp.http.get;
    this.xml = Csw4js.loadXMLDoc(Csw4js.Util.buildUrl(url, params));
};

Csw4js.Csw.prototype.getOperationByName = function(name) {
    for(var i = 0; i < this.operationsmetadata.operations.length; i++) {
        var opname = this.operationsmetadata.operations[i].name.toLowerCase();
        if (name.toLowerCase() === opname) {
            return this.operationsmetadata.operations[i];
        }
    }
    return false;
};

// util functions

Csw4js.loadXMLDoc = function(url) {
    var httpRequest;
    try {  // no proxy
        console.debug('no proxy');
        httpRequest = this.Util.httpGet(url);
        console.debug('found no proxy');
        if (httpRequest.status !== 200) {
            throw 'HTTP status code ' + httpRequest.status;
        }
        return httpRequest.responseXML;
    } catch (err) {  // with proxy
        try {
            console.warn(err);
            console.debug('with proxy');
            httpRequest = this.Util.httpGet(Csw4js.Proxy + url);
            console.debug('found with proxy');
            if (httpRequest.status !== 200) {
                throw 'HTTP status code ' + httpRequest.status;
            }
            return httpRequest.responseXML;
        } catch (err2) {
            console.error(err2);
            throw 'Unable to load XML from URL';
        }
    }
};

Csw4js.loadXMLString = function(txt) {
    var parser = null;
    var xmlDoc = null;

    if (Csw4js.NOTIE) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(txt, 'text/xml');
    }
    else {
        xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
        xmlDoc.async = false;
        xmlDoc.loadXML(txt);
    }
    return xmlDoc;
};

Csw4js.Util.httpGet = function(url) {
    var httpRequest;
    try {
        try {
            httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {
            httpRequest = new XMLHttpRequest();
        }
        httpRequest.open('GET', url, false);
        httpRequest.send(null);
        return httpRequest;
    } catch (e) {
        throw e;
    }
};

Csw4js.Util.httpPost = function(url, lang, request) {
    var httpRequest;
    try {
        try {
            httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {
            httpRequest = new XMLHttpRequest();
        }
        httpRequest.open('POST', url, false);
        httpRequest.setRequestHeader('Accept-Language',lang);
        httpRequest.send(request);
        return httpRequest;
    } catch (e) {
        throw(e);
    }
};

Csw4js.Util.buildUrl = function(url, params) {
    var kvps = [];

    for (var key in params) {
        if (params[key] !== null) {
            kvps.push(key+'='+params[key]);
        }
    }
    return url + escape('?' + kvps.join('&'));
};
<|endoftext|>


<commit_before>import nowEpoch from 'binary-utils/lib/nowAsEpoch';
import durationToSecs from 'binary-utils/lib/durationToSecs';

const responseSizeLimit = 2000;

const granularities = [60, 120, 180, 300, 600, 900, 1800, 3600, 7200, 14400, 28800, 86400];
const ohlcDataToTicks = candles => candles.map(data => ({ quote: +data.open, epoch: +data.epoch }));
const hcUnitConverter = type => {
    switch (type) {
        case 'second': return 's';
        case 'minute': return 'm';
        case 'hour': return 'h';
        case 'day': return 'd';
        default: return 'd';
    }
};

const autoAdjustGetData = (api, symbol, start, end, style = 'ticks', subscribe) => {
    const secs = end - start;
    const ticksCount = secs / 2;
    if (ticksCount >= responseSizeLimit || style === 'candles') {
        const idealGranularity = secs / responseSizeLimit;
        let finalGranularity = 60;
        granularities.forEach((g, i) => {
            if (idealGranularity > g && idealGranularity <= granularities[i + 1]) {
                finalGranularity = granularities[i + 1];
            }
        });
        finalGranularity = Math.min(86400, finalGranularity);
        return api.getTickHistory(symbol,
            {
                start,
                end,
                adjust_start_time: 1,
                count: responseSizeLimit,
                style: 'candles',
                granularity: finalGranularity,
                subscribe: subscribe ? 1 : undefined,
            }
        ).then(r => {
            if (style === 'ticks') {
                return {
                    ticks: ohlcDataToTicks(r.candles),
                    symbol,
                };
            }
            return {
                candles: r.candles,
                symbol,
            };
        });
    }
    return api.getTickHistory(symbol,
        {
            start,
            end,
            adjust_start_time: 1,
            count: responseSizeLimit,
            style: 'ticks',
            subscribe: subscribe ? 1 : undefined,
        }
    ).then(r => {
        const ticks = r.history.times.map((t, idx) => {
            const quote = r.history.prices[idx];
            return { epoch: +t, quote: +quote };
        });
        return {
            ticks,
            symbol,
        };
    });
};

/**
 *
 * @param api
 * @param symbol
 * @param durationCount
 * @param durationType
 */
export function getDataForSymbol(api, symbol, durationCount = 1, durationType = 'all', style = 'ticks', subscribe) {
    const durationUnit = hcUnitConverter(durationType);
    const end = nowEpoch();
    const start = end - durationToSecs(durationCount, durationUnit);
    return autoAdjustGetData(api, symbol, start, end, style, subscribe);
}

/**
 * get data of contract
 * @param api                      - will be injected by library
 * @param getContract              - function that accept nothing and return a Promise containing contract
 * @param durationCount            - number of duration
 * @param durationType             - type of duration, check http://api.highcharts.com/highstock#rangeSelector.buttons
 * @param style                    - one of ['ticks', 'candles'], this will affect the return data shape,
 *                                   internally library might not always use this param when requesting, eg. when data is too large,
 *                                   library will use `candles` instead of `ticks`, this is handle by library so user do not need to worry
 * @param granularity              - default to 60, check https://developers.binary.com/api/#ticks_history
 * @returns {*|Promise.<TResult>}
 */
export function getDataForContract(
    api,
    getContract,
    durationCount,
    durationType = 'all',
    style = 'ticks',
    subscribe,
) {
    const getAllData = () =>
        getContract()
            .then(contract => {
                const symbol = contract.underlying;
                if (contract.tick_count) {
                    const start = +(contract.date_start) - 5;
                    const exitTime = +(contract.exit_tick_time) + 5;
                    const end = exitTime || nowEpoch();
                    return autoAdjustGetData(api, symbol, start, end, style, subscribe);
                }

                const bufferSize = 0.05;                            // 5 % buffer
                const contractStart = +(contract.date_start);
                const contractEnd = +(contract.exit_tick_time) || +(contract.date_expiry);

                // handle Contract not started yet
                if (contractStart > nowEpoch()) {
                    return autoAdjustGetData(api, symbol, nowEpoch() - 600, nowEpoch(), style, subscribe);
                }

                const buffer = (contractEnd - contractStart) * bufferSize;
                const start = buffer ? contractStart - buffer : contractStart;
                const bufferedExitTime = contractEnd + buffer;
                const end = contractEnd ? bufferedExitTime : nowEpoch();

                return autoAdjustGetData(api, symbol, Math.round(start), Math.round(end), style, subscribe);
            });

    if (durationType === 'all') {
        return getAllData();
    }

    return getContract()
        .then(contract => {
            const symbol = contract.underlying;
            const startTime = +(contract.date_start);

            // handle Contract not started yet
            if (startTime > nowEpoch()) {
                return autoAdjustGetData(api, symbol, nowEpoch() - 600, nowEpoch(), style, subscribe);
            }

            const sellT = contract.sell_time;
            const end = sellT || nowEpoch();

            const buffer = (end - startTime) * 0.05;

            const durationUnit = hcUnitConverter(durationType);
            const start = Math.min(startTime - buffer, end - durationToSecs(durationCount, durationUnit));
            return autoAdjustGetData(api, symbol, Math.round(start), Math.round(end), style, subscribe);
        });
}
<commit_msg>Reduce data to fetch from 2000 -> 700 (#63)<commit_after>import nowEpoch from 'binary-utils/lib/nowAsEpoch';
import durationToSecs from 'binary-utils/lib/durationToSecs';

const responseSizeLimit = 700;

const granularities = [60, 120, 180, 300, 600, 900, 1800, 3600, 7200, 14400, 28800, 86400];
const ohlcDataToTicks = candles => candles.map(data => ({ quote: +data.open, epoch: +data.epoch }));
const hcUnitConverter = type => {
    switch (type) {
        case 'second': return 's';
        case 'minute': return 'm';
        case 'hour': return 'h';
        case 'day': return 'd';
        default: return 'd';
    }
};

const autoAdjustGetData = (api, symbol, start, end, style = 'ticks', subscribe) => {
    const secs = end - start;
    const ticksCount = secs / 2;
    if (ticksCount >= responseSizeLimit || style === 'candles') {
        const idealGranularity = secs / responseSizeLimit;
        let finalGranularity = 60;
        granularities.forEach((g, i) => {
            if (idealGranularity > g && idealGranularity <= granularities[i + 1]) {
                finalGranularity = granularities[i + 1];
            }
        });
        finalGranularity = Math.min(86400, finalGranularity);
        return api.getTickHistory(symbol,
            {
                start,
                end,
                adjust_start_time: 1,
                count: responseSizeLimit,
                style: 'candles',
                granularity: finalGranularity,
                subscribe: subscribe ? 1 : undefined,
            }
        ).then(r => {
            if (style === 'ticks') {
                return {
                    ticks: ohlcDataToTicks(r.candles),
                    symbol,
                };
            }
            return {
                candles: r.candles,
                symbol,
            };
        });
    }
    return api.getTickHistory(symbol,
        {
            start,
            end,
            adjust_start_time: 1,
            count: responseSizeLimit,
            style: 'ticks',
            subscribe: subscribe ? 1 : undefined,
        }
    ).then(r => {
        const ticks = r.history.times.map((t, idx) => {
            const quote = r.history.prices[idx];
            return { epoch: +t, quote: +quote };
        });
        return {
            ticks,
            symbol,
        };
    });
};

/**
 *
 * @param api
 * @param symbol
 * @param durationCount
 * @param durationType
 */
export function getDataForSymbol(api, symbol, durationCount = 1, durationType = 'all', style = 'ticks', subscribe) {
    const durationUnit = hcUnitConverter(durationType);
    const end = nowEpoch();
    const start = end - durationToSecs(durationCount, durationUnit);
    return autoAdjustGetData(api, symbol, start, end, style, subscribe);
}

/**
 * get data of contract
 * @param api                      - will be injected by library
 * @param getContract              - function that accept nothing and return a Promise containing contract
 * @param durationCount            - number of duration
 * @param durationType             - type of duration, check http://api.highcharts.com/highstock#rangeSelector.buttons
 * @param style                    - one of ['ticks', 'candles'], this will affect the return data shape,
 *                                   internally library might not always use this param when requesting, eg. when data is too large,
 *                                   library will use `candles` instead of `ticks`, this is handle by library so user do not need to worry
 * @param granularity              - default to 60, check https://developers.binary.com/api/#ticks_history
 * @returns {*|Promise.<TResult>}
 */
export function getDataForContract(
    api,
    getContract,
    durationCount,
    durationType = 'all',
    style = 'ticks',
    subscribe,
) {
    const getAllData = () =>
        getContract()
            .then(contract => {
                const symbol = contract.underlying;
                if (contract.tick_count) {
                    const start = +(contract.date_start) - 5;
                    const exitTime = +(contract.exit_tick_time) + 5;
                    const end = exitTime || nowEpoch();
                    return autoAdjustGetData(api, symbol, start, end, style, subscribe);
                }

                const bufferSize = 0.05;                            // 5 % buffer
                const contractStart = +(contract.date_start);
                const contractEnd = +(contract.exit_tick_time) || +(contract.date_expiry);

                // handle Contract not started yet
                if (contractStart > nowEpoch()) {
                    return autoAdjustGetData(api, symbol, nowEpoch() - 600, nowEpoch(), style, subscribe);
                }

                const buffer = (contractEnd - contractStart) * bufferSize;
                const start = buffer ? contractStart - buffer : contractStart;
                const bufferedExitTime = contractEnd + buffer;
                const end = contractEnd ? bufferedExitTime : nowEpoch();

                return autoAdjustGetData(api, symbol, Math.round(start), Math.round(end), style, subscribe);
            });

    if (durationType === 'all') {
        return getAllData();
    }

    return getContract()
        .then(contract => {
            const symbol = contract.underlying;
            const startTime = +(contract.date_start);

            // handle Contract not started yet
            if (startTime > nowEpoch()) {
                return autoAdjustGetData(api, symbol, nowEpoch() - 600, nowEpoch(), style, subscribe);
            }

            const sellT = contract.sell_time;
            const end = sellT || nowEpoch();

            const buffer = (end - startTime) * 0.05;

            const durationUnit = hcUnitConverter(durationType);
            const start = Math.min(startTime - buffer, end - durationToSecs(durationCount, durationUnit));
            return autoAdjustGetData(api, symbol, Math.round(start), Math.round(end), style, subscribe);
        });
}
<|endoftext|>


<commit_before>'use strict';

/** @interface */
const ITrackerManager = require('../interfaces/i-tracker-manager');
/** @interface */
const ITracker = require('../interfaces/i-tracker');

/**
 * Tracker manager class
 * @implements {ITrackerManager}
 * @extends {EventEmitter}
 */
class TrackerManager extends ITrackerManager {
	constructor() {
		super();

		/**
		 * @type {Array.<ITracker>}
		 * @protected
		 */
		this._trackers = [];

		/**
		 * Fired with: included tracker index
		 * @type {string}
		 */
		this.EVENT_TRACKER_INCLUDED = 'include:complete';

		/**
		 * Fired with: excluded tracker instance
		 * @type {string}
		 */
		this.EVENT_TRACKER_EXCLUDED = 'exclude:complete';

		/**
		 * Fired with: error explain
		 * @type {string}
		 */
		this.EVENT_ERROR = 'error';

		/**
		 * Fired with: tracker, searchResponse
		 * @type {string}
		 */
		this.EVENT_SEARCH_RESPONSE = 'search:response';

		/**
		 * Fired with: tracker, error
		 * @type {string}
		 */
		this.EVENT_SEARCH_ERROR = 'search:error';
	}

	/**
	 * @inheritDoc
	 */
	include(trackerAdapter) {
		if (trackerAdapter instanceof ITracker) {
			let index = this._trackers.push(trackerAdapter) - 1;
			this.emit(this.EVENT_TRACKER_INCLUDED, trackerAdapter);
			return index;
		} else {
			this.emit(this.EVENT_ERROR, new Error('Including error: All tracker adapter must be instances of ITracker'));
		}
		return undefined;
	}

	/**
	 * @inheritDoc
	 */
	exclude(index) {
		if (this._trackers[index] !== undefined) {
			this.emit(this.EVENT_TRACKER_EXCLUDED, this._trackers[index]);
			return this._trackers.splice(index, 1)[0];
		} else {
			this.emit(this.EVENT_ERROR, new Error(`Excluding error: Array not containing item with index = ${index}`));
		}
		return undefined;
	}

	/**

	/**
	 * @inheritDoc
	 */
	search(searchParams) {
		if (this._trackers.length !== 0) {
			this._trackers.forEach(tracker => {
				tracker.search(searchParams)
					.then(searchResponse => {
						this.emit(this.EVENT_SEARCH_RESPONSE, tracker, searchResponse);
					})
					.catch(err => {
						this.emit(this.EVENT_SEARCH_ERROR, tracker, err);
					});
			});
		} else {
			this.emit(this.EVENT_ERROR, new Error('Search error: no one tracker is included'));
		}
	}
}

module.exports = TrackerManager;
<commit_msg>Implement changed interface<commit_after>'use strict';

/** @interface */
const ITrackerManager = require('../interfaces/i-tracker-manager');
/** @interface */
const ITracker = require('../interfaces/i-tracker');

/**
 * Tracker manager class
 * @implements {ITrackerManager}
 * @extends {EventEmitter}
 */
class TrackerManager extends ITrackerManager {
	constructor() {
		super();

		/**
		 * @type {Object.<string, ITracker>}
		 * @protected
		 */
		this._trackers = {};

		/**
		 * Fired with: included tracker UID
		 * @type {string}
		 */
		this.EVENT_TRACKER_INCLUDED = 'include:complete';

		/**
		 * Fired with: excluded tracker instance
		 * @type {string}
		 */
		this.EVENT_TRACKER_EXCLUDED = 'exclude:complete';

		/**
		 * Fired with: error explain
		 * @type {string}
		 */
		this.EVENT_ERROR = 'error';

		/**
		 * Fired with: tracker, searchResponse
		 * @type {string}
		 */
		this.EVENT_SEARCH_RESPONSE = 'search:response';

		/**
		 * Fired with: tracker, error
		 * @type {string}
		 */
		this.EVENT_SEARCH_ERROR = 'search:error';
	}

	/**
	 * @inheritDoc
	 */
	include(trackerAdapter) {
		if (trackerAdapter instanceof ITracker) {
			const uid = this.constructor._generateUID();
			this._trackers[uid] = trackerAdapter;
			this.emit(this.EVENT_TRACKER_INCLUDED, trackerAdapter);
			return uid;
		} else {
			this.emit(this.EVENT_ERROR, new Error('Including error: All tracker adapter must be instances of ITracker'));
		}
		return undefined;
	}

	/**
	 * @inheritDoc
	 */
	exclude(uid) {
		if (this._trackers[uid] !== undefined) {
			const removingItem = this._trackers[uid];
			this.emit(this.EVENT_TRACKER_EXCLUDED, removingItem);
			delete this._trackers[uid];
			return true;
		} else {
			this.emit(this.EVENT_ERROR, new Error(`Excluding error: Array not containing item with index = ${uid}`));
		}
		return false;
	}

	/**
	 * @inheritDoc
	 */
	search(searchParams) {
		const uids = Object.keys(this._trackers);
		if (uids.length !== 0) {
			uids.forEach(uid => {
				const tracker = this._trackers[uid];
				tracker.search(searchParams)
					.then(searchResponse => {
						this.emit(this.EVENT_SEARCH_RESPONSE, tracker, searchResponse);
					})
					.catch(err => {
						this.emit(this.EVENT_SEARCH_ERROR, tracker, err);
					});
			});
		} else {
			this.emit(this.EVENT_ERROR, new Error('Search error: no one tracker is included'));
		}
	}

	/**
	 * @return {string}
	 * @protected
	 */
	static _generateUID() {
		return '_' + Math.random().toString(36).substr(2, 9);
	}
}

module.exports = TrackerManager;
<|endoftext|>


<commit_before>import React from 'react';

const Hello = () => (

{'Welcome to Web Signup Boilerplate!!!'}

);

export default Hello;
<commit_msg>test react-redux connect function<commit_after>import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { bindActions, mapStateToProps } from '../stores';
import * as actions from '../actions/signup';

class Hello extends React.PureComponent {
  render() {
    return
{this.props.store.title}
;
  }
}

Hello.propTypes = {
  store: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.string,
    PropTypes.number,
    PropTypes.bool,
    PropTypes.object,
  ]).isRequired,
};

export default connect(mapStateToProps('signup'), bindActions(actions))(Hello);
<|endoftext|>


<commit_before>let net = require('net')
let express = require('express')
let util = require('util')
let conf = require('../conf')
let pkg = require('../../package.json')

module.exports = function (servers) {
  let router = express.Router()

  function index (req, res) {
    res.render('index', {
      pkg,
      monitors: servers.list()
    })
  }

  function kill (req, res) {
    res.end()
    util.log('Shutting down servers')
    servers.shutdown(() => {
      util.log('Exit')
      process.exit()
    })
  }

  function redirect (req, res, next) {
    if (!servers.has(req.params.id)) {
      return res.redirect('/')
    }

    // Start server
    let id = req.params.id
    servers.start(id)

    // Redirect when server is reachable
    let port = servers.get(id).env.PORT
    let hostname = req.hostname
    let timeout = conf.timeout
    let start = new Date()

    function forward () {
      // On connect, destroy client
      // and redirect
      function handleConnect () {
        clearInterval(intervalId)
        client.destroy()
        let url = `http://${hostname}:${port}`
        util.log(`Redirect to ${url}`)
        res.redirect(url)
      }

      // On error, give up on timeout
      function handleError () {
        if (new Date() - start > timeout) {
          clearInterval(intervalId)
          res.status(502).send(
            `Can't connect to server on port ${port}, ` +
            `timeout of ${timeout}ms exceeded. Retry or check logs.`)
        }
      }

      // Try to connect
      let client = net
        .connect({ port }, handleConnect)
        .on('error', handleError)
    }

    let intervalId = setInterval(forward, 1000)
    forward()
  }

  router
    .get('/', index)
    .get('/:id', redirect)
    .post('/kill', kill)

  return router
}
<commit_msg>Refactor<commit_after>let net = require('net')
let express = require('express')
let util = require('util')
let conf = require('../conf')
let pkg = require('../../package.json')

module.exports = function (servers) {
  let router = express.Router()

  function index (req, res) {
    res.render('index', {
      pkg,
      monitors: servers.list()
    })
  }

  function kill (req, res) {
    res.end()
    util.log('Shutting down servers')
    servers.shutdown(() => {
      util.log('Exit')
      process.exit()
    })
  }

  function redirect (req, res, next) {
    let id = req.params.id

    if (!servers.has(id)) {
      return res.redirect('/')
    }

    // Start server
    servers.start(id)

    // Redirect when server is reachable
    let port = servers.get(id).env.PORT
    let hostname = req.hostname
    let timeout = conf.timeout
    let start = new Date()

    function forward () {
      // On connect, destroy client
      // and redirect
      function handleConnect () {
        clearInterval(intervalId)
        client.destroy()
        let url = `http://${hostname}:${port}`
        util.log(`Redirect to ${url}`)
        res.redirect(url)
      }

      // On error, give up on timeout
      function handleError () {
        if (new Date() - start > timeout) {
          clearInterval(intervalId)
          res.status(502).send(
            `Can't connect to server on port ${port}, ` +
            `timeout of ${timeout}ms exceeded. Retry or check logs.`)
        }
      }

      // Try to connect
      let client = net
        .connect({ port }, handleConnect)
        .on('error', handleError)
    }

    let intervalId = setInterval(forward, 1000)
    forward()
  }

  router
    .get('/', index)
    .get('/:id', redirect)
    .post('/kill', kill)

  return router
}
<|endoftext|>


<commit_before>/**
 *  Point of contact for container modules
 *
 *  e.g.: import { Home, About } from 'containers'
 *
 */

export Admin from './Admin/Admin'
export AdminDestinationList from './AdminDestinationList/AdminDestinationList'
export AdminDestinationListItem from './AdminDestinationListItem/AdminDestinationListItem'
export AdminDestinationListItemEdit from './AdminDestinationListItemEdit/AdminDestinationListItemEdit'
export AdminTrippianList from './AdminTrippianList/AdminTrippianList'
export AdminTrippianListItem from './AdminTrippianListItem/AdminTrippianListItem'
export AdminTrippianListItemEdit from './AdminTrippianListItemEdit/AdminTrippianListItemEdit'
export AdminInquiryList from './AdminInquiryList/AdminInquiryList'
export AdminInquiryListItem from './AdminInquiryListItem/AdminInquiryListItem'
export AdminInquiryListItemEdit from './AdminInquiryListItemEdit/AdminInquiryListItemEdit'
export AdminTripList from './AdminTripList/AdminTripList'
export AdminTripListItem from './AdminTripListItem/AdminTripListItem'
export AdminTripListItemEdit from './AdminTripListItemEdit/AdminTripListItemEdit'
export AdminUserList from './AdminUserList/AdminUserList'
export AdminUserListItem from './AdminUserListItem/AdminUserListItem'
export AdminUserListItemEdit from './AdminUserListItemEdit/AdminUserListItemEdit'

export About from './About/About'
export App from './App/App'
  // export Calendar from './Calendar/Calendar'
export Chat from './Chat/Chat'
export Contact from './Contact/Contact'

export Destination from './Destination/Destination'
export DestinationDetail from './DestinationDetail/DestinationDetail'
export DestinationList from './DestinationList/DestinationList'
export DestinationPost from './DestinationPost/DestinationPost'
export DestinationSearchResults from './DestinationSearchResults/DestinationSearchResults'
export PopularDestinations from './PopularDestinations/PopularDestinations'
export DestinationWrapper from './DestinationWrapper/DestinationWrapper'

export EmailNotification from './EmailNotification/EmailNotification'

export InquiryAdd from './InquiryAdd/InquiryAdd'
export InquiryList from './InquiryList/InquiryList'
export InquiryDetail from './InquiryDetail/InquiryDetail'

export IntlDemo from './IntlDemo/IntlDemo'
export Home from './Home/Home'
export JoinUs from './JoinUs/JoinUs'
export Login from './Login/Login'
export LoginSuccess from './LoginSuccess/LoginSuccess'
export Logout from './Logout/Logout'
export LoginWrapper from './LoginWrapper/LoginWrapper'
export Press from './Press/Press'
  // export LoginSuccess from './LoginSuccess/LoginSuccess'
export NotFound from './NotFound/NotFound'
  // export Review from './Review/Review'
export Signup from './Signup/Signup'
export SignupSuccess from './SignupSuccess/SignupSuccess'
export SignupWrapper from './SignupWrapper/SignupWrapper'
export TeamCards from './About/TeamCards'
export Terms from './Terms/Terms'

export PopularTrips from './PopularTrips/PopularTrips'
export TripWrapper from './TripWrapper/TripWrapper'
export Trip from './Trip/Trip'
export TripDetail from './TripDetail/TripDetail'

export Trippian from './Trippian/Trippian'
export TrippianDetail from './TrippianDetail/TrippianDetail'
export TrippianSignUp from './TrippianSignUp/TrippianSignUp'
export TrippianList from './TrippianList/TrippianList'
export TrippianEdit from './TrippianEdit/TrippianEdit'

export Dashboard from './Dashboard/Dashboard'
export MyProfile from './Dashboard/MyProfile'
export MyInquiries from './Dashboard/MyInquiries'
export MyPostedTrips from './Dashboard/MyPostedTrips'
export MyTripBox from './Dashboard/MyTripBox'

export Trips from './Trips/Trips'
<commit_msg>fix(container index): take out trip/trip container<commit_after>/**
 *  Point of contact for container modules
 *
 *  e.g.: import { Home, About } from 'containers'
 *
 */

export Admin from './Admin/Admin'
export AdminDestinationList from './AdminDestinationList/AdminDestinationList'
export AdminDestinationListItem from './AdminDestinationListItem/AdminDestinationListItem'
export AdminDestinationListItemEdit from './AdminDestinationListItemEdit/AdminDestinationListItemEdit'
export AdminTrippianList from './AdminTrippianList/AdminTrippianList'
export AdminTrippianListItem from './AdminTrippianListItem/AdminTrippianListItem'
export AdminTrippianListItemEdit from './AdminTrippianListItemEdit/AdminTrippianListItemEdit'
export AdminInquiryList from './AdminInquiryList/AdminInquiryList'
export AdminInquiryListItem from './AdminInquiryListItem/AdminInquiryListItem'
export AdminInquiryListItemEdit from './AdminInquiryListItemEdit/AdminInquiryListItemEdit'
export AdminTripList from './AdminTripList/AdminTripList'
export AdminTripListItem from './AdminTripListItem/AdminTripListItem'
export AdminTripListItemEdit from './AdminTripListItemEdit/AdminTripListItemEdit'
export AdminUserList from './AdminUserList/AdminUserList'
export AdminUserListItem from './AdminUserListItem/AdminUserListItem'
export AdminUserListItemEdit from './AdminUserListItemEdit/AdminUserListItemEdit'

export About from './About/About'
export App from './App/App'
  // export Calendar from './Calendar/Calendar'
export Chat from './Chat/Chat'
export Contact from './Contact/Contact'

export Destination from './Destination/Destination'
export DestinationDetail from './DestinationDetail/DestinationDetail'
export DestinationList from './DestinationList/DestinationList'
export DestinationPost from './DestinationPost/DestinationPost'
export DestinationSearchResults from './DestinationSearchResults/DestinationSearchResults'
export PopularDestinations from './PopularDestinations/PopularDestinations'
export DestinationWrapper from './DestinationWrapper/DestinationWrapper'

export EmailNotification from './EmailNotification/EmailNotification'

export InquiryAdd from './InquiryAdd/InquiryAdd'
export InquiryList from './InquiryList/InquiryList'
export InquiryDetail from './InquiryDetail/InquiryDetail'

export IntlDemo from './IntlDemo/IntlDemo'
export Home from './Home/Home'
export JoinUs from './JoinUs/JoinUs'
export Login from './Login/Login'
export LoginSuccess from './LoginSuccess/LoginSuccess'
export Logout from './Logout/Logout'
export LoginWrapper from './LoginWrapper/LoginWrapper'
export Press from './Press/Press'
  // export LoginSuccess from './LoginSuccess/LoginSuccess'
export NotFound from './NotFound/NotFound'
  // export Review from './Review/Review'
export Signup from './Signup/Signup'
export SignupSuccess from './SignupSuccess/SignupSuccess'
export SignupWrapper from './SignupWrapper/SignupWrapper'
export TeamCards from './About/TeamCards'
export Terms from './Terms/Terms'

export PopularTrips from './PopularTrips/PopularTrips'
export TripWrapper from './TripWrapper/TripWrapper'
export TripDetail from './TripDetail/TripDetail'

export Trippian from './Trippian/Trippian'
export TrippianDetail from './TrippianDetail/TrippianDetail'
export TrippianSignUp from './TrippianSignUp/TrippianSignUp'
export TrippianList from './TrippianList/TrippianList'
export TrippianEdit from './TrippianEdit/TrippianEdit'

export Dashboard from './Dashboard/Dashboard'
export MyProfile from './Dashboard/MyProfile'
export MyInquiries from './Dashboard/MyInquiries'
export MyPostedTrips from './Dashboard/MyPostedTrips'
export MyTripBox from './Dashboard/MyTripBox'

export Trips from './Trips/Trips'
<|endoftext|>


<commit_before>import hammerhead from '../deps/hammerhead';
import delay from './delay';
import * as domUtils from './dom';

var Promise       = hammerhead.Promise;
var nativeMethods = hammerhead.nativeMethods;
var listeners     = hammerhead.eventSandbox.listeners;

export const RECORDING_LISTENED_EVENTS = [
    'click', 'mousedown', 'mouseup', 'dblclick', 'contextmenu', 'mousemove', 'mouseover', 'mouseout',
    'touchstart', 'touchmove', 'touchend', 'keydown', 'keypress', 'input', 'keyup', 'change', 'focus', 'blur',
    'MSPointerDown', 'MSPointerMove', 'MSPointerOver', 'MSPointerOut', 'MSPointerUp', 'pointerdown',
    'pointermove', 'pointerover', 'pointerout', 'pointerup'];

// Imported form the hammerhead
export const BUTTON            = hammerhead.utils.event.BUTTON;
export const BUTTONS_PARAMETER = hammerhead.utils.event.BUTTONS_PARAMETER;
export const DOM_EVENTS        = hammerhead.utils.event.DOM_EVENTS;
export const WHICH_PARAMETER   = hammerhead.utils.event.WHICH_PARAMETER;

export var preventDefault = hammerhead.utils.event.preventDefault;

export function bind (el, event, handler, useCapture) {
    if (domUtils.isWindow(el))
        nativeMethods.windowAddEventListener.call(el, event, handler, useCapture);
    else
        nativeMethods.addEventListener.call(el, event, handler, useCapture);
}

export function unbind (el, event, handler, useCapture) {
    if (domUtils.isWindow(el))
        nativeMethods.windowRemoveEventListener.call(el, event, handler, useCapture);
    else
        nativeMethods.removeEventListener.call(el, event, handler, useCapture);
}

// Document ready
const waitForDomContentLoaded = () => {
    return new Promise(resolve => {
        var isReady = false;

        function ready () {
            if (isReady)
                return;

            if (!document.body) {
                nativeMethods.setTimeout.call(window, ready, 1);
                return;
            }

            isReady = true;

            resolve();
        }

        function onContentLoaded () {
            if (!domUtils.isIFrameWindowInDOM(window) && !domUtils.isTopWindow(window))
                return;

            unbind(document, 'DOMContentLoaded', onContentLoaded);
            ready();
        }

        if (document.readyState === 'complete')
            nativeMethods.setTimeout.call(window, onContentLoaded, 1);
        else
            bind(document, 'DOMContentLoaded', onContentLoaded);
    });
};

const waitForWindowLoad = () => new Promise(resolve => bind(window, 'load', resolve));

export function documentReady (pageLoadTimeout = 0) {
    return waitForDomContentLoaded()
        .then(() => {
            if (!listeners.getEventListeners(window, 'load').length)
                return null;

            return Promise.race([waitForWindowLoad(), delay(pageLoadTimeout)]);
        });
}
<commit_msg>[WIP] Fix unnecessary waiting for page loading on a Logify page (#2503)<commit_after>import hammerhead from '../deps/hammerhead';
import delay from './delay';
import * as domUtils from './dom';

var Promise       = hammerhead.Promise;
var nativeMethods = hammerhead.nativeMethods;
var listeners     = hammerhead.eventSandbox.listeners;

export const RECORDING_LISTENED_EVENTS = [
    'click', 'mousedown', 'mouseup', 'dblclick', 'contextmenu', 'mousemove', 'mouseover', 'mouseout',
    'touchstart', 'touchmove', 'touchend', 'keydown', 'keypress', 'input', 'keyup', 'change', 'focus', 'blur',
    'MSPointerDown', 'MSPointerMove', 'MSPointerOver', 'MSPointerOut', 'MSPointerUp', 'pointerdown',
    'pointermove', 'pointerover', 'pointerout', 'pointerup'];

// Imported form the hammerhead
export const BUTTON            = hammerhead.utils.event.BUTTON;
export const BUTTONS_PARAMETER = hammerhead.utils.event.BUTTONS_PARAMETER;
export const DOM_EVENTS        = hammerhead.utils.event.DOM_EVENTS;
export const WHICH_PARAMETER   = hammerhead.utils.event.WHICH_PARAMETER;

export var preventDefault = hammerhead.utils.event.preventDefault;

export function bind (el, event, handler, useCapture) {
    if (domUtils.isWindow(el))
        nativeMethods.windowAddEventListener.call(el, event, handler, useCapture);
    else
        nativeMethods.addEventListener.call(el, event, handler, useCapture);
}

export function unbind (el, event, handler, useCapture) {
    if (domUtils.isWindow(el))
        nativeMethods.windowRemoveEventListener.call(el, event, handler, useCapture);
    else
        nativeMethods.removeEventListener.call(el, event, handler, useCapture);
}

// Document ready
const waitForDomContentLoaded = () => {
    // NOTE: We can't use a regular Promise here, because window.load event can happen in the same event loop pass
    // The default Promise will call resolve handlers in the next pass, and load event will be lost.
    const resolveHandlers = [];

    function createPromiseResolver (resolveHandler) {
        return new Promise(resolve => resolveHandlers.push(() => resolve(resolveHandler())));
    }

    let isReady = false;

    function ready () {
        if (isReady)
            return;

        if (!document.body) {
            nativeMethods.setTimeout.call(window, ready, 1);
            return;
        }

        isReady = true;

        resolveHandlers.forEach(handler => handler());
    }

    function onContentLoaded () {
        if (!domUtils.isIFrameWindowInDOM(window) && !domUtils.isTopWindow(window))
            return;

        unbind(document, 'DOMContentLoaded', onContentLoaded);
        ready();
    }

    if (document.readyState === 'complete')
        nativeMethods.setTimeout.call(window, onContentLoaded, 1);
    else
        bind(document, 'DOMContentLoaded', onContentLoaded);

    return { then: handler => createPromiseResolver(handler) };
};

const waitForWindowLoad = () => new Promise(resolve => bind(window, 'load', resolve));

export function documentReady (pageLoadTimeout = 0) {
    return waitForDomContentLoaded()
        .then(() => {
            if (!listeners.getEventListeners(window, 'load').length)
                return null;

            return Promise.race([waitForWindowLoad(), delay(pageLoadTimeout)]);
        });
}
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var knex = require('../db/connection');
var User = require('../models/user');
var passport = require('passport');

/* POST eliminates a task with tareaD_id as id_t. */
router.post('/', isLoggedIn, function(req, res) {
	knex('tasks')
	.select('status')
	.where('id_t',req.body.tareaD_id)
	.then(function(result) {
		console.log(resut);
		if (result.status == 0) {
			knex('tasks').update('status', '1');
		} else {
			knex('tasks').update('status', '0');
		}
	});
	res.redirect('/profile');
});

module.exports = router;

function isLoggedIn (req,res,next) {
	if(req.isAuthenticated()){
		return next();
	}
	res.redirect('/');
}
<commit_msg>:kiss: 06033 deleteTasks<commit_after>var express = require('express');
var router = express.Router();
var knex = require('../db/connection');
var User = require('../models/user');
var passport = require('passport');

/* POST eliminates a task with tareaD_id as id_t. */
router.post('/', isLoggedIn, function(req, res) {
	knex('tasks')
	.select('status')
	.where('id_t',req.body.tareaD_id)
	.then(function(result) {
		console.log(result[0].status);
		if (result[0].status == 0) {
			knex('tasks').update('status', '1').then(function (result) {
				console.log('Changed from 0 to 1');
				res.redirect('./profile');
			});
		} else {
			knex('tasks').update('status', '0').then(function (result) {
				console.log('Changed from 1 to 0');
				res.redirect('./profile');
			});
		}
	});
});

module.exports = router;

function isLoggedIn (req,res,next) {
	if(req.isAuthenticated()){
		return next();
	}
	res.redirect('/');
}
<|endoftext|>


<commit_before>import React from 'react';
// import _ from 'underscore';
// import TextField from 'material-ui/TextField';
import {FieldType, registerType} from 'simple-react-form';
import {FormGroup, ControlLabel, HelpBlock} from 'react-bootstrap';
import DateTime from 'react-datetime';
// import 'react-datetime/css/react-datetime.css';

const propTypes = {};

const defaultProps = {};

class DateTimeFieldComponent extends FieldType {

  constructor(props) {
    super(props);
    this.state = { value: props.value };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ value: nextProps.value });
  }

  onChange(date) {
    if (date) {
      this.setState({ value: date.toDate() });
      this.props.onChange(date.toDate());
      return;
    }

    this.setState({ value: null });
    this.props.onChange(null);
    return null;
  }

  render() {
    return (
      <FormGroup
        validationState={this.props.errorMessage ? 'error' : undefined}
      >
        { this.props.label ? <ControlLabel>{this.props.label}</ControlLabel> : null }
        <DateTime
          ref='input'
          dateTime={this.state.value}
          onChange={this.onChange.bind(this)}
          onBlur={() => this.props.onChange(this.state.value)}
          {...this.passProps}
        />
        {this.props.errorMessage &&
          <HelpBlock>{this.props.errorMessage}</HelpBlock>
        }
      </FormGroup>
    );
  }
}

DateTimeFieldComponent.propTypes = propTypes;
DateTimeFieldComponent.defaultProps = defaultProps;

registerType({
  type: 'datetime',
  component: DateTimeFieldComponent,
  allowedTypes: [ Date, String ],
  description: 'Simple select field.'
});
<commit_msg>passing value to datetime<commit_after>import React from 'react';
// import _ from 'underscore';
// import TextField from 'material-ui/TextField';
import {FieldType, registerType} from 'simple-react-form';
import {FormGroup, ControlLabel, HelpBlock} from 'react-bootstrap';
import DateTime from 'react-datetime';
// import 'react-datetime/css/react-datetime.css';

const propTypes = {};

const defaultProps = {};

class DateTimeFieldComponent extends FieldType {

  constructor(props) {
    super(props);
    this.state = { value: props.value };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ value: nextProps.value });
  }

  onChange(date) {
    if (date) {
      this.setState({ value: date.toDate() });
      this.props.onChange(date.toDate());
      return;
    }

    this.setState({ value: null });
    this.props.onChange(null);
    return null;
  }

  render() {
    return (
      <FormGroup
        validationState={this.props.errorMessage ? 'error' : undefined}
      >
        { this.props.label ? <ControlLabel>{this.props.label}</ControlLabel> : null }
        <DateTime
          ref='input'
          dateTime={this.state.value}
          onChange={this.onChange.bind(this)}
          onBlur={() => this.props.onChange(this.state.value)}
          value={this.state.value}
          {...this.passProps}
        />
        {this.props.errorMessage &&
          <HelpBlock>{this.props.errorMessage}</HelpBlock>
        }
      </FormGroup>
    );
  }
}

DateTimeFieldComponent.propTypes = propTypes;
DateTimeFieldComponent.defaultProps = defaultProps;

registerType({
  type: 'datetime',
  component: DateTimeFieldComponent,
  allowedTypes: [ Date, String ],
  description: 'Simple select field.'
});
<|endoftext|>


<commit_before>'use strict';

const { fullRecurseMap } = require('../utilities');

const { getOperator } = require('./operators');

// Try to simplify AST
const optimizeFilter = function ({ filter }) {
  return fullRecurseMap(filter, optimizeNode);
};

const optimizeNode = function (node) {
  const operator = getOperator({ node });
  // Is not a node
  if (operator === undefined) { return node; }

  const { optimize } = operator;
  if (optimize === undefined) { return node; }

  const nodeA = optimize(node);
  return nodeA;
};

module.exports = {
  optimizeFilter,
};
<commit_msg>Use mapNodes() with filter optimizer<commit_after>'use strict';

const { getOperator } = require('./operators');
const { mapNodes } = require('./crawl');

// Try to simplify AST
const optimizeFilter = function ({ filter }) {
  return mapNodes(filter, optimizeNode);
};

const optimizeNode = function (node) {
  const operator = getOperator({ node });

  const { optimize } = operator;
  if (optimize === undefined) { return node; }

  const nodeA = optimize(node);
  return nodeA;
};

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


<commit_before>'use strict';

const Promise    = require('bluebird');
const _          = require('lodash');
const Path       = require('path');
const Handlebars = require('handlebars');
const inquirer   = require('inquirer');
const shell      = require('shelljs');
const fs         = Promise.promisifyAll(require('fs-extra'));
const console    = require('../console');

module.exports = {

    command: 'new <path>',

    config: {
        description: 'Create a new Fractal project',
        scope: ['global']
    },

    action: function (args, done) {

        const helpers          = this.fractal.utils.helpers;
        const baseDir          = args.path;
        const basePath         = baseDir.startsWith('/') ? baseDir : Path.join(process.cwd(), baseDir);
        const viewsPath        = Path.join(__dirname, '../../views/new');
        const fractalFileTpl   = Path.join(viewsPath, 'fractal.hbs');
        const docsIndexTpl     = Path.join(viewsPath, 'docs/index.hbs');
        const exampleComponent = Path.join(viewsPath, 'components/example');

        if (helpers.fileExistsSync(basePath)) {
            console.error(`Cannot create new project: The directory ${basePath} already exists.`).br();
            process.exit();
        }

        console.br().notice('Creating new project.... just a few questions:').br();

        const questions = [
            {
                type: 'input',
                name: 'projectTitle',
                message: 'What\'s the title of your project?',
                default: helpers.titlize(args.path)
            },
            {
                type: 'input',
                name: 'componentsDir',
                message: 'Where would you like to keep your components?',
                default: 'components'
            },
            {
                type: 'input',
                name: 'docsDir',
                message: 'Where would you like to keep your docs?',
                default: 'docs'
            },
            {
                type: 'input',
                name: 'publicDir',
                message: 'What would you like to call your public directory?',
                default: 'public'
            },
            {
                type: 'confirm',
                name: 'useGit',
                message: 'Will you use Git for version control on this project?',
                default: true
            }
        ];

        return inquirer.prompt(questions, function (answers) {

            console.notice('Generating project structure...');

            const componentsDir   = Path.join(basePath, answers.componentsDir);
            const docsDir         = Path.join(basePath, answers.docsDir);
            const publicDir       = Path.join(basePath, answers.publicDir);
            const packageJSONPath = Path.join(basePath, 'package.json');
            const gitIgnorePath   = Path.join(basePath, '.gitignore');
            const fractalFilePath = Path.join(basePath, 'fractal.js');
            const docsIndexPath   = Path.join(docsDir, '01-index.md');
            const componentCopyTo = Path.join(componentsDir, 'example');

            const packageJSON = {
                name: helpers.slugify(answers.projectTitle),
                version: '0.1.0',
                dependencies: {
                    '@frctl/fractal': shell.exec('npm show @frctl/fractal version', { silent:true }).output.replace(/^\s+|\s+$/g, '')
                }
            };

            const fractalContents = Handlebars.compile(fs.readFileSync(fractalFileTpl, 'utf8'))(answers);
            const indexContents   = Handlebars.compile(fs.readFileSync(docsIndexTpl, 'utf8'))(answers);

            fs.ensureDirAsync(basePath).then(() => {
                return Promise.all([
                    fs.ensureDirAsync(componentsDir),
                    fs.ensureDirAsync(docsDir),
                    fs.ensureDirAsync(publicDir),
                    fs.writeJsonAsync(packageJSONPath, packageJSON)
                ]);
            }).then(paths => {
                return fs.copyAsync(exampleComponent, componentCopyTo);
            }).then(paths => {
                if (answers.useGit) {
                    shell.touch(Path.join(publicDir, '.gitkeep'));
                    return fs.writeFileAsync(gitIgnorePath, 'node_modules\n');
                }
                return paths;
            }).then(paths => {
                return Promise.all([
                    fs.writeFileAsync(fractalFilePath, fractalContents),
                    fs.writeFileAsync(docsIndexPath, indexContents),
                ]);
            }).finally(() => {
                console.notice('Installing NPM dependencies - this may take some time!');
                shell.cd(basePath);
                const install = shell.exec('npm i @frctl/fractal --save', {
                    silent: true,
                }, function () {
                    console.success(`Your new Fractal project has been set up.`);
                    process.exit();
                });
                install.stdout.on('data', function (data) {
                    console.log(data);
                });
            }).catch(e => {
                fs.remove(basePath);
                console.error(e);
                process.exit();
            });
        });

    }

};
<commit_msg>fix(commands): Address new command issue with latest inquirer version<commit_after>'use strict';

const Promise    = require('bluebird');
const _          = require('lodash');
const Path       = require('path');
const Handlebars = require('handlebars');
const inquirer   = require('inquirer');
const shell      = require('shelljs');
const fs         = Promise.promisifyAll(require('fs-extra'));
const console    = require('../console');

module.exports = {

    command: 'new <path>',

    config: {
        description: 'Create a new Fractal project',
        scope: ['global']
    },

    action: function (args, done) {

        const helpers          = this.fractal.utils.helpers;
        const baseDir          = args.path;
        const basePath         = baseDir.startsWith('/') ? baseDir : Path.join(process.cwd(), baseDir);
        const viewsPath        = Path.join(__dirname, '../../views/new');
        const fractalFileTpl   = Path.join(viewsPath, 'fractal.hbs');
        const docsIndexTpl     = Path.join(viewsPath, 'docs/index.hbs');
        const exampleComponent = Path.join(viewsPath, 'components/example');

        if (helpers.fileExistsSync(basePath)) {
            console.error(`Cannot create new project: The directory ${basePath} already exists.`).br();
            process.exit();
        }

        console.br().notice('Creating new project.... just a few questions:').br();

        const questions = [
            {
                type: 'input',
                name: 'projectTitle',
                message: 'What\'s the title of your project?',
                default: helpers.titlize(args.path)
            },
            {
                type: 'input',
                name: 'componentsDir',
                message: 'Where would you like to keep your components?',
                default: 'components'
            },
            {
                type: 'input',
                name: 'docsDir',
                message: 'Where would you like to keep your docs?',
                default: 'docs'
            },
            {
                type: 'input',
                name: 'publicDir',
                message: 'What would you like to call your public directory?',
                default: 'public'
            },
            {
                type: 'confirm',
                name: 'useGit',
                message: 'Will you use Git for version control on this project?',
                default: true
            }
        ];

        inquirer.prompt(questions).then(function(answers) {

            console.notice('Generating project structure...');

            const componentsDir   = Path.join(basePath, answers.componentsDir);
            const docsDir         = Path.join(basePath, answers.docsDir);
            const publicDir       = Path.join(basePath, answers.publicDir);
            const packageJSONPath = Path.join(basePath, 'package.json');
            const gitIgnorePath   = Path.join(basePath, '.gitignore');
            const fractalFilePath = Path.join(basePath, 'fractal.js');
            const docsIndexPath   = Path.join(docsDir, '01-index.md');
            const componentCopyTo = Path.join(componentsDir, 'example');

            const packageJSON = {
                name: helpers.slugify(answers.projectTitle),
                version: '0.1.0',
                dependencies: {
                    '@frctl/fractal': shell.exec('npm show @frctl/fractal version', { silent:true }).output.replace(/^\s+|\s+$/g, '')
                }
            };

            const fractalContents = Handlebars.compile(fs.readFileSync(fractalFileTpl, 'utf8'))(answers);
            const indexContents   = Handlebars.compile(fs.readFileSync(docsIndexTpl, 'utf8'))(answers);

            fs.ensureDirAsync(basePath).then(() => {
                return Promise.all([
                    fs.ensureDirAsync(componentsDir),
                    fs.ensureDirAsync(docsDir),
                    fs.ensureDirAsync(publicDir),
                    fs.writeJsonAsync(packageJSONPath, packageJSON)
                ]);
            }).then(paths => {
                return fs.copyAsync(exampleComponent, componentCopyTo);
            }).then(paths => {
                if (answers.useGit) {
                    shell.touch(Path.join(publicDir, '.gitkeep'));
                    return fs.writeFileAsync(gitIgnorePath, 'node_modules\n');
                }
                return paths;
            }).then(paths => {
                return Promise.all([
                    fs.writeFileAsync(fractalFilePath, fractalContents),
                    fs.writeFileAsync(docsIndexPath, indexContents),
                ]);
            }).finally(() => {
                console.notice('Installing NPM dependencies - this may take some time!');
                shell.cd(basePath);
                const install = shell.exec('npm i @frctl/fractal --save', {
                    silent: true,
                }, function () {
                    console.success(`Your new Fractal project has been set up.`);
                    process.exit();
                });
                install.stdout.on('data', function (data) {
                    console.log(data);
                });
            }).catch(e => {
                fs.remove(basePath);
                console.error(e);
                process.exit();
            });
        });

    }

};
<|endoftext|>


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

/**
  Topics delcare the types of events that an object publishes.

  Ex.
  foam.CLASS({
    name: 'Alarm',
    topics: [ 'ring' ]
  });

  then doing:
  alarm.ring.pub();
  alarm.ring.sub(l);

  is the same as:
  alarm.pub('ring');
  alarm.sub('ring', l);

*/
foam.CLASS({
  package: 'foam.core',
  name: 'Topic',

  properties: [
    'name',
    'description',
    {
      class: 'FObjectArray',
      of: 'Topic',
      name: 'topics',
      adaptArrayElement: function(o) {
        return typeof o === 'string' ?
          foam.core.Topic.create({ name: o }, this) :
          foam.core.Topic.create(o, this);
      }
    }
  ],

  methods: [
    function installInProto(proto) {
      var name      = this.name;
      var topic     = this;
      var makeTopic = this.makeTopic;

      Object.defineProperty(proto, name, {
        get: function topicGetter() {
          if ( ! this.hasOwnPrivate_(name) ) {
            this.setPrivate_(name, makeTopic(topic, this));
          }

          return this.getPrivate_(name);
        },
        configurable: true,
        enumerable: false
      });
    },

    function makeTopic(topic, parent) {
      var name   = topic.name;
      var topics = topic.topics || [];

      var ret = {
        pub: foam.Function.bind(parent.pub, parent, name),
        sub: foam.Function.bind(parent.sub, parent, name),
        hasListeners: foam.Function.bind(parent.hasListeners, parent, name),
        toString: function() { return 'Topic(' + name + ')'; }
      };

      for ( var i = 0 ; i < topics.length ; i++ ) {
        ret[topics[i].name] = makeTopic(topics[i], ret);
      }

      return ret;
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Model',
  properties: [
    {
      class: 'AxiomArray',
      of: 'Topic',
      name: 'topics',
      adaptArrayElement: function(o) {
        return typeof o === 'string'        ?
          foam.core.Topic.create({name: o}) :
          foam.core.Topic.create(o)         ;
      }
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.FObject',
  topics: [ 'propertyChange' ]
});
<commit_msg>Docs.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.core',
  name: 'Topic',

  documentation: `
  Topics delcare the types of events that an object publishes.

    Ex.
    foam.CLASS({
      name: 'Alarm',
      topics: [ 'ring' ]
    });

    then doing:
    alarm.ring.pub();
    alarm.ring.sub(l);

    is the same as:
    alarm.pub('ring');
    alarm.sub('ring', l);

  `,

  properties: [
    'name',
    'description',
    {
      class: 'FObjectArray',
      of: 'Topic',
      name: 'topics',
      adaptArrayElement: function(o) {
        return typeof o === 'string' ?
          foam.core.Topic.create({ name: o }, this) :
          foam.core.Topic.create(o, this);
      }
    }
  ],

  methods: [
    function installInProto(proto) {
      var name      = this.name;
      var topic     = this;
      var makeTopic = this.makeTopic;

      Object.defineProperty(proto, name, {
        get: function topicGetter() {
          if ( ! this.hasOwnPrivate_(name) ) {
            this.setPrivate_(name, makeTopic(topic, this));
          }

          return this.getPrivate_(name);
        },
        configurable: true,
        enumerable: false
      });
    },

    function makeTopic(topic, parent) {
      var name   = topic.name;
      var topics = topic.topics || [];

      var ret = {
        pub: foam.Function.bind(parent.pub, parent, name),
        sub: foam.Function.bind(parent.sub, parent, name),
        hasListeners: foam.Function.bind(parent.hasListeners, parent, name),
        toString: function() { return 'Topic(' + name + ')'; }
      };

      for ( var i = 0 ; i < topics.length ; i++ ) {
        ret[topics[i].name] = makeTopic(topics[i], ret);
      }

      return ret;
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Model',
  properties: [
    {
      class: 'AxiomArray',
      of: 'Topic',
      name: 'topics',
      adaptArrayElement: function(o) {
        return typeof o === 'string'        ?
          foam.core.Topic.create({name: o}) :
          foam.core.Topic.create(o)         ;
      }
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.FObject',
  topics: [ 'propertyChange' ]
});
<|endoftext|>


<commit_before>Webos.Icon = function WIcon(name, size, theme) {
	if (typeof name == 'undefined') {
		name = 'apps/default';
	}

	var nameArray = name.split('/');
	var type = Webos.Icon.types[0];
	if ($.inArray(nameArray[0], Webos.Icon.types) != -1) {
		type = nameArray[0];
		nameArray.shift();
		name = nameArray.join('/');
	}

	this.name = name;
	this.type = type;

	if (typeof Webos.Icon.sizes[size] != 'undefined') {
		size = Webos.Icon.sizes[size];
	}

	this.size = (typeof size == 'undefined' || isNaN(parseInt(size))) ? 48 : parseInt(size);
	this.theme = theme;

	this.id = function(size, theme) {
		if (/^[\/(~\/)]/.test(this.name)) {
			return undefined;
		}

		size = (typeof size == 'undefined') ? this.size : size;

		if (typeof Webos.Icon._cache[this.name] != 'undefined' && Webos.Icon._cache[this.name].size >= size) {
			return Webos.Icon._cache[this.name].id(size, theme);
		}

		if (this.type == 'themes') {
			var theme = (typeof theme == 'undefined') ? ((typeof this.theme == 'undefined') ? Webos.Theme.current().get('icons') : this.theme) : size;
			return this.type+'/'+theme+'/'+size+'/'+this.name;
		} else {
			return this.type+'/'+size+'/'+this.name;
		}
	};

	this.path = function(size, theme) {
		var id = this.id();
		if (typeof id == 'undefined') {
			return this.name;
		} else {
			return Webos.Icon.path+'/'+id+'.png';
		}
	};

	this.realpath = function(size, theme) {
		var id = this.id(size, theme);
		if (typeof id == 'undefined') {
			return 'sbin/filecall.php?file='+this.name;
		} else {
			return 'sbin/filecall.php?file='+id+'&type=icon';
		}
	};

	this.toString = function() {
		return this.realpath();
	};

	this.is = function(icon) {
		icon = Webos.Icon.toIcon(icon);

		if (this.type == icon.type && this.name == icon.name) {
			return true;
		}

		return false;
	};

	if (!/^[\/(~\/)]/.test(this.name)) {
		Webos.Icon._cache[this.id()] = this;
	}
};

Webos.Icon.types = ['themes', 'applications'];
Webos.Icon.path = '/usr/share/icons';
Webos.Icon.sizes = {
	button: 24
};
Webos.Icon._cache = {};
Webos.Icon.toIcon = function(arg) {
	if (arg instanceof Webos.Icon) {
		return arg;
	}

	if (arg instanceof Array) {
		if (typeof arg[0] == 'string') {
			return new Webos.Icon(String(arg[0]), String(arg[1]), String(arg[2]));
		}
	}

	switch (typeof arg) {
		case 'object':
			if (arg.name) {
				return new Webos.Icon(String(arg.name), String(arg.size), String(arg.theme));
			}
		case 'string':
			return new Webos.Icon(arg);
		default:
			return new Webos.Icon();
	}
};<commit_msg>Fixed an issue in Webos.Icon.<commit_after>Webos.Icon = function WIcon(name, size, theme) {
	if (typeof name == 'undefined') {
		name = 'apps/default';
	}

	var nameArray = name.split('/');
	var type = Webos.Icon.types[0];
	if ($.inArray(nameArray[0], Webos.Icon.types) != -1) {
		type = nameArray[0];
		nameArray.shift();
		name = nameArray.join('/');
	}

	this.name = name;
	this.type = type;

	if (typeof Webos.Icon.sizes[size] != 'undefined') {
		size = Webos.Icon.sizes[size];
	}

	this.size = (typeof size == 'undefined' || isNaN(parseInt(size))) ? 48 : parseInt(size);
	this.theme = theme;

	this.id = function(size, theme) {
		if (/^[\/(~\/)]/.test(this.name)) {
			return undefined;
		}

		size = (typeof size == 'undefined') ? this.size : size;

		if (typeof Webos.Icon._cache[this.name] != 'undefined' && Webos.Icon._cache[this.name].size >= size) {
			return Webos.Icon._cache[this.name].id(size, theme);
		}

		if (this.type == 'themes') {
			var theme = (typeof theme == 'undefined') ? ((typeof this.theme == 'undefined') ? Webos.Theme.current().get('icons') : this.theme) : size;
			return this.type+'/'+theme+'/'+size+'/'+this.name;
		} else {
			return this.type+'/'+size+'/'+this.name;
		}
	};

	this.path = function(size, theme) {
		var id = this.id();
		if (typeof id == 'undefined') {
			return this.name;
		} else {
			return Webos.Icon.path+'/'+id+'.png';
		}
	};

	this.realpath = function(size, theme) {
		var id = this.id(size, theme);
		if (typeof id == 'undefined') {
			return 'sbin/filecall.php?file='+this.name;
		} else {
			return 'sbin/filecall.php?file='+id+'&type=icon';
		}
	};

	this.toString = function() {
		return this.realpath();
	};

	this.is = function(icon) {
		icon = Webos.Icon.toIcon(icon);

		if (this.type == icon.type && this.name == icon.name) {
			return true;
		}

		return false;
	};

	if (!/^[\/(~\/)]/.test(this.name)) {
		Webos.Icon._cache[this.id()] = this;
	}
};

Webos.Icon.types = ['themes', 'applications'];
Webos.Icon.path = '/usr/share/icons';
Webos.Icon.sizes = {
	button: 24
};
Webos.Icon._cache = {};
Webos.Icon.toIcon = function(arg) {
	if (arg instanceof Webos.Icon) {
		return arg;
	}

	if (arg instanceof Array) {
		if (typeof arg[0] == 'string') {
			return new Webos.Icon(arg[0], arg[1], arg[2]);
		}
	}

	switch (typeof arg) {
		case 'object':
			if (arg.name) {
				return new Webos.Icon(arg.name, arg.size, arg.theme);
			}
		case 'string':
			return new Webos.Icon(arg);
		default:
			return new Webos.Icon();
	}
};<|endoftext|>