<commit_before>/*jslint indent: 4, node: true */
/*global require: false, process: false */

var http = require('http'),
    path = require('path'),
    fs = require('fs'),
    url = require('url'),
    htmlparser = require('htmlparser2'), // npm install htmlparser2 -g
    async = require('async'), //npm install async -g
    downloadFile = function (uri, filename, callback) {
        "use strict";

        var downloadError = function (err) {
                callback(err.message, {'url': uri});
            },
            downloadStart = function (res) {

                // Don't create the file until we get the response.
                var file = fs.createWriteStream(filename);

                res.on('data', function (chunk) {

                    file.write(chunk, 'binary');
                });
                res.on('end', function () {

                    file.end();
                    callback(null, { 'url': uri, 'filename': filename });
                });
            },
            directoryReady = function (err) {
                var req = {};

                if (err && err.code !== 'EEXIST') {
                    callback(err.code, {'url': uri});
                } else {
                    req = http.get(uri, downloadStart);
                    req.on('error', downloadError);
                }
            },
            directory = path.dirname(filename);

        fs.mkdir(directory, directoryReady);
    },
    getHTML = function (uri, callback) {
        "use strict";

        var req = http.get(uri, function (res) {

            var output = '';

            res.setEncoding('utf8');

            res.on('data', function (chunk) {

                output += chunk;
            });

            res.on('end', function () {

                callback(null, { 'status': res.statusCode, 'text': output });
            });
        });
        req.on('error', function (err) {
            callback(err.message, null);
        });
    },
    parseHtml = function (sourceUrl, callback) {
        "use strict";

        var results = [];

        getHTML(sourceUrl, function (err, response) {

            var whenOpenTag = function (name, attribs) {
                    if (name === 'a') {
                        if (attribs.href) {
                            results.push(url.resolve(sourceUrl, attribs.href));
                        }
                    } else if (name === 'img') {
                        if (attribs.src) {
                            results.push(url.resolve(sourceUrl, attribs.src));
                        }
                    } else if (name === 'iframe') {
                        if (attribs.src) {
                            results.push(url.resolve(sourceUrl, attribs.src));
                        }
                    }
                },
                parser = new htmlparser.Parser({
                    onopentag: whenOpenTag,
                });

            if (err) {
                callback(err, { 'sourceUrl': sourceUrl });
            } else if (response.status === 200) {
                parser.write(response.text);
                parser.end();
                callback(null, { 'sourceUrl': sourceUrl, 'urlsFound': results });
            } else {
                callback(response.status, { 'sourceUrl': sourceUrl });
            }
        });
    },
    getOperationChain = function (filename, callback) {
        "use strict";

        var result = {};

        fs.readFile(filename, { 'encoding': "utf8" }, function (err, data) {
            if (err) {
                console.log('failed to read operation chain');
                callback(err, null);
            } else {
                result = JSON.parse(data);

                callback(null, result);
            }
        });
    },
    pruneDuplicates = function (list) {
        "use strict";

        var count = list.length,
            i = 0,
            map = {};

        for (i = 0; i < count; i += 1) {
            map[list[i]] = true;
        }

        list = [];
        for (i in map) {
            if (map.hasOwnProperty(i)) {
                list.push(i);
            }
        }

        return list.sort();
    },
    //  {
    //    "operation": "download",
    //    "input": [url, ...],
    //    "pattern": ".*\/([^\/]+)\/([^\/]+)"
    //    "filename": "{1}"
    //    "directory": "{0}"
    //    "output": [url, ...] - that failed to download
    //  }
    //
    operationDownload = function (operation, callback) {
        "use strict";

        var downloads = 0,
            processDownload = function (err, result) {

                if (err) {
                    operation.output.push(result.url);
                    console.log('ERROR downloading: ' + result.url + '\n          message: ' + err.message);
                } else {
                    console.log('Downloaded (' + downloads + ' remaining): ' + result.url);
                }

                downloads -= 1;

                if (downloads === 0) {
                    callback(operation);
                }
            },
            startDownload = function (element) {

                var re = {},
                    matches = [],
                    filename = '',
                    directory = path.resolve('.', '.');

                if (operation.pattern) {

                    if (operation.pattern[0] !== '^' || operation.pattern[operation.pattern.length - 1] !== '$') {
                        console.log('ERROR: pattern must begin with ^ and end with $');
                        return;
                    }

                    re = new RegExp(operation.pattern);
                    matches = element.match(re);

                    if (operation.filename) {
                        filename = operation.filename.format(matches);
                    }

                    if (operation.directory) {
                        directory = operation.directory.format(matches);
                    }
                }

                if (filename === '') {
                    filename = element.substr(element.lastIndexOf('/') + 1);
                }

                filename = path.resolve(directory, filename);

                if (operation.debug) {
                    console.log('directory: ' + directory);
                    console.log('filename : ' + filename);
                } else {
                    downloadFile(element, filename, processDownload);
                }
            };

        downloads = operation.input.length;
        operation.input.forEach(startDownload);
    },
    //  {
    //    "operation": "parse",
    //    "input": [url, ...],
    //    "output": [url, ...] - urls found from downloading and parsing the input urls
    //  }
    //
    operationParse = function (operation, callback) {
        "use strict";

        var pages = 0,
            processPage = function (err, result) {

                if (err) {
                    console.log('ERROR parsing: ' + result.sourceUrl + '\n      message: ' + err.message);
                } else {
                    operation.output = operation.output.concat(result.urlsFound);
                    console.log('Parsed (' + pages + ' remaining): ' + result.sourceUrl);
                }

                pages -= 1;

                if (pages === 0) {
                    if (operation.debug) {
                        console.log(pruneDuplicates(operation.output));
                    }

                    callback(operation);
                }
            },
            startFetch = function (element) {

                parseHtml(element, processPage);
            };

        pages = operation.input.length;
        operation.input.forEach(startFetch);
    },
    //  {
    //    "operation": "filter",
    //    "input": [url, ...],
    //    "include": "text1"
    //    "exclude": "text2"
    //    "output": [url, ...] - urls that contained text1 but not text2
    //  }
    //
    operationFilter = function (operation, callback) {
        "use strict";

        var re = {};

        if (operation.include) {
            if (operation.include[0] !== '^' || operation.include[operation.include.length - 1] !== '$') {
                console.log('ERROR: include must begin with ^ and end with $');
                return;
            }

            re = new RegExp(operation.include);

            operation.output = operation.input.filter(function (item) {
                return re.test(item);
            });
        } else {
            operation.output = operation.input;
        }

        if (operation.exclude) {
            if (operation.exclude[0] !== '^' || operation.exclude[operation.exclude.length - 1] !== '$') {
                console.log('ERROR: exclude must begin with ^ and end with $');
                return;
            }

            re = new RegExp(operation.exclude);

            operation.output = operation.output.filter(function (item) {
                return !re.test(item);
            });
        }

        if (operation.debug) {
            console.log(operation.output);
        }

        process.nextTick(function () {
            callback(operation);
        });
    },
    //  {
    //    "operation": "generate",
    //    "input": [url, ...],
    //    "patterns": [url, ...],
    //    "start": 2
    //    "increment": 1
    //    "end" : 10
    //    "output": [url, ...] - for each url in input replaces {0} with values from start to end increased by increment unitl the value exceeds end
    //  }
    //
    operationGenerate = function (operation, callback) {
        "use strict";

        var patterns = operation.patterns || [],
            count = patterns.length,
            start = operation.start || 0,
            increment = operation.increment || 1,
            end = operation.end || 0,
            i = 0,
            value = 0;

        operation.output = operation.input;

        for (i = 0; i < count; i += 1) {
            for (value = start; value <= end; value += increment) {
                operation.output.push(operation.patterns[i].format(value));
            }
        }

        if (operation.debug) {
            console.log(pruneDuplicates(operation.output));
        }

        process.nextTick(function () {
            callback(operation);
        });
    },
    operations = [],
    doNextOperation = function (operation) {
        "use strict";

        var nextOperation = operations.pop(),
            input = [];

        if (operation) {
            input = pruneDuplicates(operation.output);
        }

        if (nextOperation) {
            if (nextOperation.input && nextOperation.input.length > 0) {
                input = input.concat(nextOperation.input);
            }
            nextOperation.input = input;
            nextOperation.output = nextOperation.output || [];
            nextOperation.output = nextOperation.output || [];
            nextOperation.operation = nextOperation.operation || '';
            nextOperation.debug = nextOperation.debug || false;

            switch (nextOperation.operation) {
            case 'download':
                operationDownload(nextOperation, doNextOperation);
                break;
            case 'parse':
                operationParse(nextOperation, doNextOperation);
                break;
            case 'filter':
                operationFilter(nextOperation, doNextOperation);
                break;
            case 'generate':
                operationGenerate(nextOperation, doNextOperation);
                break;
            }
        } else {
            if (input.length > 0) {
                console.log(input);
            }
        }
    },
    main = function (argc, argv) {
        "use strict";

        if (argc < 3) {
            console.log('usage: %s %s <filename>', argv[0], argv[1]);
        } else {
            getOperationChain(path.resolve('.', argv[2]), function (err, result) {
                if (err) {
                    console.log(err);
                } else {
                    operations = result.reverse();

                    process.nextTick(function () {
                        doNextOperation(null);
                    });
                }
            });
        }
    },
    argv = process.argv,
    argc = argv.length;

if (!String.prototype.format) {
    String.prototype.format = function () {
        "use strict";

        var args = arguments;

        // If we are passed an array then just use that.
        if (args.length === 1 && typeof args[0] === "object") {
            args = args[0];
        }

        return this.replace(/\{(\d+)\}/g, function (match, number) {
            var result = args[number] || match;
            return result;
        });
    };
}

main(argc, argv);
<commit_msg>Added two additional places to find urls when parsing.<commit_after>/*jslint indent: 4, node: true */
/*global require: false, process: false */

