<commit_before>// NOTE: uiDepencency=true items will be sent to client for front end config use
// Nothing else sent unless using configuration page/api
// This is to reduce leaking unnecessary information

// NOTE: sensitve=true items will be masked with *** in configuration page

const configItems = [
  {
    interface: 'env',
    key: 'ip',
    cliFlag: 'ip',
    envVar: 'SQLPAD_IP',
    default: '0.0.0.0',
    description:
      'IP address to bind to. By default SQLPad will listen from all available addresses (0.0.0.0).'
  },
  {
    interface: 'env',
    key: 'port',
    cliFlag: 'port',
    envVar: 'SQLPAD_PORT',
    default: 80,
    description: 'Port for SQLPad to listen on.'
  },
  {
    interface: 'env',
    key: 'systemdSocket',
    cliFlag: 'systemd-socket',
    envVar: 'SQLPAD_SYSTEMD_SOCKET',
    default: false,
    description: 'Acquire socket from systemd if available'
  },
  {
    interface: 'env',
    key: 'httpsPort',
    cliFlag: 'https-port',
    envVar: 'SQLPAD_HTTPS_PORT',
    default: 443,
    description: 'Port for SQLPad to listen on.'
  },
  {
    interface: 'env',
    key: 'dbPath',
    cliFlag: ['db', 'dbPath', 'dir'],
    envVar: 'SQLPAD_DB_PATH',
    default: '$HOME/sqlpad/db',
    description:
      'Directory to store SQLPad embedded database content. This includes queries, users, query result cache files, etc.'
  },
  {
    interface: 'env',
    key: 'baseUrl',
    cliFlag: 'base-url',
    envVar: 'SQLPAD_BASE_URL',
    default: '',
    uiDependency: true,
    description:
      "Path to mount sqlpad app following domain. \nFor example, if '/sqlpad' is provided, queries page \nwould be located at mydomain.com/sqlpad/queries instead of mydomain.com/queries. \nUseful when subdomain is not an option."
  },
  {
    interface: 'env',
    key: 'passphrase',
    cliFlag: 'passphrase',
    envVar: 'SQLPAD_PASSPHRASE',
    sensitive: true,
    default: "At least the sensitive bits won't be plain text?",
    description:
      'A string of text used to encrypt sensitive values when stored on disk.'
  },
  {
    interface: 'env',
    key: 'certPassphrase',
    cliFlag: 'cert-passphrase',
    envVar: 'CERT_PASSPHRASE',
    sensitive: true,
    default: 'No cert',
    description: 'Passphrase for your SSL certification file'
  },
  {
    interface: 'env',
    key: 'keyPath',
    cliFlag: ['key', 'key-path', 'key-dir'],
    envVar: 'KEY_PATH',
    default: '',
    description: 'Absolute path to where SSL certificate key is stored'
  },
  {
    interface: 'env',
    key: 'certPath',
    cliFlag: ['cert', 'cert-path', 'cert-dir'],
    envVar: 'CERT_PATH',
    default: '',
    description: 'Absolute path to where SSL certificate is stored'
  },
  {
    interface: 'env',
    key: 'admin',
    cliFlag: 'admin',
    envVar: 'SQLPAD_ADMIN',
    default: '',
    description:
      'Email address to whitelist/give admin permissions to via command line or environment variable. Useful to preset Admin account or to reinstate admin access without access to the UI.'
  },
  {
    interface: 'env',
    key: 'debug',
    cliFlag: 'debug',
    envVar: 'SQLPAD_DEBUG',
    default: false,
    description: 'Add a variety of logging to console while running SQLPad'
  },
  {
    interface: 'env',
    key: 'googleClientId',
    envVar: 'GOOGLE_CLIENT_ID',
    sensitive: true,
    description:
      "Google Client ID used for OAuth setup. Note: authorized redirect URI for sqlpad is '[baseurl]/auth/google/callback'",
    default: ''
  },
  {
    interface: 'env',
    key: 'googleClientSecret',
    envVar: 'GOOGLE_CLIENT_SECRET',
    sensitive: true,
    description:
      "Google Client Secret used for OAuth setup. Note: authorized redirect URI for sqlpad is '[baseurl]/auth/google/callback'",
    default: ''
  },
  {
    interface: 'env',
    key: 'disableUserpassAuth',
    envVar: 'DISABLE_USERPASS_AUTH',
    description:
      'Set to TRUE to disable built-in user authentication. Useful to restrict authentication to OAuth only.',
    default: false
  },
  {
    interface: 'ui',
    key: 'allowCsvDownload',
    label: 'Allow CSV/XLSX Download',
    description: 'Set to false to disable csv or xlsx downloads.',
    options: [true, false],
    uiDependency: true,
    default: true
  },
  {
    interface: 'ui',
    key: 'editorWordWrap',
    label: 'Editor Word Wrap',
    description: 'Set to true to enable word wrapping in SQL editor.',
    options: [true, false],
    uiDependency: true,
    default: false
  },
  {
    interface: 'ui',
    key: 'queryResultMaxRows',
    label: 'Query Result Max Rows',
    description: 'By default query results are limited to 50,000 records.',
    default: 50000,
    uiDependency: true
  },
  {
    interface: 'ui',
    key: 'slackWebhook',
    label: 'Slack Webhook URL',
    description: 'Supply incoming Slack webhook URL to post query when saved.',
    default: ''
  },
  {
    interface: 'ui',
    key: 'showSchemaCopyButton',
    label: 'Show Schema Copy Button',
    description:
      "Enable a button to copy an object's full schema path in schema explorer. Useful for databases that require fully qualified names.",
    options: [true, false],
    default: false,
    uiDependency: true
  },
  {
    interface: 'ui',
    key: 'tableChartLinksRequireAuth',
    label: 'Require Login for Table/Chart Links',
    description:
      'If set to false, table and chart result links will be operational without having to log in. (These links only execute saved SQL queries, and do not open an endpoint to execute raw SQL.)',
    options: [true, false],
    default: true
  },
  {
    interface: 'ui',
    key: 'publicUrl',
    envVar: 'PUBLIC_URL',
    cliFlag: 'public-url',
    label: 'Public Url',
    description:
      'Public URL used for OAuth setup and links in email communications. Protocol is expected to be provided. Example: https://mysqlpad.com',
    default: '',
    uiDependency: true
  },
  {
    interface: 'ui',
    key: 'smtpFrom',
    envVar: 'SQLPAD_SMTP_FROM',
    cliFlag: 'smtp-from',
    label: 'SMTP From',
    description:
      'From email address for SMTP. Required in order to send invitation emails.',
    default: ''
  },
  {
    interface: 'ui',
    key: 'smtpHost',
    envVar: 'SQLPAD_SMTP_HOST',
    cliFlag: 'smtp-host',
    label: 'SMTP Host',
    description:
      'Host address for SMTP. Required in order to send invitation emails.',
    default: ''
  },
  {
    interface: 'ui',
    key: 'smtpPort',
    envVar: 'SQLPAD_SMTP_PORT',
    cliFlag: 'smtp-port',
    label: 'SMTP Port',
    description: 'Port for SMTP. Required in order to send invitation emails.',
    default: ''
  },
  {
    interface: 'ui',
    key: 'smtpSecure',
    envVar: 'SQLPAD_SMTP_SECURE',
    cliFlag: 'smtp-secure',
    label: 'SMTP Use SSL',
    options: [true, false],
    description: 'Toggle to use secure connection when using SMTP.',
    default: true
  },
  {
    interface: 'ui',
    key: 'smtpUser',
    envVar: 'SQLPAD_SMTP_USER',
    cliFlag: 'smtp-user',
    label: 'SMTP User',
    description:
      'Username for SMTP. Required in order to send invitation emails.',
    default: ''
  },
  {
    interface: 'ui',
    key: 'smtpPassword',
    envVar: 'SQLPAD_SMTP_PASSWORD',
    cliFlag: 'smtp-password',
    label: 'SMTP Password',
    description: 'Password for SMTP.',
    default: '',
    sensitive: true
  },
  {
    interface: 'ui',
    key: 'whitelistedDomains',
    label: 'Whitelisted Domains',
    envVar: 'WHITELISTED_DOMAINS',
    cliFlag: 'whitelisted-domains',
    description:
      "Allows whitelisting of email domains so individual email addresses do not need to be whitelisted. Domains must be delimited by whitespace. For example, 'baz.com foo.bar.com' will whitelist sara@baz.com and john@foo.bar.com",
    default: ''
  },
  {
    interface: 'ui',
    key: 'disableUpdateCheck',
    envVar: 'SQLPAD_DISABLE_UPDATE_CHECK',
    cliFlag: 'disable-update-check',
    label: 'Disable update check',
    options: [true, false],
    description:
      'If disabled, SQLPad will no longer poll npmjs.com to see if an update is available.',
    default: false
  }
]

module.exports = configItems
<commit_msg>Remove ability to set publicUrl from UI<commit_after>// NOTE: uiDepencency=true items will be sent to client for front end config use
// Nothing else sent unless using configuration page/api
// This is to reduce leaking unnecessary information

// NOTE: sensitve=true items will be masked with *** in configuration page

