<commit_before>var http = require('sys');
var http = require('http');
var https = require('https');
var RSS = require('./rss');

var reId = new RegExp(/\/(\d+)$/);

http.createServer(function(req, serverResponse) {
  try {
    //Get the ID off the url
    var m = reId.exec(req.url);
    if (m != null) { //Url has the id so send back rss feed
      serverResponse.writeHead(200, { 'content-type': 'application/rss+xml' });
      var googleId = m[1];
      var data = [];

      var options = {
        host: 'plus.google.com',
        port: 443,
        path: '/_/stream/getactivities/?&sp=[1,2,"'+googleId+'",null,null,40,null,"social.google.com",[]]',
        method: 'GET',
        headers: {
          'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0a2) Gecko/20110613 Firefox/6.0a2',
          'Connection':'keep-alive'
        }
      };

      var googleReq = https.request(options, function(googleResponse) {
        googleResponse.on('data', function(d) {
          data.push(d);
        });
        googleResponse.on('end', function() {
          var results = data.join('');

          results = results.replace(")]}'","");
          results = results.replace(/\[,/g, '["",');
          results = results.replace(/,,/g, ',"",');
          results = results.replace(/,,/g, ',"",');

          var p = JSON.parse(results);
          var post = p[1][0];
          var authorName = post[0][3].toString();

          var feed = new RSS({
            title: authorName + "'s Google+ Public Feed",
            feed_url: 'http://plus.google.com/' + googleId + '/posts',
            site_url: 'http://plus.google.com',
            author: authorName
          });

          for (i=0;i<post.length;i++)
          {
            feed.item({
                title:  post[i][4].toString(),
                url: 'https://plus.google.com/' + post[i][21].toString(), // link to the item
                date: new Date(post[i][5]) // any format that js Date can parse.
            });
          }
          serverResponse.end(feed.xml());
        });
      });
      googleReq.end();
    } else { //Else output directions
      serverResponse.writeHead(200, { 'content-type': 'text/html' });
      serverResponse.write("<title>Google+ to RSS Feed</title>");
      serverResponse.write("
Google+ to RSS Feed
");
      serverResponse.write("
Just add your google user id to this url like this http://googleplus2rss.nodester.com/12345678901234567890 and it will give you your feed.
");
      serverResponse.end("");
    }
  } catch (ex) {
    serverResponse.writeHead(200, { 'content-type': 'text/html' });
      serverResponse.write("<title>Google+ to RSS Feed</title>");
      serverResponse.write("
Google+ to RSS Feed Error
");
      serverResponse.write("
We got the following error getting the feed: " + ex.toString() + "
");
      serverResponse.end("");
  }
}).listen(11908);
>>>>>>> 48ed456dfd7941268c51b4239f06a4d86645eec9
<commit_msg>Fixed bug frm merge<commit_after>var http = require('sys');
var http = require('http');
var https = require('https');
var RSS = require('./rss');

var reId = new RegExp(/\/(\d+)$/);

http.createServer(function(req, serverResponse) {
  try {
    //Get the ID off the url
    var m = reId.exec(req.url);
    if (m != null) { //Url has the id so send back rss feed
      serverResponse.writeHead(200, { 'content-type': 'application/rss+xml' });
      var googleId = m[1];
      var data = [];

      var options = {
        host: 'plus.google.com',
        port: 443,
        path: '/_/stream/getactivities/?&sp=[1,2,"'+googleId+'",null,null,40,null,"social.google.com",[]]',
        method: 'GET',
        headers: {
          'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0a2) Gecko/20110613 Firefox/6.0a2',
          'Connection':'keep-alive'
        }
      };

      var googleReq = https.request(options, function(googleResponse) {
        googleResponse.on('data', function(d) {
          data.push(d);
        });
        googleResponse.on('end', function() {
          var results = data.join('');

          results = results.replace(")]}'","");
          results = results.replace(/\[,/g, '["",');
          results = results.replace(/,,/g, ',"",');
          results = results.replace(/,,/g, ',"",');

          var p = JSON.parse(results);
          var post = p[1][0];
          var authorName = post[0][3].toString();

          var feed = new RSS({
            title: authorName + "'s Google+ Public Feed",
            feed_url: 'http://plus.google.com/' + googleId + '/posts',
            site_url: 'http://plus.google.com',
            author: authorName
          });

          for (i=0;i<post.length;i++)
          {
            feed.item({
                title:  post[i][4].toString(),
                url: 'https://plus.google.com/' + post[i][21].toString(), // link to the item
                date: new Date(post[i][5]) // any format that js Date can parse.
            });
          }
          serverResponse.end(feed.xml());
        });
      });
      googleReq.end();
    } else { //Else output directions
      serverResponse.writeHead(200, { 'content-type': 'text/html' });
      serverResponse.write("<title>Google+ to RSS Feed</title>");
      serverResponse.write("
Google+ to RSS Feed
");
      serverResponse.write("
Just add your google user id to this url like this http://googleplus2rss.nodester.com/12345678901234567890 and it will give you your feed.
");
      serverResponse.end("");
    }
  } catch (ex) {
    serverResponse.writeHead(200, { 'content-type': 'text/html' });
      serverResponse.write("<title>Google+ to RSS Feed</title>");
      serverResponse.write("
Google+ to RSS Feed Error
");
      serverResponse.write("
We got the following error getting the feed: " + ex.toString() + "
");
      serverResponse.end("");
  }
}).listen(11908);
<|endoftext|>


<commit_before>var async  = require('async');
var fs     = require('fs');
var path   = require('path');
var utils  = require('../utils');
var Issue  = utils.issues.Issue;

var TSV    = require('./tsv');
var json   = require('./json');
var NIFTI  = require('./nii');
var bval   = require('./bval');
var bvec   = require('./bvec');
var session = require('./session');
var headerFields = require('./headerFields');

var BIDS;
BIDS = {

    options: {},
    issues: [],

    /**
     * Start
     *
     * Takes either a filelist array or
     * a path to a BIDS directory and an
     * options object and starts
     * the validation process and
     * returns the errors and warnings as
     * arguments to the callback.
     */
    start: function (dir, options, callback) {
        var self = BIDS;
        utils.options.parse(options, function (issues, options) {
            if (issues && issues.length > 0) {
                // option parsing issues
                callback({config: issues});
            } else {
                self.options = options;
                BIDS.reset();
                utils.files.readDir(dir, function (files) {
                    self.quickTest(files, function (couldBeBIDS) {
                        if (couldBeBIDS) {
                            self.fullTest(files, callback);
                        } else {
                            // Return an error immediately if quickTest fails
                            var issue = self.quickTestError(dir);
                            var summary = {
                                sessions: [],
                                subjects: [],
                                tasks: [],
                                modalities: [],
                                totalFiles: Object.keys(files).length,
                                size: 0
                            };
                            callback(utils.issues.format([issue], summary, options));
                        }
                    });
                });
            }
        });
    },

    /*
     * Generates an error for quickTest failures
     */
    quickTestError: function (dir) {
        var filename;
        if (typeof window === 'undefined') {
            // For Node, grab the path from the dir string
            filename = path.basename(dir);
        } else {
            // Browser side we need to look it up more carefully
            if (dir.length && 'webkitRelativePath' in dir[0]) {
                var wrp = dir[0].webkitRelativePath;
                while (wrp.indexOf(path.sep) !== -1) {
                    wrp = path.dirname(wrp);
                }
                filename = wrp;
            } else {
                // Fallback for non-standard webkitRelativePath
                filename = 'uploaded-directory';
            }
        }
        var issue = new Issue({
            code: 61,
            file: {
                name: filename,
                path: path.join('.', filename),
                relativePath: path.join('', filename)
            }
        });
        return issue;
    },

    /**
     * Quick Test
     *
     * A quick test to see if it could be a BIDS
     * dataset based on structure/naming. If it
     * could be it will trigger the full validation
     * otherwise it will throw a callback with a
     * generic error.
     */
    quickTest: function (fileList, callback) {
        var couldBeBIDS = false;
        for (var key in fileList) {
            if (fileList.hasOwnProperty(key)) {
                var file = fileList[key];
                var path = utils.files.relativePath(file);
                if (path) {
                    path = path.split('/');
                    path = path.reverse();
                    if (
                        path[0].includes('.nii') &&
                        (
                            path[1] == 'anat' ||
                            path[1] == 'func' ||
                            path[1] == 'dwi'
                        ) &&
                        (
                            (path[2] && path[2].indexOf('ses-') == 0) ||
                            (path[2] && path[2].indexOf('sub-') == 0)
                        )
                    ) {
                        couldBeBIDS = true;
                        break;
                    }
                }
            }
        }
        callback(couldBeBIDS);
    },

    /**
     * Full Test
     *
     * Takes on an array of files and starts
     * the validation process for a BIDS
     * package.
     */
    fullTest: function (fileList, callback) {
        var self = this;

        var jsonContentsDict = {},
            bContentsDict = {},
            events = [],
            niftis = [],
            headers = [],
            participants = null,
            phenotypeParticipants = [],
            hasSubjectDir = false;

        var summary = {
            sessions: [],
            subjects: [],
            tasks: [],
            modalities: [],
            totalFiles: Object.keys(fileList).length,
            size: 0
        };

        // check for illegal character in task name and acq name

        var task_re = /sub-(.*?)_task-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*(?:_acq-[a-zA-Z0-9-]*)?(?:_run-\d+)?_/g;
        var acq_re = /sub-(.*?)_task-\w+.\w+(_acq-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*)(?:_run-\d+)?_/g;

        var sub_re = /sub-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*_/g;   // illegal character in sub
        var ses_re = /ses-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*?_(.*?)/g; //illegal character in ses

        var illegalchar_regex_list = [
            [task_re, 58, "task name contains illegal character:"],
            [acq_re, 59, "acq name contains illegal character:"],
            [sub_re, 62, "sub name contains illegal character:" ],
            [ses_re, 63, "ses name contains illegal character:" ]
        ];

        async.eachOfLimit(fileList, 200, function (file) {
            var completename = utils.files.relativePath(file);
            if(!(completename.startsWith('/derivatives') || completename.startsWith('/code') || completename.startsWith('/sourcedata'))) {
                for (var re_index = 0; re_index < illegalchar_regex_list.length; re_index++) {
                    var err_regex = illegalchar_regex_list[re_index][0];
                    var err_code = illegalchar_regex_list[re_index][1];
                    var err_evidence = illegalchar_regex_list[re_index][2];

                    if (err_regex.exec(completename)) {
                        self.issues.push(new Issue({
                            file: fileList[f],
                            code: err_code,
                            evidence: err_evidence + completename
                        }));
                    }
                }
            }
        }

        // validate individual files
        async.eachOfLimit(fileList, 200, function (file, key, cb) {
            var path = utils.files.relativePath(file);
            file.relativePath = path;

            // check for subject directory presence
            if (path.startsWith('/sub-')) {
                hasSubjectDir = true;
            }

            // ignore associated data
            if (utils.type.isAssociatedData(file.relativePath)) {
                process.nextTick(cb);
            }

            // validate path naming
            else if (!utils.type.isBIDS(file.relativePath)) {
                self.issues.push(new Issue({
                    file: file,
                    evidence: file.name,
                    code: 1
                }));
                process.nextTick(cb);
            }

            // capture niftis for later validation
            else if (file.name.endsWith('.nii') || file.name.endsWith('.nii.gz')) {
                niftis.push(file);

                // collect modality summary
                var pathParts = path.split('_');
                var suffix = pathParts[pathParts.length - 1];
                suffix = suffix.slice(0, suffix.indexOf('.'));
                if (summary.modalities.indexOf(suffix) === -1) {
                    summary.modalities.push(suffix);
                }

                process.nextTick(cb);
            }

            // validate tsv
            else if (file.name && file.name.endsWith('.tsv')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    if (file.name.endsWith('_events.tsv')) {
                        events.push(file.relativePath);
                    }
                    TSV(file, contents, fileList, function (issues, participantList) {
                        if (participantList) {
                            if (file.name.endsWith('participants.tsv')) {
                                participants = {
                                    list: participantList,
                                    file: file
                                };
                            } else if (file.relativePath.includes('phenotype/')) {
                                phenotypeParticipants.push({
                                    list: participantList,
                                    file: file
                                });
                            }
                        }
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate bvec
            else if (file.name && file.name.endsWith('.bvec')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    bContentsDict[file.relativePath] = contents;
                    bvec(file, contents, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate bval
            else if (file.name && file.name.endsWith('.bval')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    bContentsDict[file.relativePath] = contents;
                    bval(file, contents, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate json
            else if (file.name && file.name.endsWith('.json')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    json(file, contents, function (issues, jsObj) {
                        self.issues = self.issues.concat(issues);

                        // abort further tests if schema test does not pass
                        for (var i = 0; i < issues.length; i++) {
                            if (issues[i].severity === 'error') {
                                process.nextTick(cb);
                                return;
                            }
                        }

                        jsonContentsDict[file.relativePath] = jsObj;

                        // collect task summary
                        if (file.name.indexOf('task') > -1) {
                            var task = jsObj ? jsObj.TaskName : null;
                            if (task && summary.tasks.indexOf(task) === -1) {
                                summary.tasks.push(task);
                            }
                        }
                        process.nextTick(cb);
                    });
                });
            } else {
                process.nextTick(cb);
            }

            // collect file stats
            if (typeof window !== 'undefined') {
                if (file.size) {
                    summary.size += file.size;
                }
            } else {
                if (!file.stats) {
                    try {
                        file.stats = fs.statSync(file.path);
                    } catch (err) {
                        file.stats = {size: 0};
                    }
                }
                summary.size += file.stats.size;
            }

            // collect sessions & subjects
            if (!utils.type.isAssociatedData(file.relativePath) && utils.type.isBIDS(file.relativePath)) {
                var pathValues = utils.type.getPathValues(file.relativePath);

                if (pathValues.sub && summary.subjects.indexOf(pathValues.sub) === -1) {
                    summary.subjects.push(pathValues.sub);
                }
                if (pathValues.ses && summary.sessions.indexOf(pathValues.ses) === -1) {
                    summary.sessions.push(pathValues.ses);
                }
            }

        }, function () {
            async.eachOfLimit(niftis, 200, function (file, key, cb) {
                if (self.options.ignoreNiftiHeaders) {
                    NIFTI(null, file, jsonContentsDict, bContentsDict, fileList, events, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                } else {
                    utils.files.readNiftiHeader(file, function (header) {
                        // check if header could be read
                        if (header && header.hasOwnProperty('error')) {
                            self.issues.push(header.error);
                            process.nextTick(cb);
                        } else {
                            headers.push([file, header]);
                            NIFTI(header, file, jsonContentsDict, bContentsDict, fileList, events, function (issues) {
                                self.issues = self.issues.concat(issues);
                                process.nextTick(cb);
                            });
                        }
                    });
                }

            }, function () {
                if (!hasSubjectDir) {
                    self.issues.push(new Issue({code: 45}));
                }
                // check if participants file match found subjects

                if (participants) {
                    var participantsFromFile = participants.list.sort();
                    var participantsFromFolders = summary.subjects.sort();
                    if (!utils.array.equals(participantsFromFolders, participantsFromFile, true)) {
                        self.issues.push(new Issue({
                            code: 49,
                            evidence: "participants.tsv: " + participantsFromFile.join(', ') + " folder structure: " + participantsFromFolders.join(', '),
                            file: participants.file
                        }));
                    }
                }

                // check if dataset contains T1w
                if (summary.modalities.indexOf('T1w') < 0) {
                    self.issues.push(new Issue({
                        code: 53
                    }));
                }

                if (phenotypeParticipants && phenotypeParticipants.length > 0) {
                    for (var j = 0; j < phenotypeParticipants.length; j++) {
                        var fileParticpants = phenotypeParticipants[j];
                        var diff = utils.array.diff(fileParticpants.list, summary.subjects)[0];
                        if (diff && diff.length > 0) {
                            self.issues.push(new Issue({
                                code: 51,
                                evidence: 'sub-' + diff.join(', sub-'),
                                file: fileParticpants.file
                            }));
                        }
                    }
                }
                self.issues = self.issues.concat(headerFields(headers));
                self.issues = self.issues.concat(session(fileList));
                summary.modalities = utils.modalities.group(summary.modalities);
                var issues = utils.issues.format(self.issues, summary, self.options);
                callback(issues, summary);
            });
        });
    },

    /**
     * Reset
     *
     * Resets the in object data back to original values.
     */
    reset: function () {
        this.issues = [];
    }

};

module.exports = BIDS;
<commit_msg>fix typo<commit_after>var async  = require('async');
var fs     = require('fs');
var path   = require('path');
var utils  = require('../utils');
var Issue  = utils.issues.Issue;

var TSV    = require('./tsv');
var json   = require('./json');
var NIFTI  = require('./nii');
var bval   = require('./bval');
var bvec   = require('./bvec');
var session = require('./session');
var headerFields = require('./headerFields');

var BIDS;
BIDS = {

    options: {},
    issues: [],

    /**
     * Start
     *
     * Takes either a filelist array or
     * a path to a BIDS directory and an
     * options object and starts
     * the validation process and
     * returns the errors and warnings as
     * arguments to the callback.
     */
    start: function (dir, options, callback) {
        var self = BIDS;
        utils.options.parse(options, function (issues, options) {
            if (issues && issues.length > 0) {
                // option parsing issues
                callback({config: issues});
            } else {
                self.options = options;
                BIDS.reset();
                utils.files.readDir(dir, function (files) {
                    self.quickTest(files, function (couldBeBIDS) {
                        if (couldBeBIDS) {
                            self.fullTest(files, callback);
                        } else {
                            // Return an error immediately if quickTest fails
                            var issue = self.quickTestError(dir);
                            var summary = {
                                sessions: [],
                                subjects: [],
                                tasks: [],
                                modalities: [],
                                totalFiles: Object.keys(files).length,
                                size: 0
                            };
                            callback(utils.issues.format([issue], summary, options));
                        }
                    });
                });
            }
        });
    },

    /*
     * Generates an error for quickTest failures
     */
    quickTestError: function (dir) {
        var filename;
        if (typeof window === 'undefined') {
            // For Node, grab the path from the dir string
            filename = path.basename(dir);
        } else {
            // Browser side we need to look it up more carefully
            if (dir.length && 'webkitRelativePath' in dir[0]) {
                var wrp = dir[0].webkitRelativePath;
                while (wrp.indexOf(path.sep) !== -1) {
                    wrp = path.dirname(wrp);
                }
                filename = wrp;
            } else {
                // Fallback for non-standard webkitRelativePath
                filename = 'uploaded-directory';
            }
        }
        var issue = new Issue({
            code: 61,
            file: {
                name: filename,
                path: path.join('.', filename),
                relativePath: path.join('', filename)
            }
        });
        return issue;
    },

    /**
     * Quick Test
     *
     * A quick test to see if it could be a BIDS
     * dataset based on structure/naming. If it
     * could be it will trigger the full validation
     * otherwise it will throw a callback with a
     * generic error.
     */
    quickTest: function (fileList, callback) {
        var couldBeBIDS = false;
        for (var key in fileList) {
            if (fileList.hasOwnProperty(key)) {
                var file = fileList[key];
                var path = utils.files.relativePath(file);
                if (path) {
                    path = path.split('/');
                    path = path.reverse();
                    if (
                        path[0].includes('.nii') &&
                        (
                            path[1] == 'anat' ||
                            path[1] == 'func' ||
                            path[1] == 'dwi'
                        ) &&
                        (
                            (path[2] && path[2].indexOf('ses-') == 0) ||
                            (path[2] && path[2].indexOf('sub-') == 0)
                        )
                    ) {
                        couldBeBIDS = true;
                        break;
                    }
                }
            }
        }
        callback(couldBeBIDS);
    },

    /**
     * Full Test
     *
     * Takes on an array of files and starts
     * the validation process for a BIDS
     * package.
     */
    fullTest: function (fileList, callback) {
        var self = this;

        var jsonContentsDict = {},
            bContentsDict = {},
            events = [],
            niftis = [],
            headers = [],
            participants = null,
            phenotypeParticipants = [],
            hasSubjectDir = false;

        var summary = {
            sessions: [],
            subjects: [],
            tasks: [],
            modalities: [],
            totalFiles: Object.keys(fileList).length,
            size: 0
        };

        // check for illegal character in task name and acq name

        var task_re = /sub-(.*?)_task-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*(?:_acq-[a-zA-Z0-9-]*)?(?:_run-\d+)?_/g;
        var acq_re = /sub-(.*?)_task-\w+.\w+(_acq-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*)(?:_run-\d+)?_/g;

        var sub_re = /sub-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*_/g;   // illegal character in sub
        var ses_re = /ses-[a-zA-Z0-9]*[_-][a-zA-Z0-9]*?_(.*?)/g; //illegal character in ses

        var illegalchar_regex_list = [
            [task_re, 58, "task name contains illegal character:"],
            [acq_re, 59, "acq name contains illegal character:"],
            [sub_re, 62, "sub name contains illegal character:" ],
            [ses_re, 63, "ses name contains illegal character:" ]
        ];

        async.eachOfLimit(fileList, 200, function (file) {
            var completename = utils.files.relativePath(file);
            if(!(completename.startsWith('/derivatives') || completename.startsWith('/code') || completename.startsWith('/sourcedata'))) {
                for (var re_index = 0; re_index < illegalchar_regex_list.length; re_index++) {
                    var err_regex = illegalchar_regex_list[re_index][0];
                    var err_code = illegalchar_regex_list[re_index][1];
                    var err_evidence = illegalchar_regex_list[re_index][2];

                    if (err_regex.exec(completename)) {
                        self.issues.push(new Issue({
                            file: fileList[f],
                            code: err_code,
                            evidence: err_evidence + completename
                        }));
                    }
                }
            }
        })

        // validate individual files
        async.eachOfLimit(fileList, 200, function (file, key, cb) {
            var path = utils.files.relativePath(file);
            file.relativePath = path;

            // check for subject directory presence
            if (path.startsWith('/sub-')) {
                hasSubjectDir = true;
            }

            // ignore associated data
            if (utils.type.isAssociatedData(file.relativePath)) {
                process.nextTick(cb);
            }

            // validate path naming
            else if (!utils.type.isBIDS(file.relativePath)) {
                self.issues.push(new Issue({
                    file: file,
                    evidence: file.name,
                    code: 1
                }));
                process.nextTick(cb);
            }

            // capture niftis for later validation
            else if (file.name.endsWith('.nii') || file.name.endsWith('.nii.gz')) {
                niftis.push(file);

                // collect modality summary
                var pathParts = path.split('_');
                var suffix = pathParts[pathParts.length - 1];
                suffix = suffix.slice(0, suffix.indexOf('.'));
                if (summary.modalities.indexOf(suffix) === -1) {
                    summary.modalities.push(suffix);
                }

                process.nextTick(cb);
            }

            // validate tsv
            else if (file.name && file.name.endsWith('.tsv')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    if (file.name.endsWith('_events.tsv')) {
                        events.push(file.relativePath);
                    }
                    TSV(file, contents, fileList, function (issues, participantList) {
                        if (participantList) {
                            if (file.name.endsWith('participants.tsv')) {
                                participants = {
                                    list: participantList,
                                    file: file
                                };
                            } else if (file.relativePath.includes('phenotype/')) {
                                phenotypeParticipants.push({
                                    list: participantList,
                                    file: file
                                });
                            }
                        }
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate bvec
            else if (file.name && file.name.endsWith('.bvec')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    bContentsDict[file.relativePath] = contents;
                    bvec(file, contents, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate bval
            else if (file.name && file.name.endsWith('.bval')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    bContentsDict[file.relativePath] = contents;
                    bval(file, contents, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                });
            }

            // validate json
            else if (file.name && file.name.endsWith('.json')) {
                utils.files.readFile(file, function (issue, contents) {
                    if (issue) {
                        self.issues.push(issue);
                        process.nextTick(cb);
                        return;
                    }
                    json(file, contents, function (issues, jsObj) {
                        self.issues = self.issues.concat(issues);

                        // abort further tests if schema test does not pass
                        for (var i = 0; i < issues.length; i++) {
                            if (issues[i].severity === 'error') {
                                process.nextTick(cb);
                                return;
                            }
                        }

                        jsonContentsDict[file.relativePath] = jsObj;

                        // collect task summary
                        if (file.name.indexOf('task') > -1) {
                            var task = jsObj ? jsObj.TaskName : null;
                            if (task && summary.tasks.indexOf(task) === -1) {
                                summary.tasks.push(task);
                            }
                        }
                        process.nextTick(cb);
                    });
                });
            } else {
                process.nextTick(cb);
            }

            // collect file stats
            if (typeof window !== 'undefined') {
                if (file.size) {
                    summary.size += file.size;
                }
            } else {
                if (!file.stats) {
                    try {
                        file.stats = fs.statSync(file.path);
                    } catch (err) {
                        file.stats = {size: 0};
                    }
                }
                summary.size += file.stats.size;
            }

            // collect sessions & subjects
            if (!utils.type.isAssociatedData(file.relativePath) && utils.type.isBIDS(file.relativePath)) {
                var pathValues = utils.type.getPathValues(file.relativePath);

                if (pathValues.sub && summary.subjects.indexOf(pathValues.sub) === -1) {
                    summary.subjects.push(pathValues.sub);
                }
                if (pathValues.ses && summary.sessions.indexOf(pathValues.ses) === -1) {
                    summary.sessions.push(pathValues.ses);
                }
            }

        }, function () {
            async.eachOfLimit(niftis, 200, function (file, key, cb) {
                if (self.options.ignoreNiftiHeaders) {
                    NIFTI(null, file, jsonContentsDict, bContentsDict, fileList, events, function (issues) {
                        self.issues = self.issues.concat(issues);
                        process.nextTick(cb);
                    });
                } else {
                    utils.files.readNiftiHeader(file, function (header) {
                        // check if header could be read
                        if (header && header.hasOwnProperty('error')) {
                            self.issues.push(header.error);
                            process.nextTick(cb);
                        } else {
                            headers.push([file, header]);
                            NIFTI(header, file, jsonContentsDict, bContentsDict, fileList, events, function (issues) {
                                self.issues = self.issues.concat(issues);
                                process.nextTick(cb);
                            });
                        }
                    });
                }

            }, function () {
                if (!hasSubjectDir) {
                    self.issues.push(new Issue({code: 45}));
                }
                // check if participants file match found subjects

                if (participants) {
                    var participantsFromFile = participants.list.sort();
                    var participantsFromFolders = summary.subjects.sort();
                    if (!utils.array.equals(participantsFromFolders, participantsFromFile, true)) {
                        self.issues.push(new Issue({
                            code: 49,
                            evidence: "participants.tsv: " + participantsFromFile.join(', ') + " folder structure: " + participantsFromFolders.join(', '),
                            file: participants.file
                        }));
                    }
                }

                // check if dataset contains T1w
                if (summary.modalities.indexOf('T1w') < 0) {
                    self.issues.push(new Issue({
                        code: 53
                    }));
                }

                if (phenotypeParticipants && phenotypeParticipants.length > 0) {
                    for (var j = 0; j < phenotypeParticipants.length; j++) {
                        var fileParticpants = phenotypeParticipants[j];
                        var diff = utils.array.diff(fileParticpants.list, summary.subjects)[0];
                        if (diff && diff.length > 0) {
                            self.issues.push(new Issue({
                                code: 51,
                                evidence: 'sub-' + diff.join(', sub-'),
                                file: fileParticpants.file
                            }));
                        }
                    }
                }
                self.issues = self.issues.concat(headerFields(headers));
                self.issues = self.issues.concat(session(fileList));
                summary.modalities = utils.modalities.group(summary.modalities);
                var issues = utils.issues.format(self.issues, summary, self.options);
                callback(issues, summary);
            });
        });
    },

    /**
     * Reset
     *
     * Resets the in object data back to original values.
     */
    reset: function () {
        this.issues = [];
    }

};

module.exports = BIDS;
<|endoftext|>


<commit_before>var path = require('path');
var shell = require('shelljs');
var config = require('../config');
var build = require('../service/build');
var origin_sync = require('../service/origin-sync');
var qiniu_sync = require('../service/qiniu-sync');
var generate_tar_gz = require('../service/tar-gz');
var version = require('../service/version');
var Deploger = require('../service/deploger');

module.exports = function (req, res) {
  var repos = req.body.repository;

  var log_dir = path.join('log/', repos.owner.username);
  var log_file = repos.name + '.log';

  var err_msg, err;
  var deploger = new Deploger(log_dir, log_file);
  deploy_log_listener(deploger);

  deploger.emit('before-deploy', {
    log_dir: log_dir,
    log_file: log_file,
    env: 'alpha'
  });

  // 创建日志文件
  try {
    mk_log(deploger, log_dir, log_file);
  } catch(e) {
    err_msg = '步骤1失败: 创建日志目录或文件';
    err = new Error(err_msg);

    deploger.emit('mk-log-err', {
      msg: err_msg,
      err: err
    });

    return res.status(200).json({
      code: 500,
      data: err_msg
    });
  }

  // build 项目
  deploger.emit('before-build');
  var build_rs;

  try {
    build_rs = build(
      req.body,
      config.alpha_work_path
    );
  } catch(e) {
    err_msg = '步骤2失败: build 项目';
    err = new Error(err_msg);

    deploger.emit('build-err', {
      msg: err_msg,
      err: err
    });

    return res.status(200).json({
      code: 500,
      data: err_msg
    });
  }
  deploger.emit('after-build');

  // 项目 package.json
  var pkg = require(path.resolve(build_rs.out_dir, './package.json'));

  // 同步到静态资源服务器
  try {
    origin_sync(deploger, pkg, build_rs);
  } catch(e) {
    err_msg = '步骤3失败: 同步到静态资源服务器';
    err = new Error(err_msg);

    deploger.emit('origin-sync-err', {
      msg: err_msg,
      err: err
    });

    res.status(200).json({
      code: 500,
      data: err_msg
    });
  }

  // 同步项目到七牛服务器
  try {
    qiniu_sync();
  } catch(e) {
    err_msg = '步骤4失败: 同步项目到七牛服务器';
    err = new Error(err_msg);

    deploger.emit('qiniu-sync-err', {
      msg: err_msg,
      err: err
    });

    return res.status(200).json({
      code: 500,
      data: err_msg
    });
  }
  deploger.emit('after-sync-tasks');

  try {
    generate_tar_gz(deploger, build_rs, pkg);
  } catch(e) {
    err_msg = '步骤5失败: 生成静态项目压缩包';
    err = new Error(err_msg);

    deploger.emit('generate-tar-gz-err', {
      msg: err_msg,
      err: err
    });

    return res.status(200).json({
      code: 500,
      data: err_msg
    });
  }

  version({
    owner: build_rs.repository.owner.username,
    name: build_rs.repository.name,
    version: pkg.version,
    url: build_rs.repository.url,
    download: 'http://d.ifdiu.com/f2e/alpha/' + build_rs.repository.name + '?secret=yunhua@926&owner=' + build_rs.repository.owner.username
  }, function(err) {
    deploger.emit('after-update-version');

    if (err) {
      err_msg = '步骤6失败: 更新版本数据库失败';
      err = new Error(err_msg);

      deploger.emit('update-version-err', {
        msg: err_msg,
        err: err
      });

      return res.status(200).json({
        code: 500,
        data: err_msg
      });
    }

    // TODO
    // 新建函数处理下面任务
    // 不需要清理，缓存加速再次发布
    // logger.info('正在清理发布目录...');
    // shell.exec(['rm', '-rf', build_rs.out_dir].join(' '));
    // logger.info('清理发布目录完成');

    res.status(200).json({
      code: 200,
      data: '项目发布成功'
    });
  });
};

function mk_log(deploger, log_dir, log_file) {
  var err_msg;

  log_file = path.join(log_dir, log_file);

  var mkdir_log = shell.exec('mkdir -p ' + log_dir);
  if (mkdir_log.code !== 0) {
    err_msg = '创建日志目录' + log_dir + '失败';

    deploger.emit('mkdir-log-err', {
      msg: err_msg,
      err: new Error(mkdir_log.output)
    });

    throw new Error(err_msg);
  }

  // 基本不会 throw  err
  shell.exec('touch ' + log_file);

  // var touch_logfile = shell.exec('touch ' + log_file);
  // if (touch_logfile.code !== 0) {
  //   err_msg = '创建日志文件' + log_file + '失败';

  //   deploger.emit('touch-logfile-err', {
  //     msg: err_msg,
  //     err: new Error(touch_logfile.output)
  //   });

  //   throw new Error(err_msg);
  // }

  var clear_logfile = shell.exec('> ' + log_file);
  if (clear_logfile.code !== 0) {
    err_msg = '清空日志文件' + log_file + '失败';

    deploger.emit('clear-logfile-err', {
      msg: err_msg,
      err: new Error(clear_logfile.output)
    });

    throw new Error(err_msg);
  }
}

function deploy_log_listener(deploger) {
  var logger = deploger.logger;
  var errHandler = deploger.errHandler;

  deploger
    .on('before-deploy', function(data) {
      logger.trace('发布' + data.env + '环境中');
    })
    .on('mk-log-err', errHandler)
    .on('before-build', function() {})
    .on('after-build', function() {})
    .on('build-err', errHandler)
    .on('origin-sync-err', errHandler)
    .on('qiniu-sync-err', errHandler)
    .on('after-sync-tasks', function() {
      logger.info('静态资源发布到服务器成功');
    })
    .on('generate-tar-gz-err', errHandler)
    .on('after-update-version', function() {
      logger.info('版本更新成功');
    })
  ;
}
<commit_msg>deploy log<commit_after>var path = require('path');
var shell = require('shelljs');
var config = require('../config');
var build = require('../service/build');
var origin_sync = require('../service/origin-sync');
var qiniu_sync = require('../service/qiniu-sync');
var generate_tar_gz = require('../service/tar-gz');
var version = require('../service/version');
var Deploger = require('../service/deploger');

module.exports = function (req, res) {
  var _deploger = new Deploger('log/deploy.log', 'deploy');
  _deploy_log_listener(_deploger);

  var repos = req.body.repository;

  var log_dir = path.join('log/', repos.owner.username);
  var log_file = repos.name + '.log';
  var err_msg, err;

  _deploger.emit('before-deploy', {
    log_dir: log_dir,
    log_file: log_file,
    env: 'alpha'
  });

  // 创建日志文件
  try {
    mk_log(_deploger, log_dir, log_file);
  } catch(e) {
    err_msg = '步骤1失败: 创建日志目录或文件';
    err = new Error(err_msg);

    deploger.emit('mk-log-err', {
      msg: err_msg,
      err: err
    });

    return res.status(200).json({
      code: 500,
      data: err_msg
    });
  }

  var deploger = new Deploger(path.join(log_dir, log_file), 'publish');

  // build 项目
  deploger.emit('before-build');
  var build_rs;

  try {
    build_rs = build(
      req.body,
      config.alpha_work_path
    );
  } catch(e) {
    err_msg = '步骤2失败: build 项目';
    err = new Error(err_msg);

    deploger.emit('build-err', {
      msg: err_msg,
      err: err
    });

    return res.status(200).json({
      code: 500,
      data: err_msg
    });
  }
  deploger.emit('after-build');

  // 项目 package.json
  var pkg = require(path.resolve(build_rs.out_dir, './package.json'));

  // 同步到静态资源服务器
  try {
    origin_sync(deploger, pkg, build_rs);
  } catch(e) {
    err_msg = '步骤3失败: 同步到静态资源服务器';
    err = new Error(err_msg);

    deploger.emit('origin-sync-err', {
      msg: err_msg,
      err: err
    });

    res.status(200).json({
      code: 500,
      data: err_msg
    });
  }

  // 同步项目到七牛服务器
  try {
    qiniu_sync();
  } catch(e) {
    err_msg = '步骤4失败: 同步项目到七牛服务器';
    err = new Error(err_msg);

    deploger.emit('qiniu-sync-err', {
      msg: err_msg,
      err: err
    });

    return res.status(200).json({
      code: 500,
      data: err_msg
    });
  }
  deploger.emit('after-sync-tasks');

  try {
    generate_tar_gz(deploger, build_rs, pkg);
  } catch(e) {
    err_msg = '步骤5失败: 生成静态项目压缩包';
    err = new Error(err_msg);

    deploger.emit('generate-tar-gz-err', {
      msg: err_msg,
      err: err
    });

    return res.status(200).json({
      code: 500,
      data: err_msg
    });
  }

  version({
    owner: build_rs.repository.owner.username,
    name: build_rs.repository.name,
    version: pkg.version,
    url: build_rs.repository.url,
    download: 'http://d.ifdiu.com/f2e/alpha/' + build_rs.repository.name + '?secret=yunhua@926&owner=' + build_rs.repository.owner.username
  }, function(err) {
    deploger.emit('after-update-version');

    if (err) {
      err_msg = '步骤6失败: 更新版本数据库失败';
      err = new Error(err_msg);

      deploger.emit('update-version-err', {
        msg: err_msg,
        err: err
      });

      return res.status(200).json({
        code: 500,
        data: err_msg
      });
    }

    // TODO
    // 新建函数处理下面任务
    // 不需要清理，缓存加速再次发布
    // logger.info('正在清理发布目录...');
    // shell.exec(['rm', '-rf', build_rs.out_dir].join(' '));
    // logger.info('清理发布目录完成');

    res.status(200).json({
      code: 200,
      data: '项目发布成功'
    });
  });
};

function mk_log(deploger, log_dir, log_file) {
  var err_msg;

  log_file = path.join(log_dir, log_file);

  var mkdir_log = shell.exec('mkdir -p ' + log_dir);
  if (mkdir_log.code !== 0) {
    err_msg = '创建日志目录' + log_dir + '失败';

    deploger.emit('mkdir-log-err', {
      msg: err_msg,
      err: new Error(mkdir_log.output)
    });

    throw new Error(err_msg);
  }

  // 基本不会 throw  err
  shell.exec('touch ' + log_file);

  // var touch_logfile = shell.exec('touch ' + log_file);
  // if (touch_logfile.code !== 0) {
  //   err_msg = '创建日志文件' + log_file + '失败';

  //   deploger.emit('touch-logfile-err', {
  //     msg: err_msg,
  //     err: new Error(touch_logfile.output)
  //   });

  //   throw new Error(err_msg);
  // }

  var clear_logfile = shell.exec('> ' + log_file);
  if (clear_logfile.code !== 0) {
    err_msg = '清空日志文件' + log_file + '失败';

    deploger.emit('clear-logfile-err', {
      msg: err_msg,
      err: new Error(clear_logfile.output)
    });

    throw new Error(err_msg);
  }
}

function _deploy_log_listener(deploger) {
  var logger = deploger.logger;
  var errHandler = deploger.errHandler;

  deploger
    .on('before-deploy', function(data) {
      logger.trace('发布' + data.env + '环境中');
    })
    .on('mk-log-err', errHandler)
  ;
}

function deploy_log_listener(deploger) {
  deploger
    .on('before-build', function() {})
    .on('after-build', function() {})
    .on('build-err', errHandler)
    .on('origin-sync-err', errHandler)
    .on('qiniu-sync-err', errHandler)
    .on('after-sync-tasks', function() {
      logger.info('静态资源发布到服务器成功');
    })
    .on('generate-tar-gz-err', errHandler)
    .on('after-update-version', function() {
      logger.info('版本更新成功');
    })
  ;
}
<|endoftext|>


<commit_before>'use strict';
// Here first we are stablishing a connection to the drone,
//and inside that connection we are stablishing a socket server connection
var RollingSpider = require('rolling-spider');
var temporal = require('temporal');
var rollingSpider = new RollingSpider({
  uuid: 'RS_W056147'
  // uuid: 'RS_B138046'
});

var ACTIVE = true;
var STEPS = 5;

function cooldown() {
  ACTIVE = false;
  setTimeout(function() {
    ACTIVE = true;
  }, STEPS * 12);
};

var i = 1;
while(i === 1){
  i = 0;
  console.log('lets connect to the drone!');
  rollingSpider.connect(function (error) {
    if (error){
      console.log("error: ", error)
    }

    console.log('lets set up the drone');
    rollingSpider.setup(function () {
      console.log('lets ping the drone!')
      rollingSpider.flatTrim();
      rollingSpider.startPing();
      rollingSpider.flatTrim();

      // rollingSpider.on('battery', function () {
      // console.log('Battery: ' + rollingSpider.status.battery + '%');
      // rollingSpider.signalStrength(function (err, val) {
      //   console.log('Signal: ' + val + 'dBm');
      // });
      // });

      var WebSocket = require('ws')
      var ws = new WebSocket('ws://' + 'localhost' + ':3001');
      ws.addEventListener('open', () => {
        //Telling the socket server that this is the controller
        ws.send(JSON.stringify({type:"controller"}));
      });

      ws.addEventListener('message', (event) => {
        console.log(event.data)
        var data=JSON.parse(event.data);
        if(data.type === "command"){
          if(data.content === "takeoff"){
            rollingSpider.takeoff();
          }else if(data.content === "land"){
            rollingSpider.land();
          }else if(data.content === "up"){
            rollingSpider.up({ steps: STEPS });
          }else if(data.content === "down"){
            rollingSpider.down({ steps: STEPS });
          }else if(data.content === "forward"){
            rollingSpider.forward({ steps: STEPS });
          }else if(data.content === "backward"){
            rollingSpider.backward({ steps: STEPS });
          }else if(data.content === "left"){
            rollingSpider.left({ steps: STEPS });
          }else if(data.content === "right"){
            rollingSpider.right({ steps: STEPS });
          }else if(data.content === "clockwise"){
            rollingSpider.clockwise({ steps: STEPS });
          }else if(data.content === "counterclockwise"){
            rollingSpider.counterClockwise({ steps: STEPS });
          }
        }
      });

      setTimeout(() => {
        console.log("Simulating incoming message");
      });
    });
  });
};
<commit_msg>clean version with Youtube Live<commit_after>'use strict';
// Here first we are stablishing a connection to the drone,
//and inside that connection we are stablishing a socket server connection
var RollingSpider = require('rolling-spider');
var temporal = require('temporal');
var rollingSpider = new RollingSpider({
  // uuid: 'RS_W056147'
  // uuid: 'RS_B138046'
});

var ACTIVE = true;
var STEPS = 5;

function cooldown() {
  ACTIVE = false;
  setTimeout(function() {
    ACTIVE = true;
  }, STEPS * 12);
};

var i = 1;
while(i === 1){
  i = 0;
  console.log('lets connect to the drone!');
  rollingSpider.connect(function (error) {
    if (error){
      console.log("error: ", error)
    }

    console.log('lets set up the drone');
    rollingSpider.setup(function () {
      console.log('lets ping the drone!')
      rollingSpider.flatTrim();
      rollingSpider.startPing();
      rollingSpider.flatTrim();

      var WebSocket = require('ws')
      var ws = new WebSocket('ws://' + 'localhost' + ':3001');
      ws.addEventListener('open', () => {
        //Telling the socket server that this is the controller
        ws.send(JSON.stringify({type:"controller"}));
      });

      ws.addEventListener('message', (event) => {
        console.log(event.data)
        var data=JSON.parse(event.data);
        if(data.type === "command"){
          if(data.content === "takeoff"){
            rollingSpider.takeoff();
          }else if(data.content === "land"){
            rollingSpider.land();
          }else if(data.content === "up"){
            rollingSpider.up({ steps: STEPS });
          }else if(data.content === "down"){
            rollingSpider.down({ steps: STEPS });
          }else if(data.content === "forward"){
            rollingSpider.forward({ steps: STEPS });
          }else if(data.content === "backward"){
            rollingSpider.backward({ steps: STEPS });
          }else if(data.content === "left"){
            rollingSpider.left({ steps: STEPS });
          }else if(data.content === "right"){
            rollingSpider.right({ steps: STEPS });
          }else if(data.content === "clockwise"){
            rollingSpider.clockwise({ steps: STEPS });
          }else if(data.content === "counterclockwise"){
            rollingSpider.counterClockwise({ steps: STEPS });
          }
        }
      });

      setTimeout(() => {
        console.log("Simulating incoming message");
      });
    });
  });
};
<|endoftext|>


<commit_before>'use strict';

const $ = require('cheerio');
const fs = require('fs');
const path = require('path');
const sendfile = require('koa-sendfile');
const _ = require('lodash');
/**
 * A set of functions called "actions" for `Admin`
 */

module.exports = {

  index: function *() {

    // Read the default `index.html` file from the admin panel build
    const html = fs.readFileSync(path.resolve(__dirname, '..', 'public', 'build', 'index.html'));

    // Convert the stream to a string
    const htmlString = html.toString();

    // Use `cheerio` to parse the HTML string
    const parsedHTML = $.load(htmlString);

    // // Some plugins are ignored
    // const ignoredPlugins = ['admin', 'user'];
    //
    // // Inject `js` files from plugins builds in the main admin panel
    // _.forEach(strapi.api, (value, pluginName) => {
    //   if (!_.includes(ignoredPlugins, pluginName)) {
    //     // Main plugin `js` file
    //     const pluginMainScript = $('<script>').attr('src', '/plugins/' + pluginName + '/main.js');
    //     parsedHTML('body').append(pluginMainScript);
    //
    //     // Vendors plugin `js` file
    //     const pluginVendorScript = $('<script>').attr('src', '/plugins/' + pluginName + '/vendor.js');
    //     parsedHTML('body').append(pluginVendorScript);
    //   }
    // });

    // Finally, send the HTML file with injected scripts
    this.body = parsedHTML.html();
  },

  file: function *() {
    yield sendfile(this, path.resolve(__dirname, '..', 'public', 'build', this.params.file));
    if (!this.status) this.throw(404);
  }
};
<commit_msg>Fix plugins routes in admin file generator<commit_after>'use strict';

const $ = require('cheerio');
const fs = require('fs');
const path = require('path');
const sendfile = require('koa-sendfile');
const _ = require('lodash');
/**
 * A set of functions called "actions" for `Admin`
 */

module.exports = {

  index: function *() {

    // Read the default `index.html` file from the admin panel build
    const html = fs.readFileSync(path.resolve(__dirname, '..', 'public', 'build', 'index.html'));

    // Convert the stream to a string
    const htmlString = html.toString();

    // Use `cheerio` to parse the HTML string
    const parsedHTML = $.load(htmlString);

    // Some plugins are ignored
    const ignoredPlugins = ['admin', 'user'];

    console.log('strapi.plugins', strapi.plugins)

    // Inject `js` files from plugins builds in the main admin panel
    _.forEach(strapi.plugins, (value, pluginName) => {
      if (!_.includes(ignoredPlugins, pluginName)) {
        // Main plugin `js` file
        const pluginMainScript = $('<script>').attr('src', '/' + pluginName + '/main.js');
        parsedHTML('body').append(pluginMainScript);

        // Vendors plugin `js` file
        const pluginVendorScript = $('<script>').attr('src', '/' + pluginName + '/vendor.js');
        parsedHTML('body').append(pluginVendorScript);
      }
    });

    // Finally, send the HTML file with injected scripts
    this.body = parsedHTML.html();
  },

  file: function *() {
    yield sendfile(this, path.resolve(__dirname, '..', 'public', 'build', this.params.file));
    if (!this.status) this.throw(404);
  }
};
<|endoftext|>


<commit_before>jQuery(function($) {
    /*
    $('.admin-nav-bar').delegate('li a', 'click', function(e) {
        var url = $(this).attr('href');
        var deselect_this = false;

        $(this).parent().siblings().children('a').each(function() {
            $(this).removeClass("selected");
        });

        if(!deselect_this) {
            $(this).addClass('selected');
        }

        $.pjax({
            url: url
          , container: '.the-feedbacks'
          , success: function() {
              $('.status-change > select, .priority-change > select, div.category-picker-holder, div.fast-forward-holder, .ff-form, #notification-message').hide();
          }
        });

        e.preventDefault();
    });
    */

    $("abbr.timeago").timeago();

    $(document).delegate("a.cat-picks", "click", function(e) {

        var deselect_this = false;

        $(this).parent().siblings().children('a').each(function() {
            $(this).removeClass("Matched");
        });

        if(!deselect_this) {
            $(this).addClass('Matched');
        }

        var catpick = new CatPickObject($(this));
        catpick.process();
        catpick.undo();

        e.preventDefault();
    });

    $(document).delegate("a.menubtn", "click", function(e) {

        var deselect = false;

        $(this).parent().children('a.menubtn').each(function() {
            $(this).removeClass("matched");
        });

        if(!deselect) {
            $(this).addClass('matched');
        }

        $.ajax({
            type: "GET"
          , url: $(this).attr('href')
          , success: function(msg) {
                var myStatus = new Status();
                console.log("mathew");
                myStatus.notify("Processing...", 10000);
            }
        })

        e.preventDefault();
    })

    //for modify feedback bit
    $(document).delegate("a.flagged", "click", function(e) {
        $(this).toggleClass("matched");

        var state = $(this).attr('state');
        var var_state;
        if(state == 0) {
            $(this).attr('state', 1);
            var_state = 1;
        } else {
            $(this).attr('state', 0);
            var_state = 0;
        }

        $.ajax({
            type: "GET"
          , data: {"state": var_state}
          , url: $(this).attr('href')
          , success: function(msg) {
                var myStatus = new Status();
                myStatus.notify("Processing...", 1000);
            }
        })

        e.preventDefault();
    });

    $(document).delegate("a.delete", "click", function(e) {
        if(confirm("Are you sure you want to delete this feedback?")) {
            return true;
        }
        e.preventDefault();
    });

    $('.reply').bind("click", function(e) {
        var href = $(this).attr('hrefaction');
        window.location = href;
        e.preventDefault();
        /*TODO WORK ON THIS LATER This should be a modal popup
        $.ajax({
            url: href
        });*/
    })

    var seen = {};
    $('.add-bcc > li').bind("click", function(e) {
        var pointer = $(this).index();
        var input = "<input type='text' name='bcc[]' value='"+$(this).text()+"' />  [x]";

        if(typeof seen[pointer] == 'undefined') {
           $("#bcc-target").append(input);
           seen[pointer] = true;
        }

        $(".delete-bcc").unbind("click.delete-bcc").bind("click.delete-bcc", function(e) {
            var del_pointer = $(this).attr('id');
            $(this).prev('input').remove().end().remove();
            delete seen[del_pointer];
            e.preventDefault();
        })

        e.preventDefault();
    })

    //check theme 1 by default
    $("#themeId_1 input:radio").attr('checked', true);

    //FastForward Email Block...fuck this is a mess...
    $('div.category-picker-holder, div.fast-forward-holder, .ff-form, #notification-message').hide();
    var mouse_is_inside = false;
    $('.contact, .fileas, .forward').hover(function() {
        mouse_is_inside = true;
    }, function() {
        mouse_is_inside = false;
    });

    $(document).delegate(".fileas", "click", function(e) {
        var id = $(this).attr('id');
        $('#' + id + ' div.category-picker-holder').show().hover(function() {
            mouse_is_inside = true;
        }, function() {
            mouse_is_inside = false;
        });
        e.preventDefault();
    })

    $('textarea[name="email_comment"]').bind("focus", function() {
        $(this).val("");
    })

    //fucking bug where in for some reason jquery cannot select the div.fast-forward-holder element when using the forward class name.
    $(document).delegate(".contact, .forward", "click", function(e) {
        var id = $(this).attr('id');
        var selector;

        var class_name = $(this).attr('class');

        if(class_name == 'contact') {
            selector = $('#' + id + ' div.fast-forward-holder');
        }

        if(class_name == 'forward') {
            selector = $('#' + id);
        }

        selector.show()
        .hover(function() {
            $('div.email-list > ul.email-picker li', this)
            .live('click', function() {
                var me = $(this);
                me.parent().hide()
                       .siblings('.ff-form')
                       .ajaxForm({
                            success: function() {
                                me.parents('div.fast-forward-holder').hide().end()
                                  .parents('.email-picker').show().end()
                                  .parent().siblings('.ff-form').hide().children('.ff-forward-to').html("").end();
                                $('textarea[name="email_comment"]').val("");
                                alert("Fast-forward sent to " + $('a', me).text());
                            }
                        })
                           .children('.ff-forward-to').html($(this).html()).end()
                           .children('input[name="email"]').val($('a', this).html()).end()
                       .show();
            });
            mouse_is_inside = true;
        }, function() {
            mouse_is_inside = false;
        });
        e.preventDefault();
    })

    $("body").click(function() {
        if(!mouse_is_inside) {
            $('div.fast-forward-holder, div.category-picker-holder, .ff-form').hide();
            $('.email-picker').show();
            $('textarea[name="email_comment"]').val("");
        }
    })

    //End of FastForward
    new InboxStatusChange('.check, .feature, .remove, .popup-delete').initialize();
    $('div.undo-bar').hide();

    //TODO: Please update
    $('.flag').switcharoo('-100px 0px');

    $.each($('ul#nav-menu li'), function(index, value) {
        $(value).bind('click', function(e) {
            window.location = $(this).children('a').attr('href');
        });
    });

    var check = new Checky({
        feed_selection: '.feed-selection'
      , check_feed_id: '.check-feed-id'
      , category_feed_id: '.category-feed-id'
      , click_all: '.click-all'
    });

    check.init();
    check.clickAll();

    $('.status-change > select, .priority-change > select').hide();

    var statusChange = new DropDownChange({status_element: 'span.status-change', status_selector: 'change.status'});
    statusChange.enable();
    var priorityChange = new DropDownChange({status_element: 'span.priority-change', status_selector: 'change.priority'});
    priorityChange.enable();

    $('.check').fancytips();
    $('.fileas').fancytips();
    $('.reply').fancytips();
    $('.feature').fancytips();
    $('.contact').fancytips();
    $('.flag').fancytips();
    $('.remove').fancytips({'top': 45});

    $('a.perm-delete').click(function(e) {
        if(confirm("Are you sure you want to permanently delete this feedback?")) {
            return true;
        }
        e.preventDefault();
    });

    CategoryControl();

    $('a.add-new-ctgy').bind("click", function(e) {
        var ctgy_nm = $("input[name='category_nm']");
        var ctgy_list = $("#ctgy-list");

        if(ctgy_nm.val() == false)
            alert("Category Name cannot be blank.");
        else
            $.ajax({
                url: ctgy_list.attr('hrefaction')
              , type: "POST"
              , data: {ctgy_nm: ctgy_nm.val(), companyId: $("input[name='companyid']").val()}
              , success: function(msg) {
                  ctgy_list.append(msg);
                  ctgy_nm.val("");
                  CategoryControl();
              }
            });

        e.preventDefault();
    })

    function CategoryControl() {
       $('a.rename-ctgy, a.delete-ctgy').unbind('click.ctgy-controls').bind('click.ctgy-controls', function(e) {
           var class_name = $(this).attr('class');
           var that = $(this);

           if(class_name == 'rename-ctgy') {
               var input = $('<input type="text" name="ctgy_nm"/>').val(
                   that.parents('div').siblings('div').children('.ctgy-name').html()
               );

              if(that.text() == "Update") {
                  var ctgy_nm_val = $('input[name="ctgy_nm"]').val()
                  console.log("Rename");
                  that.text("Rename")
                        .parents('div')
                        .siblings('div')
                        .children('.ctgy-name')
                        .html( ctgy_nm_val ).end().end().end()
                  $.ajax({ url: that.attr('href'), type: "POST", data: {ctgy_nm: ctgy_nm_val} });
              } else {
                  that.text("Update")
                        .parents('div')
                        .siblings('div')
                        .children('.ctgy-name')
                        .html( input ).end().end().end()
              }

           }

           if(class_name == 'delete-ctgy') {
              var d = that.parents('div.grids');
              if(confirm("Are you sure you want to delete this category? There is no undo.")) {
                  $.ajax({ url: $(this).attr('href'), success: function(msg) { d.fadeOut(); } });
              }
           }

           e.preventDefault();
       })
    }

    var jcrop_api, set_image;
    function initJcrop() {
        $('#jcrop_target').Jcrop({
            setSelect: ['40','20','190','170']
          , boxWidth: 350
          , boxHeight: 230
          , aspectRatio: 1
          , onChange: showPreview
          , onSelect: showPreview
        }, function() {
            jcrop_api = this;
        });
    }

    function showPreview(coords) {

        var rx = 100 / coords.w;
        var ry = 100 / coords.h;
        var target = $('#jcrop_target');
        var hgt = target.height();
        var wdt = target.width();

        $('#x').val(coords.x);
        $('#y').val(coords.y);
        $('#w').val(coords.w);
        $('#h').val(coords.h);

        $('#preview').css({
            width: Math.round(rx * wdt) + 'px',
            height: Math.round(ry * hgt) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        });
    };

    function save_crop_image(){

        var x_coords = $('#x').val();
        var y_coords = $('#y').val();
        var wd = $('#w').val();
        var ht = $('#h').val();
        var cropped_photo = $('#preview').attr('src');
		var crop_status = $('#crop_status');
		var oldphoto = $('#cropped_photo').val();
        crop_status.html(' Cropping Photo...');

        $.ajax({
            url: $("#ajax-crop-url").attr('hrefaction')
          , method: "POST"
          , data: {src: cropped_photo, x_coords: x_coords, y_coords: y_coords, wd: wd, ht: ht, oldphoto: oldphoto, login_type: 36}
          , success: function(data){
                crop_status.fadeOut('fast',function(){
                    $('#cropped_photo').val(data);
                });

                var myStatus = new Status();
                myStatus.notify("Your photo is successfully cropped! If you feel this is the right photo for you please click on the Save Settings button.", 7000);

            }
        });
    }

    $('div.adjust-crop').hide();
    $(document).delegate("#your_photo", "change", function() {
		$.ajaxFileUpload ({
            url: $("#ajax-upload-url").attr('hrefaction'),
            secureuri:false,
            fileElementId:'your_photo',
            dataType: 'json',
            success: function (data, status) {

                var myStatus = new Status();
                myStatus.notify("Photo Upload Success!", 1000);

                var file = "/" + data.dir;
                var width = Math.round(data.wid);
                var jcrop_div = $("div.jcrop_div");
                var existing_avatar = $('input[name="existing_avatar"]');

                $('div.adjust-crop').show();

                $('#profile_picture').attr('src',file);
                $('#jcrop_target').attr('src',file);
                $('#preview').attr('src',file);

                if(jcrop_api) {
                    jcrop_api.setImage($('#profile_picture').attr('src'));
                    jcrop_api.setSelect(['40','20','190','170']);
                }

                if(existing_avatar.length > 0) {
                    $.post($("#ajax-delete-existing-avatar").attr('hrefaction'), {avatar: existing_avatar.val()});
                }

                jcrop_div.css({'width':width});
                $('input[name="orig_image_dir"]').val(file);
                initJcrop();

            }
		});
    });

    $('#cropbtn').click(function(){
        save_crop_image();
    });

    $(document).delegate('a.save', 'click', function(e) {
        var textarea = $('.feedback-textarea');
        var hrefaction = textarea.attr('hrefaction');

        var feed_id = $('#feed-id').val();
        $.post(hrefaction, { feed_id: feed_id, feedback_text: textarea.val() }, function(msg) {
            var myStatus = new Status();
            myStatus.notify("Processing...", 1000);
        });
        e.preventDefault();
    });

    $('a.admin-delete').bind('click', function(e) {
        if(confirm("Are you sure you want to delete this user? There is no undo.")) {
            return true;
        }
        e.preventDefault();
    });

    $('.contact-edit').bind('click', function(e) {
        var href = $(this).attr('hrefaction');
        window.location = href;
        e.preventDefault();
    });

    $('.contact-delete').bind('click', function(e) {
        var hrefaction= $(this).attr('hrefaction');
        var that = this;
        if(confirm("Are you sure you want to delete this user? There is no undo.")) {
            $.get(hrefaction, function(msg) {
                $(that).parents('tr').fadeOut(350);
            });
        }
        e.preventDefault();
    });

    $('.copycheck').hide();
    $("#widget-preview").hide();
    new ZClip();
});
<commit_msg>tetsing<commit_after>jQuery(function($) {
    /*
    $('.admin-nav-bar').delegate('li a', 'click', function(e) {
        var url = $(this).attr('href');
        var deselect_this = false;

        $(this).parent().siblings().children('a').each(function() {
            $(this).removeClass("selected");
        });

        if(!deselect_this) {
            $(this).addClass('selected');
        }

        $.pjax({
            url: url
          , container: '.the-feedbacks'
          , success: function() {
              $('.status-change > select, .priority-change > select, div.category-picker-holder, div.fast-forward-holder, .ff-form, #notification-message').hide();
          }
        });

        e.preventDefault();
    });
    */

    $("abbr.timeago").timeago();

    $(document).delegate("a.cat-picks", "click", function(e) {

        var deselect_this = false;

        $(this).parent().siblings().children('a').each(function() {
            $(this).removeClass("Matched");
        });

        if(!deselect_this) {
            $(this).addClass('Matched');
        }

        var catpick = new CatPickObject($(this));
        catpick.process();
        catpick.undo();

        e.preventDefault();
    });

    $(document).delegate("a.menubtn", "click", function(e) {

        var deselect = false;

        $(this).parent().children('a.menubtn').each(function() {
            $(this).removeClass("matched");
        });

        if(!deselect) {
            $(this).addClass('matched');
        }

        $.ajax({
            type: "GET"
          , url: $(this).attr('href')
          , success: function(msg) {
                var myStatus = new Status();
                console.log("mathew");
                myStatus.notify("Processing...", 10000);
            }
        })

        e.preventDefault();
    })

    //for modify feedback bit
    $(document).delegate("a.flagged", "click", function(e) {
        $(this).toggleClass("matched");

        var state = $(this).attr('state');
        var var_state;
        if(state == 0) {
            $(this).attr('state', 1);
            var_state = 1;
        } else {
            $(this).attr('state', 0);
            var_state = 0;
        }

        $.ajax({
            type: "GET"
          , data: {"state": var_state}
          , url: $(this).attr('href')
          , success: function(msg) {
                var myStatus = new Status();
                myStatus.notify("Processing...", 1000);
            }
        })

        e.preventDefault();
    });

    $(document).delegate("a.delete", "click", function(e) {
        if(confirm("Are you sure you want to delete this feedback?")) {
            return true;
        }
        e.preventDefault();
    });

    $('.reply').bind("click", function(e) {
        var href = $(this).attr('hrefaction');
        window.location = href;
        e.preventDefault();
        /*TODO WORK ON THIS LATER This should be a modal popup
        $.ajax({
            url: href
        });*/
    })

    var seen = {};
    $('.add-bcc > li').bind("click", function(e) {
        var pointer = $(this).index();
        var input = "<input type='text' name='bcc[]' value='"+$(this).text()+"' />  [x]";

        if(typeof seen[pointer] == 'undefined') {
           $("#bcc-target").append(input);
           seen[pointer] = true;
        }

        $(".delete-bcc").unbind("click.delete-bcc").bind("click.delete-bcc", function(e) {
            var del_pointer = $(this).attr('id');
            $(this).prev('input').remove().end().remove();
            delete seen[del_pointer];
            e.preventDefault();
        })

        e.preventDefault();
    })

    //check theme 1 by default
    $("#themeId_1 input:radio").attr('checked', true);

    //FastForward Email Block...fuck this is a mess...
    $('div.category-picker-holder, div.fast-forward-holder, .ff-form, #notification-message').hide();
    var mouse_is_inside = false;
    $('.contact, .fileas, .forward').hover(function() {
        mouse_is_inside = true;
    }, function() {
        mouse_is_inside = false;
    });

    $(document).delegate(".fileas", "click", function(e) {
        var id = $(this).attr('id');
        $('#' + id + ' div.category-picker-holder').show().hover(function() {
            mouse_is_inside = true;
        }, function() {
            mouse_is_inside = false;
        });
        e.preventDefault();
    })

    $('textarea[name="email_comment"]').bind("focus", function() {
        $(this).val("");
    })

    //fucking bug where in for some reason jquery cannot select the div.fast-forward-holder element when using the forward class name.
    $(document).delegate(".contact, .forward", "click", function(e) {
        var id = $(this).attr('id');
        var selector;

        var class_name = $(this).attr('class');

        if(class_name == 'contact') {
            selector = $('#' + id + ' div.fast-forward-holder');
        }

        if(class_name == 'forward') {
            selector = $('#' + id);
        }

        selector.show()
        .hover(function() {
            $('div.email-list > ul.email-picker li', this)
            .live('click', function() {
                var me = $(this);
                me.parent().hide()
                       .siblings('.ff-form')
                       .ajaxForm({
                            success: function() {
                                me.parents('div.fast-forward-holder').hide().end()
                                  .parents('.email-picker').show().end()
                                  .parent().siblings('.ff-form').hide().children('.ff-forward-to').html("").end();
                                $('textarea[name="email_comment"]').val("");
                                alert("Fast-forward sent to " + $('a', me).text());
                            }
                        })
                           .children('.ff-forward-to').html($(this).html()).end()
                           .children('input[name="email"]').val($('a', this).html()).end()
                       .show();
            });
            mouse_is_inside = true;
        }, function() {
            mouse_is_inside = false;
        });
        e.preventDefault();
    })

    $("body").click(function() {
        if(!mouse_is_inside) {
            $('div.fast-forward-holder, div.category-picker-holder, .ff-form').hide();
            $('.email-picker').show();
            $('textarea[name="email_comment"]').val("");
        }
    })

    //End of FastForward
    new InboxStatusChange('.check, .feature, .remove, .popup-delete').initialize();
    $('div.undo-bar').hide();

    //TODO: Please update
    $('.flag').switcharoo('-100px 0px');

    $.each($('ul#nav-menu li'), function(index, value) {
        $(value).bind('click', function(e) {
            window.location = $(this).children('a').attr('href');
        });
    });

    var check = new Checky({
        feed_selection: '.feed-selection'
      , check_feed_id: '.check-feed-id'
      , category_feed_id: '.category-feed-id'
      , click_all: '.click-all'
    });

    check.init();
    check.clickAll();

    $('.status-change > select, .priority-change > select').hide();

    var statusChange = new DropDownChange({status_element: 'span.status-change', status_selector: 'change.status'});
    statusChange.enable();
    var priorityChange = new DropDownChange({status_element: 'span.priority-change', status_selector: 'change.priority'});
    priorityChange.enable();

    $('.check').fancytips();
    $('.fileas').fancytips();
    $('.reply').fancytips();
    $('.feature').fancytips();
    $('.contact').fancytips();
    $('.flag').fancytips();
    $('.remove').fancytips({'top': 45});

    $('a.perm-delete').click(function(e) {
        if(confirm("Are you sure you want to permanently delete this feedback?")) {
            return true;
        }
        e.preventDefault();
    });

    CategoryControl();

    $('a.add-new-ctgy').bind("click", function(e) {
        var ctgy_nm = $("input[name='category_nm']");
        var ctgy_list = $("#ctgy-list");

        if(ctgy_nm.val() == false)
            alert("Category Name cannot be blank.");
        else
            $.ajax({
                url: ctgy_list.attr('hrefaction')
              , type: "POST"
              , data: {ctgy_nm: ctgy_nm.val(), companyId: $("input[name='companyid']").val()}
              , success: function(msg) {
                  ctgy_list.append(msg);
                  ctgy_nm.val("");
                  CategoryControl();
              }
            });

        e.preventDefault();
    })

    function CategoryControl() {
       $('a.rename-ctgy, a.delete-ctgy').unbind('click.ctgy-controls').bind('click.ctgy-controls', function(e) {
           var class_name = $(this).attr('class');
           var that = $(this);

           if(class_name == 'rename-ctgy') {
               var input = $('<input type="text" name="ctgy_nm"/>').val(
                   that.parents('div').siblings('div').children('.ctgy-name').html()
               );

              if(that.text() == "Update") {
                  var ctgy_nm_val = $('input[name="ctgy_nm"]').val()
                  console.log("Rename");
                  that.text("Rename")
                        .parents('div')
                        .siblings('div')
                        .children('.ctgy-name')
                        .html( ctgy_nm_val ).end().end().end()
                  $.ajax({ url: that.attr('href'), type: "POST", data: {ctgy_nm: ctgy_nm_val} });
              } else {
                  that.text("Update")
                        .parents('div')
                        .siblings('div')
                        .children('.ctgy-name')
                        .html( input ).end().end().end()
              }

           }

           if(class_name == 'delete-ctgy') {
              var d = that.parents('div.grids');
              if(confirm("Are you sure you want to delete this category? There is no undo.")) {
                  $.ajax({ url: $(this).attr('href'), success: function(msg) { d.fadeOut(); } });
              }
           }

           e.preventDefault();
       })
    }

    var jcrop_api, set_image;
    function initJcrop() {
        $('#jcrop_target').Jcrop({
            setSelect: ['40','20','190','170']
          , boxWidth: 350
          , boxHeight: 230
          , aspectRatio: 1
          , onChange: showPreview
          , onSelect: showPreview
        }, function() {
            jcrop_api = this;
        });
    }

    function showPreview(coords) {

        var rx = 100 / coords.w;
        var ry = 100 / coords.h;
        var target = $('#jcrop_target');
        var hgt = target.height();
        var wdt = target.width();

        $('#x').val(coords.x);
        $('#y').val(coords.y);
        $('#w').val(coords.w);
        $('#h').val(coords.h);

        $('#preview').css({
            width: Math.round(rx * wdt) + 'px',
            height: Math.round(ry * hgt) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        });
    };

    function save_crop_image(){

        var x_coords = $('#x').val();
        var y_coords = $('#y').val();
        var wd = $('#w').val();
        var ht = $('#h').val();
        var cropped_photo = $('#preview').attr('src');
		var crop_status = $('#crop_status');
		var oldphoto = $('#cropped_photo').val();
        crop_status.html(' Cropping Photo...');

        $.ajax({
            url: $("#ajax-crop-url").attr('hrefaction')
          , method: "POST"
          , data: {src: cropped_photo, x_coords: x_coords, y_coords: y_coords, wd: wd, ht: ht, oldphoto: oldphoto, login_type: 36}
          , success: function(data){
                crop_status.fadeOut('fast',function(){
                    $('#cropped_photo').val(data);
                });

                var myStatus = new Status();
                myStatus.notify("Your photo is successfully cropped! If you feel this is the right photo for you please click on the Save Settings button.", 7000);

            }
        });
    }

    $('div.adjust-crop').hide();
    $(document).delegate("#your_photo", "change", function() {
		$.ajaxFileUpload ({
            url: $("#ajax-upload-url").attr('hrefaction'),
            secureuri:false,
            fileElementId:'your_photo',
            dataType: 'json',
            success: function (data, status) {

                var myStatus = new Status();
                myStatus.notify("Photo Upload Success!", 1000);

                var file = "/" + data.dir;
                var width = Math.round(data.wid);
                var jcrop_div = $("div.jcrop_div");
                var existing_avatar = $('input[name="existing_avatar"]');

                $('div.adjust-crop').show();

                $('#profile_picture').attr('src',file);
                $('#jcrop_target').attr('src',file);
                $('#preview').attr('src',file);

                if(jcrop_api) {
                    jcrop_api.setImage($('#profile_picture').attr('src'));
                    jcrop_api.setSelect(['40','20','190','170']);
                }

                if(existing_avatar.length > 0) {
                    $.post($("#ajax-delete-existing-avatar").attr('hrefaction'), {avatar: existing_avatar.val()});
                }

                jcrop_div.css({'width':width});
                $('input[name="orig_image_dir"]').val(file);
                initJcrop();

            }
		});
    });

    $('#cropbtn').click(function(){
        //save_crop_image();
    });

    $(document).delegate('a.save', 'click', function(e) {
        var textarea = $('.feedback-textarea');
        var hrefaction = textarea.attr('hrefaction');

        var feed_id = $('#feed-id').val();
        $.post(hrefaction, { feed_id: feed_id, feedback_text: textarea.val() }, function(msg) {
            var myStatus = new Status();
            myStatus.notify("Processing...", 1000);
        });
        e.preventDefault();
    });

    $('a.admin-delete').bind('click', function(e) {
        if(confirm("Are you sure you want to delete this user? There is no undo.")) {
            return true;
        }
        e.preventDefault();
    });

    $('.contact-edit').bind('click', function(e) {
        var href = $(this).attr('hrefaction');
        window.location = href;
        e.preventDefault();
    });

    $('.contact-delete').bind('click', function(e) {
        var hrefaction= $(this).attr('hrefaction');
        var that = this;
        if(confirm("Are you sure you want to delete this user? There is no undo.")) {
            $.get(hrefaction, function(msg) {
                $(that).parents('tr').fadeOut(350);
            });
        }
        e.preventDefault();
    });

    $('.copycheck').hide();
    $("#widget-preview").hide();
    new ZClip();
});
<|endoftext|>


<commit_before>var url = window.location.protocol + '//' + window.location.host;

var stackUrl = 'https://api.stackexchange.com';
var version = '/2.2';

var noLoginTemplate = '<button class="btn btn-primary">Log in</button>';
var loginTemplate = '';
var selectorOptionTemplate = '<option value="__VALUE__">__TITLE__</option>';

var accessToken = undefined;
var sites = undefined;

var targetSiteUrl = undefined;

var fromDate = undefined;
var toDate = undefined;

$(document).ready(function(){
	$('#login-container').html(noLoginTemplate);

	datePickerInit();

	SE.init({
		clientId: 6388,
		key: 'LatL0Qaw3)dPKFoK6Y1yiQ((',
		channelUrl: url + '/blank',
		complete: function(data){
			console.log(data);
		}
	});

	$('#login-container button').click(function(event){
		SE.authenticate({
			success: onLoginSuccess,
			error: function(data){
				alert('Something went wrong. Unable to log in');
				console.log(data);
			},
			scope: ['private_info'],
			networkUsers: true
		});
	});

	$('#calculate-button').click(function(event){
		doRepCalculation();
	});

	$('#site-selector-container select').change(function(event){
		var idx = $(this).val();

		if(idx === ''){
			$(this).parent().addClass('has-error');
			$('#site-selector-container .help-block').removeClass('hidden');
			$('#calculate-btn').addClass('disabled');
		} else{
			$(this).parent().removeClass('has-error');
			$('#site-selector-container .help-block').addClass('hidden');

			console.log(idx);
			setTargetSite(idx);
			$('#calculate-button').removeClass('disabled');
		}
	});
});

var datePickerInit = function(){
	var formatString = 'MMMM D, YYYY';
	var start = moment().subtract(6, 'days');
	var end = moment();

	function cb(start, end) {
		fromDate = start.hour(0).minute(0).second(0).utc().unix();
		toDate = end.hour(23).minute(59).second(59).utc().unix();
		console.log(fromDate);
		console.log(toDate);
		$('#date-range-picker span').html(start.format(formatString) + ' - ' + end.format(formatString));
	}

	$('#date-range-picker').daterangepicker({
		startDate: start,
		endDate: end,
		locale: {
			format: formatString
		},
		ranges: {
			'Today': [moment(), moment()],
			'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
			'Last 7 Days': [moment().subtract(6, 'days'), moment()],
			'Last 30 Days': [moment().subtract(29, 'days'), moment()],
			'This Month': [moment().startOf('month'), moment().endOf('month')],
			'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
		}
	}, cb);

	cb(start, end);
}

var onLoginSuccess = function(data){
	console.log(data);
	accessToken = data.accessToken;
	sites = data.networkUsers;

	$('#login-container').html(loginTemplate.replace('__SEID__', sites[0].account_id));

	buildSiteSelector();
}

var buildSiteSelector = function(){
	var options = selectorOptionTemplate.replace('__VALUE__', '').replace('__TITLE__', 'Please choose a site');

	$.each(sites, function(idx, val){
		options += selectorOptionTemplate.replace('__VALUE__', idx)
										 .replace('__TITLE__', val.site_name);
	});

	$('#site-selector-container select').append(options);
	$('#site-selector-container select').prop('disabled', false);
}

var setTargetSite = function(idx){
	if(idx < 0 || idx >= sites.length) {
		alert('Could not select site with index ' + idx);
		return;
	}

	targetSiteUrl = sites[idx].site_url.replace('http://', '');
	targetUserId = sites[idx].user_id;
}

var doRepCalculation = function(){
	var queryString = stackUrl + version + '/me/reputation-history-full/' + $.param({
		site: targetSiteUrl,
		access_token: accessToken,
		fromdate: fromDate,
		toDate: toDate,
	});

	$.ajax(queryString)
	.done(function(data, status, xhr){
		console.log(data);
	})
	.fail(function(xhr, status, err){
		console.log(err);
	});
}<commit_msg>Added API Key to API call<commit_after>var url = window.location.protocol + '//' + window.location.host;

var stackUrl = 'https://api.stackexchange.com';
var version = '/2.2';

var apiKey = 'LatL0Qaw3)dPKFoK6Y1yiQ((';

var noLoginTemplate = '<button class="btn btn-primary">Log in</button>';
var loginTemplate = '';
var selectorOptionTemplate = '<option value="__VALUE__">__TITLE__</option>';

var accessToken = undefined;
var sites = undefined;

var targetSiteUrl = undefined;

var fromDate = undefined;
var toDate = undefined;

$(document).ready(function(){
	$('#login-container').html(noLoginTemplate);

	datePickerInit();

	SE.init({
		clientId: 6388,
		key: apiKey,
		channelUrl: url + '/blank',
		complete: function(data){
			console.log(data);
		}
	});

	$('#login-container button').click(function(event){
		SE.authenticate({
			success: onLoginSuccess,
			error: function(data){
				alert('Something went wrong. Unable to log in');
				console.log(data);
			},
			scope: ['private_info'],
			networkUsers: true
		});
	});

	$('#calculate-button').click(function(event){
		doRepCalculation();
	});

	$('#site-selector-container select').change(function(event){
		var idx = $(this).val();

		if(idx === ''){
			$(this).parent().addClass('has-error');
			$('#site-selector-container .help-block').removeClass('hidden');
			$('#calculate-btn').addClass('disabled');
		} else{
			$(this).parent().removeClass('has-error');
			$('#site-selector-container .help-block').addClass('hidden');

			console.log(idx);
			setTargetSite(idx);
			$('#calculate-button').removeClass('disabled');
		}
	});
});

var datePickerInit = function(){
	var formatString = 'MMMM D, YYYY';
	var start = moment().subtract(6, 'days');
	var end = moment();

	function cb(start, end) {
		fromDate = start.hour(0).minute(0).second(0).utc().unix();
		toDate = end.hour(23).minute(59).second(59).utc().unix();
		console.log(fromDate);
		console.log(toDate);
		$('#date-range-picker span').html(start.format(formatString) + ' - ' + end.format(formatString));
	}

	$('#date-range-picker').daterangepicker({
		startDate: start,
		endDate: end,
		locale: {
			format: formatString
		},
		ranges: {
			'Today': [moment(), moment()],
			'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
			'Last 7 Days': [moment().subtract(6, 'days'), moment()],
			'Last 30 Days': [moment().subtract(29, 'days'), moment()],
			'This Month': [moment().startOf('month'), moment().endOf('month')],
			'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
		}
	}, cb);

	cb(start, end);
}

var onLoginSuccess = function(data){
	console.log(data);
	accessToken = data.accessToken;
	sites = data.networkUsers;

	$('#login-container').html(loginTemplate.replace('__SEID__', sites[0].account_id));

	buildSiteSelector();
}

var buildSiteSelector = function(){
	var options = selectorOptionTemplate.replace('__VALUE__', '').replace('__TITLE__', 'Please choose a site');

	$.each(sites, function(idx, val){
		options += selectorOptionTemplate.replace('__VALUE__', idx)
										 .replace('__TITLE__', val.site_name);
	});

	$('#site-selector-container select').append(options);
	$('#site-selector-container select').prop('disabled', false);
}

var setTargetSite = function(idx){
	if(idx < 0 || idx >= sites.length) {
		alert('Could not select site with index ' + idx);
		return;
	}

	targetSiteUrl = sites[idx].site_url.replace('http://', '');
	targetUserId = sites[idx].user_id;
}

var doRepCalculation = function(){
	var queryString = stackUrl + version + '/me/reputation-history-full?' + $.param({
		key: apiKey,
		site: targetSiteUrl,
		access_token: accessToken,
		fromdate: fromDate,
		toDate: toDate,
	});

	$.ajax(queryString)
	.done(function(data, status, xhr){
		console.log(data);
	})
	.fail(function(xhr, status, err){
		console.log(err);
	});
}<|endoftext|>