var http = require('http'),
    path = require('path'),
    fs = require('fs'),
    url = require('url'),
    htmlparser = require('htmlparser2'), // npm install htmlparser2 -g
    async = require('async'), //npm install async -g
    downloadFile = function (uri, filename, callback) {
        "use strict";

        var downloadError = function (err) {
                callback(err.message, {'url': uri});
            },
            downloadStart = function (res) {

                // Don't create the file until we get the response.
                var file = fs.createWriteStream(filename);

                res.on('data', function (chunk) {

                    file.write(chunk, 'binary');
                });
                res.on('end', function () {

                    file.end();
                    callback(null, { 'url': uri, 'filename': filename });
                });
            },
            directoryReady = function (err) {
                var req = {};

                if (err && err.code !== 'EEXIST') {
                    callback(err.code, {'url': uri});
                } else {
                    req = http.get(uri, downloadStart);
                    req.on('error', downloadError);
                }
            },
            directory = path.dirname(filename);

        fs.mkdir(directory, directoryReady);
    },
    getHTML = function (uri, callback) {
        "use strict";

        var req = http.get(uri, function (res) {

            var output = '';

            res.setEncoding('utf8');

            res.on('data', function (chunk) {

                output += chunk;
            });

            res.on('end', function () {

                callback(null, { 'status': res.statusCode, 'text': output });
            });
        });
        req.on('error', function (err) {
            callback(err.message, null);
        });
    },
    parseHtml = function (sourceUrl, callback) {
        "use strict";

        var results = [];

        getHTML(sourceUrl, function (err, response) {

            var whenOpenTag = function (name, attribs) {
                    if (name === 'a') {
                        if (attribs.href) {
                            results.push(url.resolve(sourceUrl, attribs.href));
                        }
                    } else if (name === 'img') {
                        if (attribs.src) {
                            results.push(url.resolve(sourceUrl, attribs.src));
                        }
                        if (attribs["data-src"]) {
                            results.push(url.resolve(sourceUrl, attribs["data-src"]));
                        }
                    } else if (name === 'iframe') {
                        if (attribs.src) {
                            results.push(url.resolve(sourceUrl, attribs.src));
                        }
                    } else if (name === 'meta') {
                        if (attribs.content) {
                            results.push(url.resolve(sourceUrl, attribs.content));
                        }
                    }
                },
                parser = new htmlparser.Parser({
                    onopentag: whenOpenTag,
                });

            if (err) {
                callback(err, { 'sourceUrl': sourceUrl });
            } else if (response.status === 200) {
                parser.write(response.text);
                parser.end();
                callback(null, { 'sourceUrl': sourceUrl, 'urlsFound': results });
            } else {
                callback(response.status, { 'sourceUrl': sourceUrl });
            }
        });
    },
    getOperationChain = function (filename, callback) {
        "use strict";

        var result = {};

        fs.readFile(filename, { 'encoding': "utf8" }, function (err, data) {
            if (err) {
                console.log('failed to read operation chain');
                callback(err, null);
            } else {
                result = JSON.parse(data);

                callback(null, result);
            }
        });
    },
    pruneDuplicates = function (list) {
        "use strict";

        var count = list.length,
            i = 0,
            map = {};

        for (i = 0; i < count; i += 1) {
            map[list[i]] = true;
        }

        list = [];
        for (i in map) {
            if (map.hasOwnProperty(i)) {
                list.push(i);
            }
        }

        return list.sort();
    },
    //  {
    //    "operation": "download",
    //    "input": [url, ...],
    //    "pattern": ".*\/([^\/]+)\/([^\/]+)"
    //    "filename": "{1}"
    //    "directory": "{0}"
    //    "output": [url, ...] - that failed to download
    //  }
    //
    operationDownload = function (operation, callback) {
        "use strict";

        var downloads = 0,
            processDownload = function (err, result) {

                if (err) {
                    operation.output.push(result.url);
                    console.log('ERROR downloading: ' + result.url + '\n          message: ' + err.message);
                } else {
                    console.log('Downloaded (' + downloads + ' remaining): ' + result.url);
                }

                downloads -= 1;

                if (downloads === 0) {
                    callback(operation);
                }
            },
            startDownload = function (element) {

                var re = {},
                    matches = [],
                    filename = '',
                    directory = path.resolve('.', '.');

                if (operation.pattern) {

                    if (operation.pattern[0] !== '^' || operation.pattern[operation.pattern.length - 1] !== '$') {
                        console.log('ERROR: pattern must begin with ^ and end with $');
                        return;
                    }

                    re = new RegExp(operation.pattern);
                    matches = element.match(re);

                    if (operation.filename) {
                        filename = operation.filename.format(matches);
                    }

                    if (operation.directory) {
                        directory = operation.directory.format(matches);
                    }
                }

                if (filename === '') {
                    filename = element.substr(element.lastIndexOf('/') + 1);
                }

                filename = path.resolve(directory, filename);

                if (operation.debug) {
                    console.log('directory: ' + directory);
                    console.log('filename : ' + filename);
                } else {
                    downloadFile(element, filename, processDownload);
                }
            };

        downloads = operation.input.length;
        operation.input.forEach(startDownload);
    },
    //  {
    //    "operation": "parse",
    //    "input": [url, ...],
    //    "output": [url, ...] - urls found from downloading and parsing the input urls
    //  }
    //
    operationParse = function (operation, callback) {
        "use strict";

        var pages = 0,
            processPage = function (err, result) {

                if (err) {
                    console.log('ERROR parsing: ' + result.sourceUrl + '\n      message: ' + err.message);
                } else {
                    operation.output = operation.output.concat(result.urlsFound);
                    console.log('Parsed (' + pages + ' remaining): ' + result.sourceUrl);
                }

                pages -= 1;

                if (pages === 0) {
                    if (operation.debug) {
                        console.log(pruneDuplicates(operation.output));
                    }

                    callback(operation);
                }
            },
            startFetch = function (element) {

                parseHtml(element, processPage);
            };

        pages = operation.input.length;
        operation.input.forEach(startFetch);
    },
    //  {
    //    "operation": "filter",
    //    "input": [url, ...],
    //    "include": "text1"
    //    "exclude": "text2"
    //    "output": [url, ...] - urls that contained text1 but not text2
    //  }
    //
    operationFilter = function (operation, callback) {
        "use strict";

        var re = {};

        if (operation.include) {
            if (operation.include[0] !== '^' || operation.include[operation.include.length - 1] !== '$') {
                console.log('ERROR: include must begin with ^ and end with $');
                return;
            }

            re = new RegExp(operation.include);

            operation.output = operation.input.filter(function (item) {
                return re.test(item);
            });
        } else {
            operation.output = operation.input;
        }

        if (operation.exclude) {
            if (operation.exclude[0] !== '^' || operation.exclude[operation.exclude.length - 1] !== '$') {
                console.log('ERROR: exclude must begin with ^ and end with $');
                return;
            }

            re = new RegExp(operation.exclude);

            operation.output = operation.output.filter(function (item) {
                return !re.test(item);
            });
        }

        if (operation.debug) {
            console.log(operation.output);
        }

        process.nextTick(function () {
            callback(operation);
        });
    },
    //  {
    //    "operation": "generate",
    //    "input": [url, ...],
    //    "patterns": [url, ...],
    //    "start": 2
    //    "increment": 1
    //    "end" : 10
    //    "output": [url, ...] - for each url in input replaces {0} with values from start to end increased by increment unitl the value exceeds end
    //  }
    //
    operationGenerate = function (operation, callback) {
        "use strict";

        var patterns = operation.patterns || [],
            count = patterns.length,
            start = operation.start || 0,
            increment = operation.increment || 1,
            end = operation.end || 0,
            i = 0,
            value = 0;

        operation.output = operation.input;

        for (i = 0; i < count; i += 1) {
            for (value = start; value <= end; value += increment) {
                operation.output.push(operation.patterns[i].format(value));
            }
        }

        if (operation.debug) {
            console.log(pruneDuplicates(operation.output));
        }

        process.nextTick(function () {
            callback(operation);
        });
    },
    operations = [],
    doNextOperation = function (operation) {
        "use strict";

        var nextOperation = operations.pop(),
            input = [];

        if (operation) {
            input = pruneDuplicates(operation.output);
        }

        if (nextOperation) {
            if (nextOperation.input && nextOperation.input.length > 0) {
                input = input.concat(nextOperation.input);
            }
            nextOperation.input = input;
            nextOperation.output = nextOperation.output || [];
            nextOperation.output = nextOperation.output || [];
            nextOperation.operation = nextOperation.operation || '';
            nextOperation.debug = nextOperation.debug || false;

            switch (nextOperation.operation) {
            case 'download':
                operationDownload(nextOperation, doNextOperation);
                break;
            case 'parse':
                operationParse(nextOperation, doNextOperation);
                break;
            case 'filter':
                operationFilter(nextOperation, doNextOperation);
                break;
            case 'generate':
                operationGenerate(nextOperation, doNextOperation);
                break;
            }
        } else {
            if (input.length > 0) {
                console.log(input);
            }
        }
    },
    main = function (argc, argv) {
        "use strict";

        if (argc < 3) {
            console.log('usage: %s %s <filename>', argv[0], argv[1]);
        } else {
            getOperationChain(path.resolve('.', argv[2]), function (err, result) {
                if (err) {
                    console.log(err);
                } else {
                    operations = result.reverse();

                    process.nextTick(function () {
                        doNextOperation(null);
                    });
                }
            });
        }
    },
    argv = process.argv,
    argc = argv.length;

if (!String.prototype.format) {
    String.prototype.format = function () {
        "use strict";

        var args = arguments;

        // If we are passed an array then just use that.
        if (args.length === 1 && typeof args[0] === "object") {
            args = args[0];
        }

        return this.replace(/\{(\d+)\}/g, function (match, number) {
            var result = args[number] || match;
            return result;
        });
    };
}

main(argc, argv);
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Alert,
  Platform
} from 'react-native';
import {Navigation} from 'react-native-navigation';

export default class History extends Component {
  static navigatorButtons = {
    leftButtons: [{
      icon: require('../../img/navicon_menu.png'),
      id: 'menu'
    }]
  };
  static navigatorStyle = {
    navBarBackgroundColor: '#336600',
    navBarTextColor: 'white',
    navBarSubtitleTextColor: '#ff0000',
    navBarButtonColor: '#ffffff',
    statusBarTextColorScheme: 'light',
    tabBarBackgroundColor: '#4dbce9',
    tabBarButtonColor: '#ffffff',
    tabBarSelectedButtonColor: '#ffff00'
  };

  constructor(props) {
    super(props);
    // if you want to listen on navigator events, set this up
    this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
  }

  onNavigatorEvent(event) {
    if (event.id === 'menu') {
      this.props.navigator.toggleDrawer({
        side: 'left',
        animated: true
      });
    }
    if (event.id === 'shop') {
      Alert.alert('NavBar', 'Edit button pressed');
    }
    if (event.id === 'add') {
      Alert.alert('NavBar', 'Add button pressed');
    }
  }

  render() {
    return (
      <View style={{flex: 1, padding: 20}}>
        <Text> Lịch sử
        </Text>
      </View>
    );
  }

//   onLightBoxPress() {
//     this.props.navigator.showLightBox({
//       screen: "example.LightBoxScreen",
//       style: {
//         backgroundBlur: "dark"
//       },
//       passProps: {
//         greeting: 'hey there'
//       },
//     });
//   }
//
//   onInAppNotificationPress() {
//     this.props.navigator.showInAppNotification({
//       screen: "example.NotificationScreen"
//     });
//   }
//
}