const configItems = [
  {
    interface: 'env',
    key: 'ip',
    cliFlag: 'ip',
    envVar: 'SQLPAD_IP',
    default: '0.0.0.0',
    description:
      'IP address to bind to. By default SQLPad will listen from all available addresses (0.0.0.0).'
  },
  {
    interface: 'env',
    key: 'port',
    cliFlag: 'port',
    envVar: 'SQLPAD_PORT',
    default: 80,
    description: 'Port for SQLPad to listen on.'
  },
  {
    interface: 'env',
    key: 'systemdSocket',
    cliFlag: 'systemd-socket',
    envVar: 'SQLPAD_SYSTEMD_SOCKET',
    default: false,
    description: 'Acquire socket from systemd if available'
  },
  {
    interface: 'env',
    key: 'httpsPort',
    cliFlag: 'https-port',
    envVar: 'SQLPAD_HTTPS_PORT',
    default: 443,
    description: 'Port for SQLPad to listen on.'
  },
  {
    interface: 'env',
    key: 'dbPath',
    cliFlag: ['db', 'dbPath', 'dir'],
    envVar: 'SQLPAD_DB_PATH',
    default: '$HOME/sqlpad/db',
    description:
      'Directory to store SQLPad embedded database content. This includes queries, users, query result cache files, etc.'
  },
  {
    interface: 'env',
    key: 'baseUrl',
    cliFlag: 'base-url',
    envVar: 'SQLPAD_BASE_URL',
    default: '',
    uiDependency: true,
    description:
      "Path to mount sqlpad app following domain. \nFor example, if '/sqlpad' is provided, queries page \nwould be located at mydomain.com/sqlpad/queries instead of mydomain.com/queries. \nUseful when subdomain is not an option."
  },
  {
    interface: 'env',
    key: 'passphrase',
    cliFlag: 'passphrase',
    envVar: 'SQLPAD_PASSPHRASE',
    sensitive: true,
    default: "At least the sensitive bits won't be plain text?",
    description:
      'A string of text used to encrypt sensitive values when stored on disk.'
  },
  {
    interface: 'env',
    key: 'certPassphrase',
    cliFlag: 'cert-passphrase',
    envVar: 'CERT_PASSPHRASE',
    sensitive: true,
    default: 'No cert',
    description: 'Passphrase for your SSL certification file'
  },
  {
    interface: 'env',
    key: 'keyPath',
    cliFlag: ['key', 'key-path', 'key-dir'],
    envVar: 'KEY_PATH',
    default: '',
    description: 'Absolute path to where SSL certificate key is stored'
  },
  {
    interface: 'env',
    key: 'certPath',
    cliFlag: ['cert', 'cert-path', 'cert-dir'],
    envVar: 'CERT_PATH',
    default: '',
    description: 'Absolute path to where SSL certificate is stored'
  },
  {
    interface: 'env',
    key: 'admin',
    cliFlag: 'admin',
    envVar: 'SQLPAD_ADMIN',
    default: '',
    description:
      'Email address to whitelist/give admin permissions to via command line or environment variable. Useful to preset Admin account or to reinstate admin access without access to the UI.'
  },
  {
    interface: 'env',
    key: 'debug',
    cliFlag: 'debug',
    envVar: 'SQLPAD_DEBUG',
    default: false,
    description: 'Add a variety of logging to console while running SQLPad'
  },
  {
    interface: 'env',
    key: 'googleClientId',
    envVar: 'GOOGLE_CLIENT_ID',
    sensitive: true,
    description:
      "Google Client ID used for OAuth setup. Note: authorized redirect URI for sqlpad is '[baseurl]/auth/google/callback'",
    default: ''
  },
  {
    interface: 'env',
    key: 'googleClientSecret',
    envVar: 'GOOGLE_CLIENT_SECRET',
    sensitive: true,
    description:
      "Google Client Secret used for OAuth setup. Note: authorized redirect URI for sqlpad is '[baseurl]/auth/google/callback'",
    default: ''
  },
  {
    interface: 'env',
    key: 'publicUrl',
    envVar: 'PUBLIC_URL',
    cliFlag: 'public-url',
    description:
      'Public URL used for OAuth setup and links in email communications. Protocol is expected to be provided. Example: https://mysqlpad.com',
    default: '',
    uiDependency: true
  },
  {
    interface: 'env',
    key: 'disableUserpassAuth',
    envVar: 'DISABLE_USERPASS_AUTH',
    description:
      'Set to TRUE to disable built-in user authentication. Useful to restrict authentication to OAuth only.',
    default: false
  },
  {
    interface: 'ui',
    key: 'allowCsvDownload',
    label: 'Allow CSV/XLSX Download',
    description: 'Set to false to disable csv or xlsx downloads.',
    options: [true, false],
    uiDependency: true,
    default: true
  },
  {
    interface: 'ui',
    key: 'editorWordWrap',
    label: 'Editor Word Wrap',
    description: 'Set to true to enable word wrapping in SQL editor.',
    options: [true, false],
    uiDependency: true,
    default: false
  },
  {
    interface: 'ui',
    key: 'queryResultMaxRows',
    label: 'Query Result Max Rows',
    description: 'By default query results are limited to 50,000 records.',
    default: 50000,
    uiDependency: true
  },
  {
    interface: 'ui',
    key: 'slackWebhook',
    label: 'Slack Webhook URL',
    description: 'Supply incoming Slack webhook URL to post query when saved.',
    default: ''
  },
  {
    interface: 'ui',
    key: 'showSchemaCopyButton',
    label: 'Show Schema Copy Button',
    description:
      "Enable a button to copy an object's full schema path in schema explorer. Useful for databases that require fully qualified names.",
    options: [true, false],
    default: false,
    uiDependency: true
  },
  {
    interface: 'ui',
    key: 'tableChartLinksRequireAuth',
    label: 'Require Login for Table/Chart Links',
    description:
      'If set to false, table and chart result links will be operational without having to log in. (These links only execute saved SQL queries, and do not open an endpoint to execute raw SQL.)',
    options: [true, false],
    default: true
  },
  {
    interface: 'ui',
    key: 'smtpFrom',
    envVar: 'SQLPAD_SMTP_FROM',
    cliFlag: 'smtp-from',
    label: 'SMTP From',
    description:
      'From email address for SMTP. Required in order to send invitation emails.',
    default: ''
  },
  {
    interface: 'ui',
    key: 'smtpHost',
    envVar: 'SQLPAD_SMTP_HOST',
    cliFlag: 'smtp-host',
    label: 'SMTP Host',
    description:
      'Host address for SMTP. Required in order to send invitation emails.',
    default: ''
  },
  {
    interface: 'ui',
    key: 'smtpPort',
    envVar: 'SQLPAD_SMTP_PORT',
    cliFlag: 'smtp-port',
    label: 'SMTP Port',
    description: 'Port for SMTP. Required in order to send invitation emails.',
    default: ''
  },
  {
    interface: 'ui',
    key: 'smtpSecure',
    envVar: 'SQLPAD_SMTP_SECURE',
    cliFlag: 'smtp-secure',
    label: 'SMTP Use SSL',
    options: [true, false],
    description: 'Toggle to use secure connection when using SMTP.',
    default: true
  },
  {
    interface: 'ui',
    key: 'smtpUser',
    envVar: 'SQLPAD_SMTP_USER',
    cliFlag: 'smtp-user',
    label: 'SMTP User',
    description:
      'Username for SMTP. Required in order to send invitation emails.',
    default: ''
  },
  {
    interface: 'ui',
    key: 'smtpPassword',
    envVar: 'SQLPAD_SMTP_PASSWORD',
    cliFlag: 'smtp-password',
    label: 'SMTP Password',
    description: 'Password for SMTP.',
    default: '',
    sensitive: true
  },
  {
    interface: 'ui',
    key: 'whitelistedDomains',
    label: 'Whitelisted Domains',
    envVar: 'WHITELISTED_DOMAINS',
    cliFlag: 'whitelisted-domains',
    description:
      "Allows whitelisting of email domains so individual email addresses do not need to be whitelisted. Domains must be delimited by whitespace. For example, 'baz.com foo.bar.com' will whitelist sara@baz.com and john@foo.bar.com",
    default: ''
  },
  {
    interface: 'ui',
    key: 'disableUpdateCheck',
    envVar: 'SQLPAD_DISABLE_UPDATE_CHECK',
    cliFlag: 'disable-update-check',
    label: 'Disable update check',
    options: [true, false],
    description:
      'If disabled, SQLPad will no longer poll npmjs.com to see if an update is available.',
    default: false
  }
]

module.exports = configItems
<|endoftext|>


<commit_before>var gulp = require("gulp");
var coffee = require("gulp-coffee");
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");
var connect = require("gulp-connect");
var less = require("gulp-less");
var coffeelint = require("gulp-coffeelint");
var recess = require("gulp-recess");
var jshint = require("gulp-jshint");
var karma = require("gulp-karma");
var gutil = require("gulp-util");
var template = require("gulp-template");

var externalSources = [
    "app/components/jquery/dist/jquery.js",
    "app/components/jquery-ui/ui/jquery-ui.js",
    "app/components/markitup/markitup/jquery.markitup.js",
    "app/components/marked/lib/marked.js",
    "app/components/lodash/dist/lodash.js",
    "app/components/lazy.js/lazy.js",
    "app/components/emoticons/lib/emoticons.js",
    "app/components/underscore.string/lib/underscore.string.js",
    "app/components/angular/angular.js",
    "app/components/angular-route/angular-route.js",
    "app/components/angular-sanitize/angular-sanitize.js",
    "app/components/angular-animate/angular-animate.js",
    "app/js/bootstrap.js",
    "app/components/moment/moment.js",
    "app/components/kalendae/build/kalendae.js",
    "app/components/checksley/checksley.js",
    "app/js/sha1.js",
    "app/components/jquery-flot/jquery.flot.js",
    "app/components/jquery-flot/jquery.flot.pie.js",
    "app/components/jquery-flot/jquery.flot.time.js",
    "app/components/flot-orderBars/js/jquery.flot.orderBars.js",
    "app/js/curvedLines.js",
    "app/js/emoticons-define.js",
    "app/components/select2/select2.js",
    "app/components/i18next/i18next.js",
    "app/js/coffeeColorPicker.js",
    "app/js/coffeeColorPicker.angular.js",
    "app/components/google-diff-match-patch-js/diff_match_patch_uncompressed.js",
    "app/components/jqueryui-touch-punch/jquery.ui.touch-punch.js",
    "app/js/highlight.pack.js",
    "app/components/jquery-textcomplete/jquery.textcomplete.js",
    "app/components/isMobile/isMobile.js",
    "app/components/favico.js/favico.js"
];

var coffeeSources = [
    "app/coffee/*.coffee",
    "app/coffee/**/*.coffee"
];

// define tasks here
gulp.task("default", ["dev", "watch", "connect"]);

gulp.task("dev", ["coffee", "less", "libs", "template"]);

gulp.task("pro", ["less", "template"], function() {
    gulp.src(coffeeSources)
        .pipe(coffee().on("error", gutil.log))
        .pipe(concat("app.js"))
        .pipe(uglify())
        .pipe(gulp.dest("app/dist/"));
    gulp.src(externalSources)
        .pipe(concat("libs.js"))
        .pipe(uglify())
        .pipe(gulp.dest("app/dist/"));
});

gulp.task("coffee", function() {
    gulp.src(coffeeSources)
        .pipe(coffee().on("error", gutil.log))
        .pipe(concat("app.js"))
        .pipe(gulp.dest("app/dist/"));
});

gulp.task("hint", function() {
    gulp.src(coffeeSources)
        .pipe(coffee().on("error", gutil.log))
        .pipe(jshint())
        .pipe(jshint.reporter("default"))
});

gulp.task("less", function() {
    gulp.src("app/less/taiga-main.less")
        .pipe(less().on("error", gutil.log))
        .pipe(concat("style.css"))
        .pipe(gulp.dest("app/less"));
});

gulp.task("libs", function() {
    gulp.src(externalSources)
        .pipe(concat("libs.js"))
        .pipe(gulp.dest("app/dist/"));
});

gulp.task("lint", function() {
    gulp.src(coffeeSources)
        .pipe(coffeelint("coffeelint.json"))
        .pipe(coffeelint.reporter())
    gulp.src("app/less/taiga-main.less")
        .pipe(recess({strictPropertyOrder: false}))
});

gulp.task("template", function() {
    gulp.src("app/index.template.html")
        .pipe(template({stamp: (new Date()).getTime()}))
        .pipe(concat("index.html"))
        .pipe(gulp.dest("app"));
});

gulp.task("build-tests", function() {
    gulp.src(["test/**/*.coffee"])
        .pipe(coffee({"bare": true}).on("error", gutil.log))
        .pipe(concat("tests.js"))
        .pipe(gulp.dest("test"));
});