const styles = StyleSheet.create({
  button: {
    textAlign: 'center',
    fontSize: 18,
    marginBottom: 10,
    marginTop: 10,
    color: 'blue'
  }
});
<commit_msg>Thêm list và datepicker vào tab lịch sử ( thêm info commit tiếp )<commit_after>import React, {Component} from 'react';
import {
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Alert,
  Platform,
  ListView
} from 'react-native';

import {Navigation} from 'react-native-navigation';
import DatePicker from 'react-native-datepicker';

var moment = require('moment');

var data = [
  {dateOfEvent: '11/12/1995', customerName: 'Nguyen Van A', phonenumber: '01292844648', status: 'Resolved' },
  {dateOfEvent: '11/12/1995', customerName: 'Nguyen Van A', phonenumber: '01292844648', status: 'Resolved' },
  {dateOfEvent: '11/12/1995', customerName: 'Nguyen Van A', phonenumber: '01292844648', status: 'Resolved' },
  {dateOfEvent: '11/12/1995', customerName: 'Nguyen Van A', phonenumber: '01292844648', status: 'Resolved' },
  {dateOfEvent: '11/12/1995', customerName: 'Nguyen Van A', phonenumber: '01292844648', status: 'Resolved' },
  {dateOfEvent: '11/12/1995', customerName: 'Nguyen Van A', phonenumber: '01292844648', status: 'Resolved' },
  {dateOfEvent: '11/12/1995', customerName: 'Nguyen Van A', phonenumber: '01292844648', status: 'Resolved' },
  {dateOfEvent: '11/12/1995', customerName: 'Nguyen Van A', phonenumber: '01292844648', status: 'Resolved' },
  {dateOfEvent: '11/12/1995', customerName: 'Nguyen Van A', phonenumber: '01292844648', status: 'Resolved' }
];

export default class History extends Component {
  static navigatorButtons = {
    leftButtons: [{
      icon: require('../../img/navicon_menu.png'),
      id: 'menu'
    }]
  };
  static navigatorStyle = {
    navBarBackgroundColor: '#336600',
    navBarTextColor: 'white',
    navBarSubtitleTextColor: '#ff0000',
    navBarButtonColor: '#ffffff',
    statusBarTextColorScheme: 'light',
    tabBarBackgroundColor: '#4dbce9',
    tabBarButtonColor: '#ffffff',
    tabBarSelectedButtonColor: '#ffff00'
  };

  constructor(props) {
    super(props);
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    // if you want to listen on navigator events, set this up
    this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
    this.state = {
          dataSource: ds.cloneWithRows(data),
          date: new Date()
        };
        this._renderRow = this._renderRow.bind(this);
  }

  onNavigatorEvent(event) {
    if (event.id === 'menu') {
      this.props.navigator.toggleDrawer({
        side: 'left',
        animated: true
      });
    }
    if (event.id === 'shop') {
      Alert.alert('NavBar', 'Edit button pressed');
    }
    if (event.id === 'add') {
      Alert.alert('NavBar', 'Add button pressed');
    }
  }

  _renderRow(data) {
      return (
        <TouchableOpacity style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', alignItems: 'center', borderBottomWidth: 1, borderColor: '#CFD8DC'}}>
          <Text style={{ padding: 7, fontSize: 11, fontWeight: 'bold'}}>{data.dateOfEvent}</Text>
          <Text style={{ padding: 7, fontSize: 11, fontWeight: 'bold'}}>{data.customerName}</Text>
          <Text style={{ padding: 7, fontSize: 11, fontWeight: 'bold'}}>{data.phonenumber}</Text>
          <Text style={{ padding: 7, fontSize: 11, fontWeight: 'bold'}}>{data.status}</Text>
        </TouchableOpacity>
      );
    }

  render() {
    return (
      <View style={{flex: 1, backgroundColor: '#CFD8DC', justifyContent: 'center'}}>
        <View style={{backgroundColor: '#FAFAFA', padding: 12, marginTop: 12, marginBottom: 12, alignSelf: 'center', borderRadius: 6}}>
          <DatePicker
                style={{width: 200, marginBottom:10, alignSelf: 'center', marginTop: 12}}
                date={this.state.date}
                mode="date"
                duration={300}
                placeholder="select date"
                format="YYYY-MM-DD"
                minDate= {moment().subtract(365, 'days').toDate()}
                maxDate= {this.state.date}
                confirmBtnText="Confirm"
                cancelBtnText="Cancel"
                customStyles={{
                    dateIcon: {
                        position: 'absolute',
                        left: 0,
                        top: 4,
                        marginLeft: 0
                    },
                    dateInput: {
                        marginLeft: 36,
                        backgroundColor: '#eee',
                        borderRadius: 8
                    }
                }}
                onDateChange={(date) => {this.setState({date: date})}}
            />
          <View style={{ marginTop: 20, alignSelf: 'center'}}>
                    <View style={{ flexDirection: 'row', alignSelf: 'center', alignItems: 'center', justifyContent: 'center', borderBottomWidth: 1, borderColor: '#CFD8DC'}}>
                      <Text style={{ padding: 7, fontSize: 11, fontWeight: 'bold'}}>Ngày</Text>
                      <Text style={{ padding: 7, fontSize: 11, fontWeight: 'bold'}}>Tên</Text>
                      <Text style={{ padding: 7, fontSize: 11, fontWeight: 'bold'}}>SĐT</Text>
                      <Text style={{ padding: 7, fontSize: 11, fontWeight: 'bold'}}>Tình trạng</Text>
                    </View>
                   <ListView
                     dataSource={this.state.dataSource}
                     renderRow={(data) => this._renderRow(data)}
                   />
                 </View>
        </View>
      </View>
    );
  }
}
<|endoftext|>


<commit_before>$.getJSON('bird.json', function(bird) {
  var template = $('#personTpl').html();
  var compiled = Handlebars.compile(template)
  var html = compiled(bird)
  $('#sampleArea').html(html);
});
<commit_msg>Fall back to Mustache.JS<commit_after>jQuery.getJSON('bird.json', function(bird) {
    var template = jQuery('#personTpl').html();
    var html = Mustache.to_html(template, bird);
    jQuery('#sampleArea').html(html);
});
<|endoftext|>


<commit_before>(function(){
    'use strict';

    var DIR         = __dirname     + '/',
        main        = require(DIR   + 'lib/server/main'),

        LIBDIR      = main.LIBDIR,
        SRVDIR      = main.SRVDIR,
        CLIENTDIR   = LIBDIR + 'client',
        HTMLDIR     = main.HTMLDIR,
        JSONDIR     = main.JSONDIR,

        path        = main.path,
        fs          = main.fs,
        CloudFunc   = main.cloudfunc,
        AppCache    = main.appcache,
        Util        = main.util,
        update      = main.update,

        server      = main.librequire('server'),
        Minify      = main.minify,
        Config      = main.config,

        INDEX       = HTMLDIR + 'index.html',
        CONFIG_PATH = JSONDIR + 'config.json',

        CA          = DIR + 'ssl/sub.class1.server.ca.pem',
        KEY         = DIR + 'ssl/ssl.key',
        CERT        = DIR + 'ssl/ssl.crt',

        FILE_TMPL   = HTMLDIR + 'file.html',

        PATH_TMPL   = HTMLDIR + 'path.html',

        FileTemplate, PathTemplate,

        FS          = CloudFunc.FS;
        /* reinit main dir os if we on Win32 should be backslashes */
        DIR         = main.DIR;

    readConfig(init);

    /**
     * additional processing of index file
     */
    function indexProcessing(pData){
        var lData       = pData.data,
            lAdditional = pData.additional;

        /*
         * если выбрана опция минимизировать скрипты
         * меняем в index.html обычные css на
         * минифицированый
         */
        if(Minify.allowed.css){
            var lPath       = '/' + Util.removeStr(Minify.MinFolder, DIR),
                lReplace    = '<link rel=stylesheet href="/css/reset.css">';
            lData = Util.removeStr(lData, lReplace)
                    .replace('/css/style.css', lPath + 'all.min.css');
        }

        lData = Util.render(lData, {
            title   : CloudFunc.getTitle(),
            fm      : lAdditional
        });

        if(!Config.appcache)
            lData = Util.removeStr(lData, ' manifest="/cloudcmd.appcache"');

        if(!Config.show_keys_panel){
            var lKeysPanel = '<div id=keyspanel';
            lData = lData.replace(lKeysPanel, lKeysPanel +' class=hidden');
        }

        return lData;

    }

    /**
     * init and process of appcache if it allowed in config
     */
    function appCacheProcessing(){
        var lFiles = [
                {'//themes.googleusercontent.com/static/fonts/droidsansmono/v4/ns-m2xQYezAtqh7ai59hJUYuTAAIFFn5GTWtryCmBQ4.woff' : './font/DroidSansMono.woff'},
                {'//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js' : './lib/client/jquery.js'}];

        if(Config.minification.css)
            lFiles.push('node_modules/minify/min/all.min.css');

        AppCache.addFiles(lFiles);
        AppCache.createManifest();
    }

    /**
     * Функция минимизирует css/js/html
     * если установлены параметры минимизации
     */
    function minimize(pAllowed){
        var lOptimizeParams = [],
            lStyleCSS   = DIR + 'css/style.css',
            lResetCSS   = DIR + 'css/reset.css',

            lCSSOptions = {
                img     : pAllowed.img,
                merge   : true
            };

        if (pAllowed.js)
            lOptimizeParams.push(LIBDIR + 'client.js');

        if (pAllowed.html)
            lOptimizeParams.push(INDEX);

        if (pAllowed.css) {
            var lStyles = [{}, {}];
            lStyles[0][lStyleCSS]   = lCSSOptions;
            lStyles[1][lResetCSS]   = lCSSOptions;

            lOptimizeParams.push(lStyles[0]);
            lOptimizeParams.push(lStyles[1]);
        }

        if (lOptimizeParams.length)
            Minify.optimize(lOptimizeParams, {
                force: true
            });
    }

    /**
     * rest interface
     * @pParams pConnectionData {request, responce}
     */
    function rest(pConnectionData){
        return Util.exec(main.rest, pConnectionData);
    }

    function init(){
        if(update)
            update.get();

        /* Determining server.js directory
         * and chang current process directory
         * (usually /) to it.
         * argv[1] - is always script name
         */
        var lServerDir = path.dirname(process.argv[1]) + '/';

        if( DIR !== lServerDir ){
            Util.log('current dir: ' + DIR);
            process.chdir(lServerDir);
        }
        Util.log('server dir:  ' + lServerDir);
        Util.log('reading configuration file config.json...');

        if(Config){
            Util.log('config.json readed');

            /* if command line parameter testing resolved
             * setting config to testing, so server
             * not created, just init and
             * all logs writed to screen
             */
            var lArg = process.argv;
                lArg = lArg[lArg.length - 1];
            if ( lArg === 'test' ||  lArg === 'test\r') {
                Util.log(process.argv);
                Config.server  = false;
            }

            if (Config.logs) {
                Util.log('log param setted up in config.json\n' +
                    'from now all logs will be writed to log.txt');
                writeLogsToFile();
            }

            if(Config.server)
                fs.watch(CONFIG_PATH, function(){
                    /* every catch up - calling twice */
                    setTimeout(function() {
                        readConfig();
                    }, 1000);
                });

            var lParams = {
                appcache    : appCacheProcessing,
                minimize    : minimize,
                rest        : rest,
                route       : route
            };

            var lFiles = [FILE_TMPL, PATH_TMPL];

            if(Config.ssl)
                lFiles.push(CA, KEY, CERT);

            main.readFiles(lFiles, function(pErrors, pFiles){
                if(pErrors)
                    Util.log(pErrors);
                else{
                    FileTemplate        = pFiles[FILE_TMPL].toString();
                    PathTemplate    = pFiles[PATH_TMPL].toString();

                    if(Config.ssl)
                        lParams.ssl = {
                            ca      : pFiles[CA],
                            key     : pFiles[KEY],
                            cert    : pFiles[CERT]
                        };

                    server.start(lParams);
                }
            });
        }
        else
            Util.log('read error: config.json');
    }

    function readConfig(pCallBack){
        fs.readFile(CONFIG_PATH, function(pError, pData){
            if(!pError){
                Util.log('config: readed');

                var lStr            = pData.toString(),
                    lReadedConf     = Util.parseJSON(lStr);

                if(!Config.minification)
                    main.config = Config = lReadedConf;

                Util.tryCatchLog(function(){
                    Config.minification.js  = lReadedConf.minification.js;
                    Config.cache            = lReadedConf.cache;

                    Minify.setAllowed(Config.minification);
                });
            }
            else
                Util.log(pError);

            Util.exec(pCallBack);
        });
    }

    /**
     * routing of server queries
     */
    function route(pParams){
        var lRet = main.checkParams(pParams);

        if(lRet){
            var p = pParams;

            if( Util.strCmp(p.name, ['/auth', '/auth/github']) ){
                Util.log('* Routing' +
                    '-> ' + p.name);
                pParams.name = main.HTMLDIR + p.name + '.html';
                lRet = main.sendFile( pParams );
            }
            else if( Util.isContainStrAtBegin(p.name, FS) || Util.strCmp( p.name, '/') ){

                if( Util.isContainStrAtBegin(p.name, FS + 'no-js/') ){
                    var lURL = Util.removeStr(pParams.name, 'no-js/');
                    return main.redirect(pParams, lURL);
                }

                lRet = sendCommanderContent(p);
            }
            /* termporary redirect for old urls */
            else
                lRet = false;
        }

        return lRet;
    }

    function sendCommanderContent(pParams){
        var lRet = main.checkParams(pParams);
        if(lRet){
            var p  = pParams;
            p.name = Util.removeStrOneTime(p.name, CloudFunc.FS) || main.SLASH;

            fs.stat(p.name, function(pError, pStat){
                if(!pError)
                    if( pStat.isDirectory() )
                        processCommanderContent(pParams);
                    else
                        main.sendFile(p);
                else
                    main.sendError(pParams, pError);

           });
        }

        return lRet;
    }

    function processCommanderContent(pParams){
        var lRet = main.checkParams(pParams);
        if(lRet){
            var p = pParams;
            main.commander.getDirContent(p.name, function(pError, pJSON){
                if(!pError){
                    var lQuery = main.getQuery(p.request);
                    if( Util.isContainStr(lQuery, 'json') ){
                        p.data  = Util.stringifyJSON(pJSON);
                        p.name +='.json';
                        main.sendResponse(p);
                    }
                    else if(!lQuery){ /* get back html*/
                        p.name   = Minify.allowed.html ? Minify.getName(INDEX) : INDEX;
                        fs.readFile(p.name, function(pError, pData){
                            if(!pError){
                                var lPanel  = CloudFunc.buildFromJSON(pJSON, FileTemplate, PathTemplate),
                                    lList   = '
'  + lPanel + '
' +
                                              '
' + lPanel + '
';

                                main.sendResponse(p, indexProcessing({
                                    additional  : lList,
                                    data        : pData.toString(),
                                }));
                            }
                            else
                                main.sendError(pParams, pError);
                        });
                    }
                }
                else
                    main.sendError(pParams, pError);
            });
        }
    }

    /* function sets stdout to file log.txt */
    function writeLogsToFile(){
        var stdo = fs.createWriteStream('./log.txt');

        process.stdout.write = (function(write) {
            return function(string, encoding, fd) {
                    stdo.write(string);
            };
        })(process.stdout.write);
    }
})();<commit_msg>minor changes<commit_after>(function(){
    'use strict';

    var DIR         = __dirname     + '/',
        main        = require(DIR   + 'lib/server/main'),

        LIBDIR      = main.LIBDIR,
        SRVDIR      = main.SRVDIR,
        CLIENTDIR   = LIBDIR + 'client',
        HTMLDIR     = main.HTMLDIR,
        JSONDIR     = main.JSONDIR,

        path        = main.path,
        fs          = main.fs,
        CloudFunc   = main.cloudfunc,
        AppCache    = main.appcache,
        Util        = main.util,
        update      = main.update,

        server      = main.librequire('server'),
        Minify      = main.minify,
        Config      = main.config,

        INDEX       = HTMLDIR + 'index.html',
        CONFIG_PATH = JSONDIR + 'config.json',

        CA          = DIR + 'ssl/sub.class1.server.ca.pem',
        KEY         = DIR + 'ssl/ssl.key',
        CERT        = DIR + 'ssl/ssl.crt',

        FILE_TMPL   = HTMLDIR + 'file.html',

        PATH_TMPL   = HTMLDIR + 'path.html',

        FileTemplate, PathTemplate,

        FS          = CloudFunc.FS;
        /* reinit main dir os if we on Win32 should be backslashes */
        DIR         = main.DIR;

    readConfig(init);

    /**
     * additional processing of index file
     */
    function indexProcessing(pData){
        var lData       = pData.data,
            lAdditional = pData.additional;

        /*
         * если выбрана опция минимизировать скрипты
         * меняем в index.html обычные css на
         * минифицированый
         */
        if(Minify.allowed.css){
            var lPath       = '/' + Util.removeStr(Minify.MinFolder, DIR),
                lReplace    = '<link rel=stylesheet href="/css/reset.css">';
            lData = Util.removeStr(lData, lReplace)
                    .replace('/css/style.css', lPath + 'all.min.css');
        }

        lData = Util.render(lData, {
            title   : CloudFunc.getTitle(),
            fm      : lAdditional
        });

        if(!Config.appcache)
            lData = Util.removeStr(lData, ' manifest="/cloudcmd.appcache"');

        if(!Config.show_keys_panel){
            var lKeysPanel = '<div id=keyspanel';
            lData = lData.replace(lKeysPanel, lKeysPanel +' class=hidden');
        }

        return lData;

    }

    /**
     * init and process of appcache if it allowed in config
     */
    function appCacheProcessing(){
        var lFONT_REMOTE    = '//themes.googleusercontent.com/static/fonts/droidsansmono/v4/ns-m2xQYezAtqh7ai59hJUYuTAAIFFn5GTWtryCmBQ4.woff',
            lFONT_LOCAL     = './font/DroidSansMono.woff',
            lJQUERY_REMOTE  = '//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js',
            lJQUERY_LOCAL   = './lib/client/jquery.js',
            lFiles = [
                { lFONT_REMOTE   : lFONT_LOCAL   },
                { lJQUERY_REMOTE : lJQUERY_LOCAL }];

        if(Config.minification.css)
            lFiles.push('node_modules/minify/min/all.min.css');

        AppCache.addFiles(lFiles);
        AppCache.createManifest();
    }

    /**
     * Функция минимизирует css/js/html
     * если установлены параметры минимизации
     */
    function minimize(pAllowed){
        var lOptimizeParams = [],
            lStyleCSS   = DIR + 'css/style.css',
            lResetCSS   = DIR + 'css/reset.css',

            lCSSOptions = {
                img     : pAllowed.img,
                merge   : true
            };

        if (pAllowed.js)
            lOptimizeParams.push(LIBDIR + 'client.js');

        if (pAllowed.html)
            lOptimizeParams.push(INDEX);

        if (pAllowed.css) {
            var lStyles = [{}, {}];
            lStyles[0][lStyleCSS]   = lCSSOptions;
            lStyles[1][lResetCSS]   = lCSSOptions;

            lOptimizeParams.push(lStyles[0]);
            lOptimizeParams.push(lStyles[1]);
        }

        if (lOptimizeParams.length)
            Minify.optimize(lOptimizeParams, {
                force: true
            });
    }

    /**
     * rest interface
     * @pParams pConnectionData {request, responce}
     */
    function rest(pConnectionData){
        return Util.exec(main.rest, pConnectionData);
    }

    function init(){
        if(update)
            update.get();

        /* Determining server.js directory
         * and chang current process directory
         * (usually /) to it.
         * argv[1] - is always script name
         */
        var lServerDir = path.dirname(process.argv[1]) + '/';

        if( DIR !== lServerDir ){
            Util.log('current dir: ' + DIR);
            process.chdir(lServerDir);
        }
        Util.log('server dir:  ' + lServerDir);
        Util.log('reading configuration file config.json...');

        if(Config){
            Util.log('config.json readed');

            /* if command line parameter testing resolved
             * setting config to testing, so server
             * not created, just init and
             * all logs writed to screen */
            var lArg = process.argv;
                lArg = lArg[lArg.length - 1];
            if ( lArg === 'test' ||  lArg === 'test\r') {
                Util.log(process.argv);
                Config.server  = false;
            }

            if (Config.logs) {
                Util.log('log param setted up in config.json\n' +
                    'from now all logs will be writed to log.txt');
                writeLogsToFile();
            }

            if(Config.server)
                fs.watch(CONFIG_PATH, function(){
                    /* every catch up - calling twice */
                    setTimeout(function() {
                        readConfig();
                    }, 1000);
                });

            var lParams = {
                appcache    : appCacheProcessing,
                minimize    : minimize,
                rest        : rest,
                route       : route
            },
                lFiles = [FILE_TMPL, PATH_TMPL];

            if(Config.ssl)
                lFiles.push(CA, KEY, CERT);

            main.readFiles(lFiles, function(pErrors, pFiles){
                if(pErrors)
                    Util.log(pErrors);
                else{
                    FileTemplate        = pFiles[FILE_TMPL].toString();
                    PathTemplate    = pFiles[PATH_TMPL].toString();

                    if(Config.ssl)
                        lParams.ssl = {
                            ca      : pFiles[CA],
                            key     : pFiles[KEY],
                            cert    : pFiles[CERT]
                        };

                    server.start(lParams);
                }
            });
        }
        else
            Util.log('read error: config.json');
    }

    function readConfig(pCallBack){
        fs.readFile(CONFIG_PATH, function(pError, pData){
            if(!pError){
                Util.log('config: readed');

                var lStr            = pData.toString(),
                    lReadedConf     = Util.parseJSON(lStr);

                if(!Config.minification)
                    main.config = Config = lReadedConf;

                Util.tryCatchLog(function(){
                    Config.minification.js  = lReadedConf.minification.js;
                    Config.cache            = lReadedConf.cache;

                    Minify.setAllowed(Config.minification);
                });
            }
            else
                Util.log(pError);

            Util.exec(pCallBack);
        });
    }

    /**
     * routing of server queries
     */
    function route(pParams){
        var lRet = main.checkParams(pParams);

        if(lRet){
            var p = pParams;

            if( Util.strCmp(p.name, ['/auth', '/auth/github']) ){
                Util.log('* Routing' +
                    '-> ' + p.name);

                pParams.name    = main.HTMLDIR + p.name + '.html';
                lRet            = main.sendFile( pParams );
            }
            else if( Util.isContainStrAtBegin(p.name, FS) || Util.strCmp( p.name, '/') ){

                if( Util.isContainStrAtBegin(p.name, FS + 'no-js/') ){
                    var lURL = Util.removeStr(pParams.name, 'no-js/');
                    return main.redirect(pParams, lURL);
                }

                lRet = sendCommanderContent(p);
            }
            /* termporary redirect for old urls */
            else
                lRet = false;
        }

        return lRet;
    }

    function sendCommanderContent(pParams){
        var lRet = main.checkParams(pParams);
        if(lRet){
            var p  = pParams;
            p.name = Util.removeStrOneTime(p.name, CloudFunc.FS) || main.SLASH;

            fs.stat(p.name, function(pError, pStat){
                if(!pError)
                    if( pStat.isDirectory() )
                        processCommanderContent(pParams);
                    else
                        main.sendFile(p);
                else
                    main.sendError(pParams, pError);

           });
        }

        return lRet;
    }

    function processCommanderContent(pParams){
        var lRet = main.checkParams(pParams);
        if(lRet){
            var p = pParams;
            main.commander.getDirContent(p.name, function(pError, pJSON){
                if(!pError){
                    var lQuery = main.getQuery(p.request);
                    if( Util.isContainStr(lQuery, 'json') ){
                        p.data  = Util.stringifyJSON(pJSON);
                        p.name +='.json';
                        main.sendResponse(p);
                    }
                    else if(!lQuery){ /* get back html*/
                        p.name   = Minify.allowed.html ? Minify.getName(INDEX) : INDEX;
                        fs.readFile(p.name, function(pError, pData){
                            if(!pError){
                                var lPanel  = CloudFunc.buildFromJSON(pJSON, FileTemplate, PathTemplate),
                                    lList   = '
'  + lPanel + '
' +
                                              '
' + lPanel + '
';

                                main.sendResponse(p, indexProcessing({
                                    additional  : lList,
                                    data        : pData.toString(),
                                }));
                            }
                            else
                                main.sendError(pParams, pError);
                        });
                    }
                }
                else
                    main.sendError(pParams, pError);
            });
        }
    }

    /* function sets stdout to file log.txt */
    function writeLogsToFile(){
        var stdo = fs.createWriteStream('./log.txt');

        process.stdout.write = (function(write) {
            return function(string, encoding, fd) {
                    stdo.write(string);
            };
        })(process.stdout.write);
    }
})();<|endoftext|>