gulp.task("test", ["coffee", "libs", "build-tests"], function() {
    gulp.src(["app/dist/libs.js", "app/dist/app.js", "test/tests.js"])
        .pipe(karma({configFile: "karma.conf.coffee", action: "run"}));
});

gulp.task("watch", function () {
    gulp.watch(["app/less/*.less", "app/less/**/*.less"], ["less"]);
    gulp.watch(externalSources, ["libs"]);
    gulp.watch(["app/coffee/*.coffee", "app/coffee/**/*.coffee"], ["coffee"]);
});

gulp.task("connect", connect.server({
    root: "app",
    port: 9001,
    livereload: false,
}));
<commit_msg>Fixed color picker (reincluding it on gulp)<commit_after>var gulp = require("gulp");
var coffee = require("gulp-coffee");
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");
var connect = require("gulp-connect");
var less = require("gulp-less");
var coffeelint = require("gulp-coffeelint");
var recess = require("gulp-recess");
var jshint = require("gulp-jshint");
var karma = require("gulp-karma");
var gutil = require("gulp-util");
var template = require("gulp-template");

var externalSources = [
    "app/components/jquery/dist/jquery.js",
    "app/components/jquery-ui/ui/jquery-ui.js",
    "app/components/markitup/markitup/jquery.markitup.js",
    "app/components/marked/lib/marked.js",
    "app/components/lodash/dist/lodash.js",
    "app/components/lazy.js/lazy.js",
    "app/components/emoticons/lib/emoticons.js",
    "app/components/underscore.string/lib/underscore.string.js",
    "app/components/angular/angular.js",
    "app/components/angular-route/angular-route.js",
    "app/components/angular-sanitize/angular-sanitize.js",
    "app/components/angular-animate/angular-animate.js",
    "app/js/bootstrap.js",
    "app/components/moment/moment.js",
    "app/components/kalendae/build/kalendae.js",
    "app/components/checksley/checksley.js",
    "app/js/sha1.js",
    "app/components/jquery-flot/jquery.flot.js",
    "app/components/jquery-flot/jquery.flot.pie.js",
    "app/components/jquery-flot/jquery.flot.time.js",
    "app/components/flot-orderBars/js/jquery.flot.orderBars.js",
    "app/js/curvedLines.js",
    "app/js/emoticons-define.js",
    "app/components/select2/select2.js",
    "app/components/i18next/i18next.js",
    "app/js/jquery.color.js",
    "app/js/coffeeColorPicker.js",
    "app/js/coffeeColorPicker.angular.js",
    "app/components/google-diff-match-patch-js/diff_match_patch_uncompressed.js",
    "app/components/jqueryui-touch-punch/jquery.ui.touch-punch.js",
    "app/js/highlight.pack.js",
    "app/components/jquery-textcomplete/jquery.textcomplete.js",
    "app/components/isMobile/isMobile.js",
    "app/components/favico.js/favico.js"
];

var coffeeSources = [
    "app/coffee/*.coffee",
    "app/coffee/**/*.coffee"
];

// define tasks here
gulp.task("default", ["dev", "watch", "connect"]);

gulp.task("dev", ["coffee", "less", "libs", "template"]);

gulp.task("pro", ["less", "template"], function() {
    gulp.src(coffeeSources)
        .pipe(coffee().on("error", gutil.log))
        .pipe(concat("app.js"))
        .pipe(uglify())
        .pipe(gulp.dest("app/dist/"));
    gulp.src(externalSources)
        .pipe(concat("libs.js"))
        .pipe(uglify())
        .pipe(gulp.dest("app/dist/"));
});

gulp.task("coffee", function() {
    gulp.src(coffeeSources)
        .pipe(coffee().on("error", gutil.log))
        .pipe(concat("app.js"))
        .pipe(gulp.dest("app/dist/"));
});

gulp.task("hint", function() {
    gulp.src(coffeeSources)
        .pipe(coffee().on("error", gutil.log))
        .pipe(jshint())
        .pipe(jshint.reporter("default"))
});

gulp.task("less", function() {
    gulp.src("app/less/taiga-main.less")
        .pipe(less().on("error", gutil.log))
        .pipe(concat("style.css"))
        .pipe(gulp.dest("app/less"));
});

gulp.task("libs", function() {
    gulp.src(externalSources)
        .pipe(concat("libs.js"))
        .pipe(gulp.dest("app/dist/"));
});

gulp.task("lint", function() {
    gulp.src(coffeeSources)
        .pipe(coffeelint("coffeelint.json"))
        .pipe(coffeelint.reporter())
    gulp.src("app/less/taiga-main.less")
        .pipe(recess({strictPropertyOrder: false}))
});

gulp.task("template", function() {
    gulp.src("app/index.template.html")
        .pipe(template({stamp: (new Date()).getTime()}))
        .pipe(concat("index.html"))
        .pipe(gulp.dest("app"));
});

gulp.task("build-tests", function() {
    gulp.src(["test/**/*.coffee"])
        .pipe(coffee({"bare": true}).on("error", gutil.log))
        .pipe(concat("tests.js"))
        .pipe(gulp.dest("test"));
});

gulp.task("test", ["coffee", "libs", "build-tests"], function() {
    gulp.src(["app/dist/libs.js", "app/dist/app.js", "test/tests.js"])
        .pipe(karma({configFile: "karma.conf.coffee", action: "run"}));
});

gulp.task("watch", function () {
    gulp.watch(["app/less/*.less", "app/less/**/*.less"], ["less"]);
    gulp.watch(externalSources, ["libs"]);
    gulp.watch(["app/coffee/*.coffee", "app/coffee/**/*.coffee"], ["coffee"]);
});

gulp.task("connect", connect.server({
    root: "app",
    port: 9001,
    livereload: false,
}));
<|endoftext|>


<commit_before>$(document).ready(function(){

    $('#backBtn').click(backToCourseInput);
    $('#finishBtn').click(backToIndex);
    $('#submitBtn').click(submitAssignmentForm);

    var next = 1;
    $(".add-more").click(function(e){
        e.preventDefault();
        // the div element selectors
        var addto = "#field" + next;
        var addRemove = "#field" + (next);

        next = next + 1;
        $("#numFields").attr("value", next);
        //console.log("just added, " + next);

        var newIn = '

' +
                        '
' +
                            '
' +
                                '<input autocomplete="off" placeholder="Ex: Homework" class="form-control col-xs-4 col-md-4" name="type' + next + '" type="text" autofocus>
' +
                            '
' +
                                '<input autocomplete="off" placeholder="Ex: 25" class="form-control col-xs-4 col-md-4" name="weighting' + next + '" type="text">

' +
                    '
';
        var newInput = $(newIn);

        var removeBtn = '

<button class="btn btn-danger remove-me" ></button>

';
        var removeButton = $(removeBtn);

        $(addto).after(newInput);
        $(addRemove).after(removeButton);
        $("#field" + next).attr('data-source',$(addto).attr('data-source'));
        $("#count").val(next);

        $('.remove-me').click(function(e){
            //alert('clicked!');
            e.preventDefault();
            var $divToRemove = $(this).closest('div'); //.find(".disabled");
            var fieldNum = ($divToRemove).attr('id').charAt(($divToRemove).attr('id').length-1);
            var fieldID = "#field" + fieldNum;
            ($divToRemove).remove();
            $(fieldID).remove();
            //next = next-1;
            //$("#numFields").attr("value", next--);
            //console.log('just deleted, ' + next);
        });
    });
});

function submitAssignmentForm(e) {
    e.preventDefault();
    // get all the values of all the inputs.
    var $allInputs = $('div#field input.form-control');
    console.log($allInputs.length);
    console.log($allInputs[0]);
    var data = {};

    for(var i=0; i<$allInputs.length; i++) {
        var name = $($allInputs[i]).attr('name');
        var val = $($allInputs[i]).val();
        data[name] = val;
    }

    console.log(data);

    $.post('/editCourseAJAX',data,callback);
}

function callback(results) {
    console.log('i made it back!');
    console.log(results);
    var department = results.department;
    var number = results.number;
    var syllabus = results.syllabus;
    var fields = "";
    for(var key in syllabus) {
        fields += key + ", ";
    }
    $("#successMessageDiv").text("Added the following fields to your " + department + " " + number + " syllabus: " + fields.substr(0,fields.length-2));
    // now display everything. so on the server side you want to make sure you remove all duplicates
    // so basically 'results' should only be what the server doesn't already contain
    // like you should change everything that isn't already the same as what's on the servers.
}

function backToCourseInput(e) {
    e.preventDefault();
    window.location.href = "javascript:history.back();";
}

function backToIndex(e) {
    e.preventDefault();
    window.location.href = "/index";
}
/*function addAssignmentTypesToSyllabus(e) {
    e.preventDefault();

    $.post("/editCourse",callBack);
}

function callBack(result) {
    alert("what am i doing");
}*/
<commit_msg>fixed success message<commit_after>$(document).ready(function(){

    $('#backBtn').click(backToCourseInput);
    $('#finishBtn').click(backToIndex);
    $('#submitBtn').click(submitAssignmentForm);

    var next = 1;
    $(".add-more").click(function(e){
        e.preventDefault();
        // the div element selectors
        var addto = "#field" + next;
        var addRemove = "#field" + (next);

        next = next + 1;
        $("#numFields").attr("value", next);
        //console.log("just added, " + next);

        var newIn = '

' +
                        '
' +
                            '
' +
                                '<input autocomplete="off" placeholder="Ex: Homework" class="form-control col-xs-4 col-md-4" name="type' + next + '" type="text" autofocus>
' +
                            '
' +
                                '<input autocomplete="off" placeholder="Ex: 25" class="form-control col-xs-4 col-md-4" name="weighting' + next + '" type="text">

' +
                    '
';
        var newInput = $(newIn);

        var removeBtn = '

<button class="btn btn-danger remove-me" ></button>

';
        var removeButton = $(removeBtn);

        $(addto).after(newInput);
        $(addRemove).after(removeButton);
        $("#field" + next).attr('data-source',$(addto).attr('data-source'));
        $("#count").val(next);

        $('.remove-me').click(function(e){
            //alert('clicked!');
            e.preventDefault();
            var $divToRemove = $(this).closest('div'); //.find(".disabled");
            var fieldNum = ($divToRemove).attr('id').charAt(($divToRemove).attr('id').length-1);
            var fieldID = "#field" + fieldNum;
            ($divToRemove).remove();
            $(fieldID).remove();
            //next = next-1;
            //$("#numFields").attr("value", next--);
            //console.log('just deleted, ' + next);
        });
    });
});

function submitAssignmentForm(e) {
    e.preventDefault();
    // get all the values of all the inputs.
    var $allInputs = $('div#field input.form-control');
    console.log($allInputs.length);
    console.log($allInputs[0]);
    var data = {};

    for(var i=0; i<$allInputs.length; i++) {
        var name = $($allInputs[i]).attr('name');
        var val = $($allInputs[i]).val();
        data[name] = val;
    }

    console.log(data);

    $.post('/editCourseAJAX',data,callback);
}

function callback(results) {
    console.log('i made it back!');

    $("#successMessageDiv").text("Success!");
    // now display everything. so on the server side you want to make sure you remove all duplicates
    // so basically 'results' should only be what the server doesn't already contain
    // like you should change everything that isn't already the same as what's on the servers.
}

function backToCourseInput(e) {
    e.preventDefault();
    window.location.href = "javascript:history.back();";
}

function backToIndex(e) {
    e.preventDefault();
    window.location.href = "/index";
}
/*function addAssignmentTypesToSyllabus(e) {
    e.preventDefault();

    $.post("/editCourse",callBack);
}

function callBack(result) {
    alert("what am i doing");
}*/
<|endoftext|>


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

  // --------------------------------------------------- variable initialisation
  /*
   * HACK: we are passing a parameter to this scripts through a data-* balise.
   * more here: http://stackoverflow.com/a/32589923/6320039
   */
  var isExam = 'exam' == document.currentScript.getAttribute('data-id');

  var id = 0;

  // JQuery quick access to important nodes
  var $domain       = $('#domain');
  var $question     = $('#question');
  var $answers      = $('#answers');
  var $nextQuestion = $('#next-question');
  var $dashboard    = $('#dashboard');

  if (isExam) var counter = 0;

  // ---------------------------------------------------- main logic (functions)
  /**
   * Change DOM elements relative to a question :
   *  - question
   *  - domain
   *  - answers
   *
   * The question is randomly retrieved from the database. If the global
   * parameter isExam is set, then the question can be only in domains
   * contained in sessionStorage.domains; and it also increment the counter.
   * If the counter is greater than sessionStorage.numberOfQuestions, then exam
   * is over and window is redirected to /result.
   * @return undefined
   */
  function changeQuestion() {
    var url;
    if (isExam) {
      if (++counter == sessionStorage.numberOfQuestions)
        $nextQuestion.find('span').html('Fin de l’examen');
      else if (counter > sessionStorage.numberOfQuestions) {
        window.location = '/result';
        return;
      }
      url = "/api/ask/rand/" + sessionStorage.domains;
    } else {
      url = "/api/ask/rand/";
    }
    $.get(url)
      .done(function(data) {
        id = data.id;
        $domain.html(data.domain);
        $question.html(data.question);
        // clean everything except first answer (bones)
        $answers.find('.answer:not(:first)').remove()
        for (var answer of data.answers) {
          $answers
            // clone body of an answer
            .find('.answer:first')
            .clone()
            // append current answer elements to the clone
            .find('input')
              .attr('name', answer)
            .end()
            .find('label')
              .attr('for', answer)
              .html(answer)
            .end()
            // append the clone to DOM (#answer)
            .appendTo($answers)
            // show the clone
            .show();
        }

        dragndrop();
      })
      .fail(function (data) {
        console.log(data);
      });

    }

    function dragndrop(){
      var draggable = document.querySelectorAll(".answer");
      var droptarget = document.getElementById("droptarget");
      //draggable[0].classList.remove("right");

      droptarget.innerHTML = "Glisser la réponse !"
      droptarget.classList.remove("false");
      droptarget.classList.remove("right");
      droptarget.classList.add("free");

      for(var i = 1; i < draggable.length; i++){
        (function(i){
          draggable[i].classList.add("draggable");
          draggable[i].setAttribute("draggable", "true");
          draggable[i].addEventListener('dragstart', dragStart, false);  //the user starts dragging the element
          draggable[i].addEventListener('dragend'  , dragEnd  , false);
        })(i)
      }

      droptarget.addEventListener('dragenter', dragEnter  , false); //fired when the user drags the draggable onto the drop target (only fires when the draggable element changes from being outside to being over)
      droptarget.addEventListener('dragover' , dragOver   , false); //Fired once the draggable element is over the drop target and keeps firing for as long as the draggable element is being dragged over the drop target.
      droptarget.addEventListener('dragleave', dragLeave  , false); //If the user drags the draggable object out of the drop target again, the dragleave event is fired.
      droptarget.addEventListener('drop'     , drop       , false); //If the user drops the draggable object on the drop target, the drop event is fired.

      /* Draggable event handlers */
      function dragStart(event) {
          var dataToSet = event.target.getElementsByTagName('label')[0].getAttribute('for');
          event.dataTransfer.setData("text", dataToSet); //data that is transfered to the drop target when the element is dropped. (MIME, data)
          event.dataTransfer.effectsAllowed = "copy";

          for(var i = 1; i < draggable.length; i++){
            (function(i){
              if(document.getElementsByTagName('label')[i].getAttribute('for') == event.target.getElementsByTagName('label')[0].getAttribute('for')){
                draggable[i].classList.add("dragged");
              }
            })(i)
          }
      }

      function dragEnd(event) {
        for(var i = 1; i < draggable.length; i++){
          (function(i){
            if(document.getElementsByTagName('label')[i].getAttribute('for') == event.target.getElementsByTagName('label')[0].getAttribute('for')){
              draggable[i].classList.remove("dragged");
            }
          })(i)
        }
      }

      /* Drop target event handlers */
      function dragEnter(event) {
        droptarget.classList.remove("free");
        droptarget.classList.add("enter");
      }

      function dragOver(event) {

          event.preventDefault();
          return false; //Necessary to avoid default browsers behaviours
      }

      function dragLeave(event) {
        droptarget.classList.remove("enter");
        droptarget.classList.add("free");
      }

      function drop(event) {
          var data = event.dataTransfer.getData('text'); //reads the data set in dragStart()
          var url = "/api/ans/" + id + "/";
          var isGoodAnswer = 0;
          var indexAnswer = 0;
          var choice = 0;

          droptarget.classList.remove("enter");

          for(var i = 1; i < draggable.length; i++){
            (function(i){
              if(document.getElementsByTagName('label')[i].getAttribute('for') == data){
                url += i-1;
                choice = draggable[i];
                choice.classList.add("hidden");
                event.target.innerHTML = data;
              }
            })(i)
          }

          console.log(url);

          $.get(url)
            .done(function(data) {
              isGoodAnswer = data.isGoodAnswer;
              indexAnswer = data.goodAnswerIndex;
              if(isGoodAnswer){
                droptarget.classList.add("right");
                //We indicate that the choosen answer is the good one
              }else{
                droptarget.classList.add("false");
                draggable[indexAnswer+1].classList.add("right");
                //We indicate that the the choosen answer is not the good one and we show the good one
              }

              //When an element is dropped, we need to remove draggable class and attribute on other items in order to avoid multiple d&d
              for(var j = 1; j < draggable.length; j++ ){
                if(draggable[j] != undefined){
                  (function(j){
                    draggable[j].removeEventListener("dragstart", dragStart);
                    draggable[j].removeEventListener("dragend", dragEnd);
                    draggable[j].setAttribute("draggable", "false");
                    draggable[j].classList.remove("draggable");
                  })(j)
                }
              }

              droptarget.removeEventListener("dragenter", dragEnter);
              droptarget.removeEventListener("dragover", dragOver);
              droptarget.removeEventListener("dragleave", dragLeave);
              droptarget.removeEventListener("drop", drop);

            });

            event.preventDefault();
            return false; //Necessary to avoid default browsers behaviours
      }
    }

    // ------------------------------------------------------------- DOM binding
    $(document).ready(changeQuestion);
    $nextQuestion.click(changeQuestion);
})();
<commit_msg>T'es mauvais jack, t'as oublié un console.log !<commit_after>(function () {
  'use strict';

  // --------------------------------------------------- variable initialisation
  /*
   * HACK: we are passing a parameter to this scripts through a data-* balise.
   * more here: http://stackoverflow.com/a/32589923/6320039
   */
  var isExam = 'exam' == document.currentScript.getAttribute('data-id');

  var id = 0;

  // JQuery quick access to important nodes
  var $domain       = $('#domain');
  var $question     = $('#question');
  var $answers      = $('#answers');
  var $nextQuestion = $('#next-question');
  var $dashboard    = $('#dashboard');

  if (isExam) var counter = 0;

  // ---------------------------------------------------- main logic (functions)
  /**
   * Change DOM elements relative to a question :
   *  - question
   *  - domain
   *  - answers
   *
   * The question is randomly retrieved from the database. If the global
   * parameter isExam is set, then the question can be only in domains
   * contained in sessionStorage.domains; and it also increment the counter.
   * If the counter is greater than sessionStorage.numberOfQuestions, then exam
   * is over and window is redirected to /result.
   * @return undefined
   */
  function changeQuestion() {
    var url;
    if (isExam) {
      if (++counter == sessionStorage.numberOfQuestions)
        $nextQuestion.find('span').html('Fin de l’examen');
      else if (counter > sessionStorage.numberOfQuestions) {
        window.location = '/result';
        return;
      }
      url = "/api/ask/rand/" + sessionStorage.domains;
    } else {
      url = "/api/ask/rand/";
    }
    $.get(url)
      .done(function(data) {
        id = data.id;
        $domain.html(data.domain);
        $question.html(data.question);
        // clean everything except first answer (bones)
        $answers.find('.answer:not(:first)').remove()
        for (var answer of data.answers) {
          $answers
            // clone body of an answer
            .find('.answer:first')
            .clone()
            // append current answer elements to the clone
            .find('input')
              .attr('name', answer)
            .end()
            .find('label')
              .attr('for', answer)
              .html(answer)
            .end()
            // append the clone to DOM (#answer)
            .appendTo($answers)
            // show the clone
            .show();
        }

        dragndrop();
      })
      .fail(function (data) {
        console.log(data);
      });

    }

    function dragndrop(){
      var draggable = document.querySelectorAll(".answer");
      var droptarget = document.getElementById("droptarget");
      //draggable[0].classList.remove("right");

      droptarget.innerHTML = "Glisser la réponse !"
      droptarget.classList.remove("false");
      droptarget.classList.remove("right");
      droptarget.classList.add("free");

      for(var i = 1; i < draggable.length; i++){
        (function(i){
          draggable[i].classList.add("draggable");
          draggable[i].setAttribute("draggable", "true");
          draggable[i].addEventListener('dragstart', dragStart, false);  //the user starts dragging the element
          draggable[i].addEventListener('dragend'  , dragEnd  , false);
        })(i)
      }

      droptarget.addEventListener('dragenter', dragEnter  , false); //fired when the user drags the draggable onto the drop target (only fires when the draggable element changes from being outside to being over)
      droptarget.addEventListener('dragover' , dragOver   , false); //Fired once the draggable element is over the drop target and keeps firing for as long as the draggable element is being dragged over the drop target.
      droptarget.addEventListener('dragleave', dragLeave  , false); //If the user drags the draggable object out of the drop target again, the dragleave event is fired.
      droptarget.addEventListener('drop'     , drop       , false); //If the user drops the draggable object on the drop target, the drop event is fired.

      /* Draggable event handlers */
      function dragStart(event) {
          var dataToSet = event.target.getElementsByTagName('label')[0].getAttribute('for');
          event.dataTransfer.setData("text", dataToSet); //data that is transfered to the drop target when the element is dropped. (MIME, data)
          event.dataTransfer.effectsAllowed = "copy";

          for(var i = 1; i < draggable.length; i++){
            (function(i){
              if(document.getElementsByTagName('label')[i].getAttribute('for') == event.target.getElementsByTagName('label')[0].getAttribute('for')){
                draggable[i].classList.add("dragged");
              }
            })(i)
          }
      }

      function dragEnd(event) {
        for(var i = 1; i < draggable.length; i++){
          (function(i){
            if(document.getElementsByTagName('label')[i].getAttribute('for') == event.target.getElementsByTagName('label')[0].getAttribute('for')){
              draggable[i].classList.remove("dragged");
            }
          })(i)
        }
      }

      /* Drop target event handlers */
      function dragEnter(event) {
        droptarget.classList.remove("free");
        droptarget.classList.add("enter");
      }

      function dragOver(event) {

          event.preventDefault();
          return false; //Necessary to avoid default browsers behaviours
      }

      function dragLeave(event) {
        droptarget.classList.remove("enter");
        droptarget.classList.add("free");
      }

      function drop(event) {
          var data = event.dataTransfer.getData('text'); //reads the data set in dragStart()
          var url = "/api/ans/" + id + "/";
          var isGoodAnswer = 0;
          var indexAnswer = 0;
          var choice = 0;

          droptarget.classList.remove("enter");

          for(var i = 1; i < draggable.length; i++){
            (function(i){
              if(document.getElementsByTagName('label')[i].getAttribute('for') == data){
                url += i-1;
                choice = draggable[i];
                choice.classList.add("hidden");
                event.target.innerHTML = data;
              }
            })(i)
          }

          $.get(url)
            .done(function(data) {
              isGoodAnswer = data.isGoodAnswer;
              indexAnswer = data.goodAnswerIndex;
              if(isGoodAnswer){
                droptarget.classList.add("right");
                //We indicate that the choosen answer is the good one
              }else{
                droptarget.classList.add("false");
                draggable[indexAnswer+1].classList.add("right");
                //We indicate that the the choosen answer is not the good one and we show the good one
              }

              //When an element is dropped, we need to remove draggable class and attribute on other items in order to avoid multiple d&d
              for(var j = 1; j < draggable.length; j++ ){
                if(draggable[j] != undefined){
                  (function(j){
                    draggable[j].removeEventListener("dragstart", dragStart);
                    draggable[j].removeEventListener("dragend", dragEnd);
                    draggable[j].setAttribute("draggable", "false");
                    draggable[j].classList.remove("draggable");
                  })(j)
                }
              }

              droptarget.removeEventListener("dragenter", dragEnter);
              droptarget.removeEventListener("dragover", dragOver);
              droptarget.removeEventListener("dragleave", dragLeave);
              droptarget.removeEventListener("drop", drop);

            });

            event.preventDefault();
            return false; //Necessary to avoid default browsers behaviours
      }
    }

    // ------------------------------------------------------------- DOM binding
    $(document).ready(changeQuestion);
    $nextQuestion.click(changeQuestion);
})();
<|endoftext|>