<commit_before>'use strict';
var States = States || {}
  , Main   = new Phaser.State();

Main.create = function() {
  console.log('Game has begun');
  this.add.existing(new Jeep(Main.game, 150, 150));
};

States.Main = Main;<commit_msg>added environmental elements<commit_after>'use strict';
var States = States || {}
  , Main   = new Phaser.State()
  , ground, fog1, fog2;
var explode;
Main.create = function() {
  // Background
  this.add.image(0, 0, 'environment', 'sky').height = this.game.height;
  var trees1 = Main.add.image(0,this.game.height - 10, 'environment', 'trees1');
  trees1.width = Main.game.width;
  trees1.alpha = 0.3;
  trees1.anchor.y = 1.0;
  var trees2 = Main.add.image(0,Main.game.height - 20, 'environment', 'trees2');
  trees2.width = Main.game.width;
  trees2.alpha = 0.2;
  trees2.anchor.y = 1.0;

  // Fog 1
  fog1 = Main.add.tileSprite(0, Main.game.height, 2400, 400, 'environment', 'dust1');
  fog1.anchor.y = 1.0;
  fog1.alpha = 0.5;

  // Ground
  ground = this.add.sprite(0, this.game.height, 'environment', 'ground');
  ground.width = this.game.width;
  ground.anchor.y = 1.0;

  // Fog 2
  fog2 = Main.add.tileSprite(0, Main.game.height, 2400, 400, 'environment', 'dust2');
  fog2.anchor.y = 1.0;
  fog2.alpha = 0.5;

  //this.add.existing(new Jeep(Main.game, 150, 150));
  //this.add.existing(new Explosion(Main.game, 150, 150));

  console.log('Game has begun');
};

Main.update = function() {
  fog1.x -= 0.5;
  fog2.x -= 1;
};

States.Main = Main;<|endoftext|>


<commit_before>export { default as absToChr } from './abs-to-chr';
export { default as chromInfoBisector } from './chrom-info-bisector';
export { default as scalesToGenomeLoci } from './scales-to-genome-loci';
<commit_msg>Add pixelToGenomeLoci export<commit_after>export { default as absToChr } from './abs-to-chr';
export { default as chromInfoBisector } from './chrom-info-bisector';
export { default as pixelToGenomeLoci } from './pixel-to-genome-loci';
export { default as scalesToGenomeLoci } from './scales-to-genome-loci';
<|endoftext|>


<commit_before>'use strict';

/**
 * ButtressJS - Realtime datastore for business software
 *
 * @file route.js
 * @description Route Class - Route authorisation (against app permissions), validation and execution
 * @module System
 * @author Chris Bates-Keegan
 *
 */

const Config = require('../config');
const Logging = require('../logging');
const Model = require('../model');
const Helpers = require('../helpers');
// var OTP = require('../stotp');
const _ = require('underscore');

/**
 */
// var _otp = OTP.create({
//   length: 12,
//   mode: OTP.Constants.Mode.ALPHANUMERIC,
//   salt: Config.RHIZOME_OTP_SALT,
//   tolerance: 3
// });

var _app = null;
var _io = null;

/**
 * @type {{Auth: {
 *          NONE: number,
 *          USER: number,
 *          ADMIN: number,
 *          SUPER: number},
 *         Permissions: {
 *          NONE: string,
 *          ADD: string,
 *          READ: string,
 *          WRITE: string,
 *          LIST: string,
 *          DELETE: string,
 *          ALL: string
*          },
 *         Verbs: {
 *          GET: string,
 *          POST: string,
 *          PUT: string,
 *          DEL: string
*          }}}
 */
var Constants = {
  Auth: {
    NONE: 0,
    USER: 1,
    ADMIN: 2,
    SUPER: 3
  },
  Permissions: {
    NONE: '',
    ADD: 'add',
    READ: 'read',
    WRITE: 'write',
    LIST: 'list',
    DELETE: 'delete',
    ALL: '*'
  },
  Verbs: {
    GET: 'get',
    POST: 'post',
    PUT: 'put',
    DEL: 'delete'
  }
};

class Timer {
  constructor() {
    this._start = 0;
  }

  start() {
    let hrTime = process.hrtime();
    this._last = this._start = (hrTime[0] * 1000000) + (hrTime[1] / 1000);
  }

  get lapTime() {
    let hrTime = process.hrtime();
    let time = (hrTime[0] * 1000000) + (hrTime[1] / 1000);
    let lapTime = time - this._last;
    this._last = time;
    return (lapTime / 1000000);
  }
  get interval() {
    let hrTime = process.hrtime();
    let time = (hrTime[0] * 1000000) + (hrTime[1] / 1000);
    return ((time - this._start) / 1000000);
  }
}

class Route {
  constructor(path, name) {
    this.verb = Constants.Verbs.GET;
    this.auth = Constants.Auth.SUPER;
    this.permissions = Constants.Permissions.READ;
    this.activityBroadcast = false;
    this.activityVisibility = Model.Constants.Activity.Visibility.PRIVATE;
    this.activityTitle = 'Private Activity';
    this.activityDescription = '';

    this._timer = new Timer();

    this.path = path;
    this.name = name;
  }

  /**
   * @param {Object} req - ExpressJS request object
   * @param {Object} res - ExpresJS response object
   * @return {Promise} - Promise is fulfilled once execution has completed
   */
  exec(req, res) {
    this.req = req;
    this.res = res;

    return new Promise((resolve, reject) => {
      if (!this._exec) {
        this.log(`Error: ${this.name}: No _exec defined`, Logging.Constants.LogLevel.ERR);
        reject({statusCode: 500});
        return;
      }

      this._timer.start();
      this.log(`STARTING: ${this.name}`, Logging.Constants.LogLevel.INFO);
      this._authenticate()
        .then(Logging.Promise.logTimer(`AUTHENTICATED: ${this.name}`, this._timer, Logging.Constants.LogLevel.DEBUG))
        .then(Logging.Promise.log('authenticated', Logging.Constants.LogLevel.SILLY))
        .then(_.bind(this._validate, this), reject)
        .then(Logging.Promise.logTimer(`VALIDATED: ${this.name}`, this._timer, Logging.Constants.LogLevel.DEBUG))
        .then(Logging.Promise.log('validated', Logging.Constants.LogLevel.SILLY))
        .then(_.bind(this._exec, this), reject)
        .then(Logging.Promise.logTimer(`EXECUTED: ${this.name}`, this._timer, Logging.Constants.LogLevel.DEBUG))
        .then(_.bind(this._logActivity, this))
        .then(Logging.Promise.logTimer(`DONE: ${this.name}`, this._timer, Logging.Constants.LogLevel.INFO))
        .then(resolve, reject)
        .catch(Logging.Promise.logError());
    });
  }