<commit_before>'use strict';

var LAMBDA_WORKER_FUNCTION_NAME = process.env.LAMBDA_FUNCTION;

var validate = require('../validate.js')
  , parseJson = require('../parse-json.js')
  , lambda = require('../lambda.js');

var errorHandlers = require('./errors.js');

var forwardMessageToLambdaWorker = function(req, res, body) {
  var sqsMessage = parseJson(body, function(err) {
    return body; // use raw body
  });
  console.log('body', body);
  var lambdaEvent = lambda.createLambdaEventFromSqsMessage(req, sqsMessage);
  lambda.trigger(LAMBDA_WORKER_FUNCTION_NAME, lambdaEvent, function(err, data) {
    if (err) {
      // local, app error
      errorHandlers.generic(req, res, 500, err.message);
      return;
    }
    else if (data instanceof Error) {
      // remote lamba had error; "bad gateway"
      errorHandlers.generic(req, res, 502, data.message);
      return;
    }
    else {
      // yay?
      if (data.Action) {
        switch (data.Action) {
          case 'DELETE':
            // yay! tells EB worker sqsd that message was processed and it issues a DeleteMessage
            res.writeHead(200);
            res.end();
            return;
          default:
            // nothing else is supported
            errorHandlers.generic(req, res, 501, 'Invalid response Action: ' + data.Action);
            return;
        }
      }
      else {
        errorHandlers.generic(req, res, 502, 'Lambda Worker Response Formatted Incorrectly');
        return;
      }
    }
  });
};

module.exports = function(req, res) {
  var body = '';
  if (!validate.isContentTypeJson(req.headers['content-type'])) {
    errorHandlers.notAcceptable(req, res);
    return;
  }
  req.on('data', function(chunk) {
    body += chunk;
  });
  req.on('end', function() {
    forwardMessageToLambdaWorker(req, res, body);
  });
};
<commit_msg>remove log<commit_after>'use strict';

var LAMBDA_WORKER_FUNCTION_NAME = process.env.LAMBDA_FUNCTION;

var validate = require('../validate.js')
  , parseJson = require('../parse-json.js')
  , lambda = require('../lambda.js');

var errorHandlers = require('./errors.js');

var forwardMessageToLambdaWorker = function(req, res, body) {
  var sqsMessage = parseJson(body, function(err) {
    return body; // use raw body
  });
  // console.log('body', body);
  var lambdaEvent = lambda.createLambdaEventFromSqsMessage(req, sqsMessage);
  lambda.trigger(LAMBDA_WORKER_FUNCTION_NAME, lambdaEvent, function(err, data) {
    if (err) {
      // local, app error
      errorHandlers.generic(req, res, 500, err.message);
      return;
    }
    else if (data instanceof Error) {
      // remote lamba had error; "bad gateway"
      errorHandlers.generic(req, res, 502, data.message);
      return;
    }
    else {
      // yay?
      if (data.Action) {
        switch (data.Action) {
          case 'DELETE':
            // yay! tells EB worker sqsd that message was processed and it issues a DeleteMessage
            res.writeHead(200);
            res.end();
            return;
          default:
            // nothing else is supported
            errorHandlers.generic(req, res, 501, 'Invalid response Action: ' + data.Action);
            return;
        }
      }
      else {
        errorHandlers.generic(req, res, 502, 'Lambda Worker Response Formatted Incorrectly');
        return;
      }
    }
  });
};

module.exports = function(req, res) {
  var body = '';
  if (!validate.isContentTypeJson(req.headers['content-type'])) {
    errorHandlers.notAcceptable(req, res);
    return;
  }
  req.on('data', function(chunk) {
    body += chunk;
  });
  req.on('end', function() {
    forwardMessageToLambdaWorker(req, res, body);
  });
};
<|endoftext|>


<commit_before>/* global angular */
'use strict'; // jshint ignore:line

angular.module('lumx.text-field', [])
    .filter('unsafe', ['$sce', function($sce)
    {
        return $sce.trustAsHtml;
    }])
    .directive('lxTextField', ['$timeout', function($timeout)
    {
        return {
            restrict: 'E',
            scope: {
                label: '@',
                disabled: '&',
                error: '&',
                valid: '&',
                fixedLabel: '&',
                icon: '@',
                theme: '@'
            },
            templateUrl: 'text-field.html',
            replace: true,
            transclude: true,
            link: function(scope, element, attrs, ctrl, transclude)
            {
                if (angular.isUndefined(scope.theme))
                {
                    scope.theme = 'light';
                }

                var modelController,
                    $field;

                scope.data = {
                    focused: false,
                    model: undefined
                };

                function focusUpdate()
                {
                    scope.data.focused = true;
                    scope.$apply();
                }

                function blurUpdate()
                {
                    scope.data.focused = false;
                    scope.$apply();
                }

                function modelUpdate()
                {
                    scope.data.model = modelController.$modelValue || $field.val();
                }

                function valueUpdate()
                {
                    modelUpdate();
                    scope.$apply();
                }

                function updateTextareaHeight()
                {
                    $timeout(function()
                    {
                        var tmpTextArea = angular.element('<textarea class="text-field__input">' + $field.val() + '</textarea>');
                        tmpTextArea.appendTo('body');

                        $field.css({ height: tmpTextArea[0].scrollHeight + 'px' });

                        tmpTextArea.remove();
                    });
                }

                transclude(function()
                {
                    $field = element.find('textarea');

                    if ($field[0])
                    {
                        updateTextareaHeight();

                        $field.on('cut paste drop keydown', function()
                        {
                            updateTextareaHeight();
                        });
                    }
                    else
                    {
                        $field = element.find('input');
                    }

                    $field.addClass('text-field__input');
                    $field.on('focus', focusUpdate);
                    $field.on('blur', blurUpdate);
                    $field.on('propertychange change click keyup input paste', valueUpdate);

                    modelController = $field.data('$ngModelController');

                    scope.$watch(function()
                    {
                        return modelController.$modelValue;
                    }, modelUpdate);
                });
            }
        };
    }]);
<commit_msg>fix text field: better height for textarea<commit_after>/* global angular */
'use strict'; // jshint ignore:line

angular.module('lumx.text-field', [])
    .filter('unsafe', ['$sce', function($sce)
    {
        return $sce.trustAsHtml;
    }])
    .directive('lxTextField', ['$timeout', function($timeout)
    {
        return {
            restrict: 'E',
            scope: {
                label: '@',
                disabled: '&',
                error: '&',
                valid: '&',
                fixedLabel: '&',
                icon: '@',
                theme: '@'
            },
            templateUrl: 'text-field.html',
            replace: true,
            transclude: true,
            link: function(scope, element, attrs, ctrl, transclude)
            {
                if (angular.isUndefined(scope.theme))
                {
                    scope.theme = 'light';
                }

                var modelController,
                    $field;

                scope.data = {
                    focused: false,
                    model: undefined
                };

                function focusUpdate()
                {
                    scope.data.focused = true;
                    scope.$apply();
                }

                function blurUpdate()
                {
                    scope.data.focused = false;
                    scope.$apply();
                }

                function modelUpdate()
                {
                    scope.data.model = modelController.$modelValue || $field.val();
                }

                function valueUpdate()
                {
                    modelUpdate();
                    scope.$apply();
                }

                function updateTextareaHeight()
                {
                    $timeout(function()
                    {
                        var tmpTextArea = angular.element('<textarea class="text-field__input" style="width: ' + $field.width() + 'px;">' + $field.val() + '</textarea>');
                        tmpTextArea.appendTo('body');

                        $field.css({ height: tmpTextArea[0].scrollHeight + 'px' });

                        tmpTextArea.remove();
                    });
                }

                transclude(function()
                {
                    $field = element.find('textarea');

                    if ($field[0])
                    {
                        updateTextareaHeight();

                        $field.on('cut paste drop keydown', function()
                        {
                            updateTextareaHeight();
                        });
                    }
                    else
                    {
                        $field = element.find('input');
                    }

                    $field.addClass('text-field__input');
                    $field.on('focus', focusUpdate);
                    $field.on('blur', blurUpdate);
                    $field.on('propertychange change click keyup input paste', valueUpdate);

                    modelController = $field.data('$ngModelController');

                    scope.$watch(function()
                    {
                        return modelController.$modelValue;
                    }, modelUpdate);
                });
            }
        };
    }]);
<|endoftext|>


<commit_before>var camera = (function(){
  var video, canvas, context, videoPause, overlayContext;
  var renderTImer;
  var width = 640;
  var height = 480;
  var fps = 15;
  var greenTimeSeries = [];
  var fft, spectrum, spectrum2, rfft;
  var normalized;
  var freq, heartrate;

  function initVideoStream(){
    // videoPause = false;
    video = document.createElement("video");
    video.setAttribute('width', width);
    video.setAttribute('height', height);
    var cameraExists = false;

    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

    window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
    if (navigator.getUserMedia){
      navigator.getUserMedia({
        video: true,
        audio: false
      }, function(stream){
        if (video.mozSrcObject !== undefined) { // for Firefox
          video.mozSrcObject = stream;
        } else {
          video.src = window.URL.createObjectURL(stream);
        } initCanvas();
      }, errorCallback);
      };
  };

  canvas = document.createElement("canvas");
  function initCanvas(){
    canvas.setAttribute('width', width);
    canvas.setAttribute('height', height);
    context = canvas.getContext("2d");

    canvasOverlay = document.createElement("canvas");
    canvasOverlay.setAttribute('width', width);
    canvasOverlay.setAttribute('height', height);
    canvasOverlay.style.position = "absolute";
    canvasOverlay.style.top = '0px';
    canvasOverlay.style.zIndex = '100001';
    canvasOverlay.style.display = 'block';
    overlayContext = canvasOverlay.getContext('2d');
    overlayContext.clearRect(0,0,width,height);

    vid.appendChild(canvas);
    vid.appendChild(canvasOverlay)

    startCapture();

  };

  // for facetracking
  function headtrack (){
      var htracker = new headtrackr.Tracker();
      htracker.init(video, canvas);
      htracker.start();

      window.htracker = htracker;
      // for each facetracking event received draw rectangle around tracked face on canvas
      document.addEventListener("facetrackingEvent", greenRect)

  };

  // for facetracking, draws the rectangle on the canvas
  function greenRect(event) {
        // clear canvas
        overlayContext.clearRect(0,0,width,height);

        var sx, sy, sw, sh, forehead, inpos, outpos;
        var greenSum = 0;
        var normalized = [];
        //approximating forehead based on facetracking
        sx = event.x + (-(event.width/5)) >> 0;
        sy = event.y + (-(event.height/3)) >> 0;
        sw = (event.width/2.5) >> 0;
        sh = (event.height/4) >> 0;

        // console.log(sx, sy, sw, sh)
        // console.log(event.width, event.height, event.x, event.y)
        // console.log(event.angle)

        //CS == camshift (in headtrackr.js)
        // once we have stable tracking, draw rectangle
        if (event.detection == "CS") {
          // Notes:
          // translate moves the origin point of context by event.x and event.y
          // ex. (88, 120) becomes the new (0, 0), removing translating for
          // the moment and adding (event.x + or event.y + ) where needed for now

          // overlayContext.translate(event.x, event.y)

          overlayContext.rotate(event.angle-(Math.PI/2));
          overlayContext.strokeStyle = "#00CC00";

          overlayContext.strokeRect(event.x + (-(event.width/2)) >> 0, event.y + (-(event.height/2)) >> 0, event.width, event.height);

          // blue forehead box (for debugging)
          // overlayContext.strokeStyle = "#33CCFF";
          // overlayContext.strokeRect(sx, sy, sw, sh);

          //red forehead box (for debugging)
          // overlayContext.fillStyle = "rgba(200, 0, 0, 1)";
          // overlayContext.fillRect(sx, sy, sw, sh);

          // Notes: forehead video box --
          // current theory is that the video brings in images at ~130dpi (@ 320 x 240),
          // whereas the canvas is 72dpi, thus the .545 or 1.85 difference
          // this isn't perfect, something about the way it calculates,
          // there is still an offset image sometimes.
          // Constraints will allow a specific resolution (theoretically), will require testing.
          // This currently only works for the iSight in a MacBook Air

          // ** for 320 x 240
          // overlayContext.drawImage(video, event.x + (sx* .8334), sy * 1.8334, sw*1.8334, sh*1.8334, sx, sy, sw, sh);

          // ** for 480 x 320
          // overlayContext.drawImage(video, (sx * 1.33), sy, sw * 1.3333, sh * 1.3333, sx, sy, sw, sh);

          // ** for 640 x 480 (which is too big for what I want do be doing, but brings the video down to 72dpi)
          overlayContext.drawImage(video, sx, sy - 10, sw, sh, sx, sy, sw, sh);

          //turn green
          forehead = overlayContext.getImageData(sx, sy, sw, sh);
          // console.log(forehead.width, forehead.height, forehead.data.length);
          // console.log(forehead.data)
          for (i = 0; i < forehead.data.length; i+=4){
            //for reference:
            // var red = forehead.data[i];
            // var green = forehead.data[i+1];
            // var blue = forehead.data[i+2];
            // var alpha = forehead.data[i+3];
            forehead.data[i] = 0;
            forehead.data[i+2] = 0;

            //get sum of green area for each frame
            greenSum = forehead.data[i+1] + greenSum;
          }

          //get average of green area for each frame
          var average = greenSum/forehead.data.length;
          console.log("Average: ", average);

          //create an array of averages for last 30 seconds
          //normalize
          if (greenTimeSeries.length < 256){
            greenTimeSeries.push(average);
          } else {
            greenTimeSeries.push(average);
            greenTimeSeries.shift();

            normalized = normalize(greenTimeSeries);

            // fast fourier transform from dsp.js
            fft = new RFFT(256, 15);
            fft.forward(normalized);
            spectrum = fft.spectrum;

            freq = frequencyExtract(spectrum, fps);
            console.log(freq)

            //this should be moved, it should not be in this loop, but outside running every second or so
            heartrate = freq * 60;
            console.log(heartrate)

          }
          // console.log("FFT: ",spectrum);
          console.log(heartrate)

          overlayContext.putImageData(forehead, sx, sy);

          overlayContext.rotate((Math.PI/2)-event.angle);

          // see note above about .translate()
          // overlayContext.translate(-event.x, -event.y);

        }
        // for debugging framerates
        // var newTime = new Date();
        // var elapsedTime = newTime - lastTime;
        // lastTime = newTime;
        // console.log(1000/elapsedTime); // to do: try sending this to the DOM

   };

   var lastTime;

  function startCapture(){
    cameraExists = true;
    video.play();

    renderTimer = setInterval(function(){
        context.drawImage(video, 0, 0, width, height);
      }, Math.round(1000 / fps));

    headtrack();
  };

  function pauseCapture(){
    if (renderTimer) clearInterval(renderTimer);
    video.pause();

    //removes the event listener and stops headtracking
    document.removeEventListener("facetrackingEvent", greenRect);
    htracker.stop();

  };
  var errorCallback = function(error){
    console.log('rejeeeected!', error);
  };

  return{
    init: function(){
      initVideoStream();
    },
    start: startCapture,
    pause: pauseCapture,
  }

})();