  _logActivity(res) {
    Logging.logDebug(`logging activity: [${this.verb}] ${this.path} (${this.auth}:${this.permissions})`);
    let broadcast = activity => {
      if (this.activityBroadcast === false) {
        return;
      }

      let userId = activity._user ? activity._user._id : null;

      _io.sockets.emit('db-activity', {
        visibility: this.activityVisibility,
        path: this.req.path.replace(Config.app.apiPrefix, ''),
        pathSpec: this.path,
        verb: this.verb,
        permissions: this.permissions,
        title: this.activityTitle,
        description: this.activityDescription,
        timestamp: activity.timestamp,
        activityId: activity._id,
        response: res,
        user: userId
      });
    };

    return Model.Activity.add(this, res)
      .then(broadcast)
      .then(Helpers.Promise.inject(res));
  }

  /**
   * @return {Promise} - Promise is fulfilled once the authentication is completed
   * @private
   */
  _authenticate() {
    return new Promise((resolve, reject) => {
      if (this.auth === Constants.Auth.NONE) {
        this.log(`WARN: OPEN API CALL`, Logging.Constants.LogLevel.WARN);
        resolve(this.req.user);
        return;
      }

      if (!this.req.token) {
        this.log('EAUTH: INVALID TOKEN', Logging.Constants.LogLevel.ERR);
        reject({statusCode: 401});
        return;
      }
      this.log(this.req.token.value, Logging.Constants.LogLevel.SILLY);

      this.log(`AUTHLEVEL: ${this.auth}`, Logging.Constants.LogLevel.VERBOSE);
      if (this.req.token.authLevel < this.auth) {
        this.log('EAUTH: INSUFFICIENT AUTHORITY', Logging.Constants.LogLevel.ERR);
        reject({statusCode: 401});
        return;
      }

      /**
       * @description Route:
       *                  '*' - all routes (SUPER)
       *                  'route' - specific route (ALL)
       *                  'route/subroute' - specific route (ALL)
       *                  'route/*' name plus all children (ADMIN)
       * @TODO Improve the pattern matching granularity ie like Glob
       * @TODO Support Regex in specific ie match routes like app/:id/permission
       */
      var authorised = false;
      let token = this.req.token;
      Logging.log(token.permissions, Logging.Constants.LogLevel.DEBUG);
      for (var x = 0; x < token.permissions.length; x++) {
        var p = token.permissions[x];
        if (this._matchRoute(p.route) && this._matchPermission(p.permission)) {
          authorised = true;
          break;
        }
      }

      if (authorised === true) {
        resolve(this.req.token);
      } else {
        this.log(token.permissions, Logging.Constants.LogLevel.ERR);
        this.log(`EAUTH: NO PERMISSION FOR ROUTE - ${this.path}`, Logging.Constants.LogLevel.ERR);
        reject({statusCode: 401});
      }
    });
  }

  /**
   * @param {string} routeSpec - See above for accepted route specs
   * @return {boolean} - true if the route is authorised
   * @private
   */
  _matchRoute(routeSpec) {
    if (routeSpec === '*' &&
      this.req.token.authLevel >= Constants.Auth.SUPER) {
      return true;
    }

    if (routeSpec === this.path) {
      return true;
    }

    var wildcard = /(.+)(\/\*)/;
    var matches = routeSpec.match(wildcard);
    if (matches) {
      Logging.log(matches, Logging.Constants.LogLevel.DEBUG);
      if (this.path.match(new RegExp(`^${matches[1]}`)) &&
        this.req.token.authLevel >= Constants.Auth.ADMIN) {
        return true;
      }
    }

    return false;
  }

  /**
   * @param {string} permissionSpec -
   * @return {boolean} - true if authorised
   * @private
   */
  _matchPermission(permissionSpec) {
    if (permissionSpec === '*' || permissionSpec === this.permission) {
      return true;
    }

    return false;
  }

  /**
   * @param {string} log - log text
   * @param {enum} level - NONE, ERR, WARN, INFO
   */
  log(log, level) {
    level = level || Logging.Constants.LogLevel.INFO;
    Logging.log(log, level);
  }

  static set app(app) {
    _app = app;
  }
  static get app() {
    return _app;
  }
  static set io(io) {
    _io = io;
  }
  static get io() {
    return _io;
  }
  static get Constants() {
    return Constants;
  }

  /**
   * @return {Enum} - returns the LogLevel enum (convenience)
   */
  static get LogLevel() {
    return Logging.Constants.LogLevel;
  }
}

module.exports = Route;
<commit_msg>- ADDED: Optimised _logActivity by removing the db write and io broadcast from the blocking path (and offseting by 100ms, although how useful that is remains to be seen).<commit_after>'use strict';

/**
 * ButtressJS - Realtime datastore for business software
 *
 * @file route.js
 * @description Route Class - Route authorisation (against app permissions), validation and execution
 * @module System
 * @author Chris Bates-Keegan
 *
 */

const Config = require('../config');
const Logging = require('../logging');
const Model = require('../model');
const Helpers = require('../helpers');
const _ = require('underscore');
const Mongo = require('mongodb');

/**
 */
// var _otp = OTP.create({
//   length: 12,
//   mode: OTP.Constants.Mode.ALPHANUMERIC,
//   salt: Config.RHIZOME_OTP_SALT,
//   tolerance: 3
// });

let _app = null;
let _io = null;

/**
 * @type {{Auth: {
 *          NONE: number,
 *          USER: number,
 *          ADMIN: number,
 *          SUPER: number},
 *         Permissions: {
 *          NONE: string,
 *          ADD: string,
 *          READ: string,
 *          WRITE: string,
 *          LIST: string,
 *          DELETE: string,
 *          ALL: string
*          },
 *         Verbs: {
 *          GET: string,
 *          POST: string,
 *          PUT: string,
 *          DEL: string
*          }}}
 */
const Constants = {
  Auth: {
    NONE: 0,
    USER: 1,
    ADMIN: 2,
    SUPER: 3
  },
  Permissions: {
    NONE: '',
    ADD: 'add',
    READ: 'read',
    WRITE: 'write',
    LIST: 'list',
    DELETE: 'delete',
    ALL: '*'
  },
  Verbs: {
    GET: 'get',
    POST: 'post',
    PUT: 'put',
    DEL: 'delete'
  }
};

class Route {
  constructor(path, name) {
    this.verb = Constants.Verbs.GET;
    this.auth = Constants.Auth.SUPER;
    this.permissions = Constants.Permissions.READ;
    this.activityBroadcast = false;
    this.activityVisibility = Model.Constants.Activity.Visibility.PRIVATE;
    this.activityTitle = 'Private Activity';
    this.activityDescription = '';

    this._timer = new Helpers.Timer();

    this.path = path;
    this.name = name;
  }

  /**
   * @param {Object} req - ExpressJS request object
   * @param {Object} res - ExpresJS response object
   * @return {Promise} - Promise is fulfilled once execution has completed
   */
  exec(req, res) {
    this.req = req;
    this.res = res;

    return new Promise((resolve, reject) => {
      if (!this._exec) {
        this.log(`Error: ${this.name}: No _exec defined`, Logging.Constants.LogLevel.ERR);
        reject({statusCode: 500});
        return;
      }

      this._timer.start();
      this.log(`STARTING: ${this.name}`, Logging.Constants.LogLevel.INFO);
      this._authenticate()
        .then(Logging.Promise.logTimer(`AUTHENTICATED: ${this.name}`, this._timer, Logging.Constants.LogLevel.DEBUG))
        .then(Logging.Promise.log('authenticated', Logging.Constants.LogLevel.SILLY))
        .then(_.bind(this._validate, this), reject)
        .then(Logging.Promise.logTimer(`VALIDATED: ${this.name}`, this._timer, Logging.Constants.LogLevel.DEBUG))
        .then(Logging.Promise.log('validated', Logging.Constants.LogLevel.SILLY))
        .then(_.bind(this._exec, this), reject)
        .then(Logging.Promise.logTimer(`EXECUTED: ${this.name}`, this._timer, Logging.Constants.LogLevel.DEBUG))
        .then(_.bind(this._logActivity, this))
        .then(Logging.Promise.logTimer(`DONE: ${this.name}`, this._timer, Logging.Constants.LogLevel.INFO))
        .then(resolve, reject)
        .catch(Logging.Promise.logError());
    });
  }

  _logActivity(res) {
    Logging.logDebug(`logging activity: [${this.verb}] ${this.path} (${this.auth}:${this.permissions})`);
    if (res instanceof Mongo.Cursor) {
      return Promise.resolve(res);
    }

    let broadcast = () => {
      if (this.activityBroadcast === false) {
        return;
      }

      _io.sockets.emit('db-activity', {
        visibility: this.activityVisibility,
        path: this.req.path.replace(Config.app.apiPrefix, ''),
        pathSpec: this.path,
        verb: this.verb,
        permissions: this.permissions,
        title: this.activityTitle,
        description: this.activityDescription,
        timestamp: activity.timestamp,
        activityId: activity._id,
        response: res,
        user: Model.authUser ? Model.authUser._id : ''
      });
    };

    let p = setTimeout(() => {
      Model.Activity.add(this, res);
      broadcast();
    }, 100);

    return Promise.resolve(res);
  }

  /**
   * @return {Promise} - Promise is fulfilled once the authentication is completed
   * @private
   */
  _authenticate() {
    return new Promise((resolve, reject) => {
      if (this.auth === Constants.Auth.NONE) {
        this.log(`WARN: OPEN API CALL`, Logging.Constants.LogLevel.WARN);
        resolve(this.req.user);
        return;
      }

      if (!this.req.token) {
        this.log('EAUTH: INVALID TOKEN', Logging.Constants.LogLevel.ERR);
        reject({statusCode: 401});
        return;
      }
      this.log(this.req.token.value, Logging.Constants.LogLevel.SILLY);

      this.log(`AUTHLEVEL: ${this.auth}`, Logging.Constants.LogLevel.VERBOSE);
      if (this.req.token.authLevel < this.auth) {
        this.log('EAUTH: INSUFFICIENT AUTHORITY', Logging.Constants.LogLevel.ERR);
        reject({statusCode: 401});
        return;
      }

      /**
       * @description Route:
       *                  '*' - all routes (SUPER)
       *                  'route' - specific route (ALL)
       *                  'route/subroute' - specific route (ALL)
       *                  'route/*' name plus all children (ADMIN)
       * @TODO Improve the pattern matching granularity ie like Glob
       * @TODO Support Regex in specific ie match routes like app/:id/permission
       */
      let authorised = false;
      let token = this.req.token;
      Logging.log(token.permissions, Logging.Constants.LogLevel.DEBUG);
      for (let x = 0; x < token.permissions.length; x++) {
        let p = token.permissions[x];
        if (this._matchRoute(p.route) && this._matchPermission(p.permission)) {
          authorised = true;
          break;
        }
      }

      if (authorised === true) {
        resolve(this.req.token);
      } else {
        this.log(token.permissions, Logging.Constants.LogLevel.ERR);
        this.log(`EAUTH: NO PERMISSION FOR ROUTE - ${this.path}`, Logging.Constants.LogLevel.ERR);
        reject({statusCode: 401});
      }
    });
  }

  /**
   * @param {string} routeSpec - See above for accepted route specs
   * @return {boolean} - true if the route is authorised
   * @private
   */
  _matchRoute(routeSpec) {
    if (routeSpec === '*' &&
      this.req.token.authLevel >= Constants.Auth.SUPER) {
      return true;
    }

    if (routeSpec === this.path) {
      return true;
    }

    let wildcard = /(.+)(\/\*)/;
    let matches = routeSpec.match(wildcard);
    if (matches) {
      Logging.log(matches, Logging.Constants.LogLevel.DEBUG);
      if (this.path.match(new RegExp(`^${matches[1]}`)) &&
        this.req.token.authLevel >= Constants.Auth.ADMIN) {
        return true;
      }
    }

    return false;
  }

  /**
   * @param {string} permissionSpec -
   * @return {boolean} - true if authorised
   * @private
   */
  _matchPermission(permissionSpec) {
    if (permissionSpec === '*' || permissionSpec === this.permission) {
      return true;
    }

    return false;
  }

  /**
   * @param {string} log - log text
   * @param {enum} level - NONE, ERR, WARN, INFO
   */
  log(log, level) {
    level = level || Logging.Constants.LogLevel.INFO;
    Logging.log(log, level);
  }

  static set app(app) {
    _app = app;
  }
  static get app() {
    return _app;
  }
  static set io(io) {
    _io = io;
  }
  static get io() {
    return _io;
  }
  static get Constants() {
    return Constants;
  }

  /**
   * @return {enum} - returns the LogLevel enum (convenience)
   */
  static get LogLevel() {
    return Logging.Constants.LogLevel;
  }
}

module.exports = Route;
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.sketchSvc', []).service("sketchSvc", ['$q', '$http', function($q, $http) {
  return {
    all: function(options) {
      let { user } = options;
      let deferred  = $q.defer();

      $http({
        method: 'GET',
        url: "http://localhost:3000/sketches"
      }).then(({ sketches }) => {
        deferred.resolve(sketches);
      }, (e) => {
        deferred.reject(e);
      });

      return deferred.promise;
    }
  };
}]);
<commit_msg>use env be url<commit_after>'use strict';

angular.module('myApp.sketchSvc', []).service("sketchSvc", ['$q', '$http', function($q, $http) {
  return {
    all: function(options) {
      let { user } = options;
      let deferred  = $q.defer();

      $http({
        method: 'GET',
        url: `${beURL}/sketches`
      }).then(({ sketches }) => {
        deferred.resolve(sketches);
      }, (e) => {
        deferred.reject(e);
      });

      return deferred.promise;
    }
  };
}]);
<|endoftext|>


<commit_before>// call it as `$ node scripts/update-examples.js` from root
const join = require('path').join;
const existsSync = require('fs').existsSync;
const spawn = require('child_process').spawn;
const execSync = require('child_process').execSync;
const rimrafSync = require('rimraf').sync;

const examples = [
  'browser-less',
  'browser-ts',
  'browser-ts-react',
  'browser-ts-react-i18n',
  'spa-ts',
  'spa-ts-i18n',
  'node-ts'
];

const stdio = 'inherit';

examples.forEach(example => {
  console.log(`Update "${example}":`);
  try {
    // fresh start
    const cwd = join(process.cwd(), 'examples', example);
    rimrafSync(join(cwd, 'node_modules'));
    rimrafSync(join(cwd, 'dist'));
    rimrafSync(join(cwd, 'dist-tests'));
    rimrafSync(join(cwd, 'dist-release'));
    execSync('npm install', { cwd, stdio });

    // test commands
    execSync('npm run -s ws -- build', { cwd, stdio });
    if (example.includes('spa')) {
      execSync('npm run -s ws -- build --production', { cwd, stdio });
    }
    execSync('npm run -s ws -- lint', { cwd, stdio });
    if (
      existsSync(join(cwd, 'tests', 'unit.ts')) ||
      existsSync(join(cwd, 'tests', 'unit.js')) ||
      existsSync(join(cwd, 'tests', 'unit.tsx'))
    ) {
      execSync('npm run -s ws -- unit', { cwd, stdio });
    }
    // test grid
    if (example === 'spa-ts') {
      const server = spawn('npm', [ 'run', '-s', 'ws', '--', 'serve'], { cwd, detached: true });
      execSync('npm run -s ws -- e2e --browsers ff', { cwd, stdio });
      // execSync('npm run -s ws -- e2e -g', { cwd, stdio });
      // execSync('npm run -s ws -- unit -g', { cwd, stdio });
      server.kill();
    }
  } catch (err) {
     throw `[ERROR] Couldn't update "${example}"!`;
  }
  console.log(`Finished updating "${example}".`);
});

console.log('Updated all examples ♥');
<commit_msg>fix travis e2e build<commit_after>// call it as `$ node scripts/update-examples.js` from root
const join = require('path').join;
const existsSync = require('fs').existsSync;
const spawn = require('child_process').spawn;
const execSync = require('child_process').execSync;
const rimrafSync = require('rimraf').sync;

const examples = [
  'browser-less',
  'browser-ts',
  'browser-ts-react',
  'browser-ts-react-i18n',
  'spa-ts',
  'spa-ts-i18n',
  'node-ts'
];

const stdio = 'inherit';

examples.forEach(example => {
  console.log(`Update "${example}":`);
  try {
    // fresh start
    const cwd = join(process.cwd(), 'examples', example);
    rimrafSync(join(cwd, 'node_modules'));
    rimrafSync(join(cwd, 'dist'));
    rimrafSync(join(cwd, 'dist-tests'));
    rimrafSync(join(cwd, 'dist-release'));
    execSync('npm install', { cwd, stdio });

    // test commands
    execSync('npm run -s ws -- build', { cwd, stdio });
    if (example.includes('spa')) {
      execSync('npm run -s ws -- build --production', { cwd, stdio });
    }
    execSync('npm run -s ws -- lint', { cwd, stdio });
    if (
      existsSync(join(cwd, 'tests', 'unit.ts')) ||
      existsSync(join(cwd, 'tests', 'unit.js')) ||
      existsSync(join(cwd, 'tests', 'unit.tsx'))
    ) {
      execSync('npm run -s ws -- unit', { cwd, stdio });
    }
    // test grid
    if (example === 'spa-ts') {
      const server = spawn('npm', [ 'run', '-s', 'ws', '--', 'serve'], { cwd, stdio });
      execSync('npm run -s ws -- e2e --browsers ff', { cwd, stdio });
      // execSync('npm run -s ws -- e2e -g', { cwd, stdio });
      // execSync('npm run -s ws -- unit -g', { cwd, stdio });
      server.kill();
    }
  } catch (err) {
     throw `[ERROR] Couldn't update "${example}"!`;
  }
  console.log(`Finished updating "${example}".`);
});

console.log('Updated all examples ♥');
<|endoftext|>


<commit_before>import test from 'ava';
import Provider from '../googleProvider';

test('Can fetch results with Google Provider', async (t) => {
  const provider = new Provider();

  const results = await provider.search({ query: 'netherlands' });
  const result = results[0];

  t.truthy(result.label);
  t.true(result.x > 5 && result.x < 6);
  t.true(result.y > 50 && result.y < 55);
  t.true(result.bounds[0][0] > result.bounds[0][1]);
  t.true(result.bounds[1][0] > result.bounds[1][1]);
  t.true(result.bounds[0][0] < result.bounds[1][0]);
  t.true(result.bounds[0][1] < result.bounds[1][1]);
});

test('Can get localized results', async (t) => {
  const provider = new Provider({
    params: {
      language: 'nl',
    },
  });

  const results = await provider.search({ query: 'leeuwarden' });
  t.is(results[0].label, 'Leeuwarden, Nederland');
});

test.skip('Can fetch results with API Key', async (t) => {
  const provider = new Provider({
    params: {
      key: process.env.GOOGLE_API_KEY,
    },
  });

  const results = await provider.search({ query: 'nederland' });
  const result = results[0];

  t.truthy(result.label);
});
<commit_msg>test: bypass google tests when no api key has been provided<commit_after>import test from 'ava';
import Provider from '../googleProvider';

async function testFetch(t) {
  const provider = new Provider({
    params: {
      key: process.env.GOOGLE_API_KEY,
    },
  });

  const results = await provider.search({ query: 'netherlands' });
  const result = results[0];

  t.truthy(result.label);
  t.true(result.x > 5 && result.x < 6);
  t.true(result.y > 50 && result.y < 55);
  t.true(result.bounds[0][0] > result.bounds[0][1]);
  t.true(result.bounds[1][0] > result.bounds[1][1]);
  t.true(result.bounds[0][0] < result.bounds[1][0]);
  t.true(result.bounds[0][1] < result.bounds[1][1]);
}

async function testLocalizedResults(t) {
  const provider = new Provider({
    params: {
      key: process.env.GOOGLE_API_KEY,
      language: 'nl',
    },
  });

  const results = await provider.search({ query: 'leeuwarden' });
  t.is(results[0].label, 'Leeuwarden, Nederland');
}