<commit_msg>Removed some lines left from debugging, can accomodate different types of webcams at different resolutions now<commit_after>var camera = (function(){
  var htracker;
  var video, canvas, context, videoPause, canvasOverlay, overlayContext;
  var countdownCanvas, countdownContext, hrCanvas, hrContext;
  var renderTImer;
  var width = 480;
  var height = 360;
  var fps = 15;
  var greenTimeSeries = [];
  var dataWindow = false;
  var heartrate;
  var heartrateArray = [];
  var lastTime;
  var bufferWindow = 512;

  function initVideoStream(){
    // videoPause = false;
    video = document.createElement("video");
    video.setAttribute('width', width);
    video.setAttribute('height', height);
    // window.video = video;
    var cameraExists = false;

    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

    window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
    if (navigator.getUserMedia){
      navigator.getUserMedia({
        video: true,
        // video: {mandatory: {frameRate: 15}}
        audio: false
      }, function(stream){
        if (video.mozSrcObject !== undefined) { // for Firefox
          video.mozSrcObject = stream;
        } else {
          video.src = window.URL.createObjectURL(stream);
        } initCanvas();
      }, errorCallback);
      };
  };

  function initCanvas(){
    canvas = document.createElement("canvas");
    canvas.setAttribute('width', width);
    canvas.setAttribute('height', height);
    // canvas.style.top = '0px'
    context = canvas.getContext("2d");

    canvasOverlay = document.createElement("canvas");
    canvasOverlay.setAttribute('width', width);
    canvasOverlay.setAttribute('height', height);
    canvasOverlay.style.position = "absolute";
    canvasOverlay.style.top = '8px';
    canvasOverlay.style.zIndex = '100001';
    canvasOverlay.style.display = 'block';
    overlayContext = canvasOverlay.getContext('2d');
    overlayContext.clearRect(0,0,width,height);

    countdownCanvas = document.createElement("canvas");
    countdownCanvas.setAttribute('width', 200);
    countdownCanvas.setAttribute('height', 100);
    countdownCanvas.style.display = 'block';
    countdownContext = countdownCanvas.getContext('2d');
    countdownContext.clearRect(0,0,width,height);

    vid.appendChild(canvas);
    vid.appendChild(canvasOverlay)
    countdown.appendChild(countdownCanvas)

    startCapture();

  };

  function headtrack (){
      //**
    // renderTimer = setInterval(function(){
    //   context.drawImage(video, 0, 0, width, height);
    //   /* greenRect(); */}, Math.round(1000 / fps));

    htracker = new headtrackr.Tracker({detectionInterval: 1000/fps});
    htracker.init(video, canvas, context);
    htracker.start();

    document.addEventListener("facetrackingEvent", greenRect)

    // for each facetracking event received draw rectangle around tracked face on canvas
    // document.addEventListener("facetrackingEvent", greenRect) //**

  };

  function greenRect(event) {
    // for facetracking, draws the rectangle on the canvas

    // clear canvas
    overlayContext.clearRect(0,0,width,height);

    var sx, sy, sw, sh, forehead, inpos, outpos;
    var greenSum = 0;
    var normalized = [];

    //approximating forehead based on facetracking
    //**
    sx = event.x + (-(event.width/5)) >> 0;
    sy = event.y + (-(event.height/3)) >> 0;
    sw = (event.width/2.5) >> 0;
    sh = (event.height/4) >> 0;

    // console.log(sx, sy, sw, sh)

    // sx = sy = 200;
    // sw = sh = 50;

    // CS == camshift (in headtrackr.js)
    // once we have stable tracking, draw rectangle
    if (event.detection == "CS") /**/ {
      // Notes:
      // translate moves the origin point of context by event.x and event.y
      // ex. (88, 120) becomes the new (0, 0), removing translating for
      // the moment and adding (event.x + or event.y + ) where needed for now

      // overlayContext.translate(event.x, event.y)

      //**
      overlayContext.rotate(event.angle-(Math.PI/2));
      overlayContext.strokeStyle = "#00CC00";

      overlayContext.strokeRect(event.x + (-(event.width/2)) >> 0, event.y + (-(event.height/2)) >> 0, event.width, event.height);

      // blue forehead box (for debugging)
      overlayContext.strokeStyle = "#33CCFF";
      overlayContext.strokeRect(sx, sy, sw, sh);

      // red forehead box (for debugging)
      // overlayContext.fillStyle = "rgba(200, 0, 0, 1)";
      // overlayContext.fillRect(sx, sy, sw, sh);

      // Notes: forehead video box --
      // current theory is that the video brings in images at ~130dpi (@ 320 x 240),
      // whereas the canvas is 72dpi, thus the .545 or 1.85 difference
      // this isn't perfect, something about the way it calculates,
      // there is still an offset image sometimes.
      // Constraints will allow a specific resolution (theoretically), will require testing.
      // This currently only works for the iSight in a MacBook Air

      // ** for 320 x 240
      // overlayContext.drawImage(video, event.x + (sx* .8334), sy * 1.8334, sw*1.8334, sh*1.8334, sx, sy, sw, sh);

      // ** for 480 x 320
      // overlayContext.drawImage(video, (sx * 1.33), sy, sw * 1.3333, sh * 1.3333, sx, sy, sw, sh);

      // ** for 640 x 480 (which is too big for what I want do be doing, but brings the video down to 72dpi)
      // overlayContext.drawImage(video, sx, sy - 10, sw, sh, sx, sy, sw, sh);

      //turn green
      forehead = context.getImageData(sx, sy, sw, sh);

      for (i = 0; i < forehead.data.length; i+=4){
        //for reference:
        // var red = forehead.data[i];
        // var green = forehead.data[i+1];
        // var blue = forehead.data[i+2];
        // var alpha = forehead.data[i+3];
        // forehead.data[i] = 0;
        // forehead.data[i+2] = 0;

        //get sum of green area for each frame
        greenSum = forehead.data[i+1] + greenSum;
      }

      //get average of green area for each frame
      var average = greenSum/forehead.data.length;
      // console.log("Average: ", average);

      //create an array of averages for last 30 seconds
      //normalize
      // cardiac();
      if (greenTimeSeries.length < bufferWindow){
        greenTimeSeries.push(average);

        //draw countdown to page
        countdownContext.font = "20pt Helvetica";
        countdownContext.clearRect(0,0,200,100);
        countdownContext.save()
        countdownContext.fillText(((bufferWindow - greenTimeSeries.length)/fps) >> 0, 25, 25)
        countdownContext.restore()

        // console.log('countdown: ', bufferWindow - greenTimeSeries.length);
      } else {
        // dataWindow = true;
        greenTimeSeries.push(average);
        greenTimeSeries.shift();

        cardiac();
        // heartbeatTimer();

      }
      // overlayContext.putImageData(forehead, sx, sy);
      overlayContext.rotate((Math.PI/2)-event.angle); //**

      // see note above about .translate()
      // overlayContext.translate(-event.x, -event.y);

    }
    //  for debugging framerates
    var newTime = new Date();
    var elapsedTime = newTime - lastTime;
    lastTime = newTime;
    // console.log("approx FPS: ", 1000/elapsedTime); // to do: try sending this to the DOM

  };

  function cardiac(){
    // var fftArray = [0, 0.6082253456115723, 0.25601473450660706, 0.3510543704032898, 0.33191803097724915, 0.40043285489082336, 0.24442104995250702, 0.2906903624534607, 0.10941631346940994, 0.22052565217018127, 0.08654522150754929, 0.11624716222286224, 0.17962567508220673, 0.10583585500717163, 0.14719387888908386, 0.1313147246837616, 0.06234072521328926, 0.1543150544166565, 0.11760584264993668, 0.11862088739871979, 0.12146361917257309, 0.266795814037323, 0.21472491323947906, 0.06073959171772003, 0.06288193166255951, 0.09347641468048096, 0.036240000277757645, 0.05102884769439697, 0.04235406965017319, 0.02831820584833622, 0.05210259556770325, 0.10648924112319946, 0.15421639382839203, 0.06438228487968445, 0.10806077718734741, 0.03795776888728142, 0.08309036493301392, 0.031337834894657135, 0.09866298735141754, 0.014706060290336609, 0.03916962072253227, 0.08954672515392303, 0.029007576406002045, 0.057937536388635635, 0.008652705699205399, 0.037266805768013, 0.02773413620889187, 0.06986536830663681, 0.003169334027916193, 0.11411335319280624, 0.08028649538755417, 0.023082412779331207, 0.07458089292049408, 0.035777997225522995, 0.03824623301625252, 0.049640655517578125, 0.077757328748703, 0.034727200865745544, 0.04745856299996376, 0.023465096950531006, 0.024489138275384903, 0.07100922614336014, 0.040082309395074844, 0.05462462082505226, 0.018537191674113274, 0.022122405469417572, 0.07421161979436874, 0.030828898772597313, 0.015992337837815285, 0.041366539895534515, 0.022134358063340187, 0.04682140797376633, 0.04059939831495285, 0.03882011026144028, 0.03683715686202049, 0.0355040617287159, 0.04130915179848671, 0.0772508755326271, 0.017217449843883514, 0.04906228929758072, 0.05653959885239601, 0.03592155873775482, 0.05430029705166817, 0.08023825287818909, 0.021106261759996414, 0.015047682449221611, 0.025425495579838753, 0.01588442362844944, 0.010336599312722683, 0.04358170926570892, 0.03919610008597374, 0.059951890259981155, 0.0548163503408432, 0.0708637610077858, 0.05006611347198486, 0.0253529604524374, 0.024189390242099762, 0.04341737926006317, 0.021617475897073746, 0.023999590426683426, 0.03697226196527481, 0.04166150838136673, 0.048380929976701736, 0.023121561855077744, 0.028621751815080643, 0.02181928977370262, 0.06232449412345886, 0.003735166508704424, 0.056197550147771835, 0.007498697843402624, 0.026589369401335716, 0.036785390228033066, 0.06052883714437485, 0.02696179784834385, 0.06407647579908371, 0.07175770401954651, 0.04474520683288574, 0.05206694453954697, 0.0502486452460289, 0.04056066647171974, 0.04000169411301613, 0.029190203174948692, 0.0447375625371933, 0.05608018860220909, 0.04813564941287041, 0.04150288179516792, 0.03023460879921913, 0.013040808029472828]

    var normalized = normalize(greenTimeSeries);

    // fast fourier transform from dsp.js
    var fft = new RFFT(bufferWindow, fps);
    fft.forward(normalized);
    var spectrum = fft.spectrum;
    console.log(spectrum.length)

    var freq = frequencyExtract(spectrum, fps);
    // console.log("peak freq in hz:", freq)

    heartrate = freq * 60;
    // console.log("heartrate: ", heartrate)
    heartrateArray.push(heartrate)

    //draw heartbeat to page
    countdownContext.font = "20pt Helvetica";
    countdownContext.clearRect(0,0,200,100);
    countdownContext.save()
    countdownContext.fillText(heartrate, 25, 25)
    countdownContext.restore()

  };

  function startCapture(){
    cameraExists = true;
    video.play();

    renderTimer = setInterval(function(){
        context.drawImage(video, 0, 0, width, height);
      }, Math.round(1000 / fps));

    headtrack();

  };

//**
  // function heartbeatTimer(){
  //       // while (dataWindow == true){
  //   var calculationTimer = setInterval(function(){
  //       cardiac();
  //     }, 1000);

  //   // };

  // }
  function pauseCapture(){
    if (renderTimer) clearInterval(renderTimer);
    // if (calculationTimer) clearInterval(calculationTimer);

    video.pause();

    //removes the event listener and stops headtracking
    document.removeEventListener("facetrackingEvent", greenRect);
    htracker.stop();

    console.log(heartrateArray)

  };
  var errorCallback = function(error){
    console.log('rejeeeected!', error);
  };

  return{
    init: function(){
      initVideoStream();
    },
    start: startCapture,
    pause: pauseCapture,
  }

})();

<|endoftext|>


<commit_before>define(function () {

    var LAZO = {},
        isServer = true,
        isClient = true;

    try {
        window;
        isServer = false;
    } catch (err) {
        isClient = false;
    }

    LAZO.app = {
        isServer: isServer,
        isClient: isClient
    };

    LAZO.logger = {
        log: function () {},
        debug: function() {},
        warn: function () {}
    };

    LAZO.config = {
        get: function(key) {
            return this[key];
        },
        set: function(key, value) {
            this[key] = value;
        }
    };

    return LAZO;

});<commit_msg>added missing mock method<commit_after>define(function () {

    var LAZO = {},
        isServer = true,
        isClient = true;

    try {
        window;
        isServer = false;
    } catch (err) {
        isClient = false;
    }

    LAZO.app = {
        isServer: isServer,
        isClient: isClient
    };

    LAZO.logger = {
        debug: function () {
        },
        error: function () {
        },
        log: function () {
        },
        warn: function () {
        }
    };

    LAZO.config = {
        get: function (key) {
            return this[key];
        },
        set: function (key, value) {
            this[key] = value;
        }
    };

    return LAZO;

});<|endoftext|>


<commit_before>/**
 * Created by vytautassugintas on 06/04/16.
 */
"use strict";
angular.module("myApp").constant("SERVER", {
	"ip": "http://www.openkudos.com/api"
})
<commit_msg>Change server URL to openkudos.com/api without www<commit_after>/**
 * Created by vytautassugintas on 06/04/16.
 */
"use strict";
angular.module("myApp").constant("SERVER", {
	"ip": "http://openkudos.com/api"
})
<|endoftext|>


<commit_before>/*
 * index.js: Compute client for OpenStack
 *
 * (C) 2013 Nodejitsu Inc.
 *
 */

var utile = require('utile'),
    openstack = require('../../client'),
    ComputeClient = require('../computeClient').ComputeClient,
    _ = require('underscore');

var Client = exports.Client = function (options) {
  openstack.Client.call(this, options);

  utile.mixin(this, require('./flavors'));
  utile.mixin(this, require('./images'));
  utile.mixin(this, require('./servers'));
  utile.mixin(this, require('./extensions'));

  this.serviceType = 'compute';
};

utile.inherits(Client, openstack.Client);
_.extend(Client.prototype, ComputeClient.prototype);

Client.prototype.bootstrapOptions = function (options, keys) {
  var result = {};

  if (options.keyname || options.key_name) {
    result.keyname = options.keyname || options.key_name;
  }

  return result;
};

<commit_msg>Removing unused bootstrap function from openstack client<commit_after>/*
 * index.js: Compute client for OpenStack
 *
 * (C) 2013 Nodejitsu Inc.
 *
 */

var utile = require('utile'),
    openstack = require('../../client'),
    ComputeClient = require('../computeClient').ComputeClient,
    _ = require('underscore');

var Client = exports.Client = function (options) {
  openstack.Client.call(this, options);

  utile.mixin(this, require('./flavors'));
  utile.mixin(this, require('./images'));
  utile.mixin(this, require('./servers'));
  utile.mixin(this, require('./extensions'));

  this.serviceType = 'compute';
};