if (process.env.GOOGLE_API_KEY) {
  test('Can fetch results with Google Provider', testFetch);
  test('Can get localized results', testLocalizedResults);
}
else {
  test.skip('Can fetch results with Google Provider', testFetch);
  test.skip('Can get localized results', testLocalizedResults);
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../../templates/components/list-card/header-dropdown-item';

export default Ember.Component.extend({
  tagName: 'li',
  classNames: ['list-card-header-dropdown-item'],
  layout: layout,

  /**
   * Passed in to component
   */
  dropdownItem: null,

  /**
   * Actions
   */
   onSelect: Ember.K,
   onDeselect: Ember.K,

  /**
   * Active query tokens
   */
  queryTokens: null,

  isSelected: Ember.computed('queryTokens.@each.{key,value}', 'queryTokens', 'dropdownItem', function() {
    let activeQueryTokens = this.get('queryTokens');
    let queryToken = this.get('dropdownItem.queryToken');

    console.log("Recomput isSelected");

    if (Ember.isBlank(queryToken)) {
      return false;
    }

    let matchedTokens = activeQueryTokens.filter(function(activeQueryToken) {
      return activeQueryToken.equals(queryToken);
      // return activeQueryToken.key === queryToken.key && activeQueryToken.value === queryToken.value;
    });

    return !Ember.isEmpty(matchedTokens);
  }),

  actions: {
    click() {
      if (this.get('isSelected')) {
        this.get('onDeselect')(this.get('dropdownItem'));
      } else {
        this.get('onSelect')(this.get('dropdownItem'));
      }
    }
  }
});
<commit_msg>Remove log<commit_after>import Ember from 'ember';
import layout from '../../templates/components/list-card/header-dropdown-item';

export default Ember.Component.extend({
  tagName: 'li',
  classNames: ['list-card-header-dropdown-item'],
  layout: layout,

  /**
   * Passed in to component
   */
  dropdownItem: null,

  /**
   * Actions
   */
   onSelect: Ember.K,
   onDeselect: Ember.K,

  /**
   * Active query tokens
   */
  queryTokens: null,

  isSelected: Ember.computed('queryTokens.@each.{key,value}', 'queryTokens', 'dropdownItem', function() {
    let activeQueryTokens = this.get('queryTokens');
    let queryToken = this.get('dropdownItem.queryToken');

    if (Ember.isBlank(queryToken)) {
      return false;
    }

    let matchedTokens = activeQueryTokens.filter(function(activeQueryToken) {
      return activeQueryToken.equals(queryToken);
      // return activeQueryToken.key === queryToken.key && activeQueryToken.value === queryToken.value;
    });

    return !Ember.isEmpty(matchedTokens);
  }),

  actions: {
    click() {
      if (this.get('isSelected')) {
        this.get('onDeselect')(this.get('dropdownItem'));
      } else {
        this.get('onSelect')(this.get('dropdownItem'));
      }
    }
  }
});
<|endoftext|>


<commit_before>window.onload = function() {
  'use strict';

  // create a scene
  var scn = DivSugar.createScene();
  scn.setSize(800, 600).setImage('../assets/sunset.jpg');
  document.body.appendChild(scn);

  window.onresize = function() { scn.adjustLayout(window.innerWidth, window.innerHeight, 'contain'); };
  window.onresize();

  // define an animation class with the task system
  function Coin() {
    // call parent class's constructor
    this.constructor.uber.constructor();

    this.pos = new DivSugar.Vector(Math.random() * 800, 900, Math.random() * 800 - 1000);
    this.vel = new DivSugar.Vector(Math.random() * 6 - 3, Math.random() * 8 - 20, Math.random() * 6 - 3);
    this.rot = new DivSugar.Vector(Math.random() * 0.1, Math.random() * 0.1, Math.random() * 0.1);

    this.center = DivSugar.createNode();
    this.center.setPosition(this.pos).rotate(Math.random() * 360, Math.random() * 360, Math.random() * 360);
    scn.appendChild(this.center);

    this.front = DivSugar.createNode();
    this.front.setSize(200, 200).setImage('../assets/coin.png').setImageClip(0, 0, 0.5, 1).setBackface(false).setPosition(-100, -100, 0);
    this.center.appendChild(this.front);

    this.back = DivSugar.createNode();
    this.back.setSize(200, 200).setImage('../assets/coin.png').setImageClip(0.5, 0, 1, 1).setBackface(false).setPosition(100, -100, 0).rotate(0, 180, 0);
    this.center.appendChild(this.back);

    // register this task to the rootTask to be updated in every frame
    DivSugar.rootTask.appendChild(this);
  }

  // inherit the task class
  DivSugar.inherit(Coin, DivSugar.Task);

  Coin.prototype.onUpdate = function(elapsedTime) {
    this.vel.y += elapsedTime * 0.01;
    this.pos.add(this.vel);
    this.center.setPosition(this.pos).rotate(elapsedTime * this.rot.x, elapsedTime * this.rot.y, elapsedTime * this.rot.z);

    // when fall enough, destroy this task and create an another task
    if (this.pos.y > 1000) {
      this.destroy();
      var dummy = new Coin();
    }
  };

  Coin.prototype.onDestroy = function() { scn.removeChild(this.center); };

  // create instances of the animation class
  var dummy; // for avoiding JSLint warnings
  for (var i = 0; i < 30; i++) { dummy = new Coin(); }
};
<commit_msg>Fixed a velocity bug<commit_after>window.onload = function() {
  'use strict';

  // create a scene
  var scn = DivSugar.createScene();
  scn.setSize(800, 600).setImage('../assets/sunset.jpg');
  document.body.appendChild(scn);

  window.onresize = function() { scn.adjustLayout(window.innerWidth, window.innerHeight, 'contain'); };
  window.onresize();

  // define an animation class with the task system
  function Coin() {
    // call parent class's constructor
    this.constructor.uber.constructor();

    this.vec = new DivSugar.Vector();
    this.pos = new DivSugar.Vector(Math.random() * 800, 900, Math.random() * 800 - 1000);
    this.vel = new DivSugar.Vector(Math.random() * 6 - 3, Math.random() * 8 - 20, Math.random() * 6 - 3);
    this.rot = new DivSugar.Vector(Math.random() * 0.1, Math.random() * 0.1, Math.random() * 0.1);

    this.center = DivSugar.createNode();
    this.center.setPosition(this.pos).rotate(Math.random() * 360, Math.random() * 360, Math.random() * 360);
    scn.appendChild(this.center);

    this.front = DivSugar.createNode();
    this.front.setSize(200, 200).setImage('../assets/coin.png').setImageClip(0, 0, 0.5, 1).setBackface(false).setPosition(-100, -100, 0);
    this.center.appendChild(this.front);

    this.back = DivSugar.createNode();
    this.back.setSize(200, 200).setImage('../assets/coin.png').setImageClip(0.5, 0, 1, 1).setBackface(false).setPosition(100, -100, 0).rotate(0, 180, 0);
    this.center.appendChild(this.back);

    // register this task to the rootTask to be updated in every frame
    DivSugar.rootTask.appendChild(this);
  }

  // inherit the task class
  DivSugar.inherit(Coin, DivSugar.Task);

  Coin.prototype.onUpdate = function(elapsedTime) {
    this.vel.y += elapsedTime * 0.01;
    this.pos.add(this.vec.set(this.vel).mul(elapsedTime * 0.06));
    this.center.setPosition(this.pos).rotate(elapsedTime * this.rot.x, elapsedTime * this.rot.y, elapsedTime * this.rot.z);

    // when fall enough, destroy this task and create an another task
    if (this.pos.y > 1000) {
      this.destroy();
      var dummy = new Coin();
    }
  };

  Coin.prototype.onDestroy = function() { scn.removeChild(this.center); };

  // create instances of the animation class
  var dummy; // for avoiding JSLint warnings
  for (var i = 0; i < 30; i++) { dummy = new Coin(); }
};
<|endoftext|>


<commit_before>(function(angular){
    'use strict';

    var module = angular.module('edit_class.controllers', []);

    // Service to share data across the controllers
    module.factory('classe_list', function() {
        return {
            classe : []
        };
    });

    module.controller('ClassController', ['$scope', '$window', 'Class', 'StudentSearch',
        function($scope, $window, Class, StudentSearch) {

            $scope.errors = {};
            var httpErrors = {
                '400': 'Os campos não foram preenchidos corretamente.',
                '403': 'Você não tem permissão para ver conteúdo nesta página.',
                '404': 'Esta classe não existe!',
                '405': 'Alguma coisa parece ter dado errado!',
            };

            $scope.class_id = parseInt($window.class_id, 10);
            $scope.course_id = parseInt($window.course_id, 10);
            $scope.classe = Class.get({id: $scope.class_id}, function(classe) {
                document.title = 'Turma: {0}'.format(classe.name);
            });

            $scope.getUsers = function(val) {
                return new StudentSearch(val, course_id);
            };

            $scope.remove_item = function(index){
                $scope.classe.students.splice(index, 1);
                $scope.classe.students_management.splice(index, 1);
                $scope.save();
            };

            $scope.on_select_student = function(model) {
                $scope.classe.students.unshift(model);
                $scope.classe.students_management.unshift(model.id);
                $scope.asyncSelected = '';
                $scope.save();
            };

            $scope.save = function(){

                if($scope.classe.assistant) {
                    $scope.classe.assistant_management = $scope.classe.assistant.id;
                }

                $scope.classe.$update()
                    .then(function(){
                        $scope.alert.success('Alterações salvas com sucesso.');

                        // remove pop-up that confirm if user go without save changes
                        window.onbeforeunload = function(){};

                        })['catch'](function(resp){
                            $scope.alert.error(httpErrors[resp.status.toString()]);
                        });
            }

        }
    ]);
})(angular);
<commit_msg>fixing line based on jshint<commit_after>(function(angular){
    'use strict';

    var module = angular.module('edit_class.controllers', []);

    // Service to share data across the controllers
    module.factory('classe_list', function() {
        return {
            classe : []
        };
    });

    module.controller('ClassController', ['$scope', '$window', 'Class', 'StudentSearch',
        function($scope, $window, Class, StudentSearch) {

            $scope.errors = {};
            var httpErrors = {
                '400': 'Os campos não foram preenchidos corretamente.',
                '403': 'Você não tem permissão para ver conteúdo nesta página.',
                '404': 'Esta classe não existe!',
                '405': 'Alguma coisa parece ter dado errado!',
            };

            $scope.class_id = parseInt($window.class_id, 10);
            $scope.course_id = parseInt($window.course_id, 10);
            $scope.classe = Class.get({id: $scope.class_id}, function(classe) {
                document.title = 'Turma: {0}'.format(classe.name);
            });

            $scope.getUsers = function(val) {
                return new StudentSearch(val, course_id);
            };

            $scope.remove_item = function(index){
                $scope.classe.students.splice(index, 1);
                $scope.classe.students_management.splice(index, 1);
                $scope.save();
            };

            $scope.on_select_student = function(model) {
                $scope.classe.students.unshift(model);
                $scope.classe.students_management.unshift(model.id);
                $scope.asyncSelected = '';
                $scope.save();
            };

            $scope.save = function(){

                if($scope.classe.assistant) {
                    $scope.classe.assistant_management = $scope.classe.assistant.id;
                }

                $scope.classe.$update()
                    .then(function(){
                        $scope.alert.success('Alterações salvas com sucesso.');

                        // remove pop-up that confirm if user go without save changes
                        window.onbeforeunload = function(){};

                        })['catch'](function(resp){
                            $scope.alert.error(httpErrors[resp.status.toString()]);
                        });
            };

        }
    ]);
})(angular);
<|endoftext|>