utile.inherits(Client, openstack.Client);
_.extend(Client.prototype, ComputeClient.prototype);

<|endoftext|>


<commit_before>Ext.define('doweown.model.Collection', {
    extend: 'Ext.data.Model',
    config: {
        belongsTo: 'Branch',
	hasMany: { model: 'ItemRecord', name: 'items', associationKey: 'itemrecord' },
	hasOne:  { model: 'HoldTag', name: 'holdtag', associationKey: 'holdtag' },
	hasOne:  { model: 'Online', name: 'online', associationKey: 'online' },
        fields: [
                {name: 'collectionname', type: 'string', mapping: 'collectionname'},
                {name: 'callnumber',     type: 'string', mapping: 'callnumber'}
        ]
    }
});
<commit_msg>correct mapping<commit_after>Ext.define('doweown.model.Collection', {
    extend: 'Ext.data.Model',
    config: {
        belongsTo: 'Branch',
	hasMany: { model: 'doweown.model.ItemRecord', name: 'items', associationKey: 'items' },
	hasOne:  { model: 'doweown.model.HoldTag', name: 'holdtag', associationKey: 'holdtag'  },
	hasOne:  { model: 'doweown.model.Online', name: 'online', associationKey: 'online' },
        fields: [
                {name: 'collectionname', type: 'string', mapping: 'collectionname'},
                {name: 'callnumber',     type: 'string', mapping: 'callnumber'}
        ]
    }
});
<|endoftext|>


<commit_before>console.log(" 🌙 Creating Lunr index...");

const lunr = require('lunr');
const fs = require('fs');

const data = fs.readFileSync('site/documents.json');
const documents = JSON.parse(data);

// field and document BOOST docs:
// https://github.com/olivernn/lunr.js/issues/267

const index = lunr(function() {
	this.field('title', { boost: 10 });
	this.field('description' , { boost: 5 });
	this.field('body');
	this.ref('id');

	documents.forEach(function(doc) {
		this.add(doc, { boost: doc.boost });
	}, this)

})

const serialisedIndex = JSON.stringify(index);

fs.writeFile('site/search_index.json', serialisedIndex, (err) => {
	if (err) throw err;
	console.log('💾 The Lunr search index has been created -> site/search_index.json');
});
<commit_msg>Store the position metadata<commit_after>console.log(" 🌙 Creating Lunr index...");

const lunr = require('lunr');
const fs = require('fs');

const data = fs.readFileSync('site/documents.json');
const documents = JSON.parse(data);

// field and document BOOST docs:
// https://github.com/olivernn/lunr.js/issues/267

const index = lunr(function() {
	this.field('title', { boost: 10 });
	this.field('description' , { boost: 5 });
	this.field('body');
	this.ref('id');
	this.metadataWhitelist = ['position'];

	documents.forEach(function(doc) {
		this.add(doc, { boost: doc.boost });
	}, this)

})

const serialisedIndex = JSON.stringify(index);

fs.writeFile('site/search_index.json', serialisedIndex, (err) => {
	if (err) throw err;
	console.log('💾 The Lunr search index has been created -> site/search_index.json');
});
<|endoftext|>


<commit_before>/**
 * Express configuration
 */

'use strict';

var express = require('express');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var path = require('path');
var config = require('./environment');
var passport = require('passport');

module.exports = function(app) {
  var env = app.get('env');

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser());
  app.use(passport.initialize());
  if ('production' === env) {
//    app.use(express.static(path.join(config.root, 'public')));
//    app.set('appPath', config.root + '/public');
    app.use(morgan('dev'));
  }

  if ('development' === env || 'test' === env) {
    app.use(require('connect-livereload')());
    app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'client')));
    app.set('appPath', 'client');
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  }
};<commit_msg>log parameters to console<commit_after>/**
 * Express configuration
 */

'use strict';

var express = require('express');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var path = require('path');
var config = require('./environment');
var passport = require('passport');

module.exports = function(app) {
  var env = app.get('env');

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser());
  app.use(passport.initialize());
  app.use(function(req, res, next) {
    console.log("req.query:", req.query);
    console.log("req.params:", req.params);
    console.log("req.body:", req.body);
    next();
  });
  if ('production' === env) {
//    app.use(express.static(path.join(config.root, 'public')));
//    app.set('appPath', config.root + '/public');
    app.use(morgan('dev'));
  }

  if ('development' === env || 'test' === env) {
    app.use(require('connect-livereload')());
    app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'client')));
    //app.set('appPath', 'client');
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  }
};<|endoftext|>


<commit_before>var gulp = require('gulp');
var karma = require('karma').server;
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var util = require('util');

// Browsers to run on Sauce Labs
// available: https://npmjs.org/browse/keyword/karma-launcher
var customLaunchers = {
  'SL_Chrome': {
    base: 'SauceLabs',
    browserName: 'chrome'
  },
  'SL_Firefox': { // FIXME IE != Firefox ??
    base: 'SauceLabs',
    browserName: 'internet explorer',
    version: '9'
  }
};

// Base Karma configuration, contains everything needed for a local teste run
// The config is extended by gulp tasks below to add coverage/sauselabs/etc
var karmaConfig = {
  basePath: '',
  frameworks: ['jasmine'],
  files: ['index.js', 'test.js'],
  reporters: ['progress', 'spec'],
  port: 9876,
  colors: true,
  autoWatch: false,
  singleRun: true,
  preprocessors: {
    'index.js': ['wrap'],
  },
  wrapPreprocessor: {
    template: 'function requireTinyCookies(document, Date, exports) { <%= contents %> }'
  },
  browsers: ['PhantomJS']
  //logLevel: config.LOG_WARN,
};

gulp.task('build', function (done) {
  return gulp.src('index.js')
  .pipe(uglify())
  .pipe(rename('tiny-cookies.min.js'))
  .pipe(gulp.dest('dist'));
});

// Test run including code coverage and Sauce Labs
// May be run locally or using travis CI
gulp.task('test:full', function (done) {
  // Check whether Sause Labs credentials are configured
  if (!process.env.SAUCE_USERNAME) {
    console.log('SAUCE_USERNAME and SAUSE_ACCESS_KEY must be configured as ENV vars');
    process.exit(1);
  }

  // Copy the Karma config
  var config = util._extend({}, karmaConfig);

  // Stop after the test run has finishsed
  config.singleRun = true;

  // Enable code coverage
  config.reporters.push('coverage');
  config.preprocessors['index.js'].push('coverage');
  config.coverageReporter = {
    dir: 'coverage/',
    reporters: [
      {type: 'lcov', subdir: '.' },
      {type: 'cobertura', subdir: '.', file: 'cobertura.xml'}
    ]
  };

  // If running on TRAVIS use the job number as tunnel-identifier for Sauce Labs
  if (process.env.TRAVIS_JOB_NUMBER !== undefined) {
    for (var i = 0; i < customLaunchers.length; i++) {
      customLaunchers[i].build                = process.env.TRAVIS_BUILD_NUMBER;
      customLaunchers[i]['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
    }
    console.log('JOB NUMBERS', customLaunchers);
  }

  // Enable Sauce Labs
  config.reporters.push('saucelabs');
  config.sauceLabs = {testName: 'tiny-cookies karma'};
  config.captureTimeout = 120000;
  config.customLaunchers = customLaunchers;
  config.browsers = Object.keys(customLaunchers);

  // Run karma
  karma.start(config, done);
});

// Execute tests on local system
gulp.task('test:local', function (done) {
  // Copy the Karma config
  var config = util._extend({}, karmaConfig);

  // Stop after the test run has finishsed
  config.singleRun = true; // Run only once

  // Run Karma
  karma.start(config, done);
});
<commit_msg>Fixed setting travis job number<commit_after>var gulp = require('gulp');
var karma = require('karma').server;
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var util = require('util');

// Browsers to run on Sauce Labs
// available: https://npmjs.org/browse/keyword/karma-launcher
var customLaunchers = {
  'SL_Chrome': {
    base: 'SauceLabs',
    browserName: 'chrome'
  },
  'SL_Firefox': { // FIXME IE != Firefox ??
    base: 'SauceLabs',
    browserName: 'internet explorer',
    version: '9'
  }
};

// Base Karma configuration, contains everything needed for a local teste run
// The config is extended by gulp tasks below to add coverage/sauselabs/etc
var karmaConfig = {
  basePath: '',
  frameworks: ['jasmine'],
  files: ['index.js', 'test.js'],
  reporters: ['progress', 'spec'],
  port: 9876,
  colors: true,
  autoWatch: false,
  singleRun: true,
  preprocessors: {
    'index.js': ['wrap'],
  },
  wrapPreprocessor: {
    template: 'function requireTinyCookies(document, Date, exports) { <%= contents %> }'
  },
  browsers: ['PhantomJS']
  //logLevel: config.LOG_WARN,
};

gulp.task('build', function (done) {
  return gulp.src('index.js')
  .pipe(uglify())
  .pipe(rename('tiny-cookies.min.js'))
  .pipe(gulp.dest('dist'));
});

// Test run including code coverage and Sauce Labs
// May be run locally or using travis CI
gulp.task('test:full', function (done) {
  // Check whether Sause Labs credentials are configured
  if (!process.env.SAUCE_USERNAME) {
    console.log('SAUCE_USERNAME and SAUSE_ACCESS_KEY must be configured as ENV vars');
    process.exit(1);
  }

  // Copy the Karma config
  var config = util._extend({}, karmaConfig);

  // Stop after the test run has finishsed
  config.singleRun = true;

  // Enable code coverage
  config.reporters.push('coverage');
  config.preprocessors['index.js'].push('coverage');
  config.coverageReporter = {
    dir: 'coverage/',
    reporters: [
      {type: 'lcov', subdir: '.' },
      {type: 'cobertura', subdir: '.', file: 'cobertura.xml'}
    ]
  };

  // If running on TRAVIS use the job number as tunnel-identifier for Sauce Labs
  if (process.env.TRAVIS_JOB_NUMBER !== undefined) {
    for (var launcher in customLaunchers) {
      customLaunchers[launcher].build                = process.env.TRAVIS_BUILD_NUMBER;
      customLaunchers[launcher]['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
    }
  }
  console.log(process.env.TRAVIS_BUILD_NUMBER, process.env.TRAVIS_JOB_NUMBER);
  console.log('JOB NUMBERS', customLaunchers);

  // Enable Sauce Labs
  config.reporters.push('saucelabs');
  config.sauceLabs = {testName: 'tiny-cookies karma'};
  config.captureTimeout = 120000;
  config.customLaunchers = customLaunchers;
  config.browsers = Object.keys(customLaunchers);

  // Run karma
  karma.start(config, done);
});

// Execute tests on local system
gulp.task('test:local', function (done) {
  // Copy the Karma config
  var config = util._extend({}, karmaConfig);

  // Stop after the test run has finishsed
  config.singleRun = true; // Run only once

  // Run Karma
  karma.start(config, done);
});
<|endoftext